summaryrefslogtreecommitdiffstats
path: root/libkdchart/KDChartBWPainter.cpp
blob: b7b57894e6093cf0b626866159c2ed05a0e157a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/* -*- Mode: C++ -*-
   KDChart - a multi-platform charting engine
   */

/****************************************************************************
 ** Copyright (C) 2001-2003 Klarälvdalens Datakonsult AB.  All rights reserved.
 **
 ** This file is part of the KDChart library.
 **
 ** This file may be distributed and/or modified under the terms of the
 ** GNU General Public License version 2 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.GPL included in the
 ** packaging of this file.
 **
 ** Licensees holding valid commercial KDChart licenses may use this file in
 ** accordance with the KDChart Commercial License Agreement provided with
 ** the Software.
 **
 ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 **
 ** See http://www.klaralvdalens-datakonsult.se/?page=products for
 **   information about KDChart Commercial License Agreements.
 **
 ** Contact [email protected] if any conditions of this
 ** licensing are not clear to you.
 **
 **********************************************************************/
#include "KDChartBWPainter.h"
#include <KDChartParams.h>
#include "KDChartTextPiece.h"

#include <tqpainter.h>
#if COMPAT_TQT_VERSION >= 0x030000
#include <tqmemarray.h>
#else
#include <tqarray.h>
#define TQMemArray TQArray
#endif

#include <stdlib.h>

/**
  \class KDChartBWPainter KDChartBWPainter.h

  \brief A chart painter implementation that can paint Box&Whisker charts.
  */

/**
  Constructor. Sets up internal data structures as necessary.

  \param params the KDChartParams structure that defines the chart
  */
    KDChartBWPainter::KDChartBWPainter( KDChartParams* params ) :
KDChartAxesPainter( params )
{
    // This constructor intentionally left blank so far; we cannot setup the
    // geometry yet since we do not know the size of the painter.
}


/**
  Destructor.
  */
KDChartBWPainter::~KDChartBWPainter()
{
    // intentionally left blank
}


void quicksort( TQMemArray<double>& a, int lo, int hi )
{
    int    i=lo, j=hi;
    double h;
    double x=a[(lo+hi)/2];
    do
    {
        while (a[i]<x) i++;
        while (a[j]>x) j--;
        if (i<=j)
        {
            h=a[i]; a[i]=a[j]; a[j]=h;
            i++; j--;
        }
    } while (i<=j);
    if (lo<j) quicksort(a, lo, j);
    if (i<hi) quicksort(a, i, hi);
}


// The following function returns the number of used cells containing a double.
int KDChartBWPainter::calculateStats( KDChartTableDataBase& data,
        uint dataset )
{
    const uint nMax = data.usedCols();
    int nUsed = 0;
    TQMemArray<double> values( nMax );
    double sum = 0.0;
    TQVariant vVal;
    if( data.sorted() ){
        for( uint i=0; i<nMax; ++i){
            if( data.cellCoord( dataset, i, vVal, 1 ) &&
                TQVariant::Double == vVal.type() ) {
                values[nUsed] = vVal.toDouble();
                sum += values[nUsed];
                ++nUsed;
            }
        }
    }else{
        // make copy of the dataset and look if it is sorted
        bool sorted = true;
        double last = 0.0; //  <--  avoids an annoying compile-time warning
        for( uint i=0; i<nMax; ++i){
            if( data.cellCoord( dataset, i, vVal, 1 ) &&
                TQVariant::Double == vVal.type() ) {
                values[nUsed] = vVal.toDouble();
                if(    nUsed // skip 1st value
                    && last > values[nUsed] )
                    sorted = false;
                last = values[nUsed];
                sum += last;
                ++nUsed;
            }
        }
        if( !sorted ){
            // sort our copy of the dataset
            quicksort( values, 0, nUsed-1 );
        }
    }

    // Values now contains all used values without empty gaps.
    // nUsed contains their number, so values[nUsed-1] is the last value.

    if( nUsed ){
        // store some values
        stats[ KDChartParams::MaxValue  ] = values[nUsed-1];
        stats[ KDChartParams::MinValue  ] = values[0];

        stats[ KDChartParams::MeanValue ] = sum / nUsed;
        // calculate statistics
        bool bOdd = 1 == nUsed % 2;
        // find median
        int nUd2 = nUsed/2;
        if( bOdd )
            stats[ KDChartParams::Median ] = values[ nUd2 ];
        else
            stats[ KDChartParams::Median ] =
                (values[ TQMAX(nUd2-1, 0) ] + values[ nUd2 ]) /2;
        // find last value of lower quartile
        nLastQ1  = TQMAX( nUd2-1, 0 );
        // find 1st value of lower quartile
        nFirstQ1 = nLastQ1 / 2;

        // determine how many values are below the median ( == how many are above it)
        int nLowerCount = nLastQ1 - nFirstQ1 + 1;

        // find 1st value of upper quartile
        nFirstQ3 = bOdd ? TQMIN( nUd2+1, nUsed-1 ) : nUd2;
        // find last value of upper quartile
        nLastQ3  = nFirstQ3 + nLowerCount - 1;

        // find quartiles
        bool bOdd2 = 1 == nLowerCount % 2;
        // find lower quartile
        if( bOdd2 )
            stats[ KDChartParams::Quartile1 ] = values[ nFirstQ1 ];
        else
            stats[ KDChartParams::Quartile1 ] =
                (values[ TQMAX(nFirstQ1-1, 0) ] + values[ nFirstQ1 ]) /2;
        // find upper quartile
        if( bOdd2 ){
            stats[ KDChartParams::Quartile3 ] = values[ nLastQ3 ];
}
        else{
            //tqDebug("  "+TQString::number(nLastQ3)+"  "+TQString::number(KDChartParams::Quartile3)
            //      +"  "+TQString::number(nUsed)+"  "+TQString::number(TQMIN(nLastQ3+1, nUsed-1)));
            stats[ KDChartParams::Quartile3 ] =
                (values[ nLastQ3 ] + values[ TQMIN(nLastQ3+1, nUsed-1) ]) /2;
}
        // find the interquartile range (IQR)
        double iqr = stats[ KDChartParams::Quartile3 ] - stats[ KDChartParams::Quartile1 ];

        // calculate the fences
        double upperInner, lowerInner, upperOuter, lowerOuter;
        params()->bWChartFences( upperInner, lowerInner,
                upperOuter, lowerOuter );
        stats[ KDChartParams::UpperInnerFence ] =
            stats[ KDChartParams::Quartile3 ] + iqr * upperInner;
        stats[ KDChartParams::LowerInnerFence ] =
            stats[ KDChartParams::Quartile1 ] - iqr * lowerInner;
        stats[ KDChartParams::UpperOuterFence ] =
            stats[ KDChartParams::Quartile3 ] + iqr * upperOuter;
        stats[ KDChartParams::LowerOuterFence ] =
            stats[ KDChartParams::Quartile1 ] - iqr * lowerOuter;
    }
    return nUsed;
}


/**
  This method is a specialization that returns a fallback legend text
  appropriate for BW that do not have the same notion of a dataset like
  e.g. bars.

  This method is only used when automatic legends are used, because
  manual and first-column legends do not need fallback texts.

  \param uint dataset the dataset number for which to generate a
  fallback text
  \return the fallback text to use for describing the specified
  dataset in the legend
  */
TQString KDChartBWPainter::fallbackLegendText( uint dataset ) const
{
    return TQObject::tr( "Series " ) + TQString::number( dataset + 1 );
}


/**
  This methods returns the number of elements to be shown in the
  legend in case fallback texts are used.

  This method is only used when automatic legends are used, because
  manual and first-column legends do not need fallback texts.

  \return the number of fallback texts to use
  */
uint KDChartBWPainter::numLegendFallbackTexts( KDChartTableDataBase* data ) const
{
    return data->usedRows();
}


bool KDChartBWPainter::isNormalMode() const
{
    return KDChartParams::BWNormal == params()->bWChartSubType();
}

int KDChartBWPainter::clipShiftUp( bool, double ) const
{
    return 0;
}

/**
  Paints the actual data area and registers the region for the data
  points if \a regions is not 0.

  \param painter the TQPainter onto which the chart should be painted
  \param data the data that will be displayed as a chart
  \param paint2nd specifies whether the main chart or the additional chart is to be drawn now
  \param regions a pointer to a list of regions that will be filled
  with regions representing the data segments, if not null
  */
void KDChartBWPainter::specificPaintData( TQPainter* painter,
        const TQRect& ourClipRect,
        KDChartTableDataBase* data,
        KDChartDataRegionList* /*regions*/,
        const KDChartAxisParams* axisPara,
        bool /*bNormalMode*/,
        uint /*chart*/,
        double logWidth,
        double /*areaWidthP1000*/,
        double logHeight,
        double /*axisYOffset*/,
        double /*minColumnValue*/,
        double /*maxColumnValue*/,
        double /*columnValueDistance*/,
        uint chartDatasetStart,
        uint chartDatasetEnd,
        uint datasetStart,
        uint datasetEnd )
{
    //double areaHeightP1000 = logHeight / 1000.0;

    uint datasetNum = ( chartDatasetEnd - chartDatasetStart ) + 1;

    double pixelsPerUnit = 0.0;
    if( 0.0 != axisPara->trueAxisHigh() - axisPara->trueAxisLow() )
        pixelsPerUnit = logHeight / (axisPara->trueAxisHigh() - axisPara->trueAxisLow());
    else
        pixelsPerUnit = logHeight / 10;

    // Distance between the individual "stocks"
    double pointDist = logWidth / ( ( double ) datasetNum );

    // compute the position of the 0 axis
    double zeroXAxisI = axisPara->axisZeroLineStartY() - _dataRect.y();

    const int lineWidth   = static_cast<int>( pointDist / 66.0 ) * TQMAX(params()->lineWidth(), 1);
    const int lineWidthD2 = lineWidth * 2 / 3;

    const bool noBrush = TQt::NoBrush == params()->bWChartBrush().style();

    // Loop over the datasets, draw one box and whisker shape for each series.
    for ( uint dataset  = chartDatasetStart;
            dataset <= chartDatasetEnd;
            ++dataset ) {

        if( dataset >= datasetStart &&
                dataset <= datasetEnd &&
                0 < calculateStats( *data, dataset ) ) {
            const TQColor color( params()->dataColor( dataset ) );
            // transform calculated values
            double drawUOF = stats[ KDChartParams::UpperOuterFence ] * pixelsPerUnit;
            double drawUIF = stats[ KDChartParams::UpperInnerFence ] * pixelsPerUnit;
            double drawQu3 = stats[ KDChartParams::Quartile3       ] * pixelsPerUnit;
            double drawMed = stats[ KDChartParams::Median          ] * pixelsPerUnit;
            double drawQu1 = stats[ KDChartParams::Quartile1       ] * pixelsPerUnit;
            double drawLIF = stats[ KDChartParams::LowerInnerFence ] * pixelsPerUnit;
            double drawLOF = stats[ KDChartParams::LowerOuterFence ] * pixelsPerUnit;
            double drawMax = stats[ KDChartParams::MaxValue        ] * pixelsPerUnit;
            double drawMin = stats[ KDChartParams::MinValue        ] * pixelsPerUnit;
            double drawMean= stats[ KDChartParams::MeanValue       ] * pixelsPerUnit;
            // get whisker values
            double drawUWhisker = TQMIN(drawUIF, drawMax);
            double drawLWhisker = TQMAX(drawLIF, drawMin);
            // get the box width
            const int boxWidth = TQMAX( 6, static_cast<int>( pointDist * 0.2 ) );
            // get marker size (for the outliers and/or for the median value)
            int markWidth = params()->bWChartOutValMarkerSize();
            bool drawOutliers = ( 0 != markWidth );
            if( drawOutliers ){
                if( 0 > markWidth)
                    markWidth = TQMAX( 4, markWidth * boxWidth / -100 );
                else
                    markWidth = TQMAX( 4, markWidth );
            }
            else
                markWidth = boxWidth * 25 / 100; // use the default for the Median marker

            painter->setPen( TQPen( color, lineWidth ) );
            painter->setBrush( params()->bWChartBrush() );
            // draw the box
            int boxWidthD2 = boxWidth / 2;
            int xPos = static_cast<int>(
                    pointDist * ( (double)(dataset - chartDatasetStart) + 0.5 )
                    - lineWidth / 2);
            painter->drawRect( xPos - boxWidthD2,
                    static_cast<int>( zeroXAxisI - drawQu3 ),
                    boxWidth,
                    static_cast<int>( drawQu3 - drawQu1) + 1 );
            // draw the median
            painter->drawLine( xPos - boxWidthD2,
                    static_cast<int>( zeroXAxisI - drawMed ),
                    xPos - boxWidthD2 + boxWidth,
                    static_cast<int>( zeroXAxisI - drawMed ) );
            // draw the whisker
            painter->drawLine( xPos - boxWidthD2,
                    static_cast<int>( zeroXAxisI - drawUWhisker ),
                    xPos - boxWidthD2 + boxWidth,
                    static_cast<int>( zeroXAxisI - drawUWhisker ) );
            painter->drawLine( xPos,
                    static_cast<int>( zeroXAxisI - drawUWhisker ),
                    xPos,
                    static_cast<int>( zeroXAxisI - drawQu3 ) );
            painter->drawLine( xPos - boxWidthD2,
                    static_cast<int>( zeroXAxisI - drawLWhisker ),
                    xPos - boxWidthD2 + boxWidth,
                    static_cast<int>( zeroXAxisI - drawLWhisker ) );
            painter->drawLine( xPos,
                    static_cast<int>( zeroXAxisI - drawLWhisker ),
                    xPos,
                    static_cast<int>( zeroXAxisI - drawQu1 ) );
            // draw the values
            int xPos2 = static_cast<int>(
                    pointDist * ( (double)(dataset - chartDatasetStart) + 0.5 )
                    - lineWidthD2 / 2);
            int markWidthD2 =  TQMAX(markWidth / 2, 2);
            int markWidthD25 = TQMAX(static_cast<int>( 0.85 * markWidth / 2.0), 2);
            int markWidthD35 = TQMAX(static_cast<int>( 0.85 * markWidth / 3.0), 2);
            // draw the outliers
            if( drawOutliers ){
                const uint nMax = data->usedCols();
                int drawVal;
                TQVariant vVal;
                for( uint i=0; i<nMax; ++i)
                    if( data->cellCoord( dataset, i, vVal, 1 ) &&
                        TQVariant::Double == vVal.type() ) {
                        drawVal = static_cast<int>( pixelsPerUnit * vVal.toDouble() );
                        if( drawLOF > drawVal || drawUOF < drawVal ) {
                            painter->setPen( TQt::NoPen );
                            painter->drawChord( xPos2 - markWidthD2,
                                    static_cast<int>(zeroXAxisI - drawVal) - markWidthD2,
                                    markWidth,
                                    markWidth,
                                    0, 5760 );
                            painter->setPen( TQPen( color, lineWidthD2 ) );
                            painter->drawArc( xPos2 - markWidthD2,
                                    static_cast<int>(zeroXAxisI - drawVal) - markWidthD2,
                                    markWidth,
                                    markWidth,
                                    0, 5760 );
                        } else if( drawLIF > drawVal || drawUIF < drawVal ) {
                            painter->setPen( TQt::NoPen );
                            painter->drawChord( xPos2 - markWidthD2,
                                    static_cast<int>( zeroXAxisI - drawVal) - markWidthD2,
                                    markWidth,
                                    markWidth,
                                    0, 5760 );
                            painter->setPen( TQPen( color, lineWidthD2 ) );
                            painter->drawLine( xPos2,
                                    static_cast<int>(zeroXAxisI - drawVal) - markWidthD2,
                                    xPos2,
                                    static_cast<int>(zeroXAxisI - drawVal) + markWidthD2 );
                            painter->drawLine( xPos2 - markWidthD25,
                                    static_cast<int>(zeroXAxisI - drawVal) - markWidthD35,
                                    xPos2 + markWidthD25,
                                    static_cast<int>(zeroXAxisI - drawVal) + markWidthD35 );
                            painter->drawLine( xPos2 + markWidthD25,
                                    static_cast<int>(zeroXAxisI - drawVal) - markWidthD35,
                                    xPos2 - markWidthD25,
                                    static_cast<int>(zeroXAxisI - drawVal) + markWidthD35 );
                        }
                    }
            }
            // draw the mean value
            bool evenLineWidthD2 = floor( ((double)lineWidthD2)/2.0 ) == ((double)lineWidthD2)/2.0;
            painter->setPen( params()->bWChartBrush().color() );
            painter->drawChord( xPos2 - markWidthD2-1 - (evenLineWidthD2 ? 0 : 1),
                    static_cast<int>( zeroXAxisI - drawMean ) - markWidthD2 - 1,
                    markWidthD2*2 + (evenLineWidthD2 ? 2 : 3),
                    markWidthD2*2 + (evenLineWidthD2 ? 2 : 3),
                    0, 5760 );
            if( noBrush ) {
                // use different color brightness for the Mean marker
                int h,s,v;
                color.hsv(&h,&s,&v);
                painter->setPen( TQPen( 128 > v ? color.light(150) : color.dark(150),
                            lineWidthD2 ) );
            } else
                painter->setPen( TQPen( color, lineWidthD2 ) );
            painter->drawLine( xPos2 - markWidthD2 - (evenLineWidthD2 ? 0 : 1),
                               static_cast<int>( zeroXAxisI - drawMean ),
                               xPos2 + markWidthD2,
                               static_cast<int>( zeroXAxisI - drawMean ) );
            painter->drawLine( xPos2 - (evenLineWidthD2 ? 0 : 1),
                               static_cast<int>( zeroXAxisI - drawMean ) - markWidthD2,
                               xPos2 - (evenLineWidthD2 ? 0 : 1),
                               static_cast<int>( zeroXAxisI - drawMean ) + markWidthD2 + (evenLineWidthD2 ? 0 : 1) );

            // draw the statistical value texts
            painter->setPen( TQt::NoPen );
            for( int ii =  KDChartParams::BWStatValSTART;
                    ii <= KDChartParams::BWStatValEND;
                    ++ii ){
                KDChartParams::BWStatVal i = (KDChartParams::BWStatVal)ii;
                if( params()->bWChartPrintStatistics( i ) ) {
                    TQFont statFont( params()->bWChartStatisticsFont( i ) );
                    float nTxtHeight = statFont.pointSizeFloat();
                    if ( params()->bWChartStatisticsUseRelSize( i ) ) {
                        nTxtHeight = params()->bWChartStatisticsFontRelSize( i )
                            * boxWidth / 100;
                        statFont.setPointSizeFloat( nTxtHeight );
                    }
                    double drawStat = pixelsPerUnit * stats[i];
                    KDChartTextPiece statText( painter, TQString::number( stats[i] ),
                            statFont );
                    int tw = statText.width();
                    int xDelta = (    KDChartParams::MaxValue  == i
                            || KDChartParams::MeanValue == i
                            || KDChartParams::MinValue  == i )
                        ? -1 * (tw + static_cast<int>( 1.3*boxWidthD2 ))
                        : static_cast<int>( 1.3*boxWidthD2 );
                    TQBrush brush( params()->bWChartStatisticsBrush( i ) );
                    painter->setBrush( brush );
                    int y = static_cast<int>( zeroXAxisI - drawStat - nTxtHeight/2);
                    painter->drawRect( xPos + xDelta - 1,
                            y,
                            tw + 2,
                            TQMAX(static_cast < int > ( nTxtHeight ), 8) + 1 );
                    statText.draw( painter,
                            xPos + xDelta,
                            y,
                            ourClipRect,
                            params()->bWChartStatisticsColor( i ),
                            0 );
                }
            }

        } else
            continue; // we cannot display this value
    }
}