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 QGS_MARK_ALGORITHM_SOURCE
147 std::unique_ptr<QgsProcessingFeatureSource> baseSource( parameterAsSource( parameters, u
"INPUT"_s, context ) );
151 std::unique_ptr<QgsProcessingFeatureSource> joinSource( parameterAsSource( parameters, u
"JOIN"_s, context ) );
156 feedback->
reportError( QObject::tr(
"No spatial index exists for join layer, performance will be severely degraded" ) );
158 QStringList joinedFieldNames = parameterAsStrings( parameters, u
"JOIN_FIELDS"_s, context );
160 bool discardNonMatching = parameterAsBoolean( parameters, u
"DISCARD_NONMATCHING"_s, context );
162 QList<int> summaries = parameterAsEnums( parameters, u
"SUMMARIES"_s, context );
163 if ( summaries.empty() )
165 for (
int i = 0; i < mAllSummaries.size(); ++i )
169 QgsFields sourceFields = baseSource->fields();
171 QList<int> joinFieldIndices;
172 if ( joinedFieldNames.empty() )
175 for (
const QgsField &sourceField : joinSource->fields() )
177 joinedFieldNames.append( sourceField.name() );
182 auto addFieldKeepType = [&fieldsToJoin](
const QgsField &original,
const QString &statistic ) {
185 fieldsToJoin.
append( field );
189 auto addFieldWithType = [&fieldsToJoin](
const QgsField &original,
const QString &statistic, QMetaType::Type type ) {
193 if ( type == QMetaType::Type::Double )
198 fieldsToJoin.
append( field );
207 QList<FieldType> fieldTypes;
209 struct FieldStatistic
211 FieldStatistic(
int enumIndex,
const QString &name, QMetaType::Type type )
212 : enumIndex( enumIndex )
219 QMetaType::Type type;
221 static const QVector<FieldStatistic> sNumericStats {
222 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
223 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
224 FieldStatistic( 2, u
"min"_s, QMetaType::Type::Double ),
225 FieldStatistic( 3, u
"max"_s, QMetaType::Type::Double ),
226 FieldStatistic( 4, u
"range"_s, QMetaType::Type::Double ),
227 FieldStatistic( 5, u
"sum"_s, QMetaType::Type::Double ),
228 FieldStatistic( 6, u
"mean"_s, QMetaType::Type::Double ),
229 FieldStatistic( 7, u
"median"_s, QMetaType::Type::Double ),
230 FieldStatistic( 8, u
"stddev"_s, QMetaType::Type::Double ),
231 FieldStatistic( 9, u
"minority"_s, QMetaType::Type::Double ),
232 FieldStatistic( 10, u
"majority"_s, QMetaType::Type::Double ),
233 FieldStatistic( 11, u
"q1"_s, QMetaType::Type::Double ),
234 FieldStatistic( 12, u
"q3"_s, QMetaType::Type::Double ),
235 FieldStatistic( 13, u
"iqr"_s, QMetaType::Type::Double ),
237 static const QVector<FieldStatistic> sDateTimeStats {
238 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
239 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
240 FieldStatistic( 14, u
"empty"_s, QMetaType::Type::LongLong ),
241 FieldStatistic( 15, u
"filled"_s, QMetaType::Type::LongLong ),
242 FieldStatistic( 2, u
"min"_s, QMetaType::Type::UnknownType ),
243 FieldStatistic( 3, u
"max"_s, QMetaType::Type::UnknownType ),
245 static const QVector<FieldStatistic> sStringStats {
246 FieldStatistic( 0, u
"count"_s, QMetaType::Type::LongLong ),
247 FieldStatistic( 1, u
"unique"_s, QMetaType::Type::LongLong ),
248 FieldStatistic( 14, u
"empty"_s, QMetaType::Type::LongLong ),
249 FieldStatistic( 15, u
"filled"_s, QMetaType::Type::LongLong ),
250 FieldStatistic( 2, u
"min"_s, QMetaType::Type::UnknownType ),
251 FieldStatistic( 3, u
"max"_s, QMetaType::Type::UnknownType ),
252 FieldStatistic( 16, u
"min_length"_s, QMetaType::Type::Int ),
253 FieldStatistic( 17, u
"max_length"_s, QMetaType::Type::Int ),
254 FieldStatistic( 18, u
"mean_length"_s, QMetaType::Type::Double ),
259 for (
const QString &field : std::as_const( joinedFieldNames ) )
261 const int fieldIndex = joinSource->fields().lookupField( field );
262 if ( fieldIndex >= 0 )
264 joinFieldIndices.append( fieldIndex );
266 const QgsField joinField = joinSource->fields().at( fieldIndex );
267 QVector<FieldStatistic> statisticList;
270 fieldTypes.append( FieldType::Numeric );
271 statisticList = sNumericStats;
273 else if ( joinField.
type() == QMetaType::Type::QDate || joinField.
type() == QMetaType::Type::QTime || joinField.
type() == QMetaType::Type::QDateTime )
275 fieldTypes.append( FieldType::DateTime );
276 statisticList = sDateTimeStats;
280 fieldTypes.append( FieldType::String );
281 statisticList = sStringStats;
284 for (
const FieldStatistic &statistic : std::as_const( statisticList ) )
286 if ( summaries.contains( statistic.enumIndex ) )
288 if ( statistic.type != QMetaType::Type::UnknownType )
289 addFieldWithType( joinField, statistic.name, statistic.type );
291 addFieldKeepType( joinField, statistic.name );
295 if ( statistic.enumIndex == 0 || statistic.enumIndex == 1 || statistic.enumIndex == 14 || statistic.enumIndex == 15 )
297 nonMatchingJoinAttributes.append( QVariant( 0 ) );
301 nonMatchingJoinAttributes.append( QVariant() );
311 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u
"OUTPUT"_s, context, destId, outputFields, baseSource->wkbType(), baseSource->sourceCrs() ) );
317 QList<int> predicates = parameterAsEnums( parameters, u
"PREDICATE"_s, context );
318 QgsJoinByLocationAlgorithm::sortPredicates( predicates );
322 const double step = baseSource->featureCount() > 0 ? 100.0 /
static_cast<double>( baseSource->featureCount() ) : 1;
331 if ( !discardNonMatching )
337 outputAttributes.append( nonMatchingJoinAttributes );
347 std::unique_ptr<QgsGeometryEngine> engine;
348 QVector<QVector<QVariant>> values;
365 engine->prepareGeometry();
368 if ( QgsJoinByLocationAlgorithm::featureFilter( testJoinFeature, engine.get(),
true, predicates ) )
371 joinAttributes.reserve( joinFieldIndices.size() );
372 for (
int joinIndex : std::as_const( joinFieldIndices ) )
374 joinAttributes.append( testJoinFeature.
attribute( joinIndex ) );
376 values.append( joinAttributes );
381 feedback->
setProgress(
static_cast<double>( i ) * step );
386 if ( values.empty() )
388 if ( discardNonMatching )
398 outputAttributes.append( nonMatchingJoinAttributes );
410 outputAttributes.reserve( outputFields.
size() );
411 for (
int fieldIndex = 0; fieldIndex < joinFieldIndices.size(); ++fieldIndex )
413 const FieldType &fieldType = fieldTypes.at( fieldIndex );
416 case FieldType::Numeric:
419 for (
const QVector<QVariant> &value : std::as_const( values ) )
424 for (
const FieldStatistic &statistic : sNumericStats )
426 if ( summaries.contains( statistic.enumIndex ) )
429 switch ( statistic.enumIndex )
474 if ( val.isValid() && std::isnan( val.toDouble() ) )
476 outputAttributes.append( val );
482 case FieldType::DateTime:
485 QVariantList inputValues;
486 inputValues.reserve( values.size() );
487 for (
const QVector<QVariant> &value : std::as_const( values ) )
489 inputValues << value.at( fieldIndex );
492 for (
const FieldStatistic &statistic : sDateTimeStats )
494 if ( summaries.contains( statistic.enumIndex ) )
497 switch ( statistic.enumIndex )
518 outputAttributes.append( val );
524 case FieldType::String:
527 QVariantList inputValues;
528 inputValues.reserve( values.size() );
529 for (
const QVector<QVariant> &value : std::as_const( values ) )
531 if ( value.at( fieldIndex ).isNull() )
534 stat.
addString( value.at( fieldIndex ).toString() );
537 for (
const FieldStatistic &statistic : sStringStats )
539 if ( summaries.contains( statistic.enumIndex ) )
542 switch ( statistic.enumIndex )
572 outputAttributes.append( val );
593 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.