QGIS API Documentation 4.3.0-Master (ffcfc20b9b4)
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(
62 "This algorithm computes a point layer with the center of mass of geometries in an input layer.\n\n"
63 "An attribute can be specified as containing weights to be applied to each feature when computing the center of mass.\n\n"
64 "If an attribute is selected in the <Unique ID field> parameter, features will be grouped according "
65 "to values in this field. Instead of a single point with the center of mass of the whole layer, "
66 "the output layer will contain a center of mass for the features in each category."
67 );
68}
69
70QString QgsMeanCoordinatesAlgorithm::shortDescription() const
71{
72 return QObject::tr( "Computes a point layer with the center of mass of geometries in an input layer." );
73}
74
75QgsMeanCoordinatesAlgorithm *QgsMeanCoordinatesAlgorithm::createInstance() const
76{
77 return new QgsMeanCoordinatesAlgorithm();
78}
79
80QVariantMap QgsMeanCoordinatesAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
81{
82 QGS_MARK_ALGORITHM_SOURCE
83
84 std::unique_ptr<QgsProcessingFeatureSource> source( parameterAsSource( parameters, u"INPUT"_s, context ) );
85 if ( !source )
86 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
87
88 const QString weightFieldName = parameterAsString( parameters, u"WEIGHT"_s, context );
89 const QString uniqueFieldName = parameterAsString( parameters, u"UID"_s, context );
90
91 QgsAttributeList attributes;
92 int weightIndex = -1;
93 if ( !weightFieldName.isEmpty() )
94 {
95 weightIndex = source->fields().lookupField( weightFieldName );
96 if ( weightIndex >= 0 )
97 attributes.append( weightIndex );
98 }
99
100 int uniqueFieldIndex = -1;
101 if ( !uniqueFieldName.isEmpty() )
102 {
103 uniqueFieldIndex = source->fields().lookupField( uniqueFieldName );
104 if ( uniqueFieldIndex >= 0 )
105 attributes.append( uniqueFieldIndex );
106 }
107
108 QgsFields fields;
109 fields.append( QgsField( u"MEAN_X"_s, QMetaType::Type::Double, QString(), 24, 15 ) );
110 fields.append( QgsField( u"MEAN_Y"_s, QMetaType::Type::Double, QString(), 24, 15 ) );
111 if ( uniqueFieldIndex >= 0 )
112 {
113 const QgsField uniqueField = source->fields().at( uniqueFieldIndex );
114 fields.append( uniqueField );
115 }
116
117 QString dest;
118 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, Qgis::WkbType::Point, source->sourceCrs() ) );
119 if ( !sink )
120 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
121
122 QgsFeatureIterator features = source->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( attributes ), Qgis::ProcessingFeatureSourceFlag::SkipGeometryValidityChecks );
123
124 double step = source->featureCount() > 0 ? 50.0 / source->featureCount() : 1;
125 int i = 0;
126 QgsFeature feat;
127
128 QHash<QVariant, QList<double>> means;
129 while ( features.nextFeature( feat ) )
130 {
131 i++;
132 if ( feedback->isCanceled() )
133 {
134 break;
135 }
136
137 feedback->setProgress( i * step );
138 if ( !feat.hasGeometry() )
139 continue;
140
141
142 QVariant featureClass;
143 if ( uniqueFieldIndex >= 0 )
144 {
145 featureClass = feat.attribute( uniqueFieldIndex );
146 }
147 else
148 {
149 featureClass = u"#####singleclass#####"_s;
150 }
151
152 double weight = 1;
153 if ( weightIndex >= 0 )
154 {
155 bool ok = false;
156 weight = feat.attribute( weightIndex ).toDouble( &ok );
157 if ( !ok )
158 weight = 1.0;
159 }
160
161 if ( weight < 0 )
162 {
163 throw QgsProcessingException( QObject::tr( "Negative weight value found. Please fix your data and try again." ) );
164 }
165
166 const QList<double> values = means.value( featureClass );
167 double cx = 0;
168 double cy = 0;
169 double totalWeight = 0;
170 if ( !values.empty() )
171 {
172 cx = values.at( 0 );
173 cy = values.at( 1 );
174 totalWeight = values.at( 2 );
175 }
176
177 QgsVertexId vid;
178 QgsPoint pt;
179 const QgsAbstractGeometry *g = feat.geometry().constGet();
180 // NOTE - should this be including the duplicate nodes for closed rings? currently it is,
181 // but I suspect that the expected behavior would be to NOT include these
182 while ( g->nextVertex( vid, pt ) )
183 {
184 cx += pt.x() * weight;
185 cy += pt.y() * weight;
186 totalWeight += weight;
187 }
188
189 means[featureClass] = QList<double>() << cx << cy << totalWeight;
190 }
191
192 i = 0;
193 step = !means.empty() ? 50.0 / means.count() : 1;
194 for ( auto it = means.constBegin(); it != means.constEnd(); ++it )
195 {
196 i++;
197 if ( feedback->isCanceled() )
198 {
199 break;
200 }
201
202 feedback->setProgress( 50 + i * step );
203 if ( qgsDoubleNear( it.value().at( 2 ), 0 ) )
204 continue;
205
206 QgsFeature outFeat;
207 const double cx = it.value().at( 0 ) / it.value().at( 2 );
208 const double cy = it.value().at( 1 ) / it.value().at( 2 );
209
210 const QgsPointXY meanPoint( cx, cy );
211 outFeat.setGeometry( QgsGeometry::fromPointXY( meanPoint ) );
212
213 QgsAttributes attributes;
214 attributes << cx << cy;
215 if ( uniqueFieldIndex >= 0 )
216 attributes.append( it.key() );
217
218 outFeat.setAttributes( attributes );
219 if ( !sink->addFeature( outFeat, QgsFeatureSink::FastInsert ) )
220 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
221 else
222 feedback->featureAddedToSink( u"OUTPUT"_s );
223 }
224
225 sink->finalize();
226 feedback->featureSinkFinalized( u"OUTPUT"_s );
227
228 QVariantMap outputs;
229 outputs.insert( u"OUTPUT"_s, dest );
230 return outputs;
231}
232
233
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3749
@ VectorPoint
Vector point layers.
Definition qgis.h:3750
@ Numeric
Accepts numeric fields.
Definition qgis.h:4037
@ SkipGeometryValidityChecks
Invalid geometry checks should always be skipped. This flag can be useful for algorithms which always...
Definition qgis.h:3930
@ Point
Point.
Definition qgis.h:296
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:66
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:56
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:65
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:45
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
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.
void featureAddedToSink(const QString &output)
Reports that a feature was added to the the sink associated with the specified algorithm output.
void featureSinkFinalized(const QString &output)
Reports that a feature sink has been finalized.
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:7557
QList< int > QgsAttributeList
Definition qgsfield.h:30
Utility class for identifying a unique vertex within a geometry.
Definition qgsvertexid.h:35