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