QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
qgsalgorithmcheckgeometryarea.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmcheckgeometryarea.cpp
3 ---------------------
4 begin : November 2023
5 copyright : (C) 2023 by Loïc Bartoletti
6 email : loic dot bartoletti 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 QgsGeometryCheckAreaAlgorithm::name() const
29{
30 return QStringLiteral( "checkgeometryarea" );
31}
32
33QString QgsGeometryCheckAreaAlgorithm::displayName() const
34{
35 return QObject::tr( "Small polygons" );
36}
37
38QString QgsGeometryCheckAreaAlgorithm::shortDescription() const
39{
40 return QObject::tr( "Detects polygons smaller than a given area." );
41}
42
43QStringList QgsGeometryCheckAreaAlgorithm::tags() const
44{
45 return QObject::tr( "check,geometry,area" ).split( ',' );
46}
47
48QString QgsGeometryCheckAreaAlgorithm::group() const
49{
50 return QObject::tr( "Check geometry" );
51}
52
53QString QgsGeometryCheckAreaAlgorithm::groupId() const
54{
55 return QStringLiteral( "checkgeometry" );
56}
57
58QString QgsGeometryCheckAreaAlgorithm::shortHelpString() const
59{
60 return QObject::tr( "This algorithm checks the areas of polygon geometries.\n"
61 "Areas below the area threshold are errors." );
62}
63
64Qgis::ProcessingAlgorithmFlags QgsGeometryCheckAreaAlgorithm::flags() const
65{
67}
68
69QgsGeometryCheckAreaAlgorithm *QgsGeometryCheckAreaAlgorithm::createInstance() const
70{
71 return new QgsGeometryCheckAreaAlgorithm();
72}
73
74void QgsGeometryCheckAreaAlgorithm::initAlgorithm( const QVariantMap &configuration )
75{
76 Q_UNUSED( configuration )
77
78 // inputs
79 addParameter(
81 QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ),
82 QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
83 )
84 );
85 addParameter( new QgsProcessingParameterField(
86 QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Unique feature identifier" ), QString(), QStringLiteral( "INPUT" )
87 ) );
88 addParameter( new QgsProcessingParameterNumber(
89 QStringLiteral( "AREATHRESHOLD" ), QObject::tr( "Area threshold" ), Qgis::ProcessingNumberParameterType::Double, 0, false, 0.0
90 ) );
91
92 // outputs
93 addParameter( new QgsProcessingParameterFeatureSink(
94 QStringLiteral( "ERRORS" ), QObject::tr( "Small polygons errors" ), Qgis::ProcessingSourceType::VectorPoint
95 ) );
96 addParameter( new QgsProcessingParameterFeatureSink(
97 QStringLiteral( "OUTPUT" ), QObject::tr( "Small polygons features" ), Qgis::ProcessingSourceType::VectorPolygon, QVariant(), true, false
98 ) );
99
100 std::unique_ptr<QgsProcessingParameterNumber> tolerance = std::make_unique<QgsProcessingParameterNumber>(
101 QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13
102 );
103 tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
104 tolerance->setHelp( QObject::tr( "The \"Tolerance\" advanced parameter defines the numerical precision of geometric operations, "
105 "given as an integer n, meaning that any difference smaller than 10⁻ⁿ (in map units) is considered zero." ) );
106 addParameter( tolerance.release() );
107}
108
109bool QgsGeometryCheckAreaAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
110{
111 mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );
112 return true;
113}
114
115QgsFields QgsGeometryCheckAreaAlgorithm::outputFields()
116{
117 QgsFields fields;
118 fields.append( QgsField( QStringLiteral( "gc_layerid" ), QMetaType::QString ) );
119 fields.append( QgsField( QStringLiteral( "gc_layername" ), QMetaType::QString ) );
120 fields.append( QgsField( QStringLiteral( "gc_partidx" ), QMetaType::Int ) );
121 fields.append( QgsField( QStringLiteral( "gc_ringidx" ), QMetaType::Int ) );
122 fields.append( QgsField( QStringLiteral( "gc_vertidx" ), QMetaType::Int ) );
123 fields.append( QgsField( QStringLiteral( "gc_errorx" ), QMetaType::Double ) );
124 fields.append( QgsField( QStringLiteral( "gc_errory" ), QMetaType::Double ) );
125 fields.append( QgsField( QStringLiteral( "gc_error" ), QMetaType::QString ) );
126 return fields;
127}
128
129QVariantMap QgsGeometryCheckAreaAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
130{
131 QString dest_output;
132 QString dest_errors;
133 const std::unique_ptr<QgsProcessingFeatureSource> input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
134 if ( !input )
135 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
136
137 QString uniqueIdFieldName( parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context ) );
138 int uniqueIdFieldIdx = input->fields().indexFromName( uniqueIdFieldName );
139 if ( uniqueIdFieldIdx == -1 )
140 throw QgsProcessingException( QObject::tr( "Missing field %1 in input layer" ).arg( uniqueIdFieldName ) );
141
142 const QgsField uniqueIdField = input->fields().at( uniqueIdFieldIdx );
143
144 QgsFields fields = outputFields();
145 fields.append( uniqueIdField );
146
147 const std::unique_ptr<QgsFeatureSink> sink_output( parameterAsSink(
148 parameters, QStringLiteral( "OUTPUT" ), context, dest_output, fields, input->wkbType(), input->sourceCrs()
149 ) );
150
151 const std::unique_ptr<QgsFeatureSink> sink_errors( parameterAsSink(
152 parameters, QStringLiteral( "ERRORS" ), context, dest_errors, fields, Qgis::WkbType::Point, input->sourceCrs()
153 ) );
154 if ( !sink_errors )
155 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "ERRORS" ) ) );
156
157 QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback );
158
159 QgsProject *project = QgsProject::instance();
160
161 QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), project->transformContext(), project );
162
163 // Test detection
164 QList<QgsGeometryCheckError *> checkErrors;
165 QStringList messages;
166
167 const double areaThreshold = parameterAsDouble( parameters, QStringLiteral( "AREATHRESHOLD" ), context );
168
169 QVariantMap configurationCheck;
170 configurationCheck.insert( "areaThreshold", areaThreshold );
171 const QgsGeometryAreaCheck check( &checkContext, configurationCheck );
172
173 multiStepFeedback.setCurrentStep( 1 );
174 feedback->setProgressText( QObject::tr( "Preparing features…" ) );
175 QMap<QString, QgsFeaturePool *> featurePools;
176
177 std::unique_ptr<QgsVectorLayer> inputLayer( input->materialize( QgsFeatureRequest() ) );
179 featurePools.insert( inputLayer->id(), &featurePool );
180
181 multiStepFeedback.setCurrentStep( 2 );
182 feedback->setProgressText( QObject::tr( "Collecting errors…" ) );
183 check.collectErrors( featurePools, checkErrors, messages, feedback );
184
185 multiStepFeedback.setCurrentStep( 3 );
186 feedback->setProgressText( QObject::tr( "Exporting errors…" ) );
187 const double step { checkErrors.size() > 0 ? 100.0 / checkErrors.size() : 1 };
188 long i = 0;
189 feedback->setProgress( 0.0 );
190
191 for ( const QgsGeometryCheckError *error : checkErrors )
192 {
193 if ( feedback->isCanceled() )
194 {
195 break;
196 }
197 QgsFeature f;
198 QgsAttributes attrs = f.attributes();
199
200 attrs << error->layerId()
201 << inputLayer->name()
202 << error->vidx().part
203 << error->vidx().ring
204 << error->vidx().vertex
205 << error->location().x()
206 << error->location().y()
207 << error->value().toString()
208 << inputLayer->getFeature( error->featureId() ).attribute( uniqueIdField.name() );
209 f.setAttributes( attrs );
210
211 f.setGeometry( error->geometry() );
212 if ( sink_output && !sink_output->addFeature( f, QgsFeatureSink::FastInsert ) )
213 throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
214
215 f.setGeometry( QgsGeometry::fromPoint( QgsPoint( error->location().x(), error->location().y() ) ) );
216 if ( !sink_errors->addFeature( f, QgsFeatureSink::FastInsert ) )
217 throw QgsProcessingException( writeFeatureError( sink_errors.get(), parameters, QStringLiteral( "ERRORS" ) ) );
218
219 i++;
220 feedback->setProgress( 100.0 * step * static_cast<double>( i ) );
221 }
222
223 // cleanup memory of the pointed data
224 for ( const QgsGeometryCheckError *error : checkErrors )
225 {
226 delete error;
227 }
228
229 QVariantMap outputs;
230 if ( sink_output )
231 outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
232 outputs.insert( QStringLiteral( "ERRORS" ), dest_errors );
233
234 return outputs;
235}
236
@ 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.
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.
A numeric 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.