diff --git a/src/analysis/CMakeLists.txt b/src/analysis/CMakeLists.txt index 00edabb0c342..e133a9eb48b2 100644 --- a/src/analysis/CMakeLists.txt +++ b/src/analysis/CMakeLists.txt @@ -61,6 +61,7 @@ set(QGIS_ANALYSIS_SRCS processing/qgsalgorithmcellstatistics.cpp processing/qgsalgorithmcentroid.cpp processing/qgsalgorithmcheckgeometryarea.cpp + processing/qgsalgorithmcheckgeometrysegmentlength.cpp processing/qgsalgorithmcheckgeometrydangle.cpp processing/qgsalgorithmcheckgeometrymultipart.cpp processing/qgsalgorithmcheckgeometryangle.cpp diff --git a/src/analysis/processing/qgsalgorithmcheckgeometrysegmentlength.cpp b/src/analysis/processing/qgsalgorithmcheckgeometrysegmentlength.cpp new file mode 100644 index 000000000000..46a27e3a61d3 --- /dev/null +++ b/src/analysis/processing/qgsalgorithmcheckgeometrysegmentlength.cpp @@ -0,0 +1,278 @@ +/*************************************************************************** + qgsalgorithmcheckgeometrysegmentlength.cpp + --------------------- + begin : December 2023 + copyright : (C) 2023 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 "qgsalgorithmcheckgeometrysegmentlength.h" +#include "qgsgeometrycheckcontext.h" +#include "qgsgeometrycheckerror.h" +#include "qgsgeometrysegmentlengthcheck.h" +#include "qgspoint.h" +#include "qgsvectorlayer.h" +#include "qgsvectordataproviderfeaturepool.h" + +///@cond PRIVATE + +auto QgsGeometryCheckSegmentLengthAlgorithm::name() const -> QString +{ + return QStringLiteral( "checkgeometrysegmentlength" ); +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::displayName() const -> QString +{ + return QObject::tr( "Check Geometry (Segment length)" ); +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::tags() const -> QStringList +{ + return QObject::tr( "check,geometry,segment,length" ).split( ',' ); +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::group() const -> QString +{ + return QObject::tr( "Check geometry" ); +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::groupId() const -> QString +{ + return QStringLiteral( "checkgeometry" ); +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::shortHelpString() const -> QString +{ + return QObject::tr( "This algorithm check the min segment length of geometry." ); +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::flags() const -> QgsProcessingAlgorithm::Flags +{ + return QgsProcessingAlgorithm::flags() | QgsProcessingAlgorithm::FlagNoThreading | QgsProcessingAlgorithm::FlagSupportsInPlaceEdits; +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::createInstance() const -> QgsGeometryCheckSegmentLengthAlgorithm * +{ + return new QgsGeometryCheckSegmentLengthAlgorithm(); +} + +static auto resolutionMethods() -> QStringList +{ + static const QStringList methods = QStringList() << QObject::tr( "No action" ); + return methods; +} + +void QgsGeometryCheckSegmentLengthAlgorithm::initAlgorithm( const QVariantMap &configuration ) +{ + + mIsInPlace = configuration.value( QStringLiteral( "IN_PLACE" ) ).toBool(); + + addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList< int >() << QgsProcessing::TypeVectorPolygon << QgsProcessing::TypeVectorLine ) ); + addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "ERRORS" ), QObject::tr( "Errors layer" ), QgsProcessing::TypeVectorPoint ) ); + addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Output layer" ), QgsProcessing::TypeVectorAnyGeometry ) ); + + addParameter( new QgsProcessingParameterNumber( QStringLiteral( "MIN_SEGMENT_LENGTH" ), QObject::tr( "min segment length" ), QgsProcessingParameterNumber::Double, 0, false, 0.0 ) ); + + std::unique_ptr< QgsProcessingParameterNumber > tolerance = std::make_unique< QgsProcessingParameterNumber >( QStringLiteral( "TOLERANCE" ), + QObject::tr( "Tolerance" ), QgsProcessingParameterNumber::Integer, 8, false, 1, 13 ); + tolerance->setFlags( tolerance->flags() | QgsProcessingParameterDefinition::FlagAdvanced ); + addParameter( tolerance.release() ); + + if ( mIsInPlace ) + { + // resolutionMethod is deprecated and not static and availableResolutionmethod is not static either + // We need a QStringList here, so copy/paste from resolutionMethod() +// Q_NOWARN_DEPRECATED_PUSH +// addParameter( new QgsProcessingParameterEnum( QStringLiteral( "RESOLUTIONMETHOD"), QObject::tr( "Resolution method"), QgsGeometrySegmentLengthCheck::resolutionMethods() ) ); +// Q_NOWARN_DEPRECATED_POP + addParameter( new QgsProcessingParameterEnum( QStringLiteral( "RESOLUTIONMETHOD" ), QObject::tr( "Resolution method" ), resolutionMethods(), false, resolutionMethods().size() - 1 ) ); + } +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::prepareAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback * ) -> bool +{ + mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context ); + + return true; +} + +auto QgsGeometryCheckSegmentLengthAlgorithm::createFeaturePool( QgsVectorLayer *layer, bool selectedOnly ) const -> QgsFeaturePool * +{ + return new QgsVectorDataProviderFeaturePool( layer, selectedOnly ); +} + +static auto outputFields( ) -> QgsFields +{ + QgsFields fields; + fields.append( QgsField( QStringLiteral( "gc_layerid" ), QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "gc_layername" ), QVariant::String ) ); + fields.append( QgsField( QStringLiteral( "gc_featid" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "gc_partidx" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "gc_ringidx" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "gc_vertidx" ), QVariant::Int ) ); + fields.append( QgsField( QStringLiteral( "gc_errorx" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "gc_errory" ), QVariant::Double ) ); + fields.append( QgsField( QStringLiteral( "gc_error" ), QVariant::String ) ); + return fields; +} + + +auto QgsGeometryCheckSegmentLengthAlgorithm::processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) -> QVariantMap +{ + QString dest_output; + QString dest_errors; + std::unique_ptr< QgsProcessingFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) ); + if ( !source ) + throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) ); + + mInputLayer.reset( source->materialize( QgsFeatureRequest() ) ); + + if ( !mInputLayer.get() ) + throw QgsProcessingException( QObject::tr( "Could not load source layer for INPUT" ) ); + + QgsFields fields = outputFields(); + + std::unique_ptr< QgsFeatureSink > sink_output( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest_output, mIsInPlace ? mInputLayer->fields() : fields, mInputLayer->wkbType(), mInputLayer->sourceCrs() ) ); + if ( !sink_output ) + { + throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) ); + } + std::unique_ptr< QgsFeatureSink > sink_errors( parameterAsSink( parameters, QStringLiteral( "ERRORS" ), context, dest_errors, fields, Qgis::WkbType::Point, mInputLayer->sourceCrs() ) ); + if ( !sink_errors ) + { + throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "ERRORS" ) ) ); + } + + int resolutionMethod{-1}; + if ( mIsInPlace ) + { + resolutionMethod = parameterAsEnum( parameters, QStringLiteral( "RESOLUTIONMETHOD" ), context ); + } + + QgsProcessingMultiStepFeedback multiStepFeedback( mIsInPlace ? 4 : 3, feedback ); + + QgsProject *project = mInputLayer->project() ? mInputLayer->project() : QgsProject::instance(); + + std::unique_ptr checkContext = std::make_unique( mTolerance, mInputLayer->sourceCrs(), project->transformContext(), project ); + + // Test detection + QList checkErrors; + QStringList messages; + + double segmentLength = parameterAsDouble( parameters, QStringLiteral( "MIN_SEGMENT_LENGTH" ), context ); + + QVariantMap configurationCheck; + configurationCheck.insert( "minSegmentLength", segmentLength ); + const QgsGeometrySegmentLengthCheck check( checkContext.get(), configurationCheck ); + + multiStepFeedback.setCurrentStep( 1 ); + feedback->setProgressText( QObject::tr( "Preparing features…" ) ); + QMap featurePools; + featurePools.insert( mInputLayer->id(), createFeaturePool( mInputLayer.get() ) ); + + multiStepFeedback.setCurrentStep( 2 ); + feedback->setProgressText( QObject::tr( "Collecting errors…" ) ); + check.collectErrors( featurePools, checkErrors, messages, feedback ); + + multiStepFeedback.setCurrentStep( 3 ); + feedback->setProgressText( QObject::tr( "Exporting errors…" ) ); + double step{checkErrors.size() > 0 ? 100.0 / checkErrors.size() : 1}; + long i = 0; + feedback->setProgress( 0.0 ); + + + for ( QgsGeometryCheckError *error : checkErrors ) + { + + if ( feedback->isCanceled() ) + { + break; + } + QgsFeature f; + QgsAttributes attrs = f.attributes(); + + attrs << error->layerId() + << mInputLayer->name() + << error->featureId() + << error->vidx().part + << error->vidx().ring + << error->vidx().vertex + << error->location().x() + << error->location().y() + << error->value().toString(); + f.setAttributes( attrs ); + + if ( mIsInPlace ) + { + QgsGeometryCheck::Changes changes; + QMap mergeIndice; + check.fixError( featurePools, error, resolutionMethod, mergeIndice, changes ); + } + else + { + 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 ) ); + } + + if ( mIsInPlace ) + { + multiStepFeedback.setCurrentStep( 4 ); + feedback->setProgressText( QObject::tr( "Exporting (fixed) layer…" ) ); + + const QgsFeaturePool *featurePool = featurePools[ mInputLayer->id() ]; + QgsFeatureIds featureIds{featurePool->allFeatureIds()}; + QgsFeatureIterator featIt{mInputLayer->getFeatures( featureIds )}; + + step = featureIds.size() > 0 ? 100.0 / featureIds.size() : 0; + feedback->setProgress( 100.0 * step ); + + QgsFeature feat; + while ( featIt.nextFeature( feat ) ) + { + if ( feedback->isCanceled() ) + { + break; + } + + if ( !sink_output->addFeature( feat, QgsFeatureSink::FastInsert ) ) + { + throw QgsProcessingException( writeFeatureError( sink_output.get(), parameters, QStringLiteral( "OUTPUT" ) ) ); + } + } + } + + QVariantMap outputs; + outputs.insert( QStringLiteral( "OUTPUT" ), dest_output ); + outputs.insert( QStringLiteral( "ERRORS" ), dest_errors ); + + return outputs; +} + +bool QgsGeometryCheckSegmentLengthAlgorithm::supportInPlaceEdit( const QgsMapLayer *layer ) const +{ + if ( const QgsVectorLayer *vl = qobject_cast< const QgsVectorLayer * >( layer ) ) + { + return ( vl->geometryType() == Qgis::GeometryType::Line ) || ( vl->geometryType() == Qgis::GeometryType::Polygon ); + } + return false; +} + +///@endcond diff --git a/src/analysis/processing/qgsalgorithmcheckgeometrysegmentlength.h b/src/analysis/processing/qgsalgorithmcheckgeometrysegmentlength.h new file mode 100644 index 000000000000..e1e461ef67d5 --- /dev/null +++ b/src/analysis/processing/qgsalgorithmcheckgeometrysegmentlength.h @@ -0,0 +1,61 @@ +/*************************************************************************** + qgsalgorithmcheckgeometrysegmentlength.h + --------------------- + begin : December 2023 + copyright : (C) 2023 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 QGSALGORITHMCHECKGEOMETRYSEGMENTLENGTH_H +#define QGSALGORITHMCHECKGEOMETRYSEGMENTLENGTH_H + +#define SIP_NO_FILE + +#include "qgis_sip.h" +#include "qgsprocessingalgorithm.h" +#include "qgsfeaturepool.h" + +///@cond PRIVATE + +class QgsGeometryCheckSegmentLengthAlgorithm : public QgsProcessingAlgorithm +{ + public: + + QgsGeometryCheckSegmentLengthAlgorithm() = 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; + Flags flags() const override; + QgsGeometryCheckSegmentLengthAlgorithm *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; + bool supportInPlaceEdit( const QgsMapLayer *layer ) const override; + + private: + QgsFeaturePool *createFeaturePool( QgsVectorLayer *layer, bool selectedOnly = false ) const; + + std::unique_ptr< QgsVectorLayer > mInputLayer; + int mTolerance{8}; + bool mIsInPlace{false}; +}; + +///@endcond PRIVATE + +#endif // QGSALGORITHMCHECKGEOMETRYSEGMENTLENGTH_H diff --git a/src/analysis/processing/qgsnativealgorithms.cpp b/src/analysis/processing/qgsnativealgorithms.cpp index 30c0a7a70f39..686ed4a32dbb 100644 --- a/src/analysis/processing/qgsnativealgorithms.cpp +++ b/src/analysis/processing/qgsnativealgorithms.cpp @@ -42,6 +42,7 @@ #include "qgsalgorithmcellstatistics.h" #include "qgsalgorithmcentroid.h" #include "qgsalgorithmcheckgeometryarea.h" +#include "qgsalgorithmcheckgeometrysegmentlength.h" #include "qgsalgorithmcheckgeometrydangle.h" #include "qgsalgorithmcheckgeometrymultipart.h" #include "qgsalgorithmcheckgeometryangle.h" @@ -312,6 +313,7 @@ void QgsNativeAlgorithms::loadAlgorithms() addAlgorithm( new QgsCellStatisticsPercentRankFromRasterAlgorithm() ); addAlgorithm( new QgsCellStatisticsPercentRankFromValueAlgorithm() ); addAlgorithm( new QgsCentroidAlgorithm() ); + addAlgorithm( new QgsGeometryCheckSegmentLengthAlgorithm() ); addAlgorithm( new QgsGeometryCheckAreaAlgorithm() ); addAlgorithm( new QgsGeometryCheckDangleAlgorithm() ); addAlgorithm( new QgsGeometryCheckMultipartAlgorithm() ); diff --git a/tests/src/analysis/testqgsprocessingcheckgeometry.cpp b/tests/src/analysis/testqgsprocessingcheckgeometry.cpp index 5686b8ec14da..490d5eab1217 100644 --- a/tests/src/analysis/testqgsprocessingcheckgeometry.cpp +++ b/tests/src/analysis/testqgsprocessingcheckgeometry.cpp @@ -38,6 +38,9 @@ class TestQgsProcessingCheckGeometry: public QgsTest void angleAlg_data(); void angleAlg(); + void segmentLengthAlg_data(); + void segmentLengthAlg(); + void multipartAlg_data(); void multipartAlg(); @@ -121,6 +124,46 @@ void TestQgsProcessingCheckGeometry::angleAlg() QCOMPARE( errorsLayer->featureCount(), expectedErrorCount ); } +void TestQgsProcessingCheckGeometry::segmentLengthAlg_data() +{ + QTest::addColumn( "layerToTest" ); + QTest::addColumn( "expectedErrorCount" ); + QTest::newRow( "Line layer" ) << mLineLayer << 1; + QTest::newRow( "Polygon layer" ) << mPolygonLayer << 3; +} + +void TestQgsProcessingCheckGeometry::segmentLengthAlg() +{ + QFETCH( QgsVectorLayer *, layerToTest ); + QFETCH( int, expectedErrorCount ); + + std::unique_ptr< QgsProcessingAlgorithm > alg( + QgsApplication::processingRegistry()->createAlgorithmById( QStringLiteral( "native:checkgeometrysegmentlength" ) ) + ); + QVERIFY( alg != nullptr ); + + QVariantMap parameters; + parameters.insert( QStringLiteral( "INPUT" ), QVariant::fromValue( layerToTest ) ); + parameters.insert( QStringLiteral( "MIN_SEGMENT_LENGTH" ), 0.03 ); + 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(), expectedErrorCount ); + QCOMPARE( errorsLayer->featureCount(), expectedErrorCount ); +} + void TestQgsProcessingCheckGeometry::areaAlg() { std::unique_ptr< QgsProcessingAlgorithm > alg(