26using namespace Qt::StringLiterals;
30QString QgsLineDensityAlgorithm::name()
const
32 return u
"linedensity"_s;
35QString QgsLineDensityAlgorithm::displayName()
const
37 return QObject::tr(
"Line density" );
40QStringList QgsLineDensityAlgorithm::tags()
const
42 return QObject::tr(
"density,kernel,line,line density,interpolation,weight" ).split(
',' );
45QString QgsLineDensityAlgorithm::group()
const
47 return QObject::tr(
"Interpolation" );
50QString QgsLineDensityAlgorithm::groupId()
const
52 return u
"interpolation"_s;
55void QgsLineDensityAlgorithm::initAlgorithm(
const QVariantMap & )
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 } } ) } } ) );
67 addParameter( createOptsParam.release() );
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 } } ) } } ) );
72 addParameter( creationOptsParam.release() );
77QString QgsLineDensityAlgorithm::shortHelpString()
const
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."
93QString QgsLineDensityAlgorithm::shortDescription()
const
96 "Calculates a density measure of linear features "
97 "which is obtained in a circular neighborhood within each raster cell."
101QgsLineDensityAlgorithm *QgsLineDensityAlgorithm::createInstance()
const
103 return new QgsLineDensityAlgorithm();
108 Q_UNUSED( feedback );
109 mSource.reset( parameterAsSource( parameters, u
"INPUT"_s, context ) );
113 mWeightField = parameterAsString( parameters, u
"WEIGHT"_s, context );
115 mPixelSize = parameterAsDouble( parameters, u
"PIXEL_SIZE"_s, context );
117 mSearchRadius = parameterAsDouble( parameters, u
"RADIUS"_s, context );
118 if ( mSearchRadius < 0.5 * mPixelSize * std::sqrt( 2 ) )
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."
126 mExtent = mSource->sourceExtent();
127 mCrs = mSource->sourceCrs();
133 const QgsPoint firstCellMidpoint =
QgsPoint( mExtent.xMinimum() + ( mPixelSize / 2 ), mExtent.yMaximum() - ( mPixelSize / 2 ) );
144 const QStringList weightName = QStringList( mWeightField );
145 const QgsFields attrFields = mSource->fields();
157 if ( !mWeightField.isEmpty() )
159 const double analysisWeight = f.
attribute( mWeightField ).toDouble();
160 mFeatureWeights.insert( f.
id(), analysisWeight );
164 QString creationOptions = parameterAsString( parameters, u
"CREATION_OPTIONS"_s, context ).trimmed();
166 const QString optionsString = parameterAsString( parameters, u
"CREATE_OPTIONS"_s, context );
167 if ( !optionsString.isEmpty() )
168 creationOptions = optionsString;
170 const QString outputFile = parameterAsOutputLayer( parameters, u
"OUTPUT"_s, context );
171 const QString outputFormat = parameterAsOutputRasterFormat( parameters, u
"OUTPUT"_s, context );
175 const int rows =
static_cast<int>( 0.5 + mExtent.height() / mPixelSize );
176 const int cols =
static_cast<int>( 0.5 + mExtent.width() / mPixelSize );
180 const QgsRectangle rasterExtent =
QgsRectangle( mExtent.xMinimum(), mExtent.yMaximum() - ( rows * mPixelSize ), mExtent.xMinimum() + ( cols * mPixelSize ), mExtent.yMaximum() );
185 if ( !creationOptions.isEmpty() )
193 if ( !provider->isValid() )
196 provider->setNoDataValue( 1, -9999 );
198 const bool hasReportsDuringClose = provider->hasReportsDuringClose();
199 const double maxProgressDuringBlockWriting = hasReportsDuringClose ? 50.0 : 100.0;
206 for (
int row = 0; row < rows; row++ )
208 for (
int col = 0; col < cols; col++ )
216 mSearchGeometry.translate( mPixelSize, 0 );
218 const QList<QgsFeatureId> fids = mIndex.intersects( mSearchGeometry.boundingBox() );
220 if ( !fids.isEmpty() )
223 engine->prepareGeometry();
225 double absDensity = 0;
228 const QgsGeometry lineGeom = mIndex.geometry(
id );
230 if ( engine->intersects( lineGeom.
constGet() ) )
232 double analysisLineLength = 0;
235 analysisLineLength = mDa.measureLength(
QgsGeometry( engine->intersection( mIndex.geometry(
id ).constGet() ) ) );
244 if ( !mWeightField.isEmpty() )
246 weight = mFeatureWeights.value(
id );
249 absDensity += ( analysisLineLength * weight );
253 double lineDensity = 0;
254 if ( absDensity > 0 )
257 double analysisSearchGeometryArea = 0;
260 analysisSearchGeometryArea = mDa.measureArea( mSearchGeometry );
267 lineDensity = absDensity / analysisSearchGeometryArea;
269 rasterDataLine->setValue( 0, col, lineDensity );
274 rasterDataLine->setValue( 0, col, 0.0 );
277 feedback->
setProgress(
static_cast<double>( cellcnt ) /
static_cast<double>( totalCellcnt ) * maxProgressDuringBlockWriting );
280 if ( !provider->writeBlock( rasterDataLine.get(), 1, 0, row ) )
282 throw QgsProcessingException( QObject::tr(
"Could not write raster block: %1" ).arg( provider->error().summary() ) );
286 mSearchGeometry.translate( ( cols - 1 ) * -mPixelSize, -mPixelSize );
289 if ( hasReportsDuringClose )
292 if ( !provider->closeWithProgress( scaledFeedback.get() ) )
301 outputs.insert( u
"OUTPUT"_s, outputFile );
@ VectorLine
Vector line layers.
@ Numeric
Accepts numeric fields.
@ RespectsEllipsoid
Algorithm respects the context's ellipsoid settings, and uses ellipsoidal based measurements.
@ Float32
Thirty two bit floating point (float).
QFlags< ProcessingAlgorithmDocumentationFlag > ProcessingAlgorithmDocumentationFlags
Flags describing algorithm behavior for documentation purposes.
@ 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.
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...
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.
void setProgress(double progress)
Sets the current progress for the feedback object.
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.
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.
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...
qint64 QgsFeatureId
64 bit feature ids negative numbers are used for uncommitted/newly added features