QGIS API Documentation  3.0.2-Girona (307d082)
qgsheatmaprenderer.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsheatmaprenderer.cpp
3  ----------------------
4  begin : November 2014
5  copyright : (C) 2014 Nyall Dawson
6  email : nyall dot dawson at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
16 #include "qgsheatmaprenderer.h"
17 
18 #include "qgssymbol.h"
19 #include "qgssymbollayerutils.h"
20 
21 #include "qgslogger.h"
22 #include "qgsfeature.h"
23 #include "qgsvectorlayer.h"
24 #include "qgssymbollayer.h"
25 #include "qgsogcutils.h"
26 #include "qgscolorramp.h"
27 #include "qgsrendercontext.h"
28 #include "qgspainteffect.h"
29 #include "qgspainteffectregistry.h"
30 
31 #include <QDomDocument>
32 #include <QDomElement>
33 
35  : QgsFeatureRenderer( QStringLiteral( "heatmapRenderer" ) )
36 {
37  mGradientRamp = new QgsGradientColorRamp( QColor( 255, 255, 255 ), QColor( 0, 0, 0 ) );
38 }
39 
41 {
42  delete mGradientRamp;
43 }
44 
45 void QgsHeatmapRenderer::initializeValues( QgsRenderContext &context )
46 {
47  mValues.resize( context.painter()->device()->width() * context.painter()->device()->height() / ( mRenderQuality * mRenderQuality ) );
48  mValues.fill( 0 );
49  mCalculatedMaxValue = 0;
50  mFeaturesRendered = 0;
51  mRadiusPixels = std::round( context.convertToPainterUnits( mRadius, mRadiusUnit, mRadiusMapUnitScale ) / mRenderQuality );
52  mRadiusSquared = mRadiusPixels * mRadiusPixels;
53 }
54 
56 {
57  QgsFeatureRenderer::startRender( context, fields );
58 
59  if ( !context.painter() )
60  {
61  return;
62  }
63 
64  // find out classification attribute index from name
65  mWeightAttrNum = fields.lookupField( mWeightExpressionString );
66  if ( mWeightAttrNum == -1 )
67  {
68  mWeightExpression.reset( new QgsExpression( mWeightExpressionString ) );
69  mWeightExpression->prepare( &context.expressionContext() );
70  }
71 
72  initializeValues( context );
73 }
74 
75 QgsMultiPointXY QgsHeatmapRenderer::convertToMultipoint( const QgsGeometry *geom )
76 {
77  QgsMultiPointXY multiPoint;
78  if ( !geom->isMultipart() )
79  {
80  multiPoint << geom->asPoint();
81  }
82  else
83  {
84  multiPoint = geom->asMultiPoint();
85  }
86 
87  return multiPoint;
88 }
89 
90 bool QgsHeatmapRenderer::renderFeature( QgsFeature &feature, QgsRenderContext &context, int layer, bool selected, bool drawVertexMarker )
91 {
92  Q_UNUSED( layer );
93  Q_UNUSED( selected );
94  Q_UNUSED( drawVertexMarker );
95 
96  if ( !context.painter() )
97  {
98  return false;
99  }
100 
101  if ( !feature.hasGeometry() || feature.geometry().type() != QgsWkbTypes::PointGeometry )
102  {
103  //can only render point type
104  return false;
105  }
106 
107  double weight = 1.0;
108  if ( !mWeightExpressionString.isEmpty() )
109  {
110  QVariant value;
111  if ( mWeightAttrNum == -1 )
112  {
113  Q_ASSERT( mWeightExpression.get() );
114  value = mWeightExpression->evaluate( &context.expressionContext() );
115  }
116  else
117  {
118  QgsAttributes attrs = feature.attributes();
119  value = attrs.value( mWeightAttrNum );
120  }
121  bool ok = false;
122  double evalWeight = value.toDouble( &ok );
123  if ( ok )
124  {
125  weight = evalWeight;
126  }
127  }
128 
129  int width = context.painter()->device()->width() / mRenderQuality;
130  int height = context.painter()->device()->height() / mRenderQuality;
131 
132  //transform geometry if required
133  QgsGeometry geom = feature.geometry();
135  if ( xform.isValid() )
136  {
137  geom.transform( xform );
138  }
139 
140  //convert point to multipoint
141  QgsMultiPointXY multiPoint = convertToMultipoint( &geom );
142 
143  //loop through all points in multipoint
144  for ( QgsMultiPointXY::const_iterator pointIt = multiPoint.constBegin(); pointIt != multiPoint.constEnd(); ++pointIt )
145  {
146  QgsPointXY pixel = context.mapToPixel().transform( *pointIt );
147  int pointX = pixel.x() / mRenderQuality;
148  int pointY = pixel.y() / mRenderQuality;
149  for ( int x = std::max( pointX - mRadiusPixels, 0 ); x < std::min( pointX + mRadiusPixels, width ); ++x )
150  {
151  for ( int y = std::max( pointY - mRadiusPixels, 0 ); y < std::min( pointY + mRadiusPixels, height ); ++y )
152  {
153  int index = y * width + x;
154  if ( index >= mValues.count() )
155  {
156  continue;
157  }
158  double distanceSquared = std::pow( pointX - x, 2.0 ) + std::pow( pointY - y, 2.0 );
159  if ( distanceSquared > mRadiusSquared )
160  {
161  continue;
162  }
163 
164  double score = weight * quarticKernel( std::sqrt( distanceSquared ), mRadiusPixels );
165  double value = mValues.at( index ) + score;
166  if ( value > mCalculatedMaxValue )
167  {
168  mCalculatedMaxValue = value;
169  }
170  mValues[ index ] = value;
171  }
172  }
173  }
174 
175  mFeaturesRendered++;
176 #if 0
177  //TODO - enable progressive rendering
178  if ( mFeaturesRendered % 200 == 0 )
179  {
180  renderImage( context );
181  }
182 #endif
183  return true;
184 }
185 
186 
187 double QgsHeatmapRenderer::uniformKernel( const double distance, const int bandwidth ) const
188 {
189  Q_UNUSED( distance );
190  Q_UNUSED( bandwidth );
191  return 1.0;
192 }
193 
194 double QgsHeatmapRenderer::quarticKernel( const double distance, const int bandwidth ) const
195 {
196  return std::pow( 1. - std::pow( distance / static_cast< double >( bandwidth ), 2 ), 2 );
197 }
198 
199 double QgsHeatmapRenderer::triweightKernel( const double distance, const int bandwidth ) const
200 {
201  return std::pow( 1. - std::pow( distance / static_cast< double >( bandwidth ), 2 ), 3 );
202 }
203 
204 double QgsHeatmapRenderer::epanechnikovKernel( const double distance, const int bandwidth ) const
205 {
206  return ( 1. - std::pow( distance / static_cast< double >( bandwidth ), 2 ) );
207 }
208 
209 double QgsHeatmapRenderer::triangularKernel( const double distance, const int bandwidth ) const
210 {
211  return ( 1. - ( distance / static_cast< double >( bandwidth ) ) );
212 }
213 
215 {
217 
218  renderImage( context );
219  mWeightExpression.reset();
220 }
221 
222 void QgsHeatmapRenderer::renderImage( QgsRenderContext &context )
223 {
224  if ( !context.painter() || !mGradientRamp )
225  {
226  return;
227  }
228 
229  QImage image( context.painter()->device()->width() / mRenderQuality,
230  context.painter()->device()->height() / mRenderQuality,
231  QImage::Format_ARGB32 );
232  image.fill( Qt::transparent );
233 
234  double scaleMax = mExplicitMax > 0 ? mExplicitMax : mCalculatedMaxValue;
235 
236  int idx = 0;
237  double pixVal = 0;
238  QColor pixColor;
239  for ( int heightIndex = 0; heightIndex < image.height(); ++heightIndex )
240  {
241  QRgb *scanLine = reinterpret_cast< QRgb * >( image.scanLine( heightIndex ) );
242  for ( int widthIndex = 0; widthIndex < image.width(); ++widthIndex )
243  {
244  //scale result to fit in the range [0, 1]
245  pixVal = mValues.at( idx ) > 0 ? std::min( ( mValues.at( idx ) / scaleMax ), 1.0 ) : 0;
246 
247  //convert value to color from ramp
248  pixColor = mGradientRamp->color( pixVal );
249 
250  scanLine[widthIndex] = pixColor.rgba();
251  idx++;
252  }
253  }
254 
255  if ( mRenderQuality > 1 )
256  {
257  QImage resized = image.scaled( context.painter()->device()->width(),
258  context.painter()->device()->height() );
259  context.painter()->drawImage( 0, 0, resized );
260  }
261  else
262  {
263  context.painter()->drawImage( 0, 0, image );
264  }
265 }
266 
268 {
269  return QStringLiteral( "[HEATMAP]" );
270 }
271 
273 {
274  QgsHeatmapRenderer *newRenderer = new QgsHeatmapRenderer();
275  if ( mGradientRamp )
276  {
277  newRenderer->setColorRamp( mGradientRamp->clone() );
278  }
279  newRenderer->setRadius( mRadius );
280  newRenderer->setRadiusUnit( mRadiusUnit );
281  newRenderer->setRadiusMapUnitScale( mRadiusMapUnitScale );
282  newRenderer->setMaximumValue( mExplicitMax );
283  newRenderer->setRenderQuality( mRenderQuality );
284  newRenderer->setWeightExpression( mWeightExpressionString );
285  copyRendererData( newRenderer );
286 
287  return newRenderer;
288 }
289 
291 {
292  //we need to expand out the request extent so that it includes points which are up to the heatmap radius outside of the
293  //actual visible extent
294  double extension = context.convertToMapUnits( mRadius, mRadiusUnit, mRadiusMapUnitScale );
295  extent.setXMinimum( extent.xMinimum() - extension );
296  extent.setXMaximum( extent.xMaximum() + extension );
297  extent.setYMinimum( extent.yMinimum() - extension );
298  extent.setYMaximum( extent.yMaximum() + extension );
299 }
300 
301 QgsFeatureRenderer *QgsHeatmapRenderer::create( QDomElement &element, const QgsReadWriteContext &context )
302 {
303  Q_UNUSED( context );
305  r->setRadius( element.attribute( QStringLiteral( "radius" ), QStringLiteral( "50.0" ) ).toFloat() );
306  r->setRadiusUnit( static_cast< QgsUnitTypes::RenderUnit >( element.attribute( QStringLiteral( "radius_unit" ), QStringLiteral( "0" ) ).toInt() ) );
307  r->setRadiusMapUnitScale( QgsSymbolLayerUtils::decodeMapUnitScale( element.attribute( QStringLiteral( "radius_map_unit_scale" ), QString() ) ) );
308  r->setMaximumValue( element.attribute( QStringLiteral( "max_value" ), QStringLiteral( "0.0" ) ).toFloat() );
309  r->setRenderQuality( element.attribute( QStringLiteral( "quality" ), QStringLiteral( "0" ) ).toInt() );
310  r->setWeightExpression( element.attribute( QStringLiteral( "weight_expression" ) ) );
311 
312  QDomElement sourceColorRampElem = element.firstChildElement( QStringLiteral( "colorramp" ) );
313  if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( QStringLiteral( "name" ) ) == QLatin1String( "[source]" ) )
314  {
315  r->setColorRamp( QgsSymbolLayerUtils::loadColorRamp( sourceColorRampElem ) );
316  }
317  return r;
318 }
319 
320 QDomElement QgsHeatmapRenderer::save( QDomDocument &doc, const QgsReadWriteContext &context )
321 {
322  Q_UNUSED( context );
323  QDomElement rendererElem = doc.createElement( RENDERER_TAG_NAME );
324  rendererElem.setAttribute( QStringLiteral( "type" ), QStringLiteral( "heatmapRenderer" ) );
325  rendererElem.setAttribute( QStringLiteral( "radius" ), QString::number( mRadius ) );
326  rendererElem.setAttribute( QStringLiteral( "radius_unit" ), QString::number( mRadiusUnit ) );
327  rendererElem.setAttribute( QStringLiteral( "radius_map_unit_scale" ), QgsSymbolLayerUtils::encodeMapUnitScale( mRadiusMapUnitScale ) );
328  rendererElem.setAttribute( QStringLiteral( "max_value" ), QString::number( mExplicitMax ) );
329  rendererElem.setAttribute( QStringLiteral( "quality" ), QString::number( mRenderQuality ) );
330  rendererElem.setAttribute( QStringLiteral( "weight_expression" ), mWeightExpressionString );
331  if ( mGradientRamp )
332  {
333  QDomElement colorRampElem = QgsSymbolLayerUtils::saveColorRamp( QStringLiteral( "[source]" ), mGradientRamp, doc );
334  rendererElem.appendChild( colorRampElem );
335  }
336  rendererElem.setAttribute( QStringLiteral( "forceraster" ), ( mForceRaster ? QStringLiteral( "1" ) : QStringLiteral( "0" ) ) );
337 
339  mPaintEffect->saveProperties( doc, rendererElem );
340 
341  if ( !mOrderBy.isEmpty() )
342  {
343  QDomElement orderBy = doc.createElement( QStringLiteral( "orderby" ) );
344  mOrderBy.save( orderBy );
345  rendererElem.appendChild( orderBy );
346  }
347  rendererElem.setAttribute( QStringLiteral( "enableorderby" ), ( mOrderByEnabled ? QStringLiteral( "1" ) : QStringLiteral( "0" ) ) );
348 
349  return rendererElem;
350 }
351 
353 {
354  Q_UNUSED( feature );
355  return nullptr;
356 }
357 
359 {
360  return QgsSymbolList();
361 }
362 
364 {
365  QSet<QString> attributes;
366 
367  // mAttrName can contain either attribute name or an expression.
368  // Sometimes it is not possible to distinguish between those two,
369  // e.g. "a - b" can be both a valid attribute name or expression.
370  // Since we do not have access to fields here, try both options.
371  attributes << mWeightExpressionString;
372 
373  QgsExpression testExpr( mWeightExpressionString );
374  if ( !testExpr.hasParserError() )
375  attributes.unite( testExpr.referencedColumns() );
376 
377  return attributes;
378 }
379 
381 {
382  if ( renderer->type() == QLatin1String( "heatmapRenderer" ) )
383  {
384  return dynamic_cast<QgsHeatmapRenderer *>( renderer->clone() );
385  }
386  else
387  {
388  return new QgsHeatmapRenderer();
389  }
390 }
391 
393 {
394  delete mGradientRamp;
395  mGradientRamp = ramp;
396 }
int lookupField(const QString &fieldName) const
Look up field&#39;s index from the field name.
Definition: qgsfields.cpp:299
The class is used as a container of context for various read/write operations on other objects...
double convertToMapUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to map units.
A rectangle specified with double values.
Definition: qgsrectangle.h:39
bool renderFeature(QgsFeature &feature, QgsRenderContext &context, int layer=-1, bool selected=false, bool drawVertexMarker=false) override
Render a feature using this renderer in the given context.
QgsFeatureRequest::OrderBy mOrderBy
Definition: qgsrenderer.h:517
bool isMultipart() const
Returns true if WKB of the geometry is of WKBMulti* type.
QString dump() const override
Returns debug information about this renderer.
void setColorRamp(QgsColorRamp *ramp)
Sets the color ramp to use for shading the heatmap.
void setXMaximum(double x)
Set the maximum x value.
Definition: qgsrectangle.h:94
void modifyRequestExtent(QgsRectangle &extent, QgsRenderContext &context) override
Allows for a renderer to modify the extent of a feature request prior to rendering.
virtual QgsColorRamp * clone() const =0
Creates a clone of the color ramp.
double y
Definition: qgspointxy.h:48
A class to represent a 2D point.
Definition: qgspointxy.h:43
QgsFeatureRequest::OrderBy orderBy() const
Get the order in which features shall be processed by this renderer.
Abstract base class for color ramps.
Definition: qgscolorramp.h:31
static bool isDefaultStack(QgsPaintEffect *effect)
Tests whether a paint effect matches the default effects stack.
static QDomElement saveColorRamp(const QString &name, QgsColorRamp *ramp, QDomDocument &doc)
Encodes a color ramp&#39;s settings to an XML element.
static QString encodeMapUnitScale(const QgsMapUnitScale &mapUnitScale)
Container of fields for a vector layer.
Definition: qgsfields.h:42
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:111
#define RENDERER_TAG_NAME
Definition: qgsrenderer.h:49
void setWeightExpression(const QString &expression)
Sets the expression used for weighting points when generating the heatmap.
QVector< QgsPointXY > QgsMultiPointXY
A collection of QgsPoints that share a common collection of attributes.
Definition: qgsgeometry.h:79
QgsPaintEffect * mPaintEffect
Definition: qgsrenderer.h:501
The feature class encapsulates a single feature including its id, geometry and a list of field/values...
Definition: qgsfeature.h:62
bool hasGeometry() const
Returns true if the feature has an associated geometry.
Definition: qgsfeature.cpp:190
virtual QColor color(double value) const =0
Returns the color corresponding to a specified value.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
QSet< QString > usedAttributes(const QgsRenderContext &context) const override
Return a list of attributes required by this renderer.
static QgsFeatureRenderer * create(QDomElement &element, const QgsReadWriteContext &context)
Creates a new heatmap renderer instance from XML.
QgsPointXY transform(const QgsPointXY &p) const
Transform the point from map (world) coordinates to device coordinates.
QList< QgsSymbol * > QgsSymbolList
Definition: qgsrenderer.h:43
QString type() const
Definition: qgsrenderer.h:126
A renderer which draws points as a live heatmap.
void setRadiusMapUnitScale(const QgsMapUnitScale &scale)
Sets the map unit scale used for the heatmap&#39;s radius.
void setYMinimum(double y)
Set the minimum y value.
Definition: qgsrectangle.h:99
static QgsColorRamp * loadColorRamp(QDomElement &element)
Creates a color ramp from the settings encoded in an XML element.
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context, or an invalid transform is no coordinate tr...
QgsGeometry geometry() const
Returns the geometry associated with this feature.
Definition: qgsfeature.cpp:101
void startRender(QgsRenderContext &context, const QgsFields &fields) override
Must be called when a new render cycle is started.
QgsWkbTypes::GeometryType type() const
Returns type of the geometry as a QgsWkbTypes::GeometryType.
void setRenderQuality(const int quality)
Sets the render quality used for drawing the heatmap.
void setRadiusUnit(const QgsUnitTypes::RenderUnit unit)
Sets the units used for the heatmap&#39;s radius.
double x
Definition: qgspointxy.h:47
OperationResult transform(const QgsCoordinateTransform &ct, QgsCoordinateTransform::TransformDirection direction=QgsCoordinateTransform::ForwardTransform, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:130
QDomElement save(QDomDocument &doc, const QgsReadWriteContext &context) override
store renderer info to XML element
QgsExpressionContext & expressionContext()
Gets the expression context.
void setRadius(const double radius)
Sets the radius for the heatmap.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:115
QgsHeatmapRenderer * clone() const override
Create a deep copy of this renderer.
Contains information about the context of a rendering operation.
double convertToPainterUnits(double size, QgsUnitTypes::RenderUnit unit, const QgsMapUnitScale &scale=QgsMapUnitScale()) const
Converts a size from the specified units to painter units (pixels).
QPainter * painter()
Returns the destination QPainter for the render operation.
const QgsMapToPixel & mapToPixel() const
QgsPointXY asPoint() const
Returns contents of the geometry as a point if wkbType is WKBPoint, otherwise returns [0...
virtual void startRender(QgsRenderContext &context, const QgsFields &fields)
Must be called when a new render cycle is started.
Definition: qgsrenderer.cpp:92
void setYMaximum(double y)
Set the maximum y value.
Definition: qgsrectangle.h:104
void CORE_EXPORT save(QDomElement &elem) const
Serialize to XML.
void stopRender(QgsRenderContext &context) override
Must be called when a render cycle has finished, to allow the renderer to clean up.
virtual void stopRender(QgsRenderContext &context)
Must be called when a render cycle has finished, to allow the renderer to clean up.
static QgsHeatmapRenderer * convertFromRenderer(const QgsFeatureRenderer *renderer)
Class for doing transforms between two map coordinate systems.
void copyRendererData(QgsFeatureRenderer *destRenderer) const
Clones generic renderer data to another renderer.
Definition: qgsrenderer.cpp:48
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:120
static QgsMapUnitScale decodeMapUnitScale(const QString &str)
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:125
QgsSymbolList symbols(QgsRenderContext &context) override
QgsMultiPointXY asMultiPoint() const
Returns contents of the geometry as a multi point if wkbType is WKBMultiPoint, otherwise an empty lis...
A vector of attributes.
Definition: qgsattributes.h:58
Gradient color ramp, which smoothly interpolates between two colors and also supports optional extra ...
Definition: qgscolorramp.h:139
void setMaximumValue(const double value)
Sets the maximum value used for shading the heatmap.
QgsSymbol * symbolForFeature(QgsFeature &feature, QgsRenderContext &context) override
virtual QgsFeatureRenderer * clone() const =0
Create a deep copy of this renderer.
QgsAttributes attributes
Definition: qgsfeature.h:72
void setXMinimum(double x)
Set the minimum x value.
Definition: qgsrectangle.h:89
virtual bool saveProperties(QDomDocument &doc, QDomElement &element) const
Saves the current state of the effect to a DOM element.