/
IntegrateFlux.cpp
489 lines (418 loc) · 15.8 KB
/
IntegrateFlux.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
#include "MantidMDAlgorithms/IntegrateFlux.h"
#include "MantidDataObjects/EventWorkspace.h"
#include "MantidAPI/MatrixWorkspace.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidKernel/BoundedValidator.h"
#include <boost/make_shared.hpp>
#include <numeric>
namespace Mantid {
namespace MDAlgorithms {
using Mantid::Kernel::Direction;
using Mantid::API::WorkspaceProperty;
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(IntegrateFlux)
namespace {
/// Void deleter for shared pointers
class NoEventWorkspaceDeleting {
public:
/// deleting operator. Does nothing
void operator()(const API::MatrixWorkspace *) {}
};
}
//----------------------------------------------------------------------------------------------
/// Algorithms name for identification. @see Algorithm::name
const std::string IntegrateFlux::name() const { return "IntegrateFlux"; }
/// Algorithm's version for identification. @see Algorithm::version
int IntegrateFlux::version() const { return 1; }
/// Algorithm's category for identification. @see Algorithm::category
const std::string IntegrateFlux::category() const {
return "MDAlgorithms\\Normalisation";
}
/// Algorithm's summary for use in the GUI and help. @see Algorithm::summary
const std::string IntegrateFlux::summary() const {
return "Interates spectra in a matrix workspace at a set of points.";
}
//----------------------------------------------------------------------------------------------
/** Initialize the algorithm's properties.
*/
void IntegrateFlux::init() {
declareProperty(Kernel::make_unique<WorkspaceProperty<API::MatrixWorkspace>>(
"InputWorkspace", "", Direction::Input),
"An input workspace.");
auto validator = boost::make_shared<Kernel::BoundedValidator<int>>();
validator->setLower(2);
declareProperty("NPoints", 1000, validator,
"Number of points per output spectrum.");
declareProperty(Kernel::make_unique<WorkspaceProperty<API::Workspace>>(
"OutputWorkspace", "", Direction::Output),
"An output workspace.");
}
//----------------------------------------------------------------------------------------------
/** Execute the algorithm.
*/
void IntegrateFlux::exec() {
API::MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
size_t nX = static_cast<size_t>(static_cast<int>(getProperty("NPoints")));
auto outputWS = createOutputWorkspace(*inputWS, nX);
integrateSpectra(*inputWS, *outputWS);
setProperty("OutputWorkspace", outputWS);
}
/**
* Create an empty output workspace with required dimensions and defined
* x-values
* @param inputWS :: The input event workspace.
* @param nX :: Suggested size of the output spectra. It can change in the
* actual output.
*/
boost::shared_ptr<API::MatrixWorkspace>
IntegrateFlux::createOutputWorkspace(const API::MatrixWorkspace &inputWS,
size_t nX) const {
size_t nSpec = inputWS.getNumberHistograms();
if (nSpec == 0) {
throw std::runtime_error("Input workspace has no data.");
}
// make sure the output spectrum size isn't too large
auto maxPoints = getMaxNumberOfPoints(inputWS);
if (nX > maxPoints) {
nX = maxPoints;
}
// and not 0 or 1 as they are to be used for interpolation
if (nX < 2) {
throw std::runtime_error("Failed to create output."
"Output spectra should have at least two points.");
}
// crate empty output workspace
API::MatrixWorkspace_sptr ws = API::WorkspaceFactory::Instance().create(
boost::shared_ptr<const API::MatrixWorkspace>(&inputWS,
NoEventWorkspaceDeleting()),
nSpec, nX, nX);
// claculate the integration points and save them in the x-vactors of
// integrFlux
double xMin = inputWS.getXMin();
double xMax = inputWS.getXMax();
double dx = (xMax - xMin) / static_cast<double>(nX - 1);
auto &X = ws->dataX(0);
auto ix = X.begin();
// x-values are equally spaced between the min and max tof in the first flux
// spectrum
for (double x = xMin; ix != X.end(); ++ix, x += dx) {
*ix = x;
}
// share the xs for all spectra
auto xRef = ws->refX(0);
for (size_t sp = 1; sp < nSpec; ++sp) {
ws->setX(sp, xRef);
}
return ws;
}
/**
* Integrate spectra in inputWS at x-values in integrWS and save the results in
* y-vectors of integrWS.
* @param inputWS :: A workspace to integrate. The events have to be
* weighted-no-time.
* @param integrWS :: A workspace to store the results.
*/
void IntegrateFlux::integrateSpectra(const API::MatrixWorkspace &inputWS,
API::MatrixWorkspace &integrWS) const {
auto eventWS = dynamic_cast<const DataObjects::EventWorkspace *>(&inputWS);
if (eventWS) {
auto eventType = eventWS->getEventType();
switch (eventType) {
case (API::WEIGHTED_NOTIME):
integrateSpectraEvents<DataObjects::WeightedEventNoTime>(*eventWS,
integrWS);
return;
case (API::WEIGHTED):
integrateSpectraEvents<DataObjects::WeightedEvent>(*eventWS, integrWS);
return;
case (API::TOF):
integrateSpectraEvents<DataObjects::TofEvent>(*eventWS, integrWS);
return;
}
} else {
integrateSpectraMatrix(inputWS, integrWS);
}
}
/**
* Integrate spectra in inputWS at x-values in integrWS and save the results in
* y-vectors of integrWS.
* @param inputWS :: An event workspace to integrate.
* @param integrWS :: A workspace to store the results.
*/
template <class EventType>
void IntegrateFlux::integrateSpectraEvents(
const DataObjects::EventWorkspace &inputWS,
API::MatrixWorkspace &integrWS) const {
inputWS.sortAll(DataObjects::TOF_SORT, nullptr);
size_t nSpec = inputWS.getNumberHistograms();
assert(nSpec == integrWS.getNumberHistograms());
auto &X = integrWS.readX(0);
// loop overr the spectra and integrate
for (size_t sp = 0; sp < nSpec; ++sp) {
const std::vector<EventType> *el;
DataObjects::getEventsFrom(inputWS.getEventList(sp), el);
auto &outY = integrWS.dataY(sp);
double sum = 0;
auto x = X.begin() + 1;
size_t i = 1;
// the integral is a running sum of the event weights in the spectrum
for (auto evnt = el->begin(); evnt != el->end(); ++evnt) {
double tof = evnt->tof();
while (x != X.end() && *x < tof) {
outY[i] = sum;
++x;
++i;
}
if (x == X.end())
break;
sum += evnt->weight();
outY[i] = sum;
}
}
}
/**
* Integrate spectra in inputWS at x-values in integrWS and save the results in
* y-vectors of integrWS.
* @param inputWS :: A 2d workspace to integrate.
* @param integrWS :: A workspace to store the results.
*/
void IntegrateFlux::integrateSpectraMatrix(
const API::MatrixWorkspace &inputWS, API::MatrixWorkspace &integrWS) const {
bool isHistogram = inputWS.isHistogramData();
if (isHistogram) {
integrateSpectraHistograms(inputWS, integrWS);
} else {
integrateSpectraPointData(inputWS, integrWS);
}
}
/**
* Integrate spectra in inputWS at x-values in integrWS and save the results in
* y-vectors of integrWS.
* @param inputWS :: A 2d workspace to integrate.
* @param integrWS :: A workspace to store the results.
*/
void IntegrateFlux::integrateSpectraHistograms(
const API::MatrixWorkspace &inputWS, API::MatrixWorkspace &integrWS) const {
size_t nSpec = inputWS.getNumberHistograms();
assert(nSpec == integrWS.getNumberHistograms());
bool isDistribution = inputWS.isDistribution();
auto &X = integrWS.readX(0);
// loop overr the spectra and integrate
for (size_t sp = 0; sp < nSpec; ++sp) {
auto &inX = inputWS.dataX(sp);
auto inY = inputWS.dataY(sp); // make a copy
// if it's a distribution y's must be multiplied by the bin widths
if (isDistribution) {
std::vector<double> xDiff(inX.size());
std::adjacent_difference(inX.begin(), inX.end(), xDiff.begin());
std::transform(xDiff.begin() + 1, xDiff.end(), inY.begin(), inY.begin(),
std::multiplies<double>());
}
// integral at the first point is always 0
auto outY = integrWS.dataY(sp).begin();
*outY = 0.0;
++outY;
// initialize summation
double sum = 0;
// cache some iterators
auto inXbegin = inX.begin();
auto inXend = inX.end();
auto x0 = inXbegin; // iterator over x in input workspace
// loop over the iteration points starting from the second one
for (auto outX = X.begin() + 1; outX != X.end(); ++outX, ++outY) {
// there are no data to integrate
if (x0 == inXend) {
*outY = sum;
continue;
}
// in each iteration we find the integral of the input spectrum
// between bounds [lowerBound,upperBound]
const double &lowerBound = *(outX - 1);
double upperBound = *outX;
// interval [*x0, *x1] is the smalest interval in inX that contains
// the integration interval [lowerBound,upperBound]
auto x1 = std::lower_bound(x0, inXend, upperBound);
// reached end of input data
if (x1 == inXend) {
--x1;
if (x1 == x0) {
*outY = sum;
x0 = inXend;
continue;
}
upperBound = *x1;
}
// if starting point in input x is smaller (not equal) than the lower
// integration bound
// then there is a partial bin at the beginning of the interval
if (*x0 < lowerBound) {
// first find the part of bin [*x0,*(x0+1)] which hasn't been integrated
// yet
// the left boundary == lowerBound
// the right boundary == min( upperBound, *(x0+1) )
const double leftX = lowerBound;
const double rightX = std::min(upperBound, *(x0 + 1));
auto i = static_cast<size_t>(std::distance(inXbegin, x0));
// add bin's fraction between leftX and rightX
sum += inY[i] * (rightX - leftX) / (*(x0 + 1) - *x0);
// if rightX == upperBound there is nothing left to integrate, move to
// the next integration point
if (rightX == upperBound) {
*outY = sum;
continue;
}
++x0;
}
// accumulate values in bins that fit entirely into the integration
// interval [lowerBound,upperBound]
auto i0 = static_cast<size_t>(std::distance(inXbegin, x0));
auto i1 = static_cast<size_t>(std::distance(inXbegin, x1));
if (*x1 > upperBound)
--i1;
for (auto i = i0; i < i1; ++i) {
sum += inY[i];
}
// if x1 is greater than upperBound there is a partial "bin" that has to
// be added
if (*x1 > upperBound) {
// find the part of "bin" [*(x1-1),*x1] which needs to be integrated
// the left boundary == *(x1-1)
// the right boundary == upperBound
const double leftX = *(x1 - 1);
const double rightX = upperBound;
auto i = static_cast<size_t>(std::distance(inXbegin, x1));
// add the area under the line between leftX and rightX
sum += inY[i - 1] * (rightX - leftX) / (*x1 - *(x1 - 1));
// advance in the input workspace
x0 = x1 - 1;
} else {
// advance in the input workspace
x0 = x1;
}
// store the current sum
*outY = sum;
}
}
}
/**
* Integrate spectra in inputWS at x-values in integrWS and save the results in
* y-vectors of integrWS.
* @param inputWS :: A 2d workspace to integrate.
* @param integrWS :: A workspace to store the results.
*/
void IntegrateFlux::integrateSpectraPointData(
const API::MatrixWorkspace &inputWS, API::MatrixWorkspace &integrWS) const {
size_t nSpec = inputWS.getNumberHistograms();
assert(nSpec == integrWS.getNumberHistograms());
auto &X = integrWS.dataX(0);
// loop overr the spectra and integrate
for (size_t sp = 0; sp < nSpec; ++sp) {
auto &inX = inputWS.readX(sp);
auto &inY = inputWS.readY(sp);
// integral at the first point is always 0
auto outY = integrWS.dataY(sp).begin();
*outY = 0.0;
++outY;
// initialize summation
double sum = 0;
// cache some iterators
auto inXbegin = inX.begin();
auto inXend = inX.end();
auto x0 = inXbegin; // iterator over x in input workspace
// loop over the iteration points starting from the second one
for (auto outX = X.begin() + 1; outX != X.end(); ++outX, ++outY) {
// there are no data to integrate
if (x0 == inXend) {
*outY = sum;
continue;
}
// in each iteration we find the integral of the input spectrum
// between bounds [lowerBound,upperBound]
const double &lowerBound = *(outX - 1);
double upperBound = *outX;
// interval [*x0, *x1] is the smalest interval in inX that contains
// the integration interval [lowerBound,upperBound]
auto x1 = std::lower_bound(x0, inXend, upperBound);
// reached end of input data
if (x1 == inXend) {
--x1;
if (x1 == x0) {
*outY = sum;
x0 = inXend;
continue;
}
upperBound = *x1;
}
// if starting point in input x is smaller (not equal) than the lower
// integration bound
// then there is a partial "bin" at the beginning of the interval
if (*x0 < lowerBound) {
// first find the part of "bin" [*x0,*(x0+1)] which hasn't been
// integrated yet
// the left boundary == lowerBound
// the right boundary == min( upperBound, *(x0+1) )
const double leftX = lowerBound;
const double rightX = std::min(upperBound, *(x0 + 1));
auto i = static_cast<size_t>(std::distance(inXbegin, x0));
// gradient of "bin" [*x0,*(x0+1)]
double dy_dx = (inY[i + 1] - inY[i]) / (*(x0 + 1) - *x0);
// add the area under the line between leftX and rightX
sum += (inY[i] + 0.5 * dy_dx * (leftX + rightX - 2 * (*(x0)))) *
(rightX - leftX);
// if rightX == upperBound there is nothing left to integrate, move to
// the next integration point
if (rightX == upperBound) {
*outY = sum;
continue;
}
++x0;
}
// accumulate values in bins that fit entirely into the integration
// interval [lowerBound,upperBound]
auto i0 = static_cast<size_t>(std::distance(inXbegin, x0));
auto i1 = static_cast<size_t>(std::distance(inXbegin, x1));
if (*x1 > upperBound)
--i1;
for (auto i = i0; i < i1; ++i) {
sum += (inY[i] + inY[i + 1]) / 2 * (inX[i + 1] - inX[i]);
}
// if x1 is greater than upperBound there is a partial "bin" that has to
// be added
if (*x1 > upperBound) {
// find the part of "bin" [*(x1-1),*x1] which needs to be integrated
// the left boundary == *(x1-1)
// the right boundary == upperBound
const double leftX = *(x1 - 1);
const double rightX = upperBound;
auto i = static_cast<size_t>(std::distance(inXbegin, x1));
// gradient of "bin" [*(x1-1),*x1]
double dy_dx = (inY[i] - inY[i - 1]) / (*x1 - *(x1 - 1));
// add the area under the line between leftX and rightX
sum += (inY[i - 1] + 0.5 * dy_dx * (rightX - *(x1 - 1))) *
(rightX - leftX);
// advance in the input workspace
x0 = x1 - 1;
} else {
// advance in the input workspace
x0 = x1;
}
// store the current sum
*outY = sum;
}
}
}
/**
* Calculate the maximun number of points in the integration grid.
* @param inputWS :: An input workspace.
*/
size_t
IntegrateFlux::getMaxNumberOfPoints(const API::MatrixWorkspace &inputWS) const {
// if it's events we shouldn't care about binning
auto eventWS = dynamic_cast<const DataObjects::EventWorkspace *>(&inputWS);
if (eventWS) {
return eventWS->getEventList(0).getNumberEvents();
}
return inputWS.blocksize();
}
} // namespace MDAlgorithms
} // namespace Mantid