31using namespace Qt::StringLiterals;
70 QList< int > temporalBands;
71 switch ( temporalProperties->
mode() )
85 temporalBands << temporalProperties->
bandNumber();
90 if ( temporalBands.empty() )
96 switch ( elevationProperties->
mode() )
100 return temporalBands.at( 0 );
105 int currentMatchingBand = -1;
108 const QMap<int, QgsDoubleRange> rangePerBand = elevationProperties->
fixedRangePerBand();
109 for (
int band : temporalBands )
112 if ( rangeForBand.
overlaps( elevationRange ) )
119 currentMatchingBand = band;
120 currentMatchingRange = rangeForBand;
124 return currentMatchingBand;
136 lowerProperty.
prepare( context );
137 upperProperty.
prepare( context );
139 int currentMatchingBand = -1;
143 for (
int band : temporalBands )
150 const double lower = lowerProperty.
valueAsDouble( context, 0, &ok );
153 const double upper = upperProperty.
valueAsDouble( context, 0, &ok );
158 if ( bandRange.
overlaps( elevationRange ) )
164 currentMatchingBand = band;
165 currentMatchingRange = bandRange;
170 return currentMatchingBand;
180 min = std::numeric_limits<double>::quiet_NaN();
181 max = std::numeric_limits<double>::quiet_NaN();
195 switch ( provider->
dataType( band ) )
205 myRasterBandStats.
minimumValue = std::numeric_limits<int8_t>::lowest();
206 myRasterBandStats.
maximumValue = std::numeric_limits<int8_t>::max();
212 myRasterBandStats.
maximumValue = std::numeric_limits<uint16_t>::max();
218 myRasterBandStats.
maximumValue = std::numeric_limits<uint32_t>::max();
224 myRasterBandStats.
minimumValue = std::numeric_limits<int16_t>::lowest();
225 myRasterBandStats.
maximumValue = std::numeric_limits<int16_t>::max();
231 myRasterBandStats.
minimumValue = std::numeric_limits<int32_t>::lowest();
232 myRasterBandStats.
maximumValue = std::numeric_limits<int32_t>::max();
238 myRasterBandStats.
minimumValue = std::numeric_limits<float_t>::lowest();
239 myRasterBandStats.
maximumValue = std::numeric_limits<float_t>::max();
245 myRasterBandStats.
minimumValue = std::numeric_limits<double_t>::lowest();
246 myRasterBandStats.
maximumValue = std::numeric_limits<double_t>::max();
271 QgsDebugMsgLevel( u
"myLower = %1 myUpper = %2"_s.arg( myLower ).arg( myUpper ), 4 );
272 provider->
cumulativeCut( band, myLower, myUpper, min, max, extent, sampleSize );
274 QgsDebugMsgLevel( u
"band = %1 min = %2 max = %3"_s.arg( band ).arg( min ).arg( max ), 4 );
285 const double absPixelSizeY { std::abs( pixelSizeY ) };
286 const double minX { origin.
x() + std::floor( ( extent.
xMinimum() - origin.
x() ) / pixelSizeX ) * pixelSizeX };
287 const double minY { origin.
y() + std::floor( ( extent.
yMinimum() - origin.
y() ) / absPixelSizeY ) * absPixelSizeY };
288 const double maxX { origin.
x() + std::ceil( ( extent.
xMaximum() - origin.
x() ) / pixelSizeX ) * pixelSizeX };
289 const double maxY { origin.
y() + std::ceil( ( extent.
yMaximum() - origin.
y() ) / absPixelSizeY ) * absPixelSizeY };
295 QList<QgsRasterReliefColor> resultList;
297 if ( !provider || !provider->
isValid() || band < 1 || band > provider->
bandCount() )
305 double frequency[252] = { 0 };
316 std::unique_ptr<QgsRasterBlock> block;
318 bool isNoData =
false;
319 while ( iter.
readNextRasterPart( band, iterCols, iterRows, block, iterLeft, iterTop ) )
321 for (
int row = 0; row < iterRows; ++row )
323 for (
int col = 0; col < iterCols; ++col )
325 const double elevation = block->valueAndNoData( row, col, isNoData );
329 int elevationClass = frequencyClassForElevation( elevation, stats.
minimumValue, frequencyClassRange );
330 elevationClass = std::max( std::min( elevationClass, 251 ), 0 );
331 frequency[elevationClass] += 1.0;
337 for (
int i = 0; i < 252; ++i )
339 frequency[i] = std::log10( frequency[i] );
343 QList<int> classBreaks;
344 classBreaks.append( 0 );
345 classBreaks.append( 28 );
346 classBreaks.append( 56 );
347 classBreaks.append( 84 );
348 classBreaks.append( 112 );
349 classBreaks.append( 140 );
350 classBreaks.append( 168 );
351 classBreaks.append( 196 );
352 classBreaks.append( 224 );
353 classBreaks.append( 252 );
355 for (
int i = 0; i < 10; ++i )
357 optimiseClassBreaks( classBreaks, frequency );
362 for (
int breakValue : std::as_const( classBreaks ) )
369 QVector<QColor> colorList;
370 colorList.reserve( 9 );
371 colorList.push_back( QColor( 7, 165, 144 ) );
372 colorList.push_back( QColor( 12, 221, 162 ) );
373 colorList.push_back( QColor( 33, 252, 183 ) );
374 colorList.push_back( QColor( 247, 252, 152 ) );
375 colorList.push_back( QColor( 252, 196, 8 ) );
376 colorList.push_back( QColor( 252, 166, 15 ) );
377 colorList.push_back( QColor( 175, 101, 15 ) );
378 colorList.push_back( QColor( 255, 133, 92 ) );
379 colorList.push_back( QColor( 204, 204, 204 ) );
381 resultList.reserve( classBreaks.size() );
382 for (
int i = 1; i < classBreaks.size(); ++i )
384 const double minElevation = stats.
minimumValue + classBreaks[i - 1] * frequencyClassRange;
385 const double maxElevation = stats.
minimumValue + classBreaks[i] * frequencyClassRange;
386 resultList.push_back(
QgsRasterReliefColor( colorList.at( i - 1 ), minElevation, maxElevation ) );
392int QgsRasterLayerUtils::frequencyClassForElevation(
double elevation,
double minElevation,
double elevationClassRange )
394 return ( elevation - minElevation ) / elevationClassRange;
397void QgsRasterLayerUtils::optimiseClassBreaks( QList<int> &breaks,
double *frequencies )
399 if ( breaks.empty() )
402 const qsizetype nClasses = breaks.size() - 1;
403 std::vector< double > a( nClasses );
404 std::vector< double > b( nClasses );
406 for (
int i = 0; i < nClasses; ++i )
409 QList<QPair<int, double>> regressionInput;
410 regressionInput.reserve( breaks.at( i + 1 ) - breaks.at( i ) );
411 for (
int j = breaks.at( i ); j < breaks.at( i + 1 ); ++j )
413 regressionInput.push_back( qMakePair( j, frequencies[j] ) );
416 double aParam, bParam;
417 if ( !regressionInput.isEmpty() && calculateRegression( regressionInput, aParam, bParam ) )
430 for (
int i = 1; i < nClasses; ++i )
432 if ( breaks[i] == breaks[i - 1] )
443 int newX =
static_cast< int >( ( b[i - 1] - b[i] ) / ( a[i] - a[i - 1] ) );
445 if ( newX <= breaks[i - 1] )
447 newX = breaks[i - 1];
449 else if ( i < nClasses - 1 && newX >= breaks[i + 1] )
451 newX = breaks[i + 1];
459bool QgsRasterLayerUtils::calculateRegression(
const QList<QPair<int, double> > &input,
double &a,
double &b )
464 QList<QPair<int, double>>::const_iterator inputIt = input.constBegin();
465 for ( ; inputIt != input.constEnd(); ++inputIt )
467 xSum += inputIt->first;
468 ySum += inputIt->second;
470 xMean = xSum / input.size();
471 yMean = ySum / input.size();
473 double sumCounter = 0;
474 double sumDenominator = 0;
475 inputIt = input.constBegin();
476 for ( ; inputIt != input.constEnd(); ++inputIt )
478 sumCounter += ( ( inputIt->first - xMean ) * ( inputIt->second - yMean ) );
479 sumDenominator += ( ( inputIt->first - xMean ) * ( inputIt->first - xMean ) );
482 a = sumCounter / sumDenominator;
483 b = yMean - a * xMean;
RasterRangeLimit
Describes the limits used to compute raster ranges (min/max values).
@ CumulativeCut
Range is [ min + cumulativeCutLower() * (max - min), min + cumulativeCutUpper() * (max - min) ].
@ StdDev
Range is [ mean - stdDevFactor() * stddev, mean + stdDevFactor() * stddev ].
@ MinimumMaximum
Real min-max values.
@ FixedRangePerBand
Layer has a fixed (manually specified) elevation range per band.
@ FixedElevationRange
Layer has a fixed elevation range.
@ RepresentsElevationSurface
Pixel values represent an elevation surface.
@ DynamicRangePerBand
Layer has a elevation range per band, calculated dynamically from an expression.
@ RepresentsTemporalValues
Pixel values represent an datetime.
@ RedrawLayerOnly
Redraw the layer when temporal range changes, but don't apply any filtering. Useful when raster symbo...
@ FixedRangePerBand
Layer has a fixed temporal range per band.
@ TemporalRangeFromDataProvider
Mode when raster layer delegates temporal range handling to the dataprovider.
@ FixedTemporalRange
Mode when temporal properties have fixed start and end datetimes.
@ FixedDateTime
Layer has a fixed date time instant.
@ StdDev
Standard deviation.
@ NoStatistic
No statistic.
@ Float32
Thirty two bit floating point (float).
@ CFloat64
Complex Float64.
@ Int16
Sixteen bit signed integer (qint16).
@ ARGB32_Premultiplied
Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32_Premultiplied.
@ Int8
Eight bit signed integer (qint8) (added in QGIS 3.30).
@ UInt16
Sixteen bit unsigned integer (quint16).
@ Byte
Eight bit unsigned integer (quint8).
@ UnknownDataType
Unknown or unspecified type.
@ ARGB32
Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32.
@ Int32
Thirty two bit signed integer (qint32).
@ Float64
Sixty four bit floating point (double).
@ CFloat32
Complex Float32.
@ UInt32
Thirty two bit unsigned integer (quint32).
virtual bool isValid() const =0
Returns true if this is a valid layer.
QgsRange which stores a range of double values.
bool isInfinite() const
Returns true if the range consists of all possible values.
Single scope for storing variables and functions for use within a QgsExpressionContext.
void setVariable(const QString &name, const QVariant &value, bool isStatic=false)
Convenience method for setting a variable in the context scope by name name and value.
static QList< QgsExpressionContextScope * > globalProjectLayerScopes(const QgsMapLayer *layer)
Creates a list of three scopes: global, layer's project and layer.
Expression contexts are used to encapsulate the parameters around which a QgsExpression should be eva...
void appendScope(QgsExpressionContextScope *scope)
Appends a scope to the end of the context.
void appendScopes(const QList< QgsExpressionContextScope * > &scopes)
Appends a list of scopes to the end of the context.
QgsPropertyCollection & dataDefinedProperties()
Returns a reference to the object's property collection, used for data defined overrides.
@ RasterPerBandUpperElevation
Upper elevation for each raster band.
@ RasterPerBandLowerElevation
Lower elevation for each raster band.
QgsProperty property(int key) const final
Returns a matching property from the collection, if one exists.
A store for object properties.
double valueAsDouble(const QgsExpressionContext &context, double defaultValue=0.0, bool *ok=nullptr) const
Calculates the current value of the property and interprets it as a double.
bool prepare(const QgsExpressionContext &context=QgsExpressionContext()) const
Prepares the property against a specified expression context.
bool includeUpper() const
Returns true if the upper bound is inclusive, or false if the upper bound is exclusive.
bool overlaps(const QgsRange< T > &other) const
Returns true if this range overlaps another range.
T upper() const
Returns the upper bound of the range.
The RasterBandStats struct is a container for statistics about a single raster band.
double mean
The mean cell value for the band. NO_DATA values are excluded.
double stdDev
The standard deviation of the cell values.
double minimumValue
The minimum cell value in the raster band.
Qgis::RasterBandStatistics statsGathered
Collected statistics.
double maximumValue
The maximum cell value in the raster band.
Base class for raster data providers.
QgsRectangle extent() const override=0
Returns the extent of the layer.
Qgis::DataType dataType(int bandNo) const override=0
Returns data type for the band specified by number.
virtual QString bandDescription(int bandNumber)
Returns the description for band bandNumber, or an empty string if the band is not valid or has not d...
virtual void cumulativeCut(int bandNo, double lowerCount, double upperCount, double &lowerValue, double &upperValue, const QgsRectangle &extent=QgsRectangle(), int sampleSize=0)
Find values for cumulative pixel count cut.
virtual int xSize() const
Gets raster size.
Q_DECL_DEPRECATED QgsRasterBandStats bandStatistics(int bandNo, int stats, const QgsRectangle &extent=QgsRectangle(), int sampleSize=0, QgsRasterBlockFeedback *feedback=nullptr)
Returns the band statistics.
virtual int bandCount() const =0
Gets number of bands.
QString displayBandName(int bandNumber) const
Generates a friendly, descriptive name for the specified bandNumber.
virtual int ySize() const
Iterator for sequentially processing raster cells.
bool readNextRasterPart(int bandNumber, int &nCols, int &nRows, QgsRasterBlock **block, int &topLeftCol, int &topLeftRow)
Fetches next part of raster data, caller takes ownership of the block and caller should delete the bl...
void startRasterRead(int bandNumber, qgssize nCols, qgssize nRows, const QgsRectangle &extent, QgsRasterBlockFeedback *feedback=nullptr)
Start reading of raster band.
Raster layer specific subclass of QgsMapLayerElevationProperties.
Qgis::RasterElevationMode mode() const
Returns the elevation mode.
bool hasElevation() const override
Returns true if the layer has an elevation or z component.
int bandForElevationRange(QgsRasterLayer *layer, const QgsDoubleRange &range) const
Returns the band corresponding to the specified range.
QMap< int, QgsDoubleRange > fixedRangePerBand() const
Returns the fixed elevation range for each band.
Implementation of map layer temporal properties for raster layers.
QList< int > filteredBandsForTemporalRange(QgsRasterLayer *layer, const QgsDateTimeRange &range) const
Returns a filtered list of bands which match the specified range.
Qgis::RasterTemporalMode mode() const
Returns the temporal properties mode.
int bandForTemporalRange(QgsRasterLayer *layer, const QgsDateTimeRange &range) const
Returns the band corresponding to the specified range.
int bandNumber() const
Returns the band number from which temporal values should be taken.
static void computeMinMax(QgsRasterDataProvider *provider, int band, const QgsRasterMinMaxOrigin &mmo, Qgis::RasterRangeLimit limits, const QgsRectangle &extent, int sampleSize, double &min, double &max)
Compute the min max values for provider along band according to MinMaxOrigin parameters mmo and exten...
static int renderedBandForElevationAndTemporalRange(QgsRasterLayer *layer, const QgsDateTimeRange &temporalRange, const QgsDoubleRange &elevationRange, bool &matched)
Given a raster layer, returns the band which should be used for rendering the layer for a specified t...
static QList< QgsRasterReliefColor > calculateOptimizedReliefClasses(QgsRasterDataProvider *provider, int band)
Calculates optimized relief class breaks according with the method of Buenzli (2011) using an iterati...
static QgsRectangle alignRasterExtent(const QgsRectangle &extent, const QgsPointXY &origin, double pixelSizeX, double pixelSizeY)
Returns a new extent that includes the given extent with corners coordinates aligned to the pixel gri...
Represents a raster layer.
QgsMapLayerTemporalProperties * temporalProperties() override
Returns the layer's temporal properties.
QgsRasterDataProvider * dataProvider() override
Returns the source data provider.
QgsMapLayerElevationProperties * elevationProperties() override
Returns the layer's elevation properties.
Describes the origin of minimum and maximum values in a raster.
double cumulativeCutLower() const
Returns the lower bound of cumulative cut method (between 0 and 1).
double stdDevFactor() const
Returns the factor f so that the min/max range is [ mean - f * stddev , mean + f * stddev ].
double cumulativeCutUpper() const
Returns the upper bound of cumulative cut method (between 0 and 1).
Defines elevation range and color for raster relief coloring.
A rectangle specified with double values.
bool isActive() const
Returns true if the temporal property is active.
bool isInfinite() const
Returns true if the range consists of all possible values.
#define BUILTIN_UNREACHABLE
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
#define QgsDebugMsgLevel(str, level)
QgsTemporalRange< QDateTime > QgsDateTimeRange
QgsRange which stores a range of date times.
#define QGIS_CHECK_OTHER_QOBJECT_THREAD_ACCESS(other)