KD Chart 2  [rev.2.7]
KDChartPercentLineDiagram_p.cpp
Go to the documentation of this file.
1 /****************************************************************************
2 ** Copyright (C) 2001-2021 Klaralvdalens Datakonsult AB. All rights reserved.
3 **
4 ** This file is part of the KD Chart library.
5 **
6 ** Licensees holding valid commercial KD Chart licenses may use this file in
7 ** accordance with the KD Chart Commercial License Agreement provided with
8 ** the Software.
9 **
10 **
11 ** This file may be distributed and/or modified under the terms of the
12 ** GNU General Public License version 2 and version 3 as published by the
13 ** Free Software Foundation and appearing in the file LICENSE.GPL.txt included.
14 **
15 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
17 **
18 ** Contact info@kdab.com if any conditions of this licensing are not
19 ** clear to you.
20 **
21 **********************************************************************/
22 
23 #include "KDChartPercentLineDiagram_p.h"
24 
25 #include <QModelIndex>
26 
27 #include "KDChartBarDiagram.h"
28 #include "KDChartLineDiagram.h"
29 #include "KDChartTextAttributes.h"
30 #include "KDChartAttributesModel.h"
32 #include "PaintingHelpers_p.h"
33 
34 using namespace KDChart;
35 using namespace std;
36 
37 PercentLineDiagram::PercentLineDiagram( LineDiagram* d )
38  : LineDiagramType( d )
39 {
40 }
41 
42 LineDiagram::LineType PercentLineDiagram::type() const
43 {
44  return LineDiagram::Percent;
45 }
46 
47 const QPair<QPointF, QPointF> PercentLineDiagram::calculateDataBoundaries() const
48 {
49  const qreal xMin = 0.0;
50  qreal xMax = diagram()->model() ? diagram()->model()->rowCount( diagram()->rootIndex() ) : 0;
51  if ( !diagram()->centerDataPoints() && diagram()->model() )
52  xMax -= 1;
53  const qreal yMin = 0.0;
54  const qreal yMax = 100.0;
55 
56  QPointF bottomLeft( QPointF( xMin, yMin ) );
57  QPointF topRight( QPointF( xMax, yMax ) );
58  return QPair<QPointF, QPointF> ( bottomLeft, topRight );
59 }
60 
61 void PercentLineDiagram::paint( PaintContext* ctx )
62 {
63  if ( qFuzzyIsNull( m_private->tension ) ) {
64  paintWithLines( ctx );
65 
66  } else {
67  paintWithSplines( ctx, m_private->tension );
68  }
69 }
70 
71 void PercentLineDiagram::paintWithLines( PaintContext* ctx )
72 {
73  reverseMapper().clear();
74 
75  const int columnCount = compressor().modelDataColumns();
76  const int rowCount = compressor().modelDataRows();
77 
78 // FIXME integrade column index retrieval to compressor:
79  int maxFound = 0;
80 // { // find the last column number that is not hidden
81 // for ( int iColumn = datasetDimension() - 1;
82 // iColumn < columnCount;
83 // iColumn += datasetDimension() )
84 // if ( ! diagram()->isHidden( iColumn ) )
85 // maxFound = iColumn;
86 // }
87  maxFound = columnCount;
88  // ^^^ temp
89  const int lastVisibleColumn = maxFound - 1;
90 
91  LabelPaintCache lpc;
92  LineAttributesInfoList lineList;
93 
94  //FIXME(khz): add LineAttributes::MissingValuesPolicy support for LineDiagram::Stacked and ::Percent
95 
96  qreal maxValue = 100; // always 100%
97  qreal sumValues = 0;
98  QVector <qreal > percentSumValues;
99 
100  //calculate sum of values for each column and store
101  for ( int row = 0; row < rowCount; ++row )
102  {
103  for ( int col = 0; col < columnCount; ++col )
104  {
105  const CartesianDiagramDataCompressor::CachePosition position( row, col );
106  CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
107  const QModelIndex sourceIndex = attributesModel()->mapToSource( point.index );
108  const LineAttributes laCell = diagram()->lineAttributes( sourceIndex );
110  if ( ISNAN( point.value ) && policy == LineAttributes::MissingValuesAreBridged )
111  point.value = interpolateMissingValue( position );
112  if ( point.value > 0 )
113  sumValues += point.value;
114  if ( col == lastVisibleColumn )
115  {
116  percentSumValues << sumValues ;
117  sumValues = 0;
118  }
119  }
120  }
121 
122  QList<QPointF> bottomPoints;
123  bool bFirstDataset = true;
124 
125  for ( int column = 0; column < columnCount; ++column )
126  {
127  //display area can be set by dataset ( == column) and/or by cell
128  LineAttributes laPreviousCell; // by default no area is drawn
129  QModelIndex indexPreviousCell;
130  QList<QPolygonF> areas;
131  QList<QPointF> points;
132 
133  for ( int row = 0; row < rowCount; ++row )
134  {
135  const CartesianDiagramDataCompressor::CachePosition position( row, column );
136  CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
137  const QModelIndex sourceIndex = attributesModel()->mapToSource( point.index );
138  const LineAttributes laCell = diagram()->lineAttributes( sourceIndex );
139  const bool bDisplayCellArea = laCell.displayArea();
140 
141  qreal stackedValues = 0, nextValues = 0, nextKey = 0;
142  for ( int column2 = column;
143  column2 >= 0;//datasetDimension() - 1;
144  column2 -= 1 )//datasetDimension() )
145  {
146  const CartesianDiagramDataCompressor::CachePosition position( row, column2 );
147  CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
148 
150  if ( ISNAN( point.value ) && policy == LineAttributes::MissingValuesAreBridged )
151  point.value = interpolateMissingValue( position );
152 
153  const qreal val = point.value;
154  if ( val > 0 )
155  stackedValues += val;
156  //qDebug() << valueForCell( iRow, iColumn2 );
157  if ( row + 1 < rowCount ) {
158  const CartesianDiagramDataCompressor::CachePosition position( row + 1, column2 );
159  CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
160 
162  if ( ISNAN( point.value ) && policy == LineAttributes::MissingValuesAreBridged )
163  point.value = interpolateMissingValue( position );
164 
165  const qreal val = point.value;
166  if ( val > 0 )
167  nextValues += val;
168  nextKey = point.key;
169  }
170  }
171  if ( percentSumValues.at( row ) != 0 )
172  stackedValues = stackedValues / percentSumValues.at( row ) * maxValue;
173  else
174  stackedValues = 0.0;
175  //qDebug() << stackedValues << endl;
176  QPointF nextPoint = ctx->coordinatePlane()->translate( QPointF( diagram()->centerDataPoints() ? point.key + 0.5 : point.key, stackedValues ) );
177  points << nextPoint;
178 
179  const QPointF ptNorthWest( nextPoint );
180  const QPointF ptSouthWest(
181  bDisplayCellArea
182  ? ( bFirstDataset
183  ? ctx->coordinatePlane()->translate( QPointF( diagram()->centerDataPoints() ? point.key + 0.5 : point.key, 0.0 ) )
184  : bottomPoints.at( row )
185  )
186  : nextPoint );
187  QPointF ptNorthEast;
188  QPointF ptSouthEast;
189 
190  if ( row + 1 < rowCount ) {
191  if ( percentSumValues.at( row + 1 ) != 0 )
192  nextValues = nextValues / percentSumValues.at( row + 1 ) * maxValue;
193  else
194  nextValues = 0.0;
195  QPointF toPoint = ctx->coordinatePlane()->translate( QPointF( diagram()->centerDataPoints() ? nextKey + 0.5 : nextKey, nextValues ) );
196  lineList.append( LineAttributesInfo( sourceIndex, nextPoint, toPoint ) );
197  ptNorthEast = toPoint;
198  ptSouthEast =
199  bDisplayCellArea
200  ? ( bFirstDataset
201  ? ctx->coordinatePlane()->translate( QPointF( diagram()->centerDataPoints() ? nextKey + 0.5 : nextKey, 0.0 ) )
202  : bottomPoints.at( row + 1 )
203  )
204  : toPoint;
205  if ( areas.count() && laCell != laPreviousCell ) {
206  PaintingHelpers::paintAreas( m_private, ctx, indexPreviousCell, areas, laPreviousCell.transparency() );
207  areas.clear();
208  }
209  if ( bDisplayCellArea ) {
210  QPolygonF poly;
211  poly << ptNorthWest << ptNorthEast << ptSouthEast << ptSouthWest;
212  areas << poly;
213  laPreviousCell = laCell;
214  indexPreviousCell = sourceIndex;
215  } else {
216  //qDebug() << "no area shown for row"<<iRow<<" column"<<iColumn;
217  }
218  } else {
219  ptNorthEast = ptNorthWest;
220  ptSouthEast = ptSouthWest;
221  }
222 
223  if ( !ISNAN( point.value ) )
224  {
225  const PositionPoints pts( ptNorthWest, ptNorthEast, ptSouthEast, ptSouthWest );
226  m_private->addLabel( &lpc, sourceIndex, &position, pts, Position::NorthWest,
227  Position::NorthWest, point.value );
228  }
229  }
230  if ( areas.count() ) {
231  PaintingHelpers::paintAreas( m_private, ctx, indexPreviousCell, areas, laPreviousCell.transparency() );
232  areas.clear();
233  }
234  bottomPoints = points;
235  bFirstDataset = false;
236  }
237  PaintingHelpers::paintElements( m_private, ctx, lpc, lineList );
238 }
239 
240 void PercentLineDiagram::paintWithSplines( PaintContext* ctx, qreal tension )
241 {
242  reverseMapper().clear();
243 
244  const int columnCount = compressor().modelDataColumns();
245  const int rowCount = compressor().modelDataRows();
246 
247  Q_ASSERT(dynamic_cast<CartesianCoordinatePlane*>(ctx->coordinatePlane()));
248  const auto plane = static_cast<CartesianCoordinatePlane*>(ctx->coordinatePlane());
249  const auto mainSplineDirection = plane->isHorizontalRangeReversed() ? ReverseSplineDirection : NormalSplineDirection;
250  const auto reverseSplineDirection = plane->isHorizontalRangeReversed() ? NormalSplineDirection : ReverseSplineDirection;
251 
252 // FIXME integrade column index retrieval to compressor:
253  int maxFound = 0;
254 // { // find the last column number that is not hidden
255 // for ( int iColumn = datasetDimension() - 1;
256 // iColumn < columnCount;
257 // iColumn += datasetDimension() )
258 // if ( ! diagram()->isHidden( iColumn ) )
259 // maxFound = iColumn;
260 // }
261  maxFound = columnCount;
262  // ^^^ temp
263  const int lastVisibleColumn = maxFound - 1;
264 
265  LabelPaintCache lpc;
266  LineAttributesInfoList lineList;
267 
268  //FIXME(khz): add LineAttributes::MissingValuesPolicy support for LineDiagram::Stacked and ::Percent
269 
270  qreal maxValue = 100; // always 100%
271  qreal sumValues = 0;
272  QVector <qreal > percentSumValues;
273 
274  //calculate sum of values for each column and store
275  for ( int row = 0; row < rowCount; ++row )
276  {
277  for ( int col = 0; col < columnCount; ++col )
278  {
279  const CartesianDiagramDataCompressor::CachePosition position( row, col );
280  CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
281  const QModelIndex sourceIndex = attributesModel()->mapToSource( point.index );
282  const LineAttributes laCell = diagram()->lineAttributes( sourceIndex );
284  if ( ISNAN( point.value ) && policy == LineAttributes::MissingValuesAreBridged )
285  point.value = interpolateMissingValue( position );
286  if ( point.value > 0 )
287  sumValues += point.value;
288  if ( col == lastVisibleColumn )
289  {
290  percentSumValues << sumValues ;
291  sumValues = 0;
292  }
293  }
294  }
295 
296  for ( int column = 0; column < columnCount; ++column )
297  {
298  CartesianDiagramDataCompressor::CachePosition previousCellPosition;
299 
300  //display area can be set by dataset ( == column) and/or by cell
301  LineAttributes laPreviousCell; // by default no area is drawn
302  QModelIndex indexPreviousCell;
303  QList<QPainterPath> areas;
304 
305  for ( int row = 0; row < rowCount; ++row ) {
306  const CartesianDiagramDataCompressor::CachePosition position( row, column );
307  CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
308  const QModelIndex sourceIndex = attributesModel()->mapToSource( point.index );
309 
310  const LineAttributes laCell = diagram()->lineAttributes( sourceIndex );
311  const bool bDisplayCellArea = laCell.displayArea();
312 
314 
315  if ( ISNAN( point.value ) && policy == LineAttributes::MissingValuesShownAsZero )
316  point.value = 0.0;
317 
318  // TODO: revert back to lambdas when we stop caring about pre-C++11
319  // See the Qt6 port
320 
321  struct valueAtLambda {
322  valueAtLambda( int rowCount, PercentLineDiagram* _this, LineAttributes::MissingValuesPolicy policy )
323  : rowCount( rowCount )
324  , _this( _this )
325  , policy( policy )
326  {
327  }
328 
329  int rowCount;
330  PercentLineDiagram* _this;
332 
333  qreal operator() ( int row, int col ) const
334  {
335  if ( row < 0 || row >= rowCount ) {
336  return NAN;
337  }
338 
339  const CartesianDiagramDataCompressor::CachePosition position( row, col );
340  const CartesianDiagramDataCompressor::DataPoint point = _this->compressor().data( position );
341 
342  return !ISNAN( point.value ) ? point.value
343  : policy == LineAttributes::MissingValuesAreBridged ? _this->interpolateMissingValue( position )
344  : NAN;
345  }
346 
347  };
348  valueAtLambda valueAt( rowCount, this, policy );
349 
350 
351  struct safeAddLambda {
352  qreal operator() (qreal accumulator, qreal newValue) const
353  {
354  return ISNAN( newValue ) ? accumulator : accumulator + newValue;
355  }
356  };
357  safeAddLambda safeAdd;
358 
359  qreal nextKey = 0;
360  QVector<qreal> stackedValuesTop( 4, 0.0 );
361  QVector<qreal> stackedValuesBottom( 4, 0.0 );
362 
363  for ( int currentRow = 0; currentRow < 4; ++currentRow ) {
364  stackedValuesTop[currentRow] = safeAdd( stackedValuesTop[currentRow], valueAt( row - 1 + currentRow, column ) );
365  }
366 
367  for ( int column2 = column - 1; column2 >= 0; --column2 )
368  {
369  for ( int currentRow = 0; currentRow < 4; ++currentRow ) {
370  stackedValuesTop[currentRow] = safeAdd( stackedValuesTop[currentRow], valueAt( row - 1 + currentRow, column2 ) );
371  stackedValuesBottom[currentRow] = safeAdd( stackedValuesBottom[currentRow], valueAt( row - 1 + currentRow, column2 ) );
372  }
373  }
374 
375  nextKey = row + 1;
376 
377  // TODO: revert back to lambdas when we stop caring about pre-C++11
378  // See the Qt6 port
379  struct dataAtLambda {
380  dataAtLambda( PaintContext* ctx, PercentLineDiagram* _this )
381  : ctx( ctx )
382  , _this( _this )
383  {
384  }
385 
386  PaintContext* ctx;
387  PercentLineDiagram* _this;
388 
389  QPointF operator() ( const QVector<qreal>& source, qreal key, int index, qreal scale ) const
390  {
391  return ctx->coordinatePlane()->translate( QPointF( _this->diagram()->centerDataPoints() ? key + 0.5 : key, source[index] * scale ) );
392  }
393  };
394  dataAtLambda dataAt( ctx, this );
395 
396  const auto scale = qFuzzyIsNull( percentSumValues.at( row ) ) ? 0 : maxValue / percentSumValues.at( row );
397  const QPointF ptNorthWest = dataAt( stackedValuesTop, point.key, 1, scale );
398  const QPointF ptSouthWest =
399  bDisplayCellArea ? dataAt( stackedValuesBottom, point.key, 1, scale )
400  : ptNorthWest;
401 
402  QPointF ptNorthEast;
403  QPointF ptSouthEast;
404 
405  if ( row + 1 < rowCount ) {
406  const auto nextScale = qFuzzyIsNull ( percentSumValues.at( row + 1 ) ) ? 0 : maxValue / percentSumValues.at ( row + 1 );
407  ptNorthEast = dataAt( stackedValuesTop, nextKey, 2, nextScale );
408  lineList.append( LineAttributesInfo( sourceIndex, ptNorthWest, ptNorthEast ) );
409  ptSouthEast =
410  bDisplayCellArea ? dataAt( stackedValuesBottom, nextKey, 2, nextScale )
411  : ptNorthEast;
412 
413  if ( areas.count() && laCell != laPreviousCell ) {
414  PaintingHelpers::paintAreas( m_private, ctx, indexPreviousCell, areas, laPreviousCell.transparency() );
415  areas.clear();
416  }
417 
418  if ( bDisplayCellArea ) {
419  QPainterPath path;
420  path.moveTo( ptNorthWest );
421 
422  const QPointF ptBeforeNorthWest =
423  row > 0 ? dataAt( stackedValuesTop, point.key - 1, 0, scale )
424  : ptNorthWest;
425  const QPointF ptAfterNorthEast =
426  row < rowCount - 2 ? dataAt( stackedValuesTop, point.key + 2, 3, nextScale )
427  : ptNorthEast;
428  addSplineChunkTo( path, tension, ptBeforeNorthWest, ptNorthWest, ptNorthEast, ptAfterNorthEast, mainSplineDirection );
429 
430  path.lineTo( ptNorthEast );
431  path.lineTo( ptSouthEast );
432 
433  const QPointF ptBeforeSouthWest =
434  row > 0 ? dataAt( stackedValuesBottom, point.key - 1, 0, scale )
435  : ptSouthWest;
436  const QPointF ptAfterSouthEast =
437  row < rowCount - 2 ? dataAt( stackedValuesBottom, point.key + 2, 3, nextScale )
438  : ptSouthEast;
439  addSplineChunkTo( path, tension, ptAfterSouthEast, ptSouthEast, ptSouthWest, ptBeforeSouthWest, reverseSplineDirection );
440 
441  areas << path;
442  laPreviousCell = laCell;
443  indexPreviousCell = sourceIndex;
444  } else {
445  //qDebug() << "no area shown for row"<<iRow<<" column"<<iColumn;
446  }
447  } else {
448  ptNorthEast = ptNorthWest;
449  ptSouthEast = ptSouthWest;
450  }
451 
452  const PositionPoints pts( ptNorthWest, ptNorthEast, ptSouthEast, ptSouthWest );
453  if ( !ISNAN( point.value ) )
454  m_private->addLabel( &lpc, sourceIndex, &position, pts, Position::NorthWest,
455  Position::NorthWest, point.value );
456  }
457  if ( areas.count() ) {
458  PaintingHelpers::paintAreas( m_private, ctx, indexPreviousCell, areas, laPreviousCell.transparency() );
459  areas.clear();
460  }
461  }
462  PaintingHelpers::paintElements( m_private, ctx, lpc, lineList );
463 }
KDChartEnums::PositionValue value() const
Returns an integer value corresponding to this Position.
void paintElements(AbstractDiagram::Private *diagramPrivate, PaintContext *ctx, const LabelPaintCache &lpc, const LineAttributesInfoList &lineList)
virtual const QPointF translate(const QPointF &diagramPoint) const =0
Translate the given point in value space coordinates to a position in pixel space.
AbstractCoordinatePlane * coordinatePlane() const
Set of attributes for changing the appearance of line charts.
void paintAreas(AbstractDiagram::Private *diagramPrivate, PaintContext *ctx, const QModelIndex &index, const QList< QPolygonF > &areas, uint opacity)
static const Position & NorthWest
LineDiagram defines a common line diagram.
Stores information about painting diagrams.
Stores the absolute target points of a Position.
MissingValuesPolicy
MissingValuesPolicy specifies how a missing value will be shown in a line diagram.
MissingValuesPolicy missingValuesPolicy() const

Klarälvdalens Datakonsult AB (KDAB)
"The Qt, C++ and OpenGL Experts"
https://www.kdab.com/

https://www.kdab.com/development-resources/qt-tools/kd-chart/