-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathplot_hbm_func.py
1597 lines (1410 loc) · 62.8 KB
/
plot_hbm_func.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
#
# Utility functions for plotting that is not in pints.plot
#
# Contains functions:
# - plot_covariance()
# - plot_covariance_trace()
# - plot_posterior_predictive_distribution()
# - change_labels_pairwise()
# - change_labels_trace()
# - change_labels_histogram()
#
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
def plot_covariance(samples,
corr=False,
kde=False,
ref_parameters=None,
n_percentiles=None):
"""
Take a list of covariance matrix samples and creates a distribution plot
of the covariance matrix.
Idea is to see if this can resemble the covariance matrix that used to
create the low-level individual experiments (observations).
`samples`
A list of samples of covariance matrix, with shape
`(n_samples, dimension, dimension)`.
`corr`
(Optional) If True, plot correlation matrix instead.
`kde`
(Optional) Set to `True` to use kernel-density estimation for the
histograms and scatter plots.
`ref_parameters`
(Optional) A set of parameters for reference in the plot. For example,
if true values of parameters are known, they can be passed in for
plotting.
`n_percentiles`
(Optional) Shows only the middle n-th percentiles of the distribution.
Default shows all samples in `samples`.
Returns a `matplotlib` figure object and axes handle.
"""
# Check samples size
try:
n_sample, n_param, n_param_tmp = samples.shape
except ValueError:
raise ValueError('`samples` must be of shape (n_sample, n_param,'
' n_param)')
# Check dimension
if n_param != n_param_tmp:
raise ValueError('Covariance matrix must be a square matrix')
# Create figure
fig_size = (3 * n_param, 3 * n_param)
fig, axes = plt.subplots(n_param, n_param, figsize=fig_size)
bins = 30
for i in range(n_param):
for j in range(n_param):
if corr and False:
raise NotImplementedError
norm = np.sqrt(samples[:, i, i]) * np.sqrt(samples[:, j, j])
else:
norm = 1.0
samples[:, i, j] = samples[:, i, j] / norm
if i == j and not corr:
# Diagonal: Plot a histogram
if n_percentiles is None:
xmin = np.min(samples[:, i, i])
xmax = np.max(samples[:, i, i])
else:
xmin = np.percentile(samples[:, i, i],
50 - n_percentiles / 2.)
xmax = np.percentile(samples[:, i, i],
50 + n_percentiles / 2.)
xbins = np.linspace(xmin, xmax, bins)
axes[i, j].set_xlim(xmin, xmax)
axes[i, j].hist(samples[:, i, i], bins=xbins, normed=True)
# Add kde plot
if kde:
x = np.linspace(xmin, xmax, 100)
axes[i, j].plot(x, stats.gaussian_kde(samples[:, i, i])(x))
# Add reference parameters if given
if ref_parameters is not None:
ymin_tv, ymax_tv = axes[i, j].get_ylim()
axes[i, j].plot(
[ref_parameters[i, i], ref_parameters[i, i]],
[0.0, ymax_tv],
'--', c='k')
elif i == j and corr:
axes[i, j].set_xlim(-1, 1)
axes[i, j].set_yticklabels([])
elif i < j:
# Top-right: no plot
axes[i, j].axis('off')
else:
# Lower-left: Plot a histogram again
if n_percentiles is None:
xmin = np.min(samples[:, i, j])
xmax = np.max(samples[:, i, j])
else:
xmin = np.percentile(samples[:, i, j],
50 - n_percentiles / 2.)
xmax = np.percentile(samples[:, i, j],
50 + n_percentiles / 2.)
xbins = np.linspace(xmin, xmax, bins)
if corr:
axes[i, j].set_xlim(-1, 1)
else:
axes[i, j].set_xlim(xmin, xmax)
axes[i, j].hist(samples[:, i, j], bins=xbins, normed=True)
# Add kde plot
if kde:
x = np.linspace(xmin, xmax, 100)
axes[i, j].plot(x, stats.gaussian_kde(samples[:, i, j])(x))
# Add reference parameters if given
if ref_parameters is not None:
ymin_tv, ymax_tv = axes[i, j].get_ylim()
axes[i, j].plot(
[ref_parameters[i, j], ref_parameters[i, j]],
[0.0, ymax_tv],
'--', c='k')
# Set tick labels
if i < n_param - 1 and corr:
# Only show x tick labels for the last row
axes[i, j].set_xticklabels([])
elif corr:
# Rotate the x tick labels to fit in the plot
for tl in axes[i, j].get_xticklabels():
tl.set_rotation(30)
# Set axis labels
axes[-1, i].set_xlabel('Parameter %d' % (i + 1))
axes[i, 0].set_ylabel('Frequency')
return fig, axes
def plot_variable_covariance(sample_mean, sample_cov,
ref_parameters=None,
n_percentiles=None,
fig=None, axes=None, colour=None):
# TODO
"""
Take a list of covariance matrix samples and creates a pairwise variable
covariance base on the distribution -- assuming multivariate normal for
now;
TODO: might need to do lognormal case too!
Idea is to see if this can resemble the covariance matrix that used to
create the low-level individual experiments (observations).
`samples`
A list of samples of covariance matrix, with shape
`(n_samples, dimension, dimension)`.
`ref_parameters`
(Optional) A set of parameters for reference in the plot. For example,
if true values of parameters are known, they can be passed in for
plotting. Pass it as [ref_mean, ref_cov].
`n_percentiles`
(Optional) Shows only the middle n-th percentiles of the distribution.
Default shows all samples in `samples`.
Returns a `matplotlib` figure object and axes handle.
"""
# Check samples size
try:
n_sample, n_param, n_param_tmp = sample_cov.shape
except ValueError:
raise ValueError('`samples` must be of shape (n_sample, n_param,'
' n_param)')
# Check dimension
if n_param != n_param_tmp:
raise ValueError('Covariance matrix must be a square matrix')
# Check mean
if sample_mean.shape[0] != n_sample:
print(sample_mean.shape[0], n_sample)
raise ValueError('Number of input means must match input covariance')
if sample_mean.shape[1] != n_param:
raise ValueError('Number of input mean parameters must match input'
' covariance')
# Warning
if n_sample > 1000:
print('WARNING: Large sample size might take long to plot')
# Create figure
if fig is None and axes is None:
fig_size = (3 * n_param, 3 * n_param)
fig, axes = plt.subplots(n_param, n_param, figsize=fig_size)
# Set colour
if colour is None:
colour = '#1f77b4'
def normal1D(x, mu, sigma):
# normal distribution
output = 1/(sigma * np.sqrt(2 * np.pi)) * \
np.exp( - (x - mu)**2 / (2 * sigma**2) )
return output
for i in range(n_param):
for j in range(n_param):
if i == j:
# Diagonal: Plot a 1D distribution
# 2 sigma covers up 95.5%
xmin = np.min(sample_mean[:, i]) \
- 2.5 * np.max(np.sqrt(sample_cov[:, i, i]))
xmax = np.max(sample_mean[:, i]) \
+ 2.5 * np.max(np.sqrt(sample_cov[:, i, i]))
xx = np.linspace(xmin, xmax, 100)
axes[i, j].set_xlim(xmin, xmax)
for m, s in zip(sample_mean[:, i], sample_cov[:, i, i]):
axes[i, j].plot(xx, normal1D(xx, m, np.sqrt(s)),
c=colour, alpha=0.2) #003366
# Add reference parameters if given
if ref_parameters is not None:
m, s = ref_parameters[0][i], ref_parameters[1][i, i]
axes[i, j].plot(xx, normal1D(xx, m, np.sqrt(s)),
'--', c='r', lw=2)
elif i < j:
# Top-right: no plot
axes[i, j].axis('off')
else:
# Lower-left: Plot a bivariate contour of CI
# 2 sigma covers up 95.5%
xmin = np.min(sample_mean[:, j]) \
- 2.5 * np.max(np.sqrt(sample_cov[:, j, j]))
xmax = np.max(sample_mean[:, j]) \
+ 2.5 * np.max(np.sqrt(sample_cov[:, j, j]))
ymin = np.min(sample_mean[:, i]) \
- 2.5 * np.max(np.sqrt(sample_cov[:, i, i]))
ymax = np.max(sample_mean[:, i]) \
+ 2.5 * np.max(np.sqrt(sample_cov[:, i, i]))
axes[i, j].set_xlim(xmin, xmax)
axes[i, j].set_ylim(ymin, ymax)
for m, s in zip(sample_mean, sample_cov):
# for xj, yi
mu = np.array([m[j], m[i]])
cov = np.array([[ s[j, j], s[j, i] ],
[ s[i, j], s[i, i] ]])
xx, yy = plot_cov_ellipse(mu, cov)
axes[i, j].plot(xx, yy, c=colour, alpha=0.2) #003366
# Add reference parameters if given
if ref_parameters is not None:
m, s = ref_parameters
# for xj, yi
mu = np.array([m[j], m[i]])
cov = np.array([[ s[j, j], s[j, i] ],
[ s[i, j], s[i, i] ]])
xx, yy = plot_cov_ellipse(mu, cov)
axes[i, j].plot(xx, yy, '--', c='r', lw=2)
# Set tick labels
if i < n_param - 1:
# Only show x tick labels for the last row
axes[i, j].set_xticklabels([])
else:
# Rotate the x tick labels to fit in the plot
for tl in axes[i, j].get_xticklabels():
tl.set_rotation(30)
if j > 0 and j != i:
# Only show y tick labels for the first column and diagonal
axes[i, j].set_yticklabels([])
# Set axis labels
axes[-1, i].set_xlabel('Parameter %d' % (i + 1))
if i == 0:
# The first one is not a parameter
axes[i, 0].set_ylabel('Frequency')
else:
axes[i, 0].set_ylabel('Parameter %d' % (i + 1))
return fig, axes
def plot_correlation_and_variable_covariance(sample_mean, sample_cov,
samples, corr=False,
ref_parameters=None,
n_percentiles=None,
fig=None, axes=None, colours=None):
# TODO
"""
Take a list of covariance matrix samples and creates a pairwise variable
covariance base on the distribution -- assuming multivariate normal for
now;
TODO: might need to do lognormal case too!
Idea is to see if this can resemble the covariance matrix that used to
create the low-level individual experiments (observations).
`samples`
A list of samples of covariance matrix, with shape
`(n_samples, dimension, dimension)`.
`ref_parameters`
(Optional) A set of parameters for reference in the plot. For example,
if true values of parameters are known, they can be passed in for
plotting. Pass it as [ref_mean, ref_cov].
`n_percentiles`
(Optional) Shows only the middle n-th percentiles of the distribution.
Default shows all samples in `samples`.
Returns a `matplotlib` figure object and axes handle.
"""
# Check samples size
try:
n_sample, n_param, n_param_tmp = sample_cov.shape
except ValueError:
raise ValueError('`samples` must be of shape (n_sample, n_param,'
' n_param)')
# Check dimension
if n_param != n_param_tmp:
raise ValueError('Covariance matrix must be a square matrix')
# Check mean
if sample_mean.shape[0] != n_sample:
print(sample_mean.shape[0], n_sample)
raise ValueError('Number of input means must match input covariance')
if sample_mean.shape[1] != n_param:
raise ValueError('Number of input mean parameters must match input'
' covariance')
# Warning
if n_sample > 1000:
print('WARNING: Large sample size might take long to plot')
# Create figure
if fig is None and axes is None:
fig_size = (3 * n_param, 3 * n_param)
fig, axes = plt.subplots(n_param, n_param, figsize=fig_size)
# Set colour
if colours is None:
colours = ['#1f77b4', '#2ca02c', '#ff7f0e']
else:
assert(len(colours) == 3)
bins = 40
def normal1D(x, mu, sigma):
# normal distribution
output = 1/(sigma * np.sqrt(2 * np.pi)) * \
np.exp( - (x - mu)**2 / (2 * sigma**2) )
return output
for i in range(n_param):
for j in range(n_param):
if i == j:
# Diagonal: Plot a 1D distribution
# 2 sigma covers up 95.5%
xmin = np.min(sample_mean[:, i]) \
- 2.5 * np.max(np.sqrt(sample_cov[:, i, i]))
xmax = np.max(sample_mean[:, i]) \
+ 2.5 * np.max(np.sqrt(sample_cov[:, i, i]))
xx = np.linspace(xmin, xmax, 100)
axes[i, j].set_xlim(xmin, xmax)
for m, s in zip(sample_mean[:, i], sample_cov[:, i, i]):
axes[i, j].plot(xx, normal1D(xx, m, np.sqrt(s)),
c=colours[1], alpha=0.2) #003366
axes[i, j].tick_params('y', colors=colours[1])
# Add reference parameters if given
if ref_parameters is not None:
m, s = ref_parameters[0][i], ref_parameters[1][i, i]
axes[i, j].plot(xx, normal1D(xx, m, np.sqrt(s)),
'--', c='k', lw=2.5)
elif i < j:
if corr and False:
raise NotImplementedError
norm = np.sqrt(samples[:, i, i]) * np.sqrt(samples[:, j, j])
else:
norm = 1.0
samples[:, i, j] = samples[:, i, j] / norm
# Lower-left: Plot a histogram again
if n_percentiles is None:
xmin = np.min(samples[:, i, j])
xmax = np.max(samples[:, i, j])
else:
xmin = np.percentile(samples[:, i, j],
50 - n_percentiles / 2.)
xmax = np.percentile(samples[:, i, j],
50 + n_percentiles / 2.)
xbins = np.linspace(xmin, xmax, bins)
# Set tick and label for y to right
axes[i, j].yaxis.tick_right()
axes[i, j].yaxis.set_label_position("right")
# Only set label for x to top
axes[i, j].xaxis.tick_top()
axes[i, j].xaxis.set_label_position("top")
if corr:
axes[i, j].set_xlim(-1, 1)
else:
axes[i, j].set_xlim(xmin, xmax)
axes[i, j].hist(samples[:, i, j], bins=xbins, normed=True,
color=colours[2])
# Add reference parameters if given
if ref_parameters is None:
ymin_tv, ymax_tv = axes[i, j].get_ylim()
axes[i, j].plot(
[0, 0],
[0.0, ymax_tv],
'--', c='k')
else:
if not corr:
C = np.copy(ref_parameters[1])
else:
D = np.sqrt(np.diag(ref_parameters[1]))
C = ref_parameters[1] / D / D[:, None]
ymin_tv, ymax_tv = axes[i, j].get_ylim()
axes[i, j].plot(
[C[i, j], C[i, j]],
[0.0, ymax_tv],
'--', c='k', lw=2.5)
# Set tick label format
axes[i, j].ticklabel_format(axis='y',
style='sci',
scilimits=(-1,1))
axes[i, j].tick_params('y', colors=colours[2])
if i > 0:
#axes[i, j].tick_params(axis='x', labelbottom='off',
# labeltop='off')
axes[i, j].set_xticklabels([])
axes[i, j].tick_params('x', colors=colours[2], labelsize=20)
axes[i, j].set_xticks([-1.0, 0.0, 1.0])
# Set x, ylabel
if i == int(len(axes)/2) and j == int(len(axes)-1):
axes[i, j].text(1.25, 0.5, 'Frequency', fontsize=38,
ha='left', va='center', rotation=90,
transform=axes[i, j].transAxes,
color=colours[2])
elif i == 0 and j == int(len(axes)/2):
axes[i, j].text(0.5, 1.25, 'Correlation', fontsize=38,
ha='center', va='bottom',
transform=axes[i, j].transAxes,
color=colours[2])
else:
# Lower-left: Plot a bivariate contour of CI
# 2 sigma covers up 95.5%
xmin = np.min(sample_mean[:, j]) \
- 2.5 * np.max(np.sqrt(sample_cov[:, j, j]))
xmax = np.max(sample_mean[:, j]) \
+ 2.5 * np.max(np.sqrt(sample_cov[:, j, j]))
ymin = np.min(sample_mean[:, i]) \
- 2.5 * np.max(np.sqrt(sample_cov[:, i, i]))
ymax = np.max(sample_mean[:, i]) \
+ 2.5 * np.max(np.sqrt(sample_cov[:, i, i]))
axes[i, j].set_xlim(xmin, xmax)
axes[i, j].set_ylim(ymin, ymax)
for m, s in zip(sample_mean, sample_cov):
# for xj, yi
mu = np.array([m[j], m[i]])
cov = np.array([[ s[j, j], s[j, i] ],
[ s[i, j], s[i, i] ]])
xx, yy = plot_cov_ellipse(mu, cov)
axes[i, j].plot(xx, yy, c=colours[0], alpha=0.2) #003366
# Add reference parameters if given
if ref_parameters is not None:
m, s = ref_parameters
# for xj, yi
mu = np.array([m[j], m[i]])
cov = np.array([[ s[j, j], s[j, i] ],
[ s[i, j], s[i, i] ]])
xx, yy = plot_cov_ellipse(mu, cov)
axes[i, j].plot(xx, yy, '--', c='k', lw=2.5)
# Set tick labels
# Only lower triangle
if i < n_param - 1 and i >= j:
# Only show x tick labels for the last row
axes[i, j].set_xticklabels([])
# else:
# # Rotate the x tick labels to fit in the plot
# for tl in axes[i, j].get_xticklabels():
# tl.set_rotation(30)
# Only lower triangle
if j > 0 and j != i and i >= j:
# Only show y tick labels for the first column and diagonal
axes[i, j].set_yticklabels([])
# Set axis labels
axes[-1, i].set_xlabel('Parameter %d' % (i + 1))
if i == 0:
# The first one is not a parameter
axes[i, 0].set_ylabel('Frequency')
else:
axes[i, 0].set_ylabel('Parameter %d' % (i + 1))
return fig, axes
def plot_cov_ellipse(mean, cov, confidence=95):
"""
Take a 2-D array of mean and 2 x 2 matrix covariance and return two x, y
arrays for plotting a ellipse.
`mean`
A 2-D array of mean
`cov`
A 2 x 2 matrix of covariance
`confidence`
The confidence interval (in %) specified by the ellipse
"""
# Calculate the eigenvectors and eigenvalues
W, V = np.linalg.eig(cov) # eigenvalues and eigenvectors
# Get the index of the largest eigenvector
idx_largest_V = np.argmax(W)
largest_V = V[:, idx_largest_V]
largest_W = W[idx_largest_V]
# Get the smallest eigenvector and eigenvalue
smallest_V = V[:, 1 - idx_largest_V]
smallest_W = W[1 - idx_largest_V]
# Calculate the angle between the x-axis and the largest eigenvector
phi = np.arctan2(largest_V[1], largest_V[0])
# Shift angle to between 0 and 2pi
phi = phi + 2.*np.pi if phi < 0 else phi
# Get the 95% confidence interval error ellipse
chisquare = 2.4477 # need to work out a conversion from CI to this
a = chisquare * np.sqrt(largest_W)
b = chisquare * np.sqrt(smallest_W)
# Ellipse in x and y coordinates
theta = np.linspace(0, 2*np.pi, 100)
ellipse_x_r = a * np.cos(theta)
ellipse_y_r = b * np.sin(theta)
# Rotate it
# Checked it is the right direction http://athenasc.com/Bivariate-Normal.pdf
xx = np.cos(phi) * ellipse_x_r - np.sin(phi) * ellipse_y_r
yy = np.sin(phi) * ellipse_x_r + np.cos(phi) * ellipse_y_r
# Rhift it
xx += mean[0]
yy += mean[1]
return xx, yy
def plot_covariance_trace(samples,
ref_parameters=None,
n_percentiles=None):
"""
Take a list of covariance matrix samples and creates a trace plot of the
covariance matrix.
Idea is to see if the list of samples are in steady state.
`samples`
A list of samples of covariance matrix, with shape
`(n_samples, dimension, dimension)`.
`ref_parameters`
(Optional) A set of parameters for reference in the plot. For example,
if true values of parameters are known, they can be passed in for
plotting.
`n_percentiles`
(Optional) Shows only the middle n-th percentiles of the distribution.
Default shows all samples in `samples`.
Returns a `matplotlib` figure object and axes handle.
"""
return None
def plot_posterior_predictive_distribution(samples,
exp_samples=None,
hyper_func=None,
normalise=False,
gx=None,
gx_args=None,
fold=False,
ref_hyper=None,
n_percentiles=None,
mode=None,
fig=None, axes=None, axes2=None):
"""
Plot marginal distributions of the integrated posterior predictive
distribution.
If exp_samples is specified, the posterior predictive distribution will be
plotted on top of the individual distribution of the exp_samples.
`samples'
A list of samples of the hyperparameters. It should have the shape of
(n_type_of_hyperparameters, n_samples, n_hyperparameters).
E.g. [ [list_of_hyper_mean], [list_of_hyper_std] ].
`exp_samples`
(Optional) A list of samples of the individual experiments. It should
have the shape of (n_exp, n_samples, n_params).
E.g. [ [samples_of_exp_1], [samples_of_exp_2], [samples_of_exp_3] ].
`hyper_func`
(Optional) The marginal distribution defined by the hyperparameters.
The first argument takes the index of variable to be marginalised. The
second argument should define the region of output (over that
variable). And it takes *one* sample of the hyperparameters as the
rest of the args. It should return the PDE overall the input region.
If not specified, assume it is multivariate Guassian.
Predefined options:
- `None` or 'normal': normal distribution
- 'log': log-normal distribution
- 'transform-normal': `gx` transformed-normal distribution
`gx`
(Optional) Required for `hyper_func`='hypercube'. The transformation
function from model parameter to hyper unit cube space and its first
derivative: ( g(x), g'(x) )
`gx_args`
(Optional) The arguments for gx, used as gx[i](x, *gx_args[i])
`fold`
(Optional) If True, plot 3 x 3 plot
`ref_hyper`
(Optional) If specified, [mean, stddev], plot reference distribution.
"""
if exp_samples is not None:
'''
try:
import pints.plot
except ImportError:
raise ImportError('To plot individual experiments\' distribution,'
' module pints.plot is required.')
'''
# Plot it!
# fig, axes = pints.plot.histogram(exp_samples)
if fold:
fig, axes = histogram_fold(exp_samples,
normalise=normalise,
n_percentiles=n_percentiles,
mode=mode,
fig=fig, axes=axes)
n_param = 9 # assume Kylie's model...
else:
fig, axes = histogram(exp_samples,
normalise=normalise,
n_percentiles=n_percentiles)
n_param = len(axes)
else:
# Create a figure
n_param = len(samples[0][0])
fig, axes = plt.subplots(n_param, 1, figsize=(8, n_param*2))
# Turn samples to numpy, make indexing easier!
samples = np.array(samples)
# Define the marginal distribution defined by the hyperparameters
if hyper_func == None or hyper_func == 'normal':
def hyper_func(i, x, sample):
# normal distribution
mu = sample[0, i]
sigma = sample[1, i]
output = 1/(sigma * np.sqrt(2 * np.pi)) * \
np.exp( - (x - mu)**2 / (2 * sigma**2) )
return output
elif hyper_func == 'log':
def hyper_func(i, x, sample):
# log-normal distribution
# see my note p.97
mu = sample[0, i]
sigma = sample[1, i]
output = 1/(sigma * np.sqrt(2 * np.pi) * x) * \
np.exp( - (np.log(x) - mu)**2 / (2 * sigma**2) )
return output
elif hyper_func == 'transform-normal':
if gx == None:
raise ValueError('gx is required when hyper_func set to be'
' \'transform-normal\'')
def hyper_func(i, x, sample, gx=gx):
# unit hypercube transformed normal distribution
# see my note p.98
mu = sample[0, i] # in y
sigma = sample[1, i] # in y
y = gx[0](x, i, *gx_args[0])
dydx = gx[1](x, i, *gx_args[1])
output = 1/(sigma * np.sqrt(2 * np.pi)) * \
np.exp( - (y - mu)**2 / (2 * sigma**2) ) * \
dydx
return output
else:
if not callable(hyper_func):
raise ValueError('hyper_func must be callable')
# Estimate where to plot...
xmin, xmax = [], []
if exp_samples is not None and not fold:
for ax in axes:
lim = ax.get_xlim()
xmin.append(lim[0])
xmax.append(lim[1])
elif exp_samples is not None and fold:
for i in range(3):
for j in range(3):
lim = axes[i][j].get_xlim()
xmin.append(lim[0])
xmax.append(lim[1])
else:
mean = np.mean(samples[0, :, :], axis=0)
std = np.std(samples[1, :, :], axis=0)
n_std = 3
for i in range(n_param):
xmin.append(mean[i] - n_std * std[i])
xmax.append(mean[i] + n_std * std[i])
if axes2 is None:
axes2out = []
else:
axes2out = axes2
# Compute marginal distributions of posterior predictive
# may different from n_param because of noise param
n_samples = len(samples[0])
resolution = 250
for i in range(len(samples[0][0])): # number of hyper params
if fold:
ai, aj = int(i/3), i%3
if axes2 is None:
ax_marginal = axes[ai, aj].twinx()
axes2out.append(ax_marginal)
else:
ax_marginal = axes2[i]
else:
if axes2 is None:
ax_marginal = axes[i].twinx()
axes2out.append(ax_marginal)
else:
ax_marginal = axes2[i]
marginal_ppd_i = np.zeros(resolution)
x = np.linspace(xmin[i], xmax[i], resolution)
# integrate marginal distribution
for t in range(n_samples): # number of samples
marginal_ppd_i += hyper_func(i, x, samples[:, t, :])
# normalise it by number of sum
marginal_ppd_i = marginal_ppd_i / n_samples
if mode is None:
ax_marginal.plot(x, marginal_ppd_i,
lw=2, color='#CC0000',
label='Post. pred.')
elif mode == 2:
ax_marginal.plot(x, marginal_ppd_i,
lw=2, ls='--', color='k',
label='Post. pred.')
if ref_hyper is not None:
# plot reference hyper distribution (the one that generate params)
ref_marginal = hyper_func(i, x, ref_hyper)
ax_marginal.plot(x, ref_marginal,
lw=2, ls='--', color='k',
label='True')
ax_marginal.legend(loc=2)
if fold:
ax_marginal.ticklabel_format(axis='y',
style='sci',
scilimits=(-1,1))
if aj == 2 and ai == 1:
ax_marginal.set_ylabel('Probability\ndensity',
color='#CC0000',
fontsize=15)
else:
ax_marginal.set_ylabel('Probability\ndensity', color='#CC0000')
ax_marginal.tick_params('y', colors='#CC0000')
plt.tight_layout()
return [fig, axes2out], axes
def plot_posterior_predictive_distribution_2col(samples,
exp_samples=None,
hyper_func=None,
normalise=False,
gx=None,
gx_args=None,
fold=False,
ref_hyper=None,
n_percentiles=None):
"""
Plot marginal distributions of the integrated posterior predictive
distribution.
Assume giving 10 parameters and plotting in 2x5 plot. And it will move 1st
one to the 9th (plotting g with noise).
If exp_samples is specified, the posterior predictive distribution will be
plotted on top of the individual distribution of the exp_samples.
`samples'
A list of samples of the hyperparameters. It should have the shape of
(n_type_of_hyperparameters, n_samples, n_hyperparameters).
E.g. [ [list_of_hyper_mean], [list_of_hyper_std] ].
`exp_samples`
(Optional) A list of samples of the individual experiments. It should
have the shape of (n_exp, n_samples, n_params).
E.g. [ [samples_of_exp_1], [samples_of_exp_2], [samples_of_exp_3] ].
`hyper_func`
(Optional) The marginal distribution defined by the hyperparameters.
The first argument takes the index of variable to be marginalised. The
second argument should define the region of output (over that
variable). And it takes *one* sample of the hyperparameters as the
rest of the args. It should return the PDE overall the input region.
If not specified, assume it is multivariate Guassian.
Predefined options:
- `None` or 'normal': normal distribution
- 'log': log-normal distribution
- 'transform-normal': `gx` transformed-normal distribution
`gx`
(Optional) Required for `hyper_func`='hypercube'. The transformation
function from model parameter to hyper unit cube space and its first
derivative: ( g(x), g'(x) )
`gx_args`
(Optional) The arguments for gx, used as gx[i](x, *gx_args[i])
`fold`
(Optional) If True, plot 3 x 3 plot
`ref_hyper`
(Optional) If specified, [mean, stddev], plot reference distribution.
"""
if exp_samples is not None:
'''
try:
import pints.plot
except ImportError:
raise ImportError('To plot individual experiments\' distribution,'
' module pints.plot is required.')
'''
# Plot it!
# fig, axes = pints.plot.histogram(exp_samples)
if fold:
fig, axes = histogram_fold_2col(exp_samples,
normalise=normalise,
n_percentiles=n_percentiles)
n_param = 10 # assume Kylie's model...
else:
fig, axes = histogram(exp_samples,
normalise=normalise,
n_percentiles=n_percentiles)
n_param = len(axes)
else:
# Create a figure
n_param = len(samples[0][0])
fig, axes = plt.subplots(n_param, 1, figsize=(8, n_param*2))
# Turn samples to numpy, make indexing easier!
samples = np.array(samples)
# Define the marginal distribution defined by the hyperparameters
if hyper_func == None or hyper_func == 'normal':
def hyper_func(i, x, sample):
# normal distribution
mu = sample[0, i]
sigma = sample[1, i]
output = 1/(sigma * np.sqrt(2 * np.pi)) * \
np.exp( - (x - mu)**2 / (2 * sigma**2) )
return output
elif hyper_func == 'log':
def hyper_func(i, x, sample):
# log-normal distribution
# see my note p.97
mu = sample[0, i]
sigma = sample[1, i]
output = 1/(sigma * np.sqrt(2 * np.pi) * x) * \
np.exp( - (np.log(x) - mu)**2 / (2 * sigma**2) )
return output
elif hyper_func == 'transform-normal':
if gx == None:
raise ValueError('gx is required when hyper_func set to be'
' \'transform-normal\'')
def hyper_func(i, x, sample, gx=gx):
# unit hypercube transformed normal distribution
# see my note p.98
mu = sample[0, i] # in y
sigma = sample[1, i] # in y
y = gx[0](x, i, *gx_args[0])
dydx = gx[1](x, i, *gx_args[1])
output = 1/(sigma * np.sqrt(2 * np.pi)) * \
np.exp( - (y - mu)**2 / (2 * sigma**2) ) * \
dydx
return output
else:
if not callable(hyper_func):
raise ValueError('hyper_func must be callable')
if ref_hyper is not None:
def ref_hyper_func(i, x, ref):
# normal distribution
mu = ref[0, i]
sigma = ref[1, i]
output = 1/(sigma * np.sqrt(2 * np.pi)) * \
np.exp( - (x - mu)**2 / (2 * sigma**2) )
return output
# Estimate where to plot...
xmin, xmax = [], []
if exp_samples is not None and not fold:
for ax in axes:
lim = ax.get_xlim()
xmin.append(lim[0])
xmax.append(lim[1])
elif exp_samples is not None and fold:
for i in range(5):
for j in range(2):
lim = axes[i][j].get_xlim()
xmin.append(lim[0])
xmax.append(lim[1])
else:
mean = np.mean(samples[0, :, :], axis=0)
std = np.std(samples[1, :, :], axis=0)
n_std = 3
for i in range(n_param):
xmin.append(mean[i] - n_std * std[i])
xmax.append(mean[i] + n_std * std[i])
#'''
# Swap order 1st and 9th
xmin[-2], xmin[-1] = xmin[-1], xmin[-2]
xmin = np.roll(xmin, 1)
xmax[-2], xmax[-1] = xmax[-1], xmax[-2]
xmax = np.roll(xmax, 1)
#'''
# Compute marginal distributions of posterior predictive
# may different from n_param because of noise param
n_samples = len(samples[0])
resolution = 250
for i in range(len(samples[0][0])): # number of hyper params
if fold:
# Swap order 1st and 9th
ai, aj = int((i - 1)/2), (i - 1) % 2
if i == 0:
ai, aj = 4, 0
ax_marginal = axes[ai, aj].twinx()
else:
ax_marginal = axes[i].twinx()
marginal_ppd_i = np.zeros(resolution)
x = np.linspace(xmin[i], xmax[i], resolution)
# integrate marginal distribution
for t in range(n_samples): # number of samples
marginal_ppd_i += hyper_func(i, x, samples[:, t, :])
# normalise it by number of sum
marginal_ppd_i = marginal_ppd_i / n_samples
ax_marginal.plot(x, marginal_ppd_i,
lw=2, color='#CC0000',
label='Post. pred.')
if ref_hyper is not None:
# plot reference hyper distribution (the one that generate params)
ref_marginal = ref_hyper_func(i, x, ref_hyper)
ax_marginal.plot(x, ref_marginal,
lw=2, ls='--', color='k',
label='True')
ax_marginal.legend(loc=2)
if fold:
ax_marginal.ticklabel_format(axis='y',
style='sci',
scilimits=(-1,1))
if aj == 1 and ai == 2:
ax_marginal.set_ylabel('Probability\ndensity',
color='#CC0000',
fontsize=16)
else:
ax_marginal.set_ylabel('Probability density', color='#CC0000')
ax_marginal.tick_params('y', colors='#CC0000')
plt.tight_layout()
return fig, axes