-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathEvaluation_tool.py
2356 lines (2089 loc) · 112 KB
/
Evaluation_tool.py
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
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 17 16:22:50 2017
@author: Jeremias Knoblauch ([email protected])
Description: Convenient object that serves as a wrapper for experiments and
(i) creates model universe members and their detectors, (ii) runs the algo,
(iii) stores results (either to itself or the HD), (iv) can simply re-call old
results that were stored on HD (iv) allows for a variety of plotting functions
once the algo has run/once data has been read in.
"""
from detector import Detector
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.dates as mdates
from matplotlib.dates import drange
from matplotlib.colors import LogNorm
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy import misc
import numpy as np
import pickle
import os
import datetime
import collections
from nearestPD import NPD
import matplotlib.lines as mlines
from BVAR_NIG import BVARNIG
class EvaluationTool:
"""Description: Convenient object that serves as a wrapper for experiments and
(i) creates model universe members and their detectors, (ii) runs the algo,
(iii) stores results (either to itself or the HD), (iv) can simply re-call old
results that were stored on HD (iv) allows for a variety of plotting functions
once the algo has run/once data has been read in.
type:
-> Gives you info on how the tool was initialized. Was it given
a detector only? Or was it given specs for creating models and
a detector? Or was it created from old data, and we only wanna plot?
The higher the number, the less work the tool has left to do before
plots can be generated
---------
1 => We get a collection of model specifications that are not
in a detector yet
2 => We get a collection of (ready) models that are not in a
detector yet
3 => We get a detector
4 => We have the results from running the detector (but not
necessarily any detector, model specifications, etc.)
"""
def __init__(self):
"""the object is initialized as empty, and there are basically two ways
of creating one: Either you input models + detectors (or their
arguments), or you give it the path to data that has been stored from
a previous experiment"""
self.type = None
self.has_true_CPs = False
self.names = ["names", "execution time", "S1", "S2", "T",
"trimmer threshold", "MAP CPs", "model labels",
"run length log distribution",
"model and run length log distribution",
"one-step-ahead predicted mean",
"one-step-ahead predicted variance",
"all run length log distributions",
"all model and run length log distributions",
"all retained run lenghts",
"has true CPs", "true CP locations",
"true CP model index", "true CP model labels"]
"""NOTE: Plotting will work with 7 different colors and 4 different
line styles!"""
self.linestyle = ["-", "--", "-.", ":",]*20
self.colors = ['b', 'c', 'm', 'y', 'k', 'g']*20
self.CP_color = 'r'
self.cushion = 10 #cushion when plotting RL distro
self.median_color = 'g'
self.max_color = 'r'
"""Initialize s.t. the baseline assumption is that we do not know the
true CPs"""
self.has_true_CPs = False
self.true_CP_location = self.true_CP_model_index = self.true_CP_model_label = None
"""*********************************************************************
TYPE I FUNCTIONS: Create Evaluation Tool via Models
*********************************************************************"""
def build_EvaluationTool_models_via_specs(self, model_class_list,
specification_list, data=None, detector_specs=None):
""" *model_class_list* gives you the list of models to be created, and
*specification_list* will give you the list of lists of parameters for
each model to be created. *data* will give you the data to run the
models on, and *detector_specs* are additional specifications for the
detector (like intensity of the CP occurence, ...)"""
"""STEP 1: Store the essentials and get your type"""
self.model_class_list = model_class_list
self.specification_list = specification_list
self.type = 1
"""STEP 2: Build all your models, and advance the type by one"""
self.model_universe = []
for (model_class, specs) in zip(self.model_class_list,
self.specification_list):
self.model_universe.append(model_class(*specs))
self.type = 2
"""STEP 3: If you have data, put all models into a detector that is
created with default specs unless you supplied other specs. If you
create this detector, advance type by one again."""
if not( data is None ):
if not (detector_specs is None):
self.detector = Detector(data, *detector_specs)
else:
self.detector = Detector(data)
self.type = 3
def build_EvaluationTool_models_via_universe(self, model_universe, data=None,
detector_specs=None):
""" *model_list* stores a collection of models for the segments, and
*data* gives you the data you wish to analyze using those models. As
before, *detector_specs* is an optional list of arguments for the
detector that will be created (if the data is passed)."""
"""STEP 1: Store the model universe that was passed to the function"""
self.model_universe = model_universe
self.type = 2
"""STEP 2: If you can/should, create the detector"""
if not( data is None ):
if not (detector_specs is None):
self.detector = Detector(data, *detector_specs)
else:
self.detector = Detector(data)
self.type = 3
def build_EvaluationTool_models_via_csv(self, specification_csv,
data=None, detector_specs=None):
""" *specification_csv* stores the path and name of a csv file
containing the model_class_list and the specification_list equivalent
from before, but simply in a .csv file with a certain structure."""
#structure: First row are the headers, i.e. gives you the names
# of the quantities defining the BVAR structure
pass #DEBUG: Not clear how to read a spreadsheet, and how to structure it yet
"""*********************************************************************
TYPE I FUNCTIONS: Create Evaluation Tool via results
*********************************************************************"""
def build_EvaluationTool_via_results(self, result_path):
"""Give it the path to a pickle-created list of results that you can
work with to do all the plotting"""
f_myfile = open(result_path, 'rb')
self.results = pickle.load(f_myfile)
f_myfile.close()
# with open(result_path, 'rb') as fp:
# self.results = pickle.load(fp)
self.names = self.results[0]
self.type=4
def build_EvaluationTool_via_run_detector(self, detector,
true_CP_location=None, true_CP_model_index = None,
true_CP_model_label = None):
if ((true_CP_location is not None) and (true_CP_model_index is not None)):
self.add_true_CPs(true_CP_location, true_CP_model_index,
true_CP_model_label )
self.detector = detector
self.type = 4
self.store_detector_results_to_object()
"""*********************************************************************
TYPE I FUNCTIONS: Add data/true Cps/... To Evaluation Tool
*********************************************************************"""
def add_data_and_detector_via_hand(self, data, detector_specs = None):
""" Let's you create the detector if you don't wish to pass the data
into the EvaluationTool object right away."""
if self.type is None or self.type < 2:
print("Error! Passing in data and detector specs before " +
"creating model_universe!")
else:
if not (detector_specs is None):
self.detector = Detector(data, *detector_specs)
else:
self.detector = Detector(data)
self.type = 3
def create_data_add_detector_via_simulation_obj(self, sim_class,
sim_parameters,
detector_specs = None):
"""You run a simulation *sim_class* that takes parameters stored in
*sim_parameters* and creates a detector afterwards. It is essential
that the sim_class object stores the generated data as ".data" """
if self.type is None or self.type < 2:
print("Error! Passing in data and detector specs before " +
"creating model_universe!")
else:
data = (sim_class(*sim_parameters).generate_data()).data
if not (detector_specs is None):
self.detector = Detector(data, *detector_specs)
else:
self.detector = Detector(data)
self.type = 3
def create_data_add_detector_via_simulation_csv(self, sim_csv,
detector_specs = None):
"""You run a simulation *sim_class* that takes parameters stored in
*sim_parameters* and creates a detector afterwards. It is essential
that the sim_class object stores the generated data as ".data" """
#DEBUG: also store true CPS!
#DEBUG: Store a boolean indicating that data was created with true CPs
pass
def add_true_CPs(self, true_CP_location, true_CP_model_index,
true_CP_model_label = None):
"""Add true CPs and store them. *true_CP_location* gives you the time
at which the CP occured. *true_CP_model* gives you the model index in
the detector object corresponding to the model starting at the corr.
CP location. *true_CP_model_label* gives you the string label of the
true DGP starting at the CP, e.g.
true_CP_model_label = ["BVAR(4,4,1)", "BVAR(1,1,1,1,1)"]."""
self.true_CP_location = true_CP_location
self.true_CP_model_index = true_CP_model_index
#if self.model_labels is None:
# self.model_labels = true_CP_model_label
self.true_CP_model_label = true_CP_model_label
self.has_true_CPs = True
"""*********************************************************************
TYPE II FUNCTIONS: Run the algorithm, store results
*********************************************************************"""
def run_algorithm(self, start=None, stop=None):
"""Just runs the detector and stores all the results that we want
inside the Evaluation_tool object"""
"""STEP 1: Run algo"""
if start is None or stop is None:
self.detector.run()
else:
self.detector.run(start, stop)
self.type = 4
self.store_detector_results_to_object()
def store_detector_results_to_object(self):
if self.type < 4:
print("CAREFUL! Your detector seems to not have been run yet, " +
"but you still store its content to your EvaluationTool object!")
"""STEP 2: Store all raw quantities inside the object"""
self.S1, self.S2, self.T = self.detector.S1, self.detector.S2, self.detector.T
self.execution_time = self.detector.execution_time
self.CPs = self.detector.CPs
self.threshold = self.detector.threshold
self.run_length_log_distr = self.detector.run_length_log_distr
self.model_and_run_length_log_distr = self.detector.model_and_run_length_log_distr
if self.detector.save_performance_indicators:
self.MSE = self.detector.MSE
self.negative_log_likelihood = self.detector.negative_log_likelihood
if self.detector.store_rl or self.detector.store_mrl:
self.storage_all_retained_run_lengths = (
self.detector.storage_all_retained_run_lengths)
if self.detector.store_rl:
self.storage_run_length_log_distr = self.detector.storage_run_length_log_distr
else:
self.storage_run_length_log_distr = None
if self.detector.store_mrl:
self.storage_model_and_run_length_log_distr = (self.
detector.storage_model_and_run_length_log_distr)
else:
self.storage_model_and_run_length_log_distr = None
#self.data = self.detector.data
self.storage_mean = self.detector.storage_mean
self.storage_var = self.detector.storage_var
"""STEP 2.1: Store strings that give you the model label"""
if isinstance(self.detector.model_universe, list):
M = int(len(self.detector.model_universe))
else:
M = self.detector.model_universe.shape[0]
self.model_labels = [None]*M
for i in range(0,M):
class_label = str(
type(self.detector.model_universe[i])).split(
".")[-1].split("'")[0]
if self.detector.model_universe[i].has_lags:
if isinstance(self.detector.model_universe[i], BVARNIG):
nbh_label = "[BAR]"
else:
if self.detector.model_universe[i].nbh_sequence is None:
#general nbh
lag_length = self.detector.model_universe[i].lag_length
nbh_label = "[general nbh, " + str(lag_length) + "]"
else:
nbh_label = str(self.detector.model_universe[i].nbh_sequence)
self.model_labels[i] = class_label + nbh_label
else:
self.model_labels[i] = class_label
"""STEP 3: Sum them all up in a results-object"""
self.results = [self.execution_time, self.S1, self.S2, self.T,
self.threshold, self.CPs, self.model_labels,
self.run_length_log_distr,
self.model_and_run_length_log_distr,
self.storage_mean, self.storage_var,
self.storage_run_length_log_distr,
self.storage_model_and_run_length_log_distr, #,
self.storage_all_retained_run_lengths
]
if self.detector.save_performance_indicators:
self.names.append("MSE")
self.names.append("NLL")
self.results.append(self.MSE)
self.results.append(self.negative_log_likelihood)
if self.has_true_CPs:
self.names.append("has true CP")
self.names.append("true CP location")
self.names.append("true CP model index")
self.names.append("true CP model label")
self.results.append(self.has_true_CPs)
self.results.append(self.true_CP_location)
self.results.append(self.true_CP_model_index)
self.results.append(self.true_CP_model_label)
"""append the names to the front of results"""
self.results.insert(0, self.names)
def store_results_to_HD(self, results_path):
"""For all objects stored inside the object, store them in a certain
structure to the location at *path*, provided that the algorithm has
run already."""
"""Check if the algorithm has already been run. If so create a list of
names and results and store to HD!"""
if self.type == 4:
"""store to HD"""
f_myfile = open(results_path, 'wb')
pickle.dump(self.results, f_myfile)
f_myfile.close()
#with open(results_path, 'rb') as fp:
# pickle.dump(self.results, fp)
def run_algorithm_store_results_to_HD(self, results_path, start=None, stop=None):
self.run_algorithm(start,stop)
self.store_results_to_HD(results_path)
"""*********************************************************************
TYPE III FUNCTIONS: create/store/read model configurations
*********************************************************************"""
#DEBUG: Static method to store configurations in pickle format
def store_BVAR_configurations_to_HD(configs, path):
"""Store the configurations passed as *config* to *path* using the
pickle module, i.e. s.t. you can retrieve them directly as a list of
arguments"""
i = 0
for config in configs:
config_path = path + "\\" + str(i)
f_myfile = open(config_path, 'wb')
pickle.dump(config, f_myfile)
f_myfile.close()
# with open(config_path, 'rb') as fp:
# pickle.dump(config, fp)
i = i+1
def read_BVAR_configuration_from_HD(path):
"""Retrieve previously stored configs and return them in a list of
lists of arguments"""
list_of_file_paths = os.listdir(path)
list_of_configs = []
i = 0
for config_path in list_of_file_paths:
f_myfile = open(config_path, 'rb')
config = pickle.load(f_myfile)
f_myfile.close()
list_of_configs.append(config)
# config = pickle.load(open(config_path, 'rb'))
# list_of_configs.append(config)
i = i+1
def create_BVAR_configurations_easy(num_configs,
a, b, prior_mean_beta, prior_var_beta,
S1,S2,nbh_sequence, restriction_sequence,
intercept_grouping = None,
general_nbh_sequence = None,
general_nbh_restriction_sequence = None,
nbh_sequence_exo = None, exo_selection = None,
padding = None, auto_prior = None):
"""Idea: You create a sequence of BVAR configs s.t. all parameters which
are only put in once into the model are used for each individual spec-
ification, but all parameters which are put in *num_configs* times are
varied across the *num_configs* created specifications"""
"""STEP 1: Loop over all the arguments that are passed to this fct.
If they have only one entry, make that entry the entry of
each config. If they don't, do nothing"""
a = EvaluationTool.create_args(num_configs, a)
b = EvaluationTool.create_args(num_configs, b)
prior_mean_beta = EvaluationTool.create_args(num_configs, prior_mean_beta)
prior_var_beta = EvaluationTool.create_args(num_configs, prior_var_beta)
S1, S2 = EvaluationTool.create_args(num_configs, S1), EvaluationTool.create_args(num_configs, S2)
nbh_sequence = EvaluationTool.create_args(num_configs, nbh_sequence)
restriction_sequence= EvaluationTool.create_args(num_configs, restriction_sequence)
intercept_grouping = EvaluationTool.create_args(num_configs,
intercept_grouping)
general_nbh_sequence= EvaluationTool.create_args(num_configs, general_nbh_sequence)
general_nbh_restriction_sequence= EvaluationTool.create_args(
num_configs, general_nbh_restriction_sequence)
nbh_sequence_exo= EvaluationTool.create_args(num_configs, nbh_sequence_exo)
exo_selection= EvaluationTool.create_args(num_configs, exo_selection)
padding= EvaluationTool.create_args(num_configs, padding)
auto_prior= EvaluationTool.create_args(num_configs, auto_prior)
"""STEP 2: Create all the configurations in a list of configs"""
configs = [None] * num_configs
for i in range(0, num_configs):
#create the configs
configs[i] = [a[i], b[i], prior_mean_beta[i], prior_var_beta[i],
S1[i], S2[i], nbh_sequence[i], restriction_sequence[i],
intercept_grouping[i],
general_nbh_sequence[i], general_nbh_restriction_sequence[i],
nbh_sequence_exo[i],exo_selection[i],padding[i],auto_prior[i]
]
"""STEP 3: Return configurations"""
return configs
def create_args(num, arg):
"""Modifies arg into a list of lenght num which contains arg num times
if arg has length 0, into a list of length None"""
if arg is None:
arg = [None] * num
elif int(len(arg)) == 1:
arg = [arg]* num
return arg
def create_BVAR_configurations(a_list, b_list, prior_mean_beta_list,
prior_var_beta_list, S1_list, S2_list,
nbh_sequence_list, restriction_sequence_list,
intercept_grouping_list = None,
general_nbh_sequence_list = None,
general_nbh_restriction_sequence_list = None,
nbh_sequence_exo_list = None, exo_selection_list = None,
padding_list = None, auto_prior_list = None):
"""Create config list and store to file using pickle dump"""
"""STEP 1: Get the number of configs and adapt all 'None' entries"""
num_configs = int(len(a_list))
if intercept_grouping_list is None:
intercept_grouping_list = [None] * num_configs
if general_nbh_sequence_list is None:
general_nbh_sequence_list = [None] * num_configs
if general_nbh_restriction_sequence_list is None:
general_nbh_restriction_sequence_list = [None] * num_configs
if nbh_sequence_exo_list is None:
nbh_sequence_exo_list = [None] * num_configs
if exo_selection_list is None:
exo_selection_list = [None] * num_configs
if padding_list is None:
padding_list = [None] * num_configs
if auto_prior_list is None:
auto_prior_list = [None] * num_configs
"""STEP 2: package everything into lists and save them with pickle"""
configs=[None] * num_configs
for i in range(0, num_configs):
configs[i] = [a_list[i], b_list[i], prior_mean_beta_list[i],
prior_var_beta_list[i], S1_list[i], S2_list[i],
nbh_sequence_list[i], restriction_sequence_list[i],
intercept_grouping_list[i], general_nbh_sequence_list[i],
general_nbh_restriction_sequence_list[i],
nbh_sequence_exo_list[i], exo_selection_list[i],
padding_list[i],auto_prior_list[i]]
"""STEP 3: Return configurations"""
return(configs)
"""*********************************************************************
TYPE IV FUNCTIONS: Create plots
*********************************************************************"""
"""Helper function: Smoothing"""
def smooth(x,window_len=11,window='hanning'):
"""smooth the data using a window with requested size.
input:
x: the input signal
window_len: the dimension of the smoothing window; should be an odd integer
window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'
flat window will produce a moving average smoothing.
output:
the smoothed signal
see also:
numpy.hanning, numpy.hamming, numpy.bartlett, numpy.blackman, numpy.convolve
scipy.signal.lfilter
TODO: the window parameter could be the window itself if an array instead of a string
NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y.
"""
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
#raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
print("Window type not admissible")
s=np.r_[x[window_len-1:0:-1],x,x[-2:-window_len-1:-1]]
#print(len(s))
if window == 'flat': #moving average
w=np.ones(window_len,'d')
else:
w=eval('np.'+window+'(window_len)')
y=np.convolve(w/w.sum(),s,mode='valid')
return y
"""PLOT I: get the raw data together with the true CPs and return as a
figure plt.figure() object.
Options:
indices => list of indices in 1d. (data already be flattened)
s.t. the corresponding TS will be plotted
time_range => range of time over which we should plot the TS
print_plt => boolean, decides whether we want to see the plot
or just create the object to pass to the next fct.
legend => boolean, whether or not we want a legend
legend_labels => gives you the labels for the TS as a list of
strings. If you don't specify the labels,
default is 1,2,...
legend_position => gives the
position of the legend, and default is upper left
"""
def plot_raw_TS(self, data, indices = [0], print_plt = True,
show_MAP_CPs = False,
legend = False, legend_labels = None,
legend_position = None, time_range = None,
start_plot = None, stop_plot = None,
aspect_ratio = 'auto',
xlab = "Time",
ylab = "Value",
ax = None,
xlab_fontsize = 10,
ylab_fontsize = 10,
xticks_fontsize = 10,
yticks_fontsize = 10,
all_dates = None,
custom_linestyles = None,
custom_colors_series = None,
custom_colors_CPs = None,
custom_linewidth = 3.0,
custom_transparency = 1.0,
ylabel_coords = None,
true_CPs = None,
additional_CPs = None,
custom_colors_additional_CPs = None,
custom_linestyles_additional_CPs = None,
custom_linewidth_additional_CPs = None,
custom_transparency_additional_CPs = 1.0,
set_xlims = None,
set_ylims = None,
up_to = None):
"""Generates plot of the raw TS at the positions marked by *indices*, over
the entire time range unless specificed otherwise via *time_range*. It
prints the picture to the console if *print_plt* is True, and puts a
legend on the plot if *legend* is True"""
"""STEP 1: Default is to take the entire time range"""
T = data.shape[0] #self.results[self.names.index("T")]
if time_range is None:
time_range = np.linspace(1,T,T, dtype=int)
"""STEP 2: If we do want a legend, the labels are 1,2,3... by default
and we plot in the upper left corner by default."""
num = int(len(indices))
if legend:
if (legend_labels is None):
legend_labels = [str(int(i)) for i in np.linspace(1,num,num)]
if legend_position is None:
legend_position = 'upper left'
else:
legend_labels = []
"""STEP 3: Plot all the lines specified by the index object"""
#S1, S2 = self.results[self.names.index("S1")], self.results[self.names.index("S2")]
#print(self.results[self.names.index("data")].shape)
#[time_range-1 ,:,:]).reshape((int(len(time_range)), S1*S2))))
#NOTE: We do not store the data in the detector (anymore), so read
# it in separately and then pass it into the fct.
#data = (self.results[self.names.index("data")]
# [time_range-1 ,:][:,indices])
if custom_colors_series is None:
custom_colors_series = self.colors
if custom_colors_CPs is None:
custom_colors_CPs = self.CP_color * 100
if ax is None:
figure, ax = plt.subplots()
if all_dates is None:
if start_plot is None or stop_plot is None:
x_axis = time_range
else:
x_axis = np.linspace(start_plot, stop_plot, len(time_range))
start, stop = time_range[0], time_range[-1]
else:
x_axis = all_dates
start, stop = all_dates[0], all_dates[-1]
#if we want to plot everything
if up_to is None or up_to > len(data[:,0]):
up_to = len(data[:,0])
legend_handles = []
for i in range(0, num): #num = len(indices)
"""The handle is like an identifier for that TS object"""
handle = ax.plot(x_axis[:up_to],
data[:up_to,indices[i]], color = custom_colors_series[i])
legend_handles.append(handle)
if not all_dates is None:
if isinstance(all_dates[0], datetime.date):
ax.xaxis_date()
T_ = len(time_range)
"""STEP 4: If we have true CPs, plot them into the figure, too"""
if False: #DEBUG: We need to add CP option self.results[self.names.index("has true CPs")]:
CP_legend_labels = []
CP_legend_handles = []
CP_locations = self.results[self.names.index("true CP locations")]
CP_model_labels = self.results[self.names.index("true CP model labels")]
CP_model_index = self.results[self.names.index("true CP model index")]
#DEBUG: How do I retrieve model index, model label and locatoin
# from the results? I NEED TO STORE THEM THERE FIRST, TOO!
for (CP_loc, CP_ind, CP_lab) in zip(CP_locations,
CP_model_index, CP_model_labels):
handle = ax.axvline(x=CP_loc, color = self.CP_color,
linestyle = self.linestyle[CP_ind])
CP_legend_handles.append(handle)
CP_legend_labels.append(CP_lab)
#DEBUG: Could make this conditional on another boolean input
legend_handles += CP_legend_handles
legend_labels += CP_legend_labels
if additional_CPs is not None:
CP_object = additional_CPs
CP_locations = [entry[0] for entry in CP_object]
CP_indices = [entry[1] for entry in CP_object]
if custom_linestyles_additional_CPs is None:
custom_linestyles_additional_CPs = self.linestyle #['solid']*len(CP_locations)
if custom_linewidth_additional_CPs is None:
custom_linewidth_additional_CPs = 3.0
if custom_colors_additional_CPs is None:
custom_colors_additional_CPs = custom_colors_CPs
CP_legend_labels = []
CP_legend_handles = []
CP_indices_until_now = []
count = 0
"""Loop over the models in order s.t. you can color in the same
fashion as for the model posterior"""
M = int(len(np.unique(np.array(CP_indices))))
for m in range(0, M):
for (CP_loc, CP_ind) in zip(CP_locations, CP_indices):
if m == CP_ind:
if CP_loc <= time_range[-1] and CP_loc >= time_range[0]:
CP_loc = ((CP_loc - time_range[0])/T_)*(stop-start) + start# carry CP forward
if CP_ind not in CP_indices_until_now:
handle = ax.axvline(x=CP_loc, color = custom_colors_additional_CPs[count],
linestyle = custom_linestyles_additional_CPs[count],
#dashes = [3,6,3,6,3,6,18],
linewidth = custom_linewidth_additional_CPs,
alpha = custom_transparency_additional_CPs)
CP_legend_handles.append(handle)
#CP_legend_labels.append(model_labels[CP_ind])
CP_indices_until_now.append(CP_ind)
count= count+1
elif CP_ind in CP_indices_until_now:
"""display it in the same color"""
relevant_index = CP_indices_until_now.index(CP_ind)
handle = ax.axvline(x=CP_loc, color = custom_colors_additional_CPs[relevant_index],
linestyle = custom_linestyles_additional_CPs[relevant_index],
linewidth = custom_linewidth_additional_CPs,
alpha = custom_transparency_additional_CPs)
if show_MAP_CPs:
#which CPs to consider
if up_to == len(data[:,0]):
#i.e., we have not specified up_to in the input
CP_object = self.results[self.names.index("MAP CPs")][-2]
else:
if (len(self.results[self.names.index("MAP CPs")][up_to]) == 0
and
up_to < len(self.results[self.names.index("MAP CPs")]) - 2):
#get the first entry which is not empty if up_to entry is 0
count = up_to
bool_ = True
while bool_:
count = count + 1
if len(self.results[
self.names.index("MAP CPs")][count]) > 0:
bool_ = False
CP_object = self.results[self.names.index("MAP CPs")][count]
elif (up_to >= len(self.results[
self.names.index("MAP CPs")]) - 2):
#we have a too large value for up_to
CP_object = self.results[self.names.index("MAP CPs")][-2]
else:
#our value of up_to is in range
CP_object = self.results[self.names.index("MAP CPs")][up_to]
CP_locations = [entry[0] for entry in CP_object]
CP_indices = [entry[1] for entry in CP_object]
model_labels = self.results[self.names.index("model labels")]
"""if no custom color, take standard"""
# if custom_colors is None:
# custom_colors = [self.CP_color]*len(CP_locations)
if custom_linestyles is None:
custom_linestyles = self.linestyle #['solid']*len(CP_locations)
if custom_linewidth is None:
custom_linewidth = 3.0
CP_legend_labels = []
CP_legend_handles = []
CP_indices_until_now = []
count = 0
"""Loop over the models in order s.t. you can color in the same
fashion as for the model posterior"""
M = len(self.results[self.names.index("model labels")])
for m in range(0, M):
for (CP_loc, CP_ind) in zip(CP_locations, CP_indices):
if m == CP_ind:
if CP_loc <= time_range[-1] and CP_loc >= time_range[0]:
CP_loc = ((CP_loc - time_range[0])/T_)*(stop-start) + start# carry CP forward
if CP_ind not in CP_indices_until_now:
handle = ax.axvline(x=CP_loc, color = custom_colors_CPs[count],
linestyle = custom_linestyles[count],
linewidth = custom_linewidth,
alpha = custom_transparency)
CP_legend_handles.append(handle)
CP_legend_labels.append(model_labels[CP_ind])
CP_indices_until_now.append(CP_ind)
count= count+1
elif CP_ind in CP_indices_until_now:
"""display it in the same color"""
relevant_index = CP_indices_until_now.index(CP_ind)
handle = ax.axvline(x=CP_loc, color = custom_colors_CPs[relevant_index],
linestyle = custom_linestyles[relevant_index],
linewidth = custom_linewidth,
alpha = custom_transparency)
if not true_CPs is None:
#true_CPs = [[location, color]]
for entry in true_CPs:
ax.axvline(x = entry[0], color = entry[1],
linestyle = "-", linewidth = entry[2])
"""STEP 5: Plot the legend if we want to"""
if not xlab is None:
ax.set_xlabel(xlab, fontsize = xlab_fontsize)
if not ylab is None:
ax.set_ylabel(ylab, fontsize = ylab_fontsize)
if not ylabel_coords is None:
ax.get_yaxis().set_label_coords(ylabel_coords[0], ylabel_coords[1])
if not xticks_fontsize is None:
ax.tick_params(axis='x', labelsize=xticks_fontsize) #, rotation=90)
if not yticks_fontsize is None:
ax.tick_params(axis='y', labelsize=yticks_fontsize) #, rotation=90)
#set x/ylims
if not set_xlims is None:
ax.set_xlim(set_xlims[0], set_xlims[1])
if not set_ylims is None:
ax.set_ylim(set_ylims[0], set_ylims[1])
ax.set_aspect(aspect_ratio)
if legend:
ax.legend(legend_handles, legend_labels, loc = legend_position)
"""STEP 6: If we are supposed to print this picture, do so. Regardless
of whether you print it, return the resulting object"""
#if print_plt:
# plt.show()
return ax #figure
"""PLOT II: get the 1-step-ahead predictions together with the estimated
CPs and return as a figure plt.figure() object.
Options:
indices => list of indices in 1d. (data already be flattened)
s.t. the corresponding TS will be plotted
time_range => range of time over which we should plot the TS
print_plt => boolean, decides whether we want to see the plot
or just create the object to pass to the next fct.
legend => boolean, whether or not we want a legend
legend_labels => gives you the labels for the TS as a list of
strings. If you don't specify the labels,
default is 1,2,...
legend_position => gives the
position of the legend, and default is upper left
show_var => bool indicating whether or not the square root of
the diagonal of the posterior covariance should be
plotted around the mean predictions
show_CPs => bool indicating whether or not the MAP CPs should be
included in the plot
"""
def plot_predictions(self, indices = [0], print_plt = True, legend = False,
legend_labels = None,
legend_position = None, time_range = None,
show_var = True, show_CPs = True,
ax = None, aspect_ratio = 'auto',
set_xlims = None,
set_ylims = None):
"""Generates plot of the pred TS at the positions marked by *indices*,
over entire time range unless specificed otherwise via *time_range*. It
prints the picture to the console if *print_plt* is True, and puts a
legend on the plot if *legend* is True. Posterior variances around the
predicted TS are shown if *show_var* is True. The MAP CPs are shown
if show_CPs = True."""
"""STEP 1: Default is to take the entire time range"""
T = self.results[self.names.index("T")]
if time_range is None:
time_range = np.linspace(1,T,T, dtype=int)
if ax is None:
figure, ax = plt.subplots()
"""STEP 2: If we do want a legend, the labels are 1,2,3... by default
and we plot in the upper left corner by default."""
num = int(len(indices))
if legend and legend_labels is None:
legend_labels = [str(int(i)) for i in np.linspace(1,num,num)]
if legend and legend_position is None:
legend_position = 'upper left'
if not legend and legend_labels is None:
legend_labels = []
"""STEP 3: Plot all the predicted means specified by the index object,
and also the predictive variance if *show_var* is True"""
S1, S2 = self.results[self.names.index("S1")], self.results[self.names.index("S2")]
means = (self.results[self.names.index("one-step-ahead predicted mean")]
[time_range-1 ,:,:]).reshape((int(len(time_range)), S1*S2))[:,indices]
if show_var:
std_err = np.sqrt(
self.results[self.names.index("one-step-ahead predicted variance")]
[time_range-1 ,:][:,indices])
#figure = plt.figure()
legend_handles = []
for i in range(0, num):
"""The handle is like an identifier for that TS object"""
handle, = ax.plot(time_range, means[:,i], color = self.colors[i])
legend_handles.append(handle)
"""If required, also plot the errors around the series"""
if show_var:
ax.plot(time_range, means[:,i]+ std_err[:,i], color = self.colors[i],
linestyle = ":")
ax.plot(time_range, means[:,i]-std_err[:,i], color = self.colors[i],
linestyle = ":")
"""STEP 4: If we have CPs, plot them into the figure, too"""
if show_CPs:
CP_object = self.results[self.names.index("MAP CPs")][-2]
#print(CP_object)
CP_locations = [entry[0] for entry in CP_object]
CP_indices = [entry[1] for entry in CP_object]
model_labels = self.results[self.names.index("model labels")]
CP_legend_labels = []
CP_legend_handles = []
for (CP_loc, CP_ind) in zip(CP_locations, CP_indices):
handle = ax.axvline(x=CP_loc, color = self.CP_color,
linestyle = self.linestyle[CP_ind])
CP_legend_handles.append(handle)
CP_lab = model_labels[CP_ind]
CP_legend_labels.append(CP_lab)
#DEBUG: Could make this conditional on another boolean input
legend_handles += CP_legend_handles
legend_labels += CP_legend_labels
#set x/ylims
if not set_xlims is None:
ax.set_xlim(set_xlims[0], set_xlims[1])
if not set_ylims is None:
ax.set_ylim(set_ylims[0], set_ylims[1])
"""STEP 5: Plot the legend if we want to"""
if legend:
ax.legend(legend_handles, legend_labels, loc = legend_position)
"""STEP 6: If we are supposed to print this picture, do so. Regardless
of whether you print it, return the resulting object"""
#if print_plt:
# ax.show()
ax.set_aspect(aspect_ratio)
return ax
"""PLOT III: plot the prediction errors
Options:
time_range => range of time over which we should plot the TS
print_plt => boolean, decides whether we want to see the plot
or just create the object to pass to the next fct.
legend => boolean telling you whether you should put the legend
in the plot
show_MAP_CPs => bool indicating whether or not the MAP CPs should be
included in the plot
show_real_CPs => bool indicating whether or not the true CPs
should be included in the plot
show_var => bool indicating whether you should show the pred.
std. err. around the pred. error
"""
def plot_prediction_error(self, data, indices=[0], time_range = None,
print_plt=False,
legend=False,
show_MAP_CPs = False,
show_real_CPs = False, show_var = False,
custom_colors = None,
ax=None, xlab = "Time", ylab = "Value",
aspect_ratio = 'auto', xlab_fontsize = 10,
ylab_fontsize = 10,
xticks_fontsize = 10,
yticks_fontsize = 10,
ylabel_coords = None,
set_xlims = None,
set_ylims = None,
up_to = None):
"""STEP 1: Obtain the time range if needed, else set it to 1:T"""
T = self.results[self.names.index("T")]
S1 = self.results[self.names.index("S1")]
S2 = self.results[self.names.index("S2")]
if time_range is None:
time_range = np.linspace(1,T,T, dtype=int)
if ax is None:
figure, ax = plt.subplots()
num = int(len(indices))
if data.ndim == 3:
data = data.reshape(T, S1*S2)
if custom_colors is None:
custom_colors = self.colors
#indices = np.array(indices)
"""STEP 2: Obtain the prediction errors"""
dat = data[time_range-1,:][:, indices]