-
Notifications
You must be signed in to change notification settings - Fork 122
/
WorkspaceCreationHelper.cpp
1363 lines (1207 loc) · 47.2 KB
/
WorkspaceCreationHelper.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
/*********************************************************************************
* PLEASE READ THIS!!!!!!!
*
* This collection of functions MAY NOT be used in any test from a package
*below
* DataObjects (e.g. Kernel, Geometry, API).
* Conversely, this file MAY NOT be modified to use anything from a package
*higher
* than DataObjects (e.g. any algorithm), even if going via the factory.
*********************************************************************************/
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "MantidTestHelpers/WorkspaceCreationHelper.h"
#include "MantidTestHelpers/ComponentCreationHelper.h"
#include "MantidAPI/Run.h"
#include "MantidAPI/IAlgorithm.h"
#include "MantidAPI/Algorithm.h"
#include "MantidAPI/SpectraAxis.h"
#include "MantidAPI/NumericAxis.h"
#include "MantidDataObjects/PeaksWorkspace.h"
#include "MantidGeometry/Instrument/Detector.h"
#include "MantidGeometry/Instrument/ParameterMap.h"
#include "MantidGeometry/Instrument/ReferenceFrame.h"
#include "MantidGeometry/Objects/ShapeFactory.h"
#include "MantidGeometry/Crystal/OrientedLattice.h"
#include "MantidKernel/MersenneTwister.h"
#include "MantidKernel/TimeSeriesProperty.h"
#include "MantidKernel/UnitFactory.h"
#include "MantidKernel/VectorHelper.h"
#include <cmath>
#include <sstream>
namespace WorkspaceCreationHelper {
using namespace Mantid;
using namespace Mantid::DataObjects;
using namespace Mantid::Kernel;
using namespace Mantid::API;
using namespace Mantid::Geometry;
using Mantid::MantidVec;
using Mantid::MantidVecPtr;
MockAlgorithm::MockAlgorithm(size_t nSteps) {
m_Progress =
std::auto_ptr<API::Progress>(new API::Progress(this, 0, 1, nSteps));
}
/**
* @param name :: The name of the workspace
* @param ws :: The workspace object
*/
void storeWS(const std::string &name, Mantid::API::Workspace_sptr ws) {
Mantid::API::AnalysisDataService::Instance().add(name, ws);
}
/**
* Deletes a workspace
* @param name :: The name of the workspace
*/
void removeWS(const std::string &name) {
Mantid::API::AnalysisDataService::Instance().remove(name);
}
Workspace2D_sptr Create1DWorkspaceRand(int size) {
MantidVecPtr x1, y1, e1;
x1.access().resize(size, 1);
y1.access().resize(size);
std::generate(y1.access().begin(), y1.access().end(), rand);
e1.access().resize(size);
std::generate(e1.access().begin(), e1.access().end(), rand);
Workspace2D_sptr retVal(new Workspace2D);
retVal->initialize(1, size, size);
retVal->setX(0, x1);
retVal->setData(0, y1, e1);
return retVal;
}
Workspace2D_sptr Create1DWorkspaceConstant(int size, double value,
double error) {
MantidVecPtr x1, y1, e1;
x1.access().resize(size, 1);
y1.access().resize(size);
std::fill(y1.access().begin(), y1.access().end(), value);
e1.access().resize(size);
std::fill(y1.access().begin(), y1.access().end(), error);
Workspace2D_sptr retVal(new Workspace2D);
retVal->initialize(1, size, size);
retVal->setX(0, x1);
retVal->setData(0, y1, e1);
return retVal;
}
Workspace2D_sptr Create1DWorkspaceFib(int size) {
MantidVecPtr x1, y1, e1;
x1.access().resize(size, 1);
y1.access().resize(size);
std::generate(y1.access().begin(), y1.access().end(), FibSeries<double>());
e1.access().resize(size);
Workspace2D_sptr retVal(new Workspace2D);
retVal->initialize(1, size, size);
retVal->setX(0, x1);
retVal->setData(0, y1, e1);
return retVal;
}
Workspace2D_sptr Create2DWorkspace(int nhist, int numBoundaries) {
return Create2DWorkspaceBinned(nhist, numBoundaries);
}
/** Create a Workspace2D where the Y value at each bin is
* == to the workspace index
* @param nhist :: # histograms
* @param numBoundaries :: # of bins
* @return Workspace2D
*/
Workspace2D_sptr Create2DWorkspaceWhereYIsWorkspaceIndex(int nhist,
int numBoundaries) {
Workspace2D_sptr out = Create2DWorkspaceBinned(nhist, numBoundaries);
for (int wi = 0; wi < nhist; wi++)
for (int x = 0; x < numBoundaries; x++)
out->dataY(wi)[x] = wi * 1.0;
return out;
}
Workspace2D_sptr create2DWorkspaceThetaVsTOF(int nHist, int nBins) {
Workspace2D_sptr outputWS = Create2DWorkspaceBinned(nHist, nBins);
NumericAxis *const newAxis = new NumericAxis(nHist);
outputWS->replaceAxis(1, newAxis);
newAxis->unit() = boost::shared_ptr<Unit>(new Units::Degrees);
for (int i = 0; i < nHist; ++i) {
newAxis->setValue(i, i + 1);
}
return outputWS;
}
Workspace2D_sptr
Create2DWorkspaceWithValues(int64_t nHist, int64_t nBins, bool isHist,
const std::set<int64_t> &maskedWorkspaceIndices,
double xVal, double yVal, double eVal) {
MantidVecPtr x1, y1, e1;
x1.access().resize(isHist ? nBins + 1 : nBins, xVal);
y1.access().resize(nBins, yVal);
e1.access().resize(nBins, eVal);
Workspace2D_sptr retVal(new Workspace2D);
retVal->initialize(nHist, isHist ? nBins + 1 : nBins, nBins);
for (int i = 0; i < nHist; i++) {
retVal->setX(i, x1);
retVal->setData(i, y1, e1);
retVal->getSpectrum(i)->setDetectorID(i);
retVal->getSpectrum(i)->setSpectrumNo(i);
}
retVal = maskSpectra(retVal, maskedWorkspaceIndices);
return retVal;
}
Workspace2D_sptr
Create2DWorkspace123(int64_t nHist, int64_t nBins, bool isHist,
const std::set<int64_t> &maskedWorkspaceIndices) {
return Create2DWorkspaceWithValues(nHist, nBins, isHist,
maskedWorkspaceIndices, 1.0, 2.0, 3.0);
}
Workspace2D_sptr
Create2DWorkspace154(int64_t nHist, int64_t nBins, bool isHist,
const std::set<int64_t> &maskedWorkspaceIndices) {
return Create2DWorkspaceWithValues(nHist, nBins, isHist,
maskedWorkspaceIndices, 1.0, 5.0, 4.0);
}
Workspace2D_sptr maskSpectra(Workspace2D_sptr workspace,
const std::set<int64_t> &maskedWorkspaceIndices) {
const int nhist = static_cast<int>(workspace->getNumberHistograms());
if (workspace->getInstrument()->nelements() == 0) {
// We need detectors to be able to mask them.
boost::shared_ptr<Instrument> instrument(new Instrument);
workspace->setInstrument(instrument);
std::string xmlShape = "<sphere id=\"shape\"> ";
xmlShape += "<centre x=\"0.0\" y=\"0.0\" z=\"0.0\" /> ";
xmlShape += "<radius val=\"0.05\" /> ";
xmlShape += "</sphere>";
xmlShape += "<algebra val=\"shape\" /> ";
ShapeFactory sFactory;
boost::shared_ptr<Object> shape = sFactory.createShape(xmlShape);
for (int i = 0; i < nhist; ++i) {
Detector *det = new Detector("det", detid_t(i), shape, NULL);
det->setPos(i, i + 1, 1);
instrument->add(det);
instrument->markAsDetector(det);
}
workspace->setInstrument(instrument);
}
ParameterMap &pmap = workspace->instrumentParameters();
for (int i = 0; i < nhist; ++i) {
if (maskedWorkspaceIndices.find(i) != maskedWorkspaceIndices.end()) {
IDetector_const_sptr det = workspace->getDetector(i);
pmap.addBool(det.get(), "masked", true);
}
}
return workspace;
}
/**
* Create a group with nEntries. It is added to the ADS with the given stem
*/
WorkspaceGroup_sptr CreateWorkspaceGroup(int nEntries, int nHist, int nBins,
const std::string &stem) {
WorkspaceGroup_sptr group(new WorkspaceGroup);
AnalysisDataService::Instance().add(stem, group);
for (int i = 0; i < nEntries; ++i) {
Workspace2D_sptr ws = Create2DWorkspace(nHist, nBins);
std::ostringstream os;
os << stem << "_" << i;
AnalysisDataService::Instance().add(os.str(), ws);
group->add(os.str());
}
return group;
}
/** Create a 2D workspace with this many histograms and bins.
* Filled with Y = 2.0 and E = sqrt(2.0)w
*/
Workspace2D_sptr Create2DWorkspaceBinned(int nhist, int nbins, double x0,
double deltax) {
MantidVecPtr x, y, e;
x.access().resize(nbins + 1);
y.access().resize(nbins, 2);
e.access().resize(nbins, sqrt(2.0));
for (int i = 0; i < nbins + 1; ++i) {
x.access()[i] = x0 + i * deltax;
}
Workspace2D_sptr retVal(new Workspace2D);
retVal->initialize(nhist, nbins + 1, nbins);
for (int i = 0; i < nhist; i++) {
retVal->setX(i, x);
retVal->setData(i, y, e);
}
return retVal;
}
/** Create a 2D workspace with this many histograms and bins. The bins are
* assumed to be non-uniform and given by the input array
* Filled with Y = 2.0 and E = sqrt(2.0)w
*/
Workspace2D_sptr Create2DWorkspaceBinned(int nhist, const int numBoundaries,
const double xBoundaries[]) {
MantidVecPtr x, y, e;
const int numBins = numBoundaries - 1;
x.access().resize(numBoundaries);
y.access().resize(numBins, 2);
e.access().resize(numBins, sqrt(2.0));
for (int i = 0; i < numBoundaries; ++i) {
x.access()[i] = xBoundaries[i];
}
Workspace2D_sptr retVal(new Workspace2D);
retVal->initialize(nhist, numBins + 1, numBins);
for (int i = 0; i < nhist; i++) {
retVal->setX(i, x);
retVal->setData(i, y, e);
}
return retVal;
}
/**
* Add random noise to the signal
* @param ws :: The workspace to add the noise to
* @param noise :: The mean noise level
* @param lower :: The lower bound of the flucation (default=-0.5)
* @param upper:: The upper bound of the flucation (default=-0.5)
*/
void addNoise(Mantid::API::MatrixWorkspace_sptr ws, double noise,
const double lower, const double upper) {
const size_t seed(12345);
MersenneTwister randGen(seed, lower, upper);
for (size_t iSpec = 0; iSpec < ws->getNumberHistograms(); iSpec++) {
Mantid::MantidVec &Y = ws->dataY(iSpec);
Mantid::MantidVec &E = ws->dataE(iSpec);
for (size_t i = 0; i < Y.size(); i++) {
Y[i] += noise * randGen.nextValue();
E[i] += noise;
}
}
}
//================================================================================================================
/**
* Create a test workspace with a fully defined instrument
* Each spectra will have a cylindrical detector defined 2*cylinder_radius away
* from the centre of the
* previous.
* Data filled with: Y: 2.0, E: sqrt(2.0), X: nbins of width 1 starting at 0
*/
Workspace2D_sptr
create2DWorkspaceWithFullInstrument(int nhist, int nbins, bool includeMonitors,
bool startYNegative, bool isHistogram,
const std::string &instrumentName) {
if (includeMonitors && nhist < 2) {
throw std::invalid_argument("Attempting to 2 include monitors for a "
"workspace with fewer than 2 histograms");
}
Workspace2D_sptr space;
if (isHistogram)
space = Create2DWorkspaceBinned(
nhist, nbins); // A 1:1 spectra is created by default
else
space = Create2DWorkspace123(nhist, nbins, false);
space->setTitle(
"Test histogram"); // actually adds a property call run_title to the logs
space->getAxis(0)->setUnit("TOF");
space->setYUnit("Counts");
boost::shared_ptr<Instrument> testInst(new Instrument(instrumentName));
testInst->setReferenceFrame(
boost::shared_ptr<ReferenceFrame>(new ReferenceFrame(Y, X, Left, "")));
space->setInstrument(testInst);
const double pixelRadius(0.05);
Object_sptr pixelShape = ComponentCreationHelper::createCappedCylinder(
pixelRadius, 0.02, V3D(0.0, 0.0, 0.0), V3D(0., 1.0, 0.), "tube");
const double detXPos(5.0);
int ndets = nhist;
if (includeMonitors)
ndets -= 2;
for (int i = 0; i < ndets; ++i) {
std::ostringstream lexer;
lexer << "pixel-" << i << ")";
Detector *physicalPixel =
new Detector(lexer.str(), space->getAxis(1)->spectraNo(i), pixelShape,
testInst.get());
int ycount(i);
if (startYNegative)
ycount -= 1;
const double ypos = ycount * 2.0 * pixelRadius;
physicalPixel->setPos(detXPos, ypos, 0.0);
testInst->add(physicalPixel);
testInst->markAsDetector(physicalPixel);
space->getSpectrum(i)->addDetectorID(physicalPixel->getID());
}
// Monitors last
if (includeMonitors) // These occupy the last 2 spectra
{
Detector *monitor1 =
new Detector("mon1", space->getAxis(1)->spectraNo(ndets), Object_sptr(),
testInst.get());
monitor1->setPos(-9.0, 0.0, 0.0);
testInst->add(monitor1);
testInst->markAsMonitor(monitor1);
Detector *monitor2 =
new Detector("mon2", space->getAxis(1)->spectraNo(ndets) + 1,
Object_sptr(), testInst.get());
monitor2->setPos(-2.0, 0.0, 0.0);
testInst->add(monitor2);
testInst->markAsMonitor(monitor2);
}
// Define a source and sample position
// Define a source component
ObjComponent *source =
new ObjComponent("moderator", Object_sptr(), testInst.get());
source->setPos(V3D(-20, 0.0, 0.0));
testInst->add(source);
testInst->markAsSource(source);
// Define a sample as a simple sphere
ObjComponent *sample =
new ObjComponent("samplePos", Object_sptr(), testInst.get());
testInst->setPos(0.0, 0.0, 0.0);
testInst->add(sample);
testInst->markAsSamplePos(sample);
return space;
}
//================================================================================================================
/** Create an Workspace2D with an instrument that contains
*RectangularDetector's.
* Bins will be 0.0, 1.0, to numBins, filled with signal=2.0, sqrt(2.0)
*
* @param numBanks :: number of rectangular banks
* @param numPixels :: each bank will be numPixels*numPixels
* @param numBins :: each spectrum will have this # of bins
* @return The EventWorkspace
*/
Mantid::DataObjects::Workspace2D_sptr
create2DWorkspaceWithRectangularInstrument(int numBanks, int numPixels,
int numBins) {
Instrument_sptr inst =
ComponentCreationHelper::createTestInstrumentRectangular(numBanks,
numPixels);
Workspace2D_sptr ws =
Create2DWorkspaceBinned(numBanks * numPixels * numPixels, numBins);
ws->setInstrument(inst);
ws->getAxis(0)->setUnit("dSpacing");
for (size_t wi = 0; wi < ws->getNumberHistograms(); wi++) {
ws->getSpectrum(wi)->setDetectorID(detid_t(numPixels * numPixels + wi));
ws->getSpectrum(wi)->setSpectrumNo(specid_t(wi));
}
return ws;
}
//================================================================================================================
/** Create an Eventworkspace with an instrument that contains
*RectangularDetector's.
* X axis = 100 histogrammed bins from 0.0 in steps of 1.0.
* 200 events per pixel.
*
* @param numBanks :: number of rectangular banks
* @param numPixels :: each bank will be numPixels*numPixels
* @param clearEvents :: if true, erase the events from list
* @return The EventWorkspace
*/
Mantid::DataObjects::EventWorkspace_sptr
createEventWorkspaceWithFullInstrument(int numBanks, int numPixels,
bool clearEvents) {
Instrument_sptr inst =
ComponentCreationHelper::createTestInstrumentRectangular(numBanks,
numPixels);
EventWorkspace_sptr ws =
CreateEventWorkspace2(numBanks * numPixels * numPixels, 100);
ws->setInstrument(inst);
// Set the X axes
MantidVec x = ws->readX(0);
NumericAxis *ax0 = new NumericAxis(x.size());
ax0->setUnit("dSpacing");
for (size_t i = 0; i < x.size(); i++)
ax0->setValue(i, x[i]);
ws->replaceAxis(0, ax0);
// re-assign detector IDs to the rectangular detector
int detID = numPixels * numPixels;
for (int wi = 0; wi < static_cast<int>(ws->getNumberHistograms()); wi++) {
ws->getEventList(wi).clearDetectorIDs();
if (clearEvents)
ws->getEventList(wi).clear(true);
ws->getEventList(wi).setDetectorID(detID);
detID++;
}
return ws;
}
Mantid::DataObjects::EventWorkspace_sptr
createEventWorkspaceWithNonUniformInstrument(int numBanks, bool clearEvents) {
// Number of detectors in a bank as created by createTestInstrumentCylindrical
const int DETECTORS_PER_BANK(9);
Instrument_sptr inst =
ComponentCreationHelper::createTestInstrumentCylindrical(numBanks, false,
0.0025, 0.005);
EventWorkspace_sptr ws =
CreateEventWorkspace2(numBanks * DETECTORS_PER_BANK, 100);
ws->setInstrument(inst);
std::vector<detid_t> detectorIds = inst->getDetectorIDs();
// Should be equal if DETECTORS_PER_BANK is correct
assert(detectorIds.size() == ws->getNumberHistograms());
// Re-assign detector IDs
for (size_t wi = 0; wi < ws->getNumberHistograms(); wi++) {
ws->getEventList(wi).clearDetectorIDs();
if (clearEvents)
ws->getEventList(wi).clear(true);
ws->getEventList(wi).setDetectorID(detectorIds[wi]);
}
return ws;
}
/**
* Create a very small 2D workspace for a virtual reflectometry instrument.
* @return workspace with instrument attached.
* @param startX : X Tof start value for the workspace.
*/
MatrixWorkspace_sptr
create2DWorkspaceWithReflectometryInstrument(double startX) {
Instrument_sptr instrument = boost::make_shared<Instrument>();
instrument->setReferenceFrame(
boost::make_shared<ReferenceFrame>(Y, X, Left, "0,0,0"));
ObjComponent *source = new ObjComponent("source");
source->setPos(V3D(0, 0, 0));
instrument->add(source);
instrument->markAsSource(source);
Detector *monitor = new Detector("Monitor", 1, NULL);
monitor->setPos(14, 0, 0);
instrument->add(monitor);
instrument->markAsMonitor(monitor);
ObjComponent *sample = new ObjComponent("some-surface-holder");
source->setPos(V3D(15, 0, 0));
instrument->add(sample);
instrument->markAsSamplePos(sample);
Detector *det = new Detector("point-detector", 2, NULL);
det->setPos(20, (20 - sample->getPos().X()), 0);
instrument->add(det);
instrument->markAsDetector(det);
const int nSpectra = 2;
const int nBins = 100;
const double deltaX = 2000; // TOF
auto workspace = Create2DWorkspaceBinned(nSpectra, nBins, startX, deltaX);
workspace->setTitle(
"Test histogram"); // actually adds a property call run_title to the logs
workspace->getAxis(0)->setUnit("TOF");
workspace->setYUnit("Counts");
workspace->setInstrument(instrument);
workspace->getSpectrum(0)->addDetectorID(det->getID());
workspace->getSpectrum(1)->addDetectorID(monitor->getID());
return workspace;
}
void createInstrumentForWorkspaceWithDistances(
MatrixWorkspace_sptr workspace, const V3D &samplePosition,
const V3D &sourcePosition, const std::vector<V3D> &detectorPositions) {
Instrument_sptr instrument = boost::make_shared<Instrument>();
instrument->setReferenceFrame(
boost::make_shared<ReferenceFrame>(Y, X, Left, "0,0,0"));
ObjComponent *source = new ObjComponent("source");
source->setPos(sourcePosition);
instrument->add(source);
instrument->markAsSource(source);
ObjComponent *sample = new ObjComponent("sample");
source->setPos(samplePosition);
instrument->add(sample);
instrument->markAsSamplePos(sample);
workspace->setInstrument(instrument);
for (int i = 0; i < static_cast<int>(detectorPositions.size()); ++i) {
std::stringstream buffer;
buffer << "detector_" << i;
Detector *det = new Detector(buffer.str(), i, NULL);
det->setPos(detectorPositions[i]);
instrument->add(det);
instrument->markAsDetector(det);
// Link it to the workspace
workspace->getSpectrum(i)->addDetectorID(det->getID());
}
}
//================================================================================================================
WorkspaceSingleValue_sptr CreateWorkspaceSingleValue(double value) {
WorkspaceSingleValue_sptr retVal(
new WorkspaceSingleValue(value, sqrt(value)));
return retVal;
}
WorkspaceSingleValue_sptr CreateWorkspaceSingleValueWithError(double value,
double error) {
WorkspaceSingleValue_sptr retVal(new WorkspaceSingleValue(value, error));
return retVal;
}
/** Perform some finalization on event workspace stuff */
void EventWorkspace_Finalize(EventWorkspace_sptr ew) {
// get a proton charge
ew->mutableRun().integrateProtonCharge();
}
/** Create event workspace with:
* 500 pixels
* 1000 histogrammed bins.
*/
EventWorkspace_sptr CreateEventWorkspace() {
return CreateEventWorkspace(500, 1001, 100, 1000);
}
/** Create event workspace with:
* numPixels pixels
* numBins histogrammed bins from 0.0 in steps of 1.0
* 200 events; two in each bin, at time 0.5, 1.5, etc.
* PulseTime = 0 second x2, 1 second x2, 2 seconds x2, etc. after 2010-01-01
*/
EventWorkspace_sptr CreateEventWorkspace2(int numPixels, int numBins) {
return CreateEventWorkspace(numPixels, numBins, 100, 0.0, 1.0, 2);
}
/** Create event workspace
*/
EventWorkspace_sptr CreateEventWorkspace(int numPixels, int numBins,
int numEvents, double x0,
double binDelta, int eventPattern,
int start_at_pixelID) {
DateAndTime run_start("2010-01-01T00:00:00");
// add one to the number of bins as this is histogram
numBins++;
EventWorkspace_sptr retVal(new EventWorkspace);
retVal->initialize(numPixels, 1, 1);
// Make fake events
if (eventPattern) // 0 == no events
{
size_t workspaceIndex = 0;
for (int pix = start_at_pixelID + 0; pix < start_at_pixelID + numPixels;
pix++) {
EventList &el = retVal->getEventList(workspaceIndex);
el.setSpectrumNo(pix);
el.setDetectorID(pix);
for (int i = 0; i < numEvents; i++) {
if (eventPattern == 1) // 0, 1 diagonal pattern
el += TofEvent((pix + i + 0.5) * binDelta, run_start + double(i));
else if (eventPattern == 2) // solid 2
{
el += TofEvent((i + 0.5) * binDelta, run_start + double(i));
el += TofEvent((i + 0.5) * binDelta, run_start + double(i));
} else if (eventPattern == 3) // solid 1
{
el += TofEvent((i + 0.5) * binDelta, run_start + double(i));
} else if (eventPattern == 4) // Number of events per bin = pixelId (aka
// workspace index in most cases)
{
for (int q = 0; q < pix; q++)
el += TofEvent((i + 0.5) * binDelta, run_start + double(i));
}
}
workspaceIndex++;
}
}
// Create the x-axis for histogramming.
MantidVecPtr x1;
MantidVec &xRef = x1.access();
xRef.resize(numBins);
for (int i = 0; i < numBins; ++i) {
xRef[i] = x0 + i * binDelta;
}
// Set all the histograms at once.
retVal->setAllX(x1);
return retVal;
}
// =====================================================================================
/** Create event workspace, with several detector IDs in one event list.
*/
EventWorkspace_sptr
CreateGroupedEventWorkspace(std::vector<std::vector<int>> groups, int numBins,
double binDelta) {
EventWorkspace_sptr retVal(new EventWorkspace);
retVal->initialize(1, 2, 1);
for (size_t g = 0; g < groups.size(); g++) {
retVal->getOrAddEventList(g).clearDetectorIDs();
std::vector<int> dets = groups[g];
for (std::vector<int>::iterator it = dets.begin(); it != dets.end(); ++it) {
for (int i = 0; i < numBins; i++)
retVal->getOrAddEventList(g) += TofEvent((i + 0.5) * binDelta, 1);
retVal->getOrAddEventList(g).addDetectorID(*it);
}
}
// Create the x-axis for histogramming.
MantidVecPtr x1;
MantidVec &xRef = x1.access();
double x0 = 0;
xRef.resize(numBins);
for (int i = 0; i < numBins; ++i) {
xRef[i] = x0 + i * binDelta;
}
// Set all the histograms at once.
retVal->setAllX(x1);
return retVal;
}
// =====================================================================================
/** Create an event workspace with randomized TOF and pulsetimes
*
* @param numbins :: # of bins to set. This is also = # of events per EventList
* @param numpixels :: number of pixels
* @param bin_delta :: a constant offset to shift the bin bounds by
* @return EventWorkspace
*/
EventWorkspace_sptr CreateRandomEventWorkspace(size_t numbins, size_t numpixels,
double bin_delta) {
EventWorkspace_sptr retVal(new EventWorkspace);
retVal->initialize(numpixels, numbins, numbins - 1);
// and X-axis for references:
NumericAxis *pAxis0 = new NumericAxis(numbins);
// Create the original X axis to histogram on.
// Create the x-axis for histogramming.
Kernel::cow_ptr<MantidVec> axis;
MantidVec &xRef = axis.access();
xRef.resize(numbins);
for (int i = 0; i < static_cast<int>(numbins); ++i) {
xRef[i] = i * bin_delta;
pAxis0->setValue(i, xRef[i]);
}
pAxis0->setUnit("TOF");
// Make up some data for each pixels
for (size_t i = 0; i < numpixels; i++) {
// Create one event for each bin
EventList &events = retVal->getEventList(static_cast<detid_t>(i));
for (double ie = 0; ie < numbins; ie++) {
// Create a list of events, randomize
events += TofEvent(std::rand(), std::rand());
}
events.addDetectorID(detid_t(i));
}
retVal->setAllX(axis);
retVal->replaceAxis(0, pAxis0);
return retVal;
}
// =====================================================================================
/** Create Workspace2d, with numHist spectra, each with 9 detectors,
* with IDs 1-9, 10-18, 19-27
*/
MatrixWorkspace_sptr CreateGroupedWorkspace2D(size_t numHist, int numBins,
double binDelta) {
Workspace2D_sptr retVal = Create2DWorkspaceBinned(static_cast<int>(numHist),
numBins, 0.0, binDelta);
retVal->setInstrument(
ComponentCreationHelper::createTestInstrumentCylindrical(
static_cast<int>(numHist)));
for (int g = 0; g < static_cast<int>(numHist); g++) {
ISpectrum *spec = retVal->getSpectrum(g);
for (int i = 1; i <= 9; i++)
spec->addDetectorID(g * 9 + i);
spec->setSpectrumNo(g + 1); // Match detector ID and spec NO
}
return boost::dynamic_pointer_cast<MatrixWorkspace>(retVal);
}
// =====================================================================================
// RootOfNumHist == square root of hystohram number;
MatrixWorkspace_sptr
CreateGroupedWorkspace2DWithRingsAndBoxes(size_t RootOfNumHist, int numBins,
double binDelta) {
size_t numHist = RootOfNumHist * RootOfNumHist;
Workspace2D_sptr retVal = Create2DWorkspaceBinned(static_cast<int>(numHist),
numBins, 0.0, binDelta);
retVal->setInstrument(
ComponentCreationHelper::createTestInstrumentCylindrical(
static_cast<int>(numHist)));
for (int g = 0; g < static_cast<int>(numHist); g++) {
ISpectrum *spec = retVal->getSpectrum(g);
for (int i = 1; i <= 9; i++)
spec->addDetectorID(g * 9 + i);
spec->setSpectrumNo(g + 1); // Match detector ID and spec NO
}
return boost::dynamic_pointer_cast<MatrixWorkspace>(retVal);
}
// not strictly creating a workspace, but really helpfull to see what one
// contains
void DisplayDataY(const MatrixWorkspace_sptr ws) {
const size_t numHists = ws->getNumberHistograms();
for (size_t i = 0; i < numHists; ++i) {
std::cout << "Histogram " << i << " = ";
for (size_t j = 0; j < ws->blocksize(); ++j) {
std::cout << ws->readY(i)[j] << " ";
}
std::cout << std::endl;
}
}
void DisplayData(const MatrixWorkspace_sptr ws) { DisplayDataX(ws); }
// not strictly creating a workspace, but really helpfull to see what one
// contains
void DisplayDataX(const MatrixWorkspace_sptr ws) {
const size_t numHists = ws->getNumberHistograms();
for (size_t i = 0; i < numHists; ++i) {
std::cout << "Histogram " << i << " = ";
for (size_t j = 0; j < ws->blocksize(); ++j) {
std::cout << ws->readX(i)[j] << " ";
}
std::cout << std::endl;
}
}
// not strictly creating a workspace, but really helpfull to see what one
// contains
void DisplayDataE(const MatrixWorkspace_sptr ws) {
const size_t numHists = ws->getNumberHistograms();
for (size_t i = 0; i < numHists; ++i) {
std::cout << "Histogram " << i << " = ";
for (size_t j = 0; j < ws->blocksize(); ++j) {
std::cout << ws->readE(i)[j] << " ";
}
std::cout << std::endl;
}
}
// =====================================================================================
/** Utility function to add a TimeSeriesProperty with a name and value
*
* @param runInfo :: Run to add to
* @param name :: property name
* @param val :: value
*/
void AddTSPEntry(Run &runInfo, std::string name, double val) {
TimeSeriesProperty<double> *tsp;
tsp = new TimeSeriesProperty<double>(name);
tsp->addValue("2011-05-24T00:00:00", val);
runInfo.addProperty(tsp);
}
// =====================================================================================
/** Sets the OrientedLattice in the crystal as an crystal with given lattice
*lengths, angles of 90 deg
*
* @param ws :: workspace to set
* @param a :: lattice length
* @param b :: lattice length
* @param c :: lattice length
*/
void SetOrientedLattice(Mantid::API::MatrixWorkspace_sptr ws, double a,
double b, double c) {
OrientedLattice *latt = new OrientedLattice(a, b, c, 90., 90., 90.);
ws->mutableSample().setOrientedLattice(latt);
delete latt;
}
// =====================================================================================
/** Create a default universal goniometer and set its angles
*
* @param ws :: workspace to set
* @param phi :: +Y rotation angle (deg)
* @param chi :: +X rotation angle (deg)
* @param omega :: +Y rotation angle (deg)
*/
void SetGoniometer(Mantid::API::MatrixWorkspace_sptr ws, double phi, double chi,
double omega) {
AddTSPEntry(ws->mutableRun(), "phi", phi);
AddTSPEntry(ws->mutableRun(), "chi", chi);
AddTSPEntry(ws->mutableRun(), "omega", omega);
Mantid::Geometry::Goniometer gm;
gm.makeUniversalGoniometer();
ws->mutableRun().setGoniometer(gm, true);
}
//
Mantid::API::MatrixWorkspace_sptr
createProcessedWorkspaceWithCylComplexInstrument(size_t numPixels,
size_t numBins,
bool has_oriented_lattice) {
size_t rHist = (size_t)sqrt(double(numPixels));
while (rHist * rHist < numPixels)
rHist++;
Mantid::API::MatrixWorkspace_sptr ws =
CreateGroupedWorkspace2DWithRingsAndBoxes(rHist, 10, 0.1);
NumericAxis *pAxis0 = new NumericAxis(numBins);
for (size_t i = 0; i < numBins; i++) {
double dE = -1.0 + static_cast<double>(i) * 0.8;
pAxis0->setValue(i, dE);
}
pAxis0->setUnit("DeltaE");
ws->replaceAxis(0, pAxis0);
if (has_oriented_lattice) {
OrientedLattice *latt = new OrientedLattice(1, 1, 1, 90., 90., 90.);
ws->mutableSample().setOrientedLattice(latt);
delete latt;
AddTSPEntry(ws->mutableRun(), "phi", 0);
AddTSPEntry(ws->mutableRun(), "chi", 0);
AddTSPEntry(ws->mutableRun(), "omega", 0);
Mantid::Geometry::Goniometer gm;
gm.makeUniversalGoniometer();
ws->mutableRun().setGoniometer(gm, true);
}
return ws;
}
/// Create a workspace with all components needed for inelastic analysis and 3
/// detectors in specific places
/// @param L2 -- the sample to detector flight path
/// @param polar -- the detector polar angle
/// @param azimutal -- the detector azimuthal
/// @param numBins -- the number of histogram bins for the workspace
/// @param Emin -- minimal energy transfer
/// @param Emax -- maxinal energy transfer
/// @param Ei -- input beam energy
Mantid::API::MatrixWorkspace_sptr
createProcessedInelasticWS(const std::vector<double> &L2,
const std::vector<double> &polar,
const std::vector<double> &azimutal, size_t numBins,
double Emin, double Emax, double Ei) {
// not used but interface needs it
std::set<int64_t> maskedWorkspaceIndices;
size_t numPixels = L2.size();
Mantid::API::MatrixWorkspace_sptr ws =
Create2DWorkspaceWithValues(uint64_t(numPixels), uint64_t(numBins), true,
maskedWorkspaceIndices, 0, 1, 0.1);
// detectors at L2, sample at 0 and source at -L2_min
ws->setInstrument(
ComponentCreationHelper::createCylInstrumentWithDetInGivenPosisions(
L2, polar, azimutal));
for (int g = 0; g < static_cast<int>(numPixels); g++) {
ISpectrum *spec = ws->getSpectrum(g);
// we just made (in createCylInstrumentWithDetInGivenPosisions) det ID-s to
// start from 1
spec->setDetectorID(g + 1);
// and this is absolutely different nummer, corresponding to det ID just by
// chance ? -- some uncertainties remain
spec->setSpectrumNo(g + 1);
// spec->setSpectrumNo(g+1);
// spec->addDetectorID(g*9);
// spec->setSpectrumNo(g+1); // Match detector ID and spec NO
}
double dE = (Emax - Emin) / double(numBins);
for (size_t j = 0; j < numPixels; j++) {
MantidVec &E_transfer = ws->dataX(j);
for (size_t i = 0; i <= numBins; i++) {
double E = Emin + static_cast<double>(i) * dE;
E_transfer[i] = E;
}
}
// set axis, correspondent to the X-values
NumericAxis *pAxis0 = new NumericAxis(numBins);
MantidVec &E_transfer = ws->dataX(0);
for (size_t i = 0; i < numBins; i++) {
double E = 0.5 * (E_transfer[i] + E_transfer[i + 1]);
pAxis0->setValue(i, E);
}
pAxis0->setUnit("DeltaE");
ws->replaceAxis(0, pAxis0);
// define oriented lattice which requested for processed ws
OrientedLattice *latt = new OrientedLattice(1, 1, 1, 90., 90., 90.);
ws->mutableSample().setOrientedLattice(latt);
delete latt;
// TODO: clarify if this property indeed goes there;
ws->mutableRun().addProperty(new PropertyWithValue<double>("Ei", Ei), true);
// these properties have to be different -> specific for processed ws, as time
// now should be reconciled
AddTSPEntry(ws->mutableRun(), "phi", 0);
AddTSPEntry(ws->mutableRun(), "chi", 0);
AddTSPEntry(ws->mutableRun(), "omega", 0);
Mantid::Geometry::Goniometer gm;
gm.makeUniversalGoniometer();
ws->mutableRun().setGoniometer(gm, true);
return ws;
}
/*
* Create an EventWorkspace from a source EventWorkspace.
* The new workspace should be exactly the same as the source workspace but
* without any events
*/
Mantid::DataObjects::EventWorkspace_sptr
createEventWorkspace3(Mantid::DataObjects::EventWorkspace_const_sptr sourceWS,
std::string wsname, API::Algorithm *alg) {
UNUSED_ARG(wsname);
// 1. Initialize:use dummy numbers for arguments, for event workspace it
// doesn't matter
Mantid::DataObjects::EventWorkspace_sptr outputWS =
Mantid::DataObjects::EventWorkspace_sptr(
new DataObjects::EventWorkspace());
// outputWS->setName(wsname);
outputWS->initialize(1, 1, 1);
// 2. Set the units
outputWS->getAxis(0)->unit() = UnitFactory::Instance().create("TOF");
outputWS->setYUnit("Counts");
outputWS->setTitle("Empty_Title");