QGIS API Documentation 3.99.0-Master (26c88405ac0)
Loading...
Searching...
No Matches
qgsalgorithmlinedensity.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsalgorithmlinedensity.cpp
3 ---------------------
4 begin : December 2019
5 copyright : (C) 2019 by Clemens Raffler
6 email : clemens dot raffler 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 "qgscircle.h"
21#include "qgsgeometryengine.h"
22#include "qgsrasterfilewriter.h"
23
25
26QString QgsLineDensityAlgorithm::name() const
27{
28 return QStringLiteral( "linedensity" );
29}
30
31QString QgsLineDensityAlgorithm::displayName() const
32{
33 return QObject::tr( "Line density" );
34}
35
36QStringList QgsLineDensityAlgorithm::tags() const
37{
38 return QObject::tr( "density,kernel,line,line density,interpolation,weight" ).split( ',' );
39}
40
41QString QgsLineDensityAlgorithm::group() const
42{
43 return QObject::tr( "Interpolation" );
44}
45
46QString QgsLineDensityAlgorithm::groupId() const
47{
48 return QStringLiteral( "interpolation" );
49}
50
51void QgsLineDensityAlgorithm::initAlgorithm( const QVariantMap & )
52{
53 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input line layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
54 addParameter( new QgsProcessingParameterField( QStringLiteral( "WEIGHT" ), QObject::tr( "Weight field " ), QVariant(), QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Numeric, false, true ) );
55 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "RADIUS" ), QObject::tr( "Search radius" ), 10, QStringLiteral( "INPUT" ), false, 0 ) );
56 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "PIXEL_SIZE" ), QObject::tr( "Pixel size" ), 10, QStringLiteral( "INPUT" ), false ) );
57
58 // backwards compatibility parameter
59 // TODO QGIS 4: remove parameter and related logic
60 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATE_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
61 createOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
62 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
63 addParameter( createOptsParam.release() );
64
65 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATION_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
66 creationOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
67 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
68 addParameter( creationOptsParam.release() );
69
70 addParameter( new QgsProcessingParameterRasterDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Line density raster" ) ) );
71}
72
73QString QgsLineDensityAlgorithm::shortHelpString() const
74{
75 return QObject::tr( "This algorithm calculates a density measure of linear features "
76 "which is obtained in a circular neighborhood within each raster cell. "
77 "First, the length of the segment of each line that is intersected by the circular neighborhood "
78 "is multiplied with the lines weight factor. In a second step, all length values are summed and "
79 "divided by the area of the circular neighborhood. This process is repeated for all raster cells."
80 );
81}
82
83Qgis::ProcessingAlgorithmDocumentationFlags QgsLineDensityAlgorithm::documentationFlags() const
84{
86}
87
88QString QgsLineDensityAlgorithm::shortDescription() const
89{
90 return QObject::tr( "Calculates a density measure of linear features "
91 "which is obtained in a circular neighborhood within each raster cell." );
92}
93
94QgsLineDensityAlgorithm *QgsLineDensityAlgorithm::createInstance() const
95{
96 return new QgsLineDensityAlgorithm();
97}
98
99bool QgsLineDensityAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
100{
101 Q_UNUSED( feedback );
102 mSource.reset( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
103 if ( !mSource )
104 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
105
106 mWeightField = parameterAsString( parameters, QStringLiteral( "WEIGHT" ), context );
107
108 mPixelSize = parameterAsDouble( parameters, QStringLiteral( "PIXEL_SIZE" ), context );
109
110 mSearchRadius = parameterAsDouble( parameters, QStringLiteral( "RADIUS" ), context );
111 if ( mSearchRadius < 0.5 * mPixelSize * std::sqrt( 2 ) )
112 throw QgsProcessingException( QObject::tr( "Raster cells must be fully contained by the search circle. Therefore, "
113 "the search radius must not be smaller than half of the pixel diagonal." ) );
114
115 mExtent = mSource->sourceExtent();
116 mCrs = mSource->sourceCrs();
117 mDa = QgsDistanceArea();
118 mDa.setEllipsoid( context.ellipsoid() );
119 mDa.setSourceCrs( mCrs, context.transformContext() );
120
121 //get cell midpoint from top left cell
122 const QgsPoint firstCellMidpoint = QgsPoint( mExtent.xMinimum() + ( mPixelSize / 2 ), mExtent.yMaximum() - ( mPixelSize / 2 ) );
123 const QgsCircle searchCircle = QgsCircle( firstCellMidpoint, mSearchRadius );
124 mSearchGeometry = QgsGeometry( searchCircle.toPolygon() );
125
126 return true;
127}
128
129QVariantMap QgsLineDensityAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
130{
132
133 const QStringList weightName = QStringList( mWeightField );
134 const QgsFields attrFields = mSource->fields();
135
137 r.setSubsetOfAttributes( weightName, attrFields );
138 QgsFeatureIterator fit = mSource->getFeatures( r );
139 QgsFeature f;
140
141 while ( fit.nextFeature( f ) )
142 {
143 mIndex.addFeature( f, QgsFeatureSink::FastInsert );
144
145 //only populate hash if weight field is given
146 if ( !mWeightField.isEmpty() )
147 {
148 const double analysisWeight = f.attribute( mWeightField ).toDouble();
149 mFeatureWeights.insert( f.id(), analysisWeight );
150 }
151 }
152
153 QString creationOptions = parameterAsString( parameters, QStringLiteral( "CREATION_OPTIONS" ), context ).trimmed();
154 // handle backwards compatibility parameter CREATE_OPTIONS
155 const QString optionsString = parameterAsString( parameters, QStringLiteral( "CREATE_OPTIONS" ), context );
156 if ( !optionsString.isEmpty() )
157 creationOptions = optionsString;
158
159 const QString outputFile = parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context );
160 const QFileInfo fi( outputFile );
161 const QString outputFormat = QgsRasterFileWriter::driverForExtension( fi.suffix() );
162
163 // round up width and height to the nearest integer as GDAL does (e.g. in gdal_rasterize)
164 // see https://github.com/qgis/QGIS/issues/43547
165 const int rows = static_cast<int>( 0.5 + mExtent.height() / mPixelSize );
166 const int cols = static_cast<int>( 0.5 + mExtent.width() / mPixelSize );
167
168 //build new raster extent based on number of columns and cellsize
169 //this prevents output cellsize being calculated too small
170 const QgsRectangle rasterExtent = QgsRectangle( mExtent.xMinimum(), mExtent.yMaximum() - ( rows * mPixelSize ), mExtent.xMinimum() + ( cols * mPixelSize ), mExtent.yMaximum() );
171
172 QgsRasterFileWriter writer = QgsRasterFileWriter( outputFile );
173 writer.setOutputProviderKey( QStringLiteral( "gdal" ) );
174 writer.setOutputFormat( outputFormat );
175 if ( !creationOptions.isEmpty() )
176 {
177 writer.setCreationOptions( creationOptions.split( '|' ) );
178 }
179
180 std::unique_ptr<QgsRasterDataProvider> provider( writer.createOneBandRaster( Qgis::DataType::Float32, cols, rows, rasterExtent, mCrs ) );
181 if ( !provider )
182 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
183 if ( !provider->isValid() )
184 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
185
186 provider->setNoDataValue( 1, -9999 );
187
188 const qgssize totalCellcnt = static_cast<qgssize>( rows ) * cols;
189 int cellcnt = 0;
190
191 auto rasterDataLine = std::make_unique<QgsRasterBlock>( Qgis::DataType::Float32, cols, 1 );
192
193 for ( int row = 0; row < rows; row++ )
194 {
195 for ( int col = 0; col < cols; col++ )
196 {
197 if ( feedback->isCanceled() )
198 {
199 break;
200 }
201
202 if ( col > 0 )
203 mSearchGeometry.translate( mPixelSize, 0 );
204
205 const QList<QgsFeatureId> fids = mIndex.intersects( mSearchGeometry.boundingBox() );
206
207 if ( !fids.isEmpty() )
208 {
209 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( mSearchGeometry.constGet() ) );
210 engine->prepareGeometry();
211
212 double absDensity = 0;
213 for ( const QgsFeatureId id : fids )
214 {
215 const QgsGeometry lineGeom = mIndex.geometry( id );
216
217 if ( engine->intersects( lineGeom.constGet() ) )
218 {
219 double analysisLineLength = 0;
220 try
221 {
222 analysisLineLength = mDa.measureLength( QgsGeometry( engine->intersection( mIndex.geometry( id ).constGet() ) ) );
223 }
224 catch ( QgsCsException & )
225 {
226 throw QgsProcessingException( QObject::tr( "An error occurred while calculating feature length" ) );
227 }
228
229 double weight = 1;
230
231 if ( !mWeightField.isEmpty() )
232 {
233 weight = mFeatureWeights.value( id );
234 }
235
236 absDensity += ( analysisLineLength * weight );
237 }
238 }
239
240 double lineDensity = 0;
241 if ( absDensity > 0 )
242 {
243 //only calculate ellipsoidal area if abs density is greater 0
244 double analysisSearchGeometryArea = 0;
245 try
246 {
247 analysisSearchGeometryArea = mDa.measureArea( mSearchGeometry );
248 }
249 catch ( QgsCsException & )
250 {
251 throw QgsProcessingException( QObject::tr( "An error occurred while calculating feature area" ) );
252 }
253
254 lineDensity = absDensity / analysisSearchGeometryArea;
255 }
256 rasterDataLine->setValue( 0, col, lineDensity );
257 }
258 else
259 {
260 //no lines found in search radius
261 rasterDataLine->setValue( 0, col, 0.0 );
262 }
263
264 feedback->setProgress( static_cast<double>( cellcnt ) / static_cast<double>( totalCellcnt ) * 100 );
265 cellcnt++;
266 }
267 if ( !provider->writeBlock( rasterDataLine.get(), 1, 0, row ) )
268 {
269 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( provider->error().summary() ) );
270 }
271
272 //'carriage return and newline' for search geometry
273 mSearchGeometry.translate( ( cols - 1 ) * -mPixelSize, -mPixelSize );
274 }
275
276 QVariantMap outputs;
277 outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
278 return outputs;
279}
280
281
@ VectorLine
Vector line layers.
Definition qgis.h:3535
@ Numeric
Accepts numeric fields.
Definition qgis.h:3818
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
Definition qgis.h:3621
@ Float32
Thirty two bit floating point (float).
Definition qgis.h:380
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
Definition qgis.h:3630
@ Hidden
Parameter is hidden and should not be shown to users.
Definition qgis.h:3764
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Definition qgis.h:3763
Circle geometry type.
Definition qgscircle.h:44
Custom exception class for Coordinate Reference System related exceptions.
A general purpose distance and area calculator, capable of performing ellipsoid based calculations.
virtual QgsPolygon * toPolygon(unsigned int segments=36) const
Returns a segmented polygon.
Wrapper for iterator of features from vector data provider or vector layer.
bool nextFeature(QgsFeature &f)
Fetch next feature and stores in f, returns true on success.
Wraps a request for features to a vector layer (or directly its vector data provider).
QgsFeatureRequest & setSubsetOfAttributes(const QgsAttributeList &attrs)
Set a subset of attributes that will be fetched.
@ 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:58
QgsFeatureId id
Definition qgsfeature.h:66
Q_INVOKABLE QVariant attribute(const QString &name) const
Lookup attribute value by attribute name.
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
void setProgress(double progress)
Sets the current progress for the feedback object.
Definition qgsfeedback.h:61
Container of fields for a vector layer.
Definition qgsfields.h:46
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.
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...
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
QString ellipsoid() const
Returns the ellipsoid to use for distance and area calculations.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
A double numeric parameter for distance values.
An input feature source (such as vector layers) parameter for processing algorithms.
A vector layer or feature source field parameter for processing algorithms.
A raster layer destination parameter, for specifying the destination path for a raster layer created ...
The raster file writer which allows you to save a raster to a new file.
static QString driverForExtension(const QString &extension)
Returns the GDAL driver name for a specified file extension.
void setOutputProviderKey(const QString &key)
Sets the name of the data provider for the raster output.
void setCreationOptions(const QStringList &options)
Sets a list of data source creation options to use when creating the output raster file.
void setOutputFormat(const QString &format)
Sets the output format.
QgsRasterDataProvider * createOneBandRaster(Qgis::DataType dataType, int width, int height, const QgsRectangle &extent, const QgsCoordinateReferenceSystem &crs) SIP_FACTORY
Create a raster file with one band without initializing the pixel data.
A rectangle specified with double values.
A spatial index for QgsFeature objects.
@ FlagStoreFeatureGeometries
Indicates that the spatial index should also store feature geometries. This requires more memory,...
unsigned long long qgssize
Qgssize is used instead of size_t, because size_t is stdlib type, unknown by SIP, and it would be har...
Definition qgis.h:7142
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features