KD Chart 2  [rev.2.7]
KDChartPercentLineDiagram_p.cpp
Go to the documentation of this file.
1 /****************************************************************************
2 ** Copyright (C) 2001-2020 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 // FIXME integrade column index retrieval to compressor:
248  int maxFound = 0;
249 // { // find the last column number that is not hidden
250 // for ( int iColumn = datasetDimension() - 1;
251 // iColumn < columnCount;
252 // iColumn += datasetDimension() )
253 // if ( ! diagram()->isHidden( iColumn ) )
254 // maxFound = iColumn;
255 // }
256  maxFound = columnCount;
257  // ^^^ temp
258  const int lastVisibleColumn = maxFound - 1;
259 
260  LabelPaintCache lpc;
261  LineAttributesInfoList lineList;
262 
263  //FIXME(khz): add LineAttributes::MissingValuesPolicy support for LineDiagram::Stacked and ::Percent
264 
265  qreal maxValue = 100; // always 100%
266  qreal sumValues = 0;
267  QVector <qreal > percentSumValues;
268 
269  //calculate sum of values for each column and store
270  for ( int row = 0; row < rowCount; ++row )
271  {
272  for ( int col = 0; col < columnCount; ++col )
273  {
274  const CartesianDiagramDataCompressor::CachePosition position( row, col );
275  CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
276  const QModelIndex sourceIndex = attributesModel()->mapToSource( point.index );
277  const LineAttributes laCell = diagram()->lineAttributes( sourceIndex );
279  if ( ISNAN( point.value ) && policy == LineAttributes::MissingValuesAreBridged )
280  point.value = interpolateMissingValue( position );
281  if ( point.value > 0 )
282  sumValues += point.value;
283  if ( col == lastVisibleColumn )
284  {
285  percentSumValues << sumValues ;
286  sumValues = 0;
287  }
288  }
289  }
290 
291  for ( int column = 0; column < columnCount; ++column )
292  {
293  //display area can be set by dataset ( == column) and/or by cell
294  LineAttributes laPreviousCell; // by default no area is drawn
295  QModelIndex indexPreviousCell;
296  QList<QPainterPath> areas;
297 
298  for ( int row = 0; row < rowCount; ++row )
299  {
300  const CartesianDiagramDataCompressor::CachePosition position( row, column );
301  CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
302  const QModelIndex sourceIndex = attributesModel()->mapToSource( point.index );
303  const LineAttributes laCell = diagram()->lineAttributes( sourceIndex );
304  const bool bDisplayCellArea = laCell.displayArea();
305 
307 
308  // TODO: revert back to lambdas when we stop caring about pre-C++11
309  // auto valueAt = [&] ( int row, int col ) -> qreal {
310  // if ( row < 0 || row >= rowCount ) {
311  // return NAN;
312  // }
313  //
314  // const CartesianDiagramDataCompressor::CachePosition position( row, col );
315  // const CartesianDiagramDataCompressor::DataPoint point = compressor().data( position );
316  //
317  // return !ISNAN( point.value ) ? point.value
318  // : policy == LineAttributes::MissingValuesAreBridged ? interpolateMissingValue( position )
319  // : NAN;
320  // };
321  //
322  // auto safeAddPositive = [] ( qreal accumulator, qreal newValue ) {
323  // return ISNAN( newValue ) || newValue <= 0 ? accumulator : accumulator + newValue;
324  // };
325 
326  struct valueAtLambda {
327  valueAtLambda( int rowCount, PercentLineDiagram* _this, LineAttributes::MissingValuesPolicy policy )
328  : rowCount( rowCount )
329  , _this( _this )
330  , policy( policy )
331  {
332  }
333 
334  int rowCount;
335  PercentLineDiagram* _this;
337 
338  qreal operator() ( int row, int col ) const
339  {
340  if ( row < 0 || row >= rowCount ) {
341  return NAN;
342  }
343 
344  const CartesianDiagramDataCompressor::CachePosition position( row, col );
345  const CartesianDiagramDataCompressor::DataPoint point = _this->compressor().data( position );
346 
347  return !ISNAN( point.value ) ? point.value
348  : policy == LineAttributes::MissingValuesAreBridged ? _this->interpolateMissingValue( position )
349  : NAN;
350  }
351 
352  };
353  valueAtLambda valueAt( rowCount, this, policy );
354 
355 
356  struct safeAddPositiveLambda {
357  qreal operator() (qreal accumulator, qreal newValue) const
358  {
359  return ISNAN( newValue ) || newValue <= 0 ? accumulator : accumulator + newValue;
360  }
361  };
362  safeAddPositiveLambda safeAddPositive;
363 
364  qreal nextKey = 0;
365  QVector<qreal> stackedValuesTop( 4, 0.0 );
366  QVector<qreal> stackedValuesBottom( 4, 0.0 );
367 
368  if ( ! qFuzzyIsNull( percentSumValues.at( row ) ) ) {
369  for ( int currentRow = 0; currentRow < 4; ++currentRow ) {
370  stackedValuesTop[currentRow] = safeAddPositive( stackedValuesTop[currentRow], valueAt( row - 1 + currentRow, column ) );
371  }
372 
373  for ( int column2 = column - 1; column2 >= 0; --column2 )
374  {
375  for ( int currentRow = 0; currentRow < 4; ++currentRow ) {
376  stackedValuesTop[currentRow] = safeAddPositive( stackedValuesTop[currentRow], valueAt( row - 1 + currentRow, column2 ) );
377  stackedValuesBottom[currentRow] = safeAddPositive( stackedValuesBottom[currentRow], valueAt( row - 1 + currentRow, column2 ) );
378  }
379  }
380 
381  for ( int currentRow = 0; currentRow < 4; ++currentRow ) {
382  stackedValuesTop[currentRow] /= percentSumValues.at( row ) / maxValue;
383  stackedValuesBottom[currentRow] /= percentSumValues.at( row ) / maxValue;
384  }
385  }
386 
387  nextKey = row + 1;
388 
389  // TODO: revert back to lambdas when we stop caring about pre-C++11
390  // auto dataAt = [&] ( const QVector<qreal>& source, qreal key, int index ) {
391  // return ctx->coordinatePlane()->translate( QPointF( diagram()->centerDataPoints() ? key + 0.5 : key, source[index] ) );
392  // };
393  struct dataAtLambda {
394  dataAtLambda( PaintContext* ctx, PercentLineDiagram* _this )
395  : ctx( ctx )
396  , _this( _this )
397  {
398  }
399 
400  PaintContext* ctx;
401  PercentLineDiagram* _this;
402 
403  QPointF operator() ( const QVector<qreal>& source, qreal key, int index ) const
404  {
405  return ctx->coordinatePlane()->translate( QPointF( _this->diagram()->centerDataPoints() ? key + 0.5 : key, source[index] ) );
406  }
407  };
408  dataAtLambda dataAt( ctx, this );
409 
410  const QPointF ptNorthWest = dataAt( stackedValuesTop, point.key, 1 );
411  const QPointF ptSouthWest =
412  bDisplayCellArea ? dataAt( stackedValuesBottom, point.key, 1 )
413  : ptNorthWest;
414 
415  QPointF ptNorthEast;
416  QPointF ptSouthEast;
417 
418  if ( row + 1 < rowCount ) {
419  ptNorthEast = dataAt( stackedValuesTop, nextKey, 2 );
420  lineList.append( LineAttributesInfo( sourceIndex, ptNorthWest, ptNorthEast ) );
421  ptSouthEast =
422  bDisplayCellArea ? dataAt( stackedValuesBottom, nextKey, 2 )
423  : ptNorthEast;
424 
425  if ( areas.count() && laCell != laPreviousCell ) {
426  PaintingHelpers::paintAreas( m_private, ctx, indexPreviousCell, areas, laPreviousCell.transparency() );
427  areas.clear();
428  }
429 
430  if ( bDisplayCellArea ) {
431  QPainterPath path;
432  path.moveTo( ptNorthWest );
433 
434  const QPointF ptBeforeNorthWest =
435  row > 0 ? dataAt( stackedValuesTop, point.key - 1, 0 )
436  : ptNorthWest;
437  const QPointF ptAfterNorthEast =
438  row < rowCount - 1 ? dataAt( stackedValuesTop, point.key + 2, 3 )
439  : ptNorthEast;
440  addSplineChunkTo( path, tension, ptBeforeNorthWest, ptNorthWest, ptNorthEast, ptAfterNorthEast );
441 
442  path.lineTo( ptNorthEast );
443  path.lineTo( ptSouthEast );
444 
445  const QPointF ptBeforeSouthWest =
446  row > 0 ? dataAt( stackedValuesBottom, point.key - 1, 0 )
447  : ptSouthWest;
448  const QPointF ptAfterSouthEast =
449  row < rowCount - 1 ? dataAt( stackedValuesBottom, point.key + 2, 3 )
450  : ptSouthEast;
451  addSplineChunkTo( path, tension, ptAfterSouthEast, ptSouthEast, ptSouthWest, ptBeforeSouthWest, ReverseSplineDirection );
452 
453  areas << path;
454  laPreviousCell = laCell;
455  indexPreviousCell = sourceIndex;
456  } else {
457  //qDebug() << "no area shown for row"<<iRow<<" column"<<iColumn;
458  }
459  } else {
460  ptNorthEast = ptNorthWest;
461  ptSouthEast = ptSouthWest;
462  }
463 
464  if ( !ISNAN( point.value ) )
465  {
466  const PositionPoints pts( ptNorthWest, ptNorthEast, ptSouthEast, ptSouthWest );
467  m_private->addLabel( &lpc, sourceIndex, &position, pts, Position::NorthWest,
468  Position::NorthWest, point.value );
469  }
470  }
471  if ( areas.count() ) {
472  PaintingHelpers::paintAreas( m_private, ctx, indexPreviousCell, areas, laPreviousCell.transparency() );
473  areas.clear();
474  }
475  }
476  PaintingHelpers::paintElements( m_private, ctx, lpc, lineList );
477 }
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/