-
Notifications
You must be signed in to change notification settings - Fork 122
/
MuonSequentialFitDialog.cpp
389 lines (308 loc) · 12.4 KB
/
MuonSequentialFitDialog.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#include "MantidQtMantidWidgets/MuonSequentialFitDialog.h"
#include "MantidQtMantidWidgets/MuonFitPropertyBrowser.h"
#include "MantidAPI/AnalysisDataService.h"
namespace MantidQt
{
namespace MantidWidgets
{
using namespace Mantid::Kernel;
using namespace Mantid::API;
Logger& MuonSequentialFitDialog::g_log(Logger::get("MuonSequentialFitDialog"));
/**
* Constructor
*/
MuonSequentialFitDialog::MuonSequentialFitDialog(MuonFitPropertyBrowser* fitPropBrowser) :
QDialog(fitPropBrowser), m_fitPropBrowser(fitPropBrowser)
{
m_ui.setupUi(this);
setState(Stopped);
// Set initial runs text
Workspace_const_sptr fitWS = m_fitPropBrowser->getWorkspace();
m_ui.runs->setText( QString::fromStdString( getRunTitle(fitWS) ) + "-" );
// TODO: find a better initial one, e.g. previously used
m_ui.labelInput->setText("Label");
initDiagnosisTable();
// After initial values are set, update depending elements accordingly. We don't rely on
// slot/signal update, as element might be left with default values which means these will
// never be called on initialication.
updateLabelError( m_ui.labelInput->text() );
updateControlButtonState();
updateControlButtonType(m_state);
updateInputEnabled(m_state);
connect( m_ui.labelInput, SIGNAL( textChanged(const QString&) ),
this, SLOT( updateLabelError(const QString&) ) );
connect( m_ui.labelInput, SIGNAL( textChanged(const QString&) ),
this, SLOT( updateControlButtonState() ) );
connect( m_ui.runs, SIGNAL( fileFindingFinished() ),
this, SLOT( updateControlButtonState() ) );
connect( this, SIGNAL( stateChanged(DialogState) ),
this, SLOT( updateControlButtonType(DialogState) ) );
connect( this, SIGNAL( stateChanged(DialogState) ),
this, SLOT( updateInputEnabled(DialogState) ) );
}
/**
* Destructor
*/
MuonSequentialFitDialog::~MuonSequentialFitDialog()
{}
/**
* Checks if specified name is valid as a name for label.
* @param label :: The name to check
* @return Empty string if valid, otherwise a string describing why is invalid
*/
std::string MuonSequentialFitDialog::isValidLabel(const std::string& label)
{
if ( label.empty() )
return "Can not be empty";
else
return AnalysisDataService::Instance().isValid(label);
}
/**
* Returns displayable title for the given workspace;
* @param ws :: Workpspace to get title from
* @return The title, or empty string if unable to get one
*/
std::string MuonSequentialFitDialog::getRunTitle(Workspace_const_sptr ws)
{
auto matrixWS = boost::dynamic_pointer_cast<const MatrixWorkspace>(ws);
if ( ! matrixWS )
return "";
const std::string& instrName = matrixWS->getInstrument()->getName();
const int runNumber = matrixWS->getRunNumber();
if ( instrName.empty() || runNumber == 0 )
return "";
std::ostringstream runTitle;
runTitle << instrName << runNumber;
return runTitle.str();
}
/**
* Initialize diagnosis table.
*/
void MuonSequentialFitDialog::initDiagnosisTable()
{
QStringList headerLabels;
// Add two static columns
headerLabels << "Run" << "Fit quality";
// Add remaining columns - one for every fit function parameter
IFunction_sptr fitFunc = m_fitPropBrowser->getFittingFunction();
for(size_t i = 0; i < fitFunc->nParams(); i++)
headerLabels << QString::fromStdString( fitFunc->parameterName(i) );
m_ui.diagnosisTable->setColumnCount( headerLabels.size() );
m_ui.diagnosisTable->setHorizontalHeaderLabels(headerLabels);
// Make the table fill all the available space
m_ui.diagnosisTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
}
/**
* Add a new entry to the diagnosis table.
* @param runTitle :: Title of the run fitted
* @param fitQuality :: Number representing a goodness of the fit
* @param fittedFunction :: Function containing fitted parameters
*/
void MuonSequentialFitDialog::addDiagnosisEntry(const std::string& runTitle, double fitQuality,
IFunction_sptr fittedFunction)
{
int newRow = m_ui.diagnosisTable->rowCount();
m_ui.diagnosisTable->insertRow(newRow);
m_ui.diagnosisTable->setItem(newRow, 0, new QTableWidgetItem( QString::fromStdString(runTitle) ) );
m_ui.diagnosisTable->setItem(newRow, 1, new QTableWidgetItem( QString::number(fitQuality) ) );
for(int i = 2; i < m_ui.diagnosisTable->columnCount(); ++i)
{
std::string paramName = m_ui.diagnosisTable->horizontalHeaderItem(i)->text().toStdString();
double value = fittedFunction->getParameter(paramName);
m_ui.diagnosisTable->setItem(newRow, i, new QTableWidgetItem( QString::number(value) ) );
}
m_ui.diagnosisTable->scrollToBottom();
}
/**
* Updates visibility/tooltip of label error asterisk.
* @param label :: New label as specified by user
*/
void MuonSequentialFitDialog::updateLabelError(const QString& label)
{
std::string error = isValidLabel( label.toStdString() );
m_ui.labelError->setVisible( ! error.empty() );
m_ui.labelError->setToolTip( QString::fromStdString(error) );
}
/**
* Check if all the input field are valid.
* @return True if everything valid, false otherwise
*/
bool MuonSequentialFitDialog::isInputValid()
{
if ( ! m_ui.runs->isValid() )
return false;
std::string label = m_ui.labelInput->text().toStdString();
if ( ! isValidLabel(label).empty() )
return false;
return true;
}
/**
* Enables/disables start button depending on wether we are allowed to start.
*/
void MuonSequentialFitDialog::updateControlButtonState()
{
m_ui.controlButton->setEnabled( isInputValid() );
}
/**
* Sets control button to be start/stop depending on new dialog state.
* @param newState :: New state of the dialog
*/
void MuonSequentialFitDialog::updateControlButtonType(DialogState newState)
{
// Disconnect everything connected to pressed() signal of the button
disconnect( m_ui.controlButton, SIGNAL( pressed() ), 0, 0);
// Connect to appropriate slot
auto buttonSlot = (newState == Stopped) ? SLOT( startFit() ) : SLOT( stopFit() );
connect( m_ui.controlButton, SIGNAL( pressed() ), this, buttonSlot );
// Set appropriate text
QString buttonText = (newState == Stopped) ? "Start" : "Stop";
m_ui.controlButton->setText(buttonText);
}
/**
* Updates current state of the dialog.
*/
void MuonSequentialFitDialog::setState(DialogState newState)
{
m_state = newState;
emit stateChanged(newState);
}
/**
* Update enabled state off all the input widgets depending on new dialog state.
* @param newState :: New state of the dialog
*/
void MuonSequentialFitDialog::updateInputEnabled(DialogState newState)
{
bool enabled = (newState == Stopped);
m_ui.runs->setEnabled(enabled);
m_ui.labelInput->setEnabled(enabled);
foreach(QAbstractButton* button, m_ui.paramTypeGroup->buttons())
button->setEnabled(enabled);
}
/**
* Start fitting process.
*/
void MuonSequentialFitDialog::startFit()
{
if ( m_state == Running )
throw std::runtime_error("Couln't start: already running");
const std::string label = m_ui.labelInput->text().toStdString();
const std::string labelGroupName = "MuonSeqFit_" + label;
AnalysisDataServiceImpl& ads = AnalysisDataService::Instance();
if ( ads.doesExist(labelGroupName) )
{
QMessageBox::StandardButton answer = QMessageBox::question(this, "Label already exists",
"Label you specified was used for one of the previous fits. Do you want to overwrite it?",
QMessageBox::Yes | QMessageBox::Cancel);
if ( answer != QMessageBox::Yes )
return;
ads.deepRemoveGroup(labelGroupName);
}
// Create a group for label
ads.add(labelGroupName, boost::make_shared<WorkspaceGroup>());
QStringList runFilenames = m_ui.runs->getFilenames();
// Tell progress bar how many iterations we will need to make and reset it
m_ui.progress->setRange( 0, runFilenames.size() );
m_ui.progress->setFormat("%p%");
m_ui.progress->setValue(0);
// Clear diagnosis table for new fit
m_ui.diagnosisTable->setRowCount(0);
// Get fit function as specified by user in the fit browser
IFunction_sptr fitFunction = FunctionFactory::Instance().createInitialized(
m_fitPropBrowser->getFittingFunction()->asString() );
// Whether we should use initial function for every fit
bool useInitFitFunction = (m_ui.paramTypeGroup->checkedButton() == m_ui.paramTypeInitial);
setState(Running);
m_stopRequested = false;
for ( auto fileIt = runFilenames.constBegin(); fileIt != runFilenames.constEnd(); ++fileIt )
{
// Process events (so that Stop button press is processed)
QApplication::processEvents();
// Stop if requested by user
if ( m_stopRequested )
break;
Workspace_sptr loadedWS;
try
{
// TODO: should be MuonLoad here
IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().createUnmanaged("LoadMuonNexus");
loadAlg->setChild(true);
loadAlg->setRethrows(true);
loadAlg->initialize();
loadAlg->setPropertyValue( "Filename", fileIt->toStdString() );
loadAlg->setPropertyValue( "OutputWorkspace", "__YouDontSeeMeIAmNinja" ); // Is not used
loadAlg->execute();
loadedWS = loadAlg->getProperty("OutputWorkspace");
}
catch(std::exception& e)
{
QMessageBox::critical(this, "Loading failed",
"Unable to load one of the files.\n\nCheck log for details");
break;
}
MatrixWorkspace_sptr ws;
if ( auto single = boost::dynamic_pointer_cast<MatrixWorkspace>(loadedWS) )
{
ws = single;
}
else if ( auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(loadedWS) )
{
auto first = boost::dynamic_pointer_cast<MatrixWorkspace>( group->getItem(0) );
ws = first;
}
const std::string runTitle = getRunTitle(ws);
const std::string wsBaseName = labelGroupName + "_" + runTitle;
IFunction_sptr functionToFit;
if ( useInitFitFunction )
// Create a copy so that the original function is not changed
functionToFit = FunctionFactory::Instance().createInitialized( fitFunction->asString() );
else
// Use the same function over and over, so that previous fitted params are used for the next fit
functionToFit = fitFunction;
IAlgorithm_sptr fit = AlgorithmManager::Instance().createUnmanaged("Fit");
try
{
fit->initialize();
fit->setRethrows(true);
// Set function. Gets updated when fit is done.
fit->setProperty("Function", functionToFit);
fit->setProperty("InputWorkspace", ws);
fit->setProperty("Output", wsBaseName);
// We should have one spectra only in the workspace, so use the first one.
fit->setProperty("WorkspaceIndex", 0);
// Various properties from the fit prop. browser
fit->setProperty("StartX", m_fitPropBrowser->startX());
fit->setProperty("EndX", m_fitPropBrowser->endX());
fit->setProperty("Minimizer", m_fitPropBrowser->minimizer());
fit->setProperty("CostFunction", m_fitPropBrowser->costFunction());
fit->execute();
}
catch(std::exception& e)
{
QMessageBox::critical(this, "Fitting failed",
"Unable to fit one of the files.\n\nCheck log for details");
break;
}
// Make sure created fit workspaces end-up in the group
// TODO: this really should use loop
ads.addToGroup(labelGroupName, wsBaseName + "_NormalisedCovarianceMatrix");
ads.addToGroup(labelGroupName, wsBaseName + "_Parameters");
ads.addToGroup(labelGroupName, wsBaseName + "_Workspace");
// Add information about the fit to the diagnosis table
addDiagnosisEntry(runTitle, fit->getProperty("OutputChi2OverDof"), functionToFit);
// Update progress
m_ui.progress->setFormat("%p% - " + QString::fromStdString(runTitle) );
m_ui.progress->setValue( m_ui.progress->value() + 1 );
}
setState(Stopped);
}
/**
* Stop fitting process.
*/
void MuonSequentialFitDialog::stopFit()
{
if ( m_state != Running )
throw std::runtime_error("Couldn't stop: is not running");
m_stopRequested = true;
}
} // namespace MantidWidgets
} // namespace Mantid