31using namespace Qt::StringLiterals;
36void QgsJoinByLocationSummaryAlgorithm::initAlgorithm(
const QVariantMap & )
40 auto predicateParam = std::make_unique<QgsProcessingParameterEnum>( u
"PREDICATE"_s, QObject::tr(
"Where the features" ), QgsJoinByLocationAlgorithm::translatedPredicates(),
true, 0 );
41 QVariantMap predicateMetadata;
42 QVariantMap widgetMetadata;
43 widgetMetadata.insert( u
"useCheckBoxes"_s,
true );
44 widgetMetadata.insert( u
"columns"_s, 2 );
45 predicateMetadata.insert( u
"widget_wrapper"_s, widgetMetadata );
46 predicateParam->setMetadata( predicateMetadata );
47 addParameter( predicateParam.release() );
56 << QObject::tr(
"count" )
57 << QObject::tr(
"unique" )
58 << QObject::tr(
"min" )
59 << QObject::tr(
"max" )
60 << QObject::tr(
"range" )
61 << QObject::tr(
"sum" )
62 << QObject::tr(
"mean" )
63 << QObject::tr(
"median" )
64 << QObject::tr(
"stddev" )
65 << QObject::tr(
"minority" )
66 << QObject::tr(
"majority" )
67 << QObject::tr(
"q1" )
68 << QObject::tr(
"q3" )
69 << QObject::tr(
"iqr" )
70 << QObject::tr(
"empty" )
71 << QObject::tr(
"filled" )
72 << QObject::tr(
"min_length" )
73 << QObject::tr(
"max_length" )
74 << QObject::tr(
"mean_length" );
76 auto summaryParam = std::make_unique<QgsProcessingParameterEnum>( u
"SUMMARIES"_s, QObject::tr(
"Summaries to calculate (leave empty to use all available)" ), mAllSummaries,
true, QVariant(),
true );
77 addParameter( summaryParam.release() );
79 addParameter(
new QgsProcessingParameterBoolean( u
"DISCARD_NONMATCHING"_s, QObject::tr(
"Discard records which could not be joined" ),
false ) );
83QString QgsJoinByLocationSummaryAlgorithm::name()
const
85 return u
"joinbylocationsummary"_s;
88QString QgsJoinByLocationSummaryAlgorithm::displayName()
const
90 return QObject::tr(
"Join attributes by location (summary)" );
93QStringList QgsJoinByLocationSummaryAlgorithm::tags()
const
96 "summary,aggregate,join,intersects,intersecting,touching,within,contains,overlaps,relation,spatial,"
97 "stats,statistics,sum,maximum,minimum,mean,average,standard,deviation,"
98 "count,distinct,unique,variance,median,quartile,range,majority,minority,histogram,distinct"
103QString QgsJoinByLocationSummaryAlgorithm::group()
const
105 return QObject::tr(
"Vector general" );
108QString QgsJoinByLocationSummaryAlgorithm::groupId()
const
110 return u
"vectorgeneral"_s;
113QString QgsJoinByLocationSummaryAlgorithm::shortHelpString()
const
116 "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"
117 "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 "
118 "first layer in the resulting one.\n\n"
119 "The algorithm calculates a statistical summary for the values from matching features in the second layer( e.g. maximum value, mean value, etc )."
123QString QgsJoinByLocationSummaryAlgorithm::shortDescription()
const
125 return QObject::tr(
"Calculates summaries of attributes from one vector layer to another by location." );
128QIcon QgsJoinByLocationSummaryAlgorithm::icon()
const
133QString QgsJoinByLocationSummaryAlgorithm::svgIconPath()
const
138QgsJoinByLocationSummaryAlgorithm *QgsJoinByLocationSummaryAlgorithm::createInstance()
const
140 return new QgsJoinByLocationSummaryAlgorithm();
145 std::unique_ptr<QgsProcessingFeatureSource> baseSource( parameterAsSource( parameters, u
"INPUT"_s, context ) );
149 std::unique_ptr<QgsProcessingFeatureSource> joinSource( parameterAsSource( parameters, u
"JOIN"_s, context ) );
154 feedback->
reportError( QObject::tr(
"No spatial index exists for join layer, performance will be severely degraded" ) );
156 QStringList joinedFieldNames = parameterAsStrings( parameters, u
"JOIN_FIELDS"_s, context );
158 bool discardNonMatching = parameterAsBoolean( parameters, u
"DISCARD_NONMATCHING"_s, context );
160 QList<int> summaries = parameterAsEnums( parameters, u
"SUMMARIES"_s, context );
161 if ( summaries.empty() )
163 for (
int i = 0; i < mAllSummaries.size(); ++i )
167 QgsFields sourceFields = baseSource->fields();
169 QList<int> joinFieldIndices;
170 if ( joinedFieldNames.empty() )
173 for (
const QgsField &sourceField : joinSource->fields() )
175 joinedFieldNames.append( sourceField.name() );
180 auto addFieldKeepType = [&fieldsToJoin](
const QgsField &original,
const QString &statistic ) {
183 fieldsToJoin.
append( field );
187 auto addFieldWithType = [&fieldsToJoin](
const QgsField &original,
const QString &statistic, QMetaType::Type type ) {
191 if ( type == QMetaType::Type::Double )
196 fieldsToJoin.
append( field );
205 QList<FieldType> fieldTypes;
207 struct FieldStatistic
209 FieldStatistic(
int enumIndex,
const QString &name, QMetaType::Type type )
210 : enumIndex( enumIndex )
217 QMetaType::Type type;
219 static const QVector<FieldStatistic> sNumericStats {
220 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
221 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
222 FieldStatistic( 2, u
"min"_s, QMetaType::Type::Double ),
223 FieldStatistic( 3, u
"max"_s, QMetaType::Type::Double ),
224 FieldStatistic( 4, u
"range"_s, QMetaType::Type::Double ),
225 FieldStatistic( 5, u
"sum"_s, QMetaType::Type::Double ),
226 FieldStatistic( 6, u
"mean"_s, QMetaType::Type::Double ),
227 FieldStatistic( 7, u
"median"_s, QMetaType::Type::Double ),
228 FieldStatistic( 8, u
"stddev"_s, QMetaType::Type::Double ),
229 FieldStatistic( 9, u
"minority"_s, QMetaType::Type::Double ),
230 FieldStatistic( 10, u
"majority"_s, QMetaType::Type::Double ),
231 FieldStatistic( 11, u
"q1"_s, QMetaType::Type::Double ),
232 FieldStatistic( 12, u
"q3"_s, QMetaType::Type::Double ),
233 FieldStatistic( 13, u
"iqr"_s, QMetaType::Type::Double ),
235 static const QVector<FieldStatistic> sDateTimeStats {
236 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
237 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
238 FieldStatistic( 14, u
"empty"_s, QMetaType::Type::LongLong ),
239 FieldStatistic( 15, u
"filled"_s, QMetaType::Type::LongLong ),
240 FieldStatistic( 2, u
"min"_s, QMetaType::Type::UnknownType ),
241 FieldStatistic( 3, u
"max"_s, QMetaType::Type::UnknownType ),
243 static const QVector<FieldStatistic> sStringStats {
244 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
245 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
246 FieldStatistic( 14, u
"empty"_s, QMetaType::Type::LongLong ),
247 FieldStatistic( 15, u
"filled"_s, QMetaType::Type::LongLong ),
248 FieldStatistic( 2, u
"min"_s, QMetaType::Type::UnknownType ),
249 FieldStatistic( 3, u
"max"_s, QMetaType::Type::UnknownType ),
250 FieldStatistic( 16, u
"min_length"_s, QMetaType::Type::Int ),
251 FieldStatistic( 17, u
"max_length"_s, QMetaType::Type::Int ),
252 FieldStatistic( 18, u
"mean_length"_s, QMetaType::Type::Double ),
257 for (
const QString &field : std::as_const( joinedFieldNames ) )
259 const int fieldIndex = joinSource->fields().lookupField( field );
260 if ( fieldIndex >= 0 )
262 joinFieldIndices.append( fieldIndex );
264 const QgsField joinField = joinSource->fields().at( fieldIndex );
265 QVector<FieldStatistic> statisticList;
268 fieldTypes.append( FieldType::Numeric );
269 statisticList = sNumericStats;
271 else if ( joinField.
type() == QMetaType::Type::QDate || joinField.
type() == QMetaType::Type::QTime || joinField.
type() == QMetaType::Type::QDateTime )
273 fieldTypes.append( FieldType::DateTime );
274 statisticList = sDateTimeStats;
278 fieldTypes.append( FieldType::String );
279 statisticList = sStringStats;
282 for (
const FieldStatistic &statistic : std::as_const( statisticList ) )
284 if ( summaries.contains( statistic.enumIndex ) )
286 if ( statistic.type != QMetaType::Type::UnknownType )
287 addFieldWithType( joinField, statistic.name, statistic.type );
289 addFieldKeepType( joinField, statistic.name );
293 if ( statistic.enumIndex == 0 || statistic.enumIndex == 1 || statistic.enumIndex == 14 || statistic.enumIndex == 15 )
295 nonMatchingJoinAttributes.append( QVariant( 0 ) );
299 nonMatchingJoinAttributes.append( QVariant() );
309 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u
"OUTPUT"_s, context, destId, outputFields, baseSource->wkbType(), baseSource->sourceCrs() ) );
315 QList<int> predicates = parameterAsEnums( parameters, u
"PREDICATE"_s, context );
316 QgsJoinByLocationAlgorithm::sortPredicates( predicates );
320 const double step = baseSource->featureCount() > 0 ? 100.0 /
static_cast<double>( baseSource->featureCount() ) : 1;
329 if ( !discardNonMatching )
335 outputAttributes.append( nonMatchingJoinAttributes );
345 std::unique_ptr<QgsGeometryEngine> engine;
346 QVector<QVector<QVariant>> values;
363 engine->prepareGeometry();
366 if ( QgsJoinByLocationAlgorithm::featureFilter( testJoinFeature, engine.get(),
true, predicates ) )
369 joinAttributes.reserve( joinFieldIndices.size() );
370 for (
int joinIndex : std::as_const( joinFieldIndices ) )
372 joinAttributes.append( testJoinFeature.
attribute( joinIndex ) );
374 values.append( joinAttributes );
379 feedback->
setProgress(
static_cast<double>( i ) * step );
384 if ( values.empty() )
386 if ( discardNonMatching )
396 outputAttributes.append( nonMatchingJoinAttributes );
408 outputAttributes.reserve( outputFields.
size() );
409 for (
int fieldIndex = 0; fieldIndex < joinFieldIndices.size(); ++fieldIndex )
411 const FieldType &fieldType = fieldTypes.at( fieldIndex );
414 case FieldType::Numeric:
417 for (
const QVector<QVariant> &value : std::as_const( values ) )
422 for (
const FieldStatistic &statistic : sNumericStats )
424 if ( summaries.contains( statistic.enumIndex ) )
427 switch ( statistic.enumIndex )
472 if ( val.isValid() && std::isnan( val.toDouble() ) )
474 outputAttributes.append( val );
480 case FieldType::DateTime:
483 QVariantList inputValues;
484 inputValues.reserve( values.size() );
485 for (
const QVector<QVariant> &value : std::as_const( values ) )
487 inputValues << value.at( fieldIndex );
490 for (
const FieldStatistic &statistic : sDateTimeStats )
492 if ( summaries.contains( statistic.enumIndex ) )
495 switch ( statistic.enumIndex )
516 outputAttributes.append( val );
522 case FieldType::String:
525 QVariantList inputValues;
526 inputValues.reserve( values.size() );
527 for (
const QVector<QVariant> &value : std::as_const( values ) )
529 if ( value.at( fieldIndex ).isNull() )
532 stat.
addString( value.at( fieldIndex ).toString() );
535 for (
const FieldStatistic &statistic : sStringStats )
537 if ( summaries.contains( statistic.enumIndex ) )
540 switch ( statistic.enumIndex )
570 outputAttributes.append( val );
591 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 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.
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.
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.