-
Notifications
You must be signed in to change notification settings - Fork 122
/
MatrixWorkspace.cpp
1672 lines (1464 loc) · 63.2 KB
/
MatrixWorkspace.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 "MantidAPI/MatrixWorkspace.h"
#include "MantidAPI/NumericAxis.h"
#include "MantidAPI/SpectraAxis.h"
#include "MantidAPI/MatrixWorkspaceMDIterator.h"
#include "MantidAPI/SpectrumDetectorMapping.h"
#include "MantidGeometry/Instrument/Detector.h"
#include "MantidGeometry/Instrument/DetectorGroup.h"
#include "MantidGeometry/Instrument/NearestNeighboursFactory.h"
#include "MantidGeometry/Instrument/ReferenceFrame.h"
#include "MantidKernel/TimeSeriesProperty.h"
#include <numeric>
#include <boost/math/special_functions/fpclassify.hpp>
using Mantid::Kernel::DateAndTime;
using Mantid::Kernel::TimeSeriesProperty;
using NeXus::NXcompression;
using Mantid::Kernel::Strings::toString;
namespace Mantid
{
namespace API
{
using std::size_t;
using namespace Geometry;
using Kernel::V3D;
Kernel::Logger& MatrixWorkspace::g_log = Kernel::Logger::get("MatrixWorkspace");
const std::string MatrixWorkspace::xDimensionId = "xDimension";
const std::string MatrixWorkspace::yDimensionId = "yDimension";
/// Default constructor
MatrixWorkspace::MatrixWorkspace(Mantid::Geometry::INearestNeighboursFactory* nnFactory) :
IMDWorkspace(), ExperimentInfo(),
m_axes(), m_isInitialized(false),
m_YUnit(), m_YUnitLabel(), m_isDistribution(false),
m_masks(), m_indexCalculator(),
m_nearestNeighboursFactory((nnFactory == NULL) ? new NearestNeighboursFactory : nnFactory),
m_nearestNeighbours()
{
}
/// Destructor
// RJT, 3/10/07: The Analysis Data Service needs to be able to delete workspaces, so I moved this from protected to public.
MatrixWorkspace::~MatrixWorkspace()
{
for (unsigned int i = 0; i < m_axes.size(); ++i)
{
delete m_axes[i];
}
}
/// @returns A human-readable string of the current state
const std::string MatrixWorkspace::toString() const
{
std::ostringstream os;
os << id() << "\n"
<< "Title: " << getTitle() << "\n"
<< "Histograms: " << getNumberHistograms() << "\n"
<< "Bins: " << blocksize() << "\n";
if ( isHistogramData() ) os << "Histogram\n";
else os << "Data points\n";
os << "X axis: ";
if (axes() > 0 )
{
Axis *ax = getAxis(0);
if ( ax && ax->unit() ) os << ax->unit()->caption() << " / " << ax->unit()->label();
else os << "Not set";
}
else
{
os << "N/A";
}
os << "\n"
<< "Y axis: " << YUnitLabel() << "\n";
os << ExperimentInfo::toString();
return os.str();
}
/** Initialize the workspace. Calls the protected init() method, which is implemented in each type of
* workspace. Returns immediately if the workspace is already initialized.
* @param NVectors :: The number of spectra in the workspace (only relevant for a 2D workspace
* @param XLength :: The number of X data points/bin boundaries in each vector (must all be the same)
* @param YLength :: The number of data/error points in each vector (must all be the same)
*/
void MatrixWorkspace::initialize(const std::size_t &NVectors, const std::size_t &XLength, const std::size_t &YLength)
{
// Check validity of arguments
if (NVectors == 0 || XLength == 0 || YLength == 0)
{
g_log.error("All arguments to init must be positive and non-zero");
throw std::out_of_range("All arguments to init must be positive and non-zero");
}
// Bypass the initialization if the workspace has already been initialized.
if (m_isInitialized) return;
// Invoke init() method of the derived class inside a try/catch clause
try
{
this->init(NVectors, XLength, YLength);
}
catch(std::runtime_error& ex)
{
g_log.error() << "Error initializing the workspace" << ex.what() << std::endl;
throw;
}
m_indexCalculator = MatrixWSIndexCalculator(this->blocksize());
// Indicate that this workspace has been initialized to prevent duplicate attempts.
m_isInitialized = true;
}
//---------------------------------------------------------------------------------------
/** Set the title of the workspace
*
* @param t :: The title
*/
void MatrixWorkspace::setTitle(const std::string& t)
{
Workspace::setTitle(t);
// A MatrixWorkspace contains uniquely one Run object, hence for this workspace
// keep the Run object run_title property the same as the workspace title
Run& run = mutableRun();
run.addProperty("run_title",t, true);
}
//---------------------------------------------------------------------------------------
/** Get the workspace title
*
* @return The title
*/
const std::string MatrixWorkspace::getTitle() const
{
if ( run().hasProperty("run_title") )
{
std::string title = run().getProperty("run_title")->value();
return title;
}
else
return Workspace::getTitle();
}
void MatrixWorkspace::updateSpectraUsing(const SpectrumDetectorMapping& map)
{
for ( size_t j = 0; j < getNumberHistograms(); ++j )
{
auto spec = getSpectrum(j);
try {
spec->setDetectorIDs(map.getDetectorIDsForSpectrumNo(spec->getSpectrumNo()));
} catch (std::out_of_range& e) {
// Get here if the spectrum number is not in the map.
spec->clearDetectorIDs();
g_log.debug(e.what());
g_log.debug() << "Spectrum number " << spec->getSpectrumNo() << " not in map.\n";
}
}
}
//---------------------------------------------------------------------------------------
/**
* Rebuild the default spectra mapping for a workspace. If a non-empty
* instrument is set then the default maps each detector to a spectra with
* the same ID. If an empty instrument is set then a 1:1 map from 1->NHistograms
* is created.
* @param includeMonitors :: If false the monitors are not included
*/
void MatrixWorkspace::rebuildSpectraMapping(const bool includeMonitors)
{
if( sptr_instrument->nelements() == 0 )
{
return;
}
std::vector<detid_t> pixelIDs = this->getInstrument()->getDetectorIDs(!includeMonitors);
try
{
size_t index = 0;
std::vector<detid_t>::const_iterator iend = pixelIDs.end();
for( std::vector<detid_t>::const_iterator it = pixelIDs.begin();
it != iend; ++it )
{
// The detector ID
const detid_t detId = *it;
// By default: Spectrum number = index + 1
const specid_t specNo = specid_t(index + 1);
if (index < this->getNumberHistograms())
{
ISpectrum * spec = getSpectrum(index);
spec->setSpectrumNo(specNo);
spec->setDetectorID(detId);
}
index++;
}
m_nearestNeighbours.reset();
}
catch (std::runtime_error & e)
{
g_log.error() << "MatrixWorkspace::rebuildSpectraMapping() error:" << std::endl;
throw &e;
}
}
//---------------------------------------------------------------------------------------
/**
* Handles the building of the NearestNeighbours object, if it has not already been
* populated for this parameter map.
* @param ignoreMaskedDetectors :: flag indicating that masked detectors should be ignored. True to ignore detectors.
*/
void MatrixWorkspace::buildNearestNeighbours(const bool ignoreMaskedDetectors) const
{
if ( !m_nearestNeighbours )
{
boost::shared_ptr<const Instrument> inst = this->getInstrument();
if ( inst )
{
SpectrumDetectorMapping spectraMap(this);
m_nearestNeighbours.reset(m_nearestNeighboursFactory->create(inst, spectraMap.getMapping(), ignoreMaskedDetectors));
}
else
{
throw Mantid::Kernel::Exception::NullPointerException("ParameterMap: buildNearestNeighbours. Can't obtain instrument.", "instrument");
}
}
}
/*
Allow the NearestNeighbours list to be cleaned and rebuilt. Certain algorithms require this in order to exclude/include
detectors from previously being considered.
*/
void MatrixWorkspace::rebuildNearestNeighbours()
{
/*m_nearestNeighbours should now be NULL. This will trigger rebuilding on subsequent first call to getNeighbours
,which peforms a lazy evaluation on the nearest neighbours map */
m_nearestNeighbours.reset();
}
//---------------------------------------------------------------------------------------
/** Queries the NearestNeighbours object for the selected detector.
* NOTE! getNeighbours(spectrumNumber, radius) is MUCH faster.
*
* @param comp :: pointer to the querying detector
* @param radius :: distance from detector on which to filter results
* @param ignoreMaskedDetectors :: flag indicating that masked detectors should be ignored. True to ignore detectors.
* @return map of DetectorID to distance for the nearest neighbours
*/
std::map<specid_t, V3D> MatrixWorkspace::getNeighbours(const Geometry::IDetector *comp, const double radius, const bool ignoreMaskedDetectors) const
{
if ( !m_nearestNeighbours )
{
buildNearestNeighbours(ignoreMaskedDetectors);
}
// Find the spectrum number
std::vector<specid_t> spectra;
this->getSpectraFromDetectorIDs(std::vector<detid_t>(1, comp->getID()), spectra);
if(spectra.empty())
{
throw Kernel::Exception::NotFoundError("MatrixWorkspace::getNeighbours - Cannot find spectrum number for detector", comp->getID());
}
std::map<specid_t, V3D> neighbours = m_nearestNeighbours->neighboursInRadius(spectra[0], radius);
return neighbours;
}
//---------------------------------------------------------------------------------------
/** Queries the NearestNeighbours object for the selected spectrum number.
*
* @param spec :: spectrum number of the detector you are looking at
* @param radius :: distance from detector on which to filter results
* @param ignoreMaskedDetectors :: flag indicating that masked detectors should be ignored. True to ignore detectors.
* @return map of DetectorID to distance for the nearest neighbours
*/
std::map<specid_t, V3D> MatrixWorkspace::getNeighbours(specid_t spec, const double radius, bool ignoreMaskedDetectors) const
{
if ( !m_nearestNeighbours )
{
buildNearestNeighbours(ignoreMaskedDetectors);
}
std::map<specid_t, V3D> neighbours = m_nearestNeighbours->neighboursInRadius(spec, radius);
return neighbours;
}
//---------------------------------------------------------------------------------------
/** Queries the NearestNeighbours object for the selected spectrum number.
*
* @param spec :: spectrum number of the detector you are looking at
* @param nNeighbours :: unsigned int, number of neighbours to include.
* @param ignoreMaskedDetectors :: flag indicating that masked detectors should be ignored. True to ignore detectors.
* @return map of DetectorID to distance for the nearest neighbours
*/
std::map<specid_t, V3D> MatrixWorkspace::getNeighboursExact(specid_t spec, const int nNeighbours, bool ignoreMaskedDetectors) const
{
if ( !m_nearestNeighbours )
{
SpectrumDetectorMapping spectraMap(this);
m_nearestNeighbours.reset(m_nearestNeighboursFactory->create(nNeighbours, this->getInstrument(), spectraMap.getMapping(), ignoreMaskedDetectors));
}
std::map<specid_t, V3D> neighbours = m_nearestNeighbours->neighbours(spec);
return neighbours;
}
//---------------------------------------------------------------------------------------
/** Return a map where:
* KEY is the Spectrum #
* VALUE is the Workspace Index
*/
spec2index_map MatrixWorkspace::getSpectrumToWorkspaceIndexMap() const
{
SpectraAxis * ax = dynamic_cast<SpectraAxis * >( this->m_axes[1] );
if (!ax)
throw std::runtime_error("MatrixWorkspace::getSpectrumToWorkspaceIndexMap: axis[1] is not a SpectraAxis, so I cannot generate a map.");
spec2index_map map;
try
{
ax->getSpectraIndexMap(map);
}
catch (std::runtime_error &)
{
throw std::runtime_error("MatrixWorkspace::getSpectrumToWorkspaceIndexMap: no elements!");
}
return map;
}
//---------------------------------------------------------------------------------------
/** Return a vector where:
* The index into the vector = spectrum number + offset
* The value at that index = the corresponding Workspace Index
*
* @param out :: vector set to above definition
* @param offset :: add this to the detector ID to get the index into the vector.
*/
void MatrixWorkspace::getSpectrumToWorkspaceIndexVector(std::vector<size_t> & out, specid_t & offset) const
{
SpectraAxis * ax = dynamic_cast<SpectraAxis * >( this->m_axes[1] );
if (!ax)
throw std::runtime_error("MatrixWorkspace::getSpectrumToWorkspaceIndexMap: axis[1] is not a SpectraAxis, so I cannot generate a map.");
// Find the min/max spectra IDs
specid_t min = std::numeric_limits<specid_t>::max(); // So that any number will be less than this
specid_t max = -std::numeric_limits<specid_t>::max(); // So that any number will be greater than this
size_t length = ax->length();
for (size_t i=0; i < length; i++)
{
specid_t spec = ax->spectraNo(i);
if (spec < min) min = spec;
if (spec > max) max = spec;
}
// Offset so that the "min" value goes to index 0
offset = -min;
// Resize correctly
out.resize(max-min+1, 0);
// Make the vector
for (size_t i=0; i < length; i++)
{
specid_t spec = ax->spectraNo(i);
out[spec+offset] = i;
}
}
//---------------------------------------------------------------------------------------
/** Does the workspace has any grouped detectors?
* @return true if the workspace has any grouped detectors, otherwise false
*/
bool MatrixWorkspace::hasGroupedDetectors() const
{
bool retVal = false;
//Loop through the workspace index
for (size_t workspaceIndex=0; workspaceIndex < this->getNumberHistograms(); workspaceIndex++)
{
auto detList = getSpectrum(workspaceIndex)->getDetectorIDs();
if (detList.size() > 1)
{
retVal=true;
break;
}
}
return retVal;
}
//---------------------------------------------------------------------------------------
/** Return a map where:
* KEY is the DetectorID (pixel ID)
* VALUE is the Workspace Index
* @param throwIfMultipleDets :: set to true to make the algorithm throw an error
* if there is more than one detector for a specific workspace index.
* @throw runtime_error if there is more than one detector per spectrum (if throwIfMultipleDets is true)
* @return Index to Index Map object. THE CALLER TAKES OWNERSHIP OF THE MAP AND IS RESPONSIBLE FOR ITS DELETION.
*/
detid2index_map MatrixWorkspace::getDetectorIDToWorkspaceIndexMap( bool throwIfMultipleDets ) const
{
detid2index_map map;
//Loop through the workspace index
for (size_t workspaceIndex=0; workspaceIndex < this->getNumberHistograms(); ++workspaceIndex)
{
auto detList = getSpectrum(workspaceIndex)->getDetectorIDs();
if (throwIfMultipleDets)
{
if (detList.size() > 1)
{
throw std::runtime_error("MatrixWorkspace::getDetectorIDToWorkspaceIndexMap(): more than 1 detector for one histogram! I cannot generate a map of detector ID to workspace index.");
}
//Set the KEY to the detector ID and the VALUE to the workspace index.
if (detList.size() == 1)
map[ *detList.begin() ] = workspaceIndex;
}
else
{
//Allow multiple detectors per workspace index
for (auto it = detList.begin(); it != detList.end(); ++it)
map[ *it ] = workspaceIndex;
}
//Ignore if the detector list is empty.
}
return map;
}
//---------------------------------------------------------------------------------------
/** Return a vector where:
* The index into the vector = DetectorID (pixel ID) + offset
* The value at that index = the corresponding Workspace Index
*
* @param out :: vector set to above definition
* @param offset :: add this to the detector ID to get the index into the vector.
* @param throwIfMultipleDets :: set to true to make the algorithm throw an error
* if there is more than one detector for a specific workspace index.
* @throw runtime_error if there is more than one detector per spectrum (if throwIfMultipleDets is true)
*/
void MatrixWorkspace::getDetectorIDToWorkspaceIndexVector( std::vector<size_t> & out, detid_t & offset, bool throwIfMultipleDets) const
{
// Make a correct initial size
out.clear();
detid_t minId = 0;
detid_t maxId = 0;
this->getInstrument()->getMinMaxDetectorIDs(minId, maxId);
offset = -minId;
const int outSize = maxId - minId + 1;
// Allocate at once
out.resize(outSize, std::numeric_limits<size_t>::max());
for (size_t workspaceIndex=0; workspaceIndex < getNumberHistograms(); ++workspaceIndex)
{
//Get the list of detectors from the WS index
const std::set<detid_t> & detList = this->getSpectrum(workspaceIndex)->getDetectorIDs();
if (throwIfMultipleDets && (detList.size() > 1))
throw std::runtime_error("MatrixWorkspace::getDetectorIDToWorkspaceIndexVector(): more than 1 detector for one histogram! I cannot generate a map of detector ID to workspace index.");
// Allow multiple detectors per workspace index, or,
// If only one is allowed, then this has thrown already
for (std::set<detid_t>::const_iterator it = detList.begin(); it != detList.end(); ++it)
{
int index = *it + offset;
if (index < 0 || index >= outSize)
{
g_log.debug() << "MatrixWorkspace::getDetectorIDToWorkspaceIndexVector(): detector ID found (" << *it << " at workspace index " << workspaceIndex << ") is invalid." << std::endl;
}
else
// Save it at that point.
out[index] = workspaceIndex;
}
} // (for each workspace index)
}
//---------------------------------------------------------------------------------------
/** Converts a list of spectrum numbers to the corresponding workspace indices.
* Not a very efficient operation, but unfortunately it's sometimes required.
*
* @param spectraList :: The list of spectrum numbers required
* @param indexList :: Returns a reference to the vector of indices (empty if not a Workspace2D)
*/
void MatrixWorkspace::getIndicesFromSpectra(const std::vector<specid_t>& spectraList, std::vector<size_t>& indexList) const
{
// Clear the output index list
indexList.clear();
indexList.reserve(this->getNumberHistograms());
std::vector<specid_t>::const_iterator iter = spectraList.begin();
while( iter != spectraList.end() )
{
for (size_t i = 0; i < this->getNumberHistograms(); ++i)
{
if ( this->getSpectrum(i)->getSpectrumNo() == *iter )
{
indexList.push_back(i);
break;
}
}
++iter;
}
}
//---------------------------------------------------------------------------------------
/** Given a spectrum number, find the corresponding workspace index
*
* @param specNo :: spectrum number wanted
* @return the workspace index
* @throw runtime_error if not found.
*/
size_t MatrixWorkspace::getIndexFromSpectrumNumber(const specid_t specNo) const
{
for (size_t i = 0; i < this->getNumberHistograms(); ++i)
{
if ( this->getSpectrum(i)->getSpectrumNo() == specNo )
return i;
}
throw std::runtime_error("Could not find spectrum number in any spectrum.");
}
//---------------------------------------------------------------------------------------
/** Converts a list of detector IDs to the corresponding workspace indices.
*
* @param detIdList :: The list of detector IDs required
* @param indexList :: Returns a reference to the vector of indices
*/
void MatrixWorkspace::getIndicesFromDetectorIDs(const std::vector<detid_t>& detIdList, std::vector<size_t>& indexList) const
{
std::map<detid_t,std::set<size_t>> detectorIDtoWSIndices;
for ( size_t i = 0; i < getNumberHistograms(); ++i )
{
auto detIDs = getSpectrum(i)->getDetectorIDs();
for ( auto it = detIDs.begin(); it != detIDs.end(); ++it)
{
detectorIDtoWSIndices[*it].insert(i);
}
}
indexList.clear();
indexList.reserve(detIdList.size());
for ( size_t j = 0; j < detIdList.size(); ++j )
{
auto wsIndices = detectorIDtoWSIndices.find(detIdList[j]);
if ( wsIndices != detectorIDtoWSIndices.end() )
{
for ( auto it = wsIndices->second.begin(); it != wsIndices->second.end(); ++it )
{
indexList.push_back(*it);
}
}
}
}
//---------------------------------------------------------------------------------------
/** Converts a list of detector IDs to the corresponding spectrum numbers. Might be slow!
*
* @param detIdList :: The list of detector IDs required
* @param spectraList :: Returns a reference to the vector of spectrum numbers.
* 0 for not-found detectors
*/
void MatrixWorkspace::getSpectraFromDetectorIDs(const std::vector<detid_t>& detIdList, std::vector<specid_t>& spectraList) const
{
std::vector<detid_t>::const_iterator it_start = detIdList.begin();
std::vector<detid_t>::const_iterator it_end = detIdList.end();
spectraList.clear();
// Try every detector in the list
std::vector<detid_t>::const_iterator it;
for (it = it_start; it != it_end; ++it)
{
bool foundDet = false;
specid_t foundSpecNum = 0;
// Go through every histogram
for (size_t i=0; i<this->getNumberHistograms(); i++)
{
if (this->getSpectrum(i)->hasDetectorID(*it))
{
foundDet = true;
foundSpecNum = this->getSpectrum(i)->getSpectrumNo();
break;
}
}
if (foundDet)
spectraList.push_back(foundSpecNum);
} // for each detector ID in the list
}
double MatrixWorkspace::getXMin() const
{
double xmin;
double xmax;
this->getXMinMax(xmin, xmax); // delegate to the proper code
return xmin;
}
double MatrixWorkspace::getXMax() const
{
double xmin;
double xmax;
this->getXMinMax(xmin, xmax); // delegate to the proper code
return xmax;
}
void MatrixWorkspace::getXMinMax(double &xmin, double &xmax) const
{
// set to crazy values to start
xmin = std::numeric_limits<double>::max();
xmax = -1.0 * xmin;
size_t numberOfSpectra = this->getNumberHistograms();
// determine the data range
for (size_t workspaceIndex = 0; workspaceIndex < numberOfSpectra; workspaceIndex++)
{
const MantidVec& dataX = this->readX(workspaceIndex);
const double xfront = dataX.front();
const double xback = dataX.back();
if (boost::math::isfinite(xfront) && boost::math::isfinite(xback))
{
if (xfront < xmin)
xmin = xfront;
if (xback > xmax)
xmax = xback;
}
}
}
//---------------------------------------------------------------------------------------
/** Integrate all the spectra in the matrix workspace within the range given.
* Default implementation, can be overridden by base classes if they know something smarter!
*
* @param out :: returns the vector where there is one entry per spectrum in the workspace. Same
* order as the workspace indices.
* @param minX :: minimum X bin to use in integrating.
* @param maxX :: maximum X bin to use in integrating.
* @param entireRange :: set to true to use the entire range. minX and maxX are then ignored!
*/
void MatrixWorkspace::getIntegratedSpectra(std::vector<double> & out, const double minX, const double maxX, const bool entireRange) const
{
out.resize(this->getNumberHistograms(), 0.0);
//Run in parallel if the implementation is threadsafe
PARALLEL_FOR_IF( this->threadSafe() )
for (int wksp_index = 0; wksp_index < static_cast<int>(this->getNumberHistograms()); wksp_index++)
{
// Get Handle to data
const Mantid::MantidVec& x=this->readX(wksp_index);
const Mantid::MantidVec& y=this->readY(wksp_index);
// If it is a 1D workspace, no need to integrate
if ((x.size()<=2) && (y.size() >= 1))
{
out[wksp_index] = y[0];
}
else
{
// Iterators for limits - whole range by default
Mantid::MantidVec::const_iterator lowit, highit;
lowit=x.begin();
highit=x.end()-1;
//But maybe we don't want the entire range?
if (!entireRange)
{
// If the first element is lower that the xmin then search for new lowit
if ((*lowit) < minX)
lowit = std::lower_bound(x.begin(),x.end(),minX);
// If the last element is higher that the xmax then search for new lowit
if ((*highit) > maxX)
highit = std::upper_bound(lowit,x.end(),maxX);
}
// Get the range for the y vector
Mantid::MantidVec::difference_type distmin = std::distance(x.begin(), lowit);
Mantid::MantidVec::difference_type distmax = std::distance(x.begin(), highit);
double sum(0.0);
if( distmin <= distmax )
{
// Integrate
sum = std::accumulate(y.begin() + distmin,y.begin() + distmax,0.0);
}
//Save it in the vector
out[wksp_index] = sum;
}
}
}
/** Get the effective detector for the given spectrum
* @param workspaceIndex The workspace index for which the detector is required
* @return A single detector object representing the detector(s) contributing
* to the given spectrum number. If more than one detector contributes then
* the returned object's concrete type will be DetectorGroup.
* @throw Kernel::Exception::NotFoundError If the Instrument is missing or the
requested workspace index does not have any associated detectors
*/
Geometry::IDetector_const_sptr MatrixWorkspace::getDetector(const size_t workspaceIndex) const
{
const ISpectrum * spec = this->getSpectrum(workspaceIndex);
if (!spec)
throw Kernel::Exception::NotFoundError("MatrixWorkspace::getDetector(): NULL spectrum found at the given workspace index.", "");
const std::set<detid_t> & dets = spec->getDetectorIDs();
Instrument_const_sptr localInstrument = getInstrument();
if( !localInstrument )
{
g_log.debug() << "No instrument defined.\n";
throw Kernel::Exception::NotFoundError("Instrument not found", "");
}
const size_t ndets = dets.size();
if ( ndets == 1 )
{
// If only 1 detector for the spectrum number, just return it
return localInstrument->getDetector(*dets.begin());
}
else if (ndets==0)
{
throw Kernel::Exception::NotFoundError("MatrixWorkspace::getDetector(): No detectors for this workspace index.", "");
}
// Else need to construct a DetectorGroup and return that
std::vector<Geometry::IDetector_const_sptr> dets_ptr = localInstrument->getDetectors(dets);
return Geometry::IDetector_const_sptr( new Geometry::DetectorGroup(dets_ptr, false) );
}
/** Returns the signed 2Theta scattering angle for a detector
* @param det :: A pointer to the detector object (N.B. might be a DetectorGroup)
* @return The scattering angle (0 < theta < pi)
* @throws InstrumentDefinitionError if source or sample is missing, or they are in the same place
*/
double MatrixWorkspace::detectorSignedTwoTheta(Geometry::IDetector_const_sptr det) const
{
Instrument_const_sptr instrument = getInstrument();
Geometry::IComponent_const_sptr source = instrument->getSource();
Geometry::IComponent_const_sptr sample = instrument->getSample();
if ( source == NULL || sample == NULL )
{
throw Kernel::Exception::InstrumentDefinitionError("Instrument not sufficiently defined: failed to get source and/or sample");
}
const Kernel::V3D samplePos = sample->getPos();
const Kernel::V3D beamLine = samplePos - source->getPos();
if ( beamLine.nullVector() )
{
throw Kernel::Exception::InstrumentDefinitionError("Source and sample are at same position!");
}
//Get the instrument up axis.
const V3D& instrumentUpAxis = instrument->getReferenceFrame()->vecPointingUp();
return det->getSignedTwoTheta(samplePos,beamLine, instrumentUpAxis);
}
/** Returns the 2Theta scattering angle for a detector
* @param det :: A pointer to the detector object (N.B. might be a DetectorGroup)
* @return The scattering angle (0 < theta < pi)
* @throws InstrumentDefinitionError if source or sample is missing, or they are in the same place
*/
double MatrixWorkspace::detectorTwoTheta(Geometry::IDetector_const_sptr det) const
{
Geometry::IComponent_const_sptr source = getInstrument()->getSource();
Geometry::IComponent_const_sptr sample = getInstrument()->getSample();
if ( source == NULL || sample == NULL )
{
throw Kernel::Exception::InstrumentDefinitionError("Instrument not sufficiently defined: failed to get source and/or sample");
}
const Kernel::V3D samplePos = sample->getPos();
const Kernel::V3D beamLine = samplePos - source->getPos();
if ( beamLine.nullVector() )
{
throw Kernel::Exception::InstrumentDefinitionError("Source and sample are at same position!");
}
return det->getTwoTheta(samplePos,beamLine);
}
/**Calculates the distance a neutron coming from the sample will have deviated from a
* straight tragetory before hitting a detector. If calling this function many times
* for the same detector you can call this function once, with waveLength=1, and use
* the fact drop is proportional to wave length squared .This function has no knowledge
* of which axis is vertical for a given instrument
* @param det :: the detector that the neutron entered
* @param waveLength :: the neutrons wave length in meters
* @return the deviation in meters
*/
double MatrixWorkspace::gravitationalDrop(Geometry::IDetector_const_sptr det, const double waveLength) const
{
using namespace PhysicalConstants;
/// Pre-factor in gravity calculation: gm^2/2h^2
static const double gm2_OVER_2h2 = g*NeutronMass*NeutronMass/( 2.0*h*h );
const V3D samplePos = getInstrument()->getSample()->getPos();
const double pathLength = det->getPos().distance(samplePos);
// Want L2 (sample-pixel distance) squared, times the prefactor g^2/h^2
const double L2 = gm2_OVER_2h2*std::pow(pathLength,2);
return waveLength*waveLength*L2;
}
//---------------------------------------------------------------------------------------
/** Add parameters to the instrument parameter map that are defined in instrument
* definition file and for which logfile data are available. Logs must be loaded
* before running this method.
*/
void MatrixWorkspace::populateInstrumentParameters()
{
ExperimentInfo::populateInstrumentParameters();
// Clear out the nearestNeighbors so that it gets recalculated
this->m_nearestNeighbours.reset();
}
//----------------------------------------------------------------------------------------------------
/// @return The number of axes which this workspace has
int MatrixWorkspace::axes() const
{
return static_cast<int>(m_axes.size());
}
//----------------------------------------------------------------------------------------------------
/** Get a pointer to a workspace axis
* @param axisIndex :: The index of the axis required
* @throw IndexError If the argument given is outside the range of axes held by this workspace
* @return Pointer to Axis object
*/
Axis* MatrixWorkspace::getAxis(const std::size_t& axisIndex) const
{
if ( axisIndex >= m_axes.size() )
{
g_log.error() << "Argument to getAxis (" << axisIndex << ") is invalid for this (" << m_axes.size() << " axis) workspace" << std::endl;
throw Kernel::Exception::IndexError(axisIndex, m_axes.size(),"Argument to getAxis is invalid for this workspace");
}
return m_axes[axisIndex];
}
/** Replaces one of the workspace's axes with the new one provided.
* @param axisIndex :: The index of the axis to replace
* @param newAxis :: A pointer to the new axis. The class will take ownership.
* @throw IndexError If the axisIndex given is outside the range of axes held by this workspace
* @throw std::runtime_error If the new axis is not of the correct length (within one of the old one)
*/
void MatrixWorkspace::replaceAxis(const std::size_t& axisIndex, Axis* const newAxis)
{
// First check that axisIndex is in range
if ( axisIndex >= m_axes.size() )
{
g_log.error() << "Value of axisIndex (" << axisIndex << ") is invalid for this (" << m_axes.size() << " axis) workspace" << std::endl;
throw Kernel::Exception::IndexError(axisIndex, m_axes.size(),"Value of axisIndex is invalid for this workspace");
}
// If we're OK, then delete the old axis and set the pointer to the new one
delete m_axes[axisIndex];
m_axes[axisIndex] = newAxis;
}
//----------------------------------------------------------------------------------------------------
/// Returns the units of the data in the workspace
std::string MatrixWorkspace::YUnit() const
{
return m_YUnit;
}
/// Sets a new unit for the data (Y axis) in the workspace
void MatrixWorkspace::setYUnit(const std::string& newUnit)
{
m_YUnit = newUnit;
}
/// Returns a caption for the units of the data in the workspace
std::string MatrixWorkspace::YUnitLabel() const
{
std::string retVal;
if ( !m_YUnitLabel.empty() ) retVal = m_YUnitLabel;
else
{
retVal = m_YUnit;
// If this workspace a distribution & has at least one axis & this axis has its unit set
// then append that unit to the string to be returned
if ( !retVal.empty() && this->isDistribution() && this->axes() && this->getAxis(0)->unit() )
{
retVal = retVal + " per " + this->getAxis(0)->unit()->label();
}
}
return retVal;
}
/// Sets a new caption for the data (Y axis) in the workspace
void MatrixWorkspace::setYUnitLabel(const std::string& newLabel)
{
m_YUnitLabel = newLabel;
}
//----------------------------------------------------------------------------------------------------
/** Are the Y-values in this workspace dimensioned?
* TODO: For example: ????
* @return whether workspace is a distribution or not
*/
const bool& MatrixWorkspace::isDistribution() const
{
return m_isDistribution;
}
/** Set the flag for whether the Y-values are dimensioned
* @return whether workspace is now a distribution
*/
bool& MatrixWorkspace::isDistribution(bool newValue)
{
m_isDistribution = newValue;
return m_isDistribution;
}
/**
* Whether the workspace contains histogram data
* @return whether the worksapace contains histogram data
*/
bool MatrixWorkspace::isHistogramData() const
{
return ( readX(0).size()==blocksize() ? false : true );
}
//----------------------------------------------------------------------------------------------------
/**
* Mask a given workspace index, setting the data and error values to zero
* @param index :: The index within the workspace to mask
*/
void MatrixWorkspace::maskWorkspaceIndex(const std::size_t index)
{
if( index >= this->getNumberHistograms() )
{
throw Kernel::Exception::IndexError(index,this->getNumberHistograms(),
"MatrixWorkspace::maskWorkspaceIndex,index");
}
ISpectrum * spec = this->getSpectrum(index);
if (!spec) throw std::invalid_argument("MatrixWorkspace::maskWorkspaceIndex() got a null Spectrum.");
// Virtual method clears the spectrum as appropriate
spec->clearData();
const std::set<detid_t> dets = spec->getDetectorIDs();
for (std::set<detid_t>::const_iterator iter=dets.begin(); iter != dets.end(); ++iter)
{
try
{
if ( const Geometry::Detector* det = dynamic_cast<const Geometry::Detector*>(sptr_instrument->getDetector(*iter).get()) )
{
m_parmap->addBool(det,"masked",true); // Thread-safe method
}
}
catch(Kernel::Exception::NotFoundError &)
{
}
}
//If masking has occured, the NearestNeighbours map will be out of date must be rebuilt.
this->rebuildNearestNeighbours();
}
//----------------------------------------------------------------------------------------------------
/** Called by the algorithm MaskBins to mask a single bin for the first time, algorithms that later propagate the
* the mask from an input to the output should call flagMasked() instead. Here y-values and errors will be scaled
* by (1-weight) as well as the mask flags (m_masks) being updated. This function doesn't protect the writes to the
* y and e-value arrays and so is not safe if called by multiple threads working on the same spectrum. Writing to
* the mask set is marked parrallel critical so different spectra can be analysised in parallel
* @param workspaceIndex :: The workspace spectrum index of the bin
* @param binIndex :: The index of the bin in the spectrum
* @param weight :: 'How heavily' the bin is to be masked. =1 for full masking (the default).
*/
void MatrixWorkspace::maskBin(const size_t& workspaceIndex, const size_t& binIndex, const double& weight)
{
// First check the workspaceIndex is valid
if (workspaceIndex >= this->getNumberHistograms() )
throw Kernel::Exception::IndexError(workspaceIndex,this->getNumberHistograms(),"MatrixWorkspace::maskBin,workspaceIndex");
// Then check the bin index
if (binIndex>= this->blocksize() )
throw Kernel::Exception::IndexError(binIndex,this->blocksize(),"MatrixWorkspace::maskBin,binIndex");