/
GenerateEventsFilter.cpp
1940 lines (1698 loc) · 67.4 KB
/
GenerateEventsFilter.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
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidAlgorithms/GenerateEventsFilter.h"
#include "MantidKernel/System.h"
#include "MantidKernel/ListValidator.h"
#include "MantidAPI/TableRow.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidAPI/WorkspaceProperty.h"
#include "MantidAPI/Column.h"
#include "MantidKernel/VisibleWhenProperty.h"
#include "MantidKernel/ArrayProperty.h"
using namespace Mantid;
using namespace Mantid::Kernel;
using namespace Mantid::API;
using namespace std;
namespace Mantid {
namespace Algorithms {
DECLARE_ALGORITHM(GenerateEventsFilter)
//----------------------------------------------------------------------------------------------
/** Constructor
*/
GenerateEventsFilter::GenerateEventsFilter() {}
//----------------------------------------------------------------------------------------------
/** Destructor
*/
GenerateEventsFilter::~GenerateEventsFilter() {}
//----------------------------------------------------------------------------------------------
/** Declare input
*/
void GenerateEventsFilter::init() {
// Input/Output Workspaces
declareProperty(new API::WorkspaceProperty<DataObjects::EventWorkspace>(
"InputWorkspace", "", Direction::Input),
"An input event workspace");
declareProperty(new API::WorkspaceProperty<API::Workspace>(
"OutputWorkspace", "", Direction::Output),
"The name to use for the output SplittersWorkspace object, "
"i.e., the filter.");
declareProperty(
new API::WorkspaceProperty<API::ITableWorkspace>("InformationWorkspace",
"", Direction::Output),
"Optional output for the information of each splitter workspace index");
declareProperty(
"FastLog", false,
"Fast log will make output workspace to be a maxtrix workspace. ");
// Time (general) range
declareProperty(
"StartTime", "",
"The start time, such that all event before this time are filtered out. "
"It could be (1) relative time to run start time "
"in unit as specified property 'UnitOfTime' or "
"(2) absolute time. "
"Absolute time takes a string in format as 1990-01-01T00:00:00, "
"while the relative time takes integer or float. ");
declareProperty(
"StopTime", "",
"The stop time, such that all events after this time are filtered out. "
"It could be (1) relative time to run start time "
"in unit as specified property 'UnitOfTime' or "
"(2) absolute time. "
"Absolute time takes a string in format as 1990-01-01T00:00:00, "
"while the relative time takes integer or float. ");
// Split by time (only) in steps
declareProperty(new ArrayProperty<double>("TimeInterval"),
"Array for lengths of time intervals for splitters. "
"If the array is empty, then there will be one splitter "
"created from StartTime and StopTime. "
"If the array has one value, then all splitters will have "
"same time intervals. "
"If the size of the array is larger than one, then the "
"splitters can have various time interval values.");
setPropertySettings("TimeInterval",
new VisibleWhenProperty("LogName", IS_EQUAL_TO, ""));
std::vector<std::string> timeoptions;
timeoptions.push_back("Seconds");
timeoptions.push_back("Nanoseconds");
timeoptions.push_back("Percent");
declareProperty(
"UnitOfTime", "Seconds",
boost::make_shared<Kernel::StringListValidator>(timeoptions),
"StartTime, StopTime and DeltaTime can be given in various unit."
"The unit can be 'Seconds' or 'Nanoseconds' from run start time."
"They can also be defined as 'Percentage' of total run time.");
// Split by log value (only) in steps
declareProperty(
"LogName", "",
"Name of the sample log to use to filter.\n"
"For example, the pulse charge is recorded in 'ProtonCharge'.");
declareProperty("MinimumLogValue", EMPTY_DBL(),
"Minimum log value for which to keep events.");
setPropertySettings("MinimumLogValue",
new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, ""));
declareProperty("MaximumLogValue", EMPTY_DBL(),
"Maximum log value for which to keep events.");
setPropertySettings("MaximumLogValue",
new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, ""));
declareProperty("LogValueInterval", EMPTY_DBL(),
"Delta of log value to be sliced into from min log value and "
"max log value.\n"
"If not given, then only value ");
setPropertySettings("LogValueInterval",
new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, ""));
std::vector<std::string> filteroptions;
filteroptions.push_back("Both");
filteroptions.push_back("Increase");
filteroptions.push_back("Decrease");
declareProperty(
"FilterLogValueByChangingDirection", "Both",
boost::make_shared<Kernel::StringListValidator>(filteroptions),
"d(log value)/dt can be positive and negative. They can be put to "
"different splitters."
"There are 3 options, 'Both', 'Increase' and 'Decrease' corresponding to "
"d(log value)/dt can be any value, positive only and negative only "
"respectively.");
setPropertySettings("FilterLogValueByChangingDirection",
new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, ""));
declareProperty("TimeTolerance", 0.0,
"Tolerance in time for the event times to keep. "
"It is used in the case to filter by single value.");
setPropertySettings("TimeTolerance",
new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, ""));
vector<string> logboundoptions;
logboundoptions.push_back("Centre");
logboundoptions.push_back("Left");
logboundoptions.push_back("Other");
auto logvalidator = boost::make_shared<StringListValidator>(logboundoptions);
declareProperty(
"LogBoundary", "Centre", logvalidator,
"How to treat log values as being measured in the centre of time. "
"There are three options, 'Centre', 'Left' and 'Other'. ");
setPropertySettings("LogBoundary",
new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, ""));
declareProperty("LogValueTolerance", EMPTY_DBL(),
"Tolerance of the log value to be included in filter. It is "
"used in the case to filter by multiple values.");
setPropertySettings("LogValueTolerance",
new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, ""));
// Output workspaces' title and name
declareProperty(
"TitleOfSplitters", "",
"Title of output splitters workspace and information workspace.");
// Linear or parallel
vector<string> processoptions;
processoptions.push_back("Serial");
processoptions.push_back("Parallel");
auto procvalidator = boost::make_shared<StringListValidator>(processoptions);
declareProperty(
"UseParallelProcessing", "Serial", procvalidator,
"Use multiple cores to generate events filter by log values. \n"
"Serial: Use a single core. Good for slow log. \n"
"Parallel: Use multiple cores. Appropriate for fast log. ");
declareProperty("NumberOfThreads", EMPTY_INT(),
"Number of threads forced to use in the parallel mode. ");
return;
}
//----------------------------------------------------------------------------------------------
/** Main execute body
*/
void GenerateEventsFilter::exec() {
// Process input properties
processInOutWorkspaces();
// Get Time
processInputTime();
double prog = 0.1;
progress(prog);
// Get Log
std::string logname = this->getProperty("LogName");
if (logname.empty()) {
// Set up filters by time only
setFilterByTimeOnly();
} else {
// Set up filters by log value in time range
setFilterByLogValue(logname);
}
// Set output workspaces
if (m_forFastLog) {
if (m_useParallel) {
generateSplittersInMatrixWorkspaceParallel();
} else {
generateSplittersInMatrixWorkspace();
}
setProperty("OutputWorkspace", m_filterWS);
} else {
generateSplittersInSplitterWS();
setProperty("OutputWorkspace", m_splitWS);
}
setProperty("InformationWorkspace", m_filterInfoWS);
return;
}
//----------------------------------------------------------------------------------------------
/** Process user properties
*/
void GenerateEventsFilter::processInOutWorkspaces() {
// Input data workspace
m_dataWS = this->getProperty("InputWorkspace");
// Output splitter information workspace
std::string title = getProperty("TitleOfSplitters");
if (title.size() == 0) {
// Using default
title = "Splitters";
}
m_filterInfoWS =
API::WorkspaceFactory::Instance().createTable("TableWorkspace");
m_filterInfoWS->setTitle(title);
m_filterInfoWS->addColumn("int", "workspacegroup");
m_filterInfoWS->addColumn("str", "title");
// Output Splitters workspace: MatrixWorkspace (optioned) will be generated in
// last step
m_forFastLog = getProperty("FastLog");
if (!m_forFastLog) {
m_splitWS = boost::shared_ptr<DataObjects::SplittersWorkspace>(
new DataObjects::SplittersWorkspace());
m_splitWS->setTitle(title);
}
string algtype = getPropertyValue("UseParallelProcessing");
if (algtype == "Serial")
m_useParallel = false;
else if (algtype == "Parallel")
m_useParallel = true;
else
throw std::runtime_error(
"Impossible to have 3rd type other than Serial and Parallel. ");
// Conflict
if (m_useParallel && !m_forFastLog) {
g_log.warning("Parallelization is for fast log only. Automatically turn "
"FastLog on. ");
m_forFastLog = true;
}
return;
}
//----------------------------------------------------------------------------------------------
/** Process the input for time. A smart but complicated default rule
* (1) Input time can be in multiple format: absolute time (ISO), relative time
* (double)
*/
void GenerateEventsFilter::processInputTime() {
// Get input
std::string s_inpt0 = this->getProperty("StartTime");
std::string s_inptf = this->getProperty("StopTime");
// Default
bool defaultstart = (s_inpt0.size() == 0);
bool defaultstop = (s_inptf.size() == 0);
// Determine format
bool instringformat = true;
if (!defaultstart && s_inpt0.find(':') == std::string::npos) {
// StartTime is not empty and does not contain ":": not ISO
instringformat = false;
} else if (!defaultstop && s_inptf.find(':') == std::string::npos) {
// StopTime is not empty and does not contain ":": not ISO format
instringformat = false;
}
// Obtain run time range
DateAndTime runstarttime = m_dataWS->run().startTime();
m_runEndTime = findRunEnd();
// Obtain time unit converter
std::string timeunit = this->getProperty("UnitOfTime");
m_timeUnitConvertFactorToNS = -1.0;
if (timeunit.compare("Seconds") == 0) {
// (second)
m_timeUnitConvertFactorToNS = 1.0E9;
} else if (timeunit.compare("Nanoseconds") == 0) {
// (nano-seconds)
m_timeUnitConvertFactorToNS = 1.0;
} else if (timeunit.compare("Percent") == 0) {
// (percent of total run time)
int64_t runtime_ns =
m_runEndTime.totalNanoseconds() - runstarttime.totalNanoseconds();
double runtimed_ns = static_cast<double>(runtime_ns);
m_timeUnitConvertFactorToNS = 0.01 * runtimed_ns;
} else {
// (Not defined/supported)
stringstream errss;
errss << "TimeType " << timeunit << " is not supported.";
throw std::runtime_error(errss.str());
}
// Set up start time
if (defaultstart) {
// Default
m_startTime = runstarttime;
} else if (instringformat) {
// Time is absolute time in ISO format
m_startTime = DateAndTime(s_inpt0);
} else {
// Relative time in double.
double inpt0 = atof(s_inpt0.c_str());
if (inpt0 < 0) {
stringstream errss;
errss << "Input relative StartTime " << inpt0 << " cannot be negative. ";
throw std::invalid_argument(errss.str());
}
int64_t t0_ns = runstarttime.totalNanoseconds() +
static_cast<int64_t>(inpt0 * m_timeUnitConvertFactorToNS);
m_startTime = Kernel::DateAndTime(t0_ns);
}
// Set up run stop time
if (defaultstop) {
// Default
m_stopTime = m_runEndTime;
} else if (instringformat) {
// Absolute time in ISO format
m_stopTime = DateAndTime(s_inptf);
} else {
// Relative time in double
double inptf = atof(s_inptf.c_str());
int64_t tf_ns = runstarttime.totalNanoseconds() +
static_cast<int64_t>(inptf * m_timeUnitConvertFactorToNS);
m_stopTime = Kernel::DateAndTime(tf_ns);
}
// Check start/stop time
if (m_startTime.totalNanoseconds() >= m_stopTime.totalNanoseconds()) {
stringstream errss;
errss << "Input StartTime " << m_startTime.toISO8601String()
<< " is equal or later than "
<< "input StopTime " << m_stopTime.toFormattedString();
throw runtime_error(errss.str());
}
g_log.information() << "Filter: StartTime = " << m_startTime
<< ", StopTime = " << m_stopTime
<< "; Run start = " << runstarttime.toISO8601String()
<< ", Run stop = " << m_runEndTime.toISO8601String()
<< "\n";
return;
}
//----------------------------------------------------------------------------------------------
/** Set splitters by time value / interval only
*/
void GenerateEventsFilter::setFilterByTimeOnly() {
vector<double> vec_timeintervals = this->getProperty("TimeInterval");
bool singleslot = false;
if (vec_timeintervals.size() == 0)
singleslot = true;
// Progress
int64_t totaltime =
m_stopTime.totalNanoseconds() - m_startTime.totalNanoseconds();
g_log.warning() << "Filter by time: start @ "
<< m_startTime.totalNanoseconds() << "; "
<< "stop @ " << m_stopTime.totalNanoseconds() << "\n";
if (singleslot) {
int wsindex = 0;
// Default and thus just one interval
std::stringstream ss;
ss << "Time Interval From " << m_startTime << " to " << m_stopTime;
addNewTimeFilterSplitter(m_startTime, m_stopTime, wsindex, ss.str());
} else if (vec_timeintervals.size() == 1) {
double timeinterval = vec_timeintervals[0];
int64_t timeslot = 0;
// Explicitly N time intervals
int64_t deltatime_ns =
static_cast<int64_t>(timeinterval * m_timeUnitConvertFactorToNS);
int64_t curtime_ns = m_startTime.totalNanoseconds();
int wsindex = 0;
while (curtime_ns < m_stopTime.totalNanoseconds()) {
// Calculate next.time
int64_t nexttime_ns = curtime_ns + deltatime_ns;
if (nexttime_ns > m_stopTime.totalNanoseconds())
nexttime_ns = m_stopTime.totalNanoseconds();
// Create splitter and information
Kernel::DateAndTime t0(curtime_ns);
Kernel::DateAndTime tf(nexttime_ns);
std::stringstream ss;
ss << "Time Interval From " << t0 << " to " << tf;
addNewTimeFilterSplitter(t0, tf, wsindex, ss.str());
// Update loop variable
curtime_ns = nexttime_ns;
wsindex++;
// Update progress
int64_t newtimeslot =
(curtime_ns - m_startTime.totalNanoseconds()) * 90 / totaltime;
if (newtimeslot > timeslot) {
// There is change and update progress
timeslot = newtimeslot;
double prog = 0.1 + double(timeslot) / 100.0;
progress(prog);
}
} // END-WHILE
} // END-IF-ELSE
else
{
// Explicitly N time intervals with various interval
// Construct a vector for time intervals in nanosecond
size_t numtimeintervals = vec_timeintervals.size();
std::vector<int64_t> vec_dtimens(numtimeintervals);
for (size_t id = 0; id < numtimeintervals; ++id)
{
int64_t deltatime_ns =
static_cast<int64_t>(vec_timeintervals[id] * m_timeUnitConvertFactorToNS);
vec_dtimens[id] = deltatime_ns;
}
// Build the splitters
int64_t timeslot = 0;
int64_t curtime_ns = m_startTime.totalNanoseconds();
int wsindex = 0;
while (curtime_ns < m_stopTime.totalNanoseconds()) {
int64_t deltatime_ns;
for (size_t id = 0; id < numtimeintervals; ++id)
{
// get next time interval value
deltatime_ns = vec_dtimens[id];
// Calculate next.time
int64_t nexttime_ns = curtime_ns + deltatime_ns;
bool breaklater = false;
if (nexttime_ns > m_stopTime.totalNanoseconds())
{
nexttime_ns = m_stopTime.totalNanoseconds();
breaklater = true;
}
// Create splitter and information
Kernel::DateAndTime t0(curtime_ns);
Kernel::DateAndTime tf(nexttime_ns);
std::stringstream ss;
ss << "Time Interval From " << t0 << " to " << tf;
addNewTimeFilterSplitter(t0, tf, wsindex, ss.str());
// Update loop variable
curtime_ns = nexttime_ns;
++wsindex;
// Update progress
int64_t newtimeslot =
(curtime_ns - m_startTime.totalNanoseconds()) * 90 / totaltime;
if (newtimeslot > timeslot) {
// There is change and update progress
timeslot = newtimeslot;
double prog = 0.1 + double(timeslot) / 100.0;
progress(prog);
}
if (breaklater)
break;
} // END-FOR
} // END-WHILE
}
return;
}
//----------------------------------------------------------------------------------------------
/** Generate filters by log values.
* @param logname :: name of the log to filter with
*/
void GenerateEventsFilter::setFilterByLogValue(std::string logname) {
// Obtain reference of sample log to filter with
m_dblLog = dynamic_cast<TimeSeriesProperty<double> *>(
m_dataWS->run().getProperty(logname));
m_intLog = dynamic_cast<TimeSeriesProperty<int> *>(
m_dataWS->run().getProperty(logname));
if (!m_dblLog && !m_intLog) {
stringstream errmsg;
errmsg
<< "Log " << logname
<< " does not exist or is not TimeSeriesProperty in double or integer.";
throw runtime_error(errmsg.str());
}
// Clear duplicate value and extend to run end
if (m_dblLog) {
g_log.debug("Attempting to remove duplicates in double series log.");
if (m_runEndTime > m_dblLog->lastTime())
m_dblLog->addValue(m_runEndTime, 0.);
m_dblLog->eliminateDuplicates();
} else {
g_log.debug("Attempting to remove duplicates in integer series log.");
m_intLog->addValue(m_runEndTime, 0);
m_intLog->eliminateDuplicates();
}
// Process input properties related to filter with log value
double minvalue = this->getProperty("MinimumLogValue");
double maxvalue = this->getProperty("MaximumLogValue");
double deltaValue = this->getProperty("LogValueInterval");
// Log value change direction
std::string filterdirection =
getProperty("FilterLogValueByChangingDirection");
bool filterIncrease;
bool filterDecrease;
if (filterdirection.compare("Both") == 0) {
filterIncrease = true;
filterDecrease = true;
} else if (filterdirection.compare("Increase") == 0) {
filterIncrease = true;
filterDecrease = false;
} else {
filterIncrease = false;
filterDecrease = true;
}
bool toProcessSingleValueFilter = false;
if (isEmpty(deltaValue)) {
toProcessSingleValueFilter = true;
} else if (deltaValue < 0) {
throw runtime_error("Delta value cannot be negative.");
}
// Log boundary
string logboundary = getProperty("LogBoundary");
if (logboundary.compare("Centre"))
m_logAtCentre = true;
else
m_logAtCentre = false;
m_logTimeTolerance = getProperty("TimeTolerance");
// Generate filters
if (m_dblLog) {
// Double TimeSeriesProperty log
// Process min/max
if (minvalue == EMPTY_DBL()) {
minvalue = m_dblLog->minValue();
}
if (maxvalue == EMPTY_DBL()) {
maxvalue = m_dblLog->maxValue();
}
if (minvalue > maxvalue) {
stringstream errmsg;
errmsg << "Fatal Error: Input minimum log value " << minvalue
<< " is larger than maximum log value " << maxvalue;
throw runtime_error(errmsg.str());
} else {
g_log.debug() << "Filter by log value: min = " << minvalue
<< ", max = " << maxvalue << ", process single value? = "
<< toProcessSingleValueFilter
<< ", delta value = " << deltaValue << "\n";
}
// Filter double value log
if (toProcessSingleValueFilter) {
// Generate a filter for a single log value
processSingleValueFilter(minvalue, maxvalue, filterIncrease,
filterDecrease);
} else {
// Generate filters for a series of log value
processMultipleValueFilters(minvalue, deltaValue, maxvalue,
filterIncrease, filterDecrease);
}
} else {
// Integer TimeSeriesProperty log
// Process min/max allowed value
int minvaluei, maxvaluei;
if (minvalue == EMPTY_DBL()) {
minvaluei = m_intLog->minValue();
minvalue = static_cast<double>(minvaluei);
} else
minvaluei = static_cast<int>(minvalue + 0.5);
if (maxvalue == EMPTY_DBL()) {
maxvaluei = m_intLog->maxValue();
maxvalue = static_cast<double>(maxvaluei);
} else
maxvaluei = static_cast<int>(maxvalue + 0.5);
if (minvalue > maxvalue) {
stringstream errmsg;
errmsg << "Fatal Error: Input minimum log value " << minvalue
<< " is larger than maximum log value " << maxvalue;
throw runtime_error(errmsg.str());
} else {
g_log.information() << "Generate event-filter for integer log: min = "
<< minvaluei << ", "
<< "max = " << maxvaluei << "\n";
}
// Split along log
DateAndTime runendtime = m_dataWS->run().endTime();
processIntegerValueFilter(minvaluei, maxvaluei, filterIncrease,
filterDecrease, runendtime);
} // ENDIFELSE: Double/Integer Log
g_log.information() << "Minimum value = " << minvalue << ", "
<< "maximum value = " << maxvalue << ".\n";
return;
}
//----------------------------------------------------------------------------------------------
/** Generate filters by single log value
* @param minvalue :: minimum value of the allowed log value;
* @param maxvalue :: maximum value of the allowed log value;
* @param filterincrease :: if true, log value in the increasing curve should
* be included;
* @param filterdecrease :: if true, log value in the decreasing curve should
* be included;
*/
void GenerateEventsFilter::processSingleValueFilter(double minvalue,
double maxvalue,
bool filterincrease,
bool filterdecrease) {
// Get parameters time-tolerance and log-boundary
double timetolerance = this->getProperty("TimeTolerance");
int64_t timetolerance_ns =
static_cast<int64_t>(timetolerance * m_timeUnitConvertFactorToNS);
std::string logboundary = this->getProperty("LogBoundary");
transform(logboundary.begin(), logboundary.end(), logboundary.begin(),
::tolower);
// Generate filter
// std::vector<Kernel::SplittingInterval> splitters;
int wsindex = 0;
makeFilterBySingleValue(minvalue, maxvalue,
static_cast<double>(timetolerance_ns) * 1.0E-9,
logboundary.compare("centre") == 0, filterincrease,
filterdecrease, m_startTime, m_stopTime, wsindex);
// Create information table workspace
if (!m_filterInfoWS)
throw runtime_error("m_filterInfoWS has not been initialized.");
API::TableRow row = m_filterInfoWS->appendRow();
std::stringstream ss;
ss << "Log " << m_dblLog->name() << " From " << minvalue << " To " << maxvalue
<< " Value-change-direction ";
if (filterincrease && filterdecrease) {
ss << " both ";
} else if (filterincrease) {
ss << " increase";
} else {
ss << " decrease";
}
row << 0 << ss.str();
return;
}
//----------------------------------------------------------------------------------------------
/** Generate filters from multiple values
* @param minvalue :: minimum value of the allowed log value;
* @param valueinterval :: step of the log value for a series of filter
* @param maxvalue :: maximum value of the allowed log value;
* @param filterincrease :: if true, log value in the increasing curve should
* be included;
* @param filterdecrease :: if true, log value in the decreasing curve should
* be included;
*/
void GenerateEventsFilter::processMultipleValueFilters(double minvalue,
double valueinterval,
double maxvalue,
bool filterincrease,
bool filterdecrease) {
// Read more input
if (valueinterval <= 0)
throw std::invalid_argument(
"Multiple values filter must have LogValueInterval larger than ZERO.");
double valuetolerance = this->getProperty("LogValueTolerance");
if (valuetolerance == EMPTY_DBL())
valuetolerance = 0.5 * valueinterval;
else if (valuetolerance < 0.0)
throw std::runtime_error("LogValueTolerance cannot be less than zero.");
// Create log value interval (low/up boundary) list and split information
// workspace
std::map<size_t, int> indexwsindexmap;
std::vector<double> logvalueranges;
int wsindex = 0;
size_t index = 0;
double curvalue = minvalue;
while (curvalue - valuetolerance < maxvalue) {
indexwsindexmap.insert(std::make_pair(index, wsindex));
// Log interval/value boundary
double lowbound = curvalue - valuetolerance;
double upbound = curvalue + valueinterval - valuetolerance;
logvalueranges.push_back(lowbound);
logvalueranges.push_back(upbound);
// Workgroup information
std::stringstream ss;
ss << "Log " << m_dblLog->name() << " From " << lowbound << " To "
<< upbound << " Value-change-direction ";
if (filterincrease && filterdecrease) {
ss << " both ";
} else if (filterincrease) {
ss << " increase";
} else {
ss << " decrease";
};
API::TableRow newrow = m_filterInfoWS->appendRow();
newrow << wsindex << ss.str();
curvalue += valueinterval;
wsindex++;
++index;
} // ENDWHILE
// Debug print
stringstream dbsplitss;
dbsplitss << "Index map size = " << indexwsindexmap.size() << "\n";
for (map<size_t, int>::iterator mit = indexwsindexmap.begin();
mit != indexwsindexmap.end(); ++mit) {
dbsplitss << "Index " << mit->first << ": WS-group = " << mit->second
<< ". Log value range: [" << logvalueranges[mit->first * 2]
<< ", " << logvalueranges[mit->first * 2 + 1] << ").\n";
}
g_log.information(dbsplitss.str());
// Check split interval obtained wehther is with valid size
if (logvalueranges.size() < 2) {
g_log.warning("There is no log value interval existing.");
return;
}
{
// Warning information
double upperboundinterval0 = logvalueranges[1];
double lowerboundlastinterval = logvalueranges[logvalueranges.size() - 2];
double minlogvalue = m_dblLog->minValue();
double maxlogvalue = m_dblLog->maxValue();
if (minlogvalue > upperboundinterval0 ||
maxlogvalue < lowerboundlastinterval) {
g_log.warning()
<< "User specifies log interval from " << minvalue - valuetolerance
<< " to " << maxvalue - valuetolerance
<< " with interval size = " << valueinterval << "; Log "
<< m_dblLog->name() << " has range " << minlogvalue << " to "
<< maxlogvalue
<< ". Therefore some workgroup index may not have any splitter."
<< std::endl;
}
}
// Generate event filters by log value
std::string logboundary = this->getProperty("LogBoundary");
transform(logboundary.begin(), logboundary.end(), logboundary.begin(),
::tolower);
if (m_useParallel) {
// Make filters in parallel
makeMultipleFiltersByValuesParallel(
indexwsindexmap, logvalueranges, logboundary.compare("centre") == 0,
filterincrease, filterdecrease, m_startTime, m_stopTime);
} else {
// Make filters in serial
makeMultipleFiltersByValues(
indexwsindexmap, logvalueranges, logboundary.compare("centre") == 0,
filterincrease, filterdecrease, m_startTime, m_stopTime);
}
return;
}
//-----------------------------------------------------------------------------------------------
/**
* Fill a TimeSplitterType that will filter the events by matching
* SINGLE log values >= min and < max. Creates SplittingInterval's where
* times match the log values, and going to index==0.
*
*(removed) split :: Splitter that will be filled.
* @param min :: Min value.
* @param max :: Max value.
* @param TimeTolerance :: Offset added to times in seconds.
* @param centre :: Whether the log value time is considered centred or at the
*beginning.
* @param filterIncrease :: As log value increase, and within (min, max),
*include this range in the filter.
* @param filterDecrease :: As log value increase, and within (min, max),
*include this range in the filter.
* @param startTime :: Start time.
* @param stopTime :: Stop time.
* @param wsindex :: Workspace index.
*/
void GenerateEventsFilter::makeFilterBySingleValue(
double min, double max, double TimeTolerance, bool centre,
bool filterIncrease, bool filterDecrease, DateAndTime startTime,
Kernel::DateAndTime stopTime, int wsindex) {
// Do nothing if the log is empty.
if (m_dblLog->size() == 0) {
g_log.warning() << "There is no entry in this property " << this->name()
<< "\n";
return;
}
// Clear splitters in vector format
m_vecSplitterGroup.clear();
m_vecSplitterTime.clear();
// Initialize control parameters
bool lastGood = false;
bool isGood = false;
;
time_duration tol = DateAndTime::durationFromSeconds(TimeTolerance);
int numgood = 0;
DateAndTime lastTime, currT;
DateAndTime start, stop;
size_t progslot = 0;
string info("");
for (int i = 0; i < m_dblLog->size(); i++) {
lastTime = currT;
// The new entry
currT = m_dblLog->nthTime(i);
// A good value?
isGood = identifyLogEntry(i, currT, lastGood, min, max, startTime, stopTime,
filterIncrease, filterDecrease);
if (isGood)
numgood++;
// Log status (time/value/value changing direciton) is changed
if (isGood != lastGood) {
// We switched from bad to good or good to bad
if (isGood) {
// Start of a good section
if (centre)
start = currT - tol;
else
start = currT;
} else {
// End of the good section
if (centre) {
stop = currT - tol;
} else {
stop = currT;
}
addNewTimeFilterSplitter(start, stop, wsindex, info);
// Reset the number of good ones, for next time
numgood = 0;
}
lastGood = isGood;
}
// Progress bar..
size_t tmpslot = i * 90 / m_dblLog->size();
if (tmpslot > progslot) {
progslot = tmpslot;
double prog = double(progslot) / 100.0 + 0.1;
progress(prog);
}
} // ENDFOR
if (numgood > 0) {
// The log ended on "good" so we need to close it using the last time we
// found
if (centre)
stop = currT - tol;
else
stop = currT;
addNewTimeFilterSplitter(start, stop, wsindex, info);
numgood = 0;
}
return;
}
//----------------------------------------------------------------------------------------------
/** Identify a log entry whether it can be included in the splitter for
* filtering by single log value
* - Direction: direction of changing value will be determined by the current
* log entry and next entry
* because the boundary should be set at the first value with new
* direction (as well as last value
* with the old direction)
*/
bool GenerateEventsFilter::identifyLogEntry(
const int &index, const Kernel::DateAndTime &currT, const bool &lastgood,
const double &minvalue, const double &maxvalue,
const Kernel::DateAndTime &startT, const Kernel::DateAndTime &stopT,
const bool &filterIncrease, const bool &filterDecrease) {
double val = m_dblLog->nthValue(index);
// Identify by time and value
bool isgood =
(val >= minvalue && val < maxvalue) && (currT >= startT && currT < stopT);
// Consider direction: not both (i.e., not increase or not decrease)
if (isgood && (!filterIncrease || !filterDecrease)) {
int numlogentries = m_dblLog->size();
double diff;
if (index < numlogentries - 1) {
// For a non-last log entry
diff = m_dblLog->nthValue(index + 1) - val;
} else {
// Last log entry: follow the last direction
diff = val - m_dblLog->nthValue(index - 1);
}
if (diff > 0 && filterIncrease)
isgood = true;
else if (diff < 0 && filterDecrease)
isgood = true;
else if (diff == 0)
isgood = lastgood;
else
isgood = false;
}
return isgood;
}
//-----------------------------------------------------------------------------------------------
/** Fill a TimeSplitterType that will filter the events by matching
* SINGLE log values >= min and < max. Creates SplittingInterval's where
* times match the log values, and going to index==0.
* @param indexwsindexmap :: Index.
* @param logvalueranges :: A vector of double. Each 2i and 2i+1 pair is one
* individual log value range.
* @param centre :: Whether the log value time is considered centred or at the
* beginning.
* @param filterIncrease :: As log value increase, and within (min, max),
* include this range in the filter.
* @param filterDecrease :: As log value increase, and within (min, max),
* include this range in the filter.
* @param startTime :: Start time.
* @param stopTime :: Stop time.
*/
void GenerateEventsFilter::makeMultipleFiltersByValues(
map<size_t, int> indexwsindexmap, vector<double> logvalueranges,
bool centre, bool filterIncrease, bool filterDecrease,
DateAndTime startTime, DateAndTime stopTime) {
g_log.notice("Starting method 'makeMultipleFiltersByValues'. ");
// Return if the log is empty.
int logsize = m_dblLog->size();
if (logsize == 0) {
g_log.warning() << "There is no entry in this property " << m_dblLog->name()
<< std::endl;
return;
}
// Set up
double timetolerance = 0.0;
if (centre) {
timetolerance = this->getProperty("TimeTolerance");
}
time_duration tol = DateAndTime::durationFromSeconds(timetolerance);