From ad5c40d149b016fa970441e24f4024e5e772089f Mon Sep 17 00:00:00 2001 From: Jacky Volpes Date: Wed, 16 Apr 2025 11:51:16 +0200 Subject: [PATCH] Processing: Add Check Geometry Algorithm and test: Overlap --- src/analysis/CMakeLists.txt | 1 + .../qgsalgorithmcheckgeometryoverlap.cpp | 229 ++++++++++++++++++ .../qgsalgorithmcheckgeometryoverlap.h | 53 ++++ .../processing/qgsnativealgorithms.cpp | 2 + .../testqgsprocessingcheckgeometry.cpp | 32 +++ 5 files changed, 317 insertions(+) create mode 100644 src/analysis/processing/qgsalgorithmcheckgeometryoverlap.cpp create mode 100644 src/analysis/processing/qgsalgorithmcheckgeometryoverlap.h diff --git a/src/analysis/CMakeLists.txt b/src/analysis/CMakeLists.txt index 5a8f32df8d9..b92bab7e0a3 100644 --- a/src/analysis/CMakeLists.txt +++ b/src/analysis/CMakeLists.txt @@ -69,6 +69,7 @@ set(QGIS_ANALYSIS_SRCS processing/qgsalgorithmfixgeometrymissingvertex.cpp processing/qgsalgorithmcheckgeometryarea.cpp processing/qgsalgorithmfixgeometryarea.cpp + processing/qgsalgorithmcheckgeometryoverlap.cpp processing/qgsalgorithmclip.cpp processing/qgsalgorithmconcavehull.cpp processing/qgsalgorithmconditionalbranch.cpp diff --git a/src/analysis/processing/qgsalgorithmcheckgeometryoverlap.cpp b/src/analysis/processing/qgsalgorithmcheckgeometryoverlap.cpp new file mode 100644 index 00000000000..7b4cee62391 --- /dev/null +++ b/src/analysis/processing/qgsalgorithmcheckgeometryoverlap.cpp @@ -0,0 +1,229 @@ +/*************************************************************************** + qgsalgorithmcheckgeometryoverlap.cpp + --------------------- + begin : April 2025 + copyright : (C) 2025 by Jacky Volpes + email : jacky dot volpes at oslandia dot com +***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgsalgorithmcheckgeometryoverlap.h" +#include "qgsgeometrycheckcontext.h" +#include "qgsgeometrycheckerror.h" +#include "qgsgeometryoverlapcheck.h" +#include "qgspoint.h" +#include "qgsvectorlayer.h" +#include "qgsvectordataproviderfeaturepool.h" + +///@cond PRIVATE + +QString QgsGeometryCheckOverlapAlgorithm::name() const +{ + return QStringLiteral( "checkgeometryoverlap" ); +} + +QString QgsGeometryCheckOverlapAlgorithm::displayName() const +{ + return QObject::tr( "Check Geometry (Overlap)" ); +} + +QStringList QgsGeometryCheckOverlapAlgorithm::tags() const +{ + return QObject::tr( "check,geometry,overlap" ).split( ',' ); +} + +QString QgsGeometryCheckOverlapAlgorithm::group() const +{ + return QObject::tr( "Check geometry" ); +} + +QString QgsGeometryCheckOverlapAlgorithm::groupId() const +{ + return QStringLiteral( "checkgeometry" ); +} + +QString QgsGeometryCheckOverlapAlgorithm::shortHelpString() const +{ + return QObject::tr( "This algorithm checks the overlapping areas.\n" + "Overlapping areas smaller than the minimum overlapping area are errors." ); +} + +Qgis::ProcessingAlgorithmFlags QgsGeometryCheckOverlapAlgorithm::flags() const +{ + return QgsProcessingAlgorithm::flags() | Qgis::ProcessingAlgorithmFlag::NoThreading; +} + +QgsGeometryCheckOverlapAlgorithm *QgsGeometryCheckOverlapAlgorithm::createInstance() const +{ + return new QgsGeometryCheckOverlapAlgorithm(); +} + +void QgsGeometryCheckOverlapAlgorithm::initAlgorithm( const QVariantMap &configuration ) +{ + Q_UNUSED( configuration ) + + addParameter( new QgsProcessingParameterFeatureSource( + QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList() << static_cast( Qgis::ProcessingSourceType::VectorPolygon ) + ) ); + addParameter( new QgsProcessingParameterField( + QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Unique feature identifier" ), QString(), QStringLiteral( "INPUT" ) + ) ); + addParameter( new QgsProcessingParameterFeatureSink( + QStringLiteral( "ERRORS" ), QObject::tr( "Errors layer" ), Qgis::ProcessingSourceType::VectorPoint + ) ); + addParameter( new QgsProcessingParameterFeatureSink( + QStringLiteral( "OUTPUT" ), QObject::tr( "Output layer" ), Qgis::ProcessingSourceType::VectorPolygon + ) ); + + addParameter( new QgsProcessingParameterNumber( + QStringLiteral( "MIN_OVERLAP_AREA" ), QObject::tr( "min overlap area" ), Qgis::ProcessingNumberParameterType::Double, 0, false, 0.0, 180.0 + ) ); + + std::unique_ptr tolerance = std::make_unique( + QStringLiteral( "TOLERANCE" ), QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13 + ); + tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced ); + addParameter( tolerance.release() ); +} + +bool QgsGeometryCheckOverlapAlgorithm::prepareAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback * ) +{ + mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context ); + + return true; +} + +QgsFields QgsGeometryCheckOverlapAlgorithm::outputFields() +{ + QgsFields fields; + fields.append( QgsField( QStringLiteral( "gc_layerid" ), QMetaType::QString ) ); + fields.append( QgsField( QStringLiteral( "gc_layername" ), QMetaType::QString ) ); + fields.append( QgsField( QStringLiteral( "gc_errorx" ), QMetaType::Double ) ); + fields.append( QgsField( QStringLiteral( "gc_errory" ), QMetaType::Double ) ); + fields.append( QgsField( QStringLiteral( "gc_error" ), QMetaType::Double ) ); + return fields; +} + + +QVariantMap QgsGeometryCheckOverlapAlgorithm::processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) +{ + QString dest_output; + QString dest_errors; + const std::unique_ptr input( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) ); + if ( !input ) + throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) ); + + QString uniqueIdFieldName( parameterAsString( parameters, QStringLiteral( "UNIQUE_ID" ), context ) ); + int uniqueIdFieldIdx = input->fields().indexFromName( uniqueIdFieldName ); + if ( uniqueIdFieldIdx == -1 ) + throw QgsProcessingException( QObject::tr( "Missing field %1 in input layer" ).arg( uniqueIdFieldName ) ); + + const QgsField uniqueIdField = input->fields().at( uniqueIdFieldIdx ); + QgsField overlapFeatureUniqueIdField = input->fields().at( uniqueIdFieldIdx ); + overlapFeatureUniqueIdField.setName( "gc_overlap_feature_" + uniqueIdField.name() ); + + QgsFields fields = outputFields(); + fields.append( uniqueIdField ); + fields.append( overlapFeatureUniqueIdField ); + + const std::unique_ptr sink_output( parameterAsSink( + parameters, QStringLiteral( "OUTPUT" ), context, dest_output, fields, input->wkbType(), input->sourceCrs() + ) ); + if ( !sink_output ) + throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) ); + + const std::unique_ptr sink_errors( parameterAsSink( + parameters, QStringLiteral( "ERRORS" ), context, dest_errors, fields, Qgis::WkbType::Point, input->sourceCrs() + ) ); + if ( !sink_errors ) + throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "ERRORS" ) ) ); + + QgsProcessingMultiStepFeedback multiStepFeedback( 3, feedback ); + + const QgsProject *project = QgsProject::instance(); + + QgsGeometryCheckContext checkContext = QgsGeometryCheckContext( mTolerance, input->sourceCrs(), project->transformContext(), project ); + + // Test detection + QList checkErrors; + QStringList messages; + + const double minOverlapArea = parameterAsDouble( parameters, QStringLiteral( "MIN_OVERLAP_AREA" ), context ); + + QVariantMap configurationCheck; + configurationCheck.insert( "maxOverlapArea", minOverlapArea ); + const QgsGeometryOverlapCheck check( &checkContext, configurationCheck ); + + multiStepFeedback.setCurrentStep( 1 ); + feedback->setProgressText( QObject::tr( "Preparing features…" ) ); + QMap checkerFeaturePools; + + std::unique_ptr inputLayer( input->materialize( QgsFeatureRequest() ) ); + QgsVectorDataProviderFeaturePool featurePool = QgsVectorDataProviderFeaturePool( inputLayer.get() ); + checkerFeaturePools.insert( inputLayer->id(), &featurePool ); + + multiStepFeedback.setCurrentStep( 2 ); + feedback->setProgressText( QObject::tr( "Collecting errors…" ) ); + check.collectErrors( checkerFeaturePools, checkErrors, messages, feedback ); + + multiStepFeedback.setCurrentStep( 3 ); + feedback->setProgressText( QObject::tr( "Exporting errors…" ) ); + const double step { checkErrors.size() > 0 ? 100.0 / checkErrors.size() : 1 }; + long i = 0; + feedback->setProgress( 0.0 ); + + for ( const QgsGeometryCheckError *error : checkErrors ) + { + const QgsGeometryOverlapCheckError *overlapError = dynamic_cast( error ); + if ( !overlapError ) + break; + if ( feedback->isCanceled() ) + break; + + QgsFeature f; + QgsAttributes attrs = f.attributes(); + + attrs << error->layerId() + << inputLayer->name() + << error->location().x() + << error->location().y() + << error->value().toDouble() + << inputLayer->getFeature( error->featureId() ).attribute( uniqueIdField.name() ) + << inputLayer->getFeature( overlapError->overlappedFeature().featureId() ).attribute( uniqueIdField.name() ); + f.setAttributes( attrs ); + + f.setGeometry( error->geometry() ); + if ( !sink_output->addFeature( f, QgsFeatureSink::FastInsert ) ) + throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) ); + + f.setGeometry( QgsGeometry::fromPoint( QgsPoint( error->location().x(), error->location().y() ) ) ); + if ( !sink_errors->addFeature( f, QgsFeatureSink::FastInsert ) ) + throw QgsProcessingException( writeFeatureError( sink_errors.get(), parameters, QStringLiteral( "ERRORS" ) ) ); + + i++; + feedback->setProgress( 100.0 * step * static_cast( i ) ); + } + + // Place the point layer above the polygon layer + if ( context.willLoadLayerOnCompletion( dest_output ) && context.willLoadLayerOnCompletion( dest_errors ) ) + { + context.layerToLoadOnCompletionDetails( dest_errors ).layerSortKey = 0; + context.layerToLoadOnCompletionDetails( dest_output ).layerSortKey = 1; + } + + QVariantMap outputs; + outputs.insert( QStringLiteral( "OUTPUT" ), dest_output ); + outputs.insert( QStringLiteral( "ERRORS" ), dest_errors ); + + return outputs; +} + +///@endcond diff --git a/src/analysis/processing/qgsalgorithmcheckgeometryoverlap.h b/src/analysis/processing/qgsalgorithmcheckgeometryoverlap.h new file mode 100644 index 00000000000..e027eebec86 --- /dev/null +++ b/src/analysis/processing/qgsalgorithmcheckgeometryoverlap.h @@ -0,0 +1,53 @@ +/*************************************************************************** + qgsalgorithmcheckgeometryoverlap.h + --------------------- + begin : April 2025 + copyright : (C) 2025 by Jacky Volpes + email : jacky dot volpes at oslandia dot com +***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#ifndef QGSALGORITHMCHECKGEOMETRYOVERLAP_H +#define QGSALGORITHMCHECKGEOMETRYOVERLAP_H + +#define SIP_NO_FILE + +#include "qgis_sip.h" +#include "qgsprocessingalgorithm.h" + +///@cond PRIVATE + +class QgsGeometryCheckOverlapAlgorithm : public QgsProcessingAlgorithm +{ + public: + QgsGeometryCheckOverlapAlgorithm() = default; + void initAlgorithm( const QVariantMap &configuration = QVariantMap() ) override; + QString name() const override; + QString displayName() const override; + QStringList tags() const override; + QString group() const override; + QString groupId() const override; + QString shortHelpString() const override; + Qgis::ProcessingAlgorithmFlags flags() const override; + QgsGeometryCheckOverlapAlgorithm *createInstance() const override SIP_FACTORY; + + protected: + bool prepareAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) override; + QVariantMap processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) override; + + private: + static QgsFields outputFields(); + int mTolerance { 8 }; +}; + +///@endcond PRIVATE + +#endif // QGSALGORITHMCHECKGEOMETRYOVERLAP_H diff --git a/src/analysis/processing/qgsnativealgorithms.cpp b/src/analysis/processing/qgsnativealgorithms.cpp index 9824f274646..c00d0908dae 100644 --- a/src/analysis/processing/qgsnativealgorithms.cpp +++ b/src/analysis/processing/qgsnativealgorithms.cpp @@ -50,6 +50,7 @@ #include "qgsalgorithmfixgeometrymissingvertex.h" #include "qgsalgorithmcheckgeometryhole.h" #include "qgsalgorithmcheckgeometrymissingvertex.h" +#include "qgsalgorithmcheckgeometryoverlap.h" #include "qgsalgorithmclip.h" #include "qgsalgorithmconcavehull.h" #include "qgsalgorithmconditionalbranch.h" @@ -338,6 +339,7 @@ void QgsNativeAlgorithms::loadAlgorithms() addAlgorithm( new QgsGeometryCheckAreaAlgorithm() ); addAlgorithm( new QgsGeometryCheckHoleAlgorithm() ); addAlgorithm( new QgsGeometryCheckMissingVertexAlgorithm() ); + addAlgorithm( new QgsGeometryCheckOverlapAlgorithm() ); addAlgorithm( new QgsClipAlgorithm() ); addAlgorithm( new QgsCollectAlgorithm() ); addAlgorithm( new QgsCombineStylesAlgorithm() ); diff --git a/tests/src/analysis/testqgsprocessingcheckgeometry.cpp b/tests/src/analysis/testqgsprocessingcheckgeometry.cpp index c521dc93281..336af3e109b 100644 --- a/tests/src/analysis/testqgsprocessingcheckgeometry.cpp +++ b/tests/src/analysis/testqgsprocessingcheckgeometry.cpp @@ -37,6 +37,8 @@ class TestQgsProcessingCheckGeometry : public QgsTest void angleAlg_data(); void angleAlg(); + void overlapAlg(); + void areaAlg(); void holeAlg(); void missingVertexAlg(); @@ -219,5 +221,35 @@ void TestQgsProcessingCheckGeometry::missingVertexAlg() QCOMPARE( errorsLayer->featureCount(), 5 ); } +void TestQgsProcessingCheckGeometry::overlapAlg() +{ + std::unique_ptr< QgsProcessingAlgorithm > alg( + QgsApplication::processingRegistry()->createAlgorithmById( QStringLiteral( "native:checkgeometryoverlap" ) ) + ); + QVERIFY( alg != nullptr ); + + QVariantMap parameters; + parameters.insert( QStringLiteral( "INPUT" ), QVariant::fromValue( mPolygonLayer ) ); + parameters.insert( QStringLiteral( "UNIQUE_ID" ), "id" ); + parameters.insert( QStringLiteral( "MIN_OVERLAP_AREA" ), 0.01 ); + parameters.insert( QStringLiteral( "OUTPUT" ), QgsProcessing::TEMPORARY_OUTPUT ); + parameters.insert( QStringLiteral( "ERRORS" ), QgsProcessing::TEMPORARY_OUTPUT ); + + bool ok = false; + QgsProcessingFeedback feedback; + std::unique_ptr< QgsProcessingContext > context = std::make_unique< QgsProcessingContext >(); + + QVariantMap results; + results = alg->run( parameters, *context, &feedback, &ok ); + QVERIFY( ok ); + + std::unique_ptr outputLayer( qobject_cast< QgsVectorLayer * >( context->getMapLayer( results.value( QStringLiteral( "OUTPUT" ) ).toString() ) ) ); + std::unique_ptr errorsLayer( qobject_cast< QgsVectorLayer * >( context->getMapLayer( results.value( QStringLiteral( "ERRORS" ) ).toString() ) ) ); + QVERIFY( outputLayer->isValid() ); + QVERIFY( errorsLayer->isValid() ); + QCOMPARE( outputLayer->featureCount(), 2 ); + QCOMPARE( errorsLayer->featureCount(), 2 ); +} + QGSTEST_MAIN( TestQgsProcessingCheckGeometry ) #include "testqgsprocessingcheckgeometry.moc"