25using namespace Qt::StringLiterals;
29QString QgsZonalHistogramAlgorithm::name()
const
31 return u
"zonalhistogram"_s;
34QString QgsZonalHistogramAlgorithm::displayName()
const
36 return QObject::tr(
"Zonal histogram" );
39QStringList QgsZonalHistogramAlgorithm::tags()
const
41 return QObject::tr(
"raster,unique,values,count,area,statistics" ).split(
',' );
44QString QgsZonalHistogramAlgorithm::group()
const
46 return QObject::tr(
"Raster analysis" );
49QString QgsZonalHistogramAlgorithm::groupId()
const
51 return u
"rasteranalysis"_s;
54void QgsZonalHistogramAlgorithm::initAlgorithm(
const QVariantMap & )
66QString QgsZonalHistogramAlgorithm::shortHelpString()
const
68 return QObject::tr(
"This algorithm appends fields representing counts of each unique value from a raster layer contained within zones defined as polygons." );
71QString QgsZonalHistogramAlgorithm::shortDescription()
const
73 return QObject::tr(
"Appends fields representing counts of each unique value from a raster layer contained within zones defined as polygons." );
76QgsZonalHistogramAlgorithm *QgsZonalHistogramAlgorithm::createInstance()
const
78 return new QgsZonalHistogramAlgorithm();
83 QgsRasterLayer *layer = parameterAsRasterLayer( parameters, u
"INPUT_RASTER"_s, context );
87 mRasterBand = parameterAsInt( parameters, u
"RASTER_BAND"_s, context );
91 mRasterExtent = layer->
extent();
95 mNbCellsXProvider = mRasterInterface->xSize();
96 mNbCellsYProvider = mRasterInterface->ySize();
97 Qgis::DataType dataType = mRasterInterface->dataType( mRasterBand );
108 feedback->
pushWarning( QObject::tr(
"The input raster is a floating-point raster. Such rasters are not suitable for use with zonal histogram algorithm.\n"
109 "Please use Round raster or Reclassify by table tools to reduce number of decimal places or define histogram bins." ) );
118 std::unique_ptr<QgsFeatureSource> zones( parameterAsSource( parameters, u
"INPUT_VECTOR"_s, context ) );
122 const long count = zones->featureCount();
123 const double step = count > 0 ? 100.0 / count : 1;
126 QList<double> uniqueValues;
127 QMap<QgsFeatureId, QHash<double, qgssize>> featuresUniqueValues;
132 if ( zones->sourceCrs() != mCrs )
160 int nCellsX, nCellsY;
162 QgsRasterAnalysisUtils::cellInfoForBBox( mRasterExtent, featureRect, mCellSizeX, mCellSizeY, nCellsX, nCellsY, mNbCellsXProvider, mNbCellsYProvider, rasterBlockExtent );
164 QHash<double, qgssize> fUniqueValues;
165 QgsRasterAnalysisUtils::statisticsFromMiddlePointTest( mRasterInterface.get(), mRasterBand, featureGeometry, nCellsX, nCellsY, mCellSizeX, mCellSizeY, rasterBlockExtent, [&fUniqueValues](
double value,
const QgsPointXY & ) { fUniqueValues[value]++; },
false );
167 if ( fUniqueValues.count() < 1 )
171 QgsRasterAnalysisUtils::statisticsFromPreciseIntersection( mRasterInterface.get(), mRasterBand, featureGeometry, nCellsX, nCellsY, mCellSizeX, mCellSizeY, rasterBlockExtent, [&fUniqueValues](
double value,
double,
const QgsPointXY & ) { fUniqueValues[value]++; },
false );
174 for (
auto it = fUniqueValues.constBegin(); it != fUniqueValues.constEnd(); ++it )
176 if ( uniqueValues.indexOf( it.key() ) == -1 )
178 uniqueValues << it.key();
180 featuresUniqueValues[f.
id()][it.key()] += it.value();
186 std::sort( uniqueValues.begin(), uniqueValues.end() );
188 const QString fieldPrefix = parameterAsString( parameters, u
"COLUMN_PREFIX"_s, context );
190 for (
auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
192 newFields.
append(
QgsField( u
"%1%2"_s.arg( fieldPrefix, mHasNoDataValue && *it == mNodataValue ? u
"NODATA"_s : QString::number( *it ) ), QMetaType::Type::LongLong, QString(), -1, 0 ) );
197 std::unique_ptr<QgsFeatureSink> sink( parameterAsSink( parameters, u
"OUTPUT"_s, context, dest, fields, zones->wkbType(), zones->sourceCrs() ) );
205 const QHash<double, qgssize> fUniqueValues = featuresUniqueValues.value( f.
id() );
206 for (
auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
208 attributes += fUniqueValues.value( *it, 0 );
222 outputs.insert( u
"OUTPUT"_s, dest );
@ VectorPolygon
Vector polygon layers.
DataType
Raster data types.
@ Int16
Sixteen bit signed integer (qint16).
@ UInt16
Sixteen bit unsigned integer (quint16).
@ Byte
Eight bit unsigned integer (quint8).
@ Int32
Thirty two bit signed integer (qint32).
@ UInt32
Thirty two bit unsigned integer (quint32).
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 & setDestinationCrs(const QgsCoordinateReferenceSystem &crs, const QgsCoordinateTransformContext &context)
Sets the destination crs for feature's geometries.
QgsFeatureRequest & setNoAttributes()
Set that no attributes 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...
void setAttributes(const QgsAttributes &attrs)
Sets the feature's attributes.
bool hasGeometry() const
Returns true if the feature has an associated geometry.
void setGeometry(const QgsGeometry &geometry)
Set the feature's geometry.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
A geometry is the spatial representation of a feature.
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
virtual QgsRectangle extent() const
Returns the extent of the layer.
QgsCoordinateReferenceSystem crs
Contains information about the context in which a processing algorithm is executed.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context.
Custom exception class for processing related exceptions.
Base class for providing feedback from a processing algorithm.
virtual void pushWarning(const QString &warning)
Pushes a warning informational message from the algorithm.
A raster band parameter for Processing algorithms.
A feature sink output for processing algorithms.
An input feature source (such as vector layers) parameter for processing algorithms.
A raster layer parameter for processing algorithms.
A string parameter for processing algorithms.
static QgsFields combineFields(const QgsFields &fieldsA, const QgsFields &fieldsB, const QString &fieldsBPrefix=QString())
Combines two field lists, avoiding duplicate field names (in a case-insensitive manner).
QgsRasterDataProvider * clone() const override=0
Clone itself, create deep copy.
virtual bool sourceHasNoDataValue(int bandNo) const
Returns true if source band has no data value.
virtual double sourceNoDataValue(int bandNo) const
Value representing no data value.
Represents a raster layer.
double rasterUnitsPerPixelX() const
Returns the number of raster units per each raster pixel in X axis.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
A rectangle specified with double values.
QgsRectangle intersect(const QgsRectangle &rect) const
Returns the intersection with the given rectangle.