-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicAnalyzer.py
1717 lines (1502 loc) · 77.2 KB
/
BasicAnalyzer.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
'''
This module defines the Analyzer object, that stores episodic time-series and analyze them for differences.
INPUT:
The constructor requires a path to a pickle file with a dictionary whose entries are:
- scenarios: a dataframe with the columns scenario/episode/seed/score, where each row corresponds to a single episode.
- env_args: env_args[scenario_name] = a dictionary of the arguments used to generate episodes in this scenario.
- data: data[scenario_name][i] = a list of values (e.g. rewards) in the i'th episode of the scenario. all episodes are assumed to be of the same length.
MODULE STRUCTURE:
- General methods
- Methods corresponding to descriptive statistics on episodes level (not looking within episodes)
- Methods corresponding to statistical tests on episode level (not looking within episodes)
- Methods corresponding to descriptive statistics on time-steps level
- Methods corresponding to statistical tests on time-steps level
- Methods corresponding to sequential tests
- Methods corresponding to summary: run_summarizing_tests() & analysis_summary()
Example:
# Define statistical tests (dictionary of pairs (constructor,args)):
tests = dict(
Mean = (Stats.SimpleMean, dict()),
CUSUM = (Stats.CUSUM, dict()),
UDT = (Stats.WeightedMean, dict()),
PDT = (Stats.TransformedCVaR, dict(p=0.9)),
)
# Create an analyzer of HalfCheetah rewards, with sample-resolution of 25 (i.e. each sample is the mean of 25 time-steps):
A = Analyzer.Analyzer('HalfCheetah_data', Path('Spectation/data/HalfCheetah-v3'), resolution=25, title='HalfCheetah')
# Run both individual & sequential tests (levels=1 would run only individual tests):
A.run_summarizing_tests(save_name='HalfCheetah', ns=(100,300,1000,3000,10000,30000,50000),
default_tester_args=dict(B=5000), lookback_horizons=(5,50), seq_test_len=50, tests=tests, levels=3)
# Analyze both individual & sequential tests results:
A.analysis_summary('HalfCheetah', do_sequential=True, do_non_seq=True)
Code profiling:
- downsampling is the costliest action in all the code.
it was moved to Analyzer (from StatsCalculator) to reduce number of calls (reduced running time ~x10).
- transforming p to z is about half as costly as calculating the statistic, and 50% of these calls were redundant.
- never assign single values to df.loc[index, col]. do the assignment for all the column together.
- next beneficial change is an efficient implementation of the rolling statistics calculation.
Ido Greenberg, 2020
'''
import pickle as pkl
from warnings import warn
from pathlib import Path
from time import time
from collections import Counter
import numpy as np
import scipy as sp
import scipy.stats as stats
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.tsa.stattools import acf, pacf
import StatsCalculator as Stats
import utils
pd.options.mode.chained_assignment = None # default='warn'
DATA = Path('Spectation/data/HalfCheetah-v3')
class Analyzer:
def __init__(self, fname, path=DATA, side=-1, resolution=1, seed=1, title='', variance_analysis=None,
uniform_T=True):
if not fname.endswith('.pkl'):
fname += '.pkl'
with open(path/fname, 'rb') as fd:
tmp = pkl.load(fd)
meta, env_args, data = tmp['scenarios'], tmp['env_args'], tmp['data']
self.m = meta
self.m['meta_scenario'] = [sc[:-3] if len(sc) > 3 else sc for sc in self.m.scenario]
self.env_args = env_args
self.resolution = resolution
to_ndarray = lambda a,N: np.array(a)
T = None
if not uniform_T:
def maxT(dd):
return max([max([len(aa) for aa in a]) for a in dd.values()])
def to_ndarray(a, N=None):
n1 = len(a)
n2 = max([len(aa) for aa in a]) if N is None else N
y = np.zeros((n1, n2))
for i,aa in enumerate(a):
y[i, :len(aa)] = aa
return y
T = maxT(data)
self.d = {s:to_ndarray(d,T) for s,d in data.items()} # N x T
self.downsample()
self.title = title
self.seed = seed
self.side = side
self.scenarios = np.unique(self.m.scenario)
self.T = len(self.d[self.scenarios[0]][0])
self.scores_std = {s:np.std(self.get_scenario_scores(s)) for s in self.scenarios}
self.G0 = {s:np.cov(np.array(self.d[s]).transpose()) for s in self.scenarios}
self.boot = {}
self.episode_stats = {}
if variance_analysis:
if isinstance(variance_analysis, str):
self.episode_variance_analysis(scenario=variance_analysis)
else:
self.episode_variance_analysis()
self.res = {}
# self.alpha = {} # (alpha0, horizons, frequency) -> alpha
def set_seed(self, seed=None):
if seed is None:
seed = self.seed
np.random.seed(seed)
def get_scenario_scores(self, scenario):
return self.m.score[self.m.scenario == scenario]
def get_meta_scenarios_summary(self, verbose=1):
ret = self.m.groupby('meta_scenario').apply(
lambda m: f'{len(m):d} episodes, {len(np.unique(m.scenario)):d} blocks, {len(np.unique(m.seed)):d} unique seeds.'
# dict(tot_episodes=len(m), sub_scenarios=len(np.unique(m.scenario)),
# unique_seeds=len(np.unique(m.seed)))
)
if verbose >= 1:
print(ret)
return ret
def n_episodes(self, scenario):
return (self.m.scenario == scenario).sum()
def get_scenarios_data(self, scenario_prefix):
return np.concatenate([self.d[s] for s in self.scenarios if s.startswith(scenario_prefix)], axis=0)
def z2p(self, z, side=None):
if side is None: side = self.side
if side == 0:
p = 2 * stats.norm.sf(np.abs(z))
elif side < 0:
p = stats.norm.sf(-z)
else:
p = stats.norm.sf(z)
return p
def smooth_scenario_data(self, scenario='ref', resolution=1, fun=np.sum):
assert (self.T % resolution == 0)
if resolution == 1:
return self.d[scenario]
return np.array([fun(a, axis=1) for a in np.split(self.d[scenario], self.T//resolution, axis=1)]).transpose()
def downsample(self, fun=None):
if self.resolution == 1:
return
if fun is None: fun = np.mean
for nm, X in self.d.items():
T = X.shape[1]
if T % self.resolution != 0:
warn(f'Data was cropped to be integer multiplication of the resolution: {T:d} -> {T - (T % self.resolution):d}')
T -= T % self.resolution
X = [fun(X[:, i*self.resolution : (i+1)*self.resolution], axis=1)[:,np.newaxis] for i in range(T//self.resolution)]
X = np.concatenate(X, axis=1)
self.d[nm] = X
def plot_episode_transitions(self, ax, Tf, Ti=0, color='k', linestyle=':', linewidth=0.5):
ax.grid(False, axis='x')
for t in range(Ti, Tf+1, self.T * self.resolution):
ax.axvline(t, color=color, linestyle=linestyle, linewidth=linewidth)
def merge_analyzer(self, A2, pre1='', pre2='', scenarios2=None):
if pre1 and not pre1.endswith('_'): pre1 += '_'
if pre2 and not pre2.endswith('_'): pre2 += '_'
if scenarios2 is None: scenarios2 = A2.scenarios
if pre1:
self.m['scenario'] = [pre1+s for s in self.m['scenario']]
self.m['meta_scenario'] = [sc[:-3] if not sc.endswith('ref') else sc for sc in self.m.scenario]
self.d = {(pre1+k): v for k, v in self.d.items()}
self.scenarios = [pre1+s for s in self.scenarios]
self.env_args = {(pre1+k): v for k, v in self.env_args.items()}
if pre2:
A2.m['scenario'] = [pre2+s for s in A2.m['scenario']]
A2.m['meta_scenario'] = [sc[:-3] if not sc.endswith('ref') else sc for sc in A2.m.scenario]
A2.d = {(pre2+k): v for k, v in A2.d.items()}
A2.scenarios = [pre2+s for s in A2.scenarios]
A2.env_args = {(pre2+k): v for k, v in A2.env_args.items()}
scenarios2 = [pre2+s for s in scenarios2]
self.m = pd.concat((self.m, A2.m[A2.m.scenario.isin(scenarios2)]))
self.d = utils.update_dict(self.d, {s:v for s,v in A2.d.items() if s in scenarios2})
self.scenarios = np.concatenate((self.scenarios, scenarios2))
self.env_args = utils.update_dict(self.env_args, {s:v for s,v in A2.env_args.items() if s in scenarios2})
def rename_scenarios(self, meta_scenarios_map):
for sc1, sc2 in meta_scenarios_map.items():
if sc1 == sc2:
continue
blocks = np.unique(self.m[self.m.meta_scenario==sc1].scenario)
self.m.loc[self.m.meta_scenario==sc1,'scenario'] = [s.replace(sc1,sc2)
for s in self.m[self.m.meta_scenario==sc1].scenario]
self.m.loc[self.m.meta_scenario==sc1,'meta_scenario'] = sc2
for sc in blocks:
self.d[sc.replace(sc1,sc2)] = self.d[sc]
self.d[sc] = None
self.env_args[sc.replace(sc1, sc2)] = self.env_args[sc]
self.env_args[sc] = None
self.scenarios = np.unique(self.m.scenario)
############ EPISODES: DESCRIPTIVE STATISTICS ############
def scores_boxplot(self, scenarios=None, ax=None, figsize=(12, 4), rotation=20):
if scenarios is None:
scenarios = self.scenarios
ax = utils.Axes(1, axsize=figsize)[0] if ax is None else ax
ax = sns.boxplot(data=self.m[self.m.scenario.isin(scenarios)], x='scenario', y='score', showmeans=True, ax=ax)
ax.set_xticklabels(ax.get_xticklabels(), rotation=rotation)
return ax
@staticmethod
def qqplot_normal(x, tit=None, ax=None, labs=None):
x = np.array(x)
if x.ndim == 1:
x = np.array([x])
if labs is None:
labs = len(x) * [None]
ax = utils.Axes(1)[0] if ax is None else ax
ax.plot([np.min(x.reshape(-1)), np.max(x.reshape(-1))],
[np.min(x.reshape(-1)), np.max(x.reshape(-1))], 'k--')
for xx, l in zip(x,labs):
z, y = stats.probplot(xx, dist="norm")[0]
ax.plot(z, y, '.-', label=l)
if labs[0]:
ax.legend(fontsize=10)
utils.labels(ax, 'Theoretical quantiles', 'Ordered values', tit, 14)
@staticmethod
def qqplot_unif(x, a=0, b=1, xlab='', ylab=None, tit=None, labs=None, ax=None):
x = np.array(x)
if x.ndim == 1:
x = np.array([x])
if labs is None:
labs = len(x) * [None]
ax = utils.Axes(1)[0] if ax is None else ax
ax.plot([0, 100], [a, b], 'k--')
for xx, l in zip(x,labs):
ax.plot(utils.get_quantiles(xx)[0], label=l)
utils.labels(ax, f'{xlab} quantile [%]', ylab, tit, 13)
if labs[0]:
ax.legend(fontsize=10)
return ax
@staticmethod
def qqplot(x1, x2, lab1='', lab2='', labs=None, ax=None, figsize=(6, 6)):
x2 = np.array(x2)
if x2.ndim == 1:
x2 = np.array([x2])
if labs is None:
labs = len(x2) * [None]
ax = utils.Axes(1, axsize=figsize)[0] if ax is None else ax
a = min(np.min(x1), np.min(x2.reshape(-1)))
b = max(np.max(x1), np.max(x2.reshape(-1)))
ax.plot([a, b], [a, b], 'k--')
for xx, l in zip(x2, labs):
ax.plot(utils.get_quantiles(x1)[0], utils.get_quantiles(xx)[0], '.', label=l)
if labs[0]: ax.legend(fontsize=10)
if lab1: ax.set_xlabel(lab1)
if lab2: ax.set_ylabel(lab2)
return ax
def scenarios_qplots(self, scenarios=None, ax=None):
if scenarios is None:
scenarios = self.scenarios
ax = utils.Axes(1)[0] if ax is None else ax
for s in scenarios:
utils.plot_quantiles(self.get_scenario_scores(s), ax=ax, label=s)
utils.labels(ax, 'Quantile [%]', 'Scenario score')
ax.legend(fontsize=10)
return ax
def episode_scores_descriptive_summary(self, ref=None, scenarios=None, z=None, axs=None,
n_plot=24, rotation=90, ylim=(6.2,7.2)):
if scenarios is None:
scenarios = self.scenarios
if ref is None:
ref = scenarios[0]
scenarios2 = [s for s in scenarios if s != ref]
if z is None:
z = np.random.random(len(scenarios2))
if axs is None:
axs = utils.Axes(6, axsize=(8,4))
a = 0
# scores boxplot
self.scores_boxplot(scenarios=scenarios[:n_plot], ax=axs[a], rotation=rotation)
a += 1
# number of episodes per scenario
axs[a].hist([self.n_episodes(s) for s in scenarios])
utils.labels(axs[a], '#episodes', title='Histogram')
a += 1
# score vs. episode-quantile by scenario
tmp = [ref, scenarios[np.argmin(z)]] + list(np.random.choice(scenarios2, 2, replace=False)) + [
scenarios[np.argmax(z)]]
self.scenarios_qplots(tmp, axs[a])
self.scenarios_qplots(tmp, axs[a+1])
axs[a+1].set_ylim(ylim)
a += 2
# qqplot scenarios vs. ref
ax = axs[a]
x1 = self.get_scenario_scores(ref)
x2 = [self.get_scenario_scores(s) for s in tmp[1:]]
Analyzer.qqplot(x1, x2, lab1=f'{ref} quantiles', lab2='new quantiles', labs=tmp[1:], ax=ax)
a += 1
# qqplot scenarios vs. ref (zoom-in)
ax = axs[a]
x1 = self.get_scenario_scores(ref)
x2 = [self.get_scenario_scores(s) for s in tmp[1:]]
Analyzer.qqplot(x1, x2, lab1=f'{ref} quantiles', lab2='new quantiles', labs=tmp[1:], ax=ax)
ax.set_xlim(ylim)
ax.set_ylim(ylim)
a += 1
return axs
############ EPISODES: STATISTICAL TESTS ############
def compare_means_t_test(self, s2, s1, side=None, verbose=0):
if side is None: side = self.side
x1 = self.get_scenario_scores(s1)
x2 = self.get_scenario_scores(s2)
n1 = len(x1)
n2 = len(x2)
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1) / n1
v2 = np.var(x2) / n2
if verbose >= 2:
print(dict(n1=n1, n2=n2, m1=m1, m2=m2, v1=v1, v2=v2))
z = (m2 - m1) / np.sqrt(v1 + v2)
p = self.z2p(z, side)
if verbose >= 1 or n1 < 30 or n2 < 30:
warn(f"T-test is actually implemented as Z-test for the sake of lazyness, but should be fine (n1={n1:.0f}, n2={n2:.0f})")
return p, z
def bootstrap(self, s, B, n=None, fun=np.mean, fun_name='mean', Tf=None, overwrite=False):
if Tf is None: Tf = self.T
if n is None:
n = self.n_episodes(s)
if fun_name not in self.boot:
self.boot[fun_name] = {}
if s not in self.boot[fun_name]:
self.boot[fun_name][s] = {}
if n not in self.boot[fun_name][s]:
self.boot[fun_name][s][n] = {}
if Tf not in self.boot[fun_name][s][n] or overwrite:
if Tf == self.T:
x = self.get_scenario_scores(s)
st = np.array([fun(np.random.choice(x, n, replace=True)) for _ in range(B)])
else:
if fun is not np.mean:
raise ValueError('Partial-episode bootstrap only supports mean-reducer.')
x = self.d[s]
full_scores = np.mean(x, axis=1)
pre_scores = np.mean(x[:, :Tf], axis=1)
n_samples = (n-1) * self.T + Tf
w_pre = Tf / n_samples
st = np.array([
w_pre * np.mean(np.random.choice(pre_scores, 1, replace=True)) + \
(1-w_pre) * (np.mean(np.random.choice(full_scores, n-1, replace=True)) if n>1 else 0)
for _ in range(B)
])
self.boot[fun_name][s][n][Tf] = st
def mean_bootstrap_test(self, s, s0='ref', B=2000, fun=np.mean, fun_name='mean',
episodes=None, Tf=None, side=None, seed=None, overwrite=False):
if Tf is None: Tf = self.T
if side is None: side = self.side
self.set_seed(seed)
# get statistic
# if episodes is None and Tf is None:
n_episodes = self.n_episodes(s)
x = self.get_scenario_scores(s)
st = fun(x)
# else:
# st, n_episodes, Tf, n_samples = self.partial_scenario_stats(s, episodes, Tf, fun=fun)
# get reference distribution
self.bootstrap(s0, B=B, n=n_episodes, fun=fun, fun_name=fun_name, Tf=Tf, overwrite=overwrite)
# get bootstrap p-val
p = (1 + np.sum((st - self.boot[fun_name][s0][n_episodes][Tf]) <= 0)) / (1 + B + (side==0))
z = -stats.norm.ppf(p)
if side < 0:
p = 1 - p + 1/(1+B)
z = stats.norm.ppf(p)
elif side == 0:
p = 2 * min(p, 1 - p)
return p, z
def get_pvals_vs_ref(self, sref='ref', scenarios=None, test=None, **kwargs):
if scenarios is None:
scenarios = self.scenarios
scenarios = [s for s in scenarios if s != sref]
if test is None:
test = self.compare_means_t_test
out = []
for s in scenarios:
out.append(test(s, sref, **kwargs))
return out
def get_pvals_pairs(self, scenarios=None, test=None, **kwargs):
if scenarios is None:
scenarios = self.scenarios
if test is None:
test = self.compare_means_t_test
n = len(scenarios)
p = np.zeros((n, n))
for i, s1 in enumerate(scenarios):
for j, s2 in enumerate(scenarios):
p[s1, s2] = test(s2, s1, **kwargs)[0]
return p
def episode_scores_tests_summary(self, scenarios2, z1, z2, p1, p2, lab1='T-test', lab2='Bootstrap',
axs=None, n_plot=24, rotation=90):
if axs is None:
axs = utils.Axes(4, axsize=(8,4))
a = 0
ax = axs[a]
tmp = pd.DataFrame(dict(
scenario=scenarios2[:n_plot] + scenarios2[:n_plot],
test=np.repeat((lab1, lab2), min(len(z1), n_plot)),
zval=np.concatenate((z1[:n_plot], z2[:n_plot]))
))
print(tmp)
sns.barplot(data=tmp, x='scenario', y='zval', hue='test', ax=ax)
ax.grid()
ax.set_xticklabels(scenarios2[:n_plot], rotation=rotation)
a += 1
Analyzer.qqplot_normal((z1, z2), 'Z-values', axs[a],
(f'{lab1:s} ({np.min(z1):.1f} - {np.max(z1):.1f})',
f'{lab2:s} ({np.min(z2):.1f} - {np.max(z2):.1f})'))
a += 1
Analyzer.qqplot_unif((p1, p2), a=0, b=1, xlab='Scenario', ylab='P-value', labs=(lab1, lab2), ax=axs[a])
a += 1
Analyzer.qqplot_unif((p1, p2), a=0, b=1, xlab='Scenario', ylab='P-value', ax=axs[a],
labs=(f'{lab1:s}: P(p<0.01)={np.mean(np.array(p1)<0.01):.3f}, P(p<0.05)={np.mean(np.array(p1)<0.05):.3f}',
f'{lab2:s}: P(p<0.01)={np.mean(np.array(p2)<0.01):.3f}, P(p<0.05)={np.mean(np.array(p2)<0.05):.3f}'))
axs[a].set_ylim((0,0.05))
a += 1
plt.tight_layout()
return axs
############ TIME-STEPS: DESCRIPTIVE STATISTICS ############
def stats_per_t(self, scenarios=('ref',), funs=(np.mean,)):
if type(scenarios) not in (list,tuple): scenarios = [scenarios]
if type(funs) not in (list,tuple): funs = [funs]
data = np.concatenate([np.array(self.d[s]) for s in scenarios], axis=0)
return [fun(data, axis=0) for fun in funs]
def rewards_per_episode(self, scenario='ref', resolution=25, outliers=0.2, acf_lags=100, show_dims=None):
if show_dims is None:
show_dims = (0, 5, 20, 100, int(0.5*self.T), int(0.9*self.T), int(0.95*self.T), int(0.99*self.T))
axs = utils.Axes(6+2*(self.resolution==1), axsize=(8, 4), fontsize=14)
axs[0].plot([np.mean([rs[i] for rs in self.d[scenario]]) for i in range(len(self.d[scenario][0]))])
axs.labs(0, 'time', 'average reward\nover episodes')
axs[1].plot([np.std([rs[i] for rs in self.d[scenario]]) for i in range(len(self.d[scenario][0]))])
axs.labs(1, 'time', 'std(rewards)\nover episodes')
ts = np.arange(0, len(self.d[scenario][0]), resolution)
sns.boxplot(data=pd.DataFrame(dict(time=self.n_episodes(scenario) * list(ts),
reward=[rs[i] for rs in self.d[scenario] for i in ts])),
x='time', y='reward', ax=axs[2], showmeans=True, fliersize=outliers)
axs[2].set_xticklabels(axs[2].get_xticklabels(), rotation=90)
sns.heatmap(self.G0[scenario], ax=axs[3],
cmap=sns.diverging_palette(h_neg=10, h_pos=130, sep=1, as_cmap=True), center=0)
axs.labs(3, 't2', 't1', f'[{scenario:s}] rewards covariance matrix')
for d in show_dims:
axs[4].plot(self.G0[scenario][:,d], label=f't1={d:d}')
axs.labs(4, 't2', 'Cov(r(t1), r(t2))')
axs[4].legend(fontsize=10, loc='upper center')
for d in show_dims:
axs[5].plot(np.arange(d,self.T)-d//2, [self.G0[scenario][t, t+d] for t in range(self.T-d)],
label=f'dt={d:d}')
axs.labs(5, 't', 'Cov(r(t), r(t+dt))')
axs[5].legend(fontsize=10, loc='upper left')
if self.resolution == 1:
self.pacf(scenarios=(scenario,), partial=False, nlags=acf_lags, do_plot=True, ax=axs[6])
self.pacf(scenarios=(scenario,), partial=True, nlags=acf_lags, do_plot=True, ax=axs[7])
plt.tight_layout()
def pacf(self, scenarios=('ref',), max_samples=None, time_range=None, merge_episodes=False,
partial=True, remove_zero=True, alpha=0.01, nlags=50, normalize=False,
do_plot=False, print_params=True, hline=0.03, ax=None, tit=None):
fun = pacf if partial else acf
if max_samples is None:
max_samples = 1e5 if partial else 1e6
if time_range is None:
time_range = (0, self.T)
n = time_range[1] - time_range[0]
if normalize:
M, S = self.stats_per_t(scenarios, (np.mean,np.std))
else:
M = np.zeros(len(self.d[scenarios[0]][0]))
S = np.ones( len(self.d[scenarios[0]][0]))
if merge_episodes:
rewards = np.array([(ep[t]-M[t])/S[t] for s in scenarios for ep in self.d[s] for t in range(time_range[0],time_range[1]) ])
if max_samples:
rewards = rewards[:int(max_samples)]
corr, err = fun(rewards, alpha=alpha, nlags=nlags)
err = (err[:, 1] - err[:, 0]) / 2
else:
corr = np.zeros(1+nlags)
corr2 = np.zeros(1+nlags)
count = 0
for s in scenarios:
for ep in self.d[s]:
r = [(ep[t]-M[t])/S[t] for t in range(time_range[0],time_range[1])]
tmp = fun(r, alpha=None, nlags=nlags)
corr += tmp
corr2 += tmp**2
count += 1
if count*n >= max_samples:
break
if count*n >= max_samples:
break
corr /= count
corr2 /= count
err = np.sqrt((corr2 - corr**2) / count) * stats.norm.ppf(1-alpha)
if remove_zero:
corr, err = corr[1:], err[1:]
if do_plot:
ax = utils.Axes(1)[0] if ax is None else ax
if hline is not None:
ax.axhline(-hline, color='k', linestyle=':')
ax.axhline( hline, color='k', linestyle=':')
ax.errorbar(1 + np.arange(len(corr)), corr, yerr=err, fmt='.-', ecolor='r', capthick=2)
if print_params:
tmp = f'(#scenarios={len(scenarios):d} | samples={n*count:d} | time_range=({time_range[0]:d},{time_range[1]:d})\n'
tmp += f'alpha={alpha:.3f} | thresh={hline if hline else "none"} | merged_episodes={merge_episodes})'
tit = (tit+'\n'+tmp) if tit else tmp
utils.labels(ax, 'Lag', 'PACF' if partial else 'ACF', tit, 14)
if ax.get_ylim()[0] < -1: ax.set_ylim((-1,None))
if ax.get_ylim()[1] > 1: ax.set_ylim((None,1))
return corr, err, M, S
def episode_variance_analysis(self, scenario='ref', resolution=1, eps=1e-9):
T = self.T // resolution
R = self.smooth_scenario_data(scenario, resolution)
G0 = np.cov(R.transpose())
G = np.zeros((T, T))
for i in range(T):
for j in range(i):
# G0[i,j] = <G[i,:j+1],G[j,:j+1]> = sum(G[i,:j+1]*G[j,:j+1]) = sum(G[i,:j-1]*G[j,:j-1]) + Gij*Gjj
G[i, j] = (G0[i, j] - np.sum(G[j, :j] * G[i, :j])) / G[j, j] if G[j, j]!=0 else 0
tmp = G0[i, i] - np.sum(G[i, :i] ** 2)
if tmp < -eps:
raise ValueError()
tmp = max(tmp, 0)
G[i, i] = np.sqrt(tmp)
Vt = np.array([G0[t,t] for t in range(len(G0))]) # time base
V = np.sum(G, axis=0)**2 # orthogonal base
if scenario not in self.episode_stats: self.episode_stats[scenario] = {}
self.episode_stats[scenario][resolution] = dict(
stds_t = np.sqrt(Vt),
vars_t = Vt,
vars_sum = np.sum(Vt),
vars_perp = V,
vars_gram = G,
modeled_cum_var = [np.sum(np.sum(G[:t,:t],axis=0)**2) for t in range(len(G))],
modeled_tot_var = np.sum(V),
empiric_tot_var = (self.T * self.scores_std[scenario])**2,
marginal_var_perp = V[-1] / Vt[-1],
)
return V, G
def episode_variance_summary(self, scenario='ref', resolution=1, show_dims=None):
T = self.T // resolution
if show_dims is None:
show_dims = (0, 1, 2, 5, 10, int(0.1*T), int(0.5*T), int(0.9*T), int(0.95*T), int(0.99*T))
time_ticks = resolution * (1 + np.arange(T))
R = self.smooth_scenario_data(scenario, resolution)
G0 = np.cov(R.transpose())
V, G = self.episode_variance_analysis(scenario=scenario, resolution=resolution)
axs = utils.Axes(8, axsize=(8, 3.5), fontsize=14)
a = 0
sns.heatmap(G, ax=axs[a], cmap=sns.diverging_palette(h_neg=10, h_pos=130, sep=1, as_cmap=True), center=0)
axs.labs(a, title=f'Gram matrix of covariance\n(sample resolution = {resolution:d} time-steps)')
a += 1
axs[a].plot(time_ticks, self.episode_stats[scenario][resolution]['vars_t'])
axs.labs(a, 'Time step', 'Variance',
f'Naive (iid-based) total variance: {self.episode_stats[scenario][resolution]["vars_sum"]:.0f}\n' + \
f'Empirical total variance: {self.episode_stats[scenario][resolution]["empiric_tot_var"]:.0f}')
a += 1
axs[a].plot(time_ticks, [100*G[i,i]**2/G0[i,i] for i in range(len(G))])
axs[a].set_ylim((0,100))
axs.labs(a, 'Time step', 'Perpendicular variance\n[% of time-step]',
f'Marginal perpendicular variance = {100*self.episode_stats[scenario][resolution]["marginal_var_perp"]:.0f}%')
a += 1
axs[a].plot(time_ticks, 100 * np.array(self.episode_stats[scenario][resolution]['modeled_cum_var']) / \
self.episode_stats[scenario][resolution]['modeled_tot_var'])
axs[a].set_ylim((0,100))
axs.labs(a, 'Time step', 'Accumulated variance [%]')
a += 1
I = 100 * V / np.sum(V)
axs[a].plot(time_ticks, I)
axs.labs(a, 'Time step', 'New info [% of episode info]')
a += 1
axs[a].plot(time_ticks, np.cumsum(I))
axs.labs(a, 'Time step', 'Accumulated info [%]',
f'Orthogonal-covs-based total variance: {self.episode_stats[scenario][resolution]["modeled_tot_var"]:.0f}\n' + \
f'Empirical total variance: {self.episode_stats[scenario][resolution]["empiric_tot_var"]:.0f}')
a += 1
for i in range(2):
axs[a+i].axhline(0, color='k')
for d in show_dims:
axs[a+0].plot(time_ticks, G[:,d], label=f'dim={d:d} (sum={np.sum(G[:,d]):.1f})')
axs.labs(a+0, 'Time step', 'STD component\nin dimension')
axs[a+1].plot(time_ticks, np.cumsum(G[:,d]), label=f'dim={d:d}')
axs.labs(a+1, 'Time step', 'Accum. STD component')
axs[a+0].legend(fontsize=10, loc='center')
axs[a+1].legend(fontsize=10, loc='center left')
a += 2
plt.tight_layout()
return axs
def reward_per_time_by_scenario(self, scenarios, resolution=1, s0='ref', outliers_size=2, fontsize=16, axs=None):
if axs is None: axs = utils.Axes(2 + 3*(len(scenarios)>1))
if len(scenarios) == 1:
s = scenarios[0]
ts = np.arange(0, len(self.d[s][0]), resolution)
sns.boxplot(data=pd.DataFrame(dict(
t=self.n_episodes(s) * list(self.resolution*(1+ts)),
reward=[rs[i] for rs in self.d[s] for i in ts])),
x='t', y='reward', ax=axs[0], showmeans=True, fliersize=outliers_size)
axs[0].set_xticklabels(axs[0].get_xticklabels(), rotation=90)
utils.labels(axs[0], 't', 'reward', self.title, fontsize=fontsize)
for s in scenarios:
X = self.get_scenarios_data(s)
axs[1].plot(self.resolution*np.arange(1,1+self.T), np.std(X, axis=0), label=s)
utils.labels(axs[1], 't', 'std(reward)', self.title, fontsize=fontsize)
else:
X0 = self.d[s0]
for s in scenarios:
X = self.get_scenarios_data(s)
axs[0].plot(self.resolution*np.arange(1,1+self.T), np.mean(X, axis=0), label=s)
axs[1].plot(self.resolution*np.arange(1,1+self.T), np.std(X, axis=0), label=s)
axs[2].plot(self.resolution*np.arange(1,1+self.T), np.mean(X, axis=0)-np.mean(X0, axis=0), label=s)
axs[3].plot(self.resolution*np.arange(1,1+self.T), (np.mean(X,axis=0)-np.mean(X0,axis=0))/np.abs(np.mean(X0,axis=0)), label=s)
axs[4].plot(self.resolution*np.arange(1,1+self.T), (np.mean(X,axis=0)-np.mean(X0,axis=0))/np.std(X0,axis=0), label=s)
utils.labels(axs[0], 't', 'mean reward', self.title, fontsize=fontsize)
utils.labels(axs[1], 't', 'std(reward)', self.title, fontsize=fontsize)
utils.labels(axs[2], 't', 'mean reward - reference', self.title, fontsize=fontsize)
utils.labels(axs[3], 't', '(reward-reference)/reference', self.title, fontsize=fontsize)
utils.labels(axs[4], 't', 'standardized reward', self.title, fontsize=fontsize)
for i in range(5):
axs[i].legend(fontsize=10)
return axs
############ TIME-STEPS: STATISTICAL TESTS ############
def get_scenario_data(self, s, n=None, n_episodes=None, n_additional=None, skip_episodes=0):
if n_episodes is None:
n_episodes = self.n_episodes(s) if n is None else n // self.T
if n_additional is None:
n_additional = 0 if n is None else n % self.T
X = self.d[s][skip_episodes : skip_episodes+n_episodes].reshape(-1)
if n_additional:
X = np.concatenate((X, self.d[s][skip_episodes+n_episodes, :n_additional]))
return X
def show_cov_matrix(self, s0='ref', axs=None):
if axs is None: axs = utils.Axes(9)
STD = np.std(self.d[s0], axis=0)
Sigma = np.cov(np.array(self.d[s0]).transpose())
Corr = np.zeros_like(Sigma)
invSigma = np.linalg.inv(Sigma)
S = invSigma# + invSigma.transpose()
n = S.shape[0]
distance_from_diag = []
Sigma_el = []
Corr_el = []
S_el = []
for i in range(n):
for j in range(n):
distance_from_diag.append(self.resolution * (j-i))
Sigma_el.append(Sigma[i,j])
Corr[i,j] = Sigma[i,j]/(STD[i]*STD[j])
Corr_el.append(Corr[i,j])
S_el.append(S[i,j])
dd = pd.DataFrame(dict(
i = np.repeat(self.resolution*(1+np.arange(n)), n),
j = n * list(self.resolution*(1+np.arange(n))),
distance_from_diag = np.abs(np.array(distance_from_diag)),
Cov_matrix_value = Sigma_el,
Cov_matrix_abs_value = np.abs(np.array(Sigma_el)),
Corr_value = Corr_el,
Corr_abs_value = np.abs(np.array(Corr_el)),
S_value = S_el,
S_abs_value = np.abs(np.array(S_el)),
))
sns.heatmap(Sigma, ax=axs[0], cmap=sns.diverging_palette(h_neg=10, h_pos=130, sep=1, as_cmap=True), center=0)
utils.labels(axs[0], f't2 ($\\times {self.resolution}$)', f't1 ($\\times {self.resolution}$)', f'[{self.title:s}] Rewards covariance matrix', 14)
sns.heatmap(S, ax=axs[1], cmap=sns.diverging_palette(h_neg=10, h_pos=130, sep=1, as_cmap=True), center=0)
utils.labels(axs[1], f't2 ($\\times {self.resolution}$)', f't1 ($\\times {self.resolution}$)', f'[{self.title:s}] Inverted covariance matrix', 14)
sns.boxplot(data=dd, x='distance_from_diag', y='Cov_matrix_value', ax=axs[2], showmeans=True)
utils.labels(axs[2], 'distance from diagonal ($|i-j|$)', 'covariance ($\Sigma_{ij}$)', fontsize=16)
sns.boxplot(data=dd, x='distance_from_diag', y='S_value', ax=axs[3], showmeans=True)
sns.boxplot(data=dd, x='distance_from_diag', y='Cov_matrix_abs_value', ax=axs[4], showmeans=True)
sns.boxplot(data=dd, x='distance_from_diag', y='S_abs_value', ax=axs[5], showmeans=True)
sns.heatmap(Corr, ax=axs[6], cmap=sns.diverging_palette(h_neg=10, h_pos=130, sep=1, as_cmap=True), center=0)
utils.labels(axs[6], f't2 ($\\times {self.resolution}$)', f't1 ($\\times {self.resolution}$)', f'[{self.title:s}] Rewards correlations', 14)
sns.boxplot(data=dd, x='distance_from_diag', y='Corr_value', ax=axs[7], showmeans=True)
utils.labels(axs[7], 'distance from diagonal ($|i-j|$)', 'correlation(i,j)', fontsize=16)
sns.boxplot(data=dd, x='distance_from_diag', y='Corr_abs_value', ax=axs[8], showmeans=True)
utils.labels(axs[8], 'distance from diagonal ($|i-j|$)', '|correlation(i,j)|', fontsize=16)
for i in list(range(2,6))+[7,8]:
axs[i].set_xticklabels(axs[i].get_xticklabels(), rotation=90, fontsize=8)
axs[i].set_title(self.title, fontsize=16)
return dd, axs
def show_testers_weights(self, tests, ax=None, s0='ref', normalize=True, logscale=False, resolution=1,
fontsize=16, **kwargs):
if ax is None: ax = utils.Axes(1)[0]
w = {}
for nm, constructor_test_args in tests.items():
tester = constructor_test_args[0](X=self.d[s0], title=nm, **constructor_test_args[1])
try:
w[nm] = tester.get_temporal_weights()
if normalize:
w[nm] /= np.sum(w[nm])
if logscale:
w[nm] = np.abs(w[nm])
ax.plot(self.resolution*resolution*np.arange(1,1+tester.T), w[nm], label=nm, **kwargs)
except NotImplementedError:
pass
# warn(f'Tester {nm:s} has no explicit weights.')
if logscale:
ax.set_yscale('log')
ax.legend(fontsize=12)
title = self.title
if resolution>1:
title += f'(sample resolution = {resolution:d})'
utils.labels(ax, 't', 'weight', title, fontsize=fontsize)
return w, ax
def run_tests(self, tests, meta_scenario, ns, s0='ref', sides=(None,), resolution=1, ref_testers=tuple(),
mark_sign=None, verbose=0, to_save=False, filename='tmp'):
# configuration
# if side is None: side = self.side
if mark_sign is None: mark_sign = (isinstance(sides,dict) or len(sides)>1)
scenarios = [s for s in self.scenarios if s.startswith(meta_scenario)]
if verbose >= 1:
print('Tested scenario:', meta_scenario)
# initialization
tot_sides = int(np.sum([len(ss) for ss in sides.values()])) \
if isinstance(sides,dict) else (len(sides) * len(tests))
n_rows = tot_sides * len(ns) * len(scenarios)
res = pd.DataFrame(dict(
test = n_rows * [''],
side = n_rows * [0],
scenario = n_rows * [''],
n = n_rows * [0],
s = n_rows * [np.nan],
p = n_rows * [np.nan],
z = n_rows * [np.nan]
))
def update_res(count, nm, sd, sc, n, stat, p, z):
res.iloc[count, 0] = f'{nm:s}{"+" if sd>0 else ("-" if sd<0 else "0")}' if mark_sign else nm
res.iloc[count, 1] = sd
res.iloc[count, 2] = sc
res.iloc[count, 3] = n
res.iloc[count, 4] = stat
res.iloc[count, 5] = p
res.iloc[count, 6] = z
# run tests
t0 = time()
testers = []
count = 0
for nm, constructor_test_args in tests.items():
# get/build tester
tester = None
for tmp in ref_testers:
if tmp.title == nm:
tester = tmp # dictionary instead of list would make more sense...
if tester is None:
args = utils.update_dict(constructor_test_args[1],
dict(X=self.d[s0], seed=self.seed, resolution=resolution, B=1000, title=nm),
force=False, copy=True)
tester = constructor_test_args[0](**args)
testers.append(tester)
t_test = len(constructor_test_args)>2 and constructor_test_args[2]
curr_sides = sides[tester.title] if isinstance(sides,dict) else sides
# run test
for n in ns:
for s in scenarios:
X = self.get_scenario_data(s, n//self.resolution, skip_episodes=0)
for side in curr_sides:
if t_test:
p, z = tester.t_test(X, side=side)
stat = np.nan
else:
p, z, stat = tester.bootstrap_main(X, side=side, return_statistic=True)
update_res(count, nm, side, s, n, stat, p, z)
count += 1
tester.clean_gpu(level=2)
if verbose >= 1:
print(f'\t{nm:s} done.\t({time()-t0:.0f} [s])')
if to_save:
with open(f'outputs/non_sequential/{filename:s}.pkl', 'wb') as fd:
pkl.dump((res, testers), fd)
return res, testers
def run_pairs_tests(self, tests, meta_scenarios, ns, s0='ref', n_blocks=100, resolution=1, self_compare=True, ref_testers=tuple(),
verbose=0, to_save=False, filename='tmp'):
# initialization
pairs = [(s1,s2) for s1 in meta_scenarios for s2 in meta_scenarios if (self_compare or s1!=s2)]
n_rows = len(pairs) * len(ns) * len(tests) * n_blocks
res = pd.DataFrame(dict(
scenario1 = n_rows * [''],
scenario2 = n_rows * [''],
n = n_rows * [0],
test = n_rows * [''],
block = n_rows * [0],
s = n_rows * [np.nan],
p = n_rows * [np.nan],
z = n_rows * [np.nan]
))
def update_res(count, s1, s2, n, test, b, stat, p, z):
res.iloc[count, 0] = s1
res.iloc[count, 1] = s2
res.iloc[count, 2] = n
res.iloc[count, 3] = test
res.iloc[count, 4] = b
res.iloc[count, 5] = stat
res.iloc[count, 6] = p
res.iloc[count, 7] = z
# run tests
t0 = time()
testers = []
count = 0
for nm, constructor_test_args in tests.items():
# get/build tester
tester = None
for tmp in ref_testers:
if tmp.title == nm:
tester = tmp # dictionary instead of list would make more sense...
if tester is None:
args = utils.update_dict(constructor_test_args[1],
dict(X=self.d[s0], seed=self.seed, resolution=resolution, B=1000, title=nm),
force=False, copy=True)
tester = constructor_test_args[0](**args)
testers.append(tester)
# run test
for pair in pairs:
for n in ns:
for b in range(n_blocks):
X1 = self.get_scenario_data(f'{pair[0]:s}_{b:02d}', n//self.resolution)
X2 = self.get_scenario_data(f'{pair[1]:s}_{b:02d}', n//self.resolution)
p, z, stat = tester.bootstrap2_main(X1, X2, return_statistic=True)
update_res(count, pair[0], pair[1], n, nm, b, stat, p, z)
count += 1
tester.clean_gpu(level=2)
if verbose >= 1:
print(f'\t{nm:s} done.\t({time()-t0:.0f} [s])')
if to_save:
with open(f'outputs/non_sequential/{filename:s}.pkl', 'wb') as fd:
pkl.dump((res, testers), fd)
return res, testers
def run_tests_with_skips(self, tests, s, s0='ref', ns=None, skips=None, side=None, resolution=1,
max_repetitions=1000, verbose=0, to_save=False, filename='tmp'):
# configuration
if side is None: side = self.side
if ns is None: ns = [self.d[s].shape[0] * self.T]
# if skips is None: skips = list(range(0, self.d[s].shape[0]-np.max(ns)//self.T, int(np.ceil(np.max(ns)/self.T))))
if skips is None: skips = {n: list(range(0, int(min(self.d[s].shape[0]-n//self.T, max_repetitions*np.ceil(n/self.T))),
int(np.ceil(n/self.T)))) for n in ns}
if verbose >= 1:
print('Tested scenario:', s)
# initialization
if isinstance(skips, dict):
n_rows = len(tests) * np.sum(list(map(len, list(skips.values()))))
else:
n_rows = len(tests) * len(ns) * len(skips)
res = pd.DataFrame(dict(
test = n_rows * [''],
n0 = n_rows * [0],
n = n_rows * [0],
s = n_rows * [np.nan],
p = n_rows * [np.nan],
z = n_rows * [np.nan]
))
def update_res(count, nm, n0, n, stat, p, z):
res.iloc[count, 0] = nm
res.iloc[count, 1] = n0
res.iloc[count, 2] = n
res.iloc[count, 3] = stat
res.iloc[count, 4] = p
res.iloc[count, 5] = z
# run tests
t0 = time()
testers = []
count = 0
for nm, constructor_test_args in tests.items():
args = utils.update_dict(constructor_test_args[1],
dict(X=self.d[s0], seed=self.seed, resolution=resolution, B=1000, title=nm),
force=False, copy=True)
tester = constructor_test_args[0](**args)
testers.append(tester)
t_test = constructor_test_args[2] if len(constructor_test_args)>2 else False
for n in ns:
curr_skips = skips[n] if isinstance(skips, dict) else skips
for skip in curr_skips:
n0 = skip * self.T
X = self.get_scenario_data(s, n, skip_episodes=skip)
if t_test:
p, z = tester.t_test(X, side=side)
stat = np.nan
else: