27using namespace Qt::StringLiterals;
31QString QgsFixGeometryGapAlgorithm::name()
const
33 return u
"fixgeometrygap"_s;
36QString QgsFixGeometryGapAlgorithm::displayName()
const
38 return QObject::tr(
"Fill gaps" );
41QString QgsFixGeometryGapAlgorithm::shortDescription()
const
43 return QObject::tr(
"Fills gaps detected with the \"Small gaps\" algorithm from the \"Check geometry\" section." );
46QStringList QgsFixGeometryGapAlgorithm::tags()
const
48 return QObject::tr(
"fix,fill,gap" ).split(
',' );
51QString QgsFixGeometryGapAlgorithm::group()
const
53 return QObject::tr(
"Fix geometry" );
56QString QgsFixGeometryGapAlgorithm::groupId()
const
58 return u
"fixgeometry"_s;
61QString QgsFixGeometryGapAlgorithm::shortHelpString()
const
63 return QObject::tr(
"This algorithm fills the gaps based on a gap and neighbors layer from the \"Small gaps\" algorithm in the \"Check geometry\" section.\n\n"
64 "3 different fixing methods are available, which will give different results." );
67QgsFixGeometryGapAlgorithm *QgsFixGeometryGapAlgorithm::createInstance()
const
69 return new QgsFixGeometryGapAlgorithm();
72void QgsFixGeometryGapAlgorithm::initAlgorithm(
const QVariantMap &configuration )
74 Q_UNUSED( configuration )
90 checkMethods.cbegin(), checkMethods.cend() - 1, std::inserter( methods, methods.begin() ),
97 u
"UNIQUE_ID"_s, QObject::tr(
"Field of original feature unique identifier" ),
101 u
"ERROR_ID_IDX"_s, QObject::tr(
"Field of error id" ),
102 u
"gc_errorid"_s, u
"GAPS"_s,
113 auto tolerance = std::make_unique<QgsProcessingParameterNumber>(
117 tolerance->setHelp( QObject::tr(
"The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
118 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
119 addParameter( tolerance.release() );
124 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, u
"INPUT"_s, context ) );
128 const std::unique_ptr<QgsProcessingFeatureSource> neighbors( parameterAsSource( parameters, u
"NEIGHBORS"_s, context ) );
132 const std::unique_ptr<QgsProcessingFeatureSource> gaps( parameterAsSource( parameters, u
"GAPS"_s, context ) );
138 const QString featIdFieldName = parameterAsString( parameters, u
"UNIQUE_ID"_s, context );
139 const QString errorIdFieldName = parameterAsString( parameters, u
"ERROR_ID_IDX"_s, context );
142 int method = parameterAsEnum( parameters, u
"METHOD"_s, context );
159 if ( gaps->fields().indexFromName( errorIdFieldName ) == -1 )
160 throw QgsProcessingException( QObject::tr(
"Field \"%1\" does not exist in the gaps layer." ).arg( errorIdFieldName ) );
161 if ( neighbors->fields().indexFromName( featIdFieldName ) == -1 )
162 throw QgsProcessingException( QObject::tr(
"Field \"%1\" does not exist in the neighbors layer." ).arg( featIdFieldName ) );
163 const int inputIdFieldIndex = input->fields().indexFromName( featIdFieldName );
164 if ( inputIdFieldIndex == -1 )
165 throw QgsProcessingException( QObject::tr(
"Field \"%1\" does not exist in input layer." ).arg( featIdFieldName ) );
167 const QgsField inputFeatIdField = input->fields().at( inputIdFieldIndex );
168 const QMetaType::Type inputFeatIdFieldType = inputFeatIdField.
type();
169 if ( inputFeatIdFieldType != neighbors->fields().at( neighbors->fields().indexFromName( featIdFieldName ) ).type() )
170 throw QgsProcessingException( QObject::tr(
"Field \"%1\" does not have the same type as in the neighbors layer." ).arg( featIdFieldName ) );
173 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink(
174 parameters, u
"OUTPUT"_s, context, dest_output, input->fields(), input->wkbType(), input->sourceCrs()
181 reportFields.
append(
QgsField( u
"report"_s, QMetaType::QString ) );
182 reportFields.
append(
QgsField( u
"error_fixed"_s, QMetaType::Bool ) );
183 const std::unique_ptr<QgsFeatureSink> sink_report( parameterAsSink(
184 parameters, u
"REPORT"_s, context, dest_report, reportFields,
Qgis::WkbType::Point, gaps->sourceCrs()
193 multiStepFeedback.setCurrentStep( 1 );
194 multiStepFeedback.setProgressText( QObject::tr(
"Preparing features..." ) );
195 std::unique_ptr<QgsVectorLayer> fixedLayer( input->materialize(
QgsFeatureRequest() ) );
197 QMap<QString, QgsFeaturePool *> featurePools;
198 featurePools.insert( fixedLayer->id(), &featurePool );
204 fixedLayer->startEditing();
211 long long progression = 0;
212 long long totalProgression = gaps->featureCount();
213 multiStepFeedback.setCurrentStep( 2 );
214 multiStepFeedback.setProgressText( QObject::tr(
"Fixing errors..." ) );
221 multiStepFeedback.setProgress(
static_cast<double>(
static_cast<long double>( progression ) / totalProgression ) * 100 );
224 QVariant gapId = gapFeature.
attribute( errorIdFieldName );
225 if ( !gapId.isValid() || gapId.isNull() )
226 throw QgsProcessingException( QObject::tr(
"NULL or invalid value found in field \"%1\"" ).arg( errorIdFieldName ) );
231 const QString errorIdValue = gapFeature.
attribute( errorIdFieldName ).toString();
235 QString neighborIdValue = f.
attribute( featIdFieldName ).toString();
236 if ( inputFeatIdFieldType == QMetaType::QString )
237 neighborIdValue =
"'" + neighborIdValue +
"'";
239 if ( fixedLayer->getFeatures(
QgsFeatureRequest().setFilterExpression(
"\"" + featIdFieldName +
"\" = " + neighborIdValue ) ).nextFeature( neighborFeature ) )
240 neighborIds << neighborFeature.
id();
243 QMap<QString, QgsFeatureIds> neighborsMap;
244 neighborsMap.insert( fixedLayer->id(), neighborIds );
256 check.fixError( featurePools, &gapError, method, QMap<QString, int>(), changes );
260 resolutionMessage = QObject::tr(
"Error is obsolete" );
267 multiStepFeedback.setProgress( 100 );
271 if ( !fixedLayer->commitChanges() )
277 totalProgression = fixedLayer->featureCount();
278 multiStepFeedback.setCurrentStep( 2 );
279 multiStepFeedback.setProgressText( QObject::tr(
"Exporting fixed layer..." ) );
282 while ( fixedFeaturesIt.
nextFeature( fixedFeature ) )
288 multiStepFeedback.setProgress(
static_cast<double>(
static_cast<long double>( progression ) / totalProgression ) * 100 );
292 multiStepFeedback.setProgress( 100 );
295 outputs.insert( u
"OUTPUT"_s, dest_output );
296 outputs.insert( u
"REPORT"_s, dest_report );
303 mTolerance = parameterAsInt( parameters, u
"TOLERANCE"_s, context );
@ Vector
Tables (i.e. vector layers with or without geometry). When used for a sink this indicates the sink ha...
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
@ Numeric
Accepts numeric fields.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
@ RequiresProject
The algorithm requires that a valid QgsProject is available from the processing context in order to e...
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
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).
@ 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 setFields(const QgsFields &fields, bool initAttributes=false)
Assigns a field map with the feature to allow attribute access by attribute name.
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Base configuration for geometry checks.
@ StatusFixed
The error is fixed.
@ StatusObsolete
The error is obsolete because of other modifications.
Status status() const
The status of the error.
QString resolutionMessage() const
A message with details, how the error has been resolved.
Implements a resolution for problems detected in geometry checks.
QMap< QString, QMap< QgsFeatureId, QList< QgsGeometryCheck::Change > > > Changes
A collection of changes.
An error produced by a QgsGeometryGapCheck.
Checks for gaps between neighbouring polygons.
QList< QgsGeometryCheckResolutionMethod > availableResolutionMethods() const override
Returns a list of available resolution methods.
@ CreateNewFeature
Create a new feature with the gap geometry.
@ MergeLongestEdge
Merge the gap with the polygon with the longest shared edge.
@ MergeLargestArea
Merge with neighbouring polygon with largest area.
QgsGeometry centroid() const
Returns the center of mass of a geometry.
virtual Qgis::ProcessingAlgorithmFlags flags() const
Returns the flags indicating how and when the algorithm operates and should be exposed to users.
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QgsProject * project() const
Returns the project in which the algorithm is being executed.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
Processing feedback object for multi-step operations.
An enum based parameter for processing algorithms, allowing for selection from predefined values.
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.
void removeMapLayer(const QString &layerId)
Remove a layer from the registry by layer ID.
QgsMapLayer * addMapLayer(QgsMapLayer *mapLayer, bool addToLegend=true, bool takeOwnership=true)
Add a layer to the map of loaded layers.
A rectangle specified with double values.
A feature pool based on a vector data provider.
QSet< QgsFeatureId > QgsFeatureIds