-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathAdaptiveSingularSpectrumSequenceModeler.cs
1555 lines (1313 loc) · 63.4 KB
/
AdaptiveSingularSpectrumSequenceModeler.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using Microsoft.ML.Runtime;
using Microsoft.ML.Runtime.Data;
using Microsoft.ML.Runtime.Internal.CpuMath;
using Microsoft.ML.Runtime.Internal.Utilities;
using Microsoft.ML.Runtime.Model;
using Microsoft.ML.Runtime.TimeSeriesProcessing;
[assembly: LoadableClass(typeof(ISequenceModeler<Single, Single>), typeof(AdaptiveSingularSpectrumSequenceModeler), null, typeof(SignatureLoadModel),
"SSA Sequence Modeler",
AdaptiveSingularSpectrumSequenceModeler.LoaderSignature)]
namespace Microsoft.ML.Runtime.TimeSeriesProcessing
{
/// <summary>
/// This class implements basic Singular Spectrum Analysis (SSA) model for modeling univariate time-series.
/// For the details of the model, refer to http://arxiv.org/pdf/1206.6910.pdf.
/// </summary>
public sealed class AdaptiveSingularSpectrumSequenceModeler : ISequenceModeler<Single, Single>
{
public const string LoaderSignature = "SSAModel";
public enum RankSelectionMethod
{
Fixed,
Exact,
Fast
}
public sealed class SsaForecastResult : ForecastResultBase<Single>
{
public VBuffer<Single> ForecastStandardDeviation;
public VBuffer<Single> UpperBound;
public VBuffer<Single> LowerBound;
public Single ConfidenceLevel;
internal bool CanComputeForecastIntervals;
internal Single BoundOffset;
public bool IsVarianceValid { get { return CanComputeForecastIntervals; } }
}
public struct GrowthRatio
{
private int _timeSpan;
private Double _growth;
public int TimeSpan
{
get
{
return _timeSpan;
}
set
{
Contracts.CheckParam(value > 0, nameof(TimeSpan), "The time span must be strictly positive.");
_timeSpan = value;
}
}
public Double Growth
{
get
{
return _growth;
}
set
{
Contracts.CheckParam(value >= 0, nameof(Growth), "The growth must be non-negative.");
_growth = value;
}
}
public GrowthRatio(int timeSpan = 1, double growth = Double.PositiveInfinity)
{
Contracts.CheckParam(timeSpan > 0, nameof(TimeSpan), "The time span must be strictly positive.");
Contracts.CheckParam(growth >= 0, nameof(Growth), "The growth must be non-negative.");
_growth = growth;
_timeSpan = timeSpan;
}
public Double Ratio { get { return Math.Pow(_growth, 1d / _timeSpan); } }
}
public sealed class ModelInfo
{
/// <summary>
/// The singular values of the SSA of the input time-series
/// </summary>
public Single[] Spectrum;
/// <summary>
/// The roots of the characteristic polynomial after stabilization (meaningful only if the model is stabilized.)
/// </summary>
public Complex[] RootsAfterStabilization;
/// <summary>
/// The roots of the characteristic polynomial before stabilization (meaningful only if the model is stabilized.)
/// </summary>
public Complex[] RootsBeforeStabilization;
/// <summary>
/// The rank of the model
/// </summary>
public int Rank;
/// <summary>
/// The window size used to compute the SSA model
/// </summary>
public int WindowSize;
/// <summary>
/// The auto-regressive coefficients learned by the model
/// </summary>
public Single[] AutoRegressiveCoefficients;
/// <summary>
/// The flag indicating whether the model has been trained
/// </summary>
public bool IsTrained;
/// <summary>
/// The flag indicating a naive model is trained instead of SSA
/// </summary>
public bool IsNaiveModelTrained;
/// <summary>
/// The flag indicating whether the learned model has an exponential trend (meaningful only if the model is stabilized.)
/// </summary>
public bool IsExponentialTrendPresent;
/// <summary>
/// The flag indicating whether the learned model has a polynomial trend (meaningful only if the model is stabilized.)
/// </summary>
public bool IsPolynomialTrendPresent;
/// <summary>
/// The flag indicating whether the learned model has been stabilized
/// </summary>
public bool IsStabilized;
/// <summary>
/// The flag indicating whether any artificial seasonality (a seasonality with period greater than the window size) is removed
/// (meaningful only if the model is stabilized.)
/// </summary>
public bool IsArtificialSeasonalityRemoved;
/// <summary>
/// The exponential trend magnitude (meaningful only if the model is stabilized.)
/// </summary>
public Double ExponentialTrendFactor;
}
private ModelInfo _info;
/// <summary>
/// Returns the meta information about the learned model.
/// </summary>
public ModelInfo Info
{
get { return _info; }
}
private Single[] _alpha;
private Single[] _state;
private readonly FixedSizeQueue<Single> _buffer;
private CpuAlignedVector _x;
private CpuAlignedVector _xSmooth;
private int _windowSize;
private readonly int _seriesLength;
private readonly RankSelectionMethod _rankSelectionMethod;
private readonly Single _discountFactor;
private readonly int _trainSize;
private int _maxRank;
private readonly Double _maxTrendRatio;
private readonly bool _shouldStablize;
private readonly bool _shouldMaintainInfo;
private readonly IHost _host;
private CpuAlignedMatrixRow _wTrans;
private Single _observationNoiseVariance;
private Single _observationNoiseMean;
private Single _autoregressionNoiseVariance;
private Single _autoregressionNoiseMean;
private int _rank;
private CpuAlignedVector _y;
private Single _nextPrediction;
/// <summary>
/// Determines whether the confidence interval required for forecasting.
/// </summary>
public bool ShouldComputeForecastIntervals { get; set; }
/// <summary>
/// Returns the rank of the subspace used for SSA projection (parameter r).
/// </summary>
public int Rank { get { return _rank; } }
/// <summary>
/// Returns the smoothed (via SSA projection) version of the last series observation fed to the model.
/// </summary>
public Single LastSmoothedValue { get { return _state[_windowSize - 2]; } }
/// <summary>
/// Returns the last series observation fed to the model.
/// </summary>
public Single LastValue { get { return _buffer.Count > 0 ? _buffer[_buffer.Count - 1] : Single.NaN; } }
private static VersionInfo GetVersionInfo()
{
return new VersionInfo(
modelSignature: "SSAMODLR",
//verWrittenCur: 0x00010001, // Initial
verWrittenCur: 0x00010002, // Added saving _state and _nextPrediction
verReadableCur: 0x00010002,
verWeCanReadBack: 0x00010001,
loaderSignature: LoaderSignature,
loaderAssemblyName: typeof(AdaptiveSingularSpectrumSequenceModeler).Assembly.FullName);
}
private const int VersionSavingStateAndPrediction = 0x00010002;
/// <summary>
/// The constructor for Adaptive SSA model.
/// </summary>
/// <param name="env">The exception context.</param>
/// <param name="trainSize">The length of series from the begining used for training.</param>
/// <param name="seriesLength">The length of series that is kept in buffer for modeling (parameter N).</param>
/// <param name="windowSize">The length of the window on the series for building the trajectory matrix (parameter L).</param>
/// <param name="discountFactor">The discount factor in [0,1] used for online updates (default = 1).</param>
/// <param name="buffer">The buffer used to keep the series in the memory. If null, an internal buffer is created (default = null).</param>
/// <param name="rankSelectionMethod">The rank selection method (default = Exact).</param>
/// <param name="rank">The desired rank of the subspace used for SSA projection (parameter r). This parameter should be in the range in [1, windowSize].
/// If set to null, the rank is automatically determined based on prediction error minimization. (default = null)</param>
/// <param name="maxRank">The maximum rank considered during the rank selection process. If not provided (i.e. set to null), it is set to windowSize - 1.</param>
/// <param name="shouldComputeForecastIntervals">The flag determining whether the confidence bounds for the point forecasts should be computed. (default = true)</param>
/// <param name="shouldstablize">The flag determining whether the model should be stabilized.</param>
/// <param name="shouldMaintainInfo">The flag determining whether the meta information for the model needs to be maintained.</param>
/// <param name="maxGrowth">The maximum growth on the exponential trend</param>
public AdaptiveSingularSpectrumSequenceModeler(IHostEnvironment env, int trainSize, int seriesLength, int windowSize, Single discountFactor = 1,
FixedSizeQueue<Single> buffer = null, RankSelectionMethod rankSelectionMethod = RankSelectionMethod.Exact, int? rank = null, int? maxRank = null,
bool shouldComputeForecastIntervals = true, bool shouldstablize = true, bool shouldMaintainInfo = false, GrowthRatio? maxGrowth = null)
{
Contracts.CheckValue(env, nameof(env));
_host = env.Register(LoaderSignature);
_host.CheckParam(windowSize >= 2, nameof(windowSize), "The window size should be at least 2."); // ...because otherwise we have nothing to autoregress on
_host.CheckParam(seriesLength > windowSize, nameof(seriesLength), "The series length should be greater than the window size.");
_host.Check(trainSize > 2 * windowSize, "The input series length for training should be greater than twice the window size.");
_host.CheckParam(0 <= discountFactor && discountFactor <= 1, nameof(discountFactor), "The discount factor should be in [0,1].");
if (maxRank != null)
{
_maxRank = (int)maxRank;
_host.CheckParam(1 <= _maxRank && _maxRank < windowSize, nameof(maxRank),
"The max rank should be in [1, windowSize).");
}
else
_maxRank = windowSize - 1;
_rankSelectionMethod = rankSelectionMethod;
if (_rankSelectionMethod == RankSelectionMethod.Fixed)
{
if (rank != null)
{
_rank = (int)rank;
_host.CheckParam(1 <= _rank && _rank < windowSize, nameof(rank), "The rank should be in [1, windowSize).");
}
else
_rank = _maxRank;
}
_seriesLength = seriesLength;
_windowSize = windowSize;
_trainSize = trainSize;
_discountFactor = discountFactor;
if (buffer == null)
_buffer = new FixedSizeQueue<Single>(seriesLength);
else
_buffer = buffer;
_alpha = new Single[windowSize - 1];
_state = new Single[windowSize - 1];
_x = new CpuAlignedVector(windowSize, SseUtils.CbAlign);
_xSmooth = new CpuAlignedVector(windowSize, SseUtils.CbAlign);
ShouldComputeForecastIntervals = shouldComputeForecastIntervals;
_observationNoiseVariance = 0;
_autoregressionNoiseVariance = 0;
_observationNoiseMean = 0;
_autoregressionNoiseMean = 0;
_shouldStablize = shouldstablize;
_maxTrendRatio = maxGrowth == null ? Double.PositiveInfinity : ((GrowthRatio)maxGrowth).Ratio;
_shouldMaintainInfo = shouldMaintainInfo;
if (_shouldMaintainInfo)
{
_info = new ModelInfo();
_info.WindowSize = _windowSize;
}
}
/// <summary>
/// The copy constructor
/// </summary>
/// <param name="model">An object whose contents are copied to the current object.</param>
private AdaptiveSingularSpectrumSequenceModeler(AdaptiveSingularSpectrumSequenceModeler model)
{
_host = model._host.Register(LoaderSignature);
_host.Assert(model._windowSize >= 2);
_host.Assert(model._seriesLength > model._windowSize);
_host.Assert(model._trainSize > 2 * model._windowSize);
_host.Assert(0 <= model._discountFactor && model._discountFactor <= 1);
_host.Assert(1 <= model._rank && model._rank < model._windowSize);
_rank = model._rank;
_maxRank = model._maxRank;
_rankSelectionMethod = model._rankSelectionMethod;
_seriesLength = model._seriesLength;
_windowSize = model._windowSize;
_trainSize = model._trainSize;
_discountFactor = model._discountFactor;
ShouldComputeForecastIntervals = model.ShouldComputeForecastIntervals;
_observationNoiseVariance = model._observationNoiseVariance;
_autoregressionNoiseVariance = model._autoregressionNoiseVariance;
_observationNoiseMean = model._observationNoiseMean;
_autoregressionNoiseMean = model._autoregressionNoiseMean;
_nextPrediction = model._nextPrediction;
_maxTrendRatio = model._maxTrendRatio;
_shouldStablize = model._shouldStablize;
_shouldMaintainInfo = model._shouldMaintainInfo;
_info = model._info;
_buffer = new FixedSizeQueue<Single>(_seriesLength);
_alpha = new Single[_windowSize - 1];
Array.Copy(model._alpha, _alpha, _windowSize - 1);
_state = new Single[_windowSize - 1];
Array.Copy(model._state, _state, _windowSize - 1);
_x = new CpuAlignedVector(_windowSize, SseUtils.CbAlign);
_xSmooth = new CpuAlignedVector(_windowSize, SseUtils.CbAlign);
if (model._wTrans != null)
{
_y = new CpuAlignedVector(_rank, SseUtils.CbAlign);
_wTrans = new CpuAlignedMatrixRow(_rank, _windowSize, SseUtils.CbAlign);
_wTrans.CopyFrom(model._wTrans);
}
}
public AdaptiveSingularSpectrumSequenceModeler(IHostEnvironment env, ModelLoadContext ctx)
{
Contracts.CheckValue(env, nameof(env));
_host = env.Register(LoaderSignature);
// *** Binary format ***
// int: _seriesLength
// int: _windowSize
// int: _trainSize
// int: _rank
// float: _discountFactor
// RankSelectionMethod: _rankSelectionMethod
// bool: isWeightSet
// float[]: _alpha
// float[]: _state
// bool: ShouldComputeForecastIntervals
// float: _observationNoiseVariance
// float: _autoregressionNoiseVariance
// float: _observationNoiseMean
// float: _autoregressionNoiseMean
// float: _nextPrediction
// int: _maxRank
// bool: _shouldStablize
// bool: _shouldMaintainInfo
// double: _maxTrendRatio
// float[]: _wTrans (only if _isWeightSet == true)
_seriesLength = ctx.Reader.ReadInt32();
// Do an early check. We'll have the stricter check later.
_host.CheckDecode(_seriesLength > 2);
_windowSize = ctx.Reader.ReadInt32();
_host.CheckDecode(_windowSize >= 2);
_host.CheckDecode(_seriesLength > _windowSize);
_trainSize = ctx.Reader.ReadInt32();
_host.CheckDecode(_trainSize > 2 * _windowSize);
_rank = ctx.Reader.ReadInt32();
_host.CheckDecode(1 <= _rank && _rank < _windowSize);
_discountFactor = ctx.Reader.ReadSingle();
_host.CheckDecode(0 <= _discountFactor && _discountFactor <= 1);
byte temp;
temp = ctx.Reader.ReadByte();
_rankSelectionMethod = (RankSelectionMethod)temp;
bool isWeightSet = ctx.Reader.ReadBoolByte();
_alpha = ctx.Reader.ReadFloatArray();
_host.CheckDecode(Utils.Size(_alpha) == _windowSize - 1);
if (ctx.Header.ModelVerReadable >= VersionSavingStateAndPrediction)
{
_state = ctx.Reader.ReadFloatArray();
_host.CheckDecode(Utils.Size(_state) == _windowSize - 1);
}
else
_state = new Single[_windowSize - 1];
ShouldComputeForecastIntervals = ctx.Reader.ReadBoolByte();
_observationNoiseVariance = ctx.Reader.ReadSingle();
_host.CheckDecode(_observationNoiseVariance >= 0);
_autoregressionNoiseVariance = ctx.Reader.ReadSingle();
_host.CheckDecode(_autoregressionNoiseVariance >= 0);
_observationNoiseMean = ctx.Reader.ReadSingle();
_autoregressionNoiseMean = ctx.Reader.ReadSingle();
if (ctx.Header.ModelVerReadable >= VersionSavingStateAndPrediction)
_nextPrediction = ctx.Reader.ReadSingle();
_maxRank = ctx.Reader.ReadInt32();
_host.CheckDecode(1 <= _maxRank && _maxRank <= _windowSize - 1);
_shouldStablize = ctx.Reader.ReadBoolByte();
_shouldMaintainInfo = ctx.Reader.ReadBoolByte();
if (_shouldMaintainInfo)
{
_info = new ModelInfo();
_info.AutoRegressiveCoefficients = new Single[_windowSize - 1];
Array.Copy(_alpha, _info.AutoRegressiveCoefficients, _windowSize - 1);
_info.IsStabilized = _shouldStablize;
_info.Rank = _rank;
_info.WindowSize = _windowSize;
}
_maxTrendRatio = ctx.Reader.ReadDouble();
_host.CheckDecode(_maxTrendRatio >= 0);
if (isWeightSet)
{
var tempArray = ctx.Reader.ReadFloatArray();
_host.CheckDecode(Utils.Size(tempArray) == _rank * _windowSize);
_wTrans = new CpuAlignedMatrixRow(_rank, _windowSize, SseUtils.CbAlign);
int i = 0;
_wTrans.CopyFrom(tempArray, ref i);
}
_buffer = new FixedSizeQueue<Single>(_seriesLength);
_x = new CpuAlignedVector(_windowSize, SseUtils.CbAlign);
_xSmooth = new CpuAlignedVector(_windowSize, SseUtils.CbAlign);
}
public void Save(ModelSaveContext ctx)
{
_host.CheckValue(ctx, nameof(ctx));
ctx.CheckAtModel();
ctx.SetVersionInfo(GetVersionInfo());
_host.Assert(_windowSize >= 2);
_host.Assert(_seriesLength > _windowSize);
_host.Assert(_trainSize > 2 * _windowSize);
_host.Assert(0 <= _discountFactor && _discountFactor <= 1);
_host.Assert(1 <= _rank && _rank < _windowSize);
_host.Assert(Utils.Size(_alpha) == _windowSize - 1);
_host.Assert(_observationNoiseVariance >= 0);
_host.Assert(_autoregressionNoiseVariance >= 0);
_host.Assert(1 <= _maxRank && _maxRank <= _windowSize - 1);
_host.Assert(_maxTrendRatio >= 0);
// *** Binary format ***
// int: _seriesLength
// int: _windowSize
// int: _trainSize
// int: _rank
// float: _discountFactor
// RankSelectionMethod: _rankSelectionMethod
// bool: _isWeightSet
// float[]: _alpha
// float[]: _state
// bool: ShouldComputeForecastIntervals
// float: _observationNoiseVariance
// float: _autoregressionNoiseVariance
// float: _observationNoiseMean
// float: _autoregressionNoiseMean
// float: _nextPrediction
// int: _maxRank
// bool: _shouldStablize
// bool: _shouldMaintainInfo
// double: _maxTrendRatio
// float[]: _wTrans (only if _isWeightSet == true)
ctx.Writer.Write(_seriesLength);
ctx.Writer.Write(_windowSize);
ctx.Writer.Write(_trainSize);
ctx.Writer.Write(_rank);
ctx.Writer.Write(_discountFactor);
ctx.Writer.Write((byte)_rankSelectionMethod);
ctx.Writer.WriteBoolByte(_wTrans != null);
ctx.Writer.WriteFloatArray(_alpha);
ctx.Writer.WriteFloatArray(_state);
ctx.Writer.WriteBoolByte(ShouldComputeForecastIntervals);
ctx.Writer.Write(_observationNoiseVariance);
ctx.Writer.Write(_autoregressionNoiseVariance);
ctx.Writer.Write(_observationNoiseMean);
ctx.Writer.Write(_autoregressionNoiseMean);
ctx.Writer.Write(_nextPrediction);
ctx.Writer.Write(_maxRank);
ctx.Writer.WriteBoolByte(_shouldStablize);
ctx.Writer.WriteBoolByte(_shouldMaintainInfo);
ctx.Writer.Write(_maxTrendRatio);
if (_wTrans != null)
{
// REVIEW: this may not be the most efficient way for serializing an aligned matrix.
var tempArray = new Single[_rank * _windowSize];
int iv = 0;
_wTrans.CopyTo(tempArray, ref iv);
ctx.Writer.WriteFloatArray(tempArray);
}
}
private static void ReconstructSignal(TrajectoryMatrix tMat, Single[] singularVectors, int rank, Single[] output)
{
Contracts.Assert(tMat != null);
Contracts.Assert(1 <= rank && rank <= tMat.WindowSize);
Contracts.Assert(Utils.Size(singularVectors) >= tMat.WindowSize * rank);
Contracts.Assert(Utils.Size(output) >= tMat.SeriesLength);
var k = tMat.SeriesLength - tMat.WindowSize + 1;
Contracts.Assert(k > 0);
var v = new Single[k];
int i;
for (i = 0; i < tMat.SeriesLength; ++i)
output[i] = 0;
for (i = 0; i < rank; ++i)
{
// Reconstructing the i-th eigen triple component and adding it to output
tMat.MultiplyTranspose(singularVectors, v, false, tMat.WindowSize * i, 0);
tMat.RankOneHankelization(singularVectors, v, 1, output, true, tMat.WindowSize * i, 0, 0);
}
}
private static void ReconstructSignalTailFast(Single[] series, TrajectoryMatrix tMat, Single[] singularVectors, int rank, Single[] output)
{
Contracts.Assert(tMat != null);
Contracts.Assert(1 <= rank && rank <= tMat.WindowSize);
Contracts.Assert(Utils.Size(singularVectors) >= tMat.WindowSize * rank);
int len = 2 * tMat.WindowSize - 1;
Contracts.Assert(Utils.Size(output) >= len);
Single v;
/*var k = tMat.SeriesLength - tMat.WindowSize + 1;
Contracts.Assert(k > 0);
var v = new Single[k];*/
Single temp;
int i;
int j;
int offset1 = tMat.SeriesLength - 2 * tMat.WindowSize + 1;
int offset2 = tMat.SeriesLength - tMat.WindowSize;
for (i = 0; i < len; ++i)
output[i] = 0;
for (i = 0; i < rank; ++i)
{
// Reconstructing the i-th eigen triple component and adding it to output
v = 0;
for (j = offset1; j < offset1 + tMat.WindowSize; ++j)
v += series[j] * singularVectors[tMat.WindowSize * i - offset1 + j];
for (j = 0; j < tMat.WindowSize - 1; ++j)
output[j] += v * singularVectors[tMat.WindowSize * i + j];
temp = v * singularVectors[tMat.WindowSize * (i + 1) - 1];
v = 0;
for (j = offset2; j < offset2 + tMat.WindowSize; ++j)
v += series[j] * singularVectors[tMat.WindowSize * i - offset2 + j];
for (j = tMat.WindowSize; j < 2 * tMat.WindowSize - 1; ++j)
output[j] += v * singularVectors[tMat.WindowSize * (i - 1) + j + 1];
temp += v * singularVectors[tMat.WindowSize * i];
output[tMat.WindowSize - 1] += (temp / 2);
}
}
private static void ComputeNoiseMoments(Single[] series, Single[] signal, Single[] alpha, out Single observationNoiseVariance, out Single autoregressionNoiseVariance,
out Single observationNoiseMean, out Single autoregressionNoiseMean, int startIndex = 0)
{
Contracts.Assert(Utils.Size(alpha) > 0);
Contracts.Assert(Utils.Size(signal) > 2 * Utils.Size(alpha)); // To assure that the autoregression noise variance is unbiased.
Contracts.Assert(Utils.Size(series) >= Utils.Size(signal) + startIndex);
var signalLength = Utils.Size(signal);
var windowSize = Utils.Size(alpha) + 1;
var k = signalLength - windowSize + 1;
Contracts.Assert(k > 0);
var y = new Single[k];
int i;
observationNoiseMean = 0;
observationNoiseVariance = 0;
autoregressionNoiseMean = 0;
autoregressionNoiseVariance = 0;
// Computing the observation noise moments
for (i = 0; i < signalLength; ++i)
observationNoiseMean += (series[i + startIndex] - signal[i]);
observationNoiseMean /= signalLength;
for (i = 0; i < signalLength; ++i)
observationNoiseVariance += (series[i + startIndex] - signal[i]) * (series[i + startIndex] - signal[i]);
observationNoiseVariance /= signalLength;
observationNoiseVariance -= (observationNoiseMean * observationNoiseMean);
// Computing the auto-regression noise moments
TrajectoryMatrix xTM = new TrajectoryMatrix(null, signal, windowSize - 1, signalLength - 1);
xTM.MultiplyTranspose(alpha, y);
for (i = 0; i < k; ++i)
autoregressionNoiseMean += (signal[windowSize - 1 + i] - y[i]);
autoregressionNoiseMean /= k;
for (i = 0; i < k; ++i)
{
autoregressionNoiseVariance += (signal[windowSize - 1 + i] - y[i] - autoregressionNoiseMean) *
(signal[windowSize - 1 + i] - y[i] - autoregressionNoiseMean);
}
autoregressionNoiseVariance /= (k - windowSize + 1);
Contracts.Assert(autoregressionNoiseVariance >= 0);
}
private static int DetermineSignalRank(Single[] series, TrajectoryMatrix tMat, Single[] singularVectors, Single[] singularValues,
Single[] outputSignal, int maxRank)
{
Contracts.Assert(tMat != null);
Contracts.Assert(Utils.Size(series) >= tMat.SeriesLength);
Contracts.Assert(Utils.Size(outputSignal) >= tMat.SeriesLength);
Contracts.Assert(Utils.Size(singularVectors) >= tMat.WindowSize * tMat.WindowSize);
Contracts.Assert(Utils.Size(singularValues) >= tMat.WindowSize);
Contracts.Assert(1 <= maxRank && maxRank <= tMat.WindowSize - 1);
var inputSeriesLength = tMat.SeriesLength;
var k = inputSeriesLength - tMat.WindowSize + 1;
Contracts.Assert(k > 0);
var x = new Single[inputSeriesLength];
var y = new Single[k];
var alpha = new Single[tMat.WindowSize - 1];
var v = new Single[k];
Single nu = 0;
Double minErr = Double.MaxValue;
int minIndex = maxRank - 1;
int evaluationLength = Math.Min(Math.Max(tMat.WindowSize, 200), k);
TrajectoryMatrix xTM = new TrajectoryMatrix(null, x, tMat.WindowSize - 1, inputSeriesLength - 1);
int i;
int j;
int n;
Single temp;
Double error;
Double sumSingularVals = 0;
Single lambda;
Single observationNoiseMean;
FixedSizeQueue<Single> window = new FixedSizeQueue<float>(tMat.WindowSize - 1);
for (i = 0; i < tMat.WindowSize; ++i)
sumSingularVals += singularValues[i];
for (i = 0; i < maxRank; ++i)
{
// Updating the auto-regressive coefficients
lambda = singularVectors[tMat.WindowSize * i + tMat.WindowSize - 1];
for (j = 0; j < tMat.WindowSize - 1; ++j)
alpha[j] += lambda * singularVectors[tMat.WindowSize * i + j];
// Updating nu
nu += lambda * lambda;
// Reconstructing the i-th eigen triple component and adding it to x
tMat.MultiplyTranspose(singularVectors, v, false, tMat.WindowSize * i, 0);
tMat.RankOneHankelization(singularVectors, v, 1, x, true, tMat.WindowSize * i, 0, 0);
observationNoiseMean = 0;
for (j = 0; j < inputSeriesLength; ++j)
observationNoiseMean += (series[j] - x[j]);
observationNoiseMean /= inputSeriesLength;
for (j = inputSeriesLength - evaluationLength - tMat.WindowSize + 1; j < inputSeriesLength - evaluationLength; ++j)
window.AddLast(x[j]);
error = 0;
for (j = inputSeriesLength - evaluationLength; j < inputSeriesLength; ++j)
{
temp = 0;
for (n = 0; n < tMat.WindowSize - 1; ++n)
temp += alpha[n] * window[n];
temp /= (1 - nu);
temp += observationNoiseMean;
window.AddLast(temp);
error += Math.Abs(series[j] - temp);
if (error > minErr)
break;
}
if (error < minErr)
{
minErr = error;
minIndex = i;
Array.Copy(x, outputSignal, inputSeriesLength);
}
}
return minIndex + 1;
}
public void InitState()
{
for (int i = 0; i < _windowSize - 2; ++i)
_state[i] = 0;
_buffer.Clear();
}
private static int DetermineSignalRankFast(Single[] series, TrajectoryMatrix tMat, Single[] singularVectors, Single[] singularValues, int maxRank)
{
Contracts.Assert(tMat != null);
Contracts.Assert(Utils.Size(series) >= tMat.SeriesLength);
Contracts.Assert(Utils.Size(singularVectors) >= tMat.WindowSize * tMat.WindowSize);
Contracts.Assert(Utils.Size(singularValues) >= tMat.WindowSize);
Contracts.Assert(1 <= maxRank && maxRank <= tMat.WindowSize - 1);
var inputSeriesLength = tMat.SeriesLength;
var k = inputSeriesLength - tMat.WindowSize + 1;
Contracts.Assert(k > 0);
var x = new Single[tMat.WindowSize - 1];
var alpha = new Single[tMat.WindowSize - 1];
Single v;
Single nu = 0;
Double minErr = Double.MaxValue;
int minIndex = maxRank - 1;
int evaluationLength = Math.Min(Math.Max(tMat.WindowSize, 200), k);
int i;
int j;
int n;
int offset;
Single temp;
Double error;
Single lambda;
Single observationNoiseMean;
FixedSizeQueue<Single> window = new FixedSizeQueue<float>(tMat.WindowSize - 1);
for (i = 0; i < maxRank; ++i)
{
// Updating the auto-regressive coefficients
lambda = singularVectors[tMat.WindowSize * i + tMat.WindowSize - 1];
for (j = 0; j < tMat.WindowSize - 1; ++j)
alpha[j] += lambda * singularVectors[tMat.WindowSize * i + j];
// Updating nu
nu += lambda * lambda;
// Reconstructing the i-th eigen triple component and adding it to x
v = 0;
offset = inputSeriesLength - evaluationLength - tMat.WindowSize + 1;
for (j = offset; j <= inputSeriesLength - evaluationLength; ++j)
v += series[j] * singularVectors[tMat.WindowSize * i - offset + j];
for (j = 0; j < tMat.WindowSize - 1; ++j)
x[j] += v * singularVectors[tMat.WindowSize * i + j];
// Computing the empirical observation noise mean
observationNoiseMean = 0;
for (j = offset; j < inputSeriesLength - evaluationLength; ++j)
observationNoiseMean += (series[j] - x[j - offset]);
observationNoiseMean /= (tMat.WindowSize - 1);
for (j = 0; j < tMat.WindowSize - 1; ++j)
window.AddLast(x[j]);
error = 0;
for (j = inputSeriesLength - evaluationLength; j < inputSeriesLength; ++j)
{
temp = 0;
for (n = 0; n < tMat.WindowSize - 1; ++n)
temp += alpha[n] * window[n];
temp /= (1 - nu);
temp += observationNoiseMean;
window.AddLast(temp);
error += Math.Abs(series[j] - temp);
if (error > minErr)
break;
}
if (error < minErr)
{
minErr = error;
minIndex = i;
}
}
return minIndex + 1;
}
private class SignalComponent
{
public Double Phase;
public int Index;
public int Cluster;
public SignalComponent(Double phase, int index)
{
Phase = phase;
Index = index;
}
}
private bool Stabilize()
{
if (Utils.Size(_alpha) == 1)
{
if (_shouldMaintainInfo)
_info.RootsBeforeStabilization = new[] { new Complex(_alpha[0], 0) };
if (_alpha[0] > 1)
_alpha[0] = 1;
else if (_alpha[0] < -1)
_alpha[0] = -1;
if (_shouldMaintainInfo)
{
_info.IsStabilized = true;
_info.RootsAfterStabilization = new[] { new Complex(_alpha[0], 0) };
_info.IsExponentialTrendPresent = false;
_info.IsPolynomialTrendPresent = false;
_info.ExponentialTrendFactor = Math.Abs(_alpha[0]);
}
return true;
}
var coeff = new Double[_windowSize - 1];
Complex[] roots = null;
bool trendFound = false;
bool polynomialTrendFound = false;
Double maxTrendMagnitude = Double.NegativeInfinity;
Double maxNonTrendMagnitude = Double.NegativeInfinity;
Double eps = 1e-9;
Double highFrequenceyBoundry = Math.PI / 2;
var sortedComponents = new List<SignalComponent>();
var trendComponents = new List<int>();
int i;
// Computing the roots of the characteristic polynomial
for (i = 0; i < _windowSize - 1; ++i)
coeff[i] = -_alpha[i];
if (!PolynomialUtils.FindPolynomialRoots(coeff, ref roots))
return false;
if (_shouldMaintainInfo)
{
_info.RootsBeforeStabilization = new Complex[_windowSize - 1];
Array.Copy(roots, _info.RootsBeforeStabilization, _windowSize - 1);
}
// Detecting trend components
for (i = 0; i < _windowSize - 1; ++i)
{
if (roots[i].Magnitude > 1 && (Math.Abs(roots[i].Phase) <= eps || Math.Abs(Math.Abs(roots[i].Phase) - Math.PI) <= eps))
trendComponents.Add(i);
}
// Removing unobserved seasonalities and consequently introducing polynomial trend
for (i = 0; i < _windowSize - 1; ++i)
{
if (roots[i].Phase != 0)
{
if (roots[i].Magnitude >= 1 && 2 * Math.PI / Math.Abs(roots[i].Phase) > _windowSize)
{
/*if (roots[i].Real > 1)
{
polynomialTrendFound = true;
roots[i] = new Complex(Math.Max(1, roots[i].Magnitude), 0);
maxPolynomialTrendMagnitude = Math.Max(maxPolynomialTrendMagnitude, roots[i].Magnitude);
}
else
roots[i] = Complex.FromPolarCoordinates(1, 0);
//roots[i] = Complex.FromPolarCoordinates(0.99, roots[i].Phase);*/
/* if (_maxTrendRatio > 1)
{
roots[i] = new Complex(roots[i].Real, 0);
polynomialTrendFound = true;
}
else
roots[i] = roots[i].Imaginary > 0 ? new Complex(roots[i].Real, 0) : new Complex(1, 0);*/
roots[i] = new Complex(roots[i].Real, 0);
polynomialTrendFound = true;
if (_shouldMaintainInfo)
_info.IsArtificialSeasonalityRemoved = true;
}
else if (roots[i].Magnitude > 1)
sortedComponents.Add(new SignalComponent(roots[i].Phase, i));
}
}
if (_maxTrendRatio > 1)
{
// Combining the close exponential-seasonal components
if (sortedComponents.Count > 1 && polynomialTrendFound)
{
sortedComponents.Sort((a, b) => a.Phase.CompareTo(b.Phase));
var clusterNum = 0;
for (i = 0; i < sortedComponents.Count - 1; ++i)
{
if ((sortedComponents[i].Phase < 0 && sortedComponents[i + 1].Phase < 0) ||
(sortedComponents[i].Phase > 0 && sortedComponents[i + 1].Phase > 0))
{
sortedComponents[i].Cluster = clusterNum;
if (Math.Abs(sortedComponents[i + 1].Phase - sortedComponents[i].Phase) > 0.05)
clusterNum++;
sortedComponents[i + 1].Cluster = clusterNum;
}
else
clusterNum++;
}
int start = 0;
bool polynomialSeasonalityFound = false;
Double largestSeasonalityPhase = 0;
for (i = 1; i < sortedComponents.Count; ++i)
{
if (sortedComponents[i].Cluster != sortedComponents[i - 1].Cluster)
{
if (i - start > 1) // There are more than one point in the cluster
{
Double avgPhase = 0;
Double avgMagnitude = 0;
for (var j = start; j < i; ++j)
{
avgPhase += sortedComponents[j].Phase;
avgMagnitude += roots[sortedComponents[j].Index].Magnitude;
}
avgPhase /= (i - start);
avgMagnitude /= (i - start);
for (var j = start; j < i; ++j)
roots[sortedComponents[j].Index] = Complex.FromPolarCoordinates(avgMagnitude,
avgPhase);
if (!polynomialSeasonalityFound && avgPhase > 0)
{
largestSeasonalityPhase = avgPhase;
polynomialSeasonalityFound = true;
}
}
start = i;
}
}
}
// Combining multiple exponential trends into polynomial ones