forked from npshub/mantid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TimeSeriesProperty.cpp
2488 lines (2161 loc) · 84.1 KB
/
TimeSeriesProperty.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 "MantidKernel/TimeSeriesProperty.h"
#include "MantidKernel/EmptyValues.h"
#include "MantidKernel/Exception.h"
#include "MantidKernel/Logger.h"
#include "MantidKernel/TimeSplitter.h"
#include <json/value.h>
#include <nexus/NeXusFile.hpp>
#include <boost/regex.hpp>
#include <numeric>
namespace Mantid {
using namespace Types::Core;
namespace Kernel {
namespace {
/// static Logger definition
Logger g_log("TimeSeriesProperty");
} // namespace
/**
* Constructor
* @param name :: The name to assign to the property
*/
template <typename TYPE>
TimeSeriesProperty<TYPE>::TimeSeriesProperty(const std::string &name)
: Property(name, typeid(std::vector<TimeValueUnit<TYPE>>)), m_values(), m_size(), m_propSortedFlag(),
m_filterApplied() {}
/**
* Constructor
* @param name :: The name to assign to the property
* @param times :: A vector of DateAndTime objects
* @param values :: A vector of TYPE
*/
template <typename TYPE>
TimeSeriesProperty<TYPE>::TimeSeriesProperty(const std::string &name,
const std::vector<Types::Core::DateAndTime> ×,
const std::vector<TYPE> &values)
: TimeSeriesProperty(name) {
addValues(times, values);
}
/// Virtual destructor
template <typename TYPE> TimeSeriesProperty<TYPE>::~TimeSeriesProperty() {}
/**
* "Virtual" copy constructor
*/
template <typename TYPE> TimeSeriesProperty<TYPE> *TimeSeriesProperty<TYPE>::clone() const {
return new TimeSeriesProperty<TYPE>(*this);
}
/**
* "Virutal copy constructor with a time shift
* @param timeShift :: a time shift in seconds
*/
template <typename TYPE> Property *TimeSeriesProperty<TYPE>::cloneWithTimeShift(const double timeShift) const {
auto timeSeriesProperty = this->clone();
auto values = timeSeriesProperty->valuesAsVector();
auto times = timeSeriesProperty->timesAsVector();
// Shift the time
for (auto it = times.begin(); it != times.end(); ++it) {
// There is a known issue which can cause cloneWithTimeShift to be called
// with a large (~9e+9 s) shift. Actual shifting is capped to be ~4.6e+19
// seconds in DateAndTime::operator+=
(*it) += timeShift;
}
timeSeriesProperty->clear();
timeSeriesProperty->addValues(times, values);
return timeSeriesProperty;
}
/** Return time series property, containing time derivative of current property.
* The property itself and the returned time derivative become sorted by time
* and the derivative is calculated in seconds^-1. (e.g. dValue/dT where
* dT=t2-t1 is time difference in seconds for subsequent time readings and
* dValue=Val1-Val2 is difference in subsequent values)
*
*/
template <typename TYPE> std::unique_ptr<TimeSeriesProperty<double>> TimeSeriesProperty<TYPE>::getDerivative() const {
if (this->m_values.size() < 2) {
throw std::runtime_error("Derivative is not defined for a time-series "
"property with less then two values");
}
this->sortIfNecessary();
auto it = this->m_values.begin();
int64_t t0 = it->time().totalNanoseconds();
TYPE v0 = it->value();
it++;
auto timeSeriesDeriv = std::make_unique<TimeSeriesProperty<double>>(this->name() + "_derivative");
timeSeriesDeriv->reserve(this->m_values.size() - 1);
for (; it != m_values.end(); it++) {
TYPE v1 = it->value();
int64_t t1 = it->time().totalNanoseconds();
if (t1 != t0) {
double deriv = 1.e+9 * (double(v1 - v0) / double(t1 - t0));
auto tm = static_cast<int64_t>((t1 + t0) / 2);
timeSeriesDeriv->addValue(Types::Core::DateAndTime(tm), deriv);
}
t0 = t1;
v0 = v1;
}
return timeSeriesDeriv;
}
/** time series derivative specialization for string type */
template <> std::unique_ptr<TimeSeriesProperty<double>> TimeSeriesProperty<std::string>::getDerivative() const {
throw std::runtime_error("Time series property derivative is not defined for strings");
}
/**
* Return the memory used by the property, in bytes
* */
template <typename TYPE> size_t TimeSeriesProperty<TYPE>::getMemorySize() const {
// Rough estimate
return m_values.size() * (sizeof(TYPE) + sizeof(DateAndTime));
}
/**
* Just returns the property (*this) unless overridden
* @param rhs a property that is merged in some descendent classes
* @return a property with the value
*/
template <typename TYPE> TimeSeriesProperty<TYPE> &TimeSeriesProperty<TYPE>::merge(Property *rhs) {
return operator+=(rhs);
}
/**
* Add the value of another property
* @param right the property to add
* @return the sum
*/
template <typename TYPE> TimeSeriesProperty<TYPE> &TimeSeriesProperty<TYPE>::operator+=(Property const *right) {
auto const *rhs = dynamic_cast<TimeSeriesProperty<TYPE> const *>(right);
if (rhs) {
if (this->operator!=(*rhs)) {
m_values.insert(m_values.end(), rhs->m_values.begin(), rhs->m_values.end());
m_propSortedFlag = TimeSeriesSortStatus::TSUNKNOWN;
} else {
// Do nothing if appending yourself to yourself. The net result would be
// the same anyway
;
}
// Count the REAL size.
m_size = static_cast<int>(m_values.size());
} else
g_log.warning() << "TimeSeriesProperty " << this->name()
<< " could not be added to another property of the same "
"name but incompatible type.\n";
return *this;
}
/**
* Deep comparison.
* @param right The other property to compare to.
* @return true if the are equal.
*/
template <typename TYPE> bool TimeSeriesProperty<TYPE>::operator==(const TimeSeriesProperty<TYPE> &right) const {
sortIfNecessary();
if (this->name() != right.name()) // should this be done?
{
return false;
}
if (this->m_size != right.m_size) {
return false;
}
if (this->realSize() != right.realSize()) {
return false;
} else {
const std::vector<DateAndTime> lhsTimes = this->timesAsVector();
const std::vector<DateAndTime> rhsTimes = right.timesAsVector();
if (!std::equal(lhsTimes.begin(), lhsTimes.end(), rhsTimes.begin())) {
return false;
}
const std::vector<TYPE> lhsValues = this->valuesAsVector();
const std::vector<TYPE> rhsValues = right.valuesAsVector();
if (!std::equal(lhsValues.begin(), lhsValues.end(), rhsValues.begin())) {
return false;
}
}
return true;
}
/**
* Deep comparison.
* @param right The other property to compare to.
* @return true if the are equal.
*/
template <typename TYPE> bool TimeSeriesProperty<TYPE>::operator==(const Property &right) const {
auto rhs_tsp = dynamic_cast<const TimeSeriesProperty<TYPE> *>(&right);
if (!rhs_tsp)
return false;
return this->operator==(*rhs_tsp);
}
/**
* Deep comparison (not equal).
* @param right The other property to compare to.
* @return true if the are not equal.
*/
template <typename TYPE> bool TimeSeriesProperty<TYPE>::operator!=(const TimeSeriesProperty<TYPE> &right) const {
return !(*this == right);
}
/**
* Deep comparison (not equal).
* @param right The other property to compare to.
* @return true if the are not equal.
*/
template <typename TYPE> bool TimeSeriesProperty<TYPE>::operator!=(const Property &right) const {
return !(*this == right);
}
/**
* Set name of the property
*/
template <typename TYPE> void TimeSeriesProperty<TYPE>::setName(const std::string &name) { m_name = name; }
/** Filter out a run by time. Takes out any TimeSeriesProperty log entries
*outside of the given
* absolute time range.
* Be noticed that this operation is not reversible.
*
* Use case 1: if start time of the filter fstart is in between t1 and t2 of
*the TimeSeriesProperty,
* then, the new start time is fstart and the value of the log is
*the log value @ t1
*
* Use case 2: if the start time of the filter in on t1 or before log start
*time t0, then
* the new start time is t1/t0/filter start time.
*
* EXCEPTION: If there is only one entry in the list, it is considered to mean
* "constant" so the value is kept even if the time is outside the range.
*
* @param start :: Absolute start time. Any log entries at times >= to this time
*are kept.
* @param stop :: Absolute stop time. Any log entries at times < than this time
*are kept.
*/
template <typename TYPE>
void TimeSeriesProperty<TYPE>::filterByTime(const Types::Core::DateAndTime &start,
const Types::Core::DateAndTime &stop) {
// 0. Sort
sortIfNecessary();
// 1. Do nothing for single (constant) value
if (m_values.size() <= 1)
return;
typename std::vector<TimeValueUnit<TYPE>>::iterator iterhead, iterend;
// 2. Determine index for start and remove Note erase is [...)
int istart = this->findIndex(start);
if (istart >= 0 && static_cast<size_t>(istart) < m_values.size()) {
// "start time" is behind time-series's starting time
iterhead = m_values.begin() + istart;
// False - The filter time is on the mark. Erase [begin(), istart)
// True - The filter time is larger than T[istart]. Erase[begin(), istart)
// ...
// filter start(time) and move istart to filter startime
bool useprefiltertime = !(m_values[istart].time() == start);
// Remove the series
m_values.erase(m_values.begin(), iterhead);
if (useprefiltertime) {
m_values[0].setTime(start);
}
} else {
// "start time" is before/after time-series's starting time: do nothing
;
}
// 3. Determine index for end and remove Note erase is [...)
int iend = this->findIndex(stop);
if (static_cast<size_t>(iend) < m_values.size()) {
if (m_values[iend].time() == stop) {
// Filter stop is on a log. Delete that log
iterend = m_values.begin() + iend;
} else {
// Filter stop is behind iend. Keep iend
iterend = m_values.begin() + iend + 1;
}
// Delete from [iend to mp.end)
m_values.erase(iterend, m_values.end());
}
// 4. Make size consistent
m_size = static_cast<int>(m_values.size());
}
/**
* Filter by a range of times. If current property has a single value it remains
* unaffected
* @param splittervec :: A list of intervals to split filter on
*/
template <typename TYPE>
void TimeSeriesProperty<TYPE>::filterByTimes(const std::vector<SplittingInterval> &splittervec) {
// 1. Sort
sortIfNecessary();
// 2. Return for single value
if (m_values.size() <= 1) {
return;
}
// 3. Prepare a copy
std::vector<TimeValueUnit<TYPE>> mp_copy;
g_log.debug() << "DB541 mp_copy Size = " << mp_copy.size() << " Original MP Size = " << m_values.size() << "\n";
// 4. Create new
for (const auto &splitter : splittervec) {
Types::Core::DateAndTime t_start = splitter.start();
Types::Core::DateAndTime t_stop = splitter.stop();
int tstartindex = findIndex(t_start);
if (tstartindex < 0) {
// The splitter is not well defined, and use the first
tstartindex = 0;
} else if (tstartindex >= int(m_values.size())) {
// The splitter is not well defined, adn use the last
tstartindex = int(m_values.size()) - 1;
}
int tstopindex = findIndex(t_stop);
if (tstopindex < 0) {
tstopindex = 0;
} else if (tstopindex >= int(m_values.size())) {
tstopindex = int(m_values.size()) - 1;
} else {
if (t_stop == m_values[size_t(tstopindex)].time() && size_t(tstopindex) > 0) {
tstopindex--;
}
}
/* Check */
if (tstartindex < 0 || tstopindex >= int(m_values.size())) {
g_log.warning() << "Memory Leak In SplitbyTime!\n";
}
if (tstartindex == tstopindex) {
TimeValueUnit<TYPE> temp(t_start, m_values[tstartindex].value());
mp_copy.emplace_back(temp);
} else {
mp_copy.emplace_back(t_start, m_values[tstartindex].value());
for (auto im = size_t(tstartindex + 1); im <= size_t(tstopindex); ++im) {
mp_copy.emplace_back(m_values[im].time(), m_values[im].value());
}
}
} // ENDFOR
g_log.debug() << "DB530 Filtered Log Size = " << mp_copy.size() << " Original Log Size = " << m_values.size()
<< "\n";
// 5. Clear
m_values.clear();
m_values = mp_copy;
mp_copy.clear();
m_size = static_cast<int>(m_values.size());
}
/**
* Split this time series property by time intervals to multiple time series
* property according to number of distinct splitters' indexes, such as 0 and 1
*
* NOTE: If the input TSP has a single value, it is assumed to be a constant
* and so is not split, but simply copied to all output.
*
* @param splitter :: a TimeSplitterType object containing the list of intervals
* and destinations.
* @param outputs :: A vector of output TimeSeriesProperty
* pointers of the same type.
* @param isPeriodic :: whether the log (this TSP) is periodic. For example
* proton-charge is periodic log.
*/
template <typename TYPE>
void TimeSeriesProperty<TYPE>::splitByTime(std::vector<SplittingInterval> &splitter, std::vector<Property *> outputs,
bool isPeriodic) const {
// 0. Sort if necessary
sortIfNecessary();
if (outputs.empty())
return;
std::vector<TimeSeriesProperty<TYPE> *> outputs_tsp;
size_t numOutputs = outputs.size();
// 1. Clear the outputs before you start
for (size_t i = 0; i < numOutputs; i++) {
auto *myOutput = dynamic_cast<TimeSeriesProperty<TYPE> *>(outputs[i]);
if (myOutput) {
outputs_tsp.emplace_back(myOutput);
if (this->m_values.size() == 1) {
// Special case for TSP with a single entry = just copy.
myOutput->m_values = this->m_values;
myOutput->m_size = 1;
} else {
myOutput->m_values.clear();
myOutput->m_size = 0;
}
} else {
outputs_tsp.emplace_back(nullptr);
}
}
// 2. Special case for TSP with a single entry = just copy.
if (this->m_values.size() == 1)
return;
// 3. We will be iterating through all the entries in the the map/vector
size_t i_property = 0;
// And at the same time, iterate through the splitter
auto itspl = splitter.begin();
size_t counter = 0;
g_log.debug() << "[DB] Number of time series entries = " << m_values.size()
<< ", Number of splitters = " << splitter.size() << "\n";
while (itspl != splitter.end() && i_property < m_values.size()) {
// Get the splitting interval times and destination
DateAndTime start = itspl->start();
DateAndTime stop = itspl->stop();
int output_index = itspl->index();
// output workspace index is out of range. go to the next splitter
if (output_index < 0 || output_index >= static_cast<int>(numOutputs))
continue;
TimeSeriesProperty<TYPE> *myOutput = outputs_tsp[output_index];
// skip if the input property is of wrong type
if (!myOutput) {
++itspl;
++counter;
continue;
}
// Skip the events before the start of the time
while (i_property < m_values.size() && m_values[i_property].time() < start)
++i_property;
if (i_property == m_values.size()) {
// i_property is out of the range. Then use the last entry
myOutput->addValue(m_values[i_property - 1].time(), m_values[i_property - 1].value());
++itspl;
++counter;
break;
}
// The current entry is within an interval. Record them until out
if (m_values[i_property].time() > start && i_property > 0 && !isPeriodic) {
// Record the previous oneif this property is not exactly on start time
// and this entry is not recorded
size_t i_prev = i_property - 1;
if (myOutput->size() == 0 || m_values[i_prev].time() != myOutput->lastTime())
myOutput->addValue(m_values[i_prev].time(), m_values[i_prev].value());
}
// Loop through all the entries until out.
while (i_property < m_values.size() && m_values[i_property].time() < stop) {
// Copy the log out to the output
myOutput->addValue(m_values[i_property].time(), m_values[i_property].value());
++i_property;
}
// Go to the next interval
++itspl;
++counter;
// But if we reached the end, then we are done.
if (itspl == splitter.end())
break;
// No need to keep looping through the filter if we are out of events
if (i_property == this->m_values.size())
break;
} // Looping through entries in the splitter vector
// Make sure all entries have the correct size recorded in m_size.
for (std::size_t i = 0; i < numOutputs; i++) {
auto *myOutput = dynamic_cast<TimeSeriesProperty<TYPE> *>(outputs[i]);
if (myOutput) {
myOutput->m_size = myOutput->realSize();
}
}
}
/// Split this TimeSeriresProperty by a vector of time with N entries,
/// and by the wsIndex workspace index defined by inputWorkspaceIndicies
/// Requirements:
/// vector output must be defined before this method is called
template <typename TYPE>
void TimeSeriesProperty<TYPE>::splitByTimeVector(const std::vector<DateAndTime> &timeToFilterTo,
const std::vector<int> &inputWorkspaceIndicies,
const std::vector<TimeSeriesProperty *> &output) {
// check inputs
if (timeToFilterTo.size() != inputWorkspaceIndicies.size() + 1) {
throw std::runtime_error("Input time vector's size does not match(one more larger than) target "
"workspace index vector's size inputWorkspaceIndicies.size() \n");
}
// return if the output vector TimeSeriesProperties is not defined
if (output.empty())
return;
sortIfNecessary();
// work on m_values, m_size, and m_time
auto const currentTimes = timesAsVector();
auto const currentValues = valuesAsVector();
size_t index_splitter = 0;
// move splitter index such that the first entry of TSP is before the stop
// time of a splitter
DateAndTime firstPropTime = currentTimes[0];
auto firstFilterTime = std::lower_bound(timeToFilterTo.begin(), timeToFilterTo.end(), firstPropTime);
if (firstFilterTime == timeToFilterTo.end()) {
// do nothing as the first TimeSeriesProperty entry's time is before any
// splitters
return;
} else if (firstFilterTime != timeToFilterTo.begin()) {
// calculate the splitter's index (now we check the stop time)
index_splitter = firstFilterTime - timeToFilterTo.begin() - 1;
}
DateAndTime filterStartTime = timeToFilterTo[index_splitter];
DateAndTime filterEndTime = timeToFilterTo[index_splitter + 1];
// move along the entries to find the entry inside the current splitter
auto firstEntryInSplitter = std::lower_bound(currentTimes.begin(), currentTimes.end(), filterStartTime);
if (firstEntryInSplitter == currentTimes.end()) {
// the first splitter's start time is LATER than the last TSP entry, then
// there won't be any
// TSP entry to be split into any wsIndex splitter.
DateAndTime last_entry_time = this->lastTime();
TYPE last_entry_value = this->lastValue();
for (auto &i : output) {
i->addValue(last_entry_time, last_entry_value);
}
return;
}
// first splitter start time is between firstEntryInSplitter and the one
// before it. so the index for firstEntryInSplitter is the first TSP entry
// in the splitter
size_t timeIndex = firstEntryInSplitter - currentTimes.begin();
firstPropTime = *firstEntryInSplitter;
for (; index_splitter < timeToFilterTo.size() - 1; ++index_splitter) {
int wsIndex = inputWorkspaceIndicies[index_splitter];
filterStartTime = timeToFilterTo[index_splitter];
filterEndTime = timeToFilterTo[index_splitter + 1];
// get the first entry index (overlap)
if (timeIndex > 0)
--timeIndex;
// add the continuous entries to same wsIndex time series property
const size_t numEntries = currentTimes.size();
// Add properties to the current wsIndex.
if (timeIndex >= numEntries) {
// We have run out of TSP entries, so use the last TSP value
// for all remaining outputs
auto currentTime = currentTimes.back();
if (output[wsIndex]->size() == 0 || output[wsIndex]->lastTime() != currentTime) {
output[wsIndex]->addValue(currentTime, currentValues.back());
}
} else {
// Add TSP values until we run out or go past the current filter
// end time.
for (; timeIndex < numEntries; ++timeIndex) {
auto currentTime = currentTimes[timeIndex];
if (output[wsIndex]->size() == 0 || output[wsIndex]->lastTime() < currentTime) {
// avoid to add duplicate entry
output[wsIndex]->addValue(currentTime, currentValues[timeIndex]);
}
if (currentTime > filterEndTime)
break;
}
}
}
// Add a debugging check such that there won't be any time entry with zero log
for (size_t i = 0; i < output.size(); ++i) {
if (output[i]->size() == 0) {
std::stringstream errss;
errss << "entry " << m_name << " has 0 size, whose first entry is at " << this->firstTime().toSimpleString();
g_log.warning(errss.str());
}
}
}
// The makeFilterByValue & expandFilterToRange methods generate a bunch of
// warnings when the template type is the wider integer types
// (when it's being assigned back to a double such as in a call to minValue or
// firstValue)
// However, in reality these methods are only used for TYPE=int or double (they
// are only called from FilterByLogValue) so suppress the warnings
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable : 4244)
#pragma warning(disable : 4804) // This one comes about for TYPE=bool - again
// the method is never called for this type
#endif
#if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
#pragma GCC diagnostic ignored "-Wconversion"
#endif
/**
* Fill a TimeSplitterType that will filter the events by matching
* log values >= min and <= max. Creates SplittingInterval's where
* times match the log values, and going to index==0.
* This method is used by the FilterByLogValue algorithm.
*
* @param split :: Splitter that will be filled.
* @param min :: min value
* @param max :: max value
* @param TimeTolerance :: offset added to times in seconds (default: 0)
* @param centre :: Whether the log value time is considered centred or at the
*beginning (the default).
*/
template <typename TYPE>
void TimeSeriesProperty<TYPE>::makeFilterByValue(std::vector<SplittingInterval> &split, double min, double max,
double TimeTolerance, bool centre) const {
const bool emptyMin = (min == EMPTY_DBL());
const bool emptyMax = (max == EMPTY_DBL());
if (!emptyMin && !emptyMax && max < min) {
std::stringstream ss;
ss << "TimeSeriesProperty::makeFilterByValue: 'max' argument must be "
"greater than 'min' "
<< "(got min=" << min << " max=" << max << ")";
throw std::invalid_argument(ss.str());
}
// If min or max were unset ("empty") in the algorithm, set to the min or max
// value of the log
if (emptyMin)
min = minValue();
if (emptyMax)
max = maxValue();
// Make sure the splitter starts out empty
split.clear();
// Do nothing if the log is empty.
if (m_values.empty())
return;
// 1. Sort
sortIfNecessary();
// 2. Do the rest
bool lastGood(false);
time_duration tol = DateAndTime::durationFromSeconds(TimeTolerance);
int numgood = 0;
DateAndTime t;
DateAndTime start, stop;
for (size_t i = 0; i < m_values.size(); ++i) {
const DateAndTime lastTime = t;
// The new entry
t = m_values[i].time();
TYPE val = m_values[i].value();
// A good value?
const bool isGood = ((val >= min) && (val <= max));
if (isGood)
numgood++;
if (isGood != lastGood) {
// We switched from bad to good or good to bad
if (isGood) {
// Start of a good section. Subtract tolerance from the time if
// boundaries are centred.
start = centre ? t - tol : t;
} else {
// End of the good section. Add tolerance to the LAST GOOD time if
// boundaries are centred.
// Otherwise, use the first 'bad' time.
stop = centre ? lastTime + tol : t;
split.emplace_back(start, stop, 0);
// Reset the number of good ones, for next time
numgood = 0;
}
lastGood = isGood;
}
}
if (numgood > 0) {
// The log ended on "good" so we need to close it using the last time we
// found
stop = t + tol;
split.emplace_back(start, stop, 0);
}
}
/** Function specialization for TimeSeriesProperty<std::string>
* @throws Kernel::Exception::NotImplementedError always
*/
template <>
void TimeSeriesProperty<std::string>::makeFilterByValue(std::vector<SplittingInterval> & /*split*/, double /*min*/,
double /*max*/, double /*TimeTolerance*/,
bool /*centre*/) const {
throw Exception::NotImplementedError("TimeSeriesProperty::makeFilterByValue "
"is not implemented for string "
"properties");
}
/** If the first and/or last values in a log are between min & max, expand and
* existing TimeSplitter
* (created by makeFilterByValue) if necessary to cover the full TimeInterval
* given.
* This method is used by the FilterByLogValue algorithm.
* @param split The splitter to modify if necessary
* @param min The minimum 'good' value
* @param max The maximum 'good' value
* @param range The full time range that we want this splitter to cover
*/
template <typename TYPE>
void TimeSeriesProperty<TYPE>::expandFilterToRange(std::vector<SplittingInterval> &split, double min, double max,
const TimeInterval &range) const {
const bool emptyMin = (min == EMPTY_DBL());
const bool emptyMax = (max == EMPTY_DBL());
if (!emptyMin && !emptyMax && max < min) {
std::stringstream ss;
ss << "TimeSeriesProperty::expandFilterToRange: 'max' argument must be "
"greater than 'min' "
<< "(got min=" << min << " max=" << max << ")";
throw std::invalid_argument(ss.str());
}
// If min or max were unset ("empty") in the algorithm, set to the min or max
// value of the log
if (emptyMin)
min = minValue();
if (emptyMax)
max = maxValue();
// Assume everything before the 1st value is constant
double val = firstValue();
if ((val >= min) && (val <= max)) {
TimeSplitterType extraFilter;
extraFilter.emplace_back(range.begin(), firstTime(), 0);
// Include everything from the start of the run to the first time measured
// (which may be a null time interval; this'll be ignored)
split = split | extraFilter;
}
// Assume everything after the LAST value is constant
val = lastValue();
if ((val >= min) && (val <= max)) {
TimeSplitterType extraFilter;
extraFilter.emplace_back(lastTime(), range.end(), 0);
// Include everything from the start of the run to the first time measured
// (which may be a null time interval; this'll be ignored)
split = split | extraFilter;
}
}
/** Function specialization for TimeSeriesProperty<std::string>
* @throws Kernel::Exception::NotImplementedError always
*/
template <>
void TimeSeriesProperty<std::string>::expandFilterToRange(std::vector<SplittingInterval> & /*split*/, double /*min*/,
double /*max*/, const TimeInterval & /*range*/) const {
throw Exception::NotImplementedError("TimeSeriesProperty::makeFilterByValue "
"is not implemented for string "
"properties");
}
/** Calculates the time-weighted average of a property.
* @return The time-weighted average value of the log.
*/
template <typename TYPE> double TimeSeriesProperty<TYPE>::timeAverageValue() const {
double retVal = 0.0;
try {
const auto &filter = getSplittingIntervals();
retVal = this->averageValueInFilter(filter);
} catch (std::exception &) {
// just return nan
retVal = std::numeric_limits<double>::quiet_NaN();
}
return retVal;
}
/** Calculates the time-weighted average of a property in a filtered range.
* This is written for that case of logs whose values start at the times given.
* @param filter The splitter/filter restricting the range of values included
* @return The time-weighted average value of the log in the range within the
* filter.
*/
template <typename TYPE>
double TimeSeriesProperty<TYPE>::averageValueInFilter(const std::vector<SplittingInterval> &filter) const {
// TODO: Consider logs that aren't giving starting values.
// First of all, if the log or the filter is empty, return NaN
if (realSize() == 0 || filter.empty()) {
return std::numeric_limits<double>::quiet_NaN();
}
// If there's just a single value in the log, return that.
if (realSize() == 1) {
return static_cast<double>(m_values.front().value());
}
sortIfNecessary();
double numerator(0.0), totalTime(0.0);
// Loop through the filter ranges
for (const auto &time : filter) {
// Calculate the total time duration (in seconds) within by the filter
totalTime += time.duration();
// Get the log value and index at the start time of the filter
int index;
double value = getSingleValue(time.start(), index);
DateAndTime startTime = time.start();
while (index < realSize() - 1 && m_values[index + 1].time() < time.stop()) {
++index;
numerator += DateAndTime::secondsFromDuration(m_values[index].time() - startTime) * value;
startTime = m_values[index].time();
value = static_cast<double>(m_values[index].value());
}
// Now close off with the end of the current filter range
numerator += DateAndTime::secondsFromDuration(time.stop() - startTime) * value;
}
// 'Normalise' by the total time
return numerator / totalTime;
}
/** Function specialization for TimeSeriesProperty<std::string>
* @throws Kernel::Exception::NotImplementedError always
*/
template <> double TimeSeriesProperty<std::string>::averageValueInFilter(const TimeSplitterType & /*filter*/) const {
throw Exception::NotImplementedError("TimeSeriesProperty::"
"averageValueInFilter is not "
"implemented for string properties");
}
template <typename TYPE> std::pair<double, double> TimeSeriesProperty<TYPE>::timeAverageValueAndStdDev() const {
std::pair<double, double> retVal{0., 0.}; // mean and stddev
try {
const auto &filter = getSplittingIntervals();
retVal = this->averageAndStdDevInFilter(filter);
} catch (std::exception &) {
retVal.first = std::numeric_limits<double>::quiet_NaN();
retVal.second = std::numeric_limits<double>::quiet_NaN();
}
return retVal;
}
template <typename TYPE>
std::pair<double, double>
TimeSeriesProperty<TYPE>::averageAndStdDevInFilter(const std::vector<SplittingInterval> &filter) const {
// the mean to calculate the standard deviation about
// this will sort the log as necessary as well
const double mean = this->averageValueInFilter(filter);
// First of all, if the log or the filter is empty or is a single value,
// return NaN for the uncertainty
if (realSize() <= 1 || filter.empty()) {
return std::pair<double, double>{mean, std::numeric_limits<double>::quiet_NaN()};
}
double numerator(0.0), totalTime(0.0);
// Loop through the filter ranges
for (const auto &time : filter) {
// Calculate the total time duration (in seconds) within by the filter
totalTime += time.duration();
// Get the log value and index at the start time of the filter
int index;
double value = getSingleValue(time.start(), index);
double valuestddev = (value - mean) * (value - mean);
DateAndTime startTime = time.start();
while (index < realSize() - 1 && m_values[index + 1].time() < time.stop()) {
++index;
numerator += DateAndTime::secondsFromDuration(m_values[index].time() - startTime) * valuestddev;
startTime = m_values[index].time();
value = static_cast<double>(m_values[index].value());
valuestddev = (value - mean) * (value - mean);
}
// Now close off with the end of the current filter range
numerator += DateAndTime::secondsFromDuration(time.stop() - startTime) * valuestddev;
}
// Normalise by the total time
return std::pair<double, double>{mean, std::sqrt(numerator / totalTime)};
}
/** Function specialization for TimeSeriesProperty<std::string>
* @throws Kernel::Exception::NotImplementedError always
*/
template <>
std::pair<double, double>
TimeSeriesProperty<std::string>::averageAndStdDevInFilter(const TimeSplitterType & /*filter*/) const {
throw Exception::NotImplementedError("TimeSeriesProperty::"
"averageAndStdDevInFilter is not "
"implemented for string properties");
}
// Re-enable the warnings disabled before makeFilterByValue
#ifdef _WIN32
#pragma warning(pop)
#endif
#if defined(__GNUC__) && !(defined(__INTEL_COMPILER))
#pragma GCC diagnostic warning "-Wconversion"
#endif
/**
* Return the time series as a correct C++ map<DateAndTime, TYPE>. All values
* are included.
*
* @return time series property values as map
*/
template <typename TYPE> std::map<DateAndTime, TYPE> TimeSeriesProperty<TYPE>::valueAsCorrectMap() const {
// 1. Sort if necessary
sortIfNecessary();
// 2. Data Strcture
std::map<DateAndTime, TYPE> asMap;
if (!m_values.empty()) {
for (size_t i = 0; i < m_values.size(); i++)
asMap[m_values[i].time()] = m_values[i].value();
}
return asMap;
}
/**
* Return the time series's values as a vector<TYPE>
* @return the time series's values as a vector<TYPE>
*/
template <typename TYPE> std::vector<TYPE> TimeSeriesProperty<TYPE>::valuesAsVector() const {
sortIfNecessary();
std::vector<TYPE> out;
out.reserve(m_values.size());
for (size_t i = 0; i < m_values.size(); i++)
out.emplace_back(m_values[i].value());
return out;
}
/**
* Return the time series as a C++ multimap<DateAndTime, TYPE>. All values.
* This method is used in parsing the ISIS ICPevent log file: different
* commands
* can be recorded against the same time stamp but all must be present.
*/
template <typename TYPE> std::multimap<DateAndTime, TYPE> TimeSeriesProperty<TYPE>::valueAsMultiMap() const {
std::multimap<DateAndTime, TYPE> asMultiMap;
if (!m_values.empty()) {
for (size_t i = 0; i < m_values.size(); i++)
asMultiMap.insert(std::make_pair(m_values[i].time(), m_values[i].value()));
}
return asMultiMap;
}
/**