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