QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
Loading...
Searching...
No Matches
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
20#include "qgsapplication.h"
21#include "qgsdistancearea.h"
22#include "qgsspatialindex.h"
23
24#include <QString>
25#include <QTextStream>
26
27using namespace Qt::StringLiterals;
28
30
31QString QgsNearestNeighbourAnalysisAlgorithm::name() const
32{
33 return u"nearestneighbouranalysis"_s;
34}
35
36QString QgsNearestNeighbourAnalysisAlgorithm::displayName() const
37{
38 return QObject::tr( "Nearest neighbour analysis" );
39}
40
41QStringList QgsNearestNeighbourAnalysisAlgorithm::tags() const
42{
43 return QObject::tr( "point,node,vertex,nearest,neighbour,distance" ).split( ',' );
44}
45
46QString QgsNearestNeighbourAnalysisAlgorithm::group() const
47{
48 return QObject::tr( "Vector analysis" );
49}
50
51QString QgsNearestNeighbourAnalysisAlgorithm::groupId() const
52{
53 return u"vectoranalysis"_s;
54}
55
56QString QgsNearestNeighbourAnalysisAlgorithm::shortHelpString() const
57{
58 return QObject::tr(
59 "This algorithm performs nearest neighbor analysis for a point layer.\n\n"
60 "The output describes how the data are distributed (clustered, randomly or distributed).\n\n"
61 "Output is generated as an HTML file with the computed statistical values."
62 );
63}
64
65QString QgsNearestNeighbourAnalysisAlgorithm::shortDescription() const
66{
67 return QObject::tr( "Performs nearest neighbor analysis for a point layer." );
68}
69
70QString QgsNearestNeighbourAnalysisAlgorithm::svgIconPath() const
71{
72 return QgsApplication::iconPath( u"/algorithms/mAlgorithmNearestNeighbour.svg"_s );
73}
74
75QIcon QgsNearestNeighbourAnalysisAlgorithm::icon() const
76{
77 return QgsApplication::getThemeIcon( u"/algorithms/mAlgorithmNearestNeighbour.svg"_s );
78}
79
80Qgis::ProcessingAlgorithmDocumentationFlags QgsNearestNeighbourAnalysisAlgorithm::documentationFlags() const
81{
83}
84
85QgsNearestNeighbourAnalysisAlgorithm *QgsNearestNeighbourAnalysisAlgorithm::createInstance() const
86{
87 return new QgsNearestNeighbourAnalysisAlgorithm();
88}
89
90void QgsNearestNeighbourAnalysisAlgorithm::initAlgorithm( const QVariantMap & )
91{
92 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPoint ) ) );
93 addParameter( new QgsProcessingParameterFileDestination( u"OUTPUT_HTML_FILE"_s, QObject::tr( "Nearest neighbour" ), QObject::tr( "HTML files (*.html *.HTML)" ), QVariant(), true ) );
94 addOutput( new QgsProcessingOutputNumber( u"OBSERVED_MD"_s, QObject::tr( "Observed mean distance" ) ) );
95 addOutput( new QgsProcessingOutputNumber( u"EXPECTED_MD"_s, QObject::tr( "Expected mean distance" ) ) );
96 addOutput( new QgsProcessingOutputNumber( u"NN_INDEX"_s, QObject::tr( "Nearest neighbour index" ) ) );
97 addOutput( new QgsProcessingOutputNumber( u"POINT_COUNT"_s, QObject::tr( "Number of points" ) ) );
98 addOutput( new QgsProcessingOutputNumber( u"Z_SCORE"_s, QObject::tr( "Z-score" ) ) );
99}
100
101QVariantMap QgsNearestNeighbourAnalysisAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
102{
103 QGS_MARK_ALGORITHM_SOURCE
104
105 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
106 if ( !source )
107 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
108
109 const QString outputFile = parameterAsFileOutput( parameters, u"OUTPUT_HTML_FILE"_s, context );
110
111 const QgsSpatialIndex spatialIndex( *source, feedback, QgsSpatialIndex::FlagStoreFeatureGeometries );
113 da.setSourceCrs( source->sourceCrs(), context.transformContext() );
114 da.setEllipsoid( context.ellipsoid() );
115
116 const double step = source->featureCount() ? 100.0 / source->featureCount() : 1;
117 QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QList<int>() ) );
118
119 const QgsFeatureRequest request;
120 const QgsFeature neighbour;
121 double sumDist = 0.0;
122 const double area = source->sourceExtent().width() * source->sourceExtent().height();
123
124 int i = 0;
125 QgsFeature f;
126 while ( it.nextFeature( f ) )
127 {
128 if ( feedback->isCanceled() )
129 {
130 break;
131 }
132
133 const QgsFeatureId neighbourId = spatialIndex.nearestNeighbor( f.geometry().asPoint(), 2 ).at( 1 );
134 try
135 {
136 sumDist += da.measureLine( spatialIndex.geometry( neighbourId ).asPoint(), f.geometry().asPoint() );
137 }
138 catch ( QgsCsException & )
139 {
140 throw QgsProcessingException( QObject::tr( "An error occurred while calculating length" ) );
141 }
142
143 i++;
144 feedback->setProgress( i * step );
145 }
146
147 const long long count = source->featureCount() > 0 ? source->featureCount() : 1;
148 const double observedDistance = sumDist / count;
149 const double expectedDistance = 0.5 / std::sqrt( count / area );
150 const double nnIndex = observedDistance / expectedDistance;
151 const double se = 0.26136 / std::sqrt( std::pow( count, 2 ) / area );
152 const double zScore = ( observedDistance - expectedDistance ) / se;
153
154 QVariantMap outputs;
155 outputs.insert( u"OBSERVED_MD"_s, observedDistance );
156 outputs.insert( u"EXPECTED_MD"_s, expectedDistance );
157 outputs.insert( u"NN_INDEX"_s, nnIndex );
158 outputs.insert( u"POINT_COUNT"_s, count );
159 outputs.insert( u"Z_SCORE"_s, zScore );
160
161 if ( !outputFile.isEmpty() )
162 {
163 QFile file( outputFile );
164 if ( file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
165 {
166 QTextStream out( &file );
167 out << u"<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/></head><body>\n"_s;
168 out << QObject::tr( "<p>Observed mean distance: %1</p>\n" ).arg( observedDistance, 0, 'f', 11 );
169 out << QObject::tr( "<p>Expected mean distance: %1</p>\n" ).arg( expectedDistance, 0, 'f', 11 );
170 out << QObject::tr( "<p>Nearest neighbour index: %1</p>\n" ).arg( nnIndex, 0, 'f', 11 );
171 out << QObject::tr( "<p>Number of points: %1</p>\n" ).arg( count );
172 out << QObject::tr( "<p>Z-Score: %1</p>\n" ).arg( zScore, 0, 'f', 11 );
173 out << u"</body></html>"_s;
174
175 outputs.insert( u"OUTPUT_HTML_FILE"_s, outputFile );
176 }
177 }
178
179 return outputs;
180}
181
@ VectorPoint
Vector point layers.
Definition qgis.h:3750
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3838
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3847
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.
Custom exception class for Coordinate Reference System related exceptions.
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)
Fetch next feature and stores in f, returns true on success.
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:60
QgsGeometry geometry
Definition qgsfeature.h:66
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
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.
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...
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