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