Skip to content

Commit

Permalink
Processing: Add Check Geometry algorithm and test: Missing vertex
Browse files Browse the repository at this point in the history
Porting missing vertex check from geometry checker to processings
  • Loading branch information
Djedouas committed Nov 28, 2024
1 parent b0b2925 commit e73ebe1
Show file tree
Hide file tree
Showing 5 changed files with 296 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/analysis/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ set(QGIS_ANALYSIS_SRCS
processing/qgsalgorithmfixgeometryangle.cpp
processing/qgsalgorithmcheckgeometryhole.cpp
processing/qgsalgorithmfixgeometryhole.cpp
processing/qgsalgorithmcheckgeometrymissingvertex.cpp
processing/qgsalgorithmcheckgeometryarea.cpp
processing/qgsalgorithmfixgeometryarea.cpp
processing/qgsalgorithmclip.cpp
Expand Down
205 changes: 205 additions & 0 deletions src/analysis/processing/qgsalgorithmcheckgeometrymissingvertex.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
/***************************************************************************
qgsalgorithmcheckgeometrymissingvertex.cpp
---------------------
begin : February 2024
copyright : (C) 2024 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 "qgsalgorithmcheckgeometrymissingvertex.h"
#include "qgsgeometrycheckcontext.h"
#include "qgsgeometrycheckerror.h"
#include "qgsgeometrymissingvertexcheck.h"
#include "qgspoint.h"
#include "qgsvectorlayer.h"
#include "qgsvectordataproviderfeaturepool.h"

///@cond PRIVATE

auto QgsGeometryCheckMissingVertexAlgorithm::name() const -> QString
{
return QStringLiteral( "checkgeometrymissingvertex" );
}

auto QgsGeometryCheckMissingVertexAlgorithm::displayName() const -> QString
{
return QObject::tr( "Check geometry (Missing Vertex)" );
}

auto QgsGeometryCheckMissingVertexAlgorithm::tags() const -> QStringList
{
return QObject::tr( "check,geometry,missing,vertex" ).split( ',' );
}

auto QgsGeometryCheckMissingVertexAlgorithm::group() const -> QString
{
return QObject::tr( "Check geometry" );
}

auto QgsGeometryCheckMissingVertexAlgorithm::groupId() const -> QString
{
return QStringLiteral( "checkgeometry" );
}

auto QgsGeometryCheckMissingVertexAlgorithm::shortHelpString() const -> QString
{
return QObject::tr( "This algorithm checks the missing vertices along polygons junctions." );
}

auto QgsGeometryCheckMissingVertexAlgorithm::flags() const -> Qgis::ProcessingAlgorithmFlags
{
return QgsProcessingAlgorithm::flags() | Qgis::ProcessingAlgorithmFlag::NoThreading;
}

auto QgsGeometryCheckMissingVertexAlgorithm::createInstance() const -> QgsGeometryCheckMissingVertexAlgorithm *
{
return new QgsGeometryCheckMissingVertexAlgorithm();
}

void QgsGeometryCheckMissingVertexAlgorithm::initAlgorithm( const QVariantMap &configuration )
{
Q_UNUSED( configuration )

// inputs
addParameter(
new QgsProcessingParameterFeatureSource(
QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ),
QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon )
)
);
addParameter( new QgsProcessingParameterField( QStringLiteral( "UNIQUE_ID" ), QObject::tr( "Unique feature identifier" ), QStringLiteral( "" ), QStringLiteral( "INPUT" ) ) );

// outputs
addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "ERRORS" ), QObject::tr( "Errors layer" ), Qgis::ProcessingSourceType::VectorPoint ) );
addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Output layer" ), Qgis::ProcessingSourceType::VectorPolygon ) );

std::unique_ptr< QgsProcessingParameterNumber > tolerance = std::make_unique< QgsProcessingParameterNumber >( QStringLiteral( "TOLERANCE" ),
QObject::tr( "Tolerance" ), Qgis::ProcessingNumberParameterType::Integer, 8, false, 1, 13 );
tolerance->setFlags( tolerance->flags() | Qgis::ProcessingParameterFlag::Advanced );
addParameter( tolerance.release() );
}

auto QgsGeometryCheckMissingVertexAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * ) -> bool
{
mTolerance = parameterAsInt( parameters, QStringLiteral( "TOLERANCE" ), context );

return true;
}

static auto outputFields( ) -> QgsFields
{
QgsFields fields;
fields.append( QgsField( QStringLiteral( "gc_layerid" ), QMetaType::QString ) );
fields.append( QgsField( QStringLiteral( "gc_layername" ), QMetaType::QString ) );
fields.append( QgsField( QStringLiteral( "gc_partidx" ), QMetaType::Int ) );
fields.append( QgsField( QStringLiteral( "gc_ringidx" ), QMetaType::Int ) );
fields.append( QgsField( QStringLiteral( "gc_vertidx" ), QMetaType::Int ) );
fields.append( QgsField( QStringLiteral( "gc_errorx" ), QMetaType::Double ) );
fields.append( QgsField( QStringLiteral( "gc_errory" ), QMetaType::Double ) );
fields.append( QgsField( QStringLiteral( "gc_error" ), QMetaType::QString ) );
return fields;
}


auto QgsGeometryCheckMissingVertexAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) -> QVariantMap
{
QString dest_output;
QString dest_errors;
QgsProcessingFeatureSource *input = parameterAsSource( parameters, QStringLiteral( "INPUT" ), context );

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 );

QgsFields fields = outputFields();
fields.append( uniqueIdField );

const std::unique_ptr< QgsFeatureSink > 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< QgsFeatureSink > 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 );

QgsProject *project = QgsProject::instance();

const std::unique_ptr<QgsGeometryCheckContext> checkContext = std::make_unique<QgsGeometryCheckContext>( mTolerance, input->sourceCrs(), project->transformContext(), project );

// Test detection
QList<QgsGeometryCheckError *> checkErrors;
QStringList messages;

const QgsGeometryMissingVertexCheck check( checkContext.get(), QVariantMap() );

multiStepFeedback.setCurrentStep( 1 );
feedback->setProgressText( QObject::tr( "Preparing features…" ) );
QMap<QString, QgsFeaturePool *> featurePools;
QgsVectorLayer *inputLayer = input->materialize( QgsFeatureRequest() );
featurePools.insert( inputLayer->id(), new QgsVectorDataProviderFeaturePool( inputLayer ) );

multiStepFeedback.setCurrentStep( 2 );
feedback->setProgressText( QObject::tr( "Collecting errors…" ) );
check.collectErrors( featurePools, 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 ( QgsGeometryCheckError *error : checkErrors )
{

if ( feedback->isCanceled() )
{
break;
}
QgsFeature f;
QgsAttributes attrs = f.attributes();

attrs << error->layerId()
<< inputLayer->name()
<< error->vidx().part
<< error->vidx().ring
<< error->vidx().vertex
<< error->location().x()
<< error->location().y()
<< error->value().toString()
<< inputLayer->getFeature( error->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<double>( i ) );
}

QVariantMap outputs;
outputs.insert( QStringLiteral( "OUTPUT" ), dest_output );
outputs.insert( QStringLiteral( "ERRORS" ), dest_errors );

return outputs;
}

///@endcond
55 changes: 55 additions & 0 deletions src/analysis/processing/qgsalgorithmcheckgeometrymissingvertex.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/***************************************************************************
qgsalgorithmcheckgeometrymissingvertex.h
---------------------
begin : February 2024
copyright : (C) 2024 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 QGSALGORITHMCHECKGEOMETRYMISSINGVERTEX_H
#define QGSALGORITHMCHECKGEOMETRYMISSINGVERTEX_H

#define SIP_NO_FILE

#include "qgis_sip.h"
#include "qgsprocessingalgorithm.h"

///@cond PRIVATE

class QgsGeometryCheckMissingVertexAlgorithm : public QgsProcessingAlgorithm
{
public:

QgsGeometryCheckMissingVertexAlgorithm() = 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;
QgsGeometryCheckMissingVertexAlgorithm *createInstance() const override SIP_FACTORY;

protected:

bool prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) override;
QVariantMap processAlgorithm( const QVariantMap &parameters,
QgsProcessingContext &context, QgsProcessingFeedback *feedback ) override;

private:
int mTolerance{8};
};

///@endcond PRIVATE

#endif // QGSALGORITHMCHECKGEOMETRYMISSINGVERTEX_H
2 changes: 2 additions & 0 deletions src/analysis/processing/qgsnativealgorithms.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
#include "qgsalgorithmfixgeometryarea.h"
#include "qgsalgorithmfixgeometryhole.h"
#include "qgsalgorithmcheckgeometryhole.h"
#include "qgsalgorithmcheckgeometrymissingvertex.h"
#include "qgsalgorithmclip.h"
#include "qgsalgorithmconcavehull.h"
#include "qgsalgorithmconditionalbranch.h"
Expand Down Expand Up @@ -330,6 +331,7 @@ void QgsNativeAlgorithms::loadAlgorithms()
addAlgorithm( new QgsGeometryCheckAngleAlgorithm() );
addAlgorithm( new QgsGeometryCheckAreaAlgorithm() );
addAlgorithm( new QgsGeometryCheckHoleAlgorithm() );
addAlgorithm( new QgsGeometryCheckMissingVertexAlgorithm() );
addAlgorithm( new QgsClipAlgorithm() );
addAlgorithm( new QgsCollectAlgorithm() );
addAlgorithm( new QgsCombineStylesAlgorithm() );
Expand Down
33 changes: 33 additions & 0 deletions tests/src/analysis/testqgsprocessingcheckgeometry.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class TestQgsProcessingCheckGeometry: public QgsTest

void areaAlg();
void holeAlg();
void missingVertexAlg();

private:

Expand Down Expand Up @@ -186,5 +187,37 @@ void TestQgsProcessingCheckGeometry::holeAlg()
QCOMPARE( errorsLayer->featureCount(), 1 );
}

void TestQgsProcessingCheckGeometry::missingVertexAlg()
{
const std::unique_ptr< QgsProcessingAlgorithm > alg(
QgsApplication::processingRegistry()->createAlgorithmById( QStringLiteral( "native:checkgeometrymissingvertex" ) )
);
QVERIFY( alg != nullptr );

const QDir testDataDir( QDir( TEST_DATA_DIR ).absoluteFilePath( "geometry_checker" ) );
QgsVectorLayer *missingVertexLayer = new QgsVectorLayer( testDataDir.absoluteFilePath( "missing_vertex.gpkg" ), QStringLiteral( "polygons" ), QStringLiteral( "ogr" ) );

QVariantMap parameters;
parameters.insert( QStringLiteral( "INPUT" ), QVariant::fromValue( missingVertexLayer ) );
parameters.insert( QStringLiteral( "UNIQUE_ID" ), "id" );
parameters.insert( QStringLiteral( "OUTPUT" ), QgsProcessing::TEMPORARY_OUTPUT );
parameters.insert( QStringLiteral( "ERRORS" ), QgsProcessing::TEMPORARY_OUTPUT );

bool ok = false;
QgsProcessingFeedback feedback;
const std::unique_ptr< QgsProcessingContext > context = std::make_unique< QgsProcessingContext >();

QVariantMap results;
results = alg->run( parameters, *context, &feedback, &ok );
QVERIFY( ok );

const std::unique_ptr<QgsVectorLayer> outputLayer( qobject_cast< QgsVectorLayer * >( context->getMapLayer( results.value( QStringLiteral( "OUTPUT" ) ).toString() ) ) );
const std::unique_ptr<QgsVectorLayer> errorsLayer( qobject_cast< QgsVectorLayer * >( context->getMapLayer( results.value( QStringLiteral( "ERRORS" ) ).toString() ) ) );
QVERIFY( outputLayer->isValid() );
QVERIFY( errorsLayer->isValid() );
QCOMPARE( outputLayer->featureCount(), 5 );
QCOMPARE( errorsLayer->featureCount(), 5 );
}

QGSTEST_MAIN( TestQgsProcessingCheckGeometry )
#include "testqgsprocessingcheckgeometry.moc"

0 comments on commit e73ebe1

Please sign in to comment.