32using namespace Qt::StringLiterals;
37void QgsJoinByLocationSummaryAlgorithm::initAlgorithm(
const QVariantMap & )
41 auto predicateParam = std::make_unique<QgsProcessingParameterEnum>( u
"PREDICATE"_s, QObject::tr(
"Where the features" ), QgsJoinByLocationAlgorithm::translatedPredicates(),
true, 0 );
42 QVariantMap predicateMetadata;
43 QVariantMap widgetMetadata;
44 widgetMetadata.insert( u
"useCheckBoxes"_s,
true );
45 widgetMetadata.insert( u
"columns"_s, 2 );
46 predicateMetadata.insert( u
"widget_wrapper"_s, widgetMetadata );
47 predicateParam->setMetadata( predicateMetadata );
48 addParameter( predicateParam.release() );
57 << QObject::tr(
"count" )
58 << QObject::tr(
"unique" )
59 << QObject::tr(
"min" )
60 << QObject::tr(
"max" )
61 << QObject::tr(
"range" )
62 << QObject::tr(
"sum" )
63 << QObject::tr(
"mean" )
64 << QObject::tr(
"median" )
65 << QObject::tr(
"stddev" )
66 << QObject::tr(
"minority" )
67 << QObject::tr(
"majority" )
68 << QObject::tr(
"q1" )
69 << QObject::tr(
"q3" )
70 << QObject::tr(
"iqr" )
71 << QObject::tr(
"empty" )
72 << QObject::tr(
"filled" )
73 << QObject::tr(
"min_length" )
74 << QObject::tr(
"max_length" )
75 << QObject::tr(
"mean_length" );
77 auto summaryParam = std::make_unique<QgsProcessingParameterEnum>( u
"SUMMARIES"_s, QObject::tr(
"Summaries to calculate (leave empty to use all available)" ), mAllSummaries,
true, QVariant(),
true );
78 addParameter( summaryParam.release() );
80 addParameter(
new QgsProcessingParameterBoolean( u
"DISCARD_NONMATCHING"_s, QObject::tr(
"Discard records which could not be joined" ),
false ) );
84QString QgsJoinByLocationSummaryAlgorithm::name()
const
86 return u
"joinbylocationsummary"_s;
89QString QgsJoinByLocationSummaryAlgorithm::displayName()
const
91 return QObject::tr(
"Join attributes by location (summary)" );
94QStringList QgsJoinByLocationSummaryAlgorithm::tags()
const
97 "summary,aggregate,join,intersects,intersecting,touching,within,contains,overlaps,relation,spatial,"
98 "stats,statistics,sum,maximum,minimum,mean,average,standard,deviation,"
99 "count,distinct,unique,variance,median,quartile,range,majority,minority,histogram,distinct"
104QString QgsJoinByLocationSummaryAlgorithm::group()
const
106 return QObject::tr(
"Vector general" );
109QString QgsJoinByLocationSummaryAlgorithm::groupId()
const
111 return u
"vectorgeneral"_s;
114QString QgsJoinByLocationSummaryAlgorithm::shortHelpString()
const
117 "This algorithm takes an input vector layer and creates a new vector layer that is an extended version of the input one, with additional attributes in its attribute table.\n\n"
118 "The additional attributes and their values are taken from a second vector layer. A spatial criteria is applied to select the values from the second layer that are added to each feature from the "
119 "first layer in the resulting one.\n\n"
120 "The algorithm calculates a statistical summary for the values from matching features in the second layer( e.g. maximum value, mean value, etc )."
124QString QgsJoinByLocationSummaryAlgorithm::shortDescription()
const
126 return QObject::tr(
"Calculates summaries of attributes from one vector layer to another by location." );
129QIcon QgsJoinByLocationSummaryAlgorithm::icon()
const
134QString QgsJoinByLocationSummaryAlgorithm::svgIconPath()
const
139QgsJoinByLocationSummaryAlgorithm *QgsJoinByLocationSummaryAlgorithm::createInstance()
const
141 return new QgsJoinByLocationSummaryAlgorithm();
146 std::unique_ptr<QgsProcessingFeatureSource> baseSource( parameterAsSource( parameters, u
"INPUT"_s, context ) );
150 std::unique_ptr<QgsProcessingFeatureSource> joinSource( parameterAsSource( parameters, u
"JOIN"_s, context ) );
155 feedback->
reportError( QObject::tr(
"No spatial index exists for join layer, performance will be severely degraded" ) );
157 QStringList joinedFieldNames = parameterAsStrings( parameters, u
"JOIN_FIELDS"_s, context );
159 bool discardNonMatching = parameterAsBoolean( parameters, u
"DISCARD_NONMATCHING"_s, context );
161 QList<int> summaries = parameterAsEnums( parameters, u
"SUMMARIES"_s, context );
162 if ( summaries.empty() )
164 for (
int i = 0; i < mAllSummaries.size(); ++i )
168 QgsFields sourceFields = baseSource->fields();
170 QList<int> joinFieldIndices;
171 if ( joinedFieldNames.empty() )
174 for (
const QgsField &sourceField : joinSource->fields() )
176 joinedFieldNames.append( sourceField.name() );
181 auto addFieldKeepType = [&fieldsToJoin](
const QgsField &original,
const QString &statistic ) {
184 fieldsToJoin.
append( field );
188 auto addFieldWithType = [&fieldsToJoin](
const QgsField &original,
const QString &statistic, QMetaType::Type type ) {
192 if ( type == QMetaType::Type::Double )
197 fieldsToJoin.
append( field );
206 QList<FieldType> fieldTypes;
208 struct FieldStatistic
210 FieldStatistic(
int enumIndex,
const QString &name, QMetaType::Type type )
211 : enumIndex( enumIndex )
218 QMetaType::Type type;
220 static const QVector<FieldStatistic> sNumericStats {
221 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
222 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
223 FieldStatistic( 2, u
"min"_s, QMetaType::Type::Double ),
224 FieldStatistic( 3, u
"max"_s, QMetaType::Type::Double ),
225 FieldStatistic( 4, u
"range"_s, QMetaType::Type::Double ),
226 FieldStatistic( 5, u
"sum"_s, QMetaType::Type::Double ),
227 FieldStatistic( 6, u
"mean"_s, QMetaType::Type::Double ),
228 FieldStatistic( 7, u
"median"_s, QMetaType::Type::Double ),
229 FieldStatistic( 8, u
"stddev"_s, QMetaType::Type::Double ),
230 FieldStatistic( 9, u
"minority"_s, QMetaType::Type::Double ),
231 FieldStatistic( 10, u
"majority"_s, QMetaType::Type::Double ),
232 FieldStatistic( 11, u
"q1"_s, QMetaType::Type::Double ),
233 FieldStatistic( 12, u
"q3"_s, QMetaType::Type::Double ),
234 FieldStatistic( 13, u
"iqr"_s, QMetaType::Type::Double ),
236 static const QVector<FieldStatistic> sDateTimeStats {
237 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
238 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
239 FieldStatistic( 14, u
"empty"_s, QMetaType::Type::LongLong ),
240 FieldStatistic( 15, u
"filled"_s, QMetaType::Type::LongLong ),
241 FieldStatistic( 2, u
"min"_s, QMetaType::Type::UnknownType ),
242 FieldStatistic( 3, u
"max"_s, QMetaType::Type::UnknownType ),
244 static const QVector<FieldStatistic> sStringStats {
245 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
246 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
247 FieldStatistic( 14, u
"empty"_s, QMetaType::Type::LongLong ),
248 FieldStatistic( 15, u
"filled"_s, QMetaType::Type::LongLong ),
249 FieldStatistic( 2, u
"min"_s, QMetaType::Type::UnknownType ),
250 FieldStatistic( 3, u
"max"_s, QMetaType::Type::UnknownType ),
251 FieldStatistic( 16, u
"min_length"_s, QMetaType::Type::Int ),
252 FieldStatistic( 17, u
"max_length"_s, QMetaType::Type::Int ),
253 FieldStatistic( 18, u
"mean_length"_s, QMetaType::Type::Double ),
256 for (
const QString &field : std::as_const( joinedFieldNames ) )
258 const int fieldIndex = joinSource->fields().lookupField( field );
259 if ( fieldIndex >= 0 )
261 joinFieldIndices.append( fieldIndex );
263 const QgsField joinField = joinSource->fields().at( fieldIndex );
264 QVector<FieldStatistic> statisticList;
267 fieldTypes.append( FieldType::Numeric );
268 statisticList = sNumericStats;
270 else if ( joinField.
type() == QMetaType::Type::QDate || joinField.
type() == QMetaType::Type::QTime || joinField.
type() == QMetaType::Type::QDateTime )
272 fieldTypes.append( FieldType::DateTime );
273 statisticList = sDateTimeStats;
277 fieldTypes.append( FieldType::String );
278 statisticList = sStringStats;
281 for (
const FieldStatistic &statistic : std::as_const( statisticList ) )
283 if ( summaries.contains( statistic.enumIndex ) )
285 if ( statistic.type != QMetaType::Type::UnknownType )
286 addFieldWithType( joinField, statistic.name, statistic.type );
288 addFieldKeepType( joinField, statistic.name );
297 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u
"OUTPUT"_s, context, destId, outputFields, baseSource->wkbType(), baseSource->sourceCrs() ) );
303 QList<int> predicates = parameterAsEnums( parameters, u
"PREDICATE"_s, context );
304 QgsJoinByLocationAlgorithm::sortPredicates( predicates );
308 const double step = baseSource->featureCount() > 0 ? 100.0 / baseSource->featureCount() : 1;
317 if ( !discardNonMatching )
329 std::unique_ptr<QgsGeometryEngine> engine;
330 QVector<QVector<QVariant>> values;
347 engine->prepareGeometry();
350 if ( QgsJoinByLocationAlgorithm::featureFilter( testJoinFeature, engine.get(),
true, predicates ) )
353 joinAttributes.reserve( joinFieldIndices.size() );
354 for (
int joinIndex : std::as_const( joinFieldIndices ) )
356 joinAttributes.append( testJoinFeature.
attribute( joinIndex ) );
358 values.append( joinAttributes );
368 if ( values.empty() )
370 if ( discardNonMatching )
388 outputAttributes.reserve( outputFields.
size() );
389 for (
int fieldIndex = 0; fieldIndex < joinFieldIndices.size(); ++fieldIndex )
391 const FieldType &fieldType = fieldTypes.at( fieldIndex );
394 case FieldType::Numeric:
397 for (
const QVector<QVariant> &value : std::as_const( values ) )
402 for (
const FieldStatistic &statistic : sNumericStats )
404 if ( summaries.contains( statistic.enumIndex ) )
407 switch ( statistic.enumIndex )
452 if ( val.isValid() && std::isnan( val.toDouble() ) )
454 outputAttributes.append( val );
460 case FieldType::DateTime:
463 QVariantList inputValues;
464 inputValues.reserve( values.size() );
465 for (
const QVector<QVariant> &value : std::as_const( values ) )
467 inputValues << value.at( fieldIndex );
470 for (
const FieldStatistic &statistic : sDateTimeStats )
472 if ( summaries.contains( statistic.enumIndex ) )
475 switch ( statistic.enumIndex )
496 outputAttributes.append( val );
502 case FieldType::String:
505 QVariantList inputValues;
506 inputValues.reserve( values.size() );
507 for (
const QVector<QVariant> &value : std::as_const( values ) )
509 if ( value.at( fieldIndex ).isNull() )
512 stat.
addString( value.at( fieldIndex ).toString() );
515 for (
const FieldStatistic &statistic : sStringStats )
517 if ( summaries.contains( statistic.enumIndex ) )
520 switch ( statistic.enumIndex )
550 outputAttributes.append( val );
568 results.insert( u
"OUTPUT"_s, destId );
@ VectorAnyGeometry
Any vector layer with geometry.
@ NotPresent
No spatial index exists for the source.
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.
Calculator for summary statistics and aggregates for a list of datetimes.
void calculate(const QVariantList &values)
Calculates summary statistics for a list of variants.
QDateTime min() const
Returns the minimum (earliest) non-null datetime value.
int count() const
Returns the calculated count of values.
int countMissing() const
Returns the number of missing (null) datetime values.
int countDistinct() const
Returns the number of distinct datetime values.
QDateTime max() const
Returns the maximum (latest) non-null datetime value.
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).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
QgsFeatureRequest & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setFilterRect(const QgsRectangle &rectangle)
Sets the rectangle from which features will be taken.
@ 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 resizeAttributes(int fieldCount)
Resizes the attributes attached to this feature to the given number of fields.
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
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.
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.
void setPrecision(int precision)
Set the field precision.
void setName(const QString &name)
Set the field name.
void setType(QMetaType::Type type)
Set variant type.
void setLength(int len)
Set the field length.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
int size() const
Returns number of items.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A boolean parameter for processing algorithms.
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.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
Calculator for summary statistics for a list of doubles.
void addVariant(const QVariant &value)
Adds a single value to the statistics calculation.
double firstQuartile() const
Returns the first quartile of the values.
double sum() const
Returns calculated sum of values.
double mean() const
Returns calculated mean of values.
double majority() const
Returns majority of values.
double interQuartileRange() const
Returns the inter quartile range of the values.
double median() const
Returns calculated median of values.
double minority() const
Returns minority of values.
double min() const
Returns calculated minimum from values.
double stDev() const
Returns population standard deviation.
double thirdQuartile() const
Returns the third quartile of the values.
int count() const
Returns calculated count of values.
double range() const
Returns calculated range (difference between maximum and minimum values).
double max() const
Returns calculated maximum from values.
void finalize()
Must be called after adding all values with addValues() and before retrieving any calculated statisti...
int variety() const
Returns variety of values.
Calculator for summary statistics and aggregates for a list of strings.
QString max() const
Returns the maximum (non-null) string value.
QString min() const
Returns the minimum (non-null) string value.
int countMissing() const
Returns the number of missing (null) string values.
int count() const
Returns the calculated count of values.
int countDistinct() const
Returns the number of distinct string values.
void finalize()
Must be called after adding all strings with addString() and before retrieving any calculated string ...
void addString(const QString &string)
Adds a single string to the statistics calculation.
int minLength() const
Returns the minimum length of strings.
int maxLength() const
Returns the maximum length of strings.
double meanLength() const
Returns the mean length of strings.