-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBSMmodel.h
2414 lines (2409 loc) · 94.5 KB
/
BSMmodel.h
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
/*************************
Basic Structural models
Needs Armadillo
Needs SSpace.h
Needs ARMAmodel.h
Needs BSMident.h
Needs stats.h
Needs DJPTtools.h
***************************/
bool RUNNING_FROM_R = true;
struct BSMinputs{
string model = "llt/none/equal/arma(0,0)", // model to fit
criterion = "aic", // identification criterion
trend, // type of trend
cycle, // type of cycle
seasonal, // type of seasonal component
irregular, // type of irregular
cycle0; // type of cycle without numbers
int ar, ma; // AR and MA orders of irregular component
double seas; // seasonal period
vec periods, // vector of periods for harmonics
rhos, // vector indicating whether period is cyclical or seasonal
ns, // number of states in components (trend, cycle, seasonal, irregular)
nPar, // number of parameters in components (trend, cycle, seasonal, irregular)
p0Return, // initial parameters user understandable
typePar, // type of parameter (0: variance;
// -1: damped of trend;
// 1: cycle rhos;
// 2: cycle periods;
// 3: ARMA;
// 4: inputs)
eps, // observation perturbation
beta0ARMA, // initial estimates of ARMA model (without variance)
constPar; // constrained parameters (0: not constrained;
// 1: concentrated-out;
// 2: variance constrained to 0;
// 3: alpha constrained to 0 or 1)
uvec harmonics; // vector with the indices of harmonics selected
mat comp, // estimated components
compV, // variance of components
typeOutliers, // Matrix with type of outliers and sample of each outlier
cycleLimits; // limits for period of cycle estimation
bool stepwise, // stepwise identification or brute one
tTest = false, // unit roots test or not for identification
arma = true, // check arma models for irregular component
pureARMA = false; // Pure ARMA model flag
vector<string> parNames; // Parameter names
};
/**************************
* Model CLASS BSM
***************************/
class BSMmodel : public SSmodel{
private:
BSMinputs inputs;
// Set model
void setModel(string, vec, vec, bool);
// Count states and parameters of BSM model
void countStates(vec, string, string, string, string);
// Fix matrices in standard BSM models (all except variances)
void initMatricesBsm(vec, vec, string, string, string, string);
// Initializing parameters of BSM model
void initParBsm();
// Optimization routine
int quasiNewtonBSM(std::function <double (vec&, void*)>,
std::function <vec (vec&, void*, double, int&)>,
vec&, void*, double&, vec&, mat&, bool);
// Estimation of a family of UC models
void estimUCs(vector<string>, uvec, double&, bool, double, int);
public:
// Constructors
BSMmodel(SSinputs, BSMinputs);
// Parameter names
void parLabels();
//Estimation
void estim();
void estim(vec);
// Identification
void ident(string);
// Outlier detection
void estimOutlier(vec);
// Check whether re-estimation is necessary
void checkModel();
// Components
void components();
// Covariance of parameters (inverse of hessian)
mat parCov(vec&);
// Finding true parameter values out of transformed parameters
vec parameterValues(vec);
// Validation of BSM models
void validate();
// Disturbance smoother (to recover just trend and epsilons)
void disturb();
// Get data
BSMinputs getInputs(){
parLabels();
return inputs;
}
// Set data
void setInputs(BSMinputs inputs){
this->inputs = inputs;
}
//Print inputs on screen
// void showInputs();
};
/***************************************************
* Auxiliar function declarations
****************************************************/
// Variance matrices in standard BSM
void bsmMatrices(vec, SSmatrix*, void*);
// Variance matrices in standard BSM for true parameters
void bsmMatricesTrue(vec, SSmatrix*, void*);
// Extract trend seasonal and irregular of model in a string
void splitModel(string, string&, string&, string&, string&);
// SS form of trend models
void trend2ss(int, mat*, mat*);
// SS form of seasonal models
void bsm2ss(int, int, vec, vec, mat*, mat*);
// Remove elements of vector in n adjacent points
uvec selectOutliers(vec&, int, float);
// Create dummy variable for outliers 0: AO, 1: LS, 2: SC
void dummy(uword, uword, rowvec&);
// combining UC models
void findUCmodels(string, string, string, string, vector<string>&);
// Corrects model, cycle string, periods and rhos for modelling cycles
void modelCorrect(string&, string&, string&, vec&, vec&);
// Calculate limits for cycle periods for estimation
void calculateLimits(int, vec, vec, mat&, double);
/****************************************************
// BSM implementations for univariate UC models
****************************************************/
// Constructor
BSMmodel::BSMmodel(SSinputs data, BSMinputs inputs) : SSmodel(data){
inputs.rhos = ones(size(inputs.periods));
lower(inputs.criterion);
SSmodel::inputs = data;
this->inputs = inputs;
this->inputs.cycleLimits.resize(1, 1);
this->inputs.cycleLimits(0, 0) = datum::nan;
vec reserve = inputs.constPar;
setModel(inputs.model, inputs.periods, inputs.rhos, true);
if (!reserve.has_nan())
this->inputs.constPar = reserve;
inputs.harmonics = regspace<uvec>(0, inputs.periods.n_elem - 1);
}
// Set model (part of constructor)
void BSMmodel::setModel(string model, vec periods, vec rhos, bool runFromConstructor){
string trend, cycle, seasonal, irregular;
vec ns(5), nPar(5), typePar, noVar, constPar;
mat cycleLimits;
splitModel(model, trend, cycle, seasonal, irregular);
// Checking cycle model and correcting from string input
if (cycle[0] != 'n' && cycle != "?"){
modelCorrect(model, cycle, inputs.cycle0, periods, rhos);
}
if (cycle[0] != 'n' && inputs.cycleLimits.has_nan()){
calculateLimits(SSmodel::inputs.y.n_elem, periods, rhos, cycleLimits, inputs.seas);
this->inputs.cycleLimits = cycleLimits;
} else if (cycle[0] != 'n') {
cycleLimits = inputs.cycleLimits;
}
// Checking for arma identification
if (irregular != "?"){
inputs.arma = 0;
}
// Checking for constant input from user and removing in that case
if (SSmodel::inputs.u.n_rows > 0){
uvec rowCnt = find(sum(SSmodel::inputs.u - 1, 1) == 0);
SSmodel::inputs.u.shed_rows(rowCnt);
}
// Initializing matrices
if (trend != "?" && cycle != "?" && seasonal != "?" && irregular != "?"){ // One model
initMatricesBsm(periods, rhos, trend, cycle, seasonal, irregular);
this->inputs.model = model;
if (cycle[0] != 'n'){
this->inputs.periods = periods;
this->inputs.rhos = rhos;
}
this->SSmodel::inputs.userInputs = &this->inputs;
// User function to fill the changing matrices
this->SSmodel::inputs.userModel = bsmMatrices;
// Initializing parameters of BSM model
if (!runFromConstructor)
SSmodel::inputs.p0(0) = -9999.9;
typePar = this->inputs.typePar;
// inputs.beta0ARMA.reset();
initParBsm();
}
// Making coherent h and size(u)
if (SSmodel::inputs.u.n_elem > 0){
SSmodel::inputs.h = SSmodel::inputs.u.n_cols - SSmodel::inputs.y.n_elem;
}
this->inputs.trend = trend;
this->inputs.cycle = cycle;
this->inputs.seasonal = seasonal;
this->inputs.irregular = irregular;
}
// Print inputs on screen
// void BSMmodel::showInputs(){
// cout << "**************************" << endl;
// cout << "Start of BSM system:" << endl;
// cout << "Model: " << inputs.model << endl;
// cout << "criterion: " << inputs.criterion << endl;
// cout << "trend: " << inputs.trend << endl;
// cout << "cycle: " << inputs.cycle << endl;
// cout << "seasonal: " << inputs.seasonal << endl;
// cout << "irregular: " << inputs.irregular << endl;
// cout << "cycle0: " << inputs.cycle0 << endl;
// cout << "ar: " << inputs.ar << endl;
// cout << "ma: " << inputs.ma << endl;
// inputs.periods.t().print("periods:");
// inputs.rhos.t().print("rhos:");
// inputs.ns.t().print("ns:");
// inputs.nPar.t().print("nPar:");
// inputs.typePar.t().print("typePar:");
// inputs.beta0ARMA.t().print("beta0ARMA:");
// inputs.constPar.t().print("constPar");
// inputs.harmonics.t().print("harmonics:");
// inputs.typeOutliers.t().print("typeOutliers:");
// inputs.cycleLimits.print("cycleLimits:");
// cout << "stepwise: " << inputs.stepwise << endl;
// cout << "tTest: " << inputs.tTest << endl;
// cout << "arma: " << inputs.arma << endl;
// inputs.eps.t().print("eps:");
// cout << "End of BSM system:" << endl;
// cout << "**************************" << endl;
// }
// Estimation: runs estim(p) or ident()
void BSMmodel::estim(){
if (inputs.trend != "?" && inputs.cycle != "?" && inputs.seasonal != "?" && inputs.irregular != "?"){
// Particular model
if (SSmodel::inputs.outlier == 0){
// Without outlier detection
estim(SSmodel::inputs.p0);
checkModel();
} else {
// With outlier detection
estimOutlier(SSmodel::inputs.p0);
}
} else {
// Some or all the components to identify
string cycle = inputs.cycle;
string cycle0 = inputs.cycle0;
size_t found = cycle.find('?');
if (found != string::npos && inputs.arma){ // cycle has ?
BSMinputs old = inputs;
SSinputs oldSS = SSmodel::inputs;
// First estimation with cycle
inputs.cycle = inputs.cycle0;
ident("head");
SSinputs bestSS = SSmodel::inputs;
BSMinputs bestBSM = inputs;
inputs = old;
SSmodel::inputs = oldSS;
// Second estimation without cycle
inputs.cycle = "none";
strReplace("?", "", inputs.cycle0);
ident("tail");
// Now decide which is best
int crit = 1;
if (inputs.criterion == "bic"){
crit = 2;
} else if (inputs.criterion == "aicc"){
crit = 3;
}
if (SSmodel::inputs.criteria(crit) > bestSS.criteria(crit)){
SSmodel::inputs = bestSS;
inputs = bestBSM;
}
inputs.cycle = cycle;
inputs.cycle0 = cycle0;
} else {
// Estimation as is
ident("both");
}
}
}
// Check whether re-estimation is necessary
void BSMmodel::checkModel(){
// Repeat estimation of one model in case of anomalies
string ok = SSmodel::inputs.estimOk;
bool add = (inputs.model[0] == 'd');
bool printed = false;
// If no convergence and llt or dt trend model, then slope p0 more rigid
if ((ok[10] == 'M' || ok[10] == 'U' || ok[10] == 'O' || ok[10] == 'N') &&
(inputs.model[0] == 'l' || inputs.model[0] == 'd')){
// Next 5 lines in every exception
if (SSmodel::inputs.verbose){
printf(" --\n");
printf(" Estimation problems, trying again...\n");
printf(" --\n");
printed = true;
}
SSinputs old = SSmodel::inputs;
setModel(inputs.model, inputs.periods(inputs.harmonics), inputs.rhos(inputs.harmonics), false);
bool VERBOSE = old.verbose;
SSmodel::inputs.verbose = false;
SSmodel::inputs.p0(1 + add) = -6.2325;
// Estimation of particular model
if (SSmodel::inputs.outlier == 0){
// Without outlier detection
estim(SSmodel::inputs.p0);
} else {
// With outlier detection
estimOutlier(SSmodel::inputs.p0);
}
if (!old.criteria.has_nan() &&
(old.criteria(1) < SSmodel::inputs.criteria(1))){
SSmodel::inputs = old;
SSmodel::inputs.verbose = VERBOSE;
}
}
// Repeat estimation of one model in case of anomalies
ok = SSmodel::inputs.estimOk;
//add = (inputs.model[0] == 'd');
// If no convergence and llt or dt trend model, then level p0 more rigid
if ((ok[10] == 'M' || ok[10] == 'U' || ok[10] == 'O' || ok[10] == 'N') &&
(inputs.model[0] == 'l' || inputs.model[0] == 'd')){
// Next 5 lines in every exception
if (SSmodel::inputs.verbose && !printed){
printf(" --\n");
printf(" Estimation problems, trying again...\n");
printf(" --\n");
printed = true;
}
SSinputs old = SSmodel::inputs;
setModel(inputs.model, inputs.periods(inputs.harmonics), inputs.rhos(inputs.harmonics), false);
bool VERBOSE = old.verbose;
SSmodel::inputs.verbose = false;
SSmodel::inputs.p0(0 + add) = -6.2325;
// Estimation of particular model
if (SSmodel::inputs.outlier == 0){
// Without outlier detection
estim(SSmodel::inputs.p0);
} else {
// With outlier detection
estimOutlier(SSmodel::inputs.p0);
}
if (!old.criteria.has_nan() &&
(old.criteria(1) < SSmodel::inputs.criteria(1))){
SSmodel::inputs = old;
SSmodel::inputs.verbose = VERBOSE;
}
}
}
void BSMmodel::estim(vec p){
double objFunValue;
vec grad;
mat iHess;
int flag; //, nPar, k;
SSmodel::inputs.p0 = p;
wall_clock timer;
timer.tic();
if (SSmodel::inputs.augmented){
SSmodel::inputs.llikFUN = llikAug;
} else {
SSmodel::inputs.llikFUN = llik;
}
flag = quasiNewtonBSM(SSmodel::inputs.llikFUN, gradLlik, p, &(SSmodel::inputs),
objFunValue, grad, iHess, SSmodel::inputs.verbose);
uvec indNan = find_nonfinite(SSmodel::inputs.y);
int nNan2pi = SSmodel::inputs.y.n_elem - indNan.n_elem;
int nTrue;
if (SSmodel::inputs.augmented){
nTrue = nNan2pi - SSmodel::inputs.u.n_rows - SSmodel::inputs.system.T.n_rows;
uvec stat;
isStationary(SSmodel::inputs.system.T, stat);
SSmodel::inputs.nonStationaryTerms = SSmodel::inputs.system.T.n_rows - stat.n_elem;
// Correction for DT trend models
// if (inputs.model[0] == 'd' && stat.n_elem > 0 && stat[0] == 1){
// SSmodel::inputs.nonStationaryTerms++;
// }
} else {
if (SSmodel::inputs.d_t < (int)(SSmodel::inputs.system.T.n_rows + 10)){
// Colapsed KF
nTrue = nNan2pi - 1 - SSmodel::inputs.d_t;
} else {
// KF did not colapsed
nTrue = nNan2pi - 1 - SSmodel::inputs.system.T.n_rows;
}
}
double LLIK, AIC, BIC, AICc;
// Exception when function is nan
if (flag > 6){
objFunValue = datum::nan;
}
LLIK = -0.5 * (log(2*datum::pi) * nNan2pi + nTrue * objFunValue);
infoCriteria(LLIK, p.n_elem - SSmodel::inputs.cLlik + SSmodel::inputs.u.n_rows + SSmodel::inputs.nonStationaryTerms,
nNan2pi, AIC, BIC, AICc);
vec criteria(4);
criteria(0) = LLIK;
criteria(1) = AIC;
criteria(2) = BIC;
criteria(3) = AICc;
SSmodel::inputs.criteria = criteria;
if (flag == 1) {
SSmodel::inputs.estimOk = "Q-Newton: Gradient convergence\n";
} else if (flag == 2){
SSmodel::inputs.estimOk = "Q-Newton: Function convergence\n";
} else if (flag == 3){
SSmodel::inputs.estimOk = "Q-Newton: Parameter convergence\n";
} else if (flag == 4){
SSmodel::inputs.estimOk = "Q-Newton: Maximum Number of iterations reached\n";
} else if (flag == 5){
SSmodel::inputs.estimOk = "Q-Newton: Maximum Number of function evaluations\n";
} else if (flag == 6){
SSmodel::inputs.estimOk = "Q-Newton: Unable to decrease objective function\n";
} else if (flag == 7){
SSmodel::inputs.estimOk = "Q-Newton: Objective function returns nan\n";
objFunValue = datum::nan;
} else {
SSmodel::inputs.estimOk = "Q-Newton: No convergence!!\n";
}
if (SSmodel::inputs.verbose){
double nSeconds = timer.toc();
printf("%s", SSmodel::inputs.estimOk.c_str());
printf("Elapsed time: %10.5f seconds\n", nSeconds);
}
SSmodel::inputs.p = p;
SSmodel::inputs.objFunValue = objFunValue;
SSmodel::inputs.grad = grad;
// Eliminating cycle periods
uvec aux = find(inputs.rhos > 0);
inputs.rhos = inputs.rhos(aux);
inputs.periods = inputs.periods(aux);
SSmodel::inputs.v.reset();
inputs.harmonics = regspace<uvec>(0, inputs.periods.n_elem - 1);
}
// Estimation of a family of UC models
void BSMmodel::estimUCs(vector <string> allUCModels, uvec harmonics,
double& minCrit, bool VERBOSE,
double oldMinCrit, int nuInit){
// Estim a number of UC models and select the best according to minCrit
// The best is compared to oldMinCrit that is the current best system
// and the overall best is put into SSmodel::inputs and inputs
// If there is no previous model to compare to set oldMinCrit to 1e12
double curCrit,
AIC,
BIC,
AICc;
SSinputs bestSS = SSmodel::inputs;
BSMinputs bestBSM = inputs;
if (isnan(oldMinCrit)){
oldMinCrit = 1e12;
}
minCrit = oldMinCrit;
bool inputsArma = inputs.arma;
for (unsigned int i = 0; i < allUCModels.size(); i++){
SSmodel::inputs.p0 = -9999.9;
bool arma = inputs.arma;
setModel(allUCModels[i], inputs.periods(harmonics), inputs.rhos(harmonics), false);
inputs.arma = arma;
// Cleaning variables for outliers starting anew
if (SSmodel::inputs.u.n_elem > 0){
if (nuInit > 0){
SSmodel::inputs.u = SSmodel::inputs.u.rows(0, nuInit - 1);
} else {
SSmodel::inputs.u.resize(0);
}
}
// Model estimation
estim();
AIC = SSmodel::inputs.criteria(1);
BIC = SSmodel::inputs.criteria(2);
AICc = SSmodel::inputs.criteria(3);
// Avoid selecting a model with problems
if (AIC == -datum::inf || AIC == datum::inf){
AIC = BIC = AICc = datum::nan;
}
if (VERBOSE){
printf(" %*s: %8.4f %8.4f %8.4f\n", 30, allUCModels[i].c_str(), AIC, BIC, AICc);
}
if (inputs.criterion == "aic"){
curCrit = AIC;
} else if (inputs.criterion == "bic"){
curCrit = BIC;
} else {
curCrit = AICc;
}
if ((curCrit < minCrit && !isnan(curCrit))){ // || i == 0){
minCrit = curCrit;
bestSS = SSmodel::inputs;
bestBSM = inputs;
}
}
SSmodel::inputs = bestSS;
inputs = bestBSM;
inputs.arma = inputsArma;
}
// Identification
void BSMmodel::ident(string show){
wall_clock timer;
timer.tic();
double season,
maxLag,
outlierCopy = SSmodel::inputs.outlier;
string inputTrend = inputs.trend,
inputCycle = inputs.cycle,
inputSeasonal = inputs.seasonal,
inputIrregular = inputs.irregular,
model,
trendTypes,
cycTypes,
seasTypes,
irrTypes,
restRW;
int trueTrend,
nuInit = SSmodel::inputs.u.n_rows;
bool VERBOSE = SSmodel::inputs.verbose;
// Controling estimation with or without outliers
if (outlierCopy > 0){
SSmodel::inputs.outlier = 0;
}
// Controlling verbose output
SSmodel::inputs.verbose = false;
vec periods = inputs.periods(find(inputs.rhos > 0));
season = max(periods);
if (season == 1){
inputSeasonal = "none";
inputs.seasonal = "none";
}
maxLag = floor(season / 2);
// Trend tests
if (SSmodel::inputs.y.n_rows < 15){
inputs.tTest = false;
}
if (inputs.stepwise && inputTrend == "?" && inputs.tTest){
vec lagsAdf(2);
double lagsAdfMax;
lagsAdf(0) = 2 * season + 2;
lagsAdf(1) = 10;
lagsAdfMax = max(lagsAdf);
if (lagsAdfMax < SSmodel::inputs.y.n_rows / 2){
inputs.tTest = false;
} else {
trueTrend = adfTests(SSmodel::inputs.y, max(lagsAdf), "bic");
if (trueTrend == 0){ // No trend detected
inputTrend = "none";
trendTypes = "none";
} else if (trueTrend == 1){
inputTrend = "some";
trendTypes = "rw";
}
}
}
// Seasonal test
string isSeasonal;
if (inputSeasonal[0] == 'n'){
inputSeasonal = "none";
isSeasonal = "none";
} else {
isSeasonal = "true";
}
// Selecting harmonics
uvec harmonics = regspace<uvec>(0, periods.n_elem - 1);
uvec harmonics0 = harmonics;
if (inputSeasonal[0] != 'n'){
vec betaHR;
selectHarmonics(SSmodel::inputs.y, SSmodel::inputs.u, periods, harmonics, betaHR, isSeasonal);
if (harmonics.n_rows == 0){
inputSeasonal = "none";
harmonics = harmonics0;
periods = inputs.periods;
}
}
if (season == 4 && harmonics.n_rows > 0){
harmonics.reset();
harmonics = regspace<uvec>(0, 1);
}
inputs.harmonics = harmonics;
// UC identification
double minCrit; // = 1e12, minCrit1;
if (VERBOSE && (show == "head" || show == "both")){
printf("------------------------------------------------------------\n");
if (SSmodel::inputs.outlier < 0){
printf(" Identification started WITH outlier detection\n");
} else {
printf(" Identification started WITHOUT outlier detection\n");
}
printf("------------------------------------------------------------\n");
printf(" Model AIC BIC AICc\n");
printf("------------------------------------------------------------\n");
}
// Finding models to identify
vector<string> allUCModels;
size_t pos;
bool runAll = !inputs.stepwise;
if (season == 1 || inputSeasonal != "?"){
runAll = true;
}
if (!runAll){
if (isSeasonal[0] == 't'){
seasTypes = "equal/different";
} else if (isSeasonal[0] == 'd'){
seasTypes = "none/equal/different";
} else if (isSeasonal[0] == 'f'){
seasTypes = "none";
}
}
if (inputIrregular == "?"){
irrTypes = "none/arma(0,0)";
} else { // Model with one irregular
irrTypes = inputIrregular;
runAll = true;
}
if (inputCycle == "?"){
cycTypes = "none/" + inputs.cycle0;
} else {
cycTypes = inputCycle;
}
if (inputTrend == "?"){
trendTypes = "none/rw";
} else if (inputTrend[0] != 's'){
trendTypes = inputTrend;
runAll = true;
} else if (inputTrend[0] == 's'){
runAll = false;
}
if (runAll){ // no stepwise
if (inputTrend == "?"){
if (inputIrregular != "none" && inputIrregular != "arma(0,0)"
&& inputIrregular != "?"){
// Avoiding identification problems between arma(p,q) and dt trend
trendTypes = "none/rw/llt";
} else {
trendTypes = "none/rw/llt/dt";
}
}
if (inputSeasonal == "?")
seasTypes = "none/equal/different";
else
seasTypes = inputSeasonal;
findUCmodels(trendTypes, cycTypes, seasTypes, irrTypes, allUCModels);
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, 1e12, nuInit);
} else { // stepwise
if (inputSeasonal[0] == 'n'){
// Annual or non seasonal data
if (inputTrend == "?" || inputTrend == "some")
trendTypes = trendTypes + "/llt/dt";
seasTypes = "none";
findUCmodels(trendTypes, cycTypes, seasTypes, irrTypes, allUCModels);
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, 1e12, nuInit);
} else {
// Seasonal data
if (inputSeasonal != "?"){
// seasTypes = "none/equal/different";
// } else {
seasTypes = inputSeasonal;
}
// Best of rw or none trends
findUCmodels(trendTypes, cycTypes, seasTypes, irrTypes, allUCModels);
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, 1e12, nuInit);
allUCModels.clear();
if (inputs.model.substr(0, 1) == "n"){
// case if best trend is none
findUCmodels("dt", cycTypes, seasTypes, "arma(0,0)", allUCModels);
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, minCrit, nuInit);
} else {
// case rw or llt is best: estimate some dts
pos = inputs.model.find("/", 0);
// Extract non trend part of the best model so far
restRW = inputs.model.substr(pos, inputs.model.size() - pos);
// Estimate the best model changing the trend to LLT
findUCmodels("llt", cycTypes, seasTypes, irrTypes, allUCModels);
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, minCrit, nuInit);
// Now take the non trend part of the best model so far and use the DT trend instead
pos = inputs.model.find("/", 0);
restRW = inputs.model.substr(pos, inputs.model.size() - pos);
allUCModels.clear();
allUCModels.push_back("dt" + restRW);
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, minCrit, nuInit);
}
}
}
// Checking for identification total failure
bool succeed = true;
if (SSmodel::inputs.p.has_nan() || isnan(minCrit)){
succeed = false;
// Setting up default model
setModel("rw/none/none/none", inputs.periods(harmonics), inputs.rhos(harmonics), false);
SSmodel::inputs.p.set_size(1);
SSmodel::inputs.p.fill(0);
llikAug(SSmodel::inputs.p, &(SSmodel::inputs));
}
if (VERBOSE && !succeed){
printf(" Identification failed!!\n");
printf(" Unable to find a proper model!!\n");
}
// Selecting best ARMA
if (inputs.arma && succeed){
string armaModel, modelNew;
vec beta0, orders(2);
orders.fill(0);
if (inputIrregular == "?" && succeed){
string inputIrregular2;
splitModel(inputs.model, inputTrend, inputCycle, inputSeasonal, inputIrregular2);
if (inputIrregular == "?" && SSmodel::inputs.y.n_elem > 30){
int maxSearch = season + 4;
if (maxSearch > 28){
maxSearch = 28;
}
maxLag = 5;
if (season == 1){
maxSearch = 8;
}
if ((float)SSmodel::inputs.y.n_elem - (float)SSmodel::inputs.system.T.n_rows - 3 - (float)maxLag - (float)maxSearch > 3 * (float)season){
filter();
uvec ind = find_finite(SSmodel::inputs.v);
// if ((float)SSmodel::inputs.v.n_elem - (float)SSmodel::inputs.system.T.n_rows - 2 > 3 * (float)season){
if ((float)ind.n_elem - (float)SSmodel::inputs.system.T.n_rows - 2 > 3 * (float)season){
selectARMA(SSmodel::inputs.v.rows(SSmodel::inputs.system.T.n_rows + 2, SSmodel::inputs.v.n_elem - 1),
maxLag, maxSearch, "bic", orders, beta0);
inputs.beta0ARMA = beta0;
}
}
}
// Model with ARMA
if (sum(orders) > 0){ // ARMA identified
armaModel.append(to_string((int)orders(0))).append(",").append(to_string((int)orders(1)));
// Reformulating the irregular model
string tModel, sModel, cModel, iModel;
splitModel(inputs.model, tModel, cModel, sModel, iModel);
// if (pureARMA)
// tModel = "none";
modelNew.append(tModel).append("/").append(cModel).append("/").append(sModel).append("/").append("arma(").append(armaModel).append(")");
allUCModels.clear();
allUCModels.push_back(modelNew);
// Estimating potential best model
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, minCrit, nuInit);
}
}
// Selecting best pure ARMA (in case best model is trend + noise of any kind so far)
pos = inputs.model.find("/none/none/");
if (pos < 5 && inputs.model[0] != 'n' && SSmodel::inputs.y.n_elem > 30){
// Searching for pure ARMA when trend + noise has been detected previously
int maxSearch = season + 4;
if (maxSearch > 28){
maxSearch = 28;
}
maxLag = 5;
if (season == 1){
maxSearch = 8;
}
vec orders1(2);
orders1.fill(0);
vec beta1;
if (SSmodel::inputs.y.n_rows - maxLag - maxSearch > 3 * season){
selectARMA(SSmodel::inputs.y, maxLag, maxSearch, "bic", orders1, beta1);
}
inputs.beta0ARMA = beta1;
if (sum(orders1) > 0){
armaModel = "";
modelNew = "";
armaModel.append(to_string((int)orders1(0))).append(",").append(to_string((int)orders1(1)));
modelNew.append("none/none/none/arma(").append(armaModel).append(")");
allUCModels.clear();
allUCModels.push_back(modelNew);
// Estimating potential best model
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, minCrit, nuInit);
}
if (inputs.model[0] == 'n'){
beta0.reset();
beta0 = beta1;
orders = orders1;
}
inputs.beta0ARMA = beta1;
}
if (VERBOSE && outlierCopy > 0){
printf("------------------------------------------------------------\n");
printf(" Final model WITH outlier detection\n");
printf("------------------------------------------------------------\n");
}
}
// bool correct = true;
if (outlierCopy > 0){
SSmodel::inputs.outlier = -abs(outlierCopy);
allUCModels.clear();
allUCModels.push_back(inputs.model);
estimUCs(allUCModels, harmonics, minCrit, VERBOSE, minCrit, nuInit);
}
if (VERBOSE && (show == "tail" || show == "both")){
double nSeconds = timer.toc();
printf("------------------------------------------------------------\n");
printf(" Identification time: %10.5f seconds\n", nSeconds);
printf("------------------------------------------------------------\n");
}
SSmodel::inputs.verbose = VERBOSE;
// Updating inputs
if (inputSeasonal[0] == 'n'){
inputs.periods = {1};
harmonics = {0};
inputs.rhos = {1};
}
inputs.harmonics = harmonics;
inputs.rhos = inputs.rhos(harmonics);
SSmodel::inputs.outlier = outlierCopy;
if (harmonics.n_elem > 0){
inputs.periods = inputs.periods(harmonics);
} else {
inputs.periods.resize(1);
inputs.periods.fill(1);
}
}
// Outlier detection a la Harvey and Koopman
void BSMmodel::estimOutlier(vec p0){
// Havey, A.C. and Koopman, S.J. (1992), Diagnostic checking of unobserved
// components time series models , JBES, 10, 377-389.
int n = SSmodel::inputs.y.n_elem - 1, //nNan,
nu = SSmodel::inputs.u.n_rows,
lu = 0;
bool VERBOSE = SSmodel::inputs.verbose;
SSmodel::inputs.verbose = false;
vec periodsCopy = inputs.periods,
rhosCopy = inputs.rhos;
// Length of u's
if (nu == 0){
lu = n + SSmodel::inputs.h + 1;
} else {
lu = SSmodel::inputs.u.n_cols;
}
wall_clock timer;
timer.tic();
// Initial estimation without checking oultiers
SSmodel::inputs.p0 = p0;
estim(SSmodel::inputs.p0);
inputs.periods = periodsCopy;
inputs.rhos = rhosCopy;
// Storing initial model clean
SSinputs bestSS = SSmodel::inputs;
BSMinputs bestBSM = inputs;
// Forward Addition loop
// Disturbances estimation
disturb();
// AO
vec eps;
if (inputs.nPar(3) == 1){
eps = abs(inputs.eps);
} else {
eps = join_vert(zeros<vec>(n - SSmodel::inputs.v.n_elem + 1),
abs(SSmodel::inputs.v / sqrt(SSmodel::inputs.F)));
eps.replace(datum::nan, 0);
}
uvec indAO = find(eps > 2.3);
vec valAO = eps(indAO);
uvec sortInd;
// Correction in case there are too many AO's
if (valAO.n_elem > 10){
sortInd = sort_index(valAO, "descend");
sortInd = sortInd.rows(0, 9);
indAO = indAO(sortInd);
valAO = valAO(sortInd);
}
// LS
uvec indLS;
vec valLS;
if (inputs.nPar(0) > 0){ // && SSmodel::inputs.eta.row(0).max() > 2.5){
valLS = abs(SSmodel::inputs.eta.row(0).t());
indLS = selectOutliers(valLS, 3, 2.5);
eps = abs(SSmodel::inputs.eta.row(0).t());
valLS = eps(indLS);
}
// SC
uvec indSC;
vec valSC;
if (inputs.ns(0) > 1 && inputs.nPar(0) > 0){ // && SSmodel::inputs.eta.row(1).max() > 3){
valSC = abs(SSmodel::inputs.eta.row(1).t());
indSC = selectOutliers(valSC, 3, 3.0);
eps = abs(SSmodel::inputs.eta.row(1).t());
valSC = eps(indSC);
}
// All outliers together
inputs.typeOutliers = join_vert(join_vert(zeros(size(indAO)), ones(size(indLS))), 2 * ones(size(indSC)));
uvec ind = join_vert(join_vert(indAO, indLS), indSC);
vec val = join_vert(join_vert(valAO, valLS), valSC);
// Sorting vectors
if (ind.n_elem > 0){
// Sorting and removing less significant in case of many outliers
sortInd = sort_index(val, "descend");
val = val(sortInd);
ind = ind(sortInd);
inputs.typeOutliers = inputs.typeOutliers(sortInd);
if (ind.n_elem > 20){
val = val.rows(0, 19);
ind = ind.rows(0, 19);
inputs.typeOutliers = inputs.typeOutliers.rows(0, 19);
}
// Sorting now by date
sortInd = sort_index(ind);
val = val(sortInd);
ind = ind(sortInd);
inputs.typeOutliers = inputs.typeOutliers(sortInd);
}
// Removing duplicated outliers of different types
vec uniqueInd = unique(conv_to<mat>::from(ind));
if (uniqueInd.n_elem < ind.n_elem){
uvec indAux(uniqueInd.n_elem);
vec valAux(uniqueInd.n_elem);
mat outlAux(uniqueInd.n_elem, 1);
uvec ii;
int j = 0;
for (uword i = 0; i < uniqueInd.n_elem; i++){
ii = find(uniqueInd(i) == ind);
if (ii.n_elem > 1){
j = ii(val(ii).index_max());
} else {
j = ii(0);
}
valAux(i) = val(j);
outlAux(i, 0) = inputs.typeOutliers(j);
indAux(i) = ind(j);
}
ind = indAux;
inputs.typeOutliers = outlAux;
val = valAux;
}
// done
bool cLlikCopy = SSmodel::inputs.cLlik,
augmentedCopy = SSmodel::inputs.augmented,
exactCopy = SSmodel::inputs.exact;
if (ind.n_elem > 0){
// matrix of potential inputs
mat uNew(ind.n_elem, lu);
uNew.fill(0);
rowvec ui(lu);
ui.fill(0);
for (unsigned int i = 0; i < uNew.n_rows; i++){
dummy(ind(i), inputs.typeOutliers(i), ui);
uNew.row(i) = ui;
}
if (nu > 0){
SSmodel::inputs.u = join_vert(SSmodel::inputs.u, uNew);
} else {
SSmodel::inputs.u = uNew;
}
// Re-estimation with inputs and all outliers in model
SSmodel::inputs.cLlik = true;
SSmodel::inputs.augmented = true;
SSmodel::inputs.exact = false;
if (VERBOSE){
SSmodel::inputs.verbose = true;
}
estim(SSmodel::inputs.p0);
inputs.periods = periodsCopy;
inputs.rhos = rhosCopy;
vec obj(1); obj(0) = SSmodel::inputs.objFunValue;
if (obj.is_finite()){
// Model with all initial outliers converged
SSmodel::inputs.verbose = false;
// Backward deletion step
uvec remove;
int ns = SSmodel::inputs.system.T.n_rows,
nuAll;
int count = 0;
do{
nuAll = nu + ind.n_elem;
vec t = abs(SSmodel::inputs.betaAug.rows(ns + nu, ns + nuAll - 1) /
sqrt(SSmodel::inputs.betaAugVar.rows(ns + nu, ns + nuAll - 1)));
remove = find(t < abs(SSmodel::inputs.outlier));
if (remove.n_elem > 0){
// Removing inputs
SSmodel::inputs.u.shed_rows(nu + remove);
inputs.typeOutliers.shed_rows(remove);
ind.shed_rows(remove);
// if (SSmodel::inputs.u.n_rows == 0 && inputs.model[0] != 'd'){
// SSmodel::inputs.augmented = false;
// SSmodel::inputs.exact = true;
// }
if (SSmodel::inputs.u.n_rows == 0){
SSmodel::inputs = bestSS;
inputs = bestBSM;
} else {
// Final estimation
estim(SSmodel::inputs.p0);
inputs.periods = periodsCopy;
inputs.rhos = rhosCopy;
}
}
count++;
} while (count < 4 && ind.n_elem > 0 && remove.n_elem > 0);
}
if (ind.n_elem > 0){
inputs.typeOutliers.insert_cols(1, conv_to<mat>::from(ind));
}
// Final check
vec best(1);
if (inputs.criterion == "aic"){
obj(0) = SSmodel::inputs.criteria(1);
best(0) = bestSS.criteria(1);
} else if (inputs.criterion == "bic"){
obj(0) = SSmodel::inputs.criteria(2);
best(0) = bestSS.criteria(2);
} else {
obj(0) = SSmodel::inputs.criteria(3);
best(0) = bestSS.criteria(3);
}
if ((!obj.is_finite()) || (obj(0) > best(0))){
// Model with outliers did not converge or is worse than initial
SSmodel::inputs = bestSS;
inputs = bestBSM;
}