-
Notifications
You must be signed in to change notification settings - Fork 122
/
FilterEvents.cpp
1954 lines (1698 loc) · 75.1 KB
/
FilterEvents.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 "MantidAlgorithms/FilterEvents.h"
#include "MantidAPI/AnalysisDataService.h"
#include "MantidAPI/FileProperty.h"
#include "MantidAPI/Run.h"
#include "MantidAPI/SpectrumInfo.h"
#include "MantidAPI/TableRow.h"
#include "MantidAPI/WorkspaceGroup.h"
#include "MantidAPI/WorkspaceProperty.h"
#include "MantidAlgorithms/TimeAtSampleStrategyDirect.h"
#include "MantidAlgorithms/TimeAtSampleStrategyElastic.h"
#include "MantidAlgorithms/TimeAtSampleStrategyIndirect.h"
#include "MantidDataObjects/SplittersWorkspace.h"
#include "MantidDataObjects/TableWorkspace.h"
#include "MantidDataObjects/Workspace2D.h"
#include "MantidDataObjects/WorkspaceCreation.h"
#include "MantidGeometry/Instrument/Goniometer.h"
#include "MantidHistogramData/Histogram.h"
#include "MantidKernel/ArrayProperty.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidKernel/ListValidator.h"
#include "MantidKernel/LogFilter.h"
#include "MantidKernel/PhysicalConstants.h"
#include "MantidKernel/PropertyWithValue.h"
#include "MantidKernel/Strings.h"
#include "MantidKernel/System.h"
#include "MantidKernel/TimeSeriesProperty.h"
#include "MantidKernel/VisibleWhenProperty.h"
#include <memory>
#include <sstream>
using namespace Mantid;
using namespace Mantid::Kernel;
using namespace Mantid::API;
using namespace Mantid::DataObjects;
using namespace Mantid::HistogramData;
using namespace Mantid::Geometry;
using Types::Core::DateAndTime;
using namespace std;
const int64_t TOLERANCE(1000000); // splitter time tolerance in nano-second.
// this value has resolution to 10000Hz
/// (integer) splitting target for undefined region, which will be recorded in
/// m_splitterGroup
const uint32_t UNDEFINED_SPLITTING_TARGET(0);
namespace Mantid::Algorithms {
DECLARE_ALGORITHM(FilterEvents)
/** Constructor
*/
FilterEvents::FilterEvents()
: m_eventWS(), m_splittersWorkspace(), m_splitterTableWorkspace(), m_matrixSplitterWS(), m_detCorrectWorkspace(),
m_useSplittersWorkspace(false), m_useArbTableSplitters(false), m_targetWorkspaceIndexSet(), m_splitters(),
m_outputWorkspacesMap(), m_wsNames(), m_detTofOffsets(), m_detTofFactors(), m_filterByPulseTime(false),
m_informationWS(), m_hasInfoWS(), m_progress(0.), m_outputWSNameBase(), m_toGroupWS(false), m_vecSplitterTime(),
m_vecSplitterGroup(), m_splitSampleLogs(false), m_useDBSpectrum(false), m_dbWSIndex(-1),
m_tofCorrType(NoneCorrect), m_specSkipType(), m_vecSkip(), m_isSplittersRelativeTime(false), m_filterStartTime(0),
m_runStartTime(0) {}
/** Declare Inputs
*/
void FilterEvents::init() {
declareProperty(std::make_unique<API::WorkspaceProperty<EventWorkspace>>("InputWorkspace", "", Direction::Input),
"An input event workspace");
declareProperty(std::make_unique<API::WorkspaceProperty<API::Workspace>>("SplitterWorkspace", "", Direction::Input),
"An input SpilltersWorskpace for filtering");
declareProperty("OutputWorkspaceBaseName", "OutputWorkspace",
"The base name to use for the output workspace. The output "
"workspace names are a combination of this and the index in "
"splitter.");
declareProperty(std::make_unique<WorkspaceProperty<TableWorkspace>>("InformationWorkspace", "", Direction::Input,
PropertyMode::Optional),
"Optional output for the information of each splitter "
"workspace index.");
declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>("OutputTOFCorrectionWorkspace", "TOFCorrectWS",
Direction::Output),
"Name of output workspace for TOF correction factor. ");
declareProperty("FilterByPulseTime", false,
"Filter the event by its pulse time only for slow sample "
"environment log. This option can make execution of "
"algorithm faster. But it lowers precision.");
declareProperty("GroupWorkspaces", false,
"Option to group all the output "
"workspaces. Group name will be "
"OutputWorkspaceBaseName.");
declareProperty("OutputWorkspaceIndexedFrom1", false,
"If selected, the minimum output workspace is indexed from 1 "
"and continuous.");
// TOF correction
vector<string> corrtypes{"None", "Customized", "Direct", "Elastic", "Indirect"};
declareProperty("CorrectionToSample", "None", std::make_shared<StringListValidator>(corrtypes),
"Type of correction on neutron events to sample time from "
"detector time. ");
declareProperty(std::make_unique<WorkspaceProperty<TableWorkspace>>("DetectorTOFCorrectionWorkspace", "",
Direction::Input, PropertyMode::Optional),
"Name of table workspace containing the log "
"time correction factor for each detector. ");
setPropertySettings("DetectorTOFCorrectionWorkspace",
std::make_unique<VisibleWhenProperty>("CorrectionToSample", IS_EQUAL_TO, "Customized"));
auto mustBePositive = std::make_shared<BoundedValidator<double>>();
mustBePositive->setLower(0.0);
declareProperty("IncidentEnergy", EMPTY_DBL(), mustBePositive,
"Value of incident energy (Ei) in meV in direct mode.");
setPropertySettings("IncidentEnergy",
std::make_unique<VisibleWhenProperty>("CorrectionToSample", IS_EQUAL_TO, "Direct"));
// Algorithm to spectra without detectors
vector<string> spec_no_det{"Skip", "Skip only if TOF correction"};
declareProperty("SpectrumWithoutDetector", "Skip", std::make_shared<StringListValidator>(spec_no_det),
"Approach to deal with spectrum without detectors. ");
declareProperty("SplitSampleLogs", true,
"If selected, all sample logs will be splitted by the "
"event splitters. It is not recommended for fast event "
"log splitters. ");
declareProperty("NumberOutputWS", 0, "Number of output output workspace splitted. ", Direction::Output);
declareProperty("DBSpectrum", EMPTY_INT(), "Spectrum (workspace index) for debug purpose. ");
declareProperty(std::make_unique<ArrayProperty<string>>("OutputWorkspaceNames", Direction::Output),
"List of output workspaces names");
declareProperty("RelativeTime", false,
"Flag to indicate that in the input Matrix splitting workspace,"
"the time indicated by X-vector is relative to either run start time or "
"some indicted time.");
declareProperty("FilterStartTime", "", "Start time for splitters that can be parsed to DateAndTime.");
declareProperty(std::make_unique<ArrayProperty<std::string>>("TimeSeriesPropertyLogs"),
"List of name of sample logs of TimeSeriesProperty format. "
"They will be either excluded from splitting if ExcludedSpecifiedLogs is "
"specified as True. Or "
"They will be the only TimeSeriesProperty sample logs that will be split "
"to child workspaces.");
declareProperty("ExcludeSpecifiedLogs", true,
"If true, all the TimeSeriesProperty logs listed will be "
"excluded from duplicating. "
"Otherwise, only those specified logs will be split.");
declareProperty("DescriptiveOutputNames", false,
"If selected, the names of the output workspaces will "
"include information about each slice.");
}
std::map<std::string, std::string> FilterEvents::validateInputs() {
const std::string SPLITER_PROP_NAME = "SplitterWorkspace";
std::map<std::string, std::string> result;
// check the splitters workspace for special behavior
API::Workspace_const_sptr splitter = this->getProperty(SPLITER_PROP_NAME);
// SplittersWorkspace is a special type that needs no further checking
if (bool(std::dynamic_pointer_cast<const SplittersWorkspace>(splitter))) {
if (std::dynamic_pointer_cast<const SplittersWorkspace>(splitter)->rowCount() == 0)
result[SPLITER_PROP_NAME] = "SplittersWorkspace must have rows defined";
} else {
const auto table = std::dynamic_pointer_cast<const TableWorkspace>(splitter);
const auto matrix = std::dynamic_pointer_cast<const MatrixWorkspace>(splitter);
if (bool(table)) {
if (table->columnCount() != 3)
result[SPLITER_PROP_NAME] = "TableWorkspace must have 3 columns";
else if (table->rowCount() == 0)
result[SPLITER_PROP_NAME] = "TableWorkspace must have rows defined";
} else if (bool(matrix)) {
if (matrix->getNumberHistograms() == 1) {
if (!matrix->isHistogramData())
result[SPLITER_PROP_NAME] = "MatrixWorkspace must be histogram";
} else {
result[SPLITER_PROP_NAME] = "MatrixWorkspace can have only one histogram";
}
} else {
result[SPLITER_PROP_NAME] = "Incompatible workspace type";
}
}
const string correctiontype = getPropertyValue("CorrectionToSample");
if (correctiontype == "Direct") {
double ei = getProperty("IncidentEnergy");
if (isEmpty(ei)) {
EventWorkspace_const_sptr inputWS = this->getProperty("InputWorkspace");
if (!inputWS->run().hasProperty("Ei")) {
const string msg("InputWorkspace does not have Ei. Must specify IncidentEnergy");
result["CorrectionToSample"] = msg;
result["IncidentEnergy"] = msg;
}
}
} else if (correctiontype == "Customized") {
TableWorkspace_const_sptr correctionWS = getProperty("DetectorTOFCorrectionWorkspace");
if (!correctionWS) {
const string msg("Must specify correction workspace with CorrectionToSample=Custom");
result["CorrectionToSample"] = msg;
result["DetectorTOFCorrectionWorkspace"] = msg;
}
}
// "None" and "Elastic" and "Indirect" don't require extra information
return result;
}
/** Execution body
*/
void FilterEvents::exec() {
// Process algorithm properties
processAlgorithmProperties();
// Examine workspace for detectors
examineAndSortEventWS();
// Parse splitters
m_progress = 0.0;
progress(m_progress, "Processing SplittersWorkspace.");
if (m_useSplittersWorkspace) // SplittersWorkspace the class in nanoseconds
processSplittersWorkspace();
else if (m_useArbTableSplitters) // TableWorkspace in seconds
processTableSplittersWorkspace();
else
processMatrixSplitterWorkspace();
// Create output workspaces
m_progress = 0.1;
progress(m_progress, "Create Output Workspaces.");
if (m_useArbTableSplitters)
createOutputWorkspacesTableSplitterCase();
else if (m_useSplittersWorkspace)
createOutputWorkspacesSplitters();
else
createOutputWorkspacesMatrixCase();
// clone the properties but TimeSeriesProperty
std::vector<Kernel::TimeSeriesProperty<int> *> int_tsp_vector;
std::vector<Kernel::TimeSeriesProperty<double> *> dbl_tsp_vector;
std::vector<Kernel::TimeSeriesProperty<bool> *> bool_tsp_vector;
std::vector<Kernel::TimeSeriesProperty<string> *> string_tsp_vector;
copyNoneSplitLogs(int_tsp_vector, dbl_tsp_vector, bool_tsp_vector, string_tsp_vector);
// Optionall import corrections
m_progress = 0.20;
progress(m_progress, "Importing TOF corrections. ");
setupDetectorTOFCalibration();
// Filter Events
m_progress = 0.30;
progress(m_progress, "Filter Events.");
double progressamount;
if (m_toGroupWS)
progressamount = 0.6;
else
progressamount = 0.7;
// add a new 'split' tsp to output workspace
std::vector<std::unique_ptr<Kernel::TimeSeriesProperty<int>>> split_tsp_vector;
if (m_useSplittersWorkspace) {
filterEventsBySplitters(progressamount);
generateSplitterTSPalpha(split_tsp_vector);
} else {
filterEventsByVectorSplitters(progressamount);
generateSplitterTSP(split_tsp_vector);
}
// assign split_tsp_vector to all the output workspaces!
mapSplitterTSPtoWorkspaces(split_tsp_vector);
// split times series property: new way to split events
splitTimeSeriesLogs(int_tsp_vector, dbl_tsp_vector, bool_tsp_vector, string_tsp_vector);
// Optional to group detector
groupOutputWorkspace();
// Form the names of output workspaces
std::vector<std::string> outputwsnames;
Goniometer inputGonio = m_eventWS->run().getGoniometer();
for (auto &miter : m_outputWorkspacesMap) {
try {
DataObjects::EventWorkspace_sptr ws_i = miter.second;
ws_i->mutableRun().setGoniometer(inputGonio, true);
} catch (std::runtime_error &) {
g_log.warning("Cannot set goniometer.");
}
outputwsnames.emplace_back(miter.second->getName());
}
setProperty("OutputWorkspaceNames", outputwsnames);
m_progress = 1.0;
progress(m_progress, "Completed");
}
//----------------------------------------------------------------------------------------------
/** Examine whether any spectrum does not have detector
* Warning message will be written out
* @brief FilterEvents::examineEventWS
*/
void FilterEvents::examineAndSortEventWS() {
// get event workspace information
size_t numhist = m_eventWS->getNumberHistograms();
m_vecSkip.resize(numhist, false);
// check whether any detector is skipped
if (m_specSkipType == EventFilterSkipNoDetTOFCorr && m_tofCorrType == NoneCorrect) {
// No TOF correction and skip spectrum only if TOF correction is required
g_log.warning("By user's choice, No spectrum will be skipped even if it has "
"no detector.");
} else {
// check detectors whether there is any of them that will be skipped
stringstream msgss;
size_t numskipspec = 0;
size_t numeventsskip = 0;
const auto &spectrumInfo = m_eventWS->spectrumInfo();
for (size_t i = 0; i < numhist; ++i) {
if (!spectrumInfo.hasDetectors(i)) {
m_vecSkip[i] = true;
++numskipspec;
const EventList &elist = m_eventWS->getSpectrum(i);
numeventsskip += elist.getNumberEvents();
msgss << i;
if (numskipspec % 10 == 0)
msgss << "\n";
else
msgss << ",";
}
} // ENDFOR
if (numskipspec > 0) {
g_log.warning() << "There are " << numskipspec << " spectra that do not have detectors. "
<< "They will be skipped during filtering. There are total " << numeventsskip
<< " events in those spectra. \nList of these specta is as below:\n"
<< msgss.str() << "\n";
} else {
g_log.notice("There is no spectrum that does not have detectors.");
}
} // END-IF-ELSE
// sort events
const auto sortType = m_filterByPulseTime ? DataObjects::PULSETIME_SORT : DataObjects::PULSETIMETOF_SORT;
// This runs the SortEvents algorithm in parallel
m_eventWS->sortAll(sortType, nullptr);
return;
}
//----------------------------------------------------------------------------------------------
/** Process input properties
*/
void FilterEvents::processAlgorithmProperties() {
m_eventWS = this->getProperty("InputWorkspace");
if (!m_eventWS) {
stringstream errss;
errss << "Inputworkspace is not event workspace. ";
g_log.error(errss.str());
throw std::invalid_argument(errss.str());
}
// Process splitting workspace (table or data)
API::Workspace_sptr tempws = this->getProperty("SplitterWorkspace");
m_splittersWorkspace = std::dynamic_pointer_cast<SplittersWorkspace>(tempws);
m_splitterTableWorkspace = std::dynamic_pointer_cast<TableWorkspace>(tempws);
if (m_splittersWorkspace) {
m_useSplittersWorkspace = true;
} else if (m_splitterTableWorkspace)
m_useArbTableSplitters = true;
else {
m_matrixSplitterWS = std::dynamic_pointer_cast<MatrixWorkspace>(tempws);
if (m_matrixSplitterWS) {
m_useSplittersWorkspace = false;
} else {
throw runtime_error("Invalid type of input workspace, neither "
"SplittersWorkspace nor MatrixWorkspace.");
}
}
m_informationWS = this->getProperty("InformationWorkspace");
// Information workspace is specified?
if (!m_informationWS)
m_hasInfoWS = false;
else
m_hasInfoWS = true;
m_outputWSNameBase = this->getPropertyValue("OutputWorkspaceBaseName");
m_filterByPulseTime = this->getProperty("FilterByPulseTime");
m_toGroupWS = this->getProperty("GroupWorkspaces");
if (m_toGroupWS && (m_outputWSNameBase == m_eventWS->getName())) {
std::stringstream errss;
errss << "It is not allowed to group output workspaces into the same name "
"(i..e, OutputWorkspaceBaseName = "
<< m_outputWSNameBase << ") as the input workspace to filter events from.";
throw std::invalid_argument(errss.str());
}
//-------------------------------------------------------------------------
// TOF detector/sample correction
//-------------------------------------------------------------------------
// Type of correction
string correctiontype = getPropertyValue("CorrectionToSample");
if (correctiontype == "None")
m_tofCorrType = NoneCorrect;
else if (correctiontype == "Customized")
m_tofCorrType = CustomizedCorrect;
else if (correctiontype == "Direct")
m_tofCorrType = DirectCorrect;
else if (correctiontype == "Elastic")
m_tofCorrType = ElasticCorrect;
else if (correctiontype == "Indirect")
m_tofCorrType = IndirectCorrect;
else {
g_log.error() << "Correction type '" << correctiontype << "' is not supported. \n";
throw runtime_error("Impossible situation!");
}
// Spectrum skip
string skipappr = getPropertyValue("SpectrumWithoutDetector");
if (skipappr == "Skip")
m_specSkipType = EventFilterSkipNoDet;
else if (skipappr == "Skip only if TOF correction")
m_specSkipType = EventFilterSkipNoDetTOFCorr;
else
throw runtime_error("An unrecognized option for SpectrumWithoutDetector");
m_splitSampleLogs = getProperty("SplitSampleLogs");
// Debug spectrum
m_dbWSIndex = getProperty("DBSpectrum");
if (isEmpty(m_dbWSIndex))
m_useDBSpectrum = false;
else
m_useDBSpectrum = true;
bool start_time_set = false;
// Get run start time
try {
m_runStartTime = m_eventWS->run().startTime();
start_time_set = true;
} catch (std::runtime_error &) {
}
// Splitters are given relative time
m_isSplittersRelativeTime = getProperty("RelativeTime");
if (m_isSplittersRelativeTime) {
// Using relative time
std::string start_time_str = getProperty("FilterStartTime");
if (!start_time_str.empty()) {
// User specifies the filter starting time
Types::Core::DateAndTime temp_shift_time(start_time_str);
m_filterStartTime = temp_shift_time;
} else {
// Retrieve filter starting time from property run_start as default
if (start_time_set) {
m_filterStartTime = m_runStartTime;
} else {
throw std::runtime_error("Input event workspace does not have property run_start. "
"User does not specifiy filter start time."
"Splitters cannot be in reltive time.");
}
}
} // END-IF: m_isSplitterRelativeTime
}
//----------------------------------------------------------------------------------------------
/** group output workspaces
* @brief FilterEvents::groupOutputWorkspace
*/
void FilterEvents::groupOutputWorkspace() {
// return if there is no such need
if (!m_toGroupWS)
return;
// set progress
m_progress = 0.95;
progress(m_progress, "Group workspaces");
std::string groupname = m_outputWSNameBase;
auto groupws = createChildAlgorithm("GroupWorkspaces", 0.95, 1.00, true);
groupws->setAlwaysStoreInADS(true);
groupws->setProperty("InputWorkspaces", m_wsNames);
groupws->setProperty("OutputWorkspace", groupname);
groupws->execute();
if (!groupws->isExecuted()) {
g_log.error("Grouping all output workspaces fails.");
return;
}
// set the group workspace as output workspace
if (!this->existsProperty("OutputWorkspace")) {
declareProperty(
std::make_unique<WorkspaceProperty<WorkspaceGroup>>("OutputWorkspace", groupname, Direction::Output),
"Name of the workspace to be created as the output of grouping ");
}
const AnalysisDataServiceImpl &ads = AnalysisDataService::Instance();
API::WorkspaceGroup_sptr workspace_group = std::dynamic_pointer_cast<WorkspaceGroup>(ads.retrieve(groupname));
if (!workspace_group) {
g_log.error("Unable to retrieve output workspace from algorithm GroupWorkspaces");
return;
}
setProperty("OutputWorkspace", workspace_group);
return;
}
//----------------------------------------------------------------------------------------------
/** Clone the sample logs that will not be split, including single-value and add
* all the
* TimeSeriesProperty sample logs
* to vectors by their type
* @brief FilterEvents::copyNoneSplitLogs
* @param int_tsp_name_vector :: output
* @param dbl_tsp_name_vector :: output
* @param bool_tsp_name_vector :: output
* @param string_tsp_vector :: output
*/
void FilterEvents::copyNoneSplitLogs(std::vector<TimeSeriesProperty<int> *> &int_tsp_name_vector,
std::vector<TimeSeriesProperty<double> *> &dbl_tsp_name_vector,
std::vector<TimeSeriesProperty<bool> *> &bool_tsp_name_vector,
std::vector<Kernel::TimeSeriesProperty<string> *> &string_tsp_vector) {
// get the user input information
bool exclude_listed_logs = getProperty("ExcludeSpecifiedLogs");
std::vector<std::string> tsp_logs = getProperty("TimeSeriesPropertyLogs");
// convert to set
std::set<std::string> tsp_logs_set(tsp_logs.begin(), tsp_logs.end());
std::set<std::string>::iterator set_iter;
// initialize
int_tsp_name_vector.clear();
dbl_tsp_name_vector.clear();
bool_tsp_name_vector.clear();
std::vector<Property *> prop_vector = m_eventWS->run().getProperties();
for (auto *prop_i : prop_vector) {
// get property
std::string name_i = prop_i->name();
// cast to different type of TimeSeriesProperties
auto *dbl_prop = dynamic_cast<TimeSeriesProperty<double> *>(prop_i);
auto *int_prop = dynamic_cast<TimeSeriesProperty<int> *>(prop_i);
auto *bool_prop = dynamic_cast<TimeSeriesProperty<bool> *>(prop_i);
auto *string_prop = dynamic_cast<TimeSeriesProperty<string> *>(prop_i);
// check for time series properties
if (dbl_prop || int_prop || bool_prop || string_prop) {
// check whether the log is there
set_iter = tsp_logs_set.find(name_i);
if (exclude_listed_logs && set_iter != tsp_logs_set.end()) {
// exclude all the listed tsp logs and this log name is in the set
// skip
g_log.warning() << "Skip splitting sample log " << name_i << "\n";
continue;
} else if (!exclude_listed_logs && set_iter == tsp_logs_set.end()) {
// include all the listed tsp logs to split but this log name is NOT in
// the set
// skip
g_log.warning() << "Skip splitting sample log " << name_i << "\n";
continue;
}
// insert the time series property to proper target vector
if (dbl_prop) {
// is double time series property
dbl_tsp_name_vector.emplace_back(dbl_prop);
} else if (int_prop) {
// is integer time series property
int_tsp_name_vector.emplace_back(int_prop);
} else if (bool_prop) {
// is integer time series property
bool_tsp_name_vector.emplace_back(bool_prop);
continue;
} else if (string_prop) {
// is string time series property
string_tsp_vector.emplace_back(string_prop);
}
} else {
// non time series properties
// single value property: copy to the new workspace
std::map<int, DataObjects::EventWorkspace_sptr>::iterator ws_iter;
for (ws_iter = m_outputWorkspacesMap.begin(); ws_iter != m_outputWorkspacesMap.end(); ++ws_iter) {
std::string value_i = prop_i->value();
double double_v;
int int_v;
if (Strings::convert(value_i, double_v) != 0) // double value
ws_iter->second->mutableRun().addProperty(name_i, double_v, true);
else if (Strings::convert(value_i, int_v) != 0)
ws_iter->second->mutableRun().addProperty(name_i, int_v, true);
else
ws_iter->second->mutableRun().addProperty(name_i, value_i, true);
}
}
} // end for
return;
}
//----------------------------------------------------------------------------------------------
/** Split ALL the TimeSeriesProperty sample logs to all the output workspace
* @brief FilterEvents::splitTimeSeriesLogs
* @param int_tsp_vector :: vector of itneger tps
* @param dbl_tsp_vector :: vector of double tsp
* @param bool_tsp_vector :: vector of boolean tsp
* @param string_tsp_vector :: vector of string tsp
*/
void FilterEvents::splitTimeSeriesLogs(const std::vector<TimeSeriesProperty<int> *> &int_tsp_vector,
const std::vector<TimeSeriesProperty<double> *> &dbl_tsp_vector,
const std::vector<TimeSeriesProperty<bool> *> &bool_tsp_vector,
const std::vector<TimeSeriesProperty<string> *> &string_tsp_vector) {
// get split times by converting vector of int64 to Time
std::vector<Types::Core::DateAndTime> split_datetime_vec;
// convert splitters workspace to vectors used by TableWorkspace and
// MatrixWorkspace splitters
if (m_useSplittersWorkspace) {
convertSplittersWorkspaceToVectors();
}
// convert splitter time vector to DateAndTime format
split_datetime_vec.resize(m_vecSplitterTime.size());
for (size_t i = 0; i < m_vecSplitterTime.size(); ++i) {
DateAndTime split_time(m_vecSplitterTime[i]);
split_datetime_vec[i] = split_time;
}
// find the maximum index of the outputs' index
std::set<int>::iterator target_iter;
int max_target_index = 0;
for (target_iter = m_targetWorkspaceIndexSet.begin(); target_iter != m_targetWorkspaceIndexSet.end(); ++target_iter) {
if (*target_iter > max_target_index)
max_target_index = *target_iter;
}
g_log.information() << "Maximum target index = " << max_target_index << "\n";
// splitters workspace need to have 1 more for left-over events
if (m_useSplittersWorkspace)
++max_target_index;
// deal with integer time series property
for (const auto &int_tsp : int_tsp_vector) {
splitTimeSeriesProperty(int_tsp, split_datetime_vec, max_target_index);
}
// split double time series property
for (const auto &dbl_tsp : dbl_tsp_vector) {
splitTimeSeriesProperty(dbl_tsp, split_datetime_vec, max_target_index);
}
// deal with bool time series property
for (const auto &bool_tsp : bool_tsp_vector) {
splitTimeSeriesProperty(bool_tsp, split_datetime_vec, max_target_index);
}
// deal with string time series property
for (const auto &string_tsp : string_tsp_vector) {
splitTimeSeriesProperty(string_tsp, split_datetime_vec, max_target_index);
}
// integrate proton charge
for (int tindex = 0; tindex <= max_target_index; ++tindex) {
// find output workspace
std::map<int, DataObjects::EventWorkspace_sptr>::iterator wsiter;
wsiter = m_outputWorkspacesMap.find(tindex);
if (wsiter == m_outputWorkspacesMap.end()) {
g_log.information() << "Workspace target (indexed as " << tindex << ") does not have workspace associated.\n";
} else {
DataObjects::EventWorkspace_sptr ws_i = wsiter->second;
if (ws_i->run().hasProperty("proton_charge")) {
ws_i->mutableRun().integrateProtonCharge();
}
}
}
return;
}
//----------------------------------------------------------------------------------------------
/** split one single time-series property (template)
* @brief FilterEvents::splitTimeSeriesProperty
* @param tsp :: a time series property instance
* @param split_datetime_vec :: splitter
* @param max_target_index :: maximum number of separated time series
*/
template <typename TYPE>
void FilterEvents::splitTimeSeriesProperty(Kernel::TimeSeriesProperty<TYPE> *tsp,
std::vector<Types::Core::DateAndTime> &split_datetime_vec,
const int max_target_index) {
// skip the sample logs if they are specified
// get property name and etc
const std::string &property_name = tsp->name();
// generate new propertys for the source to split to
std::vector<std::unique_ptr<TimeSeriesProperty<TYPE>>> output_vector;
for (int tindex = 0; tindex <= max_target_index; ++tindex) {
auto new_property = std::make_unique<TimeSeriesProperty<TYPE>>(property_name);
new_property->setUnits(tsp->units());
output_vector.emplace_back(std::move(new_property));
}
// duplicate the time series property if the size is just one
if (tsp->size() == 1) {
// duplicate
for (size_t i_out = 0; i_out < output_vector.size(); ++i_out) {
output_vector[i_out]->addValue(tsp->firstTime(), tsp->firstValue());
}
} else {
// split log
std::vector<TimeSeriesProperty<TYPE> *> split_properties(output_vector.size());
// use vector of raw pointers for splitting
std::transform(output_vector.begin(), output_vector.end(), split_properties.begin(),
[](const std::unique_ptr<TimeSeriesProperty<TYPE>> &x) { return x.get(); });
tsp->splitByTimeVector(split_datetime_vec, m_vecSplitterGroup, split_properties);
}
// assign to output workspaces
for (int tindex = 0; tindex <= max_target_index; ++tindex) {
// find output workspace
auto wsiter = m_outputWorkspacesMap.find(tindex);
if (wsiter == m_outputWorkspacesMap.end()) {
// unable to find workspace associated with target index
g_log.information() << "Workspace target (" << tindex << ") does not have workspace associated."
<< "\n";
} else {
// add property to the associated workspace
DataObjects::EventWorkspace_sptr ws_i = wsiter->second;
ws_i->mutableRun().addProperty(std::move(output_vector[tindex]), true);
}
}
return;
}
//----------------------------------------------------------------------------------------------
/** Purpose:
* Convert SplitterWorkspace object to TimeSplitterType (sorted vector)
* and create a map for all workspace group number
* Requirements:
* Gaurantees:
* - Update of m_maxTargetIndex: it can be zero in SplittersWorkspace case
* @brief FilterEvents::processSplittersWorkspace
*/
void FilterEvents::processSplittersWorkspace() {
// 1. Init data structure
size_t numsplitters = m_splittersWorkspace->getNumberSplitters();
m_splitters.reserve(numsplitters);
// 2. Insert all splitters
m_maxTargetIndex = 0;
bool inorder = true;
for (size_t i = 0; i < numsplitters; i++) {
// push back the splitter in SplittersWorkspace to list of splitters
m_splitters.emplace_back(m_splittersWorkspace->getSplitter(i));
// add the target workspace index to target workspace indexes set
m_targetWorkspaceIndexSet.insert(m_splitters.back().index());
// register for the maximum target index
if (m_splitters.back().index() > m_maxTargetIndex)
m_maxTargetIndex = m_splitters.back().index();
// check whether the splitters are in time order
if (inorder && i > 0 && m_splitters[i] < m_splitters[i - 1])
inorder = false;
}
m_progress = 0.05;
progress(m_progress);
// 3. Order if not ordered and add workspace for events excluded
if (!inorder) {
std::sort(m_splitters.begin(), m_splitters.end());
}
// 4. Add extra workgroup index for unfiltered events
m_targetWorkspaceIndexSet.insert(-1);
// 5. Add information
if (m_hasInfoWS) {
if (m_targetWorkspaceIndexSet.size() > m_informationWS->rowCount() + 1) {
g_log.warning() << "Input Splitters Workspace has different entries (" << m_targetWorkspaceIndexSet.size() - 1
<< ") than input information workspaces (" << m_informationWS->rowCount() << "). "
<< " Information may not be accurate. \n";
}
}
}
//----------------------------------------------------------------------------------------------
/** Convert SplittersWorkspace to vector of time and vector of target (itarget)
* NOTE: This is designed to use a single vector/vector splitters for all types
* of inputs
* It is not used before vast experiment on speed comparison!
* @brief FilterEvents::convertSplittersWorkspaceToVectors
*/
void FilterEvents::convertSplittersWorkspaceToVectors() {
// check: only applied for splitters given by SplittersWorkspace
assert(m_useSplittersWorkspace);
// clear and get ready
m_vecSplitterGroup.clear();
m_vecSplitterTime.clear();
// define filter-left target index
int no_filter_index = m_maxTargetIndex + 1;
// convert SplittersWorkspace to a set of pairs which can be sorted
size_t num_splitters = m_splitters.size();
int64_t last_entry_time(0);
// it is assumed that m_splitters is sorted by time
for (size_t i_splitter = 0; i_splitter < num_splitters; ++i_splitter) {
// get splitter
Kernel::SplittingInterval splitter = m_splitters[i_splitter];
int64_t start_time_i64 = splitter.start().totalNanoseconds();
int64_t stop_time_i64 = splitter.stop().totalNanoseconds();
if (m_vecSplitterTime.empty()) {
// first entry: add
m_vecSplitterTime.emplace_back(start_time_i64);
m_vecSplitterTime.emplace_back(stop_time_i64);
m_vecSplitterGroup.emplace_back(splitter.index());
} else if (abs(last_entry_time - start_time_i64) < TOLERANCE) {
// start time is SAME as last entry
m_vecSplitterTime.emplace_back(stop_time_i64);
m_vecSplitterGroup.emplace_back(splitter.index());
} else if (start_time_i64 > last_entry_time + TOLERANCE) {
// start time is way behind. then add an empty one
m_vecSplitterTime.emplace_back(start_time_i64);
m_vecSplitterTime.emplace_back(stop_time_i64);
m_vecSplitterGroup.emplace_back(no_filter_index);
m_vecSplitterGroup.emplace_back(splitter.index());
} else {
// some impossible situation
std::stringstream errorss;
errorss << "New start time " << start_time_i64 << " is before last entry's time " << last_entry_time;
throw std::runtime_error(errorss.str());
}
// update
last_entry_time = m_vecSplitterTime.back();
} // END-FOR (add all splitters)
return;
}
//----------------------------------------------------------------------------------------------
/**
* @brief FilterEvents::processMatrixSplitterWorkspace
* Purpose:
* Convert the splitters in MatrixWorkspace to m_vecSplitterTime and
* m_vecSplitterGroup
* Requirements:
* m_matrixSplitterWS has valid value
* vecX's size must be one larger than and that of vecY of m_matrixSplitterWS
* Guarantees
* - Splitters stored in m_matrixSpliterWS are transformed to
* "m_vecSplitterTime" and "m_vecSplitterGroup", whose sizes differ by 1.
* - Y values are mapped to integer group index stored in "m_vecSplitterGroup".
* The mapping is recorded in "m_yIndexMap" and "m_wsGroupdYMap"
* "m_maxTargetIndex" is used to register the maximum group index
* Negative Y is defined as "undefined"
* Note: there is NO undefined split region here, while any NEGATIVE Y value is
* defined as "undefined splitter"
*/
void FilterEvents::processMatrixSplitterWorkspace() {
// Check input workspace validity
assert(m_matrixSplitterWS);
const auto X = m_matrixSplitterWS->binEdges(0);
const auto &Y = m_matrixSplitterWS->y(0);
const size_t sizex = X.size();
const size_t sizey = Y.size();
// Assign vectors for time comparison
m_vecSplitterTime.assign(sizex, static_cast<int64_t>(0));
m_vecSplitterGroup.assign(sizey, static_cast<int>(-1));
// Transform vector
for (size_t i = 0; i < sizex; ++i) {
m_vecSplitterTime[i] = static_cast<int64_t>(X[i] * 1.E9);
}
// shift the splitters' time if user specifis that the input times are
// relative
if (m_isSplittersRelativeTime) {
const int64_t time_shift_ns = m_filterStartTime.totalNanoseconds();
for (size_t i = 0; i < sizex; ++i)
m_vecSplitterTime[i] += time_shift_ns;
}
// process the group
uint32_t max_target_index = 1;
for (size_t i = 0; i < sizey; ++i) {
auto y_index = static_cast<int>(Y[i]);
// try to find Y[i] in m_yIndexMap
auto mapiter = m_yIndexMap.find(y_index);
if (mapiter == m_yIndexMap.end()) {
// new
// default to 0 as undefined slot.
uint32_t int_target = UNDEFINED_SPLITTING_TARGET;
// if well-defined, then use the current
if (y_index >= 0) {
int_target = max_target_index;
++max_target_index;
}
// un-defined or un-filtered
m_vecSplitterGroup[i] = int_target;
// add to maps and etc.
m_yIndexMap.emplace(y_index, int_target);
m_wsGroupdYMap.emplace(int_target, y_index);
m_targetWorkspaceIndexSet.insert(int_target);
} else {
// this target Y-index has been registered previously
uint32_t target_index = mapiter->second;
m_vecSplitterGroup[i] = target_index;
}
}
// register the max target integer
m_maxTargetIndex = max_target_index - 1;
return;
}
namespace {
// offset_ns - an offset from the GPS epoch
int64_t timeInSecondsToNanoseconds(const int64_t offset_ns, const double time_sec) {
return offset_ns + static_cast<int64_t>(time_sec * 1.E9);
}
} // anonymous namespace
//----------------------------------------------------------------------------------------------
/** process the input splitters given by a TableWorkspace
* The method will transfer the start/stop time to "m_vecSplitterTime"
* and map the splitting target (in string) to "m_vecSplitterGroup".
* The mapping will be recorded in "m_targetIndexMap" and
* "m_wsGroupIndexTargetMap".
* Also, "m_maxTargetIndex" is set up to record the highest target group/index,
* i.e., max value of m_vecSplitterGroup
*/
void FilterEvents::processTableSplittersWorkspace() {
// check input workspace's validity
assert(m_splitterTableWorkspace);
if (m_splitterTableWorkspace->columnCount() != 3) {
throw std::runtime_error("Splitters given in TableWorkspace must have 3 columns.");
}
// clear vector splitterTime and vector of splitter group
m_vecSplitterTime.clear();
m_vecSplitterGroup.clear();
bool found_undefined_splitter = false;
// get the run start time
int64_t filter_shift_time(0);
if (m_isSplittersRelativeTime)
filter_shift_time = m_runStartTime.totalNanoseconds();
int max_target_index = 1;
// convert TableWorkspace's values to vectors
size_t num_rows = m_splitterTableWorkspace->rowCount();
for (size_t irow = 0; irow < num_rows; ++irow) {
// get start and stop time in second
const auto start_time =
timeInSecondsToNanoseconds(filter_shift_time, m_splitterTableWorkspace->cell_cast<double>(irow, 0));
const auto stop_time =
timeInSecondsToNanoseconds(filter_shift_time, m_splitterTableWorkspace->cell_cast<double>(irow, 1));
const auto target = m_splitterTableWorkspace->cell<std::string>(irow, 2);
if (m_vecSplitterTime.empty()) {
// first splitter: push the start time to vector
m_vecSplitterTime.emplace_back(start_time);
} else if (start_time - m_vecSplitterTime.back() > TOLERANCE) {
// the start time is way behind previous splitter's stop time
// create a new splitter and set the time interval in the middle to target
// -1
m_vecSplitterTime.emplace_back(start_time);
// NOTE: use index = 0 for un-defined slot
m_vecSplitterGroup.emplace_back(UNDEFINED_SPLITTING_TARGET);
found_undefined_splitter = true;
} else if (abs(start_time - m_vecSplitterTime.back()) < TOLERANCE) {
// new splitter's start time is same (within tolerance) as the stop time