analyze.cpp 101 KB
Newer Older
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
/*  Ekos Analyze
    Copyright (C) 2020 Hy Murveit <hy@murveit.com>

    This application is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.
 */

#include "analyze.h"

#include <KNotifications/KNotification>
#include <QDateTime>
#include <QShortcut>
#include <QtGlobal>

#include "auxiliary/kspaths.h"
#include "dms.h"
#include "ekos/manager.h"
#include "fitsviewer/fitsdata.h"
#include "fitsviewer/fitsviewer.h"
#include "ksmessagebox.h"
#include "kstars.h"
#include "Options.h"

#include <ekos_analyze_debug.h>
#include <KHelpClient>
#include <version.h>

// Subclass QCPAxisTickerDateTime, so that times are offset from the start
// of the log, instead of being offset from the UNIX 0-seconds time.
class OffsetDateTimeTicker : public QCPAxisTickerDateTime
{
    public:
        void setOffset(double offset)
        {
            timeOffset = offset;
        }
        QString getTickLabel(double tick, const QLocale &locale, QChar formatChar, int precision) override
        {
            Q_UNUSED(precision);
            Q_UNUSED(formatChar);
            // Seconds are offset from the unix origin by
            return locale.toString(keyToDateTime(tick + timeOffset).toTimeSpec(mDateTimeSpec), mDateTimeFormat);
        }
    private:
        double timeOffset = 0;
};

namespace
{

// QDateTime is written to file with this format.
QString timeFormat = "yyyy-MM-dd hh:mm:ss.zzz";

// The resolution of the scroll bar.
constexpr int MAX_SCROLL_VALUE = 10000;

// Half the height of a timeline line.
// That is timeline lines are horizontal bars along y=1 or y=2 ... and their
// vertical widths are from y-halfTimelineHeight to y+halfTimelineHeight.
constexpr double halfTimelineHeight = 0.35;

// These are initialized in initStatsPlot when the graphs are added.
// They index the graphs in statsPlot, e.g. statsPlot->graph(HFR_GRAPH)->addData(...)
int HFR_GRAPH = -1;
67 68 69 70
int TEMPERATURE_GRAPH = -1;
int NUM_CAPTURE_STARS_GRAPH = -1;
int MEDIAN_GRAPH = -1;
int ECCENTRICITY_GRAPH = -1;
71 72 73 74 75 76 77 78 79
int NUMSTARS_GRAPH = -1;
int SKYBG_GRAPH = -1;
int SNR_GRAPH = -1;
int RA_GRAPH = -1;
int DEC_GRAPH = -1;
int RA_PULSE_GRAPH = -1;
int DEC_PULSE_GRAPH = -1;
int DRIFT_GRAPH = -1;
int RMS_GRAPH = -1;
80
int CAPTURE_RMS_GRAPH = -1;
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
int MOUNT_RA_GRAPH = -1;
int MOUNT_DEC_GRAPH = -1;
int MOUNT_HA_GRAPH = -1;
int AZ_GRAPH = -1;
int ALT_GRAPH = -1;
int PIER_SIDE_GRAPH = -1;

// Initialized in initGraphicsPlot().
int FOCUS_GRAPHICS = -1;
int FOCUS_GRAPHICS_FINAL = -1;
int GUIDER_GRAPHICS = -1;

// Brushes used in the timeline plot.
const QBrush temporaryBrush(Qt::green, Qt::DiagCrossPattern);
const QBrush timelineSelectionBrush(QColor(255, 100, 100, 150), Qt::SolidPattern);
const QBrush successBrush(Qt::green, Qt::SolidPattern);
const QBrush failureBrush(Qt::red, Qt::SolidPattern);
const QBrush offBrush(Qt::gray, Qt::SolidPattern);
const QBrush progressBrush(Qt::blue, Qt::SolidPattern);
const QBrush progress2Brush(QColor(0, 165, 255), Qt::SolidPattern);
const QBrush progress3Brush(Qt::cyan, Qt::SolidPattern);
const QBrush stoppedBrush(Qt::yellow, Qt::SolidPattern);
const QBrush stopped2Brush(Qt::darkYellow, Qt::SolidPattern);

// Utility to checks if a file exists and is not a directory.
bool fileExists(const QString &path)
{
    QFileInfo info(path);
    return info.exists() && info.isFile();
}

// Utilities to go between a mount status and a string.
// Move to inditelescope.h/cpp?
const QString mountStatusString(ISD::Telescope::Status status)
{
    switch (status)
    {
        case ISD::Telescope::MOUNT_IDLE:
            return i18n("Idle");
        case ISD::Telescope::MOUNT_PARKED:
            return i18n("Parked");
        case ISD::Telescope::MOUNT_PARKING:
            return i18n("Parking");
        case ISD::Telescope::MOUNT_SLEWING:
            return i18n("Slewing");
        case ISD::Telescope::MOUNT_MOVING:
            return i18n("Moving");
        case ISD::Telescope::MOUNT_TRACKING:
            return i18n("Tracking");
        case ISD::Telescope::MOUNT_ERROR:
            return i18n("Error");
    }
    return i18n("Error");
}

ISD::Telescope::Status toMountStatus(const QString &str)
{
    if (str == i18n("Idle"))
        return ISD::Telescope::MOUNT_IDLE;
    else if (str == i18n("Parked"))
        return ISD::Telescope::MOUNT_PARKED;
    else if (str == i18n("Parking"))
        return ISD::Telescope::MOUNT_PARKING;
    else if (str == i18n("Slewing"))
        return ISD::Telescope::MOUNT_SLEWING;
    else if (str == i18n("Moving"))
        return ISD::Telescope::MOUNT_MOVING;
    else if (str == i18n("Tracking"))
        return ISD::Telescope::MOUNT_TRACKING;
    else
        return ISD::Telescope::MOUNT_ERROR;
}

// Returns the stripe color used when drawing the capture timeline for various filters.
// TODO: Not sure how to internationalize this.
bool filterStripeBrush(const QString &filter, QBrush *brush)
{
    if (!filter.compare("red", Qt::CaseInsensitive) ||
            !filter.compare("r", Qt::CaseInsensitive))
    {
        *brush = QBrush(Qt::red, Qt::SolidPattern);
        return true;
    }
    else if (!filter.compare("green", Qt::CaseInsensitive) ||
             !filter.compare("g", Qt::CaseInsensitive))
    {
        *brush = QBrush(Qt::green, Qt::SolidPattern);
        return true;
    }
    else if (!filter.compare("blue", Qt::CaseInsensitive) ||
             !filter.compare("b", Qt::CaseInsensitive))
    {
        *brush = QBrush(Qt::blue, Qt::SolidPattern);
        return true;
    }
    else if (!filter.compare("ha", Qt::CaseInsensitive) ||
             !filter.compare("h", Qt::CaseInsensitive) ||
             !filter.compare("h_alpha", Qt::CaseInsensitive) ||
             !filter.compare("halpha", Qt::CaseInsensitive))
    {
        *brush = QBrush(Qt::darkRed, Qt::SolidPattern);
        return true;
    }
    else if (!filter.compare("oiii", Qt::CaseInsensitive) ||
             !filter.compare("o3", Qt::CaseInsensitive))
    {
        *brush = QBrush(Qt::cyan, Qt::SolidPattern);
        return true;
    }
    else if (!filter.compare("sii", Qt::CaseInsensitive) ||
             !filter.compare("s2", Qt::CaseInsensitive))
    {
        // Pink.
        *brush = QBrush(QColor(255, 182, 193), Qt::SolidPattern);
        return true;
    }
    else if (!filter.compare("lpr", Qt::CaseInsensitive) ||
             !filter.compare("L", Qt::CaseInsensitive) ||
             !filter.compare("luminance", Qt::CaseInsensitive) ||
             !filter.compare("lum", Qt::CaseInsensitive) ||
             !filter.compare("lps", Qt::CaseInsensitive) ||
             !filter.compare("cls", Qt::CaseInsensitive))
    {
        *brush = QBrush(Qt::white, Qt::SolidPattern);
        return true;
    }
    return false;
}

// Used when searching for FITS files to display.
// If filename isn't found as is, it tries alterateDirectory in several ways
// e.g. if filename = /1/2/3/4/name is not found, then try alternateDirectory/name,
// then alternateDirectory/4/name, then alternateDirectory/3/4/name,
// then alternateDirectory/2/3/4/name, and so on.
// If it cannot find the FITS file, it returns an empty string, otherwise it returns
// the full path where the file was found.
QString findFilename(const QString &filename, const QString &alternateDirectory)
{
    // Try the origial full path.
    QFileInfo info(filename);
    if (info.exists() && info.isFile())
        return filename;

    // Try putting the filename at the end of the full path onto alternateDirectory.
    QString name = info.fileName();
    QString temp = QString("%1/%2").arg(alternateDirectory).arg(name);
    if (fileExists(temp))
        return temp;

    // Try appending the filename plus the ending directories onto alternateDirectory.
    int size = filename.size();
    int searchBackFrom = size - name.size();
    int num = 0;
    while (searchBackFrom >= 0)
    {
        int index = filename.lastIndexOf('/', searchBackFrom);
        if (index < 0)
            break;

        QString temp2 = QString("%1%2").arg(alternateDirectory).arg(filename.right(size - index));
        if (fileExists(temp2))
            return temp2;

        searchBackFrom = index - 1;

        // Paranoia
        if (++num > 20)
            break;
    }
    return "";
}

// This is an exhaustive search for now.
// This is reasonable as the number of sessions should be limited.
template <class T>
class IntervalFinder
{
    public:
        IntervalFinder() {}
        ~IntervalFinder() {}
        void add(T value)
        {
            intervals.append(value);
        }
        void clear()
        {
            intervals.clear();
        }
        QList<T> find(double t)
        {
            QList<T> result;
            for (const auto i : intervals)
            {
                if (t >= i.start && t <= i.end)
                    result.push_back(i);
            }
            return result;
        }
    private:
        QList<T> intervals;
};

IntervalFinder<Ekos::Analyze::CaptureSession> captureSessions;
IntervalFinder<Ekos::Analyze::FocusSession> focusSessions;
IntervalFinder<Ekos::Analyze::GuideSession> guideSessions;
IntervalFinder<Ekos::Analyze::MountSession> mountSessions;
IntervalFinder<Ekos::Analyze::AlignSession> alignSessions;
IntervalFinder<Ekos::Analyze::MountFlipSession> mountFlipSessions;

}  // namespace

namespace Ekos
{

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
// RmsFilter computes the RMS error of a 2-D sequence. Input the x error and y error
// into newSample(). It returns the sqrt of an approximate moving average of the squared
// errors roughly averaged over 40 samples--implemented by a simple digital low-pass filter.
// It's used to compute RMS guider errors, where x and y would be RA and DEC errors.
class RmsFilter
{
    public:
        RmsFilter()
        {
            constexpr double timeConstant = 40.0;
            alpha = 1.0 / pow(timeConstant, 0.865);
        }
        void resetFilter()
        {
            filteredRMS = 0;
        }
        double newSample(double x, double y)
        {
            const double valueSquared = x * x + y * y;
            filteredRMS = alpha * valueSquared + (1.0 - alpha) * filteredRMS;
            return sqrt(filteredRMS);
        }
    private:
        double alpha { 0 };
        double filteredRMS { 0 };
};

322 323 324 325
Analyze::Analyze()
{
    setupUi(this);

326 327
    captureRms.reset(new RmsFilter);
    guiderRms.reset(new RmsFilter);
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

    alternateFolder = QDir::homePath();

    initInputSelection();
    initTimelinePlot();
    initStatsPlot();
    initGraphicsPlot();
    fullWidthCB->setChecked(true);
    runtimeDisplay = true;
    fullWidthCB->setVisible(true);
    fullWidthCB->setDisabled(false);
    connect(fullWidthCB, &QCheckBox::toggled, [ = ](bool checked)
    {
        if (checked)
            this->replot();
    });

    initStatsCheckboxes();

    connect(zoomInB, &QPushButton::clicked, this, &Ekos::Analyze::zoomIn);
    connect(zoomOutB, &QPushButton::clicked, this, &Ekos::Analyze::zoomOut);
    connect(timelinePlot, &QCustomPlot::mousePress, this, &Ekos::Analyze::timelineMousePress);
    connect(timelinePlot, &QCustomPlot::mouseDoubleClick, this, &Ekos::Analyze::timelineMouseDoubleClick);
    connect(timelinePlot, &QCustomPlot::mouseWheel, this, &Ekos::Analyze::timelineMouseWheel);
    connect(statsPlot, &QCustomPlot::mousePress, this, &Ekos::Analyze::statsMousePress);
    connect(statsPlot, &QCustomPlot::mouseDoubleClick, this, &Ekos::Analyze::statsMouseDoubleClick);
    connect(statsPlot, &QCustomPlot::mouseMove, this, &Ekos::Analyze::statsMouseMove);
    connect(analyzeSB, &QScrollBar::valueChanged, this, &Ekos::Analyze::scroll);
    analyzeSB->setRange(0, MAX_SCROLL_VALUE);
    connect(helpB, &QPushButton::clicked, this, &Ekos::Analyze::helpMessage);
    connect(keepCurrentCB, &QCheckBox::stateChanged, this, &Ekos::Analyze::keepCurrent);

    setupKeyboardShortcuts(timelinePlot);

362
    reset();
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
    replot();
}

// Mouse wheel over the Timeline plot causes an x-axis zoom.
void Analyze::timelineMouseWheel(QWheelEvent *event)
{
    if (event->angleDelta().y() > 0)
        zoomIn();
    else if (event->angleDelta().y() < 0)
        zoomOut();
}

// This callback is used so that when keepCurrent is checked, we replot immediately.
// The actual keepCurrent work is done in replot().
void Analyze::keepCurrent(int state)
{
    Q_UNUSED(state);
    if (keepCurrentCB->isChecked())
    {
        removeStatsCursor();
        replot();
    }
}

// Implements the input selection UI. User can either choose the current Ekos
// session, or a file read from disk, or set the alternateDirectory variable.
void Analyze::initInputSelection()
{
    // Setup the input combo box.
    dirPath = QUrl::fromLocalFile(KSPaths::writableLocation(
                                      QStandardPaths::GenericDataLocation) + "analyze/");

Yuri Chornoivan's avatar
Yuri Chornoivan committed
395 396 397
    inputCombo->addItem(i18n("Current Session"));
    inputCombo->addItem(i18n("Read from File"));
    inputCombo->addItem(i18n("Set alternative image-file base directory"));
398 399 400 401 402 403 404 405 406
    inputValue->setText("");
    connect(inputCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, [&](int index)
    {
        if (index == 0)
        {
            // Input from current session
            if (!runtimeDisplay)
            {
                reset();
Yuri Chornoivan's avatar
Yuri Chornoivan committed
407
                inputValue->setText(i18n("Current Session"));
408 409 410 411 412 413 414 415 416 417 418 419
                maxXValue = readDataFromFile(logFilename);
                runtimeDisplay = true;
            }
            fullWidthCB->setChecked(true);
            fullWidthCB->setVisible(true);
            fullWidthCB->setDisabled(false);
            replot();
        }
        else if (index == 1)
        {
            // Input from a file.
            QUrl inputURL = QFileDialog::getOpenFileUrl(this, i18n("Select input file"), dirPath,
Yuri Chornoivan's avatar
Yuri Chornoivan committed
420
                            i18n("Analyze Log (*.analyze);;All Files (*)"));
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
            if (inputURL.isEmpty())
                return;
            dirPath = QUrl(inputURL.url(QUrl::RemoveFilename));

            reset();
            inputValue->setText(inputURL.fileName());

            // If we do this after the readData call below, it would animate the sequence.
            runtimeDisplay = false;

            maxXValue = readDataFromFile(inputURL.toLocalFile());
            plotStart = 0;
            plotWidth = maxXValue + 5;
            replot();
        }
        else if (index == 2)
        {
            QString dir = QFileDialog::getExistingDirectory(
Yuri Chornoivan's avatar
Yuri Chornoivan committed
439
                              this, i18n("Set an alternate base directory for your captured images"),
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 484 485 486 487 488 489 490
                              QDir::homePath(),
                              QFileDialog::ShowDirsOnly);
            if (dir.size() > 0)
            {
                // TODO: replace with an option.
                alternateFolder = dir;
            }
            // This is not a destiation, reset to one of the above.
            if (runtimeDisplay)
                inputCombo->setCurrentIndex(0);
            else
                inputCombo->setCurrentIndex(1);
        }
    });
}

void Analyze::setupKeyboardShortcuts(QCustomPlot *plot)
{
    // Shortcuts defined: https://doc.qt.io/archives/qt-4.8/qkeysequence.html#standard-shortcuts
    QShortcut *s = new QShortcut(QKeySequence(QKeySequence::ZoomIn), plot);
    connect(s, &QShortcut::activated, this, &Ekos::Analyze::zoomIn);
    s = new QShortcut(QKeySequence(QKeySequence::ZoomOut), plot);
    connect(s, &QShortcut::activated, this, &Ekos::Analyze::zoomOut);
    s = new QShortcut(QKeySequence(QKeySequence::MoveToNextChar), plot);
    connect(s, &QShortcut::activated, this, &Ekos::Analyze::scrollRight);
    s = new QShortcut(QKeySequence(QKeySequence::MoveToPreviousChar), plot);
    connect(s, &QShortcut::activated, this, &Ekos::Analyze::scrollLeft);
    s = new QShortcut(QKeySequence("?"), plot);
    connect(s, &QShortcut::activated, this, &Ekos::Analyze::helpMessage);
    s = new QShortcut(QKeySequence("h"), plot);
    connect(s, &QShortcut::activated, this, &Ekos::Analyze::helpMessage);
    s = new QShortcut(QKeySequence(QKeySequence::HelpContents), plot);
    connect(s, &QShortcut::activated, this, &Ekos::Analyze::helpMessage);
}

Analyze::~Analyze()
{
    // TODO:
    // We should write out to disk any sessions that haven't terminated
    // (e.g. capture, focus, guide)
}

// When a user selects a timeline session, the previously selected one
// is deselected.  Note: this does not replot().
void Analyze::unhighlightTimelineItem()
{
    if (selectionHighlight != nullptr)
    {
        timelinePlot->removeItem(selectionHighlight);
        selectionHighlight = nullptr;
    }
491
    detailsTable->clear();
492 493 494 495 496 497 498 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 547
}

// Highlight the area between start and end on row y in Timeline.
// Note that this doesn't replot().
void Analyze::highlightTimelineItem(double y, double start, double end)
{
    constexpr double halfHeight = 0.5;
    unhighlightTimelineItem();

    QCPItemRect *rect = new QCPItemRect(timelinePlot);
    rect->topLeft->setCoords(start, y + halfHeight);
    rect->bottomRight->setCoords(end, y - halfHeight);
    rect->setBrush(timelineSelectionBrush);
    selectionHighlight = rect;
}

// Creates a fat line-segment on the Timeline, optionally with a stripe in the middle.
QCPItemRect * Analyze::addSession(double start, double end, double y,
                                  const QBrush &brush, const QBrush *stripeBrush)
{
    QPen pen = QPen(Qt::black, 1, Qt::SolidLine);
    QCPItemRect *rect = new QCPItemRect(timelinePlot);
    rect->topLeft->setCoords(start, y + halfTimelineHeight);
    rect->bottomRight->setCoords(end, y - halfTimelineHeight);
    rect->setPen(pen);
    rect->setSelectedPen(pen);
    rect->setBrush(brush);
    rect->setSelectedBrush(brush);

    if (stripeBrush != nullptr)
    {
        QCPItemRect *stripe = new QCPItemRect(timelinePlot);
        stripe->topLeft->setCoords(start, y + halfTimelineHeight / 2.0);
        stripe->bottomRight->setCoords(end, y - halfTimelineHeight / 2.0);
        stripe->setPen(pen);
        stripe->setBrush(*stripeBrush);
    }
    return rect;
}

// Add the guide stats values to the Stats graphs.
// We want to avoid drawing guide-stat values when not guiding.
// That is, we have no input samples then, but the graph would connect
// two points with a line. By adding NaN values into the graph,
// those places are made invisible.
void Analyze::addGuideStats(double raDrift, double decDrift, int raPulse, int decPulse, double snr,
                            int numStars, double skyBackground, double time)
{
    double MAX_GUIDE_STATS_GAP = 30;

    if (time - lastGuideStatsTime > MAX_GUIDE_STATS_GAP &&
            lastGuideStatsTime >= 0)
    {
        addGuideStatsInternal(qQNaN(), qQNaN(), 0, 0, qQNaN(), qQNaN(), qQNaN(), qQNaN(), qQNaN(),
                              lastGuideStatsTime + .0001);
        addGuideStatsInternal(qQNaN(), qQNaN(), 0, 0, qQNaN(), qQNaN(), qQNaN(), qQNaN(), qQNaN(), time - .0001);
548
        guiderRms->resetFilter();
549 550 551 552 553
    }

    const double drift = std::hypot(raDrift, decDrift);

    // To compute the RMS error, which is sqrt(sum square error / N), filter the squared
554 555 556
    // error, which effectively returns sum squared error / N, and take the sqrt.
    // This is done by RmsFilter::newSample().
    const double rms = guiderRms->newSample(raDrift, decDrift);
557
    addGuideStatsInternal(raDrift, decDrift, double(raPulse), double(decPulse), snr, numStars, skyBackground, drift, rms, time);
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

    // If capture is active, plot the capture RMS.
    if (captureStartedTime >= 0)
    {
        // lastCaptureRmsTime is the last time we plotted a capture RMS value.
        // If we have plotted values previously, and there's a gap in guiding
        // we must place NaN values in the graph surrounding the gap.
        if ((lastCaptureRmsTime >= 0) &&
                (time - lastCaptureRmsTime > MAX_GUIDE_STATS_GAP))
        {
            // this is the first sample in a series with a gap behind us.
            statsPlot->graph(CAPTURE_RMS_GRAPH)->addData(lastCaptureRmsTime + .0001, qQNaN());
            statsPlot->graph(CAPTURE_RMS_GRAPH)->addData(time - .0001, qQNaN());
            // I can go either way on this. E.g. resetting the filter will start the RMS
            // average over again, e.g. after a autofocus where the guider was suspended
            // for a couple minutes. Not having it will average the new capture's guide
            // errors with the previous capture's. This is, of course, a display decision.
            // The actual guiding is not affected. I went with not resetting the RMS filter
            // that only uses guiding samples during capture, and resetting the one that
            // uses all guider samples (guiderRms above).
            // captureRms->resetFilter();
        }
        const double rmsC = captureRms->newSample(raDrift, decDrift);
        statsPlot->graph(CAPTURE_RMS_GRAPH)->addData(time, rmsC);
        lastCaptureRmsTime = time;
    }

585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
    lastGuideStatsTime = time;
}

void Analyze::addGuideStatsInternal(double raDrift, double decDrift, double raPulse,
                                    double decPulse, double snr,
                                    double numStars, double skyBackground,
                                    double drift, double rms, double time)
{
    statsPlot->graph(RA_GRAPH)->addData(time, raDrift);
    statsPlot->graph(DEC_GRAPH)->addData(time, decDrift);
    statsPlot->graph(RA_PULSE_GRAPH)->addData(time, raPulse);
    statsPlot->graph(DEC_PULSE_GRAPH)->addData(time, decPulse);
    statsPlot->graph(DRIFT_GRAPH)->addData(time, drift);
    statsPlot->graph(RMS_GRAPH)->addData(time, rms);

    // Set the SNR axis' maximum to 95% of the way up from the middle to the top.
    if (!qIsNaN(snr))
        snrMax = std::max(snr, snrMax);
    if (!qIsNaN(skyBackground))
        skyBgMax = std::max(skyBackground, skyBgMax);
    if (!qIsNaN(numStars))
        numStarsMax = std::max(numStars, static_cast<double>(numStarsMax));

    snrAxis->setRange(-1.05 * snrMax, std::max(10.0, 1.05 * snrMax));
609 610
    medianAxis->setRange(-1.35 * medianMax, std::max(10.0, 1.35 * medianMax));
    numCaptureStarsAxis->setRange(-1.45 * numCaptureStarsMax, std::max(10.0, 1.45 * numCaptureStarsMax));
611 612 613 614 615 616 617 618
    skyBgAxis->setRange(0, std::max(10.0, 1.15 * skyBgMax));
    numStarsAxis->setRange(0, std::max(10.0, 1.25 * numStarsMax));

    statsPlot->graph(SNR_GRAPH)->addData(time, snr);
    statsPlot->graph(NUMSTARS_GRAPH)->addData(time, numStars);
    statsPlot->graph(SKYBG_GRAPH)->addData(time, skyBackground);
}

619 620 621 622 623 624
void Analyze::addTemperature(double temperature, double time)
{
    // The HFR corresponds to the last capture
    statsPlot->graph(TEMPERATURE_GRAPH)->addData(time, temperature);
}

625
// Add the HFR values to the Stats graph, as a constant value between startTime and time.
626 627
void Analyze::addHFR(double hfr, int numCaptureStars, int median, double eccentricity,
                     double time, double startTime)
628 629 630 631 632 633
{
    // The HFR corresponds to the last capture
    statsPlot->graph(HFR_GRAPH)->addData(startTime - .0001, qQNaN());
    statsPlot->graph(HFR_GRAPH)->addData(startTime, hfr);
    statsPlot->graph(HFR_GRAPH)->addData(time, hfr);
    statsPlot->graph(HFR_GRAPH)->addData(time + .0001, qQNaN());
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651

    statsPlot->graph(NUM_CAPTURE_STARS_GRAPH)->addData(startTime - .0001, qQNaN());
    statsPlot->graph(NUM_CAPTURE_STARS_GRAPH)->addData(startTime, numCaptureStars);
    statsPlot->graph(NUM_CAPTURE_STARS_GRAPH)->addData(time, numCaptureStars);
    statsPlot->graph(NUM_CAPTURE_STARS_GRAPH)->addData(time + .0001, qQNaN());

    statsPlot->graph(MEDIAN_GRAPH)->addData(startTime - .0001, qQNaN());
    statsPlot->graph(MEDIAN_GRAPH)->addData(startTime, median);
    statsPlot->graph(MEDIAN_GRAPH)->addData(time, median);
    statsPlot->graph(MEDIAN_GRAPH)->addData(time + .0001, qQNaN());

    statsPlot->graph(ECCENTRICITY_GRAPH)->addData(startTime - .0001, qQNaN());
    statsPlot->graph(ECCENTRICITY_GRAPH)->addData(startTime, eccentricity);
    statsPlot->graph(ECCENTRICITY_GRAPH)->addData(time, eccentricity);
    statsPlot->graph(ECCENTRICITY_GRAPH)->addData(time + .0001, qQNaN());

    medianMax = std::max(median, medianMax);
    numCaptureStarsMax = std::max(numCaptureStars, numCaptureStarsMax);
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
}

// Add the Mount Coordinates values to the Stats graph.
// All but pierSide are in double degrees.
void Analyze::addMountCoords(double ra, double dec, double az,
                             double alt, int pierSide, double ha, double time)
{
    statsPlot->graph(MOUNT_RA_GRAPH)->addData(time, ra);
    statsPlot->graph(MOUNT_DEC_GRAPH)->addData(time, dec);
    statsPlot->graph(MOUNT_HA_GRAPH)->addData(time, ha);
    statsPlot->graph(AZ_GRAPH)->addData(time, az);
    statsPlot->graph(ALT_GRAPH)->addData(time, alt);
    statsPlot->graph(PIER_SIDE_GRAPH)->addData(time, double(pierSide));
}

// Read a .analyze file, and setup all the graphics.
double Analyze::readDataFromFile(const QString &filename)
{
    double lastTime = 10;
    QFile inputFile(filename);
    if (inputFile.open(QIODevice::ReadOnly))
    {
        QTextStream in(&inputFile);
        while (!in.atEnd())
        {
            QString line = in.readLine();
            double time = processInputLine(line);
            if (time > lastTime)
                lastTime = time;
        }
        inputFile.close();
    }
    return lastTime;
}

// Process an input line read from a .analyze file.
double Analyze::processInputLine(const QString &line)
{
    bool ok;
    // Break the line into comma-separated components
    QStringList list = line.split(QLatin1Char(','));
    // We need at least a command and a timestamp
    if (list.size() < 2)
        return 0;
    if (list[0].at(0).toLatin1() == '#')
    {
        // Comment character # must be at start of line.
        return 0;
    }

    if ((list[0] == "AnalyzeStartTime") && list.size() == 3)
    {
        displayStartTime = QDateTime::fromString(list[1], timeFormat);
        startTimeInitialized = true;
        analyzeTimeZone = list[2];
        return 0;
    }

    // Except for comments and the above AnalyzeStartTime, the second item
    // in the csv line is a double which represents seconds since start of the log.
    const double time = QString(list[1]).toDouble(&ok);
    if (!ok)
        return 0;
715 716
    if (time < 0 || time > 3600 * 24 * 10)
        return 0;
717 718 719 720 721 722 723 724 725

    if ((list[0] == "CaptureStarting") && (list.size() == 4))
    {
        const double exposureSeconds = QString(list[2]).toDouble(&ok);
        if (!ok)
            return 0;
        const QString filter = list[3];
        processCaptureStarting(time, exposureSeconds, filter, true);
    }
726
    else if ((list[0] == "CaptureComplete") && (list.size() >= 6) && (list.size() <= 9))
727 728 729 730 731 732 733 734 735
    {
        const double exposureSeconds = QString(list[2]).toDouble(&ok);
        if (!ok)
            return 0;
        const QString filter = list[3];
        const double hfr = QString(list[4]).toDouble(&ok);
        if (!ok)
            return 0;
        const QString filename = list[5];
736 737 738 739 740 741 742 743 744 745
        const int numStars = (list.size() > 6) ? QString(list[6]).toInt(&ok) : 0;
        if (!ok)
            return 0;
        const int median = (list.size() > 7) ? QString(list[7]).toInt(&ok) : 0;
        if (!ok)
            return 0;
        const double eccentricity = (list.size() > 8) ? QString(list[8]).toDouble(&ok) : 0;
        if (!ok)
            return 0;
        processCaptureComplete(time, filename, exposureSeconds, filter, hfr, numStars, median, eccentricity, true);
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
    }
    else if ((list[0] == "CaptureAborted") && (list.size() == 3))
    {
        const double exposureSeconds = QString(list[2]).toDouble(&ok);
        if (!ok)
            return 0;
        processCaptureAborted(time, exposureSeconds, true);
    }
    else if ((list[0] == "AutofocusStarting") && (list.size() == 4))
    {
        QString filter = list[2];
        double temperature = QString(list[3]).toDouble(&ok);
        if (!ok)
            return 0;
        processAutofocusStarting(time, temperature, filter, true);
    }
    else if ((list[0] == "AutofocusComplete") && (list.size() == 4))
    {
        QString filter = list[2];
        QString samples = list[3];
        processAutofocusComplete(time, filter, samples, true);
    }
    else if ((list[0] == "AutofocusAborted") && (list.size() == 4))
    {
        QString filter = list[2];
        QString samples = list[3];
        processAutofocusAborted(time, filter, samples, true);
    }
    else if ((list[0] == "GuideState") && list.size() == 3)
    {
        processGuideState(time, list[2], true);
    }
    else if ((list[0] == "GuideStats") && list.size() == 9)
    {
        const double ra = QString(list[2]).toDouble(&ok);
        if (!ok)
            return 0;
        const double dec = QString(list[3]).toDouble(&ok);
        if (!ok)
            return 0;
        const double raPulse = QString(list[4]).toInt(&ok);
        if (!ok)
            return 0;
        const double decPulse = QString(list[5]).toInt(&ok);
        if (!ok)
            return 0;
        const double snr = QString(list[6]).toDouble(&ok);
        if (!ok)
            return 0;
        const double skyBg = QString(list[7]).toDouble(&ok);
        if (!ok)
            return 0;
        const double numStars = QString(list[8]).toInt(&ok);
        if (!ok)
            return 0;
        processGuideStats(time, ra, dec, raPulse, decPulse, snr, skyBg, numStars, true);
    }
803 804 805 806 807 808 809
    else if ((list[0] == "Temperature") && list.size() == 3)
    {
        const double temperature = QString(list[2]).toDouble(&ok);
        if (!ok)
            return 0;
        processTemperature(time, temperature, true);
    }
810 811 812 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
    else if ((list[0] == "MountState") && list.size() == 3)
    {
        processMountState(time, list[2], true);
    }
    else if ((list[0] == "MountCoords") && (list.size() == 7 || list.size() == 8))
    {
        const double ra = QString(list[2]).toDouble(&ok);
        if (!ok)
            return 0;
        const double dec = QString(list[3]).toDouble(&ok);
        if (!ok)
            return 0;
        const double az = QString(list[4]).toDouble(&ok);
        if (!ok)
            return 0;
        const double alt = QString(list[5]).toDouble(&ok);
        if (!ok)
            return 0;
        const int side = QString(list[6]).toInt(&ok);
        if (!ok)
            return 0;
        const double ha = (list.size() > 7) ? QString(list[7]).toDouble(&ok) : 0;
        if (!ok)
            return 0;
        processMountCoords(time, ra, dec, az, alt, side, ha, true);
    }
    else if ((list[0] == "AlignState") && list.size() == 3)
    {
        processAlignState(time, list[2], true);
    }
    else if ((list[0] == "MeridianFlipState") && list.size() == 3)
    {
        processMountFlipState(time, list[2], true);
    }
    else
    {
        return 0;
    }
    return time;
}

851 852 853 854 855
namespace
{
void addDetailsRow(QTableWidget *table, const QString &col1, const QColor &color1,
                   const QString &col2, const QColor &color2,
                   const QString &col3 = "", const QColor &color3 = Qt::white)
856
{
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
    int row = table->rowCount();
    table->setRowCount(row + 1);

    QTableWidgetItem *item = new QTableWidgetItem();
    item->setText(col1);
    item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    item->setForeground(color1);
    table->setItem(row, 0, item);

    item = new QTableWidgetItem();
    item->setText(col2);
    item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    item->setForeground(color2);
    if (col1 == "Filename")
    {
        // Special Case long filenames.
        QFont ft = item->font();
        ft.setPointSizeF(8.0);
        item->setFont(ft);
    }
    table->setItem(row, 1, item);

    if (col3.size() > 0)
    {
        item = new QTableWidgetItem();
        item->setText(col3);
        item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
        item->setForeground(color3);
        table->setItem(row, 2, item);
    }
    else
    {
        // Column 1 spans 2nd and 3rd columns
        table->setSpan(row, 1, 1, 2);
    }
}
}

// Helper to create tables in the details display.
// Start the table, displaying the heading and timing information, common to all sessions.
void Analyze::Session::setupTable(const QString &name, const QString &status,
                                  const QDateTime &startClock, const QDateTime &endClock, QTableWidget *table)
{
    details = table;
    details->clear();
    details->setRowCount(0);
    details->setEditTriggers(QAbstractItemView::NoEditTriggers);
    details->setColumnCount(3);
    details->verticalHeader()->setDefaultSectionSize(20);
    details->horizontalHeader()->setStretchLastSection(true);
    details->setColumnWidth(0, 100);
    details->setColumnWidth(1, 100);
    details->setShowGrid(false);
    details->setWordWrap(true);
    details->horizontalHeader()->hide();
    details->verticalHeader()->hide();

914 915 916 917 918
    QString startDateStr = startClock.toString("dd.MM.yyyy");
    QString startTimeStr = startClock.toString("hh:mm:ss");
    QString endTimeStr = isTemporary() ? "Ongoing"
                         : endClock.toString("hh:mm:ss");

919 920 921 922 923 924
    addDetailsRow(details, name, Qt::yellow, status, Qt::yellow);
    addDetailsRow(details, "Date", Qt::yellow, startDateStr, Qt::white);
    addDetailsRow(details, "Interval", Qt::yellow, QString::number(start, 'f', 3), Qt::white,
                  isTemporary() ? "Ongoing" : QString::number(end, 'f', 3), Qt::white);
    addDetailsRow(details, "Clock", Qt::yellow, startTimeStr, Qt::white, endTimeStr, Qt::white);
    addDetailsRow(details, "Duration", Qt::yellow, QString::number(end - start, 'f', 1), Qt::white);
925 926 927
}

// Add a new row to the table, which is specific to the particular Timeline line.
928
void Analyze::Session::addRow(const QString &key, const QString &value)
929
{
930
    addDetailsRow(details, key, Qt::yellow, value, Qt::white);
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 969
}

bool Analyze::Session::isTemporary() const
{
    return rect != nullptr;
}

// The focus session parses the "pipe-separate-values" list of positions
// and HFRs given it, eventually to be used to plot the focus v-curve.
Analyze::FocusSession::FocusSession(double start_, double end_, QCPItemRect *rect, bool ok, double temperature_,
                                    const QString &filter_, const QString &points_)
    : Session(start_, end_, FOCUS_Y, rect), success(ok),
      temperature(temperature_), filter(filter_), points(points_)
{
    const QStringList list = points.split(QLatin1Char('|'));
    const int size = list.size();
    // Size can be 1 if points_ is an empty string.
    if (size < 2)
        return;

    for (int i = 0; i < size; )
    {
        bool parsed1, parsed2;
        int position = QString(list[i++]).toInt(&parsed1);
        if (i >= size)
            break;
        double hfr = QString(list[i++]).toDouble(&parsed2);
        if (!parsed1 || !parsed2)
        {
            positions.clear();
            hfrs.clear();
            fprintf(stderr, "Bad focus position %d in %s\n", i - 2, points.toLatin1().data());
            return;
        }
        positions.push_back(position);
        hfrs.push_back(hfr);
    }
}

Yuri Chornoivan's avatar
Yuri Chornoivan committed
970
// When the user clicks on a particular capture session in the timeline,
971
// a table is rendered in the details section, and, if it was a double click,
972 973 974 975 976 977
// the fits file is displayed, if it can be found.
void Analyze::captureSessionClicked(CaptureSession &c, bool doubleClick)
{
    highlightTimelineItem(c.offset, c.start, c.end);

    if (c.isTemporary())
978
        c.setupTable("Capture", "in progress", clockTime(c.start), clockTime(c.start), detailsTable);
979
    else if (c.aborted)
980
        c.setupTable("Capture", "ABORTED", clockTime(c.start), clockTime(c.end), detailsTable);
981
    else
982
        c.setupTable("Capture", "successful", clockTime(c.start), clockTime(c.end), detailsTable);
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

    c.addRow("Filter", c.filter);

    double raRMS, decRMS, totalRMS;
    int numSamples;
    displayGuideGraphics(c.start, c.end, &raRMS, &decRMS, &totalRMS, &numSamples);
    if (numSamples > 0)
        c.addRow("GuideRMS", QString::number(totalRMS, 'f', 2));

    c.addRow("Exposure", QString::number(c.duration, 'f', 2));
    if (!c.isTemporary())
        c.addRow("Filename", c.filename);

    if (doubleClick && !c.isTemporary())
    {
        QString filename = findFilename(c.filename, alternateFolder);
        if (filename.size() > 0)
            displayFITS(filename);
        else
        {
            QString message = i18n("Could not find image file: %1", c.filename);
            KSNotification::sorry(message, i18n("Invalid URL"));
        }
    }
}

// When the user clicks on a focus session in the timeline,
1010
// a table is rendered in the details section, and the HFR/position plot
1011 1012 1013 1014 1015 1016 1017 1018
// is displayed in the graphics plot. If focus is ongoing
// the information for the graphics is not plotted as it is not yet available.
void Analyze::focusSessionClicked(FocusSession &c, bool doubleClick)
{
    Q_UNUSED(doubleClick);
    highlightTimelineItem(c.offset, c.start, c.end);

    if (c.success)
1019
        c.setupTable("Focus", "successful", clockTime(c.start), clockTime(c.end), detailsTable);
1020
    else if (c.isTemporary())
1021
        c.setupTable("Focus", "in progress", clockTime(c.start), clockTime(c.start), detailsTable);
1022
    else
1023
        c.setupTable("Focus", "FAILED", clockTime(c.start), clockTime(c.end), detailsTable);
1024 1025

    if (!c.isTemporary())
1026 1027 1028 1029 1030 1031 1032 1033
    {
        if (c.success)
        {
            if (c.hfrs.size() > 0)
                c.addRow("HFR", QString::number(c.hfrs.last(), 'f', 2));
            if (c.positions.size() > 0)
                c.addRow("Solution", QString::number(c.positions.last(), 'f', 0));
        }
1034
        c.addRow("Iterations", QString::number(c.positions.size()));
1035
    }
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    c.addRow("Filter", c.filter);
    c.addRow("Temperature", QString::number(c.temperature, 'f', 1));

    if (c.isTemporary())
        resetGraphicsPlot();
    else
        displayFocusGraphics(c.positions, c.hfrs, c.success);
}

// When the user clicks on a guide session in the timeline,
1046
// a table is rendered in the details section. If it has a G_GUIDING state
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
// then a drift plot is generated and  RMS values are calculated
// for the guiding session's time interval.
void Analyze::guideSessionClicked(GuideSession &c, bool doubleClick)
{
    Q_UNUSED(doubleClick);
    highlightTimelineItem(GUIDE_Y, c.start, c.end);

    QString st;
    if (c.simpleState == G_IDLE)
        st = "Idle";
    else if (c.simpleState == G_GUIDING)
        st = "Guiding";
    else if (c.simpleState == G_CALIBRATING)
        st = "Calibrating";
    else if (c.simpleState == G_SUSPENDED)
        st = "Suspended";
    else if (c.simpleState == G_DITHERING)
        st = "Dithering";

1066
    c.setupTable("Guide", st, clockTime(c.start), clockTime(c.end), detailsTable);
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
    resetGraphicsPlot();
    if (c.simpleState == G_GUIDING)
    {
        double raRMS, decRMS, totalRMS;
        int numSamples;
        displayGuideGraphics(c.start, c.end, &raRMS, &decRMS, &totalRMS, &numSamples);
        if (numSamples > 0)
        {
            c.addRow("total RMS", QString::number(totalRMS, 'f', 2));
            c.addRow("ra RMS", QString::number(raRMS, 'f', 2));
            c.addRow("dec RMS", QString::number(decRMS, 'f', 2));
        }
        c.addRow("Num Samples", QString::number(numSamples));
    }
}

void Analyze::displayGuideGraphics(double start, double end, double *raRMS,
                                   double *decRMS, double *totalRMS, int *numSamples)
{
    resetGraphicsPlot();
    auto ra = statsPlot->graph(RA_GRAPH)->data()->findBegin(start);
    auto dec = statsPlot->graph(DEC_GRAPH)->data()->findBegin(start);
    auto raEnd = statsPlot->graph(RA_GRAPH)->data()->findEnd(end);
    auto decEnd = statsPlot->graph(DEC_GRAPH)->data()->findEnd(end);
    int num = 0;
    double raSquareErrorSum = 0, decSquareErrorSum = 0;
    while (ra != raEnd && dec != decEnd &&
            ra->mainKey() < end && dec->mainKey() < end &&
            ra != statsPlot->graph(RA_GRAPH)->data()->constEnd() &&
            dec != statsPlot->graph(DEC_GRAPH)->data()->constEnd() &&
            ra->mainKey() < end && dec->mainKey() < end)
    {
        const double raVal = ra->mainValue();
        const double decVal = dec->mainValue();
        graphicsPlot->graph(GUIDER_GRAPHICS)->addData(raVal, decVal);
        if (!qIsNaN(raVal) && !qIsNaN(decVal))
        {
            raSquareErrorSum += raVal * raVal;
            decSquareErrorSum += decVal * decVal;
            num++;
        }
        ra++;
        dec++;
    }
    if (numSamples != nullptr)
        *numSamples = num;
    if (num > 0)
    {
        if (raRMS != nullptr)
            *raRMS = sqrt(raSquareErrorSum / num);
        if (decRMS != nullptr)
            *decRMS = sqrt(decSquareErrorSum / num);
        if (totalRMS != nullptr)
            *totalRMS = sqrt((raSquareErrorSum + decSquareErrorSum) / num);
        if (numSamples != nullptr)
            *numSamples = num;
    }
    QCPItemEllipse *c1 = new QCPItemEllipse(graphicsPlot);
    c1->bottomRight->setCoords(1.0, -1.0);
    c1->topLeft->setCoords(-1.0, 1.0);
    QCPItemEllipse *c2 = new QCPItemEllipse(graphicsPlot);
    c2->bottomRight->setCoords(2.0, -2.0);
    c2->topLeft->setCoords(-2.0, 2.0);
    c1->setPen(QPen(Qt::green));
    c2->setPen(QPen(Qt::yellow));

    // Since the plot is wider than it is tall, these lines set the
    // vertical range to 2.5, and the horizontal range to whatever it
    // takes to keep the two axes' scales (number of pixels per value)
    // the same, so that circles stay circular (i.e. circles are not stretch
    // wide even though the graph area is not square).
    graphicsPlot->xAxis->setRange(-2.5, 2.5);
    graphicsPlot->yAxis->setRange(-2.5, 2.5);
    graphicsPlot->xAxis->setScaleRatio(graphicsPlot->yAxis);
}

Yuri Chornoivan's avatar
Yuri Chornoivan committed
1143
// When the user clicks on a particular mount session in the timeline,
1144
// a table is rendered in the details section.
1145 1146 1147 1148 1149
void Analyze::mountSessionClicked(MountSession &c, bool doubleClick)
{
    Q_UNUSED(doubleClick);
    highlightTimelineItem(MOUNT_Y, c.start, c.end);

1150 1151
    c.setupTable("Mount", mountStatusString(c.state), clockTime(c.start),
                 clockTime(c.isTemporary() ? c.start : c.end), detailsTable);
1152 1153
}

Yuri Chornoivan's avatar
Yuri Chornoivan committed
1154
// When the user clicks on a particular align session in the timeline,
1155
// a table is rendered in the details section.
1156 1157 1158 1159
void Analyze::alignSessionClicked(AlignSession &c, bool doubleClick)
{
    Q_UNUSED(doubleClick);
    highlightTimelineItem(ALIGN_Y, c.start, c.end);
1160 1161
    c.setupTable("Align", getAlignStatusString(c.state), clockTime(c.start),
                 clockTime(c.isTemporary() ? c.start : c.end), detailsTable);
1162 1163
}

Yuri Chornoivan's avatar
Yuri Chornoivan committed
1164
// When the user clicks on a particular meridian flip session in the timeline,
1165
// a table is rendered in the details section.
1166 1167 1168 1169
void Analyze::mountFlipSessionClicked(MountFlipSession &c, bool doubleClick)
{
    Q_UNUSED(doubleClick);
    highlightTimelineItem(MERIDIAN_FLIP_Y, c.start, c.end);
1170 1171
    c.setupTable("Meridian Flip", Mount::meridianFlipStatusString(c.state),
                 clockTime(c.start), clockTime(c.isTemporary() ? c.start : c.end), detailsTable);
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
}

// This method determines which timeline session (if any) was selected
// when the user clicks in the Timeline plot. It also sets a cursor
// in the stats plot.
void Analyze::processTimelineClick(QMouseEvent *event, bool doubleClick)
{
    unhighlightTimelineItem();
    double xval = timelinePlot->xAxis->pixelToCoord(event->x());
    double yval = timelinePlot->yAxis->pixelToCoord(event->y());
    if (yval >= CAPTURE_Y - 0.5 && yval <= CAPTURE_Y + 0.5)
    {
        QList<CaptureSession> candidates = captureSessions.find(xval);
        if (candidates.size() > 0)
            captureSessionClicked(candidates[0], doubleClick);
        else if ((temporaryCaptureSession.rect != nullptr) &&
                 (xval > temporaryCaptureSession.start))
            captureSessionClicked(temporaryCaptureSession, doubleClick);
    }
    else if (yval >= FOCUS_Y - 0.5 && yval <= FOCUS_Y + 0.5)
    {
        QList<FocusSession> candidates = focusSessions.find(xval);
        if (candidates.size() > 0)
            focusSessionClicked(candidates[0], doubleClick);
        else if ((temporaryFocusSession.rect != nullptr) &&
                 (xval > temporaryFocusSession.start))
            focusSessionClicked(temporaryFocusSession, doubleClick);
    }
    else if (yval >= GUIDE_Y - 0.5 && yval <= GUIDE_Y + 0.5)
    {
        QList<GuideSession> candidates = guideSessions.find(xval);
        if (candidates.size() > 0)
            guideSessionClicked(candidates[0], doubleClick);
        else if ((temporaryGuideSession.rect != nullptr) &&
                 (xval > temporaryGuideSession.start))
            guideSessionClicked(temporaryGuideSession, doubleClick);
    }
    else if (yval >= MOUNT_Y - 0.5 && yval <= MOUNT_Y + 0.5)
    {
        QList<MountSession> candidates = mountSessions.find(xval);
        if (candidates.size() > 0)
            mountSessionClicked(candidates[0], doubleClick);
        else if ((temporaryMountSession.rect != nullptr) &&
                 (xval > temporaryMountSession.start))
            mountSessionClicked(temporaryMountSession, doubleClick);
    }
    else if (yval >= ALIGN_Y - 0.5 && yval <= ALIGN_Y + 0.5)
    {
        QList<AlignSession> candidates = alignSessions.find(xval);
        if (candidates.size() > 0)
            alignSessionClicked(candidates[0], doubleClick);
        else if ((temporaryAlignSession.rect != nullptr) &&
                 (xval > temporaryAlignSession.start))
            alignSessionClicked(temporaryAlignSession, doubleClick);
    }
    else if (yval >= MERIDIAN_FLIP_Y - 0.5 && yval <= MERIDIAN_FLIP_Y + 0.5)
    {
        QList<MountFlipSession> candidates = mountFlipSessions.find(xval);
        if (candidates.size() > 0)
            mountFlipSessionClicked(candidates[0], doubleClick);
        else if ((temporaryMountFlipSession.rect != nullptr) &&
                 (xval > temporaryMountFlipSession.start))
            mountFlipSessionClicked(temporaryMountFlipSession, doubleClick);
    }
    setStatsCursor(xval);
    replot();
}

void Analyze::setStatsCursor(double time)
{
    removeStatsCursor();
    QCPItemLine *line = new QCPItemLine(statsPlot);
    line->setPen(QPen(Qt::darkGray, 1, Qt::SolidLine));
    double top = statsPlot->yAxis->range().upper;
    line->start->setCoords(time, 0);
    line->end->setCoords(time, top);
    statsCursor = line;
    cursorTimeOut->setText(QString("%1s").arg(time));
    cursorClockTimeOut->setText(QString("%1")
                                .arg(clockTime(time).toString("hh:mm:ss")));
    statsCursorTime = time;
    keepCurrentCB->setCheckState(Qt::Unchecked);
}

void Analyze::removeStatsCursor()
{
    if (statsCursor != nullptr)
        statsPlot->removeItem(statsCursor);
    statsCursor = nullptr;
    cursorTimeOut->setText("");
    cursorClockTimeOut->setText("");
    statsCursorTime = -1;
}

// When the users clicks in the stats plot, the cursor is set at the corresponding time.
void Analyze::processStatsClick(QMouseEvent *event, bool doubleClick)
{
    Q_UNUSED(doubleClick);
    double xval = statsPlot->xAxis->pixelToCoord(event->x());
1271
    if (event->button() == Qt::RightButton || event->modifiers() == Qt::ControlModifier)
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
        // Resets the range. Replot will take care of ra/dec needing negative values.
        statsPlot->yAxis->setRange(0, 5);
    else
        setStatsCursor(xval);
    replot();
}

void Analyze::timelineMousePress(QMouseEvent *event)
{
    processTimelineClick(event, false);
}

void Analyze::timelineMouseDoubleClick(QMouseEvent *event)
{
    processTimelineClick(event, true);
}

void Analyze::statsMousePress(QMouseEvent *event)
{
1291 1292 1293 1294 1295 1296
    // If we're on the legend, adjust the y-axis.
    if (statsPlot->xAxis->pixelToCoord(event->x()) < plotStart)
    {
        yAxisInitialPos = statsPlot->yAxis->pixelToCoord(event->y());
        return;
    }
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    processStatsClick(event, false);
}

void Analyze::statsMouseDoubleClick(QMouseEvent *event)
{
    processStatsClick(event, true);
}

// Allow the user to click and hold, causing the cursor to move in real-time.
void Analyze::statsMouseMove(QMouseEvent *event)
{
1308 1309 1310 1311 1312 1313 1314 1315 1316
    // If we're on the legend, adjust the y-axis.
    if (statsPlot->xAxis->pixelToCoord(event->x()) < plotStart)
    {
        auto range = statsPlot->yAxis->range();
        double yDiff = yAxisInitialPos - statsPlot->yAxis->pixelToCoord(event->y());
        statsPlot->yAxis->setRange(range.lower + yDiff, range.upper + yDiff);
        replot();
        return;
    }
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    processStatsClick(event, false);
}

// Called by the scrollbar, to move the current view.
void Analyze::scroll(int value)
{
    double pct = static_cast<double>(value) / MAX_SCROLL_VALUE;
    plotStart = std::max(0.0, maxXValue * pct - plotWidth / 2.0);
    // Normally replot adjusts the position of the slider.
    // If the user has done that, we don't want replot to re-do it.
    replot(false);

}
void Analyze::scrollRight()
{
1332
    plotStart = std::min(maxXValue - plotWidth / 5, plotStart + plotWidth / 5);
1333 1334 1335 1336 1337 1338
    fullWidthCB->setChecked(false);
    replot();

}
void Analyze::scrollLeft()
{
1339
    plotStart = std::max(0.0, plotStart - plotWidth / 5);
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
    fullWidthCB->setChecked(false);
    replot();

}
void Analyze::replot(bool adjustSlider)
{
    adjustTemporarySessions();
    if (fullWidthCB->isChecked())
    {
        plotStart = 0;
        plotWidth = std::max(10.0, maxXValue);
    }
    else if (keepCurrentCB->isChecked())
    {
        plotStart = std::max(0.0, maxXValue - plotWidth);
    }
    // If we're keeping to the latest values,
    // set the time display to the latest time.
    if (keepCurrentCB->isChecked() && statsCursor == nullptr)
    {
        cursorTimeOut->setText(QString("%1s").arg(maxXValue));
        cursorClockTimeOut->setText(QString("%1")
                                    .arg(clockTime(maxXValue).toString("hh:mm:ss")));
    }
    analyzeSB->setPageStep(
        std::min(MAX_SCROLL_VALUE,
                 static_cast<int>(MAX_SCROLL_VALUE * plotWidth / maxXValue)));
    if (adjustSlider)
    {
        double sliderCenter = plotStart + plotWidth / 2.0;
        analyzeSB->setSliderPosition(MAX_SCROLL_VALUE * (sliderCenter / maxXValue));
    }

    timelinePlot->xAxis->setRange(plotStart, plotStart + plotWidth);
    timelinePlot->yAxis->setRange(0, LAST_Y);

    statsPlot->xAxis->setRange(plotStart, plotStart + plotWidth);

    // Don't reset the range if the user has changed it.
    auto yRange = statsPlot->yAxis->range();
    if ((yRange.lower == 0 || yRange.lower == -2) && (yRange.upper == 5))
    {
        // Only need negative numbers on the stats plot if we're plotting RA or DEC
        if (raCB->isChecked() || decCB->isChecked() || raPulseCB->isChecked() || decPulseCB->isChecked())
            statsPlot->yAxis->setRange(-2, 5);
        else
            statsPlot->yAxis->setRange(0, 5);
    }

    dateTicker->setOffset(displayStartTime.toMSecsSinceEpoch() / 1000.0);

    timelinePlot->replot();
    statsPlot->replot();
    graphicsPlot->replot();
    updateStatsValues();
}

namespace
{
// Pass in a function that converts the double graph value to a string
// for the value box.
template<typename Func>
void updateStat(double time, QLineEdit *valueBox, QCPGraph *graph, Func func, bool useLastRealVal = false)
{
    auto begin = graph->data()->findBegin(time);
    double timeDiffThreshold = 10000000.0;
    if ((begin != graph->data()->constEnd()) &&
            (fabs(begin->mainKey() - time) < timeDiffThreshold))
    {
        double foundVal = begin->mainValue();
        valueBox->setDisabled(false);
        if (qIsNaN(foundVal))
        {
            int index = graph->findBegin(time);
            const double MAX_TIME_DIFF = 600;
            while (useLastRealVal && index >= 0)
            {
                const double val = graph->data()->at(index)->mainValue();
                const double t = graph->data()->at(index)->mainKey();
                if (time - t > MAX_TIME_DIFF)
                    break;
                if (!qIsNaN(val))
                {
                    valueBox->setText(func(val));
                    return;
                }
                index--;
            }
            valueBox->clear();
        }
        else
            valueBox->setText(func(foundVal));
    }
    else valueBox->setDisabled(true);
}

}  // namespace

// This populates the output boxes below the stats plot with the correct statistics.
void Analyze::updateStatsValues()
{
    const double time = statsCursorTime < 0 ? maxXValue : statsCursorTime;

    auto d2Fcn = [](double d) -> QString { return QString::number(d, 'f', 2); };
1444 1445
    // HFR, numCaptureStars, median & eccentricity are the only ones to use the last real value,
    // that is, it keeps those values from the last exposure.
1446
    updateStat(time, hfrOut, statsPlot->graph(HFR_GRAPH), d2Fcn, true);
1447
    updateStat(time, eccentricityOut, statsPlot->graph(ECCENTRICITY_GRAPH), d2Fcn, true);
1448 1449 1450 1451 1452 1453
    updateStat(time, skyBgOut, statsPlot->graph(SKYBG_GRAPH), d2Fcn);
    updateStat(time, snrOut, statsPlot->graph(SNR_GRAPH), d2Fcn);
    updateStat(time, raOut, statsPlot->graph(RA_GRAPH), d2Fcn);
    updateStat(time, decOut, statsPlot->graph(DEC_GRAPH), d2Fcn);
    updateStat(time, driftOut, statsPlot->graph(DRIFT_GRAPH), d2Fcn);
    updateStat(time, rmsOut, statsPlot->graph(RMS_GRAPH), d2Fcn);
1454
    updateStat(time, rmsCOut, statsPlot->graph(CAPTURE_RMS_GRAPH), d2Fcn);
1455 1456
    updateStat(time, azOut, statsPlot->graph(AZ_GRAPH), d2Fcn);
    updateStat(time, altOut, statsPlot->graph(ALT_GRAPH), d2Fcn);
1457
    updateStat(time, temperatureOut, statsPlot->graph(TEMPERATURE_GRAPH), d2Fcn);
1458

1459 1460 1461 1462 1463 1464 1465
    auto hmsFcn = [](double d) -> QString
    {
        dms ra;
        ra.setD(d);
        return QString("%1:%2:%3").arg(ra.hour()).arg(ra.minute()).arg(ra.second());
        //return ra.toHMSString();
    };
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
    updateStat(time, mountRaOut, statsPlot->graph(MOUNT_RA_GRAPH), hmsFcn);
    auto dmsFcn = [](double d) -> QString { dms dec; dec.setD(d); return dec.toDMSString(); };
    updateStat(time, mountDecOut, statsPlot->graph(MOUNT_DEC_GRAPH), dmsFcn);
    auto haFcn = [](double d) -> QString
    {
        dms ha;
        QChar z('0');
        QChar sgn('+');
        ha.setD(d);
        if (ha.Hours() > 12.0)
        {
            ha.setH(24.0 - ha.Hours());
            sgn = '-';
        }
1480
        return QString("%1%2:%3").arg(sgn).arg(ha.hour(), 2, 10, z)
1481 1482 1483 1484 1485 1486 1487 1488
        .arg(ha.minute(), 2, 10, z);
    };
    updateStat(time, mountHaOut, statsPlot->graph(MOUNT_HA_GRAPH), haFcn);

    auto intFcn = [](double d) -> QString { return QString::number(d, 'f', 0); };
    updateStat(time, numStarsOut, statsPlot->graph(NUMSTARS_GRAPH), intFcn);
    updateStat(time, raPulseOut, statsPlot->graph(RA_PULSE_GRAPH), intFcn);
    updateStat(time, decPulseOut, statsPlot->graph(DEC_PULSE_GRAPH), intFcn);
1489 1490 1491
    updateStat(time, numCaptureStarsOut, statsPlot->graph(NUM_CAPTURE_STARS_GRAPH), intFcn, true);
    updateStat(time, medianOut, statsPlot->graph(MEDIAN_GRAPH), intFcn, true);

1492 1493 1494

    auto pierFcn = [](double d) -> QString
    {
1495
        return d == 0.0 ? "W->E" : d == 1.0 ? "E->W" : "?";
1496 1497 1498 1499 1500 1501 1502
    };
    updateStat(time, pierSideOut, statsPlot->graph(PIER_SIDE_GRAPH), pierFcn);
}

void Analyze::initStatsCheckboxes()
{
    hfrCB->setChecked(Options::analyzeHFR());
1503 1504 1505
    numCaptureStarsCB->setChecked(Options::analyzeNumCaptureStars());
    medianCB->setChecked(Options::analyzeMedian());
    eccentricityCB->setChecked(Options::analyzeEccentricity());
1506 1507 1508
    numStarsCB->setChecked(Options::analyzeNumStars());
    skyBgCB->setChecked(Options::analyzeSkyBg());
    snrCB->setChecked(Options::analyzeSNR());
1509
    temperatureCB->setChecked(Options::analyzeTemperature());
1510 1511 1512 1513 1514 1515
    raCB->setChecked(Options::analyzeRA());
    decCB->setChecked(Options::analyzeDEC());
    raPulseCB->setChecked(Options::analyzeRAp());
    decPulseCB->setChecked(Options::analyzeDECp());
    driftCB->setChecked(Options::analyzeDrift());
    rmsCB->setChecked(Options::analyzeRMS());
1516
    rmsCCB->setChecked(Options::analyzeRMSC());
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
    mountRaCB->setChecked(Options::analyzeMountRA());
    mountDecCB->setChecked(Options::analyzeMountDEC());
    mountHaCB->setChecked(Options::analyzeMountHA());
    azCB->setChecked(Options::analyzeAz());
    altCB->setChecked(Options::analyzeAlt());
    pierSideCB->setChecked(Options::analyzePierSide());
}

void Analyze::zoomIn()
{
    if (plotWidth > 0.5)
    {
Hy Murveit's avatar
Hy Murveit committed
1529 1530 1531 1532 1533 1534 1535 1536 1537
        if (keepCurrentCB->isChecked())
            // If we're keeping to the end of the data, keep the end on the right.
            plotStart = std::max(0.0, maxXValue - plotWidth / 4.0);
        else if (statsCursorTime >= 0)
            // If there is a cursor, try to move it to the center.
            plotStart = std::max(0.0, statsCursorTime - plotWidth / 4.0);
        else
            // Keep the center the same.
            plotStart += plotWidth / 4.0;
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547