forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MDHistoWorkspace.cpp
1322 lines (1198 loc) · 49.5 KB
/
MDHistoWorkspace.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
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidDataObjects/MDHistoWorkspace.h"
#include "MantidAPI/IMDIterator.h"
#include "MantidAPI/IMDWorkspace.h"
#include "MantidDataObjects/MDFramesToSpecialCoordinateSystem.h"
#include "MantidDataObjects/MDHistoWorkspaceIterator.h"
#include "MantidGeometry/MDGeometry/IMDDimension.h"
#include "MantidGeometry/MDGeometry/MDDimensionExtents.h"
#include "MantidGeometry/MDGeometry/MDGeometryXMLBuilder.h"
#include "MantidGeometry/MDGeometry/MDHistoDimension.h"
#include "MantidKernel/Utils.h"
#include "MantidKernel/VMD.h"
#include "MantidKernel/WarningSuppressions.h"
#include <boost/optional.hpp>
#include <boost/scoped_array.hpp>
#include <cmath>
#include <map>
#include <memory>
using namespace Mantid::Kernel;
using namespace Mantid::Geometry;
using namespace Mantid::API;
namespace Mantid::DataObjects {
//----------------------------------------------------------------------------------------------
/** Constructor given the 4 dimensions
* @param dimX :: X dimension binning parameters
* @param dimY :: Y dimension binning parameters
* @param dimZ :: Z dimension binning parameters
* @param dimT :: T (time) dimension binning parameters
* @param displayNormalization :: optional display normalization to use as the
* default.
*/
MDHistoWorkspace::MDHistoWorkspace(Mantid::Geometry::MDHistoDimension_sptr dimX,
Mantid::Geometry::MDHistoDimension_sptr dimY,
Mantid::Geometry::MDHistoDimension_sptr dimZ,
Mantid::Geometry::MDHistoDimension_sptr dimT,
Mantid::API::MDNormalization displayNormalization)
: IMDHistoWorkspace(), numDimensions(0), m_nEventsContributed(std::numeric_limits<uint64_t>::quiet_NaN()),
m_coordSystem(None), m_displayNormalization(displayNormalization) {
std::vector<Mantid::Geometry::MDHistoDimension_sptr> dimensions;
if (dimX)
dimensions.emplace_back(std::move(dimX));
if (dimY)
dimensions.emplace_back(std::move(dimY));
if (dimZ)
dimensions.emplace_back(std::move(dimZ));
if (dimT)
dimensions.emplace_back(std::move(dimT));
this->init(dimensions);
}
//----------------------------------------------------------------------------------------------
/** Constructor given a vector of dimensions
* @param dimensions :: vector of MDHistoDimension; no limit to how many.
* @param displayNormalization :: optional display normalization to use as the
* default.
*/
MDHistoWorkspace::MDHistoWorkspace(std::vector<Mantid::Geometry::MDHistoDimension_sptr> &dimensions,
Mantid::API::MDNormalization displayNormalization)
: IMDHistoWorkspace(), numDimensions(0), m_nEventsContributed(std::numeric_limits<uint64_t>::quiet_NaN()),
m_coordSystem(None), m_displayNormalization(displayNormalization) {
this->init(dimensions);
}
//----------------------------------------------------------------------------------------------
/** Constructor given a vector of dimensions
* @param dimensions :: vector of MDHistoDimension; no limit to how many.
* @param displayNormalization :: optional display normalization to use as the
* default.
*/
MDHistoWorkspace::MDHistoWorkspace(std::vector<Mantid::Geometry::IMDDimension_sptr> &dimensions,
Mantid::API::MDNormalization displayNormalization)
: IMDHistoWorkspace(), numDimensions(0), m_nEventsContributed(std::numeric_limits<uint64_t>::quiet_NaN()),
m_coordSystem(None), m_displayNormalization(displayNormalization) {
this->init(dimensions);
}
//----------------------------------------------------------------------------------------------
/** Copy constructor
*
* @param other :: MDHistoWorkspace to copy from.
*/
MDHistoWorkspace::MDHistoWorkspace(const MDHistoWorkspace &other)
: IMDHistoWorkspace(other), m_nEventsContributed(other.m_nEventsContributed), m_coordSystem(other.m_coordSystem),
m_displayNormalization(other.m_displayNormalization) {
// Dimensions are copied by the copy constructor of MDGeometry
this->cacheValues();
// Allocate the linear arrays
m_signals = std::vector<signal_t>(m_length);
m_errorsSquared = std::vector<signal_t>(m_length);
m_numEvents = std::vector<signal_t>(m_length);
m_masks = std::make_unique<bool[]>(m_length);
// Now copy all the data
std::copy_n(other.m_signals.begin(), m_length, m_signals.begin());
std::copy_n(other.m_errorsSquared.begin(), m_length, m_errorsSquared.begin());
std::copy_n(other.m_numEvents.begin(), m_length, m_numEvents.begin());
std::copy_n(other.m_masks.get(), m_length, m_masks.get());
}
//----------------------------------------------------------------------------------------------
/** Constructor helper method
* @param dimensions :: vector of MDHistoDimension; no limit to how many.
*/
void MDHistoWorkspace::init(std::vector<Mantid::Geometry::MDHistoDimension_sptr> &dimensions) {
std::vector<IMDDimension_sptr> dim2;
dim2.reserve(dimensions.size());
std::transform(dimensions.cbegin(), dimensions.cend(), std::back_inserter(dim2),
[](const auto dimension) { return std::dynamic_pointer_cast<IMDDimension>(dimension); });
this->init(dim2);
m_nEventsContributed = 0;
}
//----------------------------------------------------------------------------------------------
/** Constructor helper method
* @param dimensions :: vector of IMDDimension; no limit to how many.
*/
void MDHistoWorkspace::init(std::vector<Mantid::Geometry::IMDDimension_sptr> &dimensions) {
MDGeometry::initGeometry(dimensions);
this->cacheValues();
// Allocate the linear arrays
m_signals = std::vector<signal_t>(m_length);
m_errorsSquared = std::vector<signal_t>(m_length);
m_numEvents = std::vector<signal_t>(m_length);
m_masks = std::make_unique<bool[]>(m_length);
// Initialize them to NAN (quickly)
signal_t nan = std::numeric_limits<signal_t>::quiet_NaN();
this->setTo(nan, nan, nan);
m_nEventsContributed = 0;
}
//----------------------------------------------------------------------------------------------
/** When all dimensions have been initialized, this caches all the necessary
* values for later use.
*/
void MDHistoWorkspace::cacheValues() {
// Copy the dimensions array
numDimensions = m_dimensions.size();
// For indexing.
if (numDimensions < 4)
indexMultiplier = std::vector<size_t>(4);
else
indexMultiplier = std::vector<size_t>(numDimensions);
// For quick indexing, accumulate these values
// First multiplier
indexMultiplier[0] = m_dimensions[0]->getNBins();
for (size_t d = 1; d < numDimensions; d++)
indexMultiplier[d] = indexMultiplier[d - 1] * m_dimensions[d]->getNBins();
// This is how many dense data points
m_length = indexMultiplier[numDimensions - 1];
// Now fix things for < 4 dimensions. Indices > the number of dimensions will
// be ignored (*0)
for (size_t d = numDimensions - 1; d < 4; d++)
indexMultiplier[d] = 0;
// Compute the volume of each cell.
coord_t volume = 1.0;
for (size_t i = 0; i < numDimensions; ++i)
volume *= m_dimensions[i]->getBinWidth();
m_inverseVolume = 1.0f / volume;
// Continue with the vertexes array
this->initVertexesArray();
m_nEventsContributed = 0;
}
//----------------------------------------------------------------------------------------------
/** After initialization, call this to initialize the vertexes array
* to the vertexes of the 0th box.
* Will be used by getVertexesArray()
* */
void MDHistoWorkspace::initVertexesArray() {
size_t nd = numDimensions;
// How many vertices does one box have? 2^nd, or bitwise shift left 1 by nd
// bits
size_t numVertices = size_t{1} << numDimensions;
// Allocate the array of the right size
m_vertexesArray = std::vector<coord_t>(nd * numVertices);
// For each vertex, increase an integeer
for (size_t i = 0; i < numVertices; ++i) {
// Start point index in the output array;
size_t outIndex = i * nd;
// Coordinates of the vertex
for (size_t d = 0; d < nd; d++) {
// Use a bit mask to look at each bit of the integer we are iterating
// through.
size_t mask = size_t{1} << d;
if ((i & mask) > 0) {
// Bit is 1, use the max of the dimension
m_vertexesArray[outIndex + d] = m_dimensions[d]->getX(1);
} else {
// Bit is 0, use the min of the dimension
m_vertexesArray[outIndex + d] = m_dimensions[d]->getX(0);
}
} // (for each dimension)
}
// Now set the m_boxLength and origin
m_boxLength = std::vector<coord_t>(nd);
m_origin = std::vector<coord_t>(nd);
for (size_t d = 0; d < nd; d++) {
m_boxLength[d] = m_dimensions[d]->getX(1) - m_dimensions[d]->getX(0);
m_origin[d] = m_dimensions[d]->getX(0);
}
// The index calculator
m_indexMax = std::vector<size_t>(numDimensions);
for (size_t d = 0; d < nd; d++)
m_indexMax[d] = m_dimensions[d]->getNBins();
m_indexMaker = std::vector<size_t>(numDimensions);
Utils::NestedForLoop::SetUpIndexMaker(numDimensions, m_indexMaker.data(), m_indexMax.data());
}
//----------------------------------------------------------------------------------------------
/** Sets all signals/errors in the workspace to the given values
*
* @param signal :: signal value to set
* @param errorSquared :: error (squared) value to set
* @param numEvents :: the number of events in each bin.
*/
void MDHistoWorkspace::setTo(signal_t signal, signal_t errorSquared, signal_t numEvents) {
std::fill_n(m_signals.begin(), m_length, signal);
std::fill_n(m_errorsSquared.begin(), m_length, errorSquared);
std::fill_n(m_numEvents.begin(), m_length, numEvents);
std::fill_n(m_masks.get(), m_length, false);
m_nEventsContributed = static_cast<uint64_t>(numEvents) * m_length;
}
//----------------------------------------------------------------------------------------------
/** Apply an implicit function to each point; if false, set to the given value.
*
* @param function :: the implicit function to apply
* @param signal :: signal value to set when function evaluates to false
* @param errorSquared :: error value to set when function evaluates to false
*/
void MDHistoWorkspace::applyImplicitFunction(Mantid::Geometry::MDImplicitFunction *function, signal_t signal,
signal_t errorSquared) {
if (numDimensions < 3)
throw std::invalid_argument("Need 3 dimensions for ImplicitFunction.");
Mantid::coord_t coord[3];
for (size_t x = 0; x < m_dimensions[0]->getNBins(); x++) {
coord[0] = m_dimensions[0]->getX(x);
for (size_t y = 0; y < m_dimensions[1]->getNBins(); y++) {
coord[1] = m_dimensions[1]->getX(y);
for (size_t z = 0; z < m_dimensions[2]->getNBins(); z++) {
coord[2] = m_dimensions[2]->getX(z);
if (!function->isPointContained(coord)) {
m_signals[x + indexMultiplier[0] * y + indexMultiplier[1] * z] = signal;
m_errorsSquared[x + indexMultiplier[0] * y + indexMultiplier[1] * z] = errorSquared;
}
}
}
}
}
//----------------------------------------------------------------------------------------------
/** For the volume at the given linear index,
* Return the vertices of every corner of the box, as
* a bare array of length numVertices * nd
*
* @param linearIndex :: index into the workspace. Same as for
*getSignalAt(index)
* @param[out] numVertices :: returns the number of vertices in the array.
* @return the bare array. This should be deleted by the caller!
* */
std::unique_ptr<coord_t[]> MDHistoWorkspace::getVertexesArray(size_t linearIndex, size_t &numVertices) const {
// How many vertices does one box have? 2^nd, or bitwise shift left 1 by nd
// bits
numVertices = static_cast<size_t>(1) << numDimensions; // Cast avoids warning about
// result of 32-bit shift
// implicitly converted to 64 bits
// on MSVC
// Index into each dimension. Built from the linearIndex.
size_t dimIndexes[10];
Utils::NestedForLoop::GetIndicesFromLinearIndex(numDimensions, linearIndex, m_indexMaker.data(), m_indexMax.data(),
dimIndexes);
// The output vertexes coordinates
auto out = std::make_unique<coord_t[]>(numDimensions * numVertices);
for (size_t i = 0; i < numVertices; ++i) {
size_t outIndex = i * numDimensions;
// Offset the 0th box by the position of this linear index, in each
// dimension
for (size_t d = 0; d < numDimensions; d++)
out[outIndex + d] = m_vertexesArray[outIndex + d] + m_boxLength[d] * static_cast<coord_t>(dimIndexes[d]);
}
return out;
}
//----------------------------------------------------------------------------------------------
/** Return the position of the center of a bin at a given position
*
* @param linearIndex :: linear index into the workspace
* @return VMD vector of the center position
*/
Mantid::Kernel::VMD MDHistoWorkspace::getCenter(size_t linearIndex) const {
// Index into each dimension. Built from the linearIndex.
size_t dimIndexes[10];
Utils::NestedForLoop::GetIndicesFromLinearIndex(numDimensions, linearIndex, m_indexMaker.data(), m_indexMax.data(),
dimIndexes);
// The output vertexes coordinates
VMD out(numDimensions);
// Offset the 0th box by the position of this linear index, in each dimension,
// plus a half
for (size_t d = 0; d < numDimensions; d++)
out[d] = m_vertexesArray[d] + m_boxLength[d] * (static_cast<coord_t>(dimIndexes[d]) + 0.5f);
return out;
}
//----------------------------------------------------------------------------------------------
/** Get the signal at a particular coordinate in the workspace.
*
* @param coords :: numDimensions-sized array of the coordinates to look at
* @param normalization : Normalisation to use.
* @return the (normalized) signal at a given coordinates.
* NaN if outside the range of this workspace
*/
signal_t MDHistoWorkspace::getSignalAtCoord(const coord_t *coords,
const Mantid::API::MDNormalization &normalization) const {
size_t linearIndex = this->getLinearIndexAtCoord(coords);
if (linearIndex < m_length) {
signal_t normalizer = getNormalizationFactor(normalization, linearIndex);
return m_signals[linearIndex] * normalizer;
} else
return std::numeric_limits<signal_t>::quiet_NaN();
}
//----------------------------------------------------------------------------------------------
/** Get the signal at a particular coordinate in the workspace
* or return 0 if masked
*
* @param coords :: numDimensions-sized array of the coordinates to look at
* @param normalization : Normalisation to use.
* @return the (normalized) signal at a given coordinates.
* NaN if outside the range of this workspace
*/
signal_t MDHistoWorkspace::getSignalWithMaskAtCoord(const coord_t *coords,
const Mantid::API::MDNormalization &normalization) const {
size_t linearIndex = this->getLinearIndexAtCoord(coords);
if (linearIndex == std::numeric_limits<size_t>::max() || this->getIsMaskedAt(linearIndex)) {
return MDMaskValue;
}
return getSignalAtCoord(coords, normalization);
}
//----------------------------------------------------------------------------------------------
/** Get the linear index into the histo array at these coordinates
*
* @param coords :: ND-sized array of coordinates
* @return the linear index, or size_t(-1) if out of range.
*/
size_t MDHistoWorkspace::getLinearIndexAtCoord(const coord_t *coords) const {
// Build up the linear index, dimension by dimension
size_t linearIndex = 0;
for (size_t d = 0; d < numDimensions; d++) {
coord_t x = coords[d] - m_origin[d];
auto ix = size_t(x / m_boxLength[d]);
if (ix >= m_indexMax[d] || (x < 0))
return size_t(-1);
linearIndex += ix * m_indexMaker[d];
}
return linearIndex;
}
//----------------------------------------------------------------------------------------------
/** Create IMDIterators from this MDHistoWorkspace
*
* @param suggestedNumCores :: split the iterators into this many cores (if
*threadsafe)
* @param function :: implicit function to limit range. NOT owned by this method
*call.
* @return MDHistoWorkspaceIterator vector
*/
std::vector<std::unique_ptr<Mantid::API::IMDIterator>>
MDHistoWorkspace::createIterators(size_t suggestedNumCores, Mantid::Geometry::MDImplicitFunction *function) const {
size_t numCores = suggestedNumCores;
if (!this->threadSafe())
numCores = 1;
size_t numElements = this->getNPoints();
if (numCores > numElements)
numCores = numElements;
if (numCores < 1)
numCores = 1;
// Create one iterator per core, splitting evenly amongst spectra
std::vector<std::unique_ptr<IMDIterator>> out;
for (size_t i = 0; i < numCores; i++) {
size_t begin = (i * numElements) / numCores;
size_t end = ((i + 1) * numElements) / numCores;
if (end > numElements)
end = numElements;
// Clone the MDImplicitFunction if necessary.
Mantid::Geometry::MDImplicitFunction *clonedFunction = function;
if (function)
clonedFunction = new Mantid::Geometry::MDImplicitFunction(*function);
out.emplace_back(std::make_unique<MDHistoWorkspaceIterator>(this, clonedFunction, begin, end));
}
return out;
}
//----------------------------------------------------------------------------------------------
/** Return the memory used, in bytes */
size_t MDHistoWorkspace::getMemorySize() const { return m_length * (sizeOfElement()); }
//----------------------------------------------------------------------------------------------
/// @return a vector containing a copy of the signal data in the workspace.
std::vector<signal_t> MDHistoWorkspace::getSignalDataVector() const {
std::vector<signal_t> out;
out.resize(m_length, 0.0);
for (size_t i = 0; i < m_length; ++i)
out[i] = m_signals[i];
// This copies again! :(
return out;
}
/// @return a vector containing a copy of the error data in the workspace.
std::vector<signal_t> MDHistoWorkspace::getErrorDataVector() const {
std::vector<signal_t> out;
out.resize(m_length, 0.0);
for (size_t i = 0; i < m_length; ++i)
out[i] = m_errorsSquared[i];
// This copies again! :(
return out;
}
/** @return true if the point is within the workspace (including the max edges)
* */
bool pointInWorkspace(const MDHistoWorkspace *ws, const VMD &point) {
for (size_t d = 0; d < ws->getNumDims(); d++) {
IMDDimension_const_sptr dim = ws->getDimension(d);
if ((point[d] < dim->getMinimum()) || (point[d] > dim->getMaximum()))
return false;
}
return true;
}
//----------------------------------------------------------------------------------------------
/** Obtain coordinates for a line plot through a MDWorkspace.
* Cross the workspace from start to end points, recording the signal along the
*line at bin centres of unmasked bins.
*
* @param start :: coordinates of the start point of the line
* @param end :: coordinates of the end point of the line
* @param normalize :: how to normalize the signal
* @returns :: LinePlot with x as linearly spaced points along the line
* between start and end, y set to the normalized signal for each bin with
* Length = length(x) - 1 and e as the error vector for each bin.
*/
IMDWorkspace::LinePlot MDHistoWorkspace::getLinePlot(const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end,
Mantid::API::MDNormalization normalize) const {
return this->getLinePoints(start, end, normalize, true);
}
//----------------------------------------------------------------------------------------------
/** Obtain coordinates for a line plot through a MDWorkspace.
* Cross the workspace from start to end points, recording the signal along the
*lin at either bin boundaries, or halfway between bin boundaries (which is bin
*centres if the line is dimension aligned). If recording halfway values then
*omit points in masked bins.
*
* @param start :: coordinates of the start point of the line
* @param end :: coordinates of the end point of the line
* @param normalize :: how to normalize the signal
* @returns :: LinePlot with x as the boundaries of the bins, relative
* to start of the line, y set to the normalized signal for each bin with
* Length = length(x) - 1 and e as the error vector for each bin.
* @param bin_centres :: if true then record points halfway between bin
*boundaries, otherwise record on bin boundaries
*/
IMDWorkspace::LinePlot MDHistoWorkspace::getLinePoints(const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end,
Mantid::API::MDNormalization normalize,
const bool bin_centres) const {
LinePlot line;
size_t nd = this->getNumDims();
if (start.getNumDims() != nd)
throw std::runtime_error("Start point must have the same number of "
"dimensions as the workspace.");
if (end.getNumDims() != nd)
throw std::runtime_error("End point must have the same number of dimensions as the workspace.");
// Unit-vector of the direction
VMD dir = end - start;
const auto length = dir.normalize();
// Vector with +1 where direction is positive, -1 where negative
#define sgn(x) ((x < 0) ? -1.0f : ((x > 0.) ? 1.0f : 0.0f))
VMD dirSign(nd);
for (size_t d = 0; d < nd; d++) {
dirSign[d] = sgn(dir[d]);
}
const auto BADINDEX = size_t(-1);
// Dimensions of the workspace
boost::scoped_array<size_t> index(new size_t[nd]);
boost::scoped_array<size_t> numBins(new size_t[nd]);
for (size_t d = 0; d < nd; d++) {
IMDDimension_const_sptr dim = this->getDimension(d);
index[d] = BADINDEX;
numBins[d] = dim->getNBins();
}
const std::set<coord_t> boundaries = getBinBoundariesOnLine(start, end, nd, dir, length);
if (boundaries.empty()) {
this->makeSinglePointWithNaN(line.x, line.y, line.e);
// Require x.size() = y.size()+1 if recording bin boundaries
if (!bin_centres)
line.x.emplace_back(length);
return line;
} else {
// Get the first point
std::set<coord_t>::iterator it;
it = boundaries.cbegin();
coord_t lastLinePos = *it;
VMD lastPos = start + (dir * lastLinePos);
if (!bin_centres) {
line.x.emplace_back(lastLinePos);
}
++it;
for (; it != boundaries.cend(); ++it) {
// This is our current position along the line
const coord_t linePos = *it;
// This is the full position at this boundary
VMD pos = start + (dir * linePos);
// Position in the middle of the bin
VMD middle = (pos + lastPos) * 0.5;
// Find the signal in this bin
const auto linearIndex = this->getLinearIndexAtCoord(middle.getBareArray());
if (bin_centres && !(linearIndex == std::numeric_limits<size_t>::max() || this->getIsMaskedAt(linearIndex))) {
auto bin_centrePos = static_cast<coord_t>((linePos + lastLinePos) * 0.5);
line.x.emplace_back(bin_centrePos);
} else if (!bin_centres)
line.x.emplace_back(linePos);
if (linearIndex < m_length) {
auto normalizer = getNormalizationFactor(normalize, linearIndex);
// And add the normalized signal/error to the list too
auto signal = this->getSignalAt(linearIndex) * normalizer;
if (std::isinf(signal)) {
// The plotting library (qwt) doesn't like infs.
signal = std::numeric_limits<signal_t>::quiet_NaN();
}
if (!bin_centres || !this->getIsMaskedAt(linearIndex)) {
line.y.emplace_back(signal);
line.e.emplace_back(this->getErrorAt(linearIndex) * normalizer);
}
// Save the position for next bin
lastPos = pos;
} else {
// Invalid index. This shouldn't happen
line.y.emplace_back(std::numeric_limits<signal_t>::quiet_NaN());
line.e.emplace_back(std::numeric_limits<signal_t>::quiet_NaN());
}
lastLinePos = linePos;
} // for each unique boundary
// If all bins were masked
if (line.x.empty()) {
this->makeSinglePointWithNaN(line.x, line.y, line.e);
}
}
return line;
}
//----------------------------------------------------------------------------------------------
/** Obtain coordinates for a line plot through a MDWorkspace.
* Cross the workspace from start to end points, recording the signal along the
*line.
* Sets the x,y vectors to the histogram bin boundaries and counts
*
* @param start :: coordinates of the start point of the line
* @param end :: coordinates of the end point of the line
* @param normalize :: how to normalize the signal
* @returns :: LinePlot with points at bin boundaries
*/
IMDWorkspace::LinePlot MDHistoWorkspace::getLineData(const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end,
Mantid::API::MDNormalization normalize) const {
return this->getLinePoints(start, end, normalize, false);
}
//----------------------------------------------------------------------------------------------
/** Find the normalization factor
*
* @param normalize :: how to normalize the signal
* @param linearIndex :: the position in the workspace of the signal value to be
*normalized
* @returns :: the normalization factor
*/
signal_t MDHistoWorkspace::getNormalizationFactor(const MDNormalization &normalize, size_t linearIndex) const {
signal_t normalizer = 1.0;
switch (normalize) {
case NoNormalization:
return normalizer;
case VolumeNormalization:
return m_inverseVolume;
case NumEventsNormalization:
return 1.0 / m_numEvents[linearIndex];
}
return normalizer;
}
//----------------------------------------------------------------------------------------------
/** Get ordered list of boundaries in position-along-the-line coordinates
*
* @param start :: start of the line
* @param end :: end of the line
* @param nd :: number of dimensions
* @param dir :: vector of the direction
* @param length :: unit-vector of the direction
* @returns :: ordered list of boundaries
*/
std::set<coord_t> MDHistoWorkspace::getBinBoundariesOnLine(const VMD &start, const VMD &end, size_t nd, const VMD &dir,
coord_t length) const {
std::set<coord_t> boundaries;
// Start with the start/end points, if they are within range.
if (pointInWorkspace(this, start))
boundaries.insert(0.0f);
if (pointInWorkspace(this, end))
boundaries.insert(length);
// Next, we go through each dimension and see where the bin boundaries
// intersect the line.
for (size_t d = 0; d < nd; d++) {
IMDDimension_const_sptr dim = getDimension(d);
coord_t lineStartX = start[d];
if (dir[d] != 0.0) {
auto nbounds = dim->getNBoundaries();
for (size_t i = 0; i < nbounds; i++) {
// Position in this coordinate
coord_t thisX = dim->getX(i);
// Position along the line. Is this between the start and end of it?
coord_t linePos = (thisX - lineStartX) / dir[d];
if (linePos >= 0 && linePos <= length) {
// Full position
VMD pos = start + (dir * linePos);
// This is a boundary if the line point is inside the workspace
if (pointInWorkspace(this, pos))
boundaries.insert(linePos);
}
}
}
}
return boundaries;
}
//==============================================================================================
//============================== ARITHMETIC OPERATIONS
//=========================================
//==============================================================================================
//----------------------------------------------------------------------------------------------
/** Check if the two workspace's sizes match (for comparison or
*element-by-element operation
*
* @param other :: the workspace to compare to
* @param operation :: descriptive string (for the error message)
* @throw an error if they don't match
*/
void MDHistoWorkspace::checkWorkspaceSize(const MDHistoWorkspace &other, const std::string &operation) {
if (other.getNumDims() != this->getNumDims())
throw std::invalid_argument("Cannot perform the " + operation +
" operation on this MDHistoWorkspace. The "
"number of dimensions does not match.");
if (other.m_length != this->m_length)
throw std::invalid_argument("Cannot perform the " + operation +
" operation on this MDHistoWorkspace. The "
"length of the signals vector does not match.");
}
//----------------------------------------------------------------------------------------------
/** Perform the += operation, element-by-element, for two MDHistoWorkspace's
*
* @param b :: workspace on the RHS of the operation
* @return *this after operation */
MDHistoWorkspace &MDHistoWorkspace::operator+=(const MDHistoWorkspace &b) {
add(b);
return *this;
}
//----------------------------------------------------------------------------------------------
/** Perform the += operation, element-by-element, for two MDHistoWorkspace's
*
* @param b :: workspace on the RHS of the operation
* */
void MDHistoWorkspace::add(const MDHistoWorkspace &b) {
checkWorkspaceSize(b, "add");
for (size_t i = 0; i < m_length; ++i) {
m_signals[i] += b.m_signals[i];
m_errorsSquared[i] += b.m_errorsSquared[i];
m_numEvents[i] += b.m_numEvents[i];
}
m_nEventsContributed += b.m_nEventsContributed;
}
//----------------------------------------------------------------------------------------------
/** Perform the += operation with a scalar as the RHS argument
*
* @param signal :: signal to apply
* @param error :: error (not squared) to apply
* */
void MDHistoWorkspace::add(const signal_t signal, const signal_t error) {
signal_t errorSquared = error * error;
for (size_t i = 0; i < m_length; ++i) {
m_signals[i] += signal;
m_errorsSquared[i] += errorSquared;
}
}
//----------------------------------------------------------------------------------------------
/** Perform the -= operation, element-by-element, for two MDHistoWorkspace's
*
* @param b :: workspace on the RHS of the operation
* @return *this after operation */
MDHistoWorkspace &MDHistoWorkspace::operator-=(const MDHistoWorkspace &b) {
subtract(b);
return *this;
}
//----------------------------------------------------------------------------------------------
/** Perform the -= operation, element-by-element, for two MDHistoWorkspace's
*
* @param b :: workspace on the RHS of the operation
* */
void MDHistoWorkspace::subtract(const MDHistoWorkspace &b) {
checkWorkspaceSize(b, "subtract");
for (size_t i = 0; i < m_length; ++i) {
m_signals[i] -= b.m_signals[i];
m_errorsSquared[i] += b.m_errorsSquared[i];
m_numEvents[i] += b.m_numEvents[i];
}
m_nEventsContributed += b.m_nEventsContributed;
}
//----------------------------------------------------------------------------------------------
/** Perform the -= operation with a scalar as the RHS argument
*
* @param signal :: signal to apply
* @param error :: error (not squared) to apply
* */
void MDHistoWorkspace::subtract(const signal_t signal, const signal_t error) {
signal_t errorSquared = error * error;
for (size_t i = 0; i < m_length; ++i) {
m_signals[i] -= signal;
m_errorsSquared[i] += errorSquared;
}
}
//----------------------------------------------------------------------------------------------
/** Perform the *= operation, element-by-element, for two MDHistoWorkspace's
*
* Error propagation of \f$ f = a * b \f$ is given by:
* \f$ df^2 = f^2 * (da^2 / a^2 + db^2 / b^2) \f$
*
* @param b_ws :: workspace on the RHS of the operation
* @return *this after operation */
MDHistoWorkspace &MDHistoWorkspace::operator*=(const MDHistoWorkspace &b_ws) {
multiply(b_ws);
return *this;
}
//----------------------------------------------------------------------------------------------
/** Perform the *= operation, element-by-element, for two MDHistoWorkspace's
*
* Error propagation of \f$ f = a * b \f$ is given by:
* \f$ df^2 = f^2 * (da^2 / a^2 + db^2 / b^2) \f$
* Rewritten as:
* \f$ df^2 = b^2 da^2 + a^2 * db^2 \f$
* to avoid problems when a or b are 0
*
* @param b_ws :: workspace on the RHS of the operation
* */
void MDHistoWorkspace::multiply(const MDHistoWorkspace &b_ws) {
checkWorkspaceSize(b_ws, "multiply");
for (size_t i = 0; i < m_length; ++i) {
signal_t a = m_signals[i];
signal_t da2 = m_errorsSquared[i];
signal_t b = b_ws.m_signals[i];
signal_t db2 = b_ws.m_errorsSquared[i];
signal_t f = a * b;
signal_t df2 = da2 * b * b + db2 * a * a;
m_signals[i] = f;
m_errorsSquared[i] = df2;
}
}
//----------------------------------------------------------------------------------------------
/** Perform the *= operation with a scalar as the RHS argument
*
* Error propagation of \f$ f = a * b \f$ is given by:
* \f$ df^2 = f^2 * (da^2 / a^2 + db^2 / b^2) \f$
* Rewritten as:
* \f$ df^2 = b^2 da^2 + a^2 * db^2 \f$
* to avoid problems when a or b are 0
*
* @param signal :: signal to apply
* @param error :: error (not squared) to apply
* @return *this after operation */
void MDHistoWorkspace::multiply(const signal_t signal, const signal_t error) {
signal_t b = signal;
signal_t db2 = error * error;
for (size_t i = 0; i < m_length; ++i) {
signal_t a = m_signals[i];
signal_t da2 = m_errorsSquared[i];
signal_t f = a * b;
signal_t df2 = da2 * b * b + db2 * a * a;
m_signals[i] = f;
m_errorsSquared[i] = df2;
}
}
//----------------------------------------------------------------------------------------------
/** Perform the /= operation, element-by-element, for two MDHistoWorkspace's
*
* Error propagation of \f$ f = a / b \f$ is given by:
* \f$ df^2 = f^2 * (da^2 / a^2 + db^2 / b^2) \f$
*
* @param b_ws :: workspace on the RHS of the operation
* @return *this after operation */
MDHistoWorkspace &MDHistoWorkspace::operator/=(const MDHistoWorkspace &b_ws) {
divide(b_ws);
return *this;
}
//----------------------------------------------------------------------------------------------
/** Perform the /= operation, element-by-element, for two MDHistoWorkspace's
*
* Error propagation of \f$ f = a / b \f$ is given by:
* \f$ df^2 = f^2 * (da^2 / a^2 + db^2 / b^2) \f$
* Rewritten as:
* \f$ df^2 = da^2 / b^2 + db^2 *f^2 / b^2 \f$
* to avoid problems when a or b are 0
*
* @param b_ws :: workspace on the RHS of the operation
**/
void MDHistoWorkspace::divide(const MDHistoWorkspace &b_ws) {
checkWorkspaceSize(b_ws, "divide");
for (size_t i = 0; i < m_length; ++i) {
signal_t a = m_signals[i];
signal_t da2 = m_errorsSquared[i];
signal_t b = b_ws.m_signals[i];
signal_t db2 = b_ws.m_errorsSquared[i];
signal_t f = a / b;
signal_t df2 = da2 / (b * b) + db2 * f * f / (b * b);
m_signals[i] = f;
m_errorsSquared[i] = df2;
}
}
//----------------------------------------------------------------------------------------------
/** Perform the /= operation with a scalar as the RHS argument
*
* Error propagation of \f$ f = a / b \f$ is given by:
* \f$ df^2 = f^2 * (da^2 / a^2 + db^2 / b^2) \f$
* Rewritten as:
* \f$ df^2 = da^2 / b^2 + db^2 *f^2 / b^2 \f$
* to avoid problems when a or b are 0
*
* @param signal :: signal to apply
* @param error :: error (not squared) to apply
**/
void MDHistoWorkspace::divide(const signal_t signal, const signal_t error) {
signal_t b = signal;
signal_t db2 = error * error;
signal_t db2_relative = db2 / (b * b);
for (size_t i = 0; i < m_length; ++i) {
signal_t a = m_signals[i];
signal_t da2 = m_errorsSquared[i];
signal_t f = a / b;
signal_t df2 = da2 / (b * b) + db2_relative * f * f;
m_signals[i] = f;
m_errorsSquared[i] = df2;
}
}
//----------------------------------------------------------------------------------------------
/** Perform the natural logarithm on each signal in the workspace.
*
* Error propagation of \f$ f = ln(a) \f$ is given by:
* \f$ df^2 = a^2 / da^2 \f$
*/
void MDHistoWorkspace::log(double filler) {
for (size_t i = 0; i < m_length; ++i) {
signal_t a = m_signals[i];
signal_t da2 = m_errorsSquared[i];
if (a <= 0) {
m_signals[i] = filler;
m_errorsSquared[i] = 0;
} else {
m_signals[i] = std::log(a);
m_errorsSquared[i] = da2 / (a * a);
}
}
}
//----------------------------------------------------------------------------------------------
/** Perform the base-10 logarithm on each signal in the workspace.
*
* Error propagation of \f$ f = ln(a) \f$ is given by:
* \f$ df^2 = (ln(10)^-2) * a^2 / da^2 \f$
*/
void MDHistoWorkspace::log10(double filler) {
for (size_t i = 0; i < m_length; ++i) {
signal_t a = m_signals[i];
signal_t da2 = m_errorsSquared[i];
if (a <= 0) {
m_signals[i] = filler;
m_errorsSquared[i] = 0;
} else {
m_signals[i] = std::log10(a);
m_errorsSquared[i] = 0.1886117 * da2 / (a * a); // 0.1886117 = ln(10)^-2
}
}
}
//----------------------------------------------------------------------------------------------
/** Perform the exp() function on each signal in the workspace.
*
* Error propagation of \f$ f = exp(a) \f$ is given by:
* \f$ df^2 = f^2 * da^2 \f$
*/
void MDHistoWorkspace::exp() {
for (size_t i = 0; i < m_length; ++i) {
signal_t f = std::exp(m_signals[i]);
signal_t da2 = m_errorsSquared[i];
m_signals[i] = f;
m_errorsSquared[i] = f * f * da2;
}
}
//----------------------------------------------------------------------------------------------
/** Perform the power function (signal^exponent) on each signal S in the
*workspace.
*
* Error propagation of \f$ f = a^b \f$ is given by:
* \f$ df^2 = f^2 * b^2 * (da^2 / a^2) \f$
*/
void MDHistoWorkspace::power(double exponent) {
double exponent_squared = exponent * exponent;
for (size_t i = 0; i < m_length; ++i) {
signal_t a = m_signals[i];
signal_t f = std::pow(a, exponent);
signal_t da2 = m_errorsSquared[i];
m_signals[i] = f;
m_errorsSquared[i] = f * f * exponent_squared * da2 / (a * a);
}
}
//==============================================================================================
//============================== BOOLEAN OPERATIONS
//============================================
//==============================================================================================
//----------------------------------------------------------------------------------------------
/// @cond DOXYGEN_BUG
/** A boolean &= (and) operation, element-by-element, for two