LinechartPlot.cc 26.7 KB
Newer Older
lm's avatar
lm committed
1
 /*=====================================================================
pixhawk's avatar
pixhawk committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
======================================================================*/

/**
 * @file
 *   @brief Line chart for vehicle data
 *
 *   @author Lorenz Meier <mavteam@student.ethz.ch>
 *
 */

#include "float.h"
#include <QDebug>
#include <QTimer>
#include <qwt_plot.h>
#include <qwt_plot_canvas.h>
#include <qwt_plot_curve.h>
#include <qwt_plot_grid.h>
#include <qwt_plot_layout.h>
#include <qwt_plot_zoomer.h>
#include <qwt_symbol.h>
#include <LinechartPlot.h>
#include <MG.h>
#include <QPaintEngine>

26 27
#include "QGC.h"

pixhawk's avatar
pixhawk committed
28 29 30 31 32 33 34
/**
 * @brief The default constructor
 *
 * @param parent The parent widget
 * @param interval The maximum interval for which data is stored (default: 30 minutes) in milliseconds
 **/
LinechartPlot::LinechartPlot(QWidget *parent, int plotid, quint64 interval): QwtPlot(parent),
35 36 37
    minTime(0),
    lastTime(0),
    maxTime(100),
38
    maxInterval(MAX_STORAGE_INTERVAL),
Lorenz Meier's avatar
Lorenz Meier committed
39
    plotPosition(0),
40 41 42 43 44 45
    timeScaleStep(DEFAULT_SCALE_INTERVAL), // 10 seconds
    automaticScrollActive(false),
    m_active(false),
    m_groundTime(true),
    d_data(NULL),
    d_curve(NULL)
pixhawk's avatar
pixhawk committed
46 47 48
{
    this->plotid = plotid;
    this->plotInterval = interval;
lm's avatar
lm committed
49

pixhawk's avatar
pixhawk committed
50 51
    maxValue = DBL_MIN;
    minValue = DBL_MAX;
lm's avatar
lm committed
52

pixhawk's avatar
pixhawk committed
53
    //lastMaxTimeAdded = QTime();
lm's avatar
lm committed
54

pixhawk's avatar
pixhawk committed
55 56 57
    curves = QMap<QString, QwtPlotCurve*>();
    data = QMap<QString, TimeSeriesData*>();
    scaleMaps = QMap<QString, QwtScaleMap*>();
lm's avatar
lm committed
58

pixhawk's avatar
pixhawk committed
59 60
    yScaleEngine = new QwtLinearScaleEngine();
    setAxisScaleEngine(QwtPlot::yLeft, yScaleEngine);
lm's avatar
lm committed
61

pixhawk's avatar
pixhawk committed
62 63 64
    /* Create color map */
    colors = QList<QColor>();
    nextColor = 0;
lm's avatar
lm committed
65

pixhawk's avatar
pixhawk committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
    ///> Color map for plots, includes 20 colors
    ///> Map will start from beginning when the first 20 colors are exceeded
    colors.append(QColor(242,255,128));
    colors.append(QColor(70,80,242));
    colors.append(QColor(232,33,47));
    colors.append(QColor(116,251,110));
    colors.append(QColor(81,183,244));
    colors.append(QColor(234,38,107));
    colors.append(QColor(92,247,217));
    colors.append(QColor(151,59,239));
    colors.append(QColor(231,72,28));
    colors.append(QColor(236,48,221));
    colors.append(QColor(75,133,243));
    colors.append(QColor(203,254,121));
    colors.append(QColor(104,64,240));
    colors.append(QColor(200,54,238));
    colors.append(QColor(104,250,138));
    colors.append(QColor(235,43,165));
    colors.append(QColor(98,248,176));
    colors.append(QColor(161,252,116));
    colors.append(QColor(87,231,246));
    colors.append(QColor(230,126,23));
lm's avatar
lm committed
88

pixhawk's avatar
pixhawk committed
89
    setAutoReplot(false);
lm's avatar
lm committed
90

pixhawk's avatar
pixhawk committed
91 92 93 94 95 96 97
    // Set grid
    QwtPlotGrid *grid = new QwtPlotGrid;
    grid->setMinPen(QPen(Qt::darkGray, 0, Qt::DotLine));
    grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine));
    grid->enableXMin(true);
    // TODO xmin?
    grid->attach(this);
lm's avatar
lm committed
98

pixhawk's avatar
pixhawk committed
99 100
    // Set left scale
    //setAxisOptions(QwtPlot::yLeft, QwtAutoScale::Logarithmic);
lm's avatar
lm committed
101

pixhawk's avatar
pixhawk committed
102 103 104 105
    // Set bottom scale
    setAxisScaleDraw(QwtPlot::xBottom, new TimeScaleDraw());
    setAxisLabelRotation(QwtPlot::xBottom, -25.0);
    setAxisLabelAlignment(QwtPlot::xBottom, Qt::AlignLeft | Qt::AlignBottom);
lm's avatar
lm committed
106

pixhawk's avatar
pixhawk committed
107
    // Add some space on the left and right side of the scale to prevent flickering
lm's avatar
lm committed
108

pixhawk's avatar
pixhawk committed
109 110 111
    QwtScaleWidget* bottomScaleWidget = axisWidget(QwtPlot::xBottom);
    const int fontMetricsX = QFontMetrics(bottomScaleWidget->font()).height();
    bottomScaleWidget->setMinBorderDist(fontMetricsX * 2, fontMetricsX / 2);
lm's avatar
lm committed
112

pixhawk's avatar
pixhawk committed
113
    plotLayout()->setAlignCanvasToScales(true);
lm's avatar
lm committed
114

pixhawk's avatar
pixhawk committed
115 116
    // Set canvas background
    setCanvasBackground(QColor(40, 40, 40));
lm's avatar
lm committed
117

pixhawk's avatar
pixhawk committed
118
    // Enable zooming
119 120
    //zoomer = new Zoomer(canvas());
    zoomer = new ScrollZoomer(canvas());
121
    zoomer->setRubberBandPen(QPen(Qt::blue, 1.2, Qt::DotLine));
pixhawk's avatar
pixhawk committed
122
    zoomer->setTrackerPen(QPen(Qt::blue));
lm's avatar
lm committed
123

pixhawk's avatar
pixhawk committed
124 125 126
    // Start QTimer for plot update
    updateTimer = new QTimer(this);
    connect(updateTimer, SIGNAL(timeout()), this, SLOT(paintRealtime()));
127
    //updateTimer->start(DEFAULT_REFRESH_RATE);
lm's avatar
lm committed
128

129
    connect(&timeoutTimer, SIGNAL(timeout()), this, SLOT(removeTimedOutCurves()));
130
    //timeoutTimer.start(5000);
pixhawk's avatar
pixhawk committed
131 132 133 134
}

LinechartPlot::~LinechartPlot()
{
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
//    datalock.lock();
//    // Delete curves
//    QMap<QString, QwtPlotCurve*>::iterator i;
//    for(i = curves.begin(); i != curves.end(); ++i) {
//        // Remove from curve list
//        QwtPlotCurve* curve = curves.take(i.key());
//        // Delete the object
//        delete curve;
//        // Set the pointer null
//        curve = NULL;
//    }

//    // Delete data
//    QMap<QString, TimeSeriesData*>::iterator j;
//    for(j = data.begin(); j != data.end(); ++j) {
//        // Remove from data list
//        TimeSeriesData* d = data.take(j.key());
//        // Delete the object
//        delete d;
//        // Set the pointer null
//        d = NULL;
//    }
//    datalock.unlock();
pixhawk's avatar
pixhawk committed
158 159
}

160 161 162 163 164 165 166 167 168 169 170 171
void LinechartPlot::showEvent(QShowEvent* event)
{
    Q_UNUSED(event);
    updateTimer->start(DEFAULT_REFRESH_RATE);
}

void LinechartPlot::hideEvent(QHideEvent* event)
{
    Q_UNUSED(event);
    updateTimer->stop();
}

pixhawk's avatar
pixhawk committed
172 173 174 175 176
int LinechartPlot::getPlotId()
{
    return this->plotid;
}

177 178 179 180 181 182 183 184
/**
 * @param id curve identifier
 */
double LinechartPlot::getCurrentValue(QString id)
{
    return data.value(id)->getCurrentValue();
}

pixhawk's avatar
pixhawk committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
/**
 * @param id curve identifier
 */
double LinechartPlot::getMean(QString id)
{
    return data.value(id)->getMean();
}

/**
 * @param id curve identifier
 */
double LinechartPlot::getMedian(QString id)
{
    return data.value(id)->getMedian();
}

201 202 203 204 205 206 207 208
/**
 * @param id curve identifier
 */
double LinechartPlot::getVariance(QString id)
{
    return data.value(id)->getVariance();
}

pixhawk's avatar
pixhawk committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
int LinechartPlot::getAverageWindow()
{
    return averageWindowSize;
}

/**
 * @brief Set the plot refresh rate
 * The default refresh rate is defined by LinechartPlot::DEFAULT_REFRESH_RATE.
 * @param ms The refresh rate in milliseconds
 **/
void LinechartPlot::setRefreshRate(int ms)
{
    updateTimer->setInterval(ms);
}

224 225 226 227
void LinechartPlot::setActive(bool active)
{
    m_active = active;
}
228

229 230 231 232 233
void LinechartPlot::removeTimedOutCurves()
{
    foreach(QString key, lastUpdate.keys())
    {
        quint64 time = lastUpdate.value(key);
234
        if (QGC::groundTimeMilliseconds() - time > 10000)
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        {
            // Remove this curve
            // Delete curves
            QwtPlotCurve* curve = curves.take(key);
            // Delete the object
            delete curve;
            // Set the pointer null
            curve = NULL;

            // Notify connected components about the removal
            emit curveRemoved(key);

            // Remove from data list
            TimeSeriesData* d = data.take(key);
            // Delete the object
            delete d;
            // Set the pointer null
            d = NULL;
253
            emit curveRemoved(key);
254 255 256 257
        }
    }
}

pixhawk's avatar
pixhawk committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
/**
 * @brief Set the zero (center line) value
 * The zero value defines the centerline of the plot.
 *
 * @param id The id of the curve
 * @param zeroValue The zero value
 **/
void LinechartPlot::setZeroValue(QString id, double zeroValue)
{
    if(data.contains(id)) {
        data.value(id)->setZeroValue(zeroValue);
    } else {
        data.insert(id, new TimeSeriesData(this, id, maxInterval, zeroValue));
    }
}

void LinechartPlot::appendData(QString dataname, quint64 ms, double value)
{
    /* Lock resource to ensure data integrity */
    datalock.lock();
lm's avatar
lm committed
278

pixhawk's avatar
pixhawk committed
279
    /* Check if dataset identifier already exists */
280
    if(!data.contains(dataname)) {
pixhawk's avatar
pixhawk committed
281
        addCurve(dataname);
282
        enforceGroundTime(m_groundTime);
283 284 285
//        qDebug() << "ADDING CURVE WITH" << dataname << ms << value;
//        qDebug() << "MINTIME:" << minTime << "MAXTIME:" << maxTime;
//        qDebug() << "LASTTIME:" << lastTime;
pixhawk's avatar
pixhawk committed
286
    }
lm's avatar
lm committed
287

pixhawk's avatar
pixhawk committed
288 289
    // Add new value
    TimeSeriesData* dataset = data.value(dataname);
lm's avatar
lm committed
290

291
    quint64 time;
lm's avatar
lm committed
292

pixhawk's avatar
pixhawk committed
293
    // Append data
294 295
    if (!m_groundTime)
    {
296
        // Use timestamp from dataset
297
        time = ms;
298
    }
299 300 301 302
    else
    {
        time = QGC::groundTimeMilliseconds();
    }
303
    dataset->append(time, value);
pixhawk's avatar
pixhawk committed
304

305 306
    lastUpdate.insert(dataname, time);

pixhawk's avatar
pixhawk committed
307 308 309 310
    // Scaling values
    if(ms < minTime) minTime = ms;
    if(ms > maxTime) maxTime = ms;
    storageInterval = maxTime - minTime;
lm's avatar
lm committed
311

312 313
    if(time > lastTime)
    {
pixhawk's avatar
pixhawk committed
314
        //qDebug() << "UPDATED LAST TIME!" << dataname << time << lastTime;
315 316
        lastTime = time;
    }
pixhawk's avatar
pixhawk committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

    //
    if (value < minValue) minValue = value;
    if (value > maxValue) maxValue = value;
    valueInterval = maxValue - minValue;

    // Assign dataset to curve
    QwtPlotCurve* curve = curves.value(dataname);
    curve->setRawData(dataset->getPlotX(), dataset->getPlotY(), dataset->getPlotCount());

    //    qDebug() << "mintime" << minTime << "maxtime" << maxTime << "last max time" << "window position" << getWindowPosition();

    datalock.unlock();
}

332 333 334 335 336 337
/**
 * @param enforce true to reset the data timestamp with the receive / ground timestamp
 */
void LinechartPlot::enforceGroundTime(bool enforce)
{
    m_groundTime = enforce;
lm's avatar
lm committed
338

339 340 341 342 343 344 345 346 347 348 349 350 351
    if (enforce)
    {
        lastTime = QGC::groundTimeMilliseconds();
        plotPosition = lastTime;
        maxTime = lastTime;
    }
    else
    {
        lastTime = 0;
        plotPosition = 0;
        minTime = 0;
        maxTime = 100;
    }
352 353
}

lm's avatar
lm committed
354 355 356 357 358 359 360 361
/**
 * @return True if the data points are stamped with the packet receive time
 */
bool LinechartPlot::groundTime()
{
    return m_groundTime;
}

pixhawk's avatar
pixhawk committed
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
void LinechartPlot::addCurve(QString id)
{
    QColor currentColor = getNextColor();

    // Create new curve and set style
    QwtPlotCurve* curve = new QwtPlotCurve(id);
    // Add curve to list
    curves.insert(id, curve);

    curve->setStyle(QwtPlotCurve::Lines);
    curve->setPaintAttribute(QwtPlotCurve::PaintFiltered);
    setCurveColor(id, currentColor);
    //curve->setBrush(currentColor); Leads to a filled curve
    //    curve->setRenderHint(QwtPlotItem::RenderAntialiased);

    curve->attach(this);
    //@TODO Color differentiation between the curves will be necessary

    /* Create symbol for datapoints on curve */
    /*
         * Symbols have significant performance penalty, better avoid them
         *
        QwtSymbol sym = QwtSymbol();
        sym.setStyle(QwtSymbol::Ellipse);
        sym.setPen(currentColor);
        sym.setSize(3);
        curve->setSymbol(sym);*/

    // Create dataset
    TimeSeriesData* dataset = new TimeSeriesData(this, id, this->plotInterval, maxInterval);

    // Add dataset to list
    data.insert(id, dataset);

    // Notify connected components about new curve
397
    emit curveAdded(id);
pixhawk's avatar
pixhawk committed
398 399 400 401 402 403
}

QColor LinechartPlot::getNextColor()
{
    /* Return current color and increment counter for next round */
    nextColor++;
404
    if(nextColor >= colors.count()) nextColor = 0;
pixhawk's avatar
pixhawk committed
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
    return colors[nextColor++];
}

QColor LinechartPlot::getColorForCurve(QString id)
{
    return curves.value(id)->pen().color();
}

/**
 * @brief Set the time window for the plot
 * The time window defines which data is shown in the plot.
 *
 * @param end The end of the interval in milliseconds
 * */
void LinechartPlot::setWindowPosition(quint64 end)
{
    windowLock.lock();
    if(end <= this->getMaxTime() && end >= (this->getMinTime() + this->getPlotInterval())) {
        plotPosition = end;
        setAxisScale(QwtPlot::xBottom, (plotPosition - getPlotInterval()), plotPosition, timeScaleStep);
    }
    //@TODO Update the rest of the plot and update drawing
    windowLock.unlock();
}

/**
 * @brief Get the time window position
 * The position marks the right edge of the plot window
 *
 * @return The position of the plot window, in milliseconds
 **/
quint64 LinechartPlot::getWindowPosition()
{
    return plotPosition;
}

/**
 * @brief Set the color of a curve
 *
 * This method emits the colorSet(id, color) signal.
 *
 * @param id The id-string of the curve
 * @param color The newly assigned color
 **/
void LinechartPlot::setCurveColor(QString id, QColor color)
{
    QwtPlotCurve* curve = curves.value(id);
    curve->setPen(color);

454
    emit colorSet(id, color);
pixhawk's avatar
pixhawk committed
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 484 485 486 487 488 489 490 491 492
}

/**
 * @brief Set the scaling of the (vertical) y axis
 * The mapping of the variable values on the drawing pane can be
 * adjusted with this method. The default is that the y axis will the chosen
 * to fit all curves in their normal base units. This can however hide all
 * details if large differences in the data values exist.
 *
 * The scaling can be changed to best fit, which fits all curves in a +100 to -100 interval.
 * The logarithmic scaling does not fit the variables, but instead applies a log10
 * scaling to all variables.
 *
 * @param scaling LinechartPlot::SCALE_ABSOLUTE for linear scaling, LinechartPlot::SCALE_BEST_FIT for the best fit scaling and LinechartPlot::SCALE_LOGARITHMIC for the logarithmic scaling.
 **/
void LinechartPlot::setScaling(int scaling)
{
    this->scaling = scaling;
    switch (scaling) {
    case LinechartPlot::SCALE_ABSOLUTE:
        setLinearScaling();
        break;
    case LinechartPlot::SCALE_LOGARITHMIC:
        setLogarithmicScaling();
        break;
    }
}

/**
 * @brief Change the visibility of a curve
 *
 * @param id The string id of the curve
 * @param visible The visibility: True to make it visible
 **/
void LinechartPlot::setVisible(QString id, bool visible)
{
    if(curves.contains(id)) {
        curves.value(id)->setVisible(visible);
493 494
        if(visible)
        {
pixhawk's avatar
pixhawk committed
495
            curves.value(id)->attach(this);
496 497 498
        }
        else
        {
pixhawk's avatar
pixhawk committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
            curves.value(id)->detach();
        }
    }
}

/**
 * @brief Hide a curve.
 *
 * This is a convenience method and maps to setVisible(id, false).
 *
 * @param id The curve to hide
 * @see setVisible() For the implementation
 **/
void LinechartPlot::hideCurve(QString id)
{
    setVisible(id, false);
}

/**
 * @brief Show a curve.
 *
 * This is a convenience method and maps to setVisible(id, true);
 *
 * @param id The curve to show
 * @see setVisible() For the implementation
 **/
void LinechartPlot::showCurve(QString id)
{
    setVisible(id, true);
}

//void LinechartPlot::showCurve(QString id, int position)
//{
//    //@TODO Implement this position-dependent
//    curves.value(id)->show();
//}

/**
 * @brief Check the visibility of a curve
 *
 * @param id The id of the curve
 * @return The visibility, true if it is visible, false otherwise
 **/
bool LinechartPlot::isVisible(QString id)
{
    return curves.value(id)->isVisible();
}

lm's avatar
lm committed
547 548 549 550 551 552
/**
 * @return The visibility, true if it is visible, false otherwise
 **/
bool LinechartPlot::anyCurveVisible()
{
    bool visible = false;
553 554 555 556
    foreach (QString key, curves.keys())
    {
        if (curves.value(key)->isVisible())
        {
lm's avatar
lm committed
557 558 559 560 561 562 563
            visible = true;
        }
    }

    return visible;
}

pixhawk's avatar
pixhawk committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
/**
 * @brief Allows to block interference of the automatic scrolling with user interaction
 * When the plot is updated very fast (at 1 ms for example) with new data, it might
 * get impossible for an user to interact. Therefore the automatic scrolling must be
 * explicitly activated.
 *
 * @param active The status of automatic scrolling, true to turn it on
 **/
void LinechartPlot::setAutoScroll(bool active)
{
    automaticScrollActive = active;
}

/**
 * @brief Get a list of all curves (visible and not visible curves)
 *
 * @return The list of curves
 **/
QList<QwtPlotCurve*> LinechartPlot::getCurves()
{
    return curves.values();
}

/**
 * @brief Get the smallest time value in all datasets
 *
 * @return The smallest time value
 **/
quint64 LinechartPlot::getMinTime()
{
    return minTime;
}

/**
 * @brief Get the biggest time value in all datasets
 *
 * @return The biggest time value
 **/
quint64 LinechartPlot::getMaxTime()
{
    return maxTime;
}

/**
 * @brief Get the plot interval
 * The plot interval is the time interval which is displayed on the plot
 *
 * @return The plot inteval in milliseconds
 * @see setPlotInterval()
 * @see getDataInterval() To get the interval for which data is available
 **/
quint64 LinechartPlot::getPlotInterval()
{
    return plotInterval;
}

/**
 * @brief Set the plot interval
 *
 * @param interval The time interval to plot, in milliseconds
 * @see getPlotInterval()
 **/
void LinechartPlot::setPlotInterval(int interval)
{
    plotInterval = interval;
    QMap<QString, TimeSeriesData*>::iterator j;
630 631
    for(j = data.begin(); j != data.end(); ++j)
    {
pixhawk's avatar
pixhawk committed
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        TimeSeriesData* d = data.value(j.key());
        d->setInterval(interval);
    }
}

/**
 * @brief Get the data interval
 * The data interval is defined by the time interval for which data
 * values are available.
 *
 * @return The data interval
 * @see getPlotInterval() To get the time interval which is currently displayed by the plot
 **/
quint64 LinechartPlot::getDataInterval()
{
    return storageInterval;
}

QList<QColor> LinechartPlot::getColorMap()
{
    return colors;
}

/**
 * @brief Set logarithmic scaling for the curve
 **/
void LinechartPlot::setLogarithmicScaling()
{
    yScaleEngine = new QwtLog10ScaleEngine();
    setAxisScaleEngine(QwtPlot::yLeft, yScaleEngine);
}

/**
 * @brief Set linear scaling for the curve
 **/
void LinechartPlot::setLinearScaling()
{
    yScaleEngine = new QwtLinearScaleEngine();
    setAxisScaleEngine(QwtPlot::yLeft, yScaleEngine);
}

void LinechartPlot::setAverageWindow(int windowSize)
{
    this->averageWindowSize = windowSize;
676 677
    foreach(TimeSeriesData* series, data)
    {
pixhawk's avatar
pixhawk committed
678 679 680 681 682 683 684 685 686 687 688
        series->setAverageWindowSize(windowSize);
    }
}

/**
 * @brief Paint immediately the plot
 * This method is a replacement for replot(). In contrast to replot(), it takes the
 * time window size and eventual zoom interaction into account.
 **/
void LinechartPlot::paintRealtime()
{
689
    if (m_active) {
690
#if (QGC_EVENTLOOP_DEBUG)
691 692 693
        static quint64 timestamp = 0;
        qDebug() << "EVENTLOOP: (" << MG::TIME::getGroundTimeNow() - timestamp << ")" << __FILE__ << __LINE__;
        timestamp = MG::TIME::getGroundTimeNow();
694
#endif
695 696
        // Update plot window value to new max time if the last time was also the max time
        windowLock.lock();
697 698
        if (automaticScrollActive)
        {
699 700 701

            // FIXME Check, but commenting this out should have been
            // beneficial (does only add complexity)
702 703 704 705 706 707 708 709
            //            if (MG::TIME::getGroundTimeNow() > maxTime && abs(MG::TIME::getGroundTimeNow() - maxTime) < 5000000)
            //            {
            //                plotPosition = MG::TIME::getGroundTimeNow();
            //            }
            //            else
            //            {
            plotPosition = lastTime;// + lastMaxTimeAdded.msec();
            //            }
710
            setAxisScale(QwtPlot::xBottom, plotPosition - plotInterval, plotPosition, timeScaleStep);
711 712 713

            // FIXME Last fix for scroll zoomer is here
            //setAxisScale(QwtPlot::yLeft, minValue + minValue * 0.05, maxValue + maxValue * 0.05f, (maxValue - minValue) / 10.0);
714
            /* Notify about change. Even if the window position was not changed
715 716
                     * itself, the relative position of the window to the interval must
                     * have changed, as the interval likely increased in length */
717 718
            emit windowPositionChanged(getWindowPosition());
        }
pixhawk's avatar
pixhawk committed
719

720
        windowLock.unlock();
pixhawk's avatar
pixhawk committed
721

722
        // Defined both on windows 32- and 64 bit
723
#if !(defined Q_OS_WIN)
pixhawk's avatar
pixhawk committed
724

725 726 727
        //    const bool cacheMode =
        //            canvas()->testPaintAttribute(QwtPlotCanvas::PaintCached);
        const bool oldDirectPaint =
728
            canvas()->testAttribute(Qt::WA_PaintOutsidePaintEvent);
pixhawk's avatar
pixhawk committed
729

730 731
        const QPaintEngine *pe = canvas()->paintEngine();
        bool directPaint = pe->hasFeature(QPaintEngine::PaintOutsidePaintEvent);
732
        //if ( pe->type() == QPaintEngine::X11 ) {
733 734 735
            // Even if not recommended by TrollTech, Qt::WA_PaintOutsidePaintEvent
            // works on X11. This has an tremendous effect on the performance..
            directPaint = true;
736
        //}
737
        canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, directPaint);
pixhawk's avatar
pixhawk committed
738 739
#endif

740 741
        // Only set current view as zoombase if zoomer is not active
        // else we could not zoom out any more
742

743
        if(zoomer->zoomStack().size() < 2) {
744
            zoomer->setZoomBase(true);
745
        } else {
746 747
            replot();
        }
pixhawk's avatar
pixhawk committed
748

749
#if !(defined Q_OS_WIN)
750
        canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, oldDirectPaint);
pixhawk's avatar
pixhawk committed
751 752 753
#endif


754
        /*
pixhawk's avatar
pixhawk committed
755 756 757 758 759 760 761 762
        QMap<QString, QwtPlotCurve*>::iterator i;
        for(i = curves.begin(); i != curves.end(); ++i) {
                const bool cacheMode = canvas()->testPaintAttribute(QwtPlotCanvas::PaintCached);
                canvas()->setPaintAttribute(QwtPlotCanvas::PaintCached, false);
                i.value()->drawItems();
                canvas()->setPaintAttribute(QwtPlotCanvas::PaintCached, cacheMode);
        }*/

763

764
    }
pixhawk's avatar
pixhawk committed
765 766 767 768 769 770 771 772 773 774
}

/**
 * @brief Removes all data and curves from the plot
 **/
void LinechartPlot::removeAllData()
{
    datalock.lock();
    // Delete curves
    QMap<QString, QwtPlotCurve*>::iterator i;
775 776
    for(i = curves.begin(); i != curves.end(); ++i)
    {
pixhawk's avatar
pixhawk committed
777 778 779 780 781 782 783 784
        // Remove from curve list
        QwtPlotCurve* curve = curves.take(i.key());
        // Delete the object
        delete curve;
        // Set the pointer null
        curve = NULL;

        // Notify connected components about the removal
785
        emit curveRemoved(i.key());
pixhawk's avatar
pixhawk committed
786 787 788 789
    }

    // Delete data
    QMap<QString, TimeSeriesData*>::iterator j;
790 791
    for(j = data.begin(); j != data.end(); ++j)
    {
pixhawk's avatar
pixhawk committed
792 793 794 795 796 797 798 799 800 801 802 803 804
        // Remove from data list
        TimeSeriesData* d = data.take(j.key());
        // Delete the object
        delete d;
        // Set the pointer null
        d = NULL;
    }
    datalock.unlock();
    replot();
}


TimeSeriesData::TimeSeriesData(QwtPlot* plot, QString friendlyName, quint64 plotInterval, quint64 maxInterval, double zeroValue):
805 806 807 808 809 810 811 812
    minValue(DBL_MAX),
    maxValue(DBL_MIN),
    zeroValue(0),
    count(0),
    mean(0.0),
    median(0.0),
    variance(0.0),
    averageWindow(50)
pixhawk's avatar
pixhawk committed
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
{
    this->plot = plot;
    this->friendlyName = friendlyName;
    this->maxInterval = maxInterval;
    this->zeroValue = zeroValue;
    this->plotInterval = plotInterval;

    /* initialize time */
    startTime = QUINT64_MAX;
    stopTime = QUINT64_MIN;

    plotCount = 0;
}

TimeSeriesData::~TimeSeriesData()
{

}

void TimeSeriesData::setInterval(quint64 ms)
{
    plotInterval = ms;
}

void TimeSeriesData::setAverageWindowSize(int windowSize)
{
    this->averageWindow = windowSize;
}

/**
 * @brief Append a data point to this data set
 *
 * @param ms The time in milliseconds
 * @param value The data value
 **/
void TimeSeriesData::append(quint64 ms, double value)
{
    dataMutex.lock();
    // Pre- allocate new space
852
    // FIXME Check this for validity
853
    if(static_cast<quint64>(size()) < (count + 100)) {
854 855
        this->ms.resize(size() + 10000);
        this->value.resize(size() + 10000);
pixhawk's avatar
pixhawk committed
856 857 858
    }
    this->ms[count] = ms;
    this->value[count] = value;
pixhawk's avatar
pixhawk committed
859
    this->lastValue = value;
pixhawk's avatar
pixhawk committed
860
    this->mean = 0;
861
    //QList<double> medianList = QList<double>();
862
    for (unsigned int i = 0; (i < averageWindow) && (((int)count - (int)i) >= 0); ++i) {
pixhawk's avatar
pixhawk committed
863
        this->mean += this->value[count-i];
864
        //medianList.append(this->value[count-i]);
pixhawk's avatar
pixhawk committed
865
    }
866
    this->mean = mean / static_cast<double>(qMin(averageWindow,static_cast<unsigned int>(count)));
867 868

    this->variance = 0;
869
    for (unsigned int i = 0; (i < averageWindow) && (((int)count - (int)i) >= 0); ++i) {
870
        this->variance += (this->value[count-i] - mean) * (this->value[count-i] - mean);
871 872 873
    }
    this->variance = this->variance / static_cast<double>(qMin(averageWindow,static_cast<unsigned int>(count)));

874 875 876 877 878 879 880 881 882 883 884 885 886
//    qSort(medianList);

//    if (medianList.count() > 2)
//    {
//        if (medianList.count() % 2 == 0)
//        {
//            median = (medianList.at(medianList.count()/2) + medianList.at(medianList.count()/2+1)) / 2.0;
//        }
//        else
//        {
//            median = medianList.at(medianList.count()/2+1);
//        }
//    }
pixhawk's avatar
pixhawk committed
887 888 889 890 891 892

    // Update statistical values
    if(ms < startTime) startTime = ms;
    if(ms > stopTime) stopTime = ms;
    interval = stopTime - startTime;

893 894
    if (interval > plotInterval) {
        while (this->ms[count - plotCount] < stopTime - plotInterval) {
pixhawk's avatar
pixhawk committed
895 896 897 898 899 900 901 902 903 904 905
            plotCount--;
        }
    }

    count++;
    plotCount++;

    if(minValue > value) minValue = value;
    if(maxValue < value) maxValue = value;

    // Trim dataset if necessary
906 907
    if(maxInterval > 0) {
        // maxInterval = 0 means infinite
pixhawk's avatar
pixhawk committed
908

909
        if(interval > maxInterval && !this->ms.isEmpty() && !this->value.isEmpty()) {
pixhawk's avatar
pixhawk committed
910
            // The time at which this time series should be cut
911
            double minTime = stopTime - maxInterval;
pixhawk's avatar
pixhawk committed
912 913
            // Delete elements from the start of the list as long the time
            // value of this elements is before the cut time
914
            while(this->ms.first() < minTime) {
915 916
                this->ms.pop_front();
                this->value.pop_front();
pixhawk's avatar
pixhawk committed
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
            }
        }
    }
    dataMutex.unlock();
}

/**
 * @brief Get the id of this data set
 *
 * @return The id-string
 **/
int TimeSeriesData::getID()
{
    return id;
}

/**
 * @brief Get the minimum value in the data set
 *
 * @return The minimum value
 **/
double TimeSeriesData::getMinValue()
{
    return minValue;
}

/**
 * @brief Get the maximum value in the data set
 *
 * @return The maximum value
 **/
double TimeSeriesData::getMaxValue()
{
    return maxValue;
}

/**
 * @return the mean
 */
double TimeSeriesData::getMean()
{
    return mean;
}

/**
 * @return the median
 */
double TimeSeriesData::getMedian()
{
    return median;
}

969 970 971 972 973 974 975 976
/**
 * @return the variance
 */
double TimeSeriesData::getVariance()
{
    return variance;
}

977 978
double TimeSeriesData::getCurrentValue()
{
pixhawk's avatar
pixhawk committed
979
    return lastValue;
980 981
}

pixhawk's avatar
pixhawk committed
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
/**
 * @brief Get the zero (center) value in the data set
 * The zero value is not a statistical value, but instead manually defined
 * when creating the data set.
 * @return The zero value
 **/
double TimeSeriesData::getZeroValue()
{
    return zeroValue;
}

/**
 * @brief Set the zero (center) value
 *
 * @param zeroValue The zero value
 * @see getZeroValue()
 **/
void TimeSeriesData::setZeroValue(double zeroValue)
{
    this->zeroValue = zeroValue;
}

/**
 * @brief Get the number of points in the dataset
 *
 * @return The number of points
 **/
int TimeSeriesData::getCount() const
{
    return count;
}

/**
 * @brief Get the number of points in the plot selection
 *
 * @return The number of points
 **/
int TimeSeriesData::getPlotCount() const
{
    return plotCount;
}

/**
 * @brief Get the data array size
 * The data array size is \e NOT equal to the number of items in the data set, as
 * array space is pre-allocated. Use getCount() to get the number of data points.
 *
 * @return The data array size
 * @see getCount()
 **/
int TimeSeriesData::size() const
{
    return ms.size();
}

/**
 * @brief Get the X (time) values
 *
 * @return The x values
 **/
const double* TimeSeriesData::getX() const
{
    return ms.data();
}

const double* TimeSeriesData::getPlotX() const
{
    return ms.data() + (count - plotCount);
}

/**
 * @brief Get the Y (data) values
 *
 * @return The y values
 **/
const double* TimeSeriesData::getY() const
{
    return value.data();
}

const double* TimeSeriesData::getPlotY() const
{
    return value.data() + (count - plotCount);
}