QGIS API Documentation 3.99.0-Master (09f76ad7019)
Loading...
Searching...
No Matches
qgsalgorithmcalculateoverlaps.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmcalculateoverlaps.cpp
3 ------------------
4 begin : May 2019
5 copyright : (C) 2019 by Nyall Dawson
6 email : nyall dot dawson 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 "qgsdistancearea.h"
21#include "qgsgeometryengine.h"
22#include "qgsspatialindex.h"
23#include "qgsvectorlayer.h"
24
25#include <QString>
26
27using namespace Qt::StringLiterals;
28
30
31QString QgsCalculateVectorOverlapsAlgorithm::name() const
32{
33 return u"calculatevectoroverlaps"_s;
34}
35
36QString QgsCalculateVectorOverlapsAlgorithm::displayName() const
37{
38 return QObject::tr( "Overlap analysis" );
39}
40
41QStringList QgsCalculateVectorOverlapsAlgorithm::tags() const
42{
43 return QObject::tr( "vector,overlay,area,percentage,intersection" ).split( ',' );
44}
45
46QString QgsCalculateVectorOverlapsAlgorithm::group() const
47{
48 return QObject::tr( "Vector analysis" );
49}
50
51QString QgsCalculateVectorOverlapsAlgorithm::groupId() const
52{
53 return u"vectoranalysis"_s;
54}
55
56void QgsCalculateVectorOverlapsAlgorithm::initAlgorithm( const QVariantMap & )
57{
58 addParameter( new QgsProcessingParameterFeatureSource( u"INPUT"_s, QObject::tr( "Input layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorPolygon ) ) );
59 addParameter( new QgsProcessingParameterMultipleLayers( u"LAYERS"_s, QObject::tr( "Overlay layers" ), Qgis::ProcessingSourceType::VectorPolygon ) );
60 addParameter( new QgsProcessingParameterFeatureSink( u"OUTPUT"_s, QObject::tr( "Overlap" ) ) );
61
62 auto gridSize = std::make_unique<QgsProcessingParameterNumber>( u"GRID_SIZE"_s, QObject::tr( "Grid size" ), Qgis::ProcessingNumberParameterType::Double, QVariant(), true, 0 );
63 gridSize->setFlags( gridSize->flags() | Qgis::ProcessingParameterFlag::Advanced );
64 addParameter( gridSize.release() );
65}
66
67QIcon QgsCalculateVectorOverlapsAlgorithm::icon() const
68{
69 return QgsApplication::getThemeIcon( u"/algorithms/mAlgorithmClip.svg"_s );
70}
71
72QString QgsCalculateVectorOverlapsAlgorithm::svgIconPath() const
73{
74 return QgsApplication::iconPath( u"/algorithms/mAlgorithmClip.svg"_s );
75}
76
77QString QgsCalculateVectorOverlapsAlgorithm::shortHelpString() const
78{
79 return QObject::tr( "This algorithm calculates the area and percentage cover by which features from an input layer "
80 "are overlapped by features from a selection of overlay layers.\n\n"
81 "New attributes are added to the output layer reporting the total area of overlap and percentage of the input feature overlapped "
82 "by each of the selected overlay layers." );
83}
84
85QString QgsCalculateVectorOverlapsAlgorithm::shortDescription() const
86{
87 return QObject::tr( "Calculates the area and percentage cover by which features from an input layer "
88 "are overlapped by features from a selection of overlay layers." );
89}
90
91Qgis::ProcessingAlgorithmDocumentationFlags QgsCalculateVectorOverlapsAlgorithm::documentationFlags() const
92{
94}
95
96QgsCalculateVectorOverlapsAlgorithm *QgsCalculateVectorOverlapsAlgorithm::createInstance() const
97{
98 return new QgsCalculateVectorOverlapsAlgorithm();
99}
100
101bool QgsCalculateVectorOverlapsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
102{
103 mSource.reset( parameterAsSource( parameters, u"INPUT"_s, context ) );
104 if ( !mSource )
105 throw QgsProcessingException( invalidSourceError( parameters, u"INPUT"_s ) );
106
107 mOutputFields = mSource->fields();
108
109 const QList<QgsMapLayer *> layers = parameterAsLayerList( parameters, u"LAYERS"_s, context );
110 mOverlayerSources.reserve( layers.size() );
111 mLayerNames.reserve( layers.size() );
112 for ( QgsMapLayer *layer : layers )
113 {
114 if ( QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer ) )
115 {
116 mLayerNames << layer->name();
117 mOverlayerSources.emplace_back( std::make_unique<QgsVectorLayerFeatureSource>( vl ) );
118 QgsFields newFields;
119 newFields.append( QgsField( u"%1_area"_s.arg( vl->name() ), QMetaType::Type::Double ) );
120 newFields.append( QgsField( u"%1_pc"_s.arg( vl->name() ), QMetaType::Type::Double ) );
121 mOutputFields = QgsProcessingUtils::combineFields( mOutputFields, newFields );
122 }
123 }
124
125 mOutputType = mSource->wkbType();
126 mCrs = mSource->sourceCrs();
127 mInputCount = mSource->featureCount();
128 mInputFeatures = mSource->getFeatures();
129 return true;
130}
131
132QVariantMap QgsCalculateVectorOverlapsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
133{
134 QString destId;
135 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u"OUTPUT"_s, context, destId, mOutputFields, mOutputType, mCrs ) );
136 if ( !sink )
137 throw QgsProcessingException( invalidSinkError( parameters, u"OUTPUT"_s ) );
138
139 // build a spatial index for each constraint layer for speed. We also store input constraint geometries here,
140 // to avoid refetching and projecting them later
141 QList<QgsSpatialIndex> spatialIndices;
142 spatialIndices.reserve( mLayerNames.size() );
143 auto nameIt = mLayerNames.constBegin();
144 for ( auto sourceIt = mOverlayerSources.begin(); sourceIt != mOverlayerSources.end(); ++sourceIt, ++nameIt )
145 {
146 feedback->pushInfo( QObject::tr( "Preparing %1" ).arg( *nameIt ) );
147 const QgsFeatureIterator featureIt = ( *sourceIt )->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QgsAttributeList() ).setDestinationCrs( mCrs, context.transformContext() ).setInvalidGeometryCheck( context.invalidGeometryCheck() ).setInvalidGeometryCallback( context.invalidGeometryCallback() ) );
148 spatialIndices << QgsSpatialIndex( featureIt, feedback, QgsSpatialIndex::FlagStoreFeatureGeometries );
149 }
150
152 da.setSourceCrs( mCrs, context.transformContext() );
153 da.setEllipsoid( context.ellipsoid() );
154
155 QgsGeometryParameters geometryParameters;
156 if ( parameters.value( u"GRID_SIZE"_s ).isValid() )
157 {
158 geometryParameters.setGridSize( parameterAsDouble( parameters, u"GRID_SIZE"_s, context ) );
159 }
160
161 // loop through input
162 const double step = mInputCount > 0 ? 100.0 / mInputCount : 0;
163 long i = 0;
164 QgsFeature feature;
165 while ( mInputFeatures.nextFeature( feature ) )
166 {
167 if ( feedback->isCanceled() )
168 break;
169
170 QgsAttributes outAttributes = feature.attributes();
171 if ( feature.hasGeometry() && !qgsDoubleNear( feature.geometry().area(), 0.0 ) )
172 {
173 const QgsGeometry inputGeom = feature.geometry();
174
175 double inputArea = 0;
176 try
177 {
178 inputArea = da.measureArea( inputGeom );
179 }
180 catch ( QgsCsException & )
181 {
182 throw QgsProcessingException( QObject::tr( "An error occurred while calculating feature area" ) );
183 }
184
185 // prepare for lots of intersection tests (for speed)
186 std::unique_ptr<QgsGeometryEngine> bufferGeomEngine( QgsGeometry::createGeometryEngine( inputGeom.constGet() ) );
187 bufferGeomEngine->prepareGeometry();
188
189 // calculate overlap attributes
190 auto spatialIteratorIt = spatialIndices.begin();
191 for ( auto it = mOverlayerSources.begin(); it != mOverlayerSources.end(); ++it, ++spatialIteratorIt )
192 {
193 if ( feedback->isCanceled() )
194 break;
195
196 const QgsSpatialIndex &index = *spatialIteratorIt;
197 const QList<QgsFeatureId> matches = index.intersects( inputGeom.boundingBox() );
198 QVector<QgsGeometry> intersectingGeoms;
199 intersectingGeoms.reserve( matches.count() );
200 for ( const QgsFeatureId match : matches )
201 {
202 if ( feedback->isCanceled() )
203 break;
204
205 const QgsGeometry overlayGeometry = index.geometry( match );
206 if ( bufferGeomEngine->intersects( overlayGeometry.constGet() ) )
207 {
208 intersectingGeoms.append( overlayGeometry );
209 }
210 }
211
212 if ( feedback->isCanceled() )
213 break;
214
215 // dissolve intersecting features, calculate total area of them within our buffer
216 const QgsGeometry overlayDissolved = QgsGeometry::unaryUnion( intersectingGeoms, geometryParameters );
217
218 if ( feedback->isCanceled() )
219 break;
220
221 const QgsGeometry overlayIntersection = inputGeom.intersection( overlayDissolved, geometryParameters );
222
223 double overlayArea = 0;
224 try
225 {
226 overlayArea = da.measureArea( overlayIntersection );
227 }
228 catch ( QgsCsException & )
229 {
230 throw QgsProcessingException( QObject::tr( "An error occurred while calculating feature area" ) );
231 }
232
233 outAttributes.append( overlayArea );
234 outAttributes.append( 100 * overlayArea / inputArea );
235 }
236 }
237 else
238 {
239 // input feature has no geometry
240 for ( auto it = mOverlayerSources.begin(); it != mOverlayerSources.end(); ++it )
241 {
242 outAttributes.append( QVariant() );
243 outAttributes.append( QVariant() );
244 }
245 }
246
247 feature.setAttributes( outAttributes );
248 if ( !sink->addFeature( feature, QgsFeatureSink::FastInsert ) )
249 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, u"OUTPUT"_s ) );
250
251 i++;
252 feedback->setProgress( i * step );
253 }
254
255 sink->finalize();
256
257 QVariantMap outputs;
258 outputs.insert( u"OUTPUT"_s, destId );
259 return outputs;
260}
261
@ VectorPolygon
Vector polygon layers.
Definition qgis.h:3607
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3692
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3701
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3834
@ Double
Double/float values.
Definition qgis.h:3875
static QIcon getThemeIcon(const QString &name, const QColor &fillColor=QColor(), const QColor &strokeColor=QColor())
Helper to get a theme icon.
static QString iconPath(const QString &iconFile)
Returns path to the desired icon file.
A vector of attributes.
Custom exception class for Coordinate Reference System related exceptions.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
double measureArea(const QgsGeometry &geometry) const
Measures the area of a geometry.
void setSourceCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets source spatial reference system crs.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
Wrapper for iterator of features from vector data provider or vector layer.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setInvalidGeometryCheck(Qgis::InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
QgsFeatureRequest & setInvalidGeometryCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is s...
@ FastInsert
Use faster inserts, at the cost of updating the passed features to reflect changes made at the provid...
The feature class encapsulates a single feature including its unique ID, geometry and a list of field...
Definition qgsfeature.h:60
QgsAttributes attributes
Definition qgsfeature.h:69
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
QgsGeometry geometry
Definition qgsfeature.h:71
bool hasGeometry() const
Returns true if the feature has an associated geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:55
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:63
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:76
Encapsulates parameters under which a geometry operation is performed.
void setGridSize(double size)
Sets the grid size which will be used to snap vertices of a geometry.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
double area() const
Returns the planar, 2-dimensional area of the geometry.
QgsGeometry intersection(const QgsGeometry &geometry, const QgsGeometryParameters &parameters=QgsGeometryParameters()) const
Returns a geometry representing the points shared by this geometry and other.
static QgsGeometry unaryUnion(const QVector< QgsGeometry > &geometries, const QgsGeometryParameters &parameters=QgsGeometryParameters())
Compute the unary union on a list of geometries.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry, double precision=0.0, Qgis::GeosCreationFlags flags=Qgis::GeosCreationFlag::SkipEmptyInteriorRings)
Creates and returns a new geometry engine representing the specified geometry using precision on a gr...
Base class for all map layer types.
Definition qgsmaplayer.h:83
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
std::function< void(const QgsFeature &) > invalidGeometryCallback(QgsFeatureSource *source=nullptr) const
Returns the callback function to use when encountering an invalid geometry and invalidGeometryCheck()...
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
Qgis::InvalidGeometryCheck invalidGeometryCheck() const
Returns the behavior used for checking invalid geometries in input layers.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
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 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).
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
QList< QgsFeatureId > intersects(const QgsRectangle &rectangle) const
Returns a list of features with a bounding box which intersects the specified rectangle.
QgsGeometry geometry(QgsFeatureId id) const
Returns the stored geometry for the indexed feature with matching id.
Represents a vector layer which manages a vector based dataset.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6935
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
QList< int > QgsAttributeList
Definition qgsfield.h:30