QGIS API Documentation 3.43.0-Master (0cdc48caa8d)
qgsalgorithmmultiunion.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmmultiunion.cpp
3 ------------------
4 begin : December 2021
5 copyright : (C) 2021 by Alexander Bruy
6 email : alexander dot bruy at gmail 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
19
20#include "qgsoverlayutils.h"
21#include "qgsvectorlayer.h"
22
24
25
26QString QgsMultiUnionAlgorithm::name() const
27{
28 return QStringLiteral( "multiunion" );
29}
30
31QString QgsMultiUnionAlgorithm::displayName() const
32{
33 return QObject::tr( "Union (multiple)" );
34}
35
36QStringList QgsMultiUnionAlgorithm::tags() const
37{
38 return QObject::tr( "union,overlap,not overlap" ).split( ',' );
39}
40
41QString QgsMultiUnionAlgorithm::group() const
42{
43 return QObject::tr( "Vector overlay" );
44}
45
46QString QgsMultiUnionAlgorithm::groupId() const
47{
48 return QStringLiteral( "vectoroverlay" );
49}
50
51QString QgsMultiUnionAlgorithm::shortHelpString() const
52{
53 return QObject::tr( "This algorithm checks overlaps between features within the Input layer and creates separate features for overlapping "
54 "and non-overlapping parts. The area of overlap will create as many identical overlapping features as there are "
55 "features that participate in that overlap." )
56 + QStringLiteral( "\n\n" )
57 + QObject::tr( "Multiple Overlay layers can also be used, in which case features from each layer are split at their overlap with features from "
58 "all other layers, creating a layer containing all the portions from both Input and Overlay layers. "
59 "The attribute table of the Union layer is filled with attribute values from the respective original layer "
60 "for non-overlapping features, and attribute values from both layers for overlapping features." );
61}
62
63QString QgsMultiUnionAlgorithm::shortDescription() const
64{
65 return QObject::tr( "Checks overlaps between features on the same layer or on more layers "
66 "and creates separate features for overlapping and non-overlapping parts." );
67}
68
69Qgis::ProcessingAlgorithmDocumentationFlags QgsMultiUnionAlgorithm::documentationFlags() const
70{
72}
73
74QgsProcessingAlgorithm *QgsMultiUnionAlgorithm::createInstance() const
75{
76 return new QgsMultiUnionAlgorithm();
77}
78
79void QgsMultiUnionAlgorithm::initAlgorithm( const QVariantMap & )
80{
81 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ) ) );
82 addParameter( new QgsProcessingParameterMultipleLayers( QStringLiteral( "OVERLAYS" ), QObject::tr( "Overlay layers" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true ) );
83
84 auto prefix = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "OVERLAY_FIELDS_PREFIX" ), QObject::tr( "Overlay fields prefix" ), QString(), false, true );
85 prefix->setFlags( prefix->flags() | Qgis::ProcessingParameterFlag::Advanced );
86 addParameter( prefix.release() );
87
88 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Union" ) ) );
89}
90
91QVariantMap QgsMultiUnionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
92{
93 std::unique_ptr<QgsFeatureSource> sourceA( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
94 if ( !sourceA )
95 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
96
97 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, QStringLiteral( "OVERLAYS" ), context );
98
99 // loop through overlay layers and check whether they are vectors
100 long totalLayerCount = 0;
101 for ( QgsMapLayer *layer : layers )
102 {
103 if ( feedback->isCanceled() )
104 break;
105
106 if ( !layer )
107 throw QgsProcessingException( QObject::tr( "Error retrieving map layer." ) );
108
109 if ( layer->type() != Qgis::LayerType::Vector )
110 throw QgsProcessingException( QObject::tr( "All layers must be vector layers!" ) );
111
112 totalLayerCount++;
113 }
114
115 const Qgis::WkbType geometryType = QgsWkbTypes::multiType( sourceA->wkbType() );
116 const QgsCoordinateReferenceSystem crs = sourceA->sourceCrs();
117 const QString overlayFieldsPrefix = parameterAsString( parameters, QStringLiteral( "OVERLAY_FIELDS_PREFIX" ), context );
118 std::unique_ptr<QgsFeatureSink> sink;
119 QVariantMap outputs;
120 bool ok;
121
122 if ( totalLayerCount == 0 )
123 {
124 // we are doing single layer union
125 QString dest;
126 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, sourceA->fields(), geometryType, sourceA->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
127 if ( !sink )
128 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
129
130 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
131
132 QgsOverlayUtils::resolveOverlaps( *sourceA, *sink, feedback );
133 sink->finalize();
134 return outputs;
135 }
136 else
137 {
138 QgsProcessingMultiStepFeedback multiStepFeedback( totalLayerCount, feedback );
139 QgsVectorLayer *unionLayer = nullptr;
140 QgsFields fields;
141
142 long i = 0;
143 for ( QgsMapLayer *layer : layers )
144 {
145 if ( feedback->isCanceled() )
146 break;
147
148 multiStepFeedback.setCurrentStep( i );
149
150 if ( !layer )
151 continue;
152
153 QgsVectorLayer *overlayLayer = qobject_cast<QgsVectorLayer *>( layer );
154 if ( !overlayLayer )
155 continue;
156
157 if ( i == 0 )
158 {
159 QString id = QStringLiteral( "memory:" );
160 fields = QgsProcessingUtils::combineFields( sourceA->fields(), overlayLayer->fields(), overlayFieldsPrefix );
161 sink.reset( QgsProcessingUtils::createFeatureSink( id, context, fields, geometryType, crs, QVariantMap(), QStringList(), QStringList(), QgsFeatureSink::RegeneratePrimaryKey ) );
162 ok = makeUnion( *sourceA, *overlayLayer, *sink, context, &multiStepFeedback );
163
164 if ( !ok )
165 throw QgsProcessingException( QObject::tr( "Interrupted by user." ) );
166
167 unionLayer = qobject_cast<QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( id, context ) );
168 }
169 else if ( i == totalLayerCount - 1 )
170 {
171 fields = QgsProcessingUtils::combineFields( unionLayer->fields(), overlayLayer->fields(), overlayFieldsPrefix );
172
173
174 QString dest;
175 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields, geometryType, crs, QgsFeatureSink::RegeneratePrimaryKey ) );
176 if ( !sink )
177 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
178
179 outputs.insert( QStringLiteral( "OUTPUT" ), dest );
180 ok = makeUnion( *unionLayer, *overlayLayer, *sink, context, &multiStepFeedback );
181 if ( !ok )
182 throw QgsProcessingException( QObject::tr( "Interrupted by user." ) );
183 }
184 else
185 {
186 QString id = QStringLiteral( "memory:" );
187 fields = QgsProcessingUtils::combineFields( unionLayer->fields(), overlayLayer->fields(), overlayFieldsPrefix );
188 sink.reset( QgsProcessingUtils::createFeatureSink( id, context, fields, geometryType, crs, QVariantMap(), QStringList(), QStringList(), QgsFeatureSink::RegeneratePrimaryKey ) );
189 ok = makeUnion( *unionLayer, *overlayLayer, *sink, context, &multiStepFeedback );
190 if ( !ok )
191 throw QgsProcessingException( QObject::tr( "Interrupted by user." ) );
192
193 unionLayer = qobject_cast<QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( id, context ) );
194 }
195
196 i++;
197 }
198 }
199
200 return outputs;
201}
202
203bool QgsMultiUnionAlgorithm::makeUnion( const QgsFeatureSource &sourceA, const QgsFeatureSource &sourceB, QgsFeatureSink &sink, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
204{
205 const QList<int> fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), sourceA.fields() );
206 const QList<int> fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), sourceB.fields() );
207
208 long count = 0;
209 const long total = sourceA.featureCount() * 2 + sourceB.featureCount();
210
211 QgsOverlayUtils::intersection( sourceA, sourceB, sink, context, feedback, count, total, fieldIndicesA, fieldIndicesB );
212 if ( feedback->isCanceled() )
213 return false;
214
215 QgsOverlayUtils::difference( sourceA, sourceB, sink, context, feedback, count, total, QgsOverlayUtils::OutputAB );
216 if ( feedback->isCanceled() )
217 return false;
218
219 QgsOverlayUtils::difference( sourceB, sourceA, sink, context, feedback, count, total, QgsOverlayUtils::OutputBA );
220 return true;
221}
222
@ VectorAnyGeometry
Any vector layer with geometry.
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
@ Vector
Vector layer.
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3496
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:256
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Represents a coordinate reference system (CRS).
An interface for objects which accept features via addFeature(s) methods.
@ RegeneratePrimaryKey
This flag indicates, that a primary key field cannot be guaranteed to be unique and the sink should i...
An interface for objects which provide features via a getFeatures method.
virtual QgsFields fields() const =0
Returns the fields associated with features in the source.
virtual long long featureCount() const =0
Returns the number of features contained in the source, or -1 if the feature count is unknown.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
Container of fields for a vector layer.
Definition qgsfields.h:46
Base class for all map layer types.
Definition qgsmaplayer.h:77
Abstract base class for processing algorithms.
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.
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 parameter for processing algorithms which accepts multiple map layers.
static QList< int > fieldNamesToIndices(const QStringList &fieldNames, const QgsFields &fields)
Returns a list of field indices parsed from the given list of field names.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
static QgsFeatureSink * createFeatureSink(QString &destination, QgsProcessingContext &context, const QgsFields &fields, Qgis::WkbType geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions=QVariantMap(), const QStringList &datasourceOptions=QStringList(), const QStringList &layerOptions=QStringList(), QgsFeatureSink::SinkFlags sinkFlags=QgsFeatureSink::SinkFlags(), QgsRemappingSinkDefinition *remappingDefinition=nullptr)
Creates a feature sink ready for adding features.
static QgsMapLayer * mapLayerFromString(const QString &string, QgsProcessingContext &context, bool allowLoadingNewLayers=true, QgsProcessingUtils::LayerHint typeHint=QgsProcessingUtils::LayerHint::UnknownType, QgsProcessing::LayerOptionsFlags flags=QgsProcessing::LayerOptionsFlags())
Interprets a string as a map layer within the supplied context.
Represents a vector layer which manages a vector based dataset.
static Qgis::WkbType multiType(Qgis::WkbType type)
Returns the multi type for a WKB type.
const QgsCoordinateReferenceSystem & crs