-
Notifications
You must be signed in to change notification settings - Fork 122
/
InstrumentWindowPickTab.cpp
1512 lines (1399 loc) · 48 KB
/
InstrumentWindowPickTab.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
#include "InstrumentWindow.h"
#include "InstrumentWindowPickTab.h"
#include "OneCurvePlot.h"
#include "CollapsiblePanel.h"
#include "InstrumentActor.h"
#include "ProjectionSurface.h"
#include "UnwrappedSurface.h"
#include "Projection3D.h"
#include "PeakMarker2D.h"
#include "MantidKernel/ConfigService.h"
#include "MantidKernel/DynamicFactory.h"
#include "MantidGeometry/Instrument/ParameterMap.h"
#include "MantidAPI/AnalysisDataService.h"
#include "MantidAPI/ITableWorkspace.h"
#include "MantidAPI/IPeaksWorkspace.h"
#include "MantidAPI/MatrixWorkspace.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidAPI/TableRow.h"
#include "MantidAPI/FrameworkManager.h"
#include "MantidGeometry/Crystal/OrientedLattice.h"
#include "qwt_scale_widget.h"
#include "qwt_scale_div.h"
#include "qwt_scale_engine.h"
#include <QVBoxLayout>
#include <QPushButton>
#include <QTextEdit>
#include <QMenu>
#include <QAction>
#include <QActionGroup>
#include <QWidgetAction>
#include <QLabel>
#include <QMessageBox>
#include <QDialog>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QComboBox>
#include <QLineEdit>
#include <QSignalMapper>
#include <QPixmap>
#include <QSettings>
#include <QApplication>
#include <numeric>
#include <cfloat>
#include <cmath>
#include <algorithm>
/// to be used in std::transform
struct Sqrt
{
double operator()(double x)
{
return sqrt(x);
}
};
/**
* Constructor.
* @param instrWindow :: Parent InstrumentWindow.
*/
InstrumentWindowPickTab::InstrumentWindowPickTab(InstrumentWindow* instrWindow):
InstrumentWindowTab(instrWindow),
m_currentDetID(-1),
m_tubeXUnits(DETECTOR_ID),
m_freezePlot(false)
{
// connect to InstrumentWindow signals
connect(m_instrWindow,SIGNAL(integrationRangeChanged(double,double)),this,SLOT(changedIntegrationRange(double,double)));
m_plotSum = true;
QVBoxLayout* layout=new QVBoxLayout(this);
// set up the selection display
m_selectionInfoDisplay = new QTextEdit(this);
// set up the plot widget
m_plot = new OneCurvePlot(this);
m_plot->setYAxisLabelRotation(-90);
m_plot->setXScale(0,1);
m_plot->setYScale(-1.2,1.2);
connect(m_plot,SIGNAL(showContextMenu()),this,SLOT(plotContextMenu()));
connect(m_plot,SIGNAL(clickedAt(double,double)),this,SLOT(addPeak(double,double)));
// Plot context menu actions
m_sumDetectors = new QAction("Sum",this);
m_sumDetectors->setCheckable(true);
m_sumDetectors->setChecked(true);
m_integrateTimeBins = new QAction("Integrate",this);
m_integrateTimeBins->setCheckable(true);
m_summationType = new QActionGroup(this);
m_summationType->addAction(m_sumDetectors);
m_summationType->addAction(m_integrateTimeBins);
m_logY = new QAction("Y log scale",this);
m_linearY = new QAction("Y linear scale",this);
m_yScale = new QActionGroup(this);
m_yScale->addAction(m_linearY);
m_yScale->addAction(m_logY);
m_logY->setCheckable(true);
m_linearY->setCheckable(true);
m_linearY->setChecked(true);
connect(m_sumDetectors,SIGNAL(triggered()),this,SLOT(sumDetectors()));
connect(m_integrateTimeBins,SIGNAL(triggered()),this,SLOT(integrateTimeBins()));
connect(m_logY,SIGNAL(triggered()),m_plot,SLOT(setYLogScale()));
connect(m_linearY,SIGNAL(triggered()),m_plot,SLOT(setYLinearScale()));
m_unitsMapper = new QSignalMapper(this);
m_detidUnits = new QAction("Detector ID",this);
m_detidUnits->setCheckable(true);
m_unitsMapper->setMapping(m_detidUnits,DETECTOR_ID);
connect(m_detidUnits,SIGNAL(triggered()),m_unitsMapper,SLOT(map()));
m_lengthUnits = new QAction("Tube length",this);
m_lengthUnits->setCheckable(true);
m_unitsMapper->setMapping(m_lengthUnits,LENGTH);
connect(m_lengthUnits,SIGNAL(triggered()),m_unitsMapper,SLOT(map()));
m_phiUnits = new QAction("Phi",this);
m_phiUnits->setCheckable(true);
m_unitsMapper->setMapping(m_phiUnits,PHI);
connect(m_phiUnits,SIGNAL(triggered()),m_unitsMapper,SLOT(map()));
m_outOfPlaneAngleUnits = new QAction("Out of plane angle",this);
m_outOfPlaneAngleUnits->setCheckable(true);
m_unitsMapper->setMapping(m_outOfPlaneAngleUnits,OUT_OF_PLANE_ANGLE);
connect(m_outOfPlaneAngleUnits,SIGNAL(triggered()),m_unitsMapper,SLOT(map()));
m_unitsGroup = new QActionGroup(this);
m_unitsGroup->addAction(m_detidUnits);
m_unitsGroup->addAction(m_lengthUnits);
m_unitsGroup->addAction(m_phiUnits); // re #4169 disabled until fixed or removed
m_unitsGroup->addAction(m_outOfPlaneAngleUnits);
connect(m_unitsMapper,SIGNAL(mapped(int)),this,SLOT(setTubeXUnits(int)));
// Instrument display context menu actions
m_storeCurve = new QAction("Store curve",this);
connect(m_storeCurve,SIGNAL(triggered()),this,SLOT(storeCurve()));
m_savePlotToWorkspace = new QAction("Save plot to workspace",this);
connect(m_savePlotToWorkspace,SIGNAL(triggered()),this,SLOT(savePlotToWorkspace()));
CollapsibleStack* panelStack = new CollapsibleStack(this);
m_infoPanel = panelStack->addPanel("Selection",m_selectionInfoDisplay);
m_plotPanel = panelStack->addPanel("Name",m_plot);
m_activeTool = new QLabel(this);
// set up the tool bar
m_zoom = new QPushButton();
m_zoom->setCheckable(true);
m_zoom->setAutoExclusive(true);
m_zoom->setIcon(QIcon(":/PickTools/zoom.png"));
m_zoom->setToolTip("Zoom in and out");
m_one = new QPushButton();
m_one->setCheckable(true);
m_one->setAutoExclusive(true);
m_one->setChecked(true);
m_one->setToolTip("Select single pixel");
m_one->setIcon(QIcon(":/PickTools/selection-pointer.png"));
m_tube = new QPushButton();
m_tube->setCheckable(true);
m_tube->setAutoExclusive(true);
m_tube->setIcon(QIcon(":/PickTools/selection-tube.png"));
m_tube->setToolTip("Select whole tube");
m_rectangle = new QPushButton();
m_rectangle->setCheckable(true);
m_rectangle->setAutoExclusive(true);
m_rectangle->setIcon(QIcon(":/PickTools/selection-box.png"));
m_rectangle->setToolTip("Draw a rectangle");
m_ellipse = new QPushButton();
m_ellipse->setCheckable(true);
m_ellipse->setAutoExclusive(true);
m_ellipse->setIcon(QIcon(":/PickTools/selection-circle.png"));
m_ellipse->setToolTip("Draw a ellipse");
m_ring_ellipse = new QPushButton();
m_ring_ellipse->setCheckable(true);
m_ring_ellipse->setAutoExclusive(true);
m_ring_ellipse->setIcon(QIcon(":/PickTools/selection-circle-ring.png"));
m_ring_ellipse->setToolTip("Draw an elliptical ring");
m_ring_rectangle = new QPushButton();
m_ring_rectangle->setCheckable(true);
m_ring_rectangle->setAutoExclusive(true);
m_ring_rectangle->setIcon(QIcon(":/PickTools/selection-box-ring.png"));
m_ring_rectangle->setToolTip("Draw a rectangular ring");
m_edit = new QPushButton();
m_edit->setCheckable(true);
m_edit->setAutoExclusive(true);
m_edit->setIcon(QIcon(":/PickTools/selection-edit.png"));
m_edit->setToolTip("Edit a shape");
m_peak = new QPushButton();
m_peak->setCheckable(true);
m_peak->setAutoExclusive(true);
m_peak->setIcon(QIcon(":/PickTools/selection-peak.png"));
m_peak->setToolTip("Add single crystal peak");
m_peakSelect = new QPushButton();
m_peakSelect->setCheckable(true);
m_peakSelect->setAutoExclusive(true);
m_peakSelect->setIcon(QIcon(":/PickTools/eraser.png"));
m_peakSelect->setToolTip("Erase single crystal peak(s)");
QGridLayout* toolBox = new QGridLayout();
toolBox->addWidget(m_zoom,0,0);
toolBox->addWidget(m_edit,0,1);
toolBox->addWidget(m_ellipse,0,2);
toolBox->addWidget(m_rectangle,0,3);
toolBox->addWidget(m_ring_ellipse,0,4);
toolBox->addWidget(m_ring_rectangle,0,5);
toolBox->addWidget(m_one,1,0);
toolBox->addWidget(m_tube,1,1);
toolBox->addWidget(m_peak,1,2);
toolBox->addWidget(m_peakSelect,1,3);
toolBox->setColStretch(6,1);
toolBox->setSpacing(2);
connect(m_zoom,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_one,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_tube,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_peak,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_peakSelect,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_rectangle,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_ellipse,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_ring_ellipse,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_ring_rectangle,SIGNAL(clicked()),this,SLOT(setSelectionType()));
connect(m_edit,SIGNAL(clicked()),this,SLOT(setSelectionType()));
setSelectionType();
// lay out the widgets
layout->addWidget(m_activeTool);
layout->addLayout(toolBox);
layout->addWidget(panelStack);
setPlotCaption();
}
/**
* Returns true if the plot can be updated when the mouse moves over detectors
*/
bool InstrumentWindowPickTab::canUpdateTouchedDetector()const
{
return ! m_peak->isChecked();
}
/**
* Update the miniplot for a selected detector.
* @param detid :: ID of detector to use to update the plot.
*/
void InstrumentWindowPickTab::updatePlot(int detid)
{
if (m_instrWindow->blocked())
{
m_plot->clearCurve();
return;
}
if (m_plotPanel->isCollapsed()) return;
if (detid >= 0)
{
if (m_one->isChecked() || m_peak->isChecked())
{// plot spectrum of a single detector
plotSingle(detid);
}
else if (m_tube->isChecked())
{// plot integrals
plotTube(detid);
}
}
else
{
m_plot->clearCurve();
}
m_plot->recalcAxisDivs();
m_plot->replot();
}
/**
* Update the info window with information for a selected detector.
* @param detid :: ID of the selected detector.
*/
void InstrumentWindowPickTab::updateSelectionInfo(int detid)
{
if (m_freezePlot)
{// freeze the plot for one update
m_freezePlot = false;
detid = m_currentDetID;
}
if (m_instrWindow->blocked())
{
m_selectionInfoDisplay->clear();
return;
}
QString text;
if (detid >= 0)
{
// collect info about selected detector and add it to text
InstrumentActor* instrActor = m_instrWindow->getInstrumentActor();
Mantid::Geometry::IDetector_const_sptr det;
try
{
det = instrActor->getInstrument()->getDetector(detid);
}
catch(...)
{
// if this slot is called during instrument window deletion
// expect exceptions thrown
return;
}
text = "Selected detector: " + QString::fromStdString(det->getName()) + "\n";
text += "Detector ID: " + QString::number(detid) + '\n';
QString wsIndex;
try {
wsIndex = QString::number(instrActor->getWorkspaceIndex(detid));
updatePlot(detid); // Update the plot if the detector links to some data
} catch (Mantid::Kernel::Exception::NotFoundError &) {
// Detector doesn't have a workspace index relating to it
wsIndex = "None";
m_plot->clearCurve(); // Clear the plot window
m_plot->replot();
}
text += "Workspace index: " + wsIndex + '\n';
Mantid::Kernel::V3D pos = det->getPos();
text += "xyz: " + QString::number(pos.X()) + "," + QString::number(pos.Y()) + "," + QString::number(pos.Z()) + '\n';
double r,t,p;
pos.getSpherical(r,t,p);
text += "rtp: " + QString::number(r) + "," + QString::number(t) + "," + QString::number(p) + '\n';
Mantid::Geometry::ICompAssembly_const_sptr parent = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(det->getParent());
if (parent)
{
QString textpath;
while (parent)
{
textpath="/"+QString::fromStdString(parent->getName())+textpath;
parent=boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(parent->getParent());
}
text += "Component path:" +textpath+"/"+ QString::fromStdString(det->getName()) +'\n';
}
const double integrated = instrActor->getIntegratedCounts(detid);
const QString counts = integrated == -1.0 ? "N/A" : QString::number(integrated);
text += "Counts: " + counts + '\n';
QString xUnits;
if (m_selectionType > SingleDetectorSelection && !m_plotSum)
{
switch(m_tubeXUnits)
{
case DETECTOR_ID: xUnits = "Detector ID"; break;
case LENGTH: xUnits = "Length"; break;
case PHI: xUnits = "Phi"; break;
case OUT_OF_PLANE_ANGLE: xUnits = "Out of plane angle"; break;
default: xUnits = "Detector ID";
}
}
else
{
xUnits = QString::fromStdString(instrActor->getWorkspace()->getAxis(0)->unit()->caption());
}
text += "X units: " + xUnits + '\n';
// display info about peak overlays
text += getParameterInfo(det);
}
else
{
m_plot->clearCurve(); // Clear the plot window
m_plot->replot();
}
// display info about peak overlays
text += getNonDetectorInfo();
if ( !text.isEmpty() )
{
m_selectionInfoDisplay->setText(text);
}
else
{
m_selectionInfoDisplay->clear();
}
}
/**
* Form a string for output from the components instrument parameters
*/
QString InstrumentWindowPickTab::getParameterInfo(Mantid::Geometry::IComponent_const_sptr comp)
{
QString text = "";
std::map<Mantid::Geometry::ComponentID, std::vector<std::string> > mapCmptToNameVector;
auto paramNames = comp->getParameterNamesByComponent();
for (auto itParamName = paramNames.begin(); itParamName != paramNames.end(); ++itParamName)
{
//build the data structure I need Map comp id -> vector of names
std::string paramName = itParamName->first;
Mantid::Geometry::ComponentID paramCompId = itParamName->second;
//attempt to insert this will fail silently if the key already exists
if ( mapCmptToNameVector.find(paramCompId) == mapCmptToNameVector.end() )
{
mapCmptToNameVector.insert(std::pair<Mantid::Geometry::ComponentID, std::vector<std::string> >(paramCompId,std::vector<std::string>()));
}
//get the vector out and add the name
mapCmptToNameVector[paramCompId].push_back(paramName);
}
//walk out from the selected component
Mantid::Geometry::IComponent_const_sptr paramComp = comp;
while (paramComp)
{
auto& compParamNames = mapCmptToNameVector[paramComp->getComponentID()];
if (compParamNames.size() > 0)
{
text += QString::fromStdString("\nParameters from: " + paramComp->getName() + "\n");
std::sort(compParamNames.begin(), compParamNames.end(),Mantid::Kernel::CaseInsensitiveStringComparator());
for (auto itParamName = compParamNames.begin(); itParamName != compParamNames.end(); ++itParamName)
{
std::string paramName = *itParamName;
//no need to search recursively as we are asking from the matching component
std::string paramValue = paramComp->getParameterAsString(paramName,false);
if (paramValue != "")
{
text += QString::fromStdString(paramName + ": " + paramValue + "\n");
}
}
}
paramComp = paramComp->getParent();
}
return text;
}
/**
* Display the miniplot's context menu.
*/
void InstrumentWindowPickTab::plotContextMenu()
{
QMenu context(this);
if (m_selectionType > SingleDetectorSelection)
{// only for multiple detector selectors
context.addActions(m_summationType->actions());
if ( m_selectionType == Draw )
{
m_sumDetectors->setChecked(true);
m_integrateTimeBins->setEnabled(false);
}
else
{
m_sumDetectors->setChecked(m_plotSum);
m_integrateTimeBins->setChecked(!m_plotSum);
m_integrateTimeBins->setEnabled(true);
}
context.addSeparator();
}
if (m_plot->hasStored())
{
// the remove menu
QMenu *removeCurves = new QMenu("Remove",this);
QSignalMapper *signalMapper = new QSignalMapper(this);
QStringList labels = m_plot->getLabels();
foreach(QString label,labels)
{
QColor c = m_plot->getCurveColor(label);
QPixmap pixmap(16,2);
pixmap.fill(c);
QAction *remove = new QAction(QIcon(pixmap),label,removeCurves);
removeCurves->addAction(remove);
connect(remove,SIGNAL(triggered()),signalMapper,SLOT(map()));
signalMapper->setMapping(remove,label);
}
connect(signalMapper, SIGNAL(mapped(const QString &)),
this, SLOT(removeCurve(const QString &)));
context.addMenu(removeCurves);
}
// the axes menu
QMenu* axes = new QMenu("Axes",this);
axes->addActions(m_yScale->actions());
if (m_plot->isYLogScale())
{
m_logY->setChecked(true);
}
else
{
m_linearY->setChecked(true);
}
// Tube x units menu options
if (m_selectionType > SingleDetectorSelection && !m_plotSum)
{
axes->addSeparator();
axes->addActions(m_unitsGroup->actions());
switch(m_tubeXUnits)
{
case DETECTOR_ID: m_detidUnits->setChecked(true); break;
case LENGTH: m_lengthUnits->setChecked(true); break;
case PHI: m_phiUnits->setChecked(true); break;
case OUT_OF_PLANE_ANGLE: m_outOfPlaneAngleUnits->setChecked(true); break;
default: m_detidUnits->setChecked(true);
}
}
context.addMenu(axes);
// save plot to workspace
if (m_plot->hasStored() || m_plot->hasCurve())
{
context.addAction(m_savePlotToWorkspace);
}
// show menu
context.exec(QCursor::pos());
}
/**
* Update the plot caption. The captions shows the selection type.
*/
void InstrumentWindowPickTab::setPlotCaption()
{
QString caption;
if (m_selectionType < SingleDetectorSelection)
{
caption = "Plotting detector spectra";
}
else if (m_edit->isChecked())
{
caption = "Plotting multiple detector sum";
}
else if (m_plotSum)
{
caption = "Plotting sum";
}
else
{
caption = "Plotting integral";
}
m_plotPanel->setCaption(caption);
}
/**
* Switch to the detectors summing regime.
*/
void InstrumentWindowPickTab::sumDetectors()
{
m_plotSum = true;
m_plot->clearAll();
m_plot->replot();
setPlotCaption();
}
/**
* Switch to the time bin integration regime.
*/
void InstrumentWindowPickTab::integrateTimeBins()
{
m_plotSum = false;
m_plot->clearAll();
m_plot->replot();
setPlotCaption();
}
/**
* Update the tab to display info for a new detector.
* @param detid :: ID of the new detector.
*/
void InstrumentWindowPickTab::updatePick(int detid)
{
updateSelectionInfo(detid); // Also calls updatePlot
m_currentDetID = detid;
}
/**
* Plot data for a detector.
* @param detid :: ID of the detector to be plotted.
*/
void InstrumentWindowPickTab::plotSingle(int detid)
{
std::vector<double> x,y;
prepareDataForSinglePlot(detid,x,y);
m_plot->clearPeakLabels();
// set the data
m_plot->setData(&x[0],&y[0],static_cast<int>(y.size()), m_instrWindow->getInstrumentActor()->getWorkspace()->getAxis(0)->unit()->unitID());
m_plot->setLabel("Detector " + QString::number(detid));
// find any markers
auto surface = getSurface();
if (surface)
{
QList<PeakMarker2D*> markers = surface->getMarkersWithID(detid);
foreach(PeakMarker2D* marker,markers)
{
m_plot->addPeakLabel(marker);
}
}
}
/**
* Plot data integrated either over the detectors in a tube or over time bins.
* If m_plotSum == true the miniplot displays the accumulated data in a tube against time of flight.
* If m_plotSum == false the miniplot displays the data integrated over the time bins. The values are
* plotted against the length of the tube, but the units on the x-axis can be one of the following:
* DETECTOR_ID
* LENGTH
* PHI
* The units can be set with setTubeXUnits(...) method.
* @param detid :: A detector id. The miniplot will display data for a component containing the detector
* with this id.
*/
void InstrumentWindowPickTab::plotTube(int detid)
{
InstrumentActor* instrActor = m_instrWindow->getInstrumentActor();
Mantid::API::MatrixWorkspace_const_sptr ws = instrActor->getWorkspace();
Mantid::Geometry::IDetector_const_sptr det = instrActor->getInstrument()->getDetector(detid);
boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
Mantid::Geometry::ICompAssembly_const_sptr ass = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(parent);
if (parent && ass)
{
if (m_plotSum) // plot sums over detectors vs time bins
{
plotTubeSums(detid);
}
else // plot detector integrals vs detID or a function of detector position in the tube
{
plotTubeIntegrals(detid);
}
}
else
{
m_plot->clearCurve();
}
}
/**
* Plot the accumulated data in a tube against time of flight.
* @param detid :: A detector id. The miniplot will display data for a component containing the detector
* with this id.
*/
void InstrumentWindowPickTab::plotTubeSums(int detid)
{
std::vector<double> x,y;
prepareDataForSumsPlot(detid,x,y);
InstrumentActor* instrActor = m_instrWindow->getInstrumentActor();
Mantid::Geometry::IDetector_const_sptr det = instrActor->getInstrument()->getDetector(detid);
boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
QString label = QString::fromStdString(parent->getName()) + " (" + QString::number(detid) + ") Sum";
m_plot->setData(&x[0],&y[0],static_cast<int>(y.size()), m_instrWindow->getInstrumentActor()->getWorkspace()->getAxis(0)->unit()->unitID());
m_plot->setLabel(label);
}
/**
* Plot the data integrated over the time bins. The values are
* plotted against the length of the tube, but the units on the x-axis can be one of the following:
* DETECTOR_ID
* LENGTH
* PHI
* The units can be set with setTubeXUnits(...) method.
* @param detid :: A detector id. The miniplot will display data for a component containing the detector
* with this id.
*/
void InstrumentWindowPickTab::plotTubeIntegrals(int detid)
{
InstrumentActor* instrActor = m_instrWindow->getInstrumentActor();
Mantid::Geometry::IDetector_const_sptr det = instrActor->getInstrument()->getDetector(detid);
boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
// curve label: "tube_name (detid) Integrals"
// detid is included to distiguish tubes with the same name
QString label = QString::fromStdString(parent->getName()) + " (" + QString::number(detid) + ") Integrals";
label += "/" + getTubeXUnitsName(m_tubeXUnits);
std::vector<double> x,y;
prepareDataForIntegralsPlot(detid,x,y);
m_plot->setData(&x[0],&y[0],static_cast<int>(y.size()));
m_plot->setLabel(label);
}
/**
* Set the selection type according to which tool button is checked.
*/
void InstrumentWindowPickTab::setSelectionType()
{
ProjectionSurface::InteractionMode surfaceMode = ProjectionSurface::PickSingleMode;
if (m_zoom->isChecked())
{
m_selectionType = Single;
m_activeTool->setText("Tool: Navigation");
surfaceMode = ProjectionSurface::MoveMode;
}
else if (m_one->isChecked())
{
m_selectionType = Single;
m_activeTool->setText("Tool: Pixel selection");
surfaceMode = ProjectionSurface::PickSingleMode;
}
else if (m_tube->isChecked())
{
m_selectionType = Tube;
m_activeTool->setText("Tool: Tube/bank selection");
surfaceMode = ProjectionSurface::PickTubeMode;
}
else if (m_peak->isChecked())
{
m_selectionType = AddPeak;
m_activeTool->setText("Tool: Add a single crystal peak");
surfaceMode = ProjectionSurface::AddPeakMode;
}
else if (m_peakSelect->isChecked())
{
m_selectionType = ErasePeak;
m_activeTool->setText("Tool: Erase crystal peak(s)");
surfaceMode = ProjectionSurface::EraseMode;
}
else if (m_rectangle->isChecked())
{
m_selectionType = Draw;
m_activeTool->setText("Tool: Rectangle");
surfaceMode = ProjectionSurface::DrawMode;
m_instrWindow->getSurface()->startCreatingShape2D("rectangle",Qt::green,QColor(255,255,255,80));
}
else if (m_ellipse->isChecked())
{
m_selectionType = Draw;
m_activeTool->setText("Tool: Ellipse");
surfaceMode = ProjectionSurface::DrawMode;
m_instrWindow->getSurface()->startCreatingShape2D("ellipse",Qt::green,QColor(255,255,255,80));
}
else if (m_ring_ellipse->isChecked())
{
m_selectionType = Draw;
m_activeTool->setText("Tool: Elliptical ring");
surfaceMode = ProjectionSurface::DrawMode;
m_instrWindow->getSurface()->startCreatingShape2D("ring ellipse",Qt::green,QColor(255,255,255,80));
}
else if (m_ring_rectangle->isChecked())
{
m_selectionType = Draw;
m_activeTool->setText("Tool: Rectangular ring");
surfaceMode = ProjectionSurface::DrawMode;
m_instrWindow->getSurface()->startCreatingShape2D("ring rectangle",Qt::green,QColor(255,255,255,80));
}
else if (m_edit->isChecked())
{
m_selectionType = Draw;
m_activeTool->setText("Tool: Shape editing");
surfaceMode = ProjectionSurface::DrawMode;
}
auto surface = m_instrWindow->getSurface();
if ( surface )
{
surface->setInteractionMode( surfaceMode );
auto interactionMode = surface->getInteractionMode();
if ( interactionMode == ProjectionSurface::DrawMode || interactionMode == ProjectionSurface::MoveMode )
{
updatePlotMultipleDetectors();
}
else
{
m_plot->clearAll();
m_plot->replot();
}
setPlotCaption();
}
m_instrWindow->updateInfoText();
}
/**
* Add a peak to the single crystal peak table.
* @param x :: Time of flight
* @param y :: Peak height (counts)
*/
void InstrumentWindowPickTab::addPeak(double x,double y)
{
if (!m_peak->isChecked() || m_currentDetID < 0) return;
try
{
Mantid::API::IPeaksWorkspace_sptr tw = m_instrWindow->getSurface()->getEditPeaksWorkspace();
InstrumentActor* instrActor = m_instrWindow->getInstrumentActor();
Mantid::API::MatrixWorkspace_const_sptr ws = instrActor->getWorkspace();
std::string peakTableName;
bool newPeaksWorkspace = false;
if ( tw )
{
peakTableName = tw->name();
}
else
{
peakTableName = "SingleCrystalPeakTable";
// This does need to get the instrument from the workspace as it's doing calculations
// .....and this method should be an algorithm! Or at least somewhere different to here.
Mantid::Geometry::Instrument_const_sptr instr = ws->getInstrument();
if (! Mantid::API::AnalysisDataService::Instance().doesExist(peakTableName))
{
tw = Mantid::API::WorkspaceFactory::Instance().createPeaks("PeaksWorkspace");
tw->setInstrument(instr);
Mantid::API::AnalysisDataService::Instance().add(peakTableName,tw);
newPeaksWorkspace = true;
}
else
{
tw = boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(peakTableName));
if (!tw)
{
QMessageBox::critical(this,"Mantid - Error","Workspace " + QString::fromStdString(peakTableName) + " is not a TableWorkspace");
return;
}
}
auto surface = boost::dynamic_pointer_cast<UnwrappedSurface>( m_instrWindow->getSurface() );
if ( surface )
{
surface->setPeaksWorkspace(boost::dynamic_pointer_cast<Mantid::API::IPeaksWorkspace>(tw));
}
}
// Run the AddPeak algorithm
auto alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("AddPeak");
alg->setPropertyValue( "RunWorkspace", ws->name() );
alg->setPropertyValue( "PeaksWorkspace", peakTableName );
alg->setProperty( "DetectorID", m_currentDetID );
alg->setProperty( "TOF", x );
alg->setProperty( "Height", instrActor->getIntegratedCounts(m_currentDetID) );
alg->setProperty( "BinCount", y );
alg->execute();
// if data WS has UB copy it to the new peaks workspace
if ( newPeaksWorkspace && ws->sample().hasOrientedLattice() )
{
auto UB = ws->sample().getOrientedLattice().getUB();
auto lattice = new Mantid::Geometry::OrientedLattice;
lattice->setUB(UB);
tw->mutableSample().setOrientedLattice(lattice);
}
// if there is a UB available calculate HKL for the new peak
if ( tw->sample().hasOrientedLattice() )
{
auto alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("CalculatePeaksHKL");
alg->setPropertyValue( "PeaksWorkspace", peakTableName );
alg->execute();
}
}
catch(std::exception& e)
{
QMessageBox::critical(this,"MantidPlot -Error",
"Cannot create a Peak object because of the error:\n"+QString(e.what()));
}
}
/**
* Respond to the show event.
*/
void InstrumentWindowPickTab::showEvent (QShowEvent *)
{
// Make the state of the display view consistent with the current selection type
setSelectionType();
// make sure picking updated
m_instrWindow->updateInstrumentView(true);
m_instrWindow->getSurface()->changeBorderColor( getShapeBorderColor() );
}
/**
* Keep current curve permanently displayed on the plot.
*/
void InstrumentWindowPickTab::storeCurve()
{
m_plot->store();
}
/**
* Remove a stored curve.
* @param label :: The label of the curve to remove
*/
void InstrumentWindowPickTab::removeCurve(const QString & label)
{
m_plot->removeCurve(label);
m_plot->replot();
}
/**
* Set the x units for the integrated tube plot.
* @param units :: The x units in terms of TubeXUnits.
*/
void InstrumentWindowPickTab::setTubeXUnits(int units)
{
if (units < 0 || units >= NUMBER_OF_UNITS) return;
m_tubeXUnits = static_cast<TubeXUnits>(units);
m_plot->clearAll();
m_plot->replot();
}
/**
* Prepare data for plotting a spectrum of a single detector.
* @param detid :: ID of the detector to be plotted.
* @param x :: Vector of x coordinates (output)
* @param y :: Vector of y coordinates (output)
* @param err :: Optional pointer to a vector of errors (output)
*/
void InstrumentWindowPickTab::prepareDataForSinglePlot(
int detid,
std::vector<double>&x,
std::vector<double>&y,
std::vector<double>* err)
{
InstrumentActor* instrActor = m_instrWindow->getInstrumentActor();
Mantid::API::MatrixWorkspace_const_sptr ws = instrActor->getWorkspace();
size_t wi;
try {
wi = instrActor->getWorkspaceIndex(detid);
} catch (Mantid::Kernel::Exception::NotFoundError &) {
return; // Detector doesn't have a workspace index relating to it
}
// get the data
const Mantid::MantidVec& X = ws->readX(wi);
const Mantid::MantidVec& Y = ws->readY(wi);
const Mantid::MantidVec& E = ws->readE(wi);
// find min and max for x
size_t imin,imax;
instrActor->getBinMinMaxIndex(wi,imin,imax);
x.assign(X.begin() + imin,X.begin() + imax);
y.assign(Y.begin() + imin,Y.begin() + imax);
if ( ws->isHistogramData() )
{
// calculate the bin centres
std::transform(x.begin(),x.end(),X.begin() + imin + 1,x.begin(),std::plus<double>());
std::transform(x.begin(),x.end(),x.begin(),std::bind2nd(std::divides<double>(),2.0));
}
if (err)
{
err->assign(E.begin() + imin,E.begin() + imax);
}
}
/**
* Prepare data for plotting accumulated data in a tube against time of flight.
* @param detid :: A detector id. The miniplot will display data for a component containing the detector
* with this id.
* @param x :: Vector of x coordinates (output)
* @param y :: Vector of y coordinates (output)
* @param err :: Optional pointer to a vector of errors (output)
*/
void InstrumentWindowPickTab::prepareDataForSumsPlot(
int detid,
std::vector<double>&x,
std::vector<double>&y,
std::vector<double>* err)
{
InstrumentActor* instrActor = m_instrWindow->getInstrumentActor();
Mantid::API::MatrixWorkspace_const_sptr ws = instrActor->getWorkspace();
Mantid::Geometry::IDetector_const_sptr det = instrActor->getInstrument()->getDetector(detid);
boost::shared_ptr<const Mantid::Geometry::IComponent> parent = det->getParent();
Mantid::Geometry::ICompAssembly_const_sptr ass = boost::dynamic_pointer_cast<const Mantid::Geometry::ICompAssembly>(parent);
size_t wi;
try {
wi = instrActor->getWorkspaceIndex(detid);
} catch (Mantid::Kernel::Exception::NotFoundError &) {
return; // Detector doesn't have a workspace index relating to it
}
size_t imin,imax;
instrActor->getBinMinMaxIndex(wi,imin,imax);
const Mantid::MantidVec& X = ws->readX(wi);
x.assign(X.begin() + imin, X.begin() + imax);
if ( ws->isHistogramData() )
{
// calculate the bin centres
std::transform(x.begin(),x.end(),X.begin() + imin + 1,x.begin(),std::plus<double>());
std::transform(x.begin(),x.end(),x.begin(),std::bind2nd(std::divides<double>(),2.0));
}
y.resize(x.size(),0);
if (err)
{
err->resize(x.size(),0);
}
const int n = ass->nelements();
for(int i = 0; i < n; ++i)
{
Mantid::Geometry::IDetector_sptr idet = boost::dynamic_pointer_cast<Mantid::Geometry::IDetector>((*ass)[i]);
if (idet)
{
try {
size_t index = instrActor->getWorkspaceIndex(idet->getID());
const Mantid::MantidVec& Y = ws->readY(index);
std::transform(y.begin(),y.end(),Y.begin() + imin,y.begin(),std::plus<double>());