QGIS API Documentation 3.28.0-Firenze (ed3ad0430f)
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#include "qgsvectorlayer.h"
20#include "qgsgeometryengine.h"
21#include "qgsdistancearea.h"
22
24
25QString QgsCalculateVectorOverlapsAlgorithm::name() const
26{
27 return QStringLiteral( "calculatevectoroverlaps" );
28}
29
30QString QgsCalculateVectorOverlapsAlgorithm::displayName() const
31{
32 return QObject::tr( "Overlap analysis" );
33}
34
35QStringList QgsCalculateVectorOverlapsAlgorithm::tags() const
36{
37 return QObject::tr( "vector,overlay,area,percentage,intersection" ).split( ',' );
38}
39
40QString QgsCalculateVectorOverlapsAlgorithm::group() const
41{
42 return QObject::tr( "Vector analysis" );
43}
44
45QString QgsCalculateVectorOverlapsAlgorithm::groupId() const
46{
47 return QStringLiteral( "vectoranalysis" );
48}
49
50void QgsCalculateVectorOverlapsAlgorithm::initAlgorithm( const QVariantMap & )
51{
52 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input layer" ), QList< int >() << QgsProcessing::TypeVectorPolygon ) );
53 addParameter( new QgsProcessingParameterMultipleLayers( QStringLiteral( "LAYERS" ), QObject::tr( "Overlay layers" ), QgsProcessing::TypeVectorPolygon ) );
54 addParameter( new QgsProcessingParameterFeatureSink( QStringLiteral( "OUTPUT" ), QObject::tr( "Overlap" ) ) );
55
56 std::unique_ptr< QgsProcessingParameterNumber > gridSize = std::make_unique< QgsProcessingParameterNumber >( QStringLiteral( "GRID_SIZE" ),
57 QObject::tr( "Grid size" ), QgsProcessingParameterNumber::Double, QVariant(), true, 0 );
58 gridSize->setFlags( gridSize->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
59 addParameter( gridSize.release() );
60}
61
62QIcon QgsCalculateVectorOverlapsAlgorithm::icon() const
63{
64 return QgsApplication::getThemeIcon( QStringLiteral( "/algorithms/mAlgorithmClip.svg" ) );
65}
66
67QString QgsCalculateVectorOverlapsAlgorithm::svgIconPath() const
68{
69 return QgsApplication::iconPath( QStringLiteral( "/algorithms/mAlgorithmClip.svg" ) );
70}
71
72QString QgsCalculateVectorOverlapsAlgorithm::shortHelpString() const
73{
74 return QObject::tr( "This algorithm calculates the area and percentage cover by which features from an input layer "
75 "are overlapped by features from a selection of overlay layers.\n\n"
76 "New attributes are added to the output layer reporting the total area of overlap and percentage of the input feature overlapped "
77 "by each of the selected overlay layers." );
78}
79
80QgsCalculateVectorOverlapsAlgorithm *QgsCalculateVectorOverlapsAlgorithm::createInstance() const
81{
82 return new QgsCalculateVectorOverlapsAlgorithm();
83}
84
85bool QgsCalculateVectorOverlapsAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback * )
86{
87 mSource.reset( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
88 if ( !mSource )
89 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
90
91 mOutputFields = mSource->fields();
92
93 const QList< QgsMapLayer * > layers = parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context );
94 mOverlayerSources.reserve( layers.size() );
95 mLayerNames.reserve( layers.size() );
96 for ( QgsMapLayer *layer : layers )
97 {
98 if ( QgsVectorLayer *vl = qobject_cast< QgsVectorLayer * >( layer ) )
99 {
100 mLayerNames << layer->name();
101 mOverlayerSources.emplace_back( std::make_unique< QgsVectorLayerFeatureSource >( vl ) );
102 mOutputFields.append( QgsField( QStringLiteral( "%1_area" ).arg( vl->name() ), QVariant::Double ) );
103 mOutputFields.append( QgsField( QStringLiteral( "%1_pc" ).arg( vl->name() ), QVariant::Double ) );
104 }
105 }
106
107 mOutputType = mSource->wkbType();
108 mCrs = mSource->sourceCrs();
109 mInputCount = mSource->featureCount();
110 mInputFeatures = mSource->getFeatures();
111 return true;
112}
113
114QVariantMap QgsCalculateVectorOverlapsAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
115{
116 QString destId;
117 std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, destId, mOutputFields,
118 mOutputType, mCrs ) );
119 if ( !sink )
120 throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );
121
122 // build a spatial index for each constraint layer for speed. We also store input constraint geometries here,
123 // to avoid refetching and projecting them later
124 QList< QgsSpatialIndex > spatialIndices;
125 spatialIndices.reserve( mLayerNames.size() );
126 auto nameIt = mLayerNames.constBegin();
127 for ( auto sourceIt = mOverlayerSources.begin(); sourceIt != mOverlayerSources.end(); ++sourceIt, ++nameIt )
128 {
129 feedback->pushInfo( QObject::tr( "Preparing %1" ).arg( *nameIt ) );
130 const QgsFeatureIterator featureIt = ( *sourceIt )->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QgsAttributeList() ).setDestinationCrs( mCrs, context.transformContext() ).setInvalidGeometryCheck( context.invalidGeometryCheck() ).setInvalidGeometryCallback( context.invalidGeometryCallback() ) );
131 spatialIndices << QgsSpatialIndex( featureIt, feedback, QgsSpatialIndex::FlagStoreFeatureGeometries );
132 }
133
135 da.setSourceCrs( mCrs, context.transformContext() );
136 da.setEllipsoid( context.ellipsoid() );
137
138 QgsGeometryParameters geometryParameters;
139 if ( parameters.value( QStringLiteral( "GRID_SIZE" ) ).isValid() )
140 {
141 geometryParameters.setGridSize( parameterAsDouble( parameters, QStringLiteral( "GRID_SIZE" ), context ) );
142 }
143
144 // loop through input
145 const double step = mInputCount > 0 ? 100.0 / mInputCount : 0;
146 long i = 0;
147 QgsFeature feature;
148 while ( mInputFeatures.nextFeature( feature ) )
149 {
150 if ( feedback->isCanceled() )
151 break;
152
153 QgsAttributes outAttributes = feature.attributes();
154 if ( feature.hasGeometry() && !qgsDoubleNear( feature.geometry().area(), 0.0 ) )
155 {
156 const QgsGeometry inputGeom = feature.geometry();
157 const double inputArea = da.measureArea( inputGeom );
158
159 // prepare for lots of intersection tests (for speed)
160 std::unique_ptr< QgsGeometryEngine > bufferGeomEngine( QgsGeometry::createGeometryEngine( inputGeom.constGet() ) );
161 bufferGeomEngine->prepareGeometry();
162
163 // calculate overlap attributes
164 auto spatialIteratorIt = spatialIndices.begin();
165 for ( auto it = mOverlayerSources.begin(); it != mOverlayerSources.end(); ++ it, ++spatialIteratorIt )
166 {
167 if ( feedback->isCanceled() )
168 break;
169
170 const QgsSpatialIndex &index = *spatialIteratorIt;
171 const QList<QgsFeatureId> matches = index.intersects( inputGeom.boundingBox() );
172 QVector< QgsGeometry > intersectingGeoms;
173 intersectingGeoms.reserve( matches.count() );
174 for ( const QgsFeatureId match : matches )
175 {
176 if ( feedback->isCanceled() )
177 break;
178
179 const QgsGeometry overlayGeometry = index.geometry( match );
180 if ( bufferGeomEngine->intersects( overlayGeometry.constGet() ) )
181 {
182 intersectingGeoms.append( overlayGeometry );
183 }
184 }
185
186 if ( feedback->isCanceled() )
187 break;
188
189 // dissolve intersecting features, calculate total area of them within our buffer
190 const QgsGeometry overlayDissolved = QgsGeometry::unaryUnion( intersectingGeoms, geometryParameters );
191
192 if ( feedback->isCanceled() )
193 break;
194
195 const QgsGeometry overlayIntersection = inputGeom.intersection( overlayDissolved, geometryParameters );
196
197 const double overlayArea = da.measureArea( overlayIntersection );
198 outAttributes.append( overlayArea );
199 outAttributes.append( 100 * overlayArea / inputArea );
200 }
201 }
202 else
203 {
204 // input feature has no geometry
205 for ( auto it = mOverlayerSources.begin(); it != mOverlayerSources.end(); ++ it )
206 {
207 outAttributes.append( QVariant() );
208 outAttributes.append( QVariant() );
209 }
210 }
211
212 feature.setAttributes( outAttributes );
213 if ( !sink->addFeature( feature, QgsFeatureSink::FastInsert ) )
214 throw QgsProcessingException( writeFeatureError( sink.get(), parameters, QStringLiteral( "OUTPUT" ) ) );
215
216 i++;
217 feedback->setProgress( i * step );
218 }
219
220 QVariantMap outputs;
221 outputs.insert( QStringLiteral( "OUTPUT" ), destId );
222 return outputs;
223}
224
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.
Definition: qgsattributes.h:59
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.
This class wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setInvalidGeometryCallback(const std::function< void(const QgsFeature &)> &callback)
Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is s...
QgsFeatureRequest & setInvalidGeometryCheck(InvalidGeometryCheck check)
Sets invalid geometry checking behavior.
@ 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:56
QgsAttributes attributes
Definition: qgsfeature.h:65
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
Definition: qgsfeature.cpp:160
QgsGeometry geometry
Definition: qgsfeature.h:67
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:233
bool isCanceled() const SIP_HOLDGIL
Tells whether the operation has been canceled already.
Definition: qgsfeedback.h:54
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:51
Encapsulates parameters under which a geometry operation is performed.
Definition: qgsgeometry.h:111
void setGridSize(double size)
Sets the grid size which will be used to snap vertices of a geometry.
Definition: qgsgeometry.h:136
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:164
const QgsAbstractGeometry * constGet() const SIP_HOLDGIL
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
double area() const
Returns the planar, 2-dimensional area of the geometry.
static QgsGeometryEngine * createGeometryEngine(const QgsAbstractGeometry *geometry)
Creates and returns a new geometry engine representing the specified 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.
Base class for all map layer types.
Definition: qgsmaplayer.h:73
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.
QgsFeatureRequest::InvalidGeometryCheck invalidGeometryCheck() const
Returns the behavior used for checking invalid geometries in input layers.
Custom exception class for processing related exceptions.
Definition: qgsexception.h:83
Base class for providing feedback from a processing algorithm.
virtual void pushInfo(const QString &info)
Pushes a general informational message from the algorithm.
@ FlagAdvanced
Parameter is an advanced parameter which should be hidden from users by default.
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.
@ TypeVectorPolygon
Vector polygon layers.
Definition: qgsprocessing.h:51
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 data sets.
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:2527
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features
Definition: qgsfeatureid.h:28
QList< int > QgsAttributeList
Definition: qgsfield.h:26