/
MuonAnalysis.cpp
3517 lines (2927 loc) · 101 KB
/
MuonAnalysis.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
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
491
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
548
549
550
551
552
553
554
555
556
557
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
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
803
804
805
806
807
808
809
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
851
852
853
854
855
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//----------------------
// Includes
//----------------------
#include "MantidAPI/AlgorithmManager.h"
#include "MantidAPI/FrameworkManager.h"
#include "MantidAPI/IAlgorithm.h"
#include "MantidAPI/AnalysisDataService.h"
#include "MantidAPI/Run.h"
#include "MantidAPI/ScopedWorkspace.h"
#include "MantidAPI/TableRow.h"
#include "MantidAPI/WorkspaceGroup.h"
#include "MantidGeometry/IComponent.h"
#include "MantidGeometry/IDetector.h"
#include "MantidGeometry/Instrument/DetectorGroup.h"
#include "MantidGeometry/Instrument/XMLlogfile.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/FacilityInfo.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/V3D.h"
#include "MantidKernel/cow_ptr.h"
#include "MantidQtAPI/FileDialogHandler.h"
#include "MantidQtAPI/ManageUserDirectories.h"
#include "MantidQtCustomInterfaces/IO_MuonGrouping.h"
#include "MantidQtCustomInterfaces/MuonAnalysis.h"
#include "MantidQtCustomInterfaces/MuonAnalysisFitDataTab.h"
#include "MantidQtCustomInterfaces/MuonAnalysisOptionTab.h"
#include "MantidQtCustomInterfaces/MuonAnalysisResultTableTab.h"
#include "MantidQtMantidWidgets/FitPropertyBrowser.h"
#include "MantidQtMantidWidgets/MuonFitPropertyBrowser.h"
#include "MantidQtMantidWidgets/MuonSequentialFitDialog.h"
#include <Poco/File.h>
#include <Poco/Path.h>
#include <Poco/StringTokenizer.h>
#include <boost/lexical_cast.hpp>
#include <algorithm>
#include <QLineEdit>
#include <QVariant>
#include <QtProperty>
#include <QFileDialog>
#include <QHash>
#include <QTextStream>
#include <QTreeWidgetItem>
#include <QSettings>
#include <QMessageBox>
#include <QInputDialog>
#include <QSignalMapper>
#include <QHeaderView>
#include <QApplication>
#include <QTemporaryFile>
#include <QDesktopServices>
#include <QUrl>
#include <fstream>
//Add this class to the list of specialised dialogs in this namespace
namespace MantidQt
{
namespace CustomInterfaces
{
DECLARE_SUBWINDOW(MuonAnalysis);
using namespace Mantid::API;
using namespace Mantid::Kernel;
using namespace MantidQt::MantidWidgets;
using namespace MantidQt::CustomInterfaces;
using namespace MantidQt::CustomInterfaces::Muon;
using namespace Mantid::Geometry;
// Initialize the logger
Logger& MuonAnalysis::g_log = Logger::get("MuonAnalysis");
// Static constants
const QString MuonAnalysis::NOT_AVAILABLE("N/A");
//----------------------
// Public member functions
//----------------------
///Constructor
MuonAnalysis::MuonAnalysis(QWidget *parent) :
UserSubWindow(parent),
m_last_dir(),
m_workspace_name("MuonAnalysis"), m_grouped_name(m_workspace_name + "Grouped"),
m_currentDataName(),
m_groupTableRowInFocus(0), m_pairTableRowInFocus(0),
m_currentTab(NULL),
m_groupNames(),
m_settingsGroup("CustomInterfaces/MuonAnalysis/"),
m_updating(false), m_loaded(false), m_deadTimesChanged(false),
m_textToDisplay(""),
m_dataTimeZero(0.0), m_dataFirstGoodData(0.0)
{}
/**
* Initialize local Python environmnet.
*/
void MuonAnalysis::initLocalPython()
{
QString code;
code += "from mantid.simpleapi import *\n";
// Needed for Python GUI API
code += "from PyQt4.QtGui import QPen, QBrush, QColor\n"
"from PyQt4.QtCore import QSize\n";
runPythonCode(code);
// TODO: Following shouldn't be here. It is now because ApplicationWindow sets up the Python
// environment only after the UserSubWindow is shown.
// Hide the toolbars, if user wants to
if(m_uiForm.hideToolbars->isChecked())
emit setToolbarsHidden(true);
}
/// Set up the dialog layout
void MuonAnalysis::initLayout()
{
m_uiForm.setupUi(this);
std::set<std::string> supportedFacilities;
supportedFacilities.insert("ISIS");
supportedFacilities.insert("SmuS");
const std::string userFacility = ConfigService::Instance().getFacility().name();
// Allow to load current run for ISIS only
if ( userFacility != "ISIS" )
m_uiForm.loadCurrent->setDisabled(true);
// If facility if not supported by the interface - show a warning, but still open it
if ( supportedFacilities.find(userFacility) == supportedFacilities.end() )
{
const std::string supportedFacilitiesStr = Strings::join(supportedFacilities.begin(),
supportedFacilities.end(), ", ");
const QString errorTemplate =
"Your facility (%1) is not supported by MuonAnalysis, so you will not be able to load any files. \n\n"
"Supported facilities are: %2. \n\n"
"Please use Preferences -> Mantid -> Instrument to update your facility information.";
const QString error = errorTemplate.arg( userFacility.c_str(), supportedFacilitiesStr.c_str() );
QMessageBox::warning(this, "Unsupported facility", error);
}
m_uiForm.fitBrowser->init();
connect( m_uiForm.fitBrowser, SIGNAL(sequentialFitRequested()),
this, SLOT(openSequentialFitDialog()) );
// alow appending files
m_uiForm.mwRunFiles->allowMultipleFiles(true);
// Further set initial look
startUpLook();
m_uiForm.mwRunFiles->readSettings(m_settingsGroup + "mwRunFilesBrowse");
connect(m_uiForm.previousRun, SIGNAL(clicked()), this, SLOT(checkAppendingPreviousRun()));
connect(m_uiForm.nextRun, SIGNAL(clicked()), this, SLOT(checkAppendingNextRun()));
m_optionTab = new MuonAnalysisOptionTab(m_uiForm, m_settingsGroup);
m_optionTab->initLayout();
m_fitDataTab = new MuonAnalysisFitDataTab(m_uiForm);
m_fitDataTab->init();
m_resultTableTab = new MuonAnalysisResultTableTab(m_uiForm);
connect(m_resultTableTab, SIGNAL(runPythonCode(const QString&, bool)),
this, SIGNAL(runAsPythonScript(const QString&, bool)));
setCurrentDataName(NOT_AVAILABLE);
// connect guess alpha
connect(m_uiForm.guessAlphaButton, SIGNAL(clicked()), this, SLOT(guessAlphaClicked()));
// signal/slot connections to respond to changes in instrument selection combo boxes
connect(m_uiForm.instrSelector, SIGNAL(instrumentSelectionChanged(const QString&)), this, SLOT(userSelectInstrument(const QString&)));
// Load current
connect(m_uiForm.loadCurrent, SIGNAL(clicked()), this, SLOT(runLoadCurrent()));
// If group table change
// currentCellChanged ( int currentRow, int currentColumn, int previousRow, int previousColumn )
connect(m_uiForm.groupTable, SIGNAL(cellChanged(int, int)), this, SLOT(groupTableChanged(int, int)));
connect(m_uiForm.groupTable, SIGNAL(cellClicked(int, int)), this, SLOT(groupTableClicked(int, int)));
connect(m_uiForm.groupTable->verticalHeader(), SIGNAL(sectionClicked(int)), SLOT(groupTableClicked(int)));
// group table plot button
connect(m_uiForm.groupTablePlotButton, SIGNAL(clicked()), this, SLOT(runGroupTablePlotButton()));
// If pair table change
connect(m_uiForm.pairTable, SIGNAL(cellChanged(int, int)), this, SLOT(pairTableChanged(int, int)));
connect(m_uiForm.pairTable, SIGNAL(cellClicked(int, int)), this, SLOT(pairTableClicked(int, int)));
connect(m_uiForm.pairTable->verticalHeader(), SIGNAL(sectionClicked(int)), SLOT(pairTableClicked(int)));
// Pair table plot button
connect(m_uiForm.pairTablePlotButton, SIGNAL(clicked()), this, SLOT(runPairTablePlotButton()));
// save grouping
connect(m_uiForm.saveGroupButton, SIGNAL(clicked()), this, SLOT(runSaveGroupButton()));
// load grouping
connect(m_uiForm.loadGroupButton, SIGNAL(clicked()), this, SLOT(runLoadGroupButton()));
// clear grouping
connect(m_uiForm.clearGroupingButton, SIGNAL(clicked()), this, SLOT(runClearGroupingButton()));
// front plot button
connect(m_uiForm.frontPlotButton, SIGNAL(clicked()), this, SLOT(runFrontPlotButton()));
// front group/ group pair combobox
connect(m_uiForm.frontGroupGroupPairComboBox, SIGNAL( currentIndexChanged(int) ), this, SLOT( updateFront() ));
// Synchronize plot function selector on the Home tab with the one under the Group Table
connect(m_uiForm.frontPlotFuncs, SIGNAL( activated(int) ),m_uiForm.groupTablePlotChoice, SLOT( setCurrentIndex(int) ) );
connect(m_uiForm.groupTablePlotChoice, SIGNAL( activated(int) ), this, SLOT( syncGroupTablePlotTypeWithHome() ) );
connect(m_uiForm.homePeriodBox1, SIGNAL( currentIndexChanged(int) ), this, SLOT( checkForEqualPeriods() ));
connect(m_uiForm.homePeriodBox2, SIGNAL( currentIndexChanged(int) ), this, SLOT( checkForEqualPeriods() ));
connect(m_uiForm.hideToolbars, SIGNAL( toggled(bool) ), this, SIGNAL( setToolbarsHidden(bool) ));
// connect "?" (Help) Button
connect(m_uiForm.muonAnalysisHelp, SIGNAL(clicked()), this, SLOT(muonAnalysisHelpClicked()));
connect(m_uiForm.muonAnalysisHelpGrouping, SIGNAL(clicked()), this, SLOT(muonAnalysisHelpGroupingClicked()));
// add combo boxes to pairTable
for (int i = 0; i < m_uiForm.pairTable->rowCount(); i++)
{
m_uiForm.pairTable->setCellWidget(i,1, new QComboBox);
m_uiForm.pairTable->setCellWidget(i,2, new QComboBox);
}
// file input
connect(m_uiForm.mwRunFiles, SIGNAL(fileFindingFinished()), this, SLOT(inputFileChanged_MWRunFiles()));
connect(m_uiForm.timeZeroAuto, SIGNAL(stateChanged(int)), this, SLOT(setTimeZeroState(int)));
connect(m_uiForm.firstGoodDataAuto, SIGNAL(stateChanged(int)), this, SLOT(setFirstGoodDataState(int)));
// load previous saved values
loadAutoSavedValues(m_settingsGroup);
// connect the fit function widget buttons to their respective slots.
loadFittings();
// Detect when the tab is changed
connect(m_uiForm.tabWidget, SIGNAL(currentChanged(int)), this, SLOT(changeTab(int)));
connectAutoUpdate();
connectAutoSave();
// Muon scientists never fits peaks, hence they want the following parameter, set to a high number
ConfigService::Instance().setString("curvefitting.peakRadius","99");
connect(m_uiForm.deadTimeType, SIGNAL( currentIndexChanged(int) ),
this, SLOT( onDeadTimeTypeChanged(int) ));
connect(m_uiForm.mwRunDeadTimeFile, SIGNAL( fileFindingFinished() ),
this, SLOT( deadTimeFileSelected() ));
m_currentTab = m_uiForm.tabWidget->currentWidget();
connect(this, SIGNAL( setToolbarsHidden(bool) ), this, SLOT( doSetToolbarsHidden(bool) ),
Qt::QueuedConnection ); // We dont' neet this to happen instantly, prefer safer way
// Manage User Directories
connect(m_uiForm.manageDirectoriesBtn, SIGNAL(clicked()), this, SLOT(openDirectoryDialog() ) );
}
/**
* Muon Analysis help (slot)
*/
void MuonAnalysis::muonAnalysisHelpClicked()
{
QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
"MuonAnalysis"));
}
/**
* Muon Analysis Grouping help (slot)
*/
void MuonAnalysis::muonAnalysisHelpGroupingClicked()
{
QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") +
"MuonAnalysisGrouping"));
}
/**
* Set the connected workspace name.
* @param name The new connected ws name
*/
void MuonAnalysis::setCurrentDataName(const QString& name)
{
m_currentDataName = name;
// Update labels
m_uiForm.connectedDataHome->setText("Connected: " + m_currentDataName);
m_uiForm.connectedDataGrouping->setText("Connected: " + m_currentDataName);
m_uiForm.connectedDataSettings->setText("Connected: " + m_currentDataName);
}
/**
* Front plot button (slot)
*/
void MuonAnalysis::runFrontPlotButton()
{
if(m_updating)
return;
if (m_deadTimesChanged)
{
inputFileChanged(m_previousFilenames);
return;
}
plotSelectedItem();
}
/**
* Creates a plot of selected group/pair.
*/
void MuonAnalysis::plotSelectedItem()
{
ItemType itemType;
int tableRow;
int index = m_uiForm.frontGroupGroupPairComboBox->currentIndex();
if (index < 0)
return; // Nothing to plot
if (index >= numGroups())
{
itemType = Pair;
tableRow = m_pairToRow[index-numGroups()];
}
else
{
itemType = Group;
tableRow = m_groupToRow[index];
}
PlotType plotType = parsePlotType(m_uiForm.frontPlotFuncs);
plotItem(itemType, tableRow, plotType);
}
/**
* Creates workspace for specified group/pair and plots it;
* @param itemType :: Whether it's a group or pair
* @param tableRow :: Row in the group/pair table which contains the item
* @param plotType :: What kind of plot we want to analyse
*/
void MuonAnalysis::plotItem(ItemType itemType, int tableRow, PlotType plotType)
{
m_updating = true;
AnalysisDataServiceImpl& ads = AnalysisDataService::Instance();
try
{
// Create workspace and a raw (unbinned) version of it
MatrixWorkspace_sptr ws = createAnalysisWorkspace(itemType, tableRow, plotType);
MatrixWorkspace_sptr wsRaw = createAnalysisWorkspace(itemType, tableRow, plotType, true);
// Make sure they are in the current group
if ( ! m_currentGroup->contains(ws) )
{
m_currentGroup->addWorkspace(ws);
m_currentGroup->addWorkspace(wsRaw);
}
// Find names for new workspaces
const std::string wsName = getNewAnalysisWSName(m_currentGroup->getName(), itemType, tableRow,
plotType);
const std::string wsRawName = wsName + "_Raw";
// Make sure they end up in the ADS
ads.addOrReplace(wsName, ws);
ads.addOrReplace(wsRawName, wsRaw);
QString wsNameQ = QString::fromStdString(wsName);
// Hide all the previous plot windows, if requested by user
if (m_uiForm.hideGraphs->isChecked())
hideAllPlotWindows();
// Plot the workspace
plotSpectrum( wsNameQ, (plotType == Logorithm) );
setCurrentDataName( wsNameQ );
}
catch(...)
{
QMessageBox::critical( this, "MuonAnalysis - Error", "Unable to plot the item. Check log for details." );
}
m_updating = false;
}
/**
* Finds a name for new analysis workspace.
* @param runLabel :: String describing the run we are working with
* @param itemType :: Whether it's a group or pair
* @param tableRow :: Row in the group/pair table which contains the item
* @param plotType :: What kind of plot we want to analyse
* @return New name
*/
std::string MuonAnalysis::getNewAnalysisWSName(const std::string& runLabel, ItemType itemType, int tableRow,
PlotType plotType)
{
std::string plotTypeName;
switch(plotType)
{
case Asymmetry:
plotTypeName = "Asym"; break;
case Counts:
plotTypeName = "Counts"; break;
case Logorithm:
plotTypeName = "Logs"; break;
}
std::string itemTypeName;
std::string itemName;
if ( itemType == Pair )
{
itemTypeName = "Pair";
itemName = m_uiForm.pairTable->item(tableRow,0)->text().toStdString();
}
else if ( itemType == Group )
{
itemTypeName = "Group";
itemName = m_uiForm.groupTable->item(tableRow,0)->text().toStdString();
}
const std::string firstPart = runLabel + "; " + itemTypeName + "; " + itemName + "; " + plotTypeName + "; #";
std::string newName;
if ( isOverwriteEnabled() )
{
// If ovewrite is enabled, can use the same name again and again
newName = firstPart + "1";
}
else
{
// If overwrite is disabled, need to find unique name for the new workspace
int plotNum(1);
do
{
newName = firstPart + boost::lexical_cast<std::string>(plotNum++);
}
while ( AnalysisDataService::Instance().doesExist(newName) );
}
return newName;
}
/**
* Returns PlotType as chosen using given selector.
* @param selector :: Widget to use for parsing
* @return PlotType as selected using the widget
*/
MuonAnalysis::PlotType MuonAnalysis::parsePlotType(QComboBox* selector)
{
std::string plotTypeName = selector->currentText().toStdString();
if ( plotTypeName == "Asymmetry" )
{
return Asymmetry;
}
else if ( plotTypeName == "Counts" )
{
return Counts;
}
else if ( plotTypeName == "Logorithm" )
{
return Logorithm;
}
else
{
throw std::runtime_error("Unknown plot type name: " + plotTypeName);
}
}
/**
* Creates workspace ready for analysis and plotting.
* @param itemType :: Whether it's a group or pair
* @param tableRow :: Row in the group/pair table which contains the item
* @param plotType :: What kind of plot we want to analyse
* @param isRaw :: Whether binning should be applied to the workspace
* @return Created workspace
*/
MatrixWorkspace_sptr MuonAnalysis::createAnalysisWorkspace(ItemType itemType, int tableRow, PlotType plotType,
bool isRaw)
{
IAlgorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged("MuonCalculateAsymmetry");
alg->initialize();
auto loadedWS = AnalysisDataService::Instance().retrieveWS<Workspace>(m_grouped_name);
if ( auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(loadedWS) )
{
// If is a group, will need to handle periods
if ( MatrixWorkspace_sptr ws1 = getPeriodWorkspace(First, group) )
{
alg->setProperty( "FirstPeriodWorkspace", prepareAnalysisWorkspace(ws1, isRaw) );
}
else
{
// First period should be selected no matter what
throw std::runtime_error("First period should be specified");
}
if ( MatrixWorkspace_sptr ws2 = getPeriodWorkspace(Second, group) )
{
// If second period was selected, set it up together with selected period arithmetics
alg->setProperty("SecondPeriodWorkspace", prepareAnalysisWorkspace(ws2, isRaw) );
// Parse selected operation
const std::string op = m_uiForm.homePeriodBoxMath->currentText().toStdString();
alg->setProperty("PeriodOperation", op);
}
}
else if ( auto ws = boost::dynamic_pointer_cast<MatrixWorkspace>(loadedWS) )
{
alg->setProperty( "FirstPeriodWorkspace", prepareAnalysisWorkspace(ws, isRaw) );
}
else
{
throw std::runtime_error("Usupported workspace type");
}
if ( itemType == Group )
{
std::string outputType;
switch(plotType)
{
case Counts:
case Logorithm:
outputType = "GroupCounts"; break;
case Asymmetry:
outputType = "GroupAsymmetry"; break;
default:
throw std::invalid_argument("Unsupported plot type");
}
alg->setProperty("OutputType", outputType);
int groupNum = getGroupNumberFromRow(tableRow);
alg->setProperty("GroupIndex", groupNum);
}
else if ( itemType == Pair )
{
if ( plotType == Asymmetry )
alg->setProperty("OutputType", "PairAsymmetry");
else
throw std::invalid_argument("Pairs support asymmetry plot type only");
QTableWidget* t = m_uiForm.pairTable;
double alpha = t->item(tableRow,3)->text().toDouble();
int index1 = static_cast<QComboBox*>( t->cellWidget(tableRow,1) )->currentIndex();
int index2 = static_cast<QComboBox*>( t->cellWidget(tableRow,2) )->currentIndex();
alg->setProperty("PairFirstIndex", index1);
alg->setProperty("PairSecondIndex", index2);
alg->setProperty("Alpha", alpha);
}
else
{
throw std::invalid_argument("Unsupported item type");
}
// We don't want workspace in the ADS so far
alg->setChild(true);
// Name is not used, as is child algorithm, so just to make validator happy
alg->setPropertyValue("OutputWorkspace", "__IAmNinjaYouDontSeeMe");
alg->execute();
return alg->getProperty("OutputWorkspace");
}
/**
* Crop/rebins/offsets the workspace according to interface settings.
* @param ws :: Loaded data which to prepare
* @param isRaw :: If true, Rebin is not applied
* @return Prepared workspace
*/
MatrixWorkspace_sptr MuonAnalysis::prepareAnalysisWorkspace(MatrixWorkspace_sptr ws, bool isRaw)
{
// Adjust for time zero if necessary
if ( m_dataTimeZero != timeZero())
{
double shift = m_dataTimeZero - timeZero();
Mantid::API::IAlgorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged("ChangeBinOffset");
alg->initialize();
alg->setChild(true);
alg->setProperty("InputWorkspace", ws);
alg->setProperty("Offset", shift);
alg->setPropertyValue("OutputWorkspace", "__IAmNinjaYouDontSeeMe"); // Is not used
alg->execute();
ws = alg->getProperty("OutputWorkspace");
}
// Crop workspace
Mantid::API::IAlgorithm_sptr cropAlg = AlgorithmManager::Instance().createUnmanaged("CropWorkspace");
cropAlg->initialize();
cropAlg->setChild(true);
cropAlg->setProperty("InputWorkspace", ws);
cropAlg->setProperty("Xmin", plotFromTime());
if ( !m_uiForm.timeAxisFinishAtInput->text().isEmpty() )
cropAlg->setProperty("Xmax", plotToTime());
cropAlg->setPropertyValue("OutputWorkspace", "__IAmNinjaYouDontSeeMe"); // Is not used
cropAlg->execute();
ws = cropAlg->getProperty("OutputWorkspace");
// Rebin data if option set in Plot Options and we don't want raw workspace
if ( !isRaw && m_uiForm.rebinComboBox->currentIndex() != 0)
{
std::string rebinParams;
double binSize = ws->dataX(0)[1] - ws->dataX(0)[0];
if(m_uiForm.rebinComboBox->currentIndex() == 1) // Fixed
{
double bunchedBinSize = binSize * m_uiForm.optionStepSizeText->text().toDouble();
rebinParams = boost::lexical_cast<std::string>(bunchedBinSize);
}
else // Variable
{
rebinParams = m_uiForm.binBoundaries->text().toStdString();
}
// Rebin data
IAlgorithm_sptr rebinAlg = AlgorithmManager::Instance().createUnmanaged("Rebin");
rebinAlg->initialize();
rebinAlg->setChild(true);
rebinAlg->setProperty("InputWorkspace", ws);
rebinAlg->setProperty("Params", rebinParams);
rebinAlg->setProperty("FullBinsOnly", true);
rebinAlg->setPropertyValue("OutputWorkspace", "__IAmNinjaYouDontSeeMe"); // Is not used
rebinAlg->execute();
ws = rebinAlg->getProperty("OutputWorkspace");
}
return ws;
}
/**
* Selects a workspace from the group according to what is selected on the interface for the period.
* @param periodType :: Which period we want
* @param group :: Workspace group as loaded from the data file
* @return Selected workspace
*/
MatrixWorkspace_sptr MuonAnalysis::getPeriodWorkspace(PeriodType periodType, WorkspaceGroup_sptr group)
{
QComboBox* periodSelector;
switch(periodType)
{
case First:
periodSelector = m_uiForm.homePeriodBox1; break;
case Second:
periodSelector = m_uiForm.homePeriodBox2; break;
default:
throw std::invalid_argument("Unsupported period type");
}
const QString periodLabel = periodSelector->currentText();
if ( periodLabel != "None" )
{
int periodNumber = periodLabel.toInt();
size_t periodIndex = static_cast<size_t>(periodNumber - 1);
if ( periodNumber < 1 || periodIndex >= group->size() )
throw std::runtime_error("Loaded group doesn't seem to have period " + periodLabel.toStdString());
return boost::dynamic_pointer_cast<MatrixWorkspace>( group->getItem(periodIndex) );
}
else
{
return MatrixWorkspace_sptr();
}
}
/**
* If the instrument selection has changed (slot)
*
* @param prefix :: instrument name from QComboBox object
*/
void MuonAnalysis::userSelectInstrument(const QString& prefix)
{
if ( prefix != m_curInterfaceSetup )
{
runClearGroupingButton();
m_curInterfaceSetup = prefix;
// save this new choice
QSettings group;
group.beginGroup(m_settingsGroup + "instrument");
group.setValue("name", prefix);
}
}
/**
* Save grouping button (slot)
*/
void MuonAnalysis::runSaveGroupButton()
{
if ( numGroups() <= 0 )
{
QMessageBox::warning(this, "MantidPlot - MuonAnalysis", "No grouping to save.");
return;
}
QSettings prevValues;
prevValues.beginGroup(m_settingsGroup + "SaveOutput");
// Get value for "dir". If the setting doesn't exist then use
// the the path in "defaultsave.directory"
QString prevPath = prevValues.value("dir", QString::fromStdString(
ConfigService::Instance().getString("defaultsave.directory"))).toString();
QString filter;
filter.append("Files (*.xml *.XML)");
filter += ";;AllFiles (*.*)";
QString groupingFile = MantidQt::API::FileDialogHandler::getSaveFileName(this,
"Save Grouping file as", prevPath, filter);
// Add extension if the groupingFile specified doesn't have one. (Solving Linux problem).
if (!groupingFile.endsWith(".xml"))
groupingFile += ".xml";
if( ! groupingFile.isEmpty() )
{
Grouping groupingToSave;
parseGroupingTable(m_uiForm, groupingToSave);
saveGroupingToXML(groupingToSave, groupingFile.toStdString());
QString directory = QFileInfo(groupingFile).path();
prevValues.setValue("dir", directory);
}
}
/**
* Load grouping button (slot)
*/
void MuonAnalysis::runLoadGroupButton()
{
m_updating = true;
// Get grouping file
QSettings prevValues;
prevValues.beginGroup(m_settingsGroup + "LoadGroupFile");
// Get value for "dir". If the setting doesn't exist then use
// the the path in "defaultsave.directory"
QString prevPath = prevValues.value("dir", QString::fromStdString(
ConfigService::Instance().getString("defaultload.directory"))).toString();
QString filter;
filter.append("Files (*.xml *.XML)");
filter += ";;AllFiles (*.*)";
QString groupingFile = QFileDialog::getOpenFileName(this, "Load Grouping file", prevPath, filter);
if( groupingFile.isEmpty() || QFileInfo(groupingFile).isDir() )
return;
QString directory = QFileInfo(groupingFile).path();
prevValues.setValue("dir", directory);
Grouping loadedGrouping;
try
{
loadGroupingFromXML(groupingFile.toStdString(), loadedGrouping);
}
catch (Exception::FileError& e)
{
g_log.error("Unable to load grouping. Data left unchanged");
g_log.error(e.what());
m_updating = false;
return;
}
clearTablesAndCombo();
fillGroupingTable(loadedGrouping, m_uiForm);
m_updating = false;
if ( m_loaded )
{
try
{
groupLoadedWorkspace();
}
catch(std::exception& e)
{
g_log.error( e.what() );
QMessageBox::critical(this, "MantidPlot - MuonAnalysis",
"Unable to group the workspace. See log for details.");
}
}
}
/**
* Clear grouping button (slot)
*/
void MuonAnalysis::runClearGroupingButton()
{
clearTablesAndCombo();
}
/**
* Group table plot button (slot)
*/
void MuonAnalysis::runGroupTablePlotButton()
{
if(m_updating)
return;
if (m_deadTimesChanged)
{
inputFileChanged(m_previousFilenames);
return;
}
if ( getGroupNumberFromRow(m_groupTableRowInFocus) != -1 )
{
PlotType plotType = parsePlotType(m_uiForm.groupTablePlotChoice);
plotItem(Group, m_groupTableRowInFocus, plotType);
}
}
/**
* Load current (slot)
*/
void MuonAnalysis::runLoadCurrent()
{
QString instname = m_uiForm.instrSelector->currentText().toUpper();
// If Argus data then simple
if ( instname == "ARGUS" )
{
QString argusDAE = "\\\\ndw828\\argusdata\\current cycle\\nexus\\argus0000000.nxs";
Poco::File l_path( argusDAE.toStdString() );
try
{
if ( !l_path.exists() )
{
QMessageBox::warning(this,"Mantid - MuonAnalysis",
QString("Can't load ARGUS Current data since\n") +
argusDAE + QString("\n") +
QString("does not seem to exist"));
return;
}
}
catch(Poco::Exception&)
{
QMessageBox::warning(this, "MantidPlot - MuonAnalysis", "Can't read from the selected directory, either the computer you are trying"
"\nto access is down or your computer is not currently connected to the network.");
return;
}
m_uiForm.mwRunFiles->setUserInput(argusDAE);
m_uiForm.mwRunFiles->setText("CURRENT RUN");
return;
}
if ( instname == "EMU" || instname == "HIFI" || instname == "MUSR")
{
std::string autosavePointsTo = "";
std::string autosaveFile = "\\\\" + instname.toStdString() + "\\data\\autosave.run";
Poco::File pathAutosave( autosaveFile );
try // check if exists
{
if ( pathAutosave.exists() )
{
std::ifstream autofileIn(autosaveFile.c_str(), std::ifstream::in);
autofileIn >> autosavePointsTo;
}
}
catch(Poco::Exception&)
{
QMessageBox::warning(this, "MantidPlot - MuonAnalysis", "Can't read from the selected directory, either the computer you are trying"
"\nto access is down or your computer is not currently connected to the network.");
return;
}
QString psudoDAE;
if ( autosavePointsTo.empty() )
psudoDAE = "\\\\" + instname + "\\data\\" + instname + "auto_A.tmp";
else
psudoDAE = "\\\\" + instname + "\\data\\" + autosavePointsTo.c_str();
Poco::File l_path( psudoDAE.toStdString() );
try
{
if ( !l_path.exists() )
{
QMessageBox::warning(this,"Mantid - MuonAnalysis",
QString("Can't load ") + "Current data since\n" +
psudoDAE + QString("\n") +
QString("does not seem to exist"));
return;
}
}
catch(Poco::Exception&)
{
QMessageBox::warning(this,"Mantid - MuonAnalysis",
QString("Can't load ") + "Current data since\n" +
psudoDAE + QString("\n") +
QString("does not seem to exist"));
return;
}
m_uiForm.mwRunFiles->setUserInput(psudoDAE);
m_uiForm.mwRunFiles->setText("CURRENT RUN");
return;
}
QMessageBox::critical(this, "Unsupported instrument",
"Current run loading is not supported for the selected instrument.");
}
/**
* Pair table plot button (slot)
*/
void MuonAnalysis::runPairTablePlotButton()
{
if(m_updating)
return;
if (m_deadTimesChanged)
{
inputFileChanged(m_previousFilenames);
return;
}
if ( getPairNumberFromRow(m_pairTableRowInFocus) != -1 )
{
// Sync with selectors on the front
m_uiForm.frontGroupGroupPairComboBox->setCurrentIndex(numGroups() + m_pairTableRowInFocus);
m_uiForm.frontPlotFuncs->setCurrentIndex(m_uiForm.pairTablePlotChoice->currentIndex());
PlotType plotType = parsePlotType(m_uiForm.pairTablePlotChoice);
plotItem(Pair, m_pairTableRowInFocus, plotType);
}
}
/**
* Pair table vertical lable clicked (slot)
*/
void MuonAnalysis::pairTableClicked(int row)
{
m_pairTableRowInFocus = row;
// if something sensible in row then update front
int pNum = getPairNumberFromRow(row);
if ( pNum >= 0 )
{
m_uiForm.frontGroupGroupPairComboBox->setCurrentIndex(pNum+numGroups());
}
}
/**
* Pair table clicked (slot)
*/
void MuonAnalysis::pairTableClicked(int row, int column)
{
(void) column;
pairTableClicked(row);
}
/**
* Group table clicked (slot)
*/
void MuonAnalysis::groupTableClicked(int row, int column)
{