25using namespace Qt::StringLiterals;
29QString QgsDetectVectorChangesAlgorithm::name()
const
31 return u
"detectvectorchanges"_s;
34QString QgsDetectVectorChangesAlgorithm::displayName()
const
36 return QObject::tr(
"Detect dataset changes" );
39QStringList QgsDetectVectorChangesAlgorithm::tags()
const
41 return QObject::tr(
"added,dropped,new,deleted,features,geometries,difference,delta,revised,original,version" ).split(
',' );
44QString QgsDetectVectorChangesAlgorithm::group()
const
46 return QObject::tr(
"Vector general" );
49QString QgsDetectVectorChangesAlgorithm::groupId()
const
51 return u
"vectorgeneral"_s;
54void QgsDetectVectorChangesAlgorithm::initAlgorithm(
const QVariantMap & )
59 auto compareAttributesParam = std::make_unique<QgsProcessingParameterField>( u
"COMPARE_ATTRIBUTES"_s, QObject::tr(
"Attributes to consider for match (or none to compare geometry only)" ), QVariant(), u
"ORIGINAL"_s,
Qgis::ProcessingFieldParameterDataType::Any,
true,
true );
60 compareAttributesParam->setDefaultToAllFields(
true );
61 addParameter( compareAttributesParam.release() );
63 std::unique_ptr<QgsProcessingParameterDefinition> matchTypeParam = std::make_unique<QgsProcessingParameterEnum>( u
"MATCH_TYPE"_s, QObject::tr(
"Geometry comparison behavior" ), QStringList() << QObject::tr(
"Exact Match" ) << QObject::tr(
"Tolerant Match (Topological Equality)" ),
false, 1 );
65 addParameter( matchTypeParam.release() );
72 addOutput(
new QgsProcessingOutputNumber( u
"ADDED_COUNT"_s, QObject::tr(
"Count of features added in revised layer" ) ) );
73 addOutput(
new QgsProcessingOutputNumber( u
"DELETED_COUNT"_s, QObject::tr(
"Count of features deleted from original layer" ) ) );
76QString QgsDetectVectorChangesAlgorithm::shortHelpString()
const
78 return QObject::tr(
"This algorithm compares two vector layers, and determines which features are unchanged, added or deleted between "
79 "the two. It is designed for comparing two different versions of the same dataset.\n\n"
80 "When comparing features, the original and revised feature geometries will be compared against each other. Depending "
81 "on the Geometry Comparison Behavior setting, the comparison will either be made using an exact comparison (where "
82 "geometries must be an exact match for each other, including the order and count of vertices) or a topological "
83 "comparison only (where geometries are considered equal if all of their component edges overlap. E.g. "
84 "lines with the same vertex locations but opposite direction will be considered equal by this method). If the topological "
85 "comparison is selected then any z or m values present in the geometries will not be compared.\n\n"
86 "By default, the algorithm compares all attributes from the original and revised features. If the Attributes to Consider for Match "
87 "parameter is changed, then only the selected attributes will be compared (e.g. allowing users to ignore a timestamp or ID field "
88 "which is expected to change between the revisions).\n\n"
89 "If any features in the original or revised layers do not have an associated geometry, then care must be taken to ensure "
90 "that these features have a unique set of attributes selected for comparison. If this condition is not met, warnings will be "
91 "raised and the resultant outputs may be misleading.\n\n"
92 "The algorithm outputs three layers, one containing all features which are considered to be unchanged between the revisions, "
93 "one containing features deleted from the original layer which are not present in the revised layer, and one containing features "
94 "added to the revised layer which are not present in the original layer." );
97QString QgsDetectVectorChangesAlgorithm::shortDescription()
const
99 return QObject::tr(
"Calculates features which are unchanged, added or deleted between two dataset versions." );
102QgsDetectVectorChangesAlgorithm *QgsDetectVectorChangesAlgorithm::createInstance()
const
104 return new QgsDetectVectorChangesAlgorithm();
109 mOriginal.reset( parameterAsSource( parameters, u
"ORIGINAL"_s, context ) );
113 mRevised.reset( parameterAsSource( parameters, u
"REVISED"_s, context ) );
117 mMatchType =
static_cast<GeometryMatchType
>( parameterAsEnum( parameters, u
"MATCH_TYPE"_s, context ) );
119 switch ( mMatchType )
122 if ( mOriginal->wkbType() != mRevised->wkbType() )
132 if ( mOriginal->sourceCrs() != mRevised->sourceCrs() )
133 feedback->
reportError( QObject::tr(
"CRS for revised layer (%1) does not match the original layer (%2) - reprojection accuracy may affect geometry matching" ).arg( mOriginal->sourceCrs().userFriendlyIdentifier(), mRevised->sourceCrs().userFriendlyIdentifier() ),
false );
135 mFieldsToCompare = parameterAsStrings( parameters, u
"COMPARE_ATTRIBUTES"_s, context );
136 mOriginalFieldsToCompareIndices.reserve( mFieldsToCompare.size() );
137 mRevisedFieldsToCompareIndices.reserve( mFieldsToCompare.size() );
138 QStringList missingOriginalFields;
139 QStringList missingRevisedFields;
140 for (
const QString &field : mFieldsToCompare )
142 const int originalIndex = mOriginal->fields().lookupField( field );
143 mOriginalFieldsToCompareIndices.append( originalIndex );
144 if ( originalIndex < 0 )
145 missingOriginalFields << field;
147 const int revisedIndex = mRevised->fields().lookupField( field );
148 if ( revisedIndex < 0 )
149 missingRevisedFields << field;
150 mRevisedFieldsToCompareIndices.append( revisedIndex );
153 if ( !missingOriginalFields.empty() )
154 throw QgsProcessingException( QObject::tr(
"Original layer missing selected comparison attributes: %1" ).arg( missingOriginalFields.join(
',' ) ) );
155 if ( !missingRevisedFields.empty() )
156 throw QgsProcessingException( QObject::tr(
"Revised layer missing selected comparison attributes: %1" ).arg( missingRevisedFields.join(
',' ) ) );
163 QString unchangedDestId;
164 std::unique_ptr<QgsFeatureSink> unchangedSink( parameterAsSink( parameters, u
"UNCHANGED"_s, context, unchangedDestId, mOriginal->fields(), mOriginal->wkbType(), mOriginal->sourceCrs() ) );
165 if ( !unchangedSink && parameters.value( u
"UNCHANGED"_s ).isValid() )
169 std::unique_ptr<QgsFeatureSink> addedSink( parameterAsSink( parameters, u
"ADDED"_s, context, addedDestId, mRevised->fields(), mRevised->wkbType(), mRevised->sourceCrs() ) );
170 if ( !addedSink && parameters.value( u
"ADDED"_s ).isValid() )
173 QString deletedDestId;
174 std::unique_ptr<QgsFeatureSink> deletedSink( parameterAsSink( parameters, u
"DELETED"_s, context, deletedDestId, mOriginal->fields(), mOriginal->wkbType(), mOriginal->sourceCrs() ) );
175 if ( !deletedSink && parameters.value( u
"DELETED"_s ).isValid() )
185 double step = mOriginal->featureCount() > 0 ? 100.0 / mOriginal->featureCount() : 0;
186 QHash<QgsFeatureId, QgsGeometry> originalGeometries;
187 QHash<QgsFeatureId, QgsAttributes> originalAttributes;
188 QHash<QgsAttributes, QgsFeatureId> originalNullGeometryAttributes;
192 attrs.resize( mFieldsToCompare.size() );
200 originalGeometries.insert( f.
id(), f.
geometry() );
203 if ( !mFieldsToCompare.empty() )
206 for (
const int field : mOriginalFieldsToCompareIndices )
210 originalAttributes.insert( f.
id(), attrs );
215 if ( originalNullGeometryAttributes.contains( attrs ) )
217 feedback->
reportError( QObject::tr(
"A non-unique set of comparison attributes was found for "
218 "one or more features without geometries - results may be misleading (features %1 and %2)" )
220 .arg( originalNullGeometryAttributes.value( attrs ) ) );
224 originalNullGeometryAttributes.insert( attrs, f.
id() );
234 QSet<QgsFeatureId> unchangedOriginalIds;
235 QSet<QgsFeatureId> addedRevisedIds;
240 step = mRevised->featureCount() > 0 ? 100.0 / mRevised->featureCount() : 0;
243 it = mRevised->getFeatures( revisedRequest );
251 for (
const int field : mRevisedFieldsToCompareIndices )
253 attrs[idx++] = revisedFeature.
attributes().at( field );
256 bool matched =
false;
260 if ( originalNullGeometryAttributes.contains( attrs ) )
263 unchangedOriginalIds.insert( originalNullGeometryAttributes.value( attrs ) );
270 const QList<QgsFeatureId> candidates = index.intersects( revisedFeature.
geometry().
boundingBox() );
277 if ( unchangedOriginalIds.contains( candidateId ) )
284 if ( !mFieldsToCompare.empty() )
286 if ( attrs != originalAttributes[candidateId] )
293 QgsGeometry original = originalGeometries.value( candidateId );
297 revised = revisedFeature.
geometry();
299 switch ( mMatchType )
315 bool geometryMatch =
false;
316 switch ( mMatchType )
325 geometryMatch = revised.
equals( original );
332 unchangedOriginalIds.insert( candidateId );
342 addedRevisedIds.insert( revisedFeature.
id() );
346 feedback->
setProgress( 0.70 * current * step + 10 );
352 step = mOriginal->featureCount() > 0 ? 100.0 / mOriginal->featureCount() : 0;
355 it = mOriginal->getFeatures( request );
367 if ( unchangedOriginalIds.contains( f.
id() ) )
388 feedback->
setProgress( 0.10 * current * step + 80 );
399 step = addedRevisedIds.size() > 0 ? 100.0 / addedRevisedIds.size() : 0;
400 it = mRevised->getFeatures(
QgsFeatureRequest().setFilterFids( addedRevisedIds ) );
412 feedback->
setProgress( 0.10 * current * step + 90 );
417 feedback->
pushInfo( QObject::tr(
"%n feature(s) unchanged",
nullptr, unchangedOriginalIds.size() ) );
418 feedback->
pushInfo( QObject::tr(
"%n feature(s) added",
nullptr, addedRevisedIds.size() ) );
419 feedback->
pushInfo( QObject::tr(
"%n feature(s) deleted",
nullptr, deleted ) );
422 unchangedSink->finalize();
424 addedSink->finalize();
426 deletedSink->finalize();
429 outputs.insert( u
"UNCHANGED"_s, unchangedDestId );
430 outputs.insert( u
"ADDED"_s, addedDestId );
431 outputs.insert( u
"DELETED"_s, deletedDestId );
432 outputs.insert( u
"UNCHANGED_COUNT"_s,
static_cast<long long>( unchangedOriginalIds.size() ) );
433 outputs.insert( u
"ADDED_COUNT"_s,
static_cast<long long>( addedRevisedIds.size() ) );
434 outputs.insert( u
"DELETED_COUNT"_s,
static_cast<long long>( deleted ) );
@ VectorAnyGeometry
Any vector layer with geometry.
@ NoGeometry
Geometry is not required. It may still be returned if e.g. required for a filter condition.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
virtual bool dropMValue()=0
Drops any measure values which exist in the geometry.
virtual bool dropZValue()=0
Drops any z-dimensions which exist in the geometry.
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 & setFlags(Qgis::FeatureRequestFlags flags)
Sets flags that affect how features will be fetched.
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.
@ 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...
bool hasGeometry() const
Returns true if the feature has an associated geometry.
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.
A geometry is the spatial representation of a feature.
QgsAbstractGeometry * get()
Returns a modifiable (non-const) reference to the underlying abstract geometry primitive.
bool equals(const QgsGeometry &geometry) const
Test if this geometry is exactly equal to another geometry.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
bool isGeosEqual(const QgsGeometry &) const
Compares the geometry with another geometry using GEOS.
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 pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
virtual void reportError(const QString &error, bool fatalError=false)
Reports that the algorithm encountered an error while executing.
A numeric output for processing algorithms.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A spatial index for QgsFeature objects.
static Qgis::GeometryType geometryType(Qgis::WkbType type)
Returns the geometry type for a WKB type, e.g., both MultiPolygon and CurvePolygon would have a Polyg...
static Q_INVOKABLE QString displayString(Qgis::WkbType type)
Returns a non-translated display string type for a WKB type, e.g., the geometry name used in WKT geom...
static Q_INVOKABLE QString geometryDisplayString(Qgis::GeometryType type)
Returns a display string for a geometry type.
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features