QGIS API Documentation  3.20.0-Odense (decaadbb31)
qgsalgorithmnearestneighbouranalysis.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsalgorithmnearestneighbouranalysis.cpp
3  ---------------------
4  begin : December 2019
5  copyright : (C) 2019 by Alexander Bruy
6  email : alexander dot bruy at gmail dot com
7  ***************************************************************************/
8 
9 /***************************************************************************
10  * *
11  * This program is free software; you can redistribute it and/or modify *
12  * it under the terms of the GNU General Public License as published by *
13  * the Free Software Foundation; either version 2 of the License, or *
14  * (at your option) any later version. *
15  * *
16  ***************************************************************************/
17 
19 #include "qgsapplication.h"
20 #include <QTextStream>
21 
23 
24 QString QgsNearestNeighbourAnalysisAlgorithm::name() const
25 {
26  return QStringLiteral( "nearestneighbouranalysis" );
27 }
28 
29 QString QgsNearestNeighbourAnalysisAlgorithm::displayName() const
30 {
31  return QObject::tr( "Nearest neighbour analysis" );
32 }
33 
34 QStringList QgsNearestNeighbourAnalysisAlgorithm::tags() const
35 {
36  return QObject::tr( "point,node,vertex,nearest,neighbour,distance" ).split( ',' );
37 }
38 
39 QString QgsNearestNeighbourAnalysisAlgorithm::group() const
40 {
41  return QObject::tr( "Vector analysis" );
42 }
43 
44 QString QgsNearestNeighbourAnalysisAlgorithm::groupId() const
45 {
46  return QStringLiteral( "vectoranalysis" );
47 }
48 
49 QString QgsNearestNeighbourAnalysisAlgorithm::shortHelpString() const
50 {
51  return QObject::tr( "This algorithm performs nearest neighbor analysis for a point layer.\n\n"
52  "The output describes how the data are distributed (clustered, randomly or distributed).\n\n"
53  "Output is generated as an HTML file with the computed statistical values." );
54 }
55 
56 QString QgsNearestNeighbourAnalysisAlgorithm::svgIconPath() const
57 {
58  return QgsApplication::iconPath( QStringLiteral( "/algorithms/mAlgorithmNearestNeighbour.svg" ) );
59 }
60 
61 QIcon QgsNearestNeighbourAnalysisAlgorithm::icon() const
62 {
63  return QgsApplication::getThemeIcon( QStringLiteral( "/algorithms/mAlgorithmNearestNeighbour.svg" ) );
64 }
65 
66 QgsNearestNeighbourAnalysisAlgorithm *QgsNearestNeighbourAnalysisAlgorithm::createInstance() const
67 {
68  return new QgsNearestNeighbourAnalysisAlgorithm();
69 }
70 
71 void QgsNearestNeighbourAnalysisAlgorithm::initAlgorithm( const QVariantMap & )
72 {
73  addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList< int >() << QgsProcessing::TypeVectorPoint ) );
74  addParameter( new QgsProcessingParameterFileDestination( QStringLiteral( "OUTPUT_HTML_FILE" ), QObject::tr( "Nearest neighbour" ),
75  QObject::tr( "HTML files (*.html *.HTML)" ), QVariant(), true ) );
76  addOutput( new QgsProcessingOutputNumber( QStringLiteral( "OBSERVED_MD" ), QObject::tr( "Observed mean distance" ) ) );
77  addOutput( new QgsProcessingOutputNumber( QStringLiteral( "EXPECTED_MD" ), QObject::tr( "Expected mean distance" ) ) );
78  addOutput( new QgsProcessingOutputNumber( QStringLiteral( "NN_INDEX" ), QObject::tr( "Nearest neighbour index" ) ) );
79  addOutput( new QgsProcessingOutputNumber( QStringLiteral( "POINT_COUNT" ), QObject::tr( "Number of points" ) ) );
80  addOutput( new QgsProcessingOutputNumber( QStringLiteral( "Z_SCORE" ), QObject::tr( "Z-score" ) ) );
81 }
82 
83 QVariantMap QgsNearestNeighbourAnalysisAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
84 {
85  std::unique_ptr< QgsProcessingFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
86  if ( !source )
87  throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
88 
89  QString outputFile = parameterAsFileOutput( parameters, QStringLiteral( "OUTPUT_HTML_FILE" ), context );
90 
91  QgsSpatialIndex spatialIndex( *source, feedback, QgsSpatialIndex::FlagStoreFeatureGeometries );
92  QgsDistanceArea da;
93  da.setSourceCrs( source->sourceCrs(), context.transformContext() );
94  da.setEllipsoid( context.ellipsoid() );
95 
96  double step = source->featureCount() ? 100.0 / source->featureCount() : 1;
97  QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QList< int >() ) );
98 
99  QgsFeatureRequest request;
100  QgsFeature neighbour;
101  double sumDist = 0.0;
102  double area = source->sourceExtent().width() * source->sourceExtent().height();
103 
104  int i = 0;
105  QgsFeature f;
106  while ( it.nextFeature( f ) )
107  {
108  if ( feedback->isCanceled() )
109  {
110  break;
111  }
112 
113  QgsFeatureId neighbourId = spatialIndex.nearestNeighbor( f.geometry().asPoint(), 2 ).at( 1 );
114  sumDist += da.measureLine( spatialIndex.geometry( neighbourId ).asPoint(), f.geometry().asPoint() );
115 
116  i++;
117  feedback->setProgress( i * step );
118  }
119 
120  long long count = source->featureCount() > 0 ? source->featureCount() : 1;
121  double observedDistance = sumDist / count;
122  double expectedDistance = 0.5 / std::sqrt( count / area );
123  double nnIndex = observedDistance / expectedDistance;
124  double se = 0.26136 / std::sqrt( std::pow( count, 2 ) / area );
125  double zScore = ( observedDistance - expectedDistance ) / se;
126 
127  QVariantMap outputs;
128  outputs.insert( QStringLiteral( "OBSERVED_MD" ), observedDistance );
129  outputs.insert( QStringLiteral( "EXPECTED_MD" ), expectedDistance );
130  outputs.insert( QStringLiteral( "NN_INDEX" ), nnIndex );
131  outputs.insert( QStringLiteral( "POINT_COUNT" ), count );
132  outputs.insert( QStringLiteral( "Z_SCORE" ), zScore );
133 
134  if ( !outputFile.isEmpty() )
135  {
136  QFile file( outputFile );
137  if ( file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
138  {
139  QTextStream out( &file );
140 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
141  out.setCodec( "UTF-8" );
142 #endif
143  out << QStringLiteral( "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/></head><body>\n" );
144  out << QObject::tr( "<p>Observed mean distance: %1</p>\n" ).arg( observedDistance, 0, 'f', 11 );
145  out << QObject::tr( "<p>Expected mean distance: %1</p>\n" ).arg( expectedDistance, 0, 'f', 11 );
146  out << QObject::tr( "<p>Nearest neighbour index: %1</p>\n" ).arg( nnIndex, 0, 'f', 11 );
147  out << QObject::tr( "<p>Number of points: %1</p>\n" ).arg( count );
148  out << QObject::tr( "<p>Z-Score: %1</p>\n" ).arg( zScore, 0, 'f', 11 );
149  out << QStringLiteral( "</body></html>" );
150 
151  outputs.insert( QStringLiteral( "OUTPUT_HTML_FILE" ), outputFile );
152  }
153  }
154 
155  return outputs;
156 }
157 
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QString iconPath(const QString &iconFile)
Returns path to the desired icon file.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
double measureLine(const QVector< QgsPointXY > &points) const
Measures the length of a line with multiple segments.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
This class wraps a request for features to a vector layer (or directly its vector data provider).
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition: qgsfeature.h:56
QgsGeometry geometry
Definition: qgsfeature.h:67
bool isCanceled() const SIP_HOLDGIL
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition: qgsfeedback.h:63
QgsPointXY asPoint() const
Returns the contents of the geometry as a 2-dimensional point.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
Custom exception class for processing related exceptions.
Definition: qgsexception.h:83
Base class for providing feedback from a processing algorithm.
A numeric output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A generic file based destination parameter, for specifying the destination path for a file (non-map l...
@ TypeVectorPoint
Vector point layers.
Definition: qgsprocessing.h:49
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28