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