QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmcheckgeometrymissingvertex.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmcheckgeometrymissingvertex.cpp
3 ---------------------
4 begin : February 2024
5 copyright : (C) 2024 by Jacky Volpes
6 email : jacky dot volpes at oslandia dot com
7***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 ***************************************************************************/
17
22#include "qgspoint.h"
23#include "qgsvectorlayer.h"
25
27
28QString QgsGeometryCheckMissingVertexAlgorithm::name() const
29{
30 return QStringLiteral( "checkgeometrymissingvertex" );
31}
32
33QString QgsGeometryCheckMissingVertexAlgorithm::displayName() const
34{
35 return QObject::tr( "Missing vertices along borders" );
36}
37
38QString QgsGeometryCheckMissingVertexAlgorithm::shortDescription() const
39{
40 return QObject::tr( "Detects missing vertices along polygon borders for topology compliance." );
41}
42
43QStringList QgsGeometryCheckMissingVertexAlgorithm::tags() const
44{
45 return QObject::tr( "check,geometry,missing,vertex" ).split( ',' );
46}
47
48QString QgsGeometryCheckMissingVertexAlgorithm::group() const
49{
50 return QObject::tr( "Check geometry" );
51}
52
53QString QgsGeometryCheckMissingVertexAlgorithm::groupId() const
54{
55 return QStringLiteral( "checkgeometry" );
56}
57
58QString QgsGeometryCheckMissingVertexAlgorithm::shortHelpString() const
59{
60 return QObject::tr( "This algorithm checks for missing vertices along polygon borders.\n"
61 "To be topologically correct, a vertex at the junction of two polygons must be present on both polygons. "
62 "Missing vertices are errors." );
63}
64
65Qgis::ProcessingAlgorithmFlags QgsGeometryCheckMissingVertexAlgorithm::flags() const
66{
68}
69
70QgsGeometryCheckMissingVertexAlgorithm *QgsGeometryCheckMissingVertexAlgorithm::createInstance() const
71{
72 return new QgsGeometryCheckMissingVertexAlgorithm();
73}
74
75void QgsGeometryCheckMissingVertexAlgorithm::initAlgorithm( const QVariantMap &configuration )
76{
77 Q_UNUSED( configuration )
78
79 // inputs
80 addParameter(
82 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ),
83 QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
84 )
85 );
86 addParameter( new QgsProcessingParameterField(
87 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Unique feature identifier" ), QString(), QStringLiteral( "INPUT" )
88 ) );
89
90 // outputs
91 addParameter( new QgsProcessingParameterFeatureSink(
92 QStringLiteral( "ERRORS" ), QObject::tr( "Missing vertices errors" ), Qgis::ProcessingSourceType::VectorPoint
93 ) );
94 addParameter( new QgsProcessingParameterFeatureSink(
95 QStringLiteral( "OUTPUT" ), QObject::tr( "Missing vertices features" ), Qgis::ProcessingSourceType::VectorPolygon, QVariant(), true, false
96 ) );
97
98 std::unique_ptr<QgsProcessingParameterNumber> tolerance = std::make_unique<QgsProcessingParameterNumber>(
99 QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
100 );
101 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
102 tolerance->setHelp( QObject::tr( "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
103 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
104 addParameter( tolerance.release() );
105}
106
107bool QgsGeometryCheckMissingVertexAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
108{
109 mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );
110
111 return true;
112}
113
114QgsFields QgsGeometryCheckMissingVertexAlgorithm::outputFields()
115{
116 QgsFields fields;
117 fields.append( QgsField( QStringLiteral( "gc_layerid" ), QMetaType::QString ) );
118 fields.append( QgsField( QStringLiteral( "gc_layername" ), QMetaType::QString ) );
119 fields.append( QgsField( QStringLiteral( "gc_partidx" ), QMetaType::Int ) );
120 fields.append( QgsField( QStringLiteral( "gc_ringidx" ), QMetaType::Int ) );
121 fields.append( QgsField( QStringLiteral( "gc_vertidx" ), QMetaType::Int ) );
122 fields.append( QgsField( QStringLiteral( "gc_errorx" ), QMetaType::Double ) );
123 fields.append( QgsField( QStringLiteral( "gc_errory" ), QMetaType::Double ) );
124 fields.append( QgsField( QStringLiteral( "gc_error" ), QMetaType::QString ) );
125 return fields;
126}
127
128QVariantMap QgsGeometryCheckMissingVertexAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
129{
130 QString dest_output;
131 QString dest_errors;
132 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
133 if ( !input )
134 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
135
136 QString uniqueIdFieldName( parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context ) );
137 int uniqueIdFieldIdx = input->fields().indexFromName( uniqueIdFieldName );
138 if ( uniqueIdFieldIdx == -1 )
139 throw QgsProcessingException( QObject::tr( "Missing field %1 in input layer" ).arg( uniqueIdFieldName ) );
140
141 const QgsField uniqueIdField = input->fields().at( uniqueIdFieldIdx );
142
143 QgsFields fields = outputFields();
144 fields.append( uniqueIdField );
145
146 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest_output, fields, input->wkbType(), input->sourceCrs() ) );
147
148 const std::unique_ptr<QgsFeatureSink> sink_errors( parameterAsSink( parameters, QStringLiteral( "ERRORS" ), context, dest_errors, fields, Qgis::WkbType::Point, input->sourceCrs() ) );
149 if ( !sink_errors )
150 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "ERRORS" ) ) );
151
152 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
153
154 QgsProject *project = QgsProject::instance();
155
156 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), project->transformContext(), project );
157
158 // Test detection
159 QList<QgsGeometryCheckError *> checkErrors;
160 QStringList messages;
161
162 const QgsGeometryMissingVertexCheck check( &checkContext, QVariantMap() );
163
164 multiStepFeedback.setCurrentStep( 1 );
165 feedback->setProgressText( QObject::tr( "Preparing features…" ) );
166 QMap<QString, QgsFeaturePool *> featurePools;
167 std::unique_ptr<QgsVectorLayer> inputLayer( input->materialize( QgsFeatureRequest() ) );
169 featurePools.insert( inputLayer->id(), &featurePool );
170
171 multiStepFeedback.setCurrentStep( 2 );
172 feedback->setProgressText( QObject::tr( "Collecting errors…" ) );
173 check.collectErrors( featurePools, checkErrors, messages, feedback );
174
175 multiStepFeedback.setCurrentStep( 3 );
176 feedback->setProgressText( QObject::tr( "Exporting errors…" ) );
177 const double step { checkErrors.size() > 0 ? 100.0 / checkErrors.size() : 1 };
178 long i = 0;
179 feedback->setProgress( 0.0 );
180
181 for ( const QgsGeometryCheckError *error : checkErrors )
182 {
183 if ( feedback->isCanceled() )
184 {
185 break;
186 }
187 QgsFeature f;
188 QgsAttributes attrs = f.attributes();
189
190 attrs << error->layerId()
191 << inputLayer->name()
192 << error->vidx().part
193 << error->vidx().ring
194 << error->vidx().vertex
195 << error->location().x()
196 << error->location().y()
197 << error->value().toString()
198 << inputLayer->getFeature( error->featureId() ).attribute( uniqueIdField.name() );
199 f.setAttributes( attrs );
200
201 f.setGeometry( error->geometry() );
202 if ( sink_output && !sink_output->addFeature( f, QgsFeatureSink::FastInsert ) )
203 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
204
205 f.setGeometry( QgsGeometry::fromPoint( QgsPoint( error->location().x(), error->location().y() ) ) );
206 if ( !sink_errors->addFeature( f, QgsFeatureSink::FastInsert ) )
207 throw QgsProcessingException( writeFeatureError( sink_errors.get(), parameters, QStringLiteral( "ERRORS" ) ) );
208
209 i++;
210 feedback->setProgress( 100.0 * step * static_cast<double>( i ) );
211 }
212
213 // cleanup memory of the pointed data
214 for ( const QgsGeometryCheckError *error : checkErrors )
215 {
216 delete error;
217 }
218
219 QVariantMap outputs;
220 if ( sink_output )
221 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
222 outputs.insert( QStringLiteral( "ERRORS" ), dest_errors );
223
224 return outputs;
225}
226
@ VectorPoint
Vector point layers.
@ VectorPolygon
Vector polygon layers.
QFlags< ProcessingAlgorithmFlag > ProcessingAlgorithmFlags
Flags indicating how and when an algorithm operates and should be exposed to users.
Definition qgis.h:3476
@ NoThreading
Algorithm is not thread safe and cannot be run in a background thread, e.g. for algorithms which mani...
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
A vector of attributes.
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...
Definition qgsfeature.h:58
QgsAttributes attributes
Definition qgsfeature.h:67
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
QString name
Definition qgsfield.h:62
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:70
Base configuration for geometry checks.
This represents an error reported by a geometry check.
A topology check for missing vertices.
static QgsGeometry fromPoint(const QgsPoint &point)
Creates a new geometry from a QgsPoint object.
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
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.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void setProgressText(const QString &text)
Sets a progress report text string.
Processing feedback object for multi-step operations.
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.
Encapsulates a QGIS project, including sets of map layers and their styles, layouts,...
Definition qgsproject.h:107
static QgsProject * instance()
Returns the QgsProject singleton instance.
QgsCoordinateTransformContext transformContext
Definition qgsproject.h:113
A feature pool based on a vector data provider.