-
Notifications
You must be signed in to change notification settings - Fork 122
/
IndirectDiffractionReduction.cpp
442 lines (371 loc) · 14.7 KB
/
IndirectDiffractionReduction.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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//----------------------
// Includes
//----------------------
#include "MantidQtCustomInterfaces/IndirectDiffractionReduction.h"
#include "MantidQtAPI/ManageUserDirectories.h"
#include "MantidAPI/AlgorithmManager.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/MultiFileNameParser.h"
#include <QDesktopServices>
#include <QUrl>
using namespace Mantid::API;
using namespace Mantid::Geometry;
//Add this class to the list of specialised dialogs in this namespace
namespace MantidQt
{
namespace CustomInterfaces
{
namespace // anon
{
/// static logger
Mantid::Kernel::Logger g_log("IndirectDiffractionReduction");
// Helper function for use with std::transform.
std::string toStdString(const QString & qString)
{
return qString.toStdString();
}
} // anon namespace
DECLARE_SUBWINDOW(IndirectDiffractionReduction);
using namespace Mantid::API;
using namespace MantidQt::CustomInterfaces;
using MantidQt::API::BatchAlgorithmRunner;
//----------------------
// Public member functions
//----------------------
///Constructor
IndirectDiffractionReduction::IndirectDiffractionReduction(QWidget *parent) :
UserSubWindow(parent), m_valInt(NULL), m_valDbl(NULL),
m_settingsGroup("CustomInterfaces/DEMON"),
m_batchAlgoRunner(new BatchAlgorithmRunner(parent))
{
}
///Destructor
IndirectDiffractionReduction::~IndirectDiffractionReduction()
{
saveSettings();
}
/**
* RUnd a diffraction reduction when the user clieks Run.
*/
void IndirectDiffractionReduction::demonRun()
{
if(!validateDemon())
{
showInformationBox("Invalid input. Incorrect entries marked with red star.");
return;
}
QString instName = m_uiForm.cbInst->currentText();
QString mode = m_uiForm.cbReflection->currentText();
if(instName == "OSIRIS" && mode == "diffonly")
runOSIRISdiffonlyReduction();
else
runGenericReduction(instName, mode);
}
/**
* Runs a diffraction reduction for any instrument in any mode.
*
* @param instName Name of the instrument
* @param mode Mode instrument is operating in (diffspec/diffonly)
*/
void IndirectDiffractionReduction::runGenericReduction(QString instName, QString mode)
{
// MSGDiffractionReduction
QString pfile = instName + "_diffraction_" + mode + "_Parameters.xml";
QString pyInput =
"from IndirectDiffractionReduction import MSGDiffractionReducer\n"
"reducer = MSGDiffractionReducer()\n"
"reducer.set_instrument_name('" + instName + "')\n"
"reducer.set_detector_range("+m_uiForm.set_leSpecMin->text()+"-1, " +m_uiForm.set_leSpecMax->text()+"-1)\n"
"reducer.set_parameter_file('" + pfile + "')\n"
"files = [r'" + m_uiForm.dem_rawFiles->getFilenames().join("',r'") + "']\n"
"for file in files:\n"
" reducer.append_data_file(file)\n";
// Fix Vesuvio to FoilOut for now
if(instName == "VESUVIO")
pyInput += "reducer.append_load_option('Mode','FoilOut')\n";
if ( m_uiForm.dem_ckSumFiles->isChecked() )
{
pyInput += "reducer.set_sum_files(True)\n";
}
pyInput += "formats = []\n";
if ( m_uiForm.ckGSS->isChecked() ) pyInput += "formats.append('gss')\n";
if ( m_uiForm.ckNexus->isChecked() ) pyInput += "formats.append('nxs')\n";
if ( m_uiForm.ckAscii->isChecked() ) pyInput += "formats.append('ascii')\n";
QString rebin = m_uiForm.leRebinStart->text() + "," + m_uiForm.leRebinWidth->text()
+ "," + m_uiForm.leRebinEnd->text();
if ( rebin != ",," )
{
pyInput += "reducer.set_rebin_string('" + rebin +"')\n";
}
pyInput += "reducer.set_save_formats(formats)\n";
pyInput +=
"reducer.reduce()\n";
if ( m_uiForm.cbPlotType->currentText() == "Spectra" )
{
pyInput += "wslist = reducer.get_result_workspaces()\n"
"from mantidplot import *\n"
"plotSpectrum(wslist, 0)\n";
}
QString pyOutput = runPythonCode(pyInput).trimmed();
}
/**
* Runs a diffraction reduction for OSIRIS operating in diffonly mode using the OSIRISDiffractionReduction algorithm.
*/
void IndirectDiffractionReduction::runOSIRISdiffonlyReduction()
{
// Get the files names from MWRunFiles widget, and convert them from Qt forms into stl equivalents.
QStringList fileNames = m_uiForm.dem_rawFiles->getFilenames();
std::vector<std::string> stlFileNames;
stlFileNames.reserve(fileNames.size());
std::transform(fileNames.begin(),fileNames.end(),std::back_inserter(stlFileNames), toStdString);
// Use the file names to suggest a workspace name to use. Report to logger and stop if unable to parse correctly.
QString drangeWsName;
QString tofWsName;
try
{
QString nameBase = QString::fromStdString(Mantid::Kernel::MultiFileNameParsing::suggestWorkspaceName(stlFileNames));
tofWsName = "'" + nameBase + "_tof'";
drangeWsName = "'" + nameBase + "_dRange'";
}
catch(std::runtime_error & re)
{
g_log.error(re.what());
return;
}
IAlgorithm_sptr osirisDiffReduction = AlgorithmManager::Instance().create("OSIRISDiffractionReduction");
osirisDiffReduction->initialize();
osirisDiffReduction->setProperty("Sample", m_uiForm.dem_rawFiles->getFilenames().join(",").toStdString());
osirisDiffReduction->setProperty("Vanadium", m_uiForm.dem_vanadiumFile->getFilenames().join(",").toStdString());
osirisDiffReduction->setProperty("CalFile", m_uiForm.dem_calFile->getFirstFilename().toStdString());
osirisDiffReduction->setProperty("OutputWorkspace", drangeWsName.toStdString());
m_batchAlgoRunner->addAlgorithm(osirisDiffReduction);
BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromReductionProps;
inputFromReductionProps["InputWorkspace"] = drangeWsName.toStdString();
IAlgorithm_sptr convertUnits = AlgorithmManager::Instance().create("ConvertUnits");
convertUnits->initialize();
convertUnits->setProperty("OutputWorkspace", tofWsName.toStdString());
convertUnits->setProperty("Target", "TOF");
m_batchAlgoRunner->addAlgorithm(convertUnits, inputFromReductionProps);
BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromConvUnitsProps;
inputFromConvUnitsProps["InputWorkspace"] = tofWsName.toStdString();
if ( m_uiForm.ckGSS->isChecked() )
{
QString gssFilename = tofWsName + ".gss";
IAlgorithm_sptr saveGSS = AlgorithmManager::Instance().create("SaveGSS");
saveGSS->initialize();
saveGSS->setProperty("Filename", gssFilename.toStdString());
m_batchAlgoRunner->addAlgorithm(saveGSS, inputFromConvUnitsProps);
}
if ( m_uiForm.ckNexus->isChecked() )
{
QString nexusFilename = drangeWsName + ".nxs";
IAlgorithm_sptr saveNexus = AlgorithmManager::Instance().create("SaveNexusProcessed");
saveNexus->initialize();
saveNexus->setProperty("Filename", nexusFilename.toStdString());
m_batchAlgoRunner->addAlgorithm(saveNexus, inputFromReductionProps);
}
if ( m_uiForm.ckAscii->isChecked() )
{
QString asciiFilename = drangeWsName + ".dat";
IAlgorithm_sptr saveASCII = AlgorithmManager::Instance().create("SaveAscii");
saveASCII->initialize();
saveASCII->setProperty("Filename", asciiFilename.toStdString());
m_batchAlgoRunner->addAlgorithm(saveASCII, inputFromReductionProps);
}
m_batchAlgoRunner->executeBatchAsync();
/* if ( m_uiForm.cbPlotType->currentText() == "Spectra" ) */
/* { */
/* QString pyInput = "from mantidplot import *\n" */
/* "plotSpectrum(" + drangeWsName + ", 0)\n" */
/* "plotSpectrum(" + tofWsName + ", 0)\n"; */
/* runPythonCode(pyInput).trimmed(); */
/* } */
}
/**
* Loads an empty instrument and returns a pointer to the workspace.
*
* Optionally loads an IPF if a reflection was provided.
*
* @param instrumentName Name of an inelastic indiretc instrument (IRIS, OSIRIN, TOSCA, VESUVIO)
* @param reflection Reflection mode to load parameters for (diffspec or diffonly)
*/
MatrixWorkspace_sptr IndirectDiffractionReduction::loadInstrument(std::string instrumentName, std::string reflection)
{
std::string instWorkspaceName = "__empty_" + instrumentName;
std::string idfPath = Mantid::Kernel::ConfigService::Instance().getString("instrumentDefinition.directory");
if(!AnalysisDataService::Instance().doesExist(instWorkspaceName))
{
std::string parameterFilename = idfPath + instrumentName + "_Definition.xml";
IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("LoadEmptyInstrument");
loadAlg->initialize();
loadAlg->setProperty("Filename", parameterFilename);
loadAlg->setProperty("OutputWorkspace", instWorkspaceName);
loadAlg->execute();
}
MatrixWorkspace_sptr instWorkspace = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(instWorkspaceName);
// Load parameter file if a reflection was given
if(!reflection.empty())
{
std::string ipfFilename = idfPath + instrumentName + "_diffraction_" + reflection + "_Parameters.xml";
IAlgorithm_sptr loadParamAlg = AlgorithmManager::Instance().create("LoadParameterFile");
loadParamAlg->initialize();
loadParamAlg->setProperty("Filename", ipfFilename);
loadParamAlg->setProperty("Workspace", instWorkspaceName);
loadParamAlg->execute();
}
return instWorkspace;
}
/**
* Handles loading an instrument and reflections when an instruiment is selected form the drop down.
*/
void IndirectDiffractionReduction::instrumentSelected(int)
{
// If the interface is not shown, do not go looking for parameter files, etc.
if(!m_uiForm.cbInst->isVisible())
return;
std::string instrumentName = m_uiForm.cbInst->currentText().toStdString();
MatrixWorkspace_sptr instWorkspace = loadInstrument(instrumentName);
Instrument_const_sptr instrument = instWorkspace->getInstrument();
std::vector<std::string> analysers;
boost::split(analysers, instrument->getStringParameter("refl-diffraction")[0], boost::is_any_of(","));
m_uiForm.cbReflection->blockSignals(true);
m_uiForm.cbReflection->clear();
for(auto it = analysers.begin(); it != analysers.end(); ++it)
{
std::string reflection = *it;
m_uiForm.cbReflection->addItem(QString::fromStdString(reflection));
}
reflectionSelected(m_uiForm.cbReflection->currentIndex());
m_uiForm.cbReflection->blockSignals(false);
}
/**
* Handles setting default spectra range when a reflection is slected from the drop down.
*/
void IndirectDiffractionReduction::reflectionSelected(int)
{
std::string instrumentName = m_uiForm.cbInst->currentText().toStdString();
std::string reflection = m_uiForm.cbReflection->currentText().toStdString();
MatrixWorkspace_sptr instWorkspace = loadInstrument(instrumentName, reflection);
Instrument_const_sptr instrument = instWorkspace->getInstrument();
// Get default spectra range
double specMin = instrument->getNumberParameter("spectra-min")[0];
double specMax = instrument->getNumberParameter("spectra-max")[0];
m_uiForm.set_leSpecMin->setText(QString::number(specMin));
m_uiForm.set_leSpecMax->setText(QString::number(specMax));
// Determine whether we need vanadium input
std::vector<std::string> correctionVector = instrument->getStringParameter("Workflow.Diffraction.Correction");
bool vanadiumNeeded = false;
if(correctionVector.size() > 0)
vanadiumNeeded = (correctionVector[0] == "Vanadium");
if(vanadiumNeeded)
m_uiForm.swVanadium->setCurrentIndex(0);
else
m_uiForm.swVanadium->setCurrentIndex(1);
// Hide options that the current instrument config cannot process
if(instrumentName == "OSIRIS" && reflection == "diffonly")
m_uiForm.dem_ckSumFiles->setEnabled(false);
else
m_uiForm.dem_ckSumFiles->setEnabled(true);
}
/**
* Handles opening the directory manager window.
*/
void IndirectDiffractionReduction::openDirectoryDialog()
{
MantidQt::API::ManageUserDirectories *ad = new MantidQt::API::ManageUserDirectories(this);
ad->show();
ad->setFocus();
}
/**
* Handles the user clicking the help button.
*/
void IndirectDiffractionReduction::help()
{
QString url = "http://www.mantidproject.org/Indirect_Diffraction_Reduction";
QDesktopServices::openUrl(QUrl(url));
}
void IndirectDiffractionReduction::initLayout()
{
m_uiForm.setupUi(this);
connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(help()));
connect(m_uiForm.pbManageDirs, SIGNAL(clicked()), this, SLOT(openDirectoryDialog()));
connect(m_uiForm.pbRun, SIGNAL(clicked()), this, SLOT(demonRun()));
connect(m_uiForm.cbInst, SIGNAL(currentIndexChanged(int)), this, SLOT(instrumentSelected(int)));
connect(m_uiForm.cbReflection, SIGNAL(currentIndexChanged(int)), this, SLOT(reflectionSelected(int)));
m_valInt = new QIntValidator(this);
m_valDbl = new QDoubleValidator(this);
m_uiForm.set_leSpecMin->setValidator(m_valInt);
m_uiForm.set_leSpecMax->setValidator(m_valInt);
m_uiForm.leRebinStart->setValidator(m_valDbl);
m_uiForm.leRebinWidth->setValidator(m_valDbl);
m_uiForm.leRebinEnd->setValidator(m_valDbl);
loadSettings();
validateDemon();
}
void IndirectDiffractionReduction::initLocalPython()
{
instrumentSelected(0);
}
void IndirectDiffractionReduction::loadSettings()
{
QSettings settings;
QString dataDir = QString::fromStdString(Mantid::Kernel::ConfigService::Instance().getString("datasearch.directories")).split(";")[0];
settings.beginGroup(m_settingsGroup);
settings.setValue("last_directory", dataDir);
m_uiForm.dem_rawFiles->readSettings(settings.group());
m_uiForm.dem_calFile->readSettings(settings.group());
m_uiForm.dem_calFile->setUserInput(settings.value("last_cal_file").toString());
m_uiForm.dem_vanadiumFile->setUserInput(settings.value("last_van_files").toString());
settings.endGroup();
}
void IndirectDiffractionReduction::saveSettings()
{
QSettings settings;
settings.beginGroup(m_settingsGroup);
settings.setValue("last_cal_file", m_uiForm.dem_calFile->getText());
settings.setValue("last_van_files", m_uiForm.dem_vanadiumFile->getText());
settings.endGroup();
}
bool IndirectDiffractionReduction::validateDemon()
{
bool rawValid = true;
if ( ! m_uiForm.dem_rawFiles->isValid() ) { rawValid = false; }
QString rebStartTxt = m_uiForm.leRebinStart->text();
QString rebStepTxt = m_uiForm.leRebinWidth->text();
QString rebEndTxt = m_uiForm.leRebinEnd->text();
bool rebinValid = true;
// Need all or none
if(rebStartTxt.isEmpty() && rebStepTxt.isEmpty() && rebEndTxt.isEmpty() )
{
rebinValid = true;
m_uiForm.valRebinStart->setText("");
m_uiForm.valRebinWidth->setText("");
m_uiForm.valRebinEnd->setText("");
}
else
{
#define CHECK_VALID(text,validator)\
if(text.isEmpty())\
{\
rebinValid = false;\
validator->setText("*");\
}\
else\
{\
rebinValid = true;\
validator->setText("");\
}
CHECK_VALID(rebStartTxt,m_uiForm.valRebinStart);
CHECK_VALID(rebStepTxt,m_uiForm.valRebinWidth);
CHECK_VALID(rebEndTxt,m_uiForm.valRebinEnd);
if(rebinValid && rebStartTxt.toDouble() > rebEndTxt.toDouble())
{
rebinValid = false;
m_uiForm.valRebinStart->setText("*");
m_uiForm.valRebinEnd->setText("*");
}
}
return rawValid && rebinValid;
}
}
}