QGIS API Documentation 3.43.0-Master (e01d6d7c4c0)
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#include "qgscircle.h"
20#include "qgsgeometryengine.h"
21#include "qgsrasterfilewriter.h"
22
24
25QString QgsLineDensityAlgorithm::name() const
26{
27 return QStringLiteral( "linedensity" );
28}
29
30QString QgsLineDensityAlgorithm::displayName() const
31{
32 return QObject::tr( "Line density" );
33}
34
35QStringList QgsLineDensityAlgorithm::tags() const
36{
37 return QObject::tr( "density,kernel,line,line density,interpolation,weight" ).split( ',' );
38}
39
40QString QgsLineDensityAlgorithm::group() const
41{
42 return QObject::tr( "Interpolation" );
43}
44
45QString QgsLineDensityAlgorithm::groupId() const
46{
47 return QStringLiteral( "interpolation" );
48}
49
50void QgsLineDensityAlgorithm::initAlgorithm( const QVariantMap & )
51{
52 addParameter( new QgsProcessingParameterFeatureSource( QStringLiteral( "INPUT" ), QObject::tr( "Input line layer" ), QList<int>() << static_cast<int>( Qgis::ProcessingSourceType::VectorLine ) ) );
53 addParameter( new QgsProcessingParameterField( QStringLiteral( "WEIGHT" ), QObject::tr( "Weight field " ), QVariant(), QStringLiteral( "INPUT" ), Qgis::ProcessingFieldParameterDataType::Numeric, false, true ) );
54 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "RADIUS" ), QObject::tr( "Search radius" ), 10, QStringLiteral( "INPUT" ), false, 0 ) );
55 addParameter( new QgsProcessingParameterDistance( QStringLiteral( "PIXEL_SIZE" ), QObject::tr( "Pixel size" ), 10, QStringLiteral( "INPUT" ), false ) );
56
57 // backwards compatibility parameter
58 // TODO QGIS 4: remove parameter and related logic
59 auto createOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATE_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
60 createOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
61 createOptsParam->setFlags( createOptsParam->flags() | Qgis::ProcessingParameterFlag::Hidden );
62 addParameter( createOptsParam.release() );
63
64 auto creationOptsParam = std::make_unique<QgsProcessingParameterString>( QStringLiteral( "CREATION_OPTIONS" ), QObject::tr( "Creation options" ), QVariant(), false, true );
65 creationOptsParam->setMetadata( QVariantMap( { { QStringLiteral( "widget_wrapper" ), QVariantMap( { { QStringLiteral( "widget_type" ), QStringLiteral( "rasteroptions" ) } } ) } } ) );
66 creationOptsParam->setFlags( creationOptsParam->flags() | Qgis::ProcessingParameterFlag::Advanced );
67 addParameter( creationOptsParam.release() );
68
69 addParameter( new QgsProcessingParameterRasterDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Line density raster" ) ) );
70}
71
72QString QgsLineDensityAlgorithm::shortHelpString() const
73{
74 return QObject::tr( "This algorithm calculates a density measure of linear features "
75 "which is obtained in a circular neighborhood within each raster cell. "
76 "First, the length of the segment of each line that is intersected by the circular neighborhood "
77 "is multiplied with the lines weight factor. In a second step, all length values are summed and "
78 "divided by the area of the circular neighborhood. This process is repeated for all raster cells."
79 );
80}
81
82QString QgsLineDensityAlgorithm::shortDescription() const
83{
84 return QObject::tr( "Calculates a density measure of linear features "
85 "which is obtained in a circular neighborhood within each raster cell." );
86}
87
88QgsLineDensityAlgorithm *QgsLineDensityAlgorithm::createInstance() const
89{
90 return new QgsLineDensityAlgorithm();
91}
92
93bool QgsLineDensityAlgorithm::prepareAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
94{
95 Q_UNUSED( feedback );
96 mSource.reset( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
97 if ( !mSource )
98 throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );
99
100 mWeightField = parameterAsString( parameters, QStringLiteral( "WEIGHT" ), context );
101
102 mPixelSize = parameterAsDouble( parameters, QStringLiteral( "PIXEL_SIZE" ), context );
103
104 mSearchRadius = parameterAsDouble( parameters, QStringLiteral( "RADIUS" ), context );
105 if ( mSearchRadius < 0.5 * mPixelSize * std::sqrt( 2 ) )
106 throw QgsProcessingException( QObject::tr( "Raster cells must be fully contained by the search circle. Therefore, "
107 "the search radius must not be smaller than half of the pixel diagonal." ) );
108
109 mExtent = mSource->sourceExtent();
110 mCrs = mSource->sourceCrs();
111 mDa = QgsDistanceArea();
112 mDa.setEllipsoid( context.ellipsoid() );
113 mDa.setSourceCrs( mCrs, context.transformContext() );
114
115 //get cell midpoint from top left cell
116 const QgsPoint firstCellMidpoint = QgsPoint( mExtent.xMinimum() + ( mPixelSize / 2 ), mExtent.yMaximum() - ( mPixelSize / 2 ) );
117 const QgsCircle searchCircle = QgsCircle( firstCellMidpoint, mSearchRadius );
118 mSearchGeometry = QgsGeometry( searchCircle.toPolygon() );
119
120 return true;
121}
122
123QVariantMap QgsLineDensityAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
124{
126
127 const QStringList weightName = QStringList( mWeightField );
128 const QgsFields attrFields = mSource->fields();
129
131 r.setSubsetOfAttributes( weightName, attrFields );
132 QgsFeatureIterator fit = mSource->getFeatures( r );
133 QgsFeature f;
134
135 while ( fit.nextFeature( f ) )
136 {
137 mIndex.addFeature( f, QgsFeatureSink::FastInsert );
138
139 //only populate hash if weight field is given
140 if ( !mWeightField.isEmpty() )
141 {
142 const double analysisWeight = f.attribute( mWeightField ).toDouble();
143 mFeatureWeights.insert( f.id(), analysisWeight );
144 }
145 }
146
147 QString creationOptions = parameterAsString( parameters, QStringLiteral( "CREATION_OPTIONS" ), context ).trimmed();
148 // handle backwards compatibility parameter CREATE_OPTIONS
149 const QString optionsString = parameterAsString( parameters, QStringLiteral( "CREATE_OPTIONS" ), context );
150 if ( !optionsString.isEmpty() )
151 creationOptions = optionsString;
152
153 const QString outputFile = parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context );
154 const QFileInfo fi( outputFile );
155 const QString outputFormat = QgsRasterFileWriter::driverForExtension( fi.suffix() );
156
157 // round up width and height to the nearest integer as GDAL does (e.g. in gdal_rasterize)
158 // see https://github.com/qgis/QGIS/issues/43547
159 const int rows = static_cast<int>( 0.5 + mExtent.height() / mPixelSize );
160 const int cols = static_cast<int>( 0.5 + mExtent.width() / mPixelSize );
161
162 //build new raster extent based on number of columns and cellsize
163 //this prevents output cellsize being calculated too small
164 const QgsRectangle rasterExtent = QgsRectangle( mExtent.xMinimum(), mExtent.yMaximum() - ( rows * mPixelSize ), mExtent.xMinimum() + ( cols * mPixelSize ), mExtent.yMaximum() );
165
166 QgsRasterFileWriter writer = QgsRasterFileWriter( outputFile );
167 writer.setOutputProviderKey( QStringLiteral( "gdal" ) );
168 writer.setOutputFormat( outputFormat );
169 if ( !creationOptions.isEmpty() )
170 {
171 writer.setCreationOptions( creationOptions.split( '|' ) );
172 }
173
174 std::unique_ptr<QgsRasterDataProvider> provider( writer.createOneBandRaster( Qgis::DataType::Float32, cols, rows, rasterExtent, mCrs ) );
175 if ( !provider )
176 throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
177 if ( !provider->isValid() )
178 throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
179
180 provider->setNoDataValue( 1, -9999 );
181
182 const qgssize totalCellcnt = static_cast<qgssize>( rows ) * cols;
183 int cellcnt = 0;
184
185 auto rasterDataLine = std::make_unique<QgsRasterBlock>( Qgis::DataType::Float32, cols, 1 );
186
187 for ( int row = 0; row < rows; row++ )
188 {
189 for ( int col = 0; col < cols; col++ )
190 {
191 if ( feedback->isCanceled() )
192 {
193 break;
194 }
195
196 if ( col > 0 )
197 mSearchGeometry.translate( mPixelSize, 0 );
198
199 const QList<QgsFeatureId> fids = mIndex.intersects( mSearchGeometry.boundingBox() );
200
201 if ( !fids.isEmpty() )
202 {
203 std::unique_ptr<QgsGeometryEngine> engine( QgsGeometry::createGeometryEngine( mSearchGeometry.constGet() ) );
204 engine->prepareGeometry();
205
206 double absDensity = 0;
207 for ( const QgsFeatureId id : fids )
208 {
209 const QgsGeometry lineGeom = mIndex.geometry( id );
210
211 if ( engine->intersects( lineGeom.constGet() ) )
212 {
213 double analysisLineLength = 0;
214 try
215 {
216 analysisLineLength = mDa.measureLength( QgsGeometry( engine->intersection( mIndex.geometry( id ).constGet() ) ) );
217 }
218 catch ( QgsCsException & )
219 {
220 throw QgsProcessingException( QObject::tr( "An error occurred while calculating feature length" ) );
221 }
222
223 double weight = 1;
224
225 if ( !mWeightField.isEmpty() )
226 {
227 weight = mFeatureWeights.value( id );
228 }
229
230 absDensity += ( analysisLineLength * weight );
231 }
232 }
233
234 double lineDensity = 0;
235 if ( absDensity > 0 )
236 {
237 //only calculate ellipsoidal area if abs density is greater 0
238 double analysisSearchGeometryArea = 0;
239 try
240 {
241 analysisSearchGeometryArea = mDa.measureArea( mSearchGeometry );
242 }
243 catch ( QgsCsException & )
244 {
245 throw QgsProcessingException( QObject::tr( "An error occurred while calculating feature area" ) );
246 }
247
248 lineDensity = absDensity / analysisSearchGeometryArea;
249 }
250 rasterDataLine->setValue( 0, col, lineDensity );
251 }
252 else
253 {
254 //no lines found in search radius
255 rasterDataLine->setValue( 0, col, 0.0 );
256 }
257
258 feedback->setProgress( static_cast<double>( cellcnt ) / static_cast<double>( totalCellcnt ) * 100 );
259 cellcnt++;
260 }
261 if ( !provider->writeBlock( rasterDataLine.get(), 1, 0, row ) )
262 {
263 throw QgsProcessingException( QObject::tr( "Could not write raster block: %1" ).arg( provider->error().summary() ) );
264 }
265
266 //'carriage return and newline' for search geometry
267 mSearchGeometry.translate( ( cols - 1 ) * -mPixelSize, -mPixelSize );
268 }
269
270 QVariantMap outputs;
271 outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
272 return outputs;
273}
274
275
@ VectorLine
Vector line layers.
@ Numeric
Accepts numeric fields.
@ Float32
Thirty two bit floating point (float)
@ Hidden
Parameter is hidden and should not be shown to users.
@ Advanced
Parameter is an advanced parameter which should be hidden from users by default.
Circle geometry type.
Definition qgscircle.h:45
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:6826
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features