QGIS API Documentation 3.99.0-Master (357b655ed83)
Loading...
Searching...
No Matches
qgsalgorithmmeancoordinates.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmmeancoordinates.cpp
3 ---------------------
4 begin : April 2017
5 copyright : (C) 2017 by Nyall Dawson
6 email : nyall dot dawson 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 <QString>
21
22using namespace Qt::StringLiterals;
23
25
26QString QgsMeanCoordinatesAlgorithm::name() const
27{
28 return u"meancoordinates"_s;
29}
30
31QString QgsMeanCoordinatesAlgorithm::displayName() const
32{
33 return QObject::tr( "Mean coordinate(s)" );
34}
35
36QStringList QgsMeanCoordinatesAlgorithm::tags() const
37{
38 return QObject::tr( "mean,average,coordinate" ).split( ',' );
39}
40
41QString QgsMeanCoordinatesAlgorithm::group() const
42{
43 return QObject::tr( "Vector analysis" );
44}
45
46QString QgsMeanCoordinatesAlgorithm::groupId() const
47{
48 return u"vectoranalysis"_s;
49}
50
51void QgsMeanCoordinatesAlgorithm::initAlgorithm( const QVariantMap & )
52{
53 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorAnyGeometry ) ) );
54 addParameter( new QgsProcessingParameterField( u"WEIGHT"_s, QObject::tr( "Weight field" ), QVariant(), u"INPUT"_s, Qgis::ProcessingFieldParameterDataType::Numeric, false, true ) );
55 addParameter( new QgsProcessingParameterField( u"UID"_s, QObject::tr( "Unique ID field" ), QVariant(), u"INPUT"_s, Qgis::ProcessingFieldParameterDataType::Any, false, true ) );
56 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Mean coordinates" ), Qgis::ProcessingSourceType::VectorPoint ) );
57}
58
59QString QgsMeanCoordinatesAlgorithm::shortHelpString() const
60{
61 return QObject::tr( "This algorithm computes a point layer with the center of mass of geometries in an input layer.\n\n"
62 "An attribute can be specified as containing weights to be applied to each feature when computing the center of mass.\n\n"
63 "If an attribute is selected in the <Unique ID field> parameter, features will be grouped according "
64 "to values in this field. Instead of a single point with the center of mass of the whole layer, "
65 "the output layer will contain a center of mass for the features in each category." );
66}
67
68QString QgsMeanCoordinatesAlgorithm::shortDescription() const
69{
70 return QObject::tr( "Computes a point layer with the center of mass of geometries in an input layer." );
71}
72
73QgsMeanCoordinatesAlgorithm *QgsMeanCoordinatesAlgorithm::createInstance() const
74{
75 return new QgsMeanCoordinatesAlgorithm();
76}
77
78QVariantMap QgsMeanCoordinatesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
79{
80 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
81 if ( !source )
82 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
83
84 const QString weightFieldName = parameterAsString( parameters, u"WEIGHT"_s, context );
85 const QString uniqueFieldName = parameterAsString( parameters, u"UID"_s, context );
86
87 QgsAttributeList attributes;
88 int weightIndex = -1;
89 if ( !weightFieldName.isEmpty() )
90 {
91 weightIndex = source->fields().lookupField( weightFieldName );
92 if ( weightIndex >= 0 )
93 attributes.append( weightIndex );
94 }
95
96 int uniqueFieldIndex = -1;
97 if ( !uniqueFieldName.isEmpty() )
98 {
99 uniqueFieldIndex = source->fields().lookupField( uniqueFieldName );
100 if ( uniqueFieldIndex >= 0 )
101 attributes.append( uniqueFieldIndex );
102 }
103
104 QgsFields fields;
105 fields.append( QgsField( u"MEAN_X"_s, QMetaType::Type::Double, QString(), 24, 15 ) );
106 fields.append( QgsField( u"MEAN_Y"_s, QMetaType::Type::Double, QString(), 24, 15 ) );
107 if ( uniqueFieldIndex >= 0 )
108 {
109 const QgsField uniqueField = source->fields().at( uniqueFieldIndex );
110 fields.append( uniqueField );
111 }
112
113 QString dest;
114 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Point, source->sourceCrs() ) );
115 if ( !sink )
116 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
117
118 QgsFeatureIterator features = source->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( attributes ), Qgis::ProcessingFeatureSourceFlag::SkipGeometryValidityChecks );
119
120 double step = source->featureCount() > 0 ? 50.0 / source->featureCount() : 1;
121 int i = 0;
122 QgsFeature feat;
123
124 QHash<QVariant, QList<double>> means;
125 while ( features.nextFeature( feat ) )
126 {
127 i++;
128 if ( feedback->isCanceled() )
129 {
130 break;
131 }
132
133 feedback->setProgress( i * step );
134 if ( !feat.hasGeometry() )
135 continue;
136
137
138 QVariant featureClass;
139 if ( uniqueFieldIndex >= 0 )
140 {
141 featureClass = feat.attribute( uniqueFieldIndex );
142 }
143 else
144 {
145 featureClass = u"#####singleclass#####"_s;
146 }
147
148 double weight = 1;
149 if ( weightIndex >= 0 )
150 {
151 bool ok = false;
152 weight = feat.attribute( weightIndex ).toDouble( &ok );
153 if ( !ok )
154 weight = 1.0;
155 }
156
157 if ( weight < 0 )
158 {
159 throw QgsProcessingException( QObject::tr( "Negative weight value found. Please fix your data and try again." ) );
160 }
161
162 const QList<double> values = means.value( featureClass );
163 double cx = 0;
164 double cy = 0;
165 double totalWeight = 0;
166 if ( !values.empty() )
167 {
168 cx = values.at( 0 );
169 cy = values.at( 1 );
170 totalWeight = values.at( 2 );
171 }
172
173 QgsVertexId vid;
174 QgsPoint pt;
175 const QgsAbstractGeometry *g = feat.geometry().constGet();
176 // NOTE - should this be including the duplicate nodes for closed rings? currently it is,
177 // but I suspect that the expected behavior would be to NOT include these
178 while ( g->nextVertex( vid, pt ) )
179 {
180 cx += pt.x() * weight;
181 cy += pt.y() * weight;
182 totalWeight += weight;
183 }
184
185 means[featureClass] = QList<double>() << cx << cy << totalWeight;
186 }
187
188 i = 0;
189 step = !means.empty() ? 50.0 / means.count() : 1;
190 for ( auto it = means.constBegin(); it != means.constEnd(); ++it )
191 {
192 i++;
193 if ( feedback->isCanceled() )
194 {
195 break;
196 }
197
198 feedback->setProgress( 50 + i * step );
199 if ( qgsDoubleNear( it.value().at( 2 ), 0 ) )
200 continue;
201
202 QgsFeature outFeat;
203 const double cx = it.value().at( 0 ) / it.value().at( 2 );
204 const double cy = it.value().at( 1 ) / it.value().at( 2 );
205
206 const QgsPointXY meanPoint( cx, cy );
207 outFeat.setGeometry( QgsGeometry::fromPointXY( meanPoint ) );
208
209 QgsAttributes attributes;
210 attributes << cx << cy;
211 if ( uniqueFieldIndex >= 0 )
212 attributes.append( it.key() );
213
214 outFeat.setAttributes( attributes );
215 if ( !sink->addFeature( outFeat, QgsFeatureSink::FastInsert ) )
216 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
217 }
218
219 sink->finalize();
220
221 QVariantMap outputs;
222 outputs.insert( u"OUTPUT"_s, dest );
223 return outputs;
224}
225
226
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3604
@ VectorPoint
Vector point layers.
Definition qgis.h:3605
@ Numeric
Accepts numeric fields.
Definition qgis.h:3889
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3782
@ Point
Point.
Definition qgis.h:282
Abstract base class for all geometries.
virtual bool nextVertex(QgsVertexId &id, QgsPoint &vertex) const =0
Returns next vertex id and coordinates.
A vector of attributes.
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).
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:76
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
Represents a 2D point.
Definition qgspointxy.h:62
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
double x
Definition qgspoint.h:56
double y
Definition qgspoint.h:57
Contains information about the context in which a processing algorithm is executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6935
QList< int > QgsAttributeList
Definition qgsfield.h:30
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:34