QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
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
23#include <QString>
24
25using namespace Qt::StringLiterals;
26
28
29
30QString QgsMultiUnionAlgorithm::name() const
31{
32 return u"multiunion"_s;
33}
34
35QString QgsMultiUnionAlgorithm::displayName() const
36{
37 return QObject::tr( "Union (multiple)" );
38}
39
40QStringList QgsMultiUnionAlgorithm::tags() const
41{
42 return QObject::tr( "union,overlap,not overlap" ).split( ',' );
43}
44
45QString QgsMultiUnionAlgorithm::group() const
46{
47 return QObject::tr( "Vector overlay" );
48}
49
50QString QgsMultiUnionAlgorithm::groupId() const
51{
52 return u"vectoroverlay"_s;
53}
54
55QString QgsMultiUnionAlgorithm::shortHelpString() const
56{
57 return QObject::tr( "This algorithm checks overlaps between features within the Input layer and creates separate features for overlapping "
58 "and non-overlapping parts. The area of overlap will create as many identical overlapping features as there are "
59 "features that participate in that overlap." )
60 + u"\n\n"_s
61 + QObject::tr( "Multiple Overlay layers can also be used, in which case features from each layer are split at their overlap with features from "
62 "all other layers, creating a layer containing all the portions from both Input and Overlay layers. "
63 "The attribute table of the Union layer is filled with attribute values from the respective original layer "
64 "for non-overlapping features, and attribute values from both layers for overlapping features." );
65}
66
67QString QgsMultiUnionAlgorithm::shortDescription() const
68{
69 return QObject::tr( "Checks overlaps between features on the same layer or on more layers "
70 "and creates separate features for overlapping and non-overlapping parts." );
71}
72
73Qgis::ProcessingAlgorithmDocumentationFlags QgsMultiUnionAlgorithm::documentationFlags() const
74{
76}
77
78QgsProcessingAlgorithm *QgsMultiUnionAlgorithm::createInstance() const
79{
80 return new QgsMultiUnionAlgorithm();
81}
82
83void QgsMultiUnionAlgorithm::initAlgorithm( const QVariantMap & )
84{
85 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ) ) );
86 addParameter( new QgsProcessingParameterMultipleLayers( u"OVERLAYS"_s, QObject::tr( "Overlay layers" ), Qgis::ProcessingSourceType::VectorAnyGeometry, QVariant(), true ) );
87
88 auto prefix = std::make_unique<QgsProcessingParameterString>( u"OVERLAY_FIELDS_PREFIX"_s, QObject::tr( "Overlay fields prefix" ), QString(), false, true );
89 prefix->setFlags( prefix->flags() | Qgis::ProcessingParameterFlag::Advanced );
90 addParameter( prefix.release() );
91
92 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Union" ) ) );
93}
94
95QVariantMap QgsMultiUnionAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
96{
97 std::unique_ptr<QgsFeatureSource> sourceA( parameterAsSource( parameters, u"INPUT"_s, context ) );
98 if ( !sourceA )
99 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
100
101 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"OVERLAYS"_s, context );
102
103 // loop through overlay layers and check whether they are vectors
104 long totalLayerCount = 0;
105 for ( QgsMapLayer *layer : layers )
106 {
107 if ( feedback->isCanceled() )
108 break;
109
110 if ( !layer )
111 throw QgsProcessingException( QObject::tr( "Error retrieving map layer." ) );
112
113 if ( layer->type() != Qgis::LayerType::Vector )
114 throw QgsProcessingException( QObject::tr( "All layers must be vector layers!" ) );
115
116 totalLayerCount++;
117 }
118
119 const Qgis::WkbType geometryType = QgsWkbTypes::multiType( sourceA->wkbType() );
120 const QgsCoordinateReferenceSystem crs = sourceA->sourceCrs();
121 const QString overlayFieldsPrefix = parameterAsString( parameters, u"OVERLAY_FIELDS_PREFIX"_s, context );
122 std::unique_ptr<QgsFeatureSink> sink;
123 QVariantMap outputs;
124 bool ok;
125
126 if ( totalLayerCount == 0 )
127 {
128 // we are doing single layer union
129 QString dest;
130 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, sourceA->fields(), geometryType, sourceA->sourceCrs(), QgsFeatureSink::RegeneratePrimaryKey ) );
131 if ( !sink )
132 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
133
134 outputs.insert( u"OUTPUT"_s, dest );
135
136 QgsOverlayUtils::resolveOverlaps( *sourceA, *sink, feedback );
137 sink->finalize();
138 return outputs;
139 }
140 else
141 {
142 QgsProcessingMultiStepFeedback multiStepFeedback( totalLayerCount, feedback );
143 QgsVectorLayer *unionLayer = nullptr;
144 QgsFields fields;
145
146 long i = 0;
147 for ( QgsMapLayer *layer : layers )
148 {
149 if ( feedback->isCanceled() )
150 break;
151
152 multiStepFeedback.setCurrentStep( i );
153
154 if ( !layer )
155 continue;
156
157 QgsVectorLayer *overlayLayer = qobject_cast<QgsVectorLayer *>( layer );
158 if ( !overlayLayer )
159 continue;
160
161 if ( i == 0 )
162 {
163 QString id = u"memory:"_s;
164 fields = QgsProcessingUtils::combineFields( sourceA->fields(), overlayLayer->fields(), overlayFieldsPrefix );
165 sink.reset( QgsProcessingUtils::createFeatureSink( id, context, fields, geometryType, crs, QVariantMap(), QStringList(), QStringList(), QgsFeatureSink::RegeneratePrimaryKey ) );
166 ok = makeUnion( *sourceA, *overlayLayer, *sink, context, &multiStepFeedback );
167
168 if ( !ok )
169 throw QgsProcessingException( QObject::tr( "Interrupted by user." ) );
170
171 unionLayer = qobject_cast<QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( id, context ) );
172 }
173 else if ( i == totalLayerCount - 1 )
174 {
175 fields = QgsProcessingUtils::combineFields( unionLayer->fields(), overlayLayer->fields(), overlayFieldsPrefix );
176
177
178 QString dest;
179 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, dest, fields, geometryType, crs, QgsFeatureSink::RegeneratePrimaryKey ) );
180 if ( !sink )
181 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
182
183 outputs.insert( u"OUTPUT"_s, dest );
184 ok = makeUnion( *unionLayer, *overlayLayer, *sink, context, &multiStepFeedback );
185 if ( !ok )
186 throw QgsProcessingException( QObject::tr( "Interrupted by user." ) );
187 }
188 else
189 {
190 QString id = u"memory:"_s;
191 fields = QgsProcessingUtils::combineFields( unionLayer->fields(), overlayLayer->fields(), overlayFieldsPrefix );
192 sink.reset( QgsProcessingUtils::createFeatureSink( id, context, fields, geometryType, crs, QVariantMap(), QStringList(), QStringList(), QgsFeatureSink::RegeneratePrimaryKey ) );
193 ok = makeUnion( *unionLayer, *overlayLayer, *sink, context, &multiStepFeedback );
194 if ( !ok )
195 throw QgsProcessingException( QObject::tr( "Interrupted by user." ) );
196
197 unionLayer = qobject_cast<QgsVectorLayer *>( QgsProcessingUtils::mapLayerFromString( id, context ) );
198 }
199
200 i++;
201 }
202 }
203
204 return outputs;
205}
206
207bool QgsMultiUnionAlgorithm::makeUnion( const QgsFeatureSource &sourceA, const QgsFeatureSource &sourceB, QgsFeatureSink &sink, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
208{
209 const QList<int> fieldIndicesA = QgsProcessingUtils::fieldNamesToIndices( QStringList(), sourceA.fields() );
210 const QList<int> fieldIndicesB = QgsProcessingUtils::fieldNamesToIndices( QStringList(), sourceB.fields() );
211
212 long count = 0;
213 const long total = sourceA.featureCount() * 2 + sourceB.featureCount();
214
215 QgsOverlayUtils::intersection( sourceA, sourceB, sink, context, feedback, count, total, fieldIndicesA, fieldIndicesB );
216 if ( feedback->isCanceled() )
217 return false;
218
219 QgsOverlayUtils::difference( sourceA, sourceB, sink, context, feedback, count, total, QgsOverlayUtils::OutputAB );
220 if ( feedback->isCanceled() )
221 return false;
222
223 QgsOverlayUtils::difference( sourceB, sourceA, sink, context, feedback, count, total, QgsOverlayUtils::OutputBA );
224 return true;
225}
226
@ VectorAnyGeometry
Any vector layer with geometry.
Definition qgis.h:3604
@ RegeneratesPrimaryKey
Algorithm always drops any existing primary keys or FID values and regenerates them in outputs.
Definition qgis.h:3690
@ Vector
Vector layer.
Definition qgis.h:194
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3701
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:280
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
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:55
Container of fields for a vector layer.
Definition qgsfields.h:46
Base class for all map layer types.
Definition qgsmaplayer.h:83
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.