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