25using namespace Qt::StringLiterals;
29QString QgsAggregateAlgorithm::name()
const
31 return u
"aggregate"_s;
34QString QgsAggregateAlgorithm::displayName()
const
36 return QObject::tr(
"Aggregate" );
39QString QgsAggregateAlgorithm::shortHelpString()
const
42 "This algorithm takes a vector or table layer and aggregates features based on a group by expression. Features for which group by expression return the same value are grouped together.\n\n"
43 "It is possible to group all source features together using constant value in group by parameter, example: NULL.\n\n"
44 "It is also possible to group features using multiple fields using Array function, example: Array(\"Field1\", \"Field2\").\n\n"
45 "Geometries (if present) are combined into one multipart geometry for each group.\n\n"
46 "Output attributes are computed depending on each given aggregate definition."
50QString QgsAggregateAlgorithm::shortDescription()
const
52 return QObject::tr(
"Aggregates features based on a group by expression, combining geometries (if present) into one multipart geometry for each group." );
60QStringList QgsAggregateAlgorithm::tags()
const
62 return QObject::tr(
"attributes,sum,mean,median,count,collect,dissolve,statistics,merge,combine,concatenate" ).split(
',' );
65QString QgsAggregateAlgorithm::group()
const
67 return QObject::tr(
"Vector geometry" );
70QString QgsAggregateAlgorithm::groupId()
const
72 return u
"vectorgeometry"_s;
75QgsAggregateAlgorithm *QgsAggregateAlgorithm::createInstance()
const
77 return new QgsAggregateAlgorithm();
80void QgsAggregateAlgorithm::initAlgorithm(
const QVariantMap & )
83 addParameter(
new QgsProcessingParameterExpression( u
"GROUP_BY"_s, QObject::tr(
"Group by expression (NULL to group all features)" ), u
"NULL"_s, u
"INPUT"_s ) );
90 mSource.reset( parameterAsSource( parameters, u
"INPUT"_s, context ) );
94 mGroupBy = parameterAsExpression( parameters, u
"GROUP_BY"_s, context );
99 mGroupByExpression = createExpression( mGroupBy, context );
100 mGeometryExpression = createExpression( u
"collect($geometry, %1)"_s.arg( mGroupBy ), context );
102 const QVariantList aggregates = parameters.value( u
"AGGREGATES"_s ).toList();
103 int currentAttributeIndex = 0;
104 for (
const QVariant &aggregate : aggregates )
106 const QVariantMap aggregateDef = aggregate.toMap();
108 const QString name = aggregateDef.value( u
"name"_s ).toString();
109 if ( name.isEmpty() )
112 const QMetaType::Type type =
static_cast<QMetaType::Type
>( aggregateDef.value( u
"type"_s ).toInt() );
113 const QString typeName = aggregateDef.value( u
"type_name"_s ).toString();
114 const QMetaType::Type subType =
static_cast<QMetaType::Type
>( aggregateDef.value( u
"sub_type"_s ).toInt() );
116 const int length = aggregateDef.value( u
"length"_s, 0 ).toInt();
117 const int precision = aggregateDef.value( u
"precision"_s, 0 ).toInt();
119 mFields.append(
QgsField( name, type, typeName, length, precision, QString(), subType ) );
122 const QString aggregateType = aggregateDef.value( u
"aggregate"_s ).toString();
123 const QString source = aggregateDef.value( u
"input"_s ).toString();
124 const QString delimiter = aggregateDef.value( u
"delimiter"_s ).toString();
127 if ( aggregateType ==
"first_value"_L1 )
131 else if ( aggregateType ==
"last_value"_L1 )
134 mAttributesRequireLastFeature << currentAttributeIndex;
136 else if ( aggregateType ==
"concatenate"_L1 || aggregateType ==
"concatenate_unique"_L1 )
142 expression = u
"%1(%2, %3)"_s.arg( aggregateType, source, mGroupBy );
144 mExpressions.append( createExpression( expression, context ) );
145 currentAttributeIndex++;
153 QGS_MARK_ALGORITHM_SOURCE
155 QgsExpressionContext expressionContext = createExpressionContext( parameters, context, mSource.get() );
156 mGroupByExpression.prepare( &expressionContext );
159 const long long count = mSource->featureCount();
160 double progressStep = count > 0 ? 50.0 / count : 1;
161 long long current = 0;
163 QHash<QVariantList, Group> groups;
164 QVector<QVariantList> keys;
167 std::vector<std::unique_ptr<QgsFeatureSink>> groupSinks;
172 expressionContext.setFeature( feature );
173 const QVariant groupByValue = mGroupByExpression.evaluate( &expressionContext );
174 if ( mGroupByExpression.hasEvalError() )
176 throw QgsProcessingException( QObject::tr(
"Evaluation error in group by expression \"%1\": %2" ).arg( mGroupByExpression.expression(), mGroupByExpression.evalErrorString() ) );
180 const QVariantList key = groupByValue.userType() == QMetaType::Type::QVariantList ? groupByValue.toList() : ( QVariantList() << groupByValue );
182 const auto groupIt = groups.find( key );
183 if ( groupIt == groups.end() )
185 QString
id = u
"memory:"_s;
194 group.sink = sink.get();
196 groupSinks.emplace_back( std::move( sink ) );
198 group.firstFeature = feature;
199 group.lastFeature = feature;
200 groups[key] = std::move( group );
207 groupIt->lastFeature = feature;
220 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u
"OUTPUT"_s, context, destId, mFields,
QgsWkbTypes::multiType( mSource->wkbType() ), mSource->sourceCrs() ) );
226 progressStep = 50.0 / keys.size();
229 for (
const QVariantList &key : keys )
231 const Group &group = groups[key];
238 if ( mGeometryExpression.hasEvalError() )
240 throw QgsProcessingException( QObject::tr(
"Evaluation error in geometry expression \"%1\": %2" ).arg( mGeometryExpression.expression(), mGeometryExpression.evalErrorString() ) );
248 QStringList keyString;
249 for (
const QVariant &v : key )
250 keyString << v.toString();
252 throw QgsProcessingException( QObject::tr(
"Impossible to combine geometries for %1 = %2" ).arg( mGroupBy, keyString.join(
',' ) ) );
257 attributes.reserve( mExpressions.size() );
258 int currentAttributeIndex = 0;
259 for (
auto it = mExpressions.begin(); it != mExpressions.end(); ++it )
261 exprContext.
setFeature( mAttributesRequireLastFeature.contains( currentAttributeIndex ) ? group.lastFeature : group.firstFeature );
264 const QVariant value = it->evaluate( &exprContext );
265 if ( it->hasEvalError() )
267 throw QgsProcessingException( QObject::tr(
"Evaluation error in expression \"%1\": %2" ).arg( it->expression(), it->evalErrorString() ) );
269 attributes.append( value );
273 attributes.append( QVariant() );
275 currentAttributeIndex++;
288 feedback->
setProgress( 50 + current * progressStep );
297 results.insert( u
"OUTPUT"_s, destId );
301bool QgsAggregateAlgorithm::supportInPlaceEdit(
const QgsMapLayer *layer )
const
310 expr.setGeomCalculator( &mDa );
312 expr.setAreaUnits( context.
areaUnit() );
313 if ( expr.hasParserError() )
315 throw QgsProcessingException( QObject::tr(
"Parser error in expression \"%1\": %2" ).arg( expressionString, expr.parserErrorString() ) );
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
static QgsExpressionContextScope * layerScope(const QgsMapLayer *layer)
Creates a new scope which contains variables and functions relating to a QgsMapLayer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void setFeature(const QgsFeature &feature)
Convenience function for setting a feature for the context.
Handles parsing and evaluation of expressions (formerly called "search strings").
static QString quotedString(QString text)
Returns a quoted version of a string (in single quotes).
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.
bool isValid() const
Will return if this iterator is valid.
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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Encapsulates parameters under which a geometry operation is performed.
A geometry is the spatial representation of a feature.
QVector< QgsGeometry > asGeometryCollection() const
Returns contents of the geometry as a list of geometries.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters ¶meters=QgsGeometryParameters(), QgsFeedback *feedback=nullptr)
Compute the unary union on a list of geometries.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
Base class for all map layer types.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Qgis::AreaUnit areaUnit() const
Returns the area unit to use for area calculations.
Qgis::DistanceUnit distanceUnit() const
Returns the distance unit to use for distance calculations.
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.
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 parameter for "aggregate" configurations, which consist of a definition of desired output fields,...
An expression parameter for processing algorithms.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap(), const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QgsRemappingSinkDefinition *remappingDefinition=nullptr)
Creates a feature sink ready for adding features.
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, QgsProcessingUtils::LayerHint typeHint=QgsProcessingUtils::LayerHint::UnknownType, QgsProcessing::LayerOptionsFlags flags=QgsProcessing::LayerOptionsFlags())
Interprets a string as a map layer within the supplied context.
static Qgis::WkbType multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.