File: FitSessionController.cpp

package info (click to toggle)
bornagain 23.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 103,936 kB
  • sloc: cpp: 423,131; python: 40,997; javascript: 11,167; awk: 630; sh: 318; ruby: 173; xml: 130; makefile: 51; ansic: 24
file content (199 lines) | stat: -rw-r--r-- 7,025 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      GUI/View/Fit/FitSessionController.cpp
//! @brief     Implements class FitSessionController.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "GUI/View/Fit/FitSessionController.h"
#include "Base/Util/Assert.h"
#include "GUI/Model/Data/Data2DItem.h"
#include "GUI/Model/Job/BatchInfo.h"
#include "GUI/Model/Job/JobItem.h"
#include "GUI/Model/Job/JobStatus.h"
#include "GUI/Model/Tune/FitParameterContainerItem.h"
#include "GUI/Model/Tune/FitSuiteItem.h"
#include "GUI/View/FitControl/FitObjectiveBuilder.h"
#include "GUI/View/FitControl/FitWorkerLauncher.h"
#include "GUI/View/FitControl/GUIFitObserver.h"
#include "GUI/View/FitMessage/FitLog.h"

namespace {

const bool use_fit_objective = true;
} // namespace

FitSessionController::FitSessionController(QObject* parent)
    : QObject(parent)
    , m_job_item(nullptr)
    , m_run_fit_manager(new FitWorkerLauncher(this))
    , m_observer(new GUIFitObserver)
    , m_fitlog(new FitLog(this))
    , m_block_progress_update(false)
{
    connect(m_observer.get(), &GUIFitObserver::updateReady, this,
            &FitSessionController::onObserverUpdate);

    connect(m_run_fit_manager, &FitWorkerLauncher::fittingStarted, this,
            &FitSessionController::onFittingStarted);
    connect(m_run_fit_manager, &FitWorkerLauncher::fittingFinished, this,
            &FitSessionController::onFittingFinished);
    connect(m_run_fit_manager, &FitWorkerLauncher::fittingError, this,
            &FitSessionController::onFittingError);
}

FitSessionController::~FitSessionController() = default;

void FitSessionController::setJobItem(JobItem* jobItem)
{
    if (m_job_item && m_job_item != jobItem) // TODO maybe "=="?
        throw std::runtime_error("JobItem was already set");

    m_job_item = jobItem;
    ASSERT(m_job_item);

    // In principle, there is no need to unsubscribe from jobItem on jobItem destroy.
    // FitSessionManager deletes controller right after the jobItem. But to ease the possible
    // investigation, it is here.
    connect(m_job_item, &QObject::destroyed, this, &FitSessionController::onJobDestroyed,
            Qt::UniqueConnection);

    // Propagates update interval from FitSuiteItem to fit observer.
    connect(m_job_item->fitSuiteItem(), &FitSuiteItem::updateIntervalChanged, m_observer.get(),
            &GUIFitObserver::setInterval, Qt::UniqueConnection);
}

void FitSessionController::onStartFittingRequest()
{
    if (!m_job_item)
        return;

    try {
        m_objective_builder = std::make_unique<FitObjectiveBuilder>(m_job_item);
        m_observer->setInterval(m_job_item->fitSuiteItem()->updateInterval());
        m_objective_builder->attachObserver(m_observer);
        m_observer->finishedPlotting();
        m_run_fit_manager->runFitting(m_objective_builder);
    } catch (std::exception& e) {
        m_job_item->setFailed();
        m_fitlog->append(e.what(), FitLogLevel::Error);
        emit fittingError(QString::fromStdString(e.what()));
    }
}

FitLog* FitSessionController::fitLog()
{
    return m_fitlog.get();
}

void FitSessionController::onStopFittingRequest()
{
    m_run_fit_manager->interruptFitting();
}

void FitSessionController::onObserverUpdate()
{
    auto progressInfo = m_observer->progressInfo();
    m_job_item->simulatedDataItem()->setRawDataVector(progressInfo.simValues());

    updateIterationCount(progressInfo);

    if (!use_fit_objective)
        updateFitParameterValues(progressInfo);

    updateLog(progressInfo);

    if (!progressInfo.logInfo().empty())
        m_fitlog->append(progressInfo.logInfo(), FitLogLevel::Default);

    m_observer->finishedPlotting();
}

void FitSessionController::onFittingStarted()
{
    m_fitlog->clearLog();

    m_job_item->batchInfo()->setStatus(JobStatus::Fitting);
    m_job_item->batchInfo()->setProgress(0);
    m_job_item->batchInfo()->setBeginTime(m_run_fit_manager->fitStart());
    m_job_item->batchInfo()->setEndTime(QDateTime());

    emit fittingStarted();
}

void FitSessionController::onFittingFinished()
{
    if (!isFailed(m_job_item->batchInfo()->status()))
        m_job_item->batchInfo()->setStatus(JobStatus::Completed);
    m_job_item->batchInfo()->setEndTime(m_run_fit_manager->fitEnd());
    m_job_item->batchInfo()->setProgress(100);

    if (isCompleted(m_job_item->batchInfo()->status()))
        m_fitlog->append("Done", FitLogLevel::Success);

    emit fittingFinished();
    emit m_job_item->simulatedDataItem()->datafieldChanged();
}

void FitSessionController::onFittingError(const QString& text)
{
    QString message;
    message.append("Current settings cause fitting failure.\n\n");
    message.append(text);
    m_fitlog->append(message.toStdString(), FitLogLevel::Error);
    m_job_item->batchInfo()->setEndTime(m_run_fit_manager->fitEnd());

    emit fittingError(message);
}

void FitSessionController::updateIterationCount(const FitProgressInfo& info)
{
    FitSuiteItem* fitSuiteItem = m_job_item->fitSuiteItem();
    // FIXME ProgressCanvas updates chi2 and n_iteration on P_ITERATION_COUNT change
    // The order of two lines below is important
    fitSuiteItem->setChi2(info.chi2());
    fitSuiteItem->setIterationCount(info.iterationCount());
}

void FitSessionController::updateFitParameterValues(const FitProgressInfo& info)
{
    FitParameterContainerItem* fitParContainer =
        m_job_item->fitSuiteItem()->fitParameterContainerItem();
    fitParContainer->setValuesInParameterContainer(info.parValues(),
                                                   m_job_item->parameterContainerItem());
}

void FitSessionController::updateStartValuesFromTree()
{
    FitParameterContainerItem* fitParContainer =
        m_job_item->fitSuiteItem()->fitParameterContainerItem();
    fitParContainer->pullValuesFromParameterContainer(m_job_item->parameterContainerItem());
}

void FitSessionController::updateLog(const FitProgressInfo& info)
{
    QString message = QString("NCalls:%1 chi2:%2 \n").arg(info.iterationCount()).arg(info.chi2());
    FitParameterContainerItem* fitParContainer =
        m_job_item->fitSuiteItem()->fitParameterContainerItem();
    int index(0);
    for (FitParameterItem* item : fitParContainer->fitParameterItems()) {
        if (item->linkItems().empty())
            continue;
        QString parinfo =
            QString("      %1 %2\n").arg(item->displayName()).arg(info.parValues()[index++]);
        message.append(parinfo);
    }
    m_fitlog->append(message.toStdString(), FitLogLevel::Default);
}

void FitSessionController::onJobDestroyed()
{
    m_job_item = nullptr;
}