-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstan_helpers.py
2459 lines (2082 loc) · 102 KB
/
stan_helpers.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
import sys
import os
import os.path
import itertools
import pickle
import re
from collections import OrderedDict
from typing import Tuple, List, Dict, Union, Optional, Callable
import math
import numpy as np
import scipy.integrate
import scipy.stats
import scipy.signal
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression, GammaRegressor, \
HuberRegressor
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_pdf import PdfPages
import arviz as az
import seaborn as sns
from anndata import AnnData
import scanpy as sc
from tqdm import tqdm
from pystan import StanModel
class StanSession:
"""Wrapper for fitting data using pystan.
Attributes:
model_name (str): Name of the Stan model.
model: (StanModel). Compiled Stan model.
output_dir (Union[str, bytes, os.PathLike]): Directory to save pystan
output.
data (Dict, optional): Data to be fit. Defaults to None.
num_chains (int, optional): Number of MCMC chains. Defaults to 4.
num_iters (int, optional): Number of total MCMC iterations. Defaults
to 2000.
warmup (int, optional): Number of warmup iterations. Defaults to 1000.
thin (int, optional): Thinning interval. Defaults to 1.
control (Optional[Dict], optional): Control parameters for NUTS.
Defaults to {}.
rhat_upper_bound (float, optional): Upper bound for R^hat when
determining convergence. Defaults to 1.1.
fit (pystan.StanFit4model): StanFit4model instance from NUTS.
inference_data (arviz.InferenceData): Inference data convereted from
Stan fit instance.
fit_summary: Summary table of Stan fit.
"""
def __init__(self, stan_model_path: Union[str, bytes, os.PathLike],
output_dir: Union[str, bytes, os.PathLike],
data: Dict = None, num_chains: int = 4,
num_iters: int = 2000, warmup: int = 1000, thin: int = 1,
control: Optional[Dict] = None,
rhat_upper_bound: float = 1.1) -> None:
"""
Args:
stan_model_path (Union[str, bytes, os.PathLike]): Path to Stan
model. Can be a Stan model specification or compiled Stan
model.
output_dir (Union[str, bytes, os.PathLike]): Directory to save
pystan output.
data (Dict, optional): Data to be fit. Defaults to None.
num_chains (int, optional): Number of MCMC chains. Defaults to 4.
num_iters (int, optional): Number of total MCMC iterations.
Defaults to 2000.
warmup (int, optional): Number of warmup iterations. Defaults to
1000.
thin (int, optional): Thinning interval. Defaults to 1.
control (Optional[Dict], optional): Control parameters for NUTS.
Defaults to None.
rhat_upper_bound (float, optional): Upper bound for R^hat when
determining convergence. Defaults to 1.1.
"""
# load Stan model
stan_model_filename = os.path.basename(stan_model_path)
self.model_name, model_ext = os.path.splitext(stan_model_filename)
self.output_dir = output_dir
if model_ext == '.stan':
# load model from Stan code
self.model = StanModel(file=stan_model_path,
model_name=self.model_name)
compiled_model_path = os.path.join(self.output_dir,
'stan_model.pkl')
with open(compiled_model_path, 'wb') as f:
pickle.dump(self.model, f)
print('Compiled stan model saved', flush=True)
elif model_ext == '.pkl':
# load saved model
with open(stan_model_path, 'rb') as f:
self.model = pickle.load(f)
print('Compiled stan model loaded', flush=True)
else:
# cannot load given file, exit
print('Unsupported input file', flush=True)
sys.exit(1)
self.data = data
self.num_chains = num_chains
self.num_iters = num_iters
self.warmup = warmup
self.thin = thin
self.control = control if control else {}
self.rhat_upper_bound = rhat_upper_bound
self.fit = None
self.fit_summary = None
self.inference_data = None
def run_sampling(self):
"""Run NUTS sampling.
While sampling, sample (warmup + actual sample) of each chain i is
saved to 'chain_{i}.csv', with a header containing relevant
information. After sampling finished, pystan returns a StanFit4model
object, which is exported to a pickle file. Note that there is no
official support on reloading the pickle file. The StanFit4model is
also converted to an InferenceData object, which is exported to a
netcdf file. The netcdf file can be reloaded.
"""
if 'max_treedepth' not in self.control:
self.control['max_treedepth'] = 10
if 'adapt_delta' not in self.control:
self.control['adapt_delta'] = 0.8
# run sampling
self.fit = self.model.sampling(
data=self.data, chains=self.num_chains, iter=self.num_iters,
warmup=self.warmup, thin=self.thin,
sample_file=os.path.join(self.output_dir, 'chain'),
control=self.control)
print('Stan sampling finished', flush=True)
# save fit object
stan_fit_path = os.path.join(self.output_dir, 'stan_fit.pkl')
with open(stan_fit_path, 'wb') as f:
pickle.dump(self.fit, f)
print('Stan fit object saved', flush=True)
# convert fit object to arviz's inference data
print('Converting Stan fit object to Arviz inference data...',
flush=True)
self.inference_data = az.from_pystan(self.fit)
inference_data_path = os.path.join(self.output_dir, 'arviz_inf_data.nc')
az.to_netcdf(self.inference_data, inference_data_path)
print('Arviz inference data saved', flush=True)
def gather_fit_result(self, verbose: bool = True):
"""Export results from StanFit4model object.
Exported results include
- stan_fit_summary.txt: A summary text from pystan
- stan_fit_summary.csv: A summary table of sample statistics from
pystan
- stan_fit_samples.csv: Samples from all chains in one table
- stan_fit_trace.png: Trace plot of samples from pystan
- stan_fit_posterior.png: Plot of marginal posterior distribution of
each parameter
- stan_fit_pair.png: Pair plots of samples. Note that it does not
show all pairs of parameters due to limit of Arviz.
Args:
verbose (bool, optional): Flag for printing additional information.
Defaults to True.
"""
if verbose:
print('Gathering result from stan fit object...', flush=True)
# get summary of fit
summary_path = os.path.join(self.output_dir, 'stan_fit_summary.txt')
with open(summary_path, 'w') as sf:
sf.write(self.fit.stansummary())
fit_summary = self.fit.summary()
self.fit_summary = pd.DataFrame(
data=fit_summary['summary'],
index=fit_summary['summary_rownames'],
columns=fit_summary['summary_colnames'])
fit_summary_path = os.path.join(self.output_dir, 'stan_fit_summary.csv')
self.fit_summary.to_csv(fit_summary_path)
if verbose:
print('Stan summary saved', flush=True)
# save samples
fit_samples = self.fit.to_dataframe()
fit_samples_path = os.path.join(self.output_dir,
'stan_fit_samples.csv')
fit_samples.to_csv(fit_samples_path)
if verbose:
print('Stan samples saved', flush=True)
# make plots using arviz
# make trace plot
plt.clf()
az.plot_trace(self.inference_data)
trace_figure_path = os.path.join(self.output_dir, 'stan_fit_trace.png')
plt.savefig(trace_figure_path)
plt.close()
if verbose:
print('Trace plot saved', flush=True)
# make plot for posterior
plt.clf()
az.plot_posterior(self.inference_data)
posterior_figure_path = os.path.join(self.output_dir,
'stan_fit_posterior.png')
plt.savefig(posterior_figure_path)
plt.close()
if verbose:
print('Posterior plot saved', flush=True)
# make pair plots
plt.clf()
az.plot_pair(self.inference_data)
pair_figure_path = os.path.join(self.output_dir, 'stan_fit_pair.png')
plt.savefig(pair_figure_path)
plt.close()
if verbose:
print('Pair plot saved', flush=True)
def get_mixed_chains(self) -> Union[List, None]:
"""Get a combination of chains with good R_hat value of log
posteriors.
Returns:
Union[List, None]: Indices of mixed MCMC chains as a list, or None
if no combination of more than 2 chains is mixed.
"""
if 0.9 <= self.fit_summary.loc['lp__', 'Rhat'] <= self.rhat_upper_bound:
return list(range(self.num_chains))
if self.num_chains <= 2:
return None
best_combo = None
best_rhat = np.inf
best_rhat_dist = np.inf
# try remove one bad chain
for chain_combo in itertools.combinations(range(self.num_chains),
self.num_chains - 1):
chain_combo = list(chain_combo)
combo_data = self.inference_data.sel(chain=chain_combo)
combo_stats_rhat = az.rhat(combo_data.sample_stats[['lp']],
method='split')
combo_lp_rhat = combo_stats_rhat['lp'].item()
combo_lp_rhat_dist = np.abs(combo_lp_rhat - 1.0)
if combo_lp_rhat_dist < best_rhat_dist:
best_combo = chain_combo
best_rhat = combo_lp_rhat
best_rhat_dist = combo_lp_rhat_dist
if 0.9 <= best_rhat <= self.rhat_upper_bound:
return best_combo
else:
return None
def run_optimization(self) -> OrderedDict:
"""Run Stan optimization
Returns:
OrderedDict: Optimized parameter values.
"""
optimized_params = self.model.optimizing(data=self.data)
return optimized_params
def run_variational_bayes(self) -> Dict:
"""Run variational Bayes
Note this is an experimental feature as of pystan 2.19
Returns:
Dict: variational Bayes results
"""
sample_path = os.path.join(self.output_dir, 'chain_0.csv')
diagnostic_path = os.path.join(self.output_dir, 'vb_diagnostic.txt')
vb_results = self.model.vb(data=self.data, sample_file=sample_path,
diagnostic_file=diagnostic_path)
return vb_results
class StanSessionAnalyzer:
"""Analyze samples from a Stan sampling/varitional Bayes session
Attributes:
output_dir (Union[str, bytes, os.PathLike]): Directory of Stan
output.
stan_operation (str, optional): Stan operation to perform.
Currently, only 'sampling' is supported Defaults to 'sampling'.
sample_source (str, optional): Source of saved sample file(s).
Supported sources are 'sample_files' (samples of individual
chains in csv), 'fit_export' (exported summary in txt
and samples of all chains in csv)), and 'arviz_inf_data' (
Arviz InferenceData saved as netcdf file). Defaults to
'arviz_inf_data'.
num_chains (int, optional): Number of MCMC chains. Required only
if sample_source is 'sample_files'. Defaults to 4.
warmup (int, optional): Number of warmup iterations. Required only
if sample_source is 'sample_files'. Defaults to 1000.
param_names (Union[None, List[str]], optional): Names of
parameters. If None, a list of default parameter names will be
generated (sigma, theta0, theta1, ...). Defaults to None.
samples (List[pd.DataFrame]): List of posterior samples as pandas
DataFrames.
log_posterior (List): List of log posterior probabilities of each MCMC
chain.
raw_samples: raw samples loaded from sample_source. The type is
different depending on the source.
num_samples (int): Number of MCMC draws in each chain.
num_params (int): Number of parameters in the underlying statistical
model.
"""
def __init__(self, output_dir: Union[str, bytes, os.PathLike],
stan_operation: str = 'sampling',
sample_source: str = 'arviz_inf_data', num_chains: int = 4,
warmup: int = 1000, param_names: Union[None, List[str]] = None,
verbose: bool = False):
"""
Args:
output_dir (Union[str, bytes, os.PathLike]): Directory of Stan
output.
stan_operation (str, optional): Stan operation to perform.
Currently, only 'sampling' is supported Defaults to 'sampling'.
sample_source (str, optional): Source of saved sample file(s).
Supported sources are 'sample_files' (samples of individual
chains in csv), 'fit_export' (exported summary in txt
and samples of all chains in csv)), and 'arviz_inf_data' (
Arviz InferenceData saved as netcdf file). Defaults to
'arviz_inf_data'.
num_chains (int, optional): Number of MCMC chains. Required only
if sample_source is 'sample_files'. Defaults to 4.
warmup (int, optional): Number of warmup iterations. Required only
if sample_source is 'sample_files'. Defaults to 1000.
param_names (Union[None, List[str]], optional): Names of
parameters. If None, a list of default parameter names will be
generated (sigma, theta0, theta1, ...). Defaults to None.
verbose (bool, optional): Flag for printing additional information.
Defaults to False.
"""
self.output_dir = output_dir
self.stan_operation = stan_operation
self.sample_source = sample_source
self.num_chains = num_chains
self.warmup = warmup
self.param_names = param_names
# load sample files
if verbose:
print('Loading stan sample files...', flush=True)
self.samples = []
self.log_posterior = []
if self.sample_source == 'sample_files':
# use sample files generated by stan's sampling function
self.raw_samples = []
for chain_idx in range(self.num_chains):
# get raw samples
sample_path = os.path.join(
self.output_dir, 'chain_{}.csv'.format(chain_idx))
raw_samples = pd.read_csv(sample_path, index_col=False,
comment='#')
raw_samples.set_index(pd.RangeIndex(raw_samples.shape[0]),
inplace=True)
self.raw_samples.append(raw_samples)
# extract sampled parameters
if self.stan_operation == 'sampling':
first_col_idx = 7
else:
first_col_idx = 3
self.samples.append(
raw_samples.iloc[self.warmup:, first_col_idx:])
# get log posterior
self.log_posterior.append(raw_samples.iloc[self.warmup:, 0])
elif self.sample_source == 'fit_export':
# get number of chains and number of warmup iterations from
# stan_fit_summary.txt
summary_path = os.path.join(self.output_dir, 'stan_fit_summary.txt')
with open(summary_path, 'r') as summary_file:
lines = summary_file.readlines()
sampling_params = re.findall(r'\d+', lines[1])
self.num_chains = int(sampling_params[0])
self.warmup = int(sampling_params[2])
# get samples
sample_path = os.path.join(self.output_dir, 'stan_fit_samples.csv')
self.raw_samples = pd.read_csv(sample_path, index_col=0)
self.samples = load_stan_fit_samples(sample_path)
# get log posterior
for chain_idx in range(self.num_chains):
self.log_posterior.append(
self.raw_samples.loc[
self.raw_samples['warmup'] == 0 &
self.raw_samples['chain'] == chain_idx, :])
else: # sample_source == 'arviz_inf_data':
sample_path = os.path.join(self.output_dir, 'arviz_inf_data.nc')
self.raw_samples = az.from_netcdf(sample_path)
self.num_chains = self.raw_samples.sample_stats.dims['chain']
self.samples = load_arviz_inference_data(sample_path)
for chain_idx in range(self.num_chains):
self.log_posterior.append(
self.raw_samples.sample_stats['lp'][chain_idx].values)
self.num_samples = self.samples[0].shape[0]
self.num_params = self.samples[0].shape[1]
# set parameters names
if not param_names or len(param_names) != self.num_params:
self.param_names = ['sigma'] \
+ [f'theta[{i}]' for i in range(self.num_params - 1)]
for samples in self.samples:
samples.columns = self.param_names
def get_sampling_time(self, unit: str = 's') -> np.ndarray:
"""Get computational time for sampling for each MCMC chain.
Args:
unit (str, optional): Unit for time. Options are 's' for seconds,
'm' for minutes, and 'h' for hours. Defaults to 's'.
Returns:
np.ndarray: computational time for each chain.
"""
sampling_time = np.zeros(self.num_chains)
for chain_idx in range(self.num_chains):
sample_file_path = os.path.join(self.output_dir,
f'chain_{chain_idx}.csv')
with open(sample_file_path, 'r') as sf:
time_text = sf.readlines()[-2]
sampling_time[chain_idx] = float(time_text.split()[1])
if unit == 'm':
sampling_time[chain_idx] /= 60
elif unit == 'h':
sampling_time[chain_idx] /= 3600
return sampling_time
def get_tree_depths(self) -> np.ndarray:
"""Get tree depths for each MCMC chain.
Returns:
np.ndarray: tree depth for each chain.
"""
if self.sample_source == 'arviz_inf_data':
inf_data = self.raw_samples
else:
inf_data_path = os.path.join(self.output_dir, 'arviz_inf_data.nc')
inf_data = az.from_netcdf(inf_data_path)
return inf_data.sample_stats['treedepth'].data
def simulate_chains(self, ode: Callable, t0: int, ts: np.ndarray,
y0: np.ndarray, y_ref: Union[None, np.ndarray] = None,
show_progress: bool = False,
var_names: Union[None, List, np.ndarray] = None,
integrator: str = 'dopri5',
subsample_step_size: Union[None, int] = None,
plot: bool = True, verbose: bool = True,
**integrator_params) -> List[np.ndarray]:
"""Simulate trajectories with parameters sampled by all MCMC chains.
Args:
ode (Callable): A Python function that returns $dy/dt$ given $y$,
$t$, and $theta$ (parameter values).
t0 (int): Initial time.
ts (np.ndarray): Time points.
y0 (np.ndarray): Initial values of $y$.
y_ref (Union[None, np.ndarray], optional): Reference values of $y$,
which will be plotted as empty circles if given. Defaults to
None.
show_progress (bool, optional): Flag for showing progress bar while
simulating trajectories. Defaults to False.
var_names (Union[None, List, np.ndarray], optional): Variables
names to be printed on trajectory plots, if not None. Defaults
to None.
integrator (str, optional): ODE integrator to solve the ODE. See
SciPy documentation for valid options. Defaults to 'dopri5'.
subsample_step_size (Union[None, int], optional): Number of draws
to skip in the posterior samples of parameters. Ignored if
None. Defaults to None.
plot (bool, optional): Flag for plotting simulated trajectories.
Defaults to True.
verbose (bool, optional): Flag for printing additional information.
Defaults to True.
**integrator_params: parameters to be passed to the integrator.
Returns:
List[np.ndarray]: Simulated trajectories of all MCMC chains.
"""
num_vars = y0.size
if y_ref is None:
y_ref = [None] * num_vars
if var_names is None:
var_names = [None] * num_vars
y_sim = []
for chain_idx in range(self.num_chains):
# get thetas
thetas = self.samples[chain_idx].to_numpy()[:, 1:]
if subsample_step_size:
thetas = thetas[::subsample_step_size, :]
num_samples = thetas.shape[0]
y = np.zeros((num_samples, ts.size, num_vars))
# simulate trajectory from each samples
if verbose:
print(f'Simulating trajectories from chain {chain_idx}...',
flush=True)
for sample_idx, theta in tqdm(enumerate(thetas), total=num_samples,
disable=not show_progress):
y[sample_idx, :, :] = simulate_trajectory(
ode, theta, t0, ts, y0, integrator=integrator,
**integrator_params)
y_sim.append(y)
if plot:
self._plot_trajectories(chain_idx, ts, y, y_ref, var_names)
return y_sim
def _plot_trajectories(self, chain_idx: int, ts: np.ndarray, y: np.ndarray,
y_ref: np.ndarray,
var_names: Union[List, np.ndarray]):
"""Plot ODE solution (trajectories) for an MCMC chain.
Args:
chain_idx (int): Index of the MCMC chain to be plotted. Only used
for saving the plot.
ts (np.ndarray): Time points
y (np.ndarray): ODE solution the MCMC chain to be plotted.
y_ref (np.ndarray): Reference values for the ODE solution.
var_names (Union[List, np.ndarray]): Variables names to be printed
on trajectory plots.
"""
num_vars = len(y_ref)
plt.clf()
plt.figure(figsize=(num_vars * 4, 4))
for var_idx in range(num_vars):
plt.subplot(1, num_vars, var_idx + 1)
plt.plot(ts, y[:, :, var_idx].T)
if y_ref[var_idx] is not None:
plt.plot(ts, y_ref[var_idx], 'ko', fillstyle='none')
if var_names[var_idx]:
plt.title(var_names[var_idx])
plt.tight_layout()
figure_name = os.path.join(
self.output_dir, 'chain_{}_trajectories.png'.format(chain_idx))
plt.savefig(figure_name)
plt.close()
def get_trajectory_distance(self, ode: Callable, t0: int, ts: np.ndarray,
y0: np.ndarray, y_ref: np.ndarray,
target_var_idx: int,
rhat_upper_bound: float = 4.0,
subsample_step_size: int = 50,
integrator: str = 'dopri5',
**integrator_params) -> np.ndarray:
"""Compute distance between a reference trajectory and trajectories
simulated from subsamples of each MCMC chain.
Only mixed MCMC chains (i.e. chains with $\hat{R}$ under a threshold)
are included when computing the distance.
Args:
ode (Callable): A Python function that returns $dy/dt$ given $y$,
$t$, and $theta$ (parameter values).
t0 (int): Initial time.
ts (np.ndarray): Time points.
y0 (np.ndarray): Initial values of $y$.
y_ref (np.ndarray): Reference values of $y$.
target_var_idx (int): Index of the trajectory in ODE to be compared
to the reference trajectories.
rhat_upper_bound (float, optional): Maximum $\hat{R}$ for mixed
chains. Defaults to 4.0.
subsample_step_size (int, optional): Number of draws to skip in the
posterior samples of parameters. Defaults to 50.
integrator (str, optional): ODE integrator to solve the ODE. See
SciPy documentation for valid options. Defaults to 'dopri5'.
**integrator_params: parameters to be passed to the integrator.
Returns:
np.ndarray: Average distance between the reference trajectory and
simulated trajectories of each MCMC chain.
"""
mixed_samples = self.get_samples(rhat_upper_bound=rhat_upper_bound)
thetas = mixed_samples.to_numpy()[:, 1:]
if subsample_step_size:
thetas = thetas[::subsample_step_size, :]
y_diffs = np.empty(thetas.shape[0])
for i, theta in enumerate(thetas):
y = simulate_trajectory(ode, theta, t0, ts, y0,
integrator=integrator, **integrator_params)
y_diffs[i] = np.linalg.norm(
y[:, target_var_idx] - y_ref[target_var_idx])
return np.mean(y_diffs)
def get_sample_mean_trajectory(self, ode: Callable, t0: int,
ts: np.ndarray, y0: np.ndarray,
rhat_upper_bound: float = 4.0,
integrator: str = 'dopri5',
**integrator_params) -> np.ndarray:
"""Simulate trajectories using posterior mean of parameters for mixed
chains.
Args:
ode (Callable): A Python function that returns $dy/dt$ given $y$,
$t$, and $theta$ (parameter values).
t0 (int): Initial time.
ts (np.ndarray): Time points.
y0 (np.ndarray): Initial values of $y$.
rhat_upper_bound (float, optional): Maximum $\hat{R}$ for mixed
chains. Defaults to 4.0.
integrator (str, optional): . Defaults to 'dopri5'.
Returns:
np.ndarray: Trajectories simulated from posterior mean of
parameters.
"""
sample_means = self.get_sample_means(rhat_upper_bound=rhat_upper_bound)
thetas = sample_means.to_numpy()[1:]
y = simulate_trajectory(ode, thetas, t0, ts, y0, integrator=integrator,
**integrator_params)
return y
def plot_parameters(self):
"""Make plots for sampled parameters of all MCMC chains"""
for chain_idx in range(self.num_chains):
print(f'Making trace plot for chain {chain_idx}...', flush=True)
self._make_trace_plot(chain_idx)
print(f'Making violin plot for chain {chain_idx}...', flush=True)
self._make_violin_plot(chain_idx)
print(f'Making pairs plot for chain {chain_idx}...', flush=True)
self._make_pair_plot(chain_idx)
sys.stderr.flush()
def _make_trace_plot(self, chain_idx):
"""Make trace plots for sampled parameters in an MCMC chain.
Args:
chain_idx (int): Index of the MCMC chain.
"""
samples = self.samples[chain_idx].to_numpy()
plt.clf()
plt.figure(figsize=(6, self.num_params * 2))
# plot trace of each parameter
for idx in range(self.num_params):
plt.subplot(self.num_params, 1, idx + 1)
plt.plot(samples[:, idx])
plt.title(self.param_names[idx])
plt.tight_layout()
# save trace plot
figure_name = os.path.join(
self.output_dir, f'chain_{chain_idx}_parameter_trace.png')
plt.savefig(figure_name)
plt.close()
def _make_violin_plot(self, chain_idx, use_log_scale: bool = True):
"""Make violin plot for sampled parameters in an MCMC chain.
Args:
chain_idx ([type]): Index of the MCMC chain.
use_log_scale (bool, optional): Flag for plotting in log scale.
Defaults to True.
"""
plt.clf()
plt.figure(figsize=(self.num_params, 4))
if use_log_scale:
plt.yscale('log')
plt.violinplot(self.samples[chain_idx].to_numpy())
# add paramter names to ticks on x-axis
param_ticks = np.arange(1, self.num_params + 1)
plt.xticks(param_ticks, self.param_names)
plt.tight_layout()
# save violin plot
figure_name = os.path.join(
self.output_dir, f'chain_{chain_idx}_parameter_violin_plot.png')
plt.savefig(figure_name)
plt.close()
def _make_pair_plot(self, chain_idx):
"""Make pair plots for sampled parameters in an MCMC chain.
Args:
chain_idx (int): Index of the MCMC chain.
"""
plt.clf()
sns.pairplot(self.samples[chain_idx], diag_kind='kde',
plot_kws=dict(alpha=0.4, s=30, color='#191970',
edgecolor='#ffffff', linewidth=0.2),
diag_kws=dict(color='#191970', shade=True))
figure_name = os.path.join(
self.output_dir, f'chain_{chain_idx}_parameter_pair_plot.png')
plt.savefig(figure_name)
plt.close()
def get_r_squared(self):
"""Compute R^2 for all pairs of sampled parameters in each chain.
Computed R^2 is saved to output directory in csv.
"""
for chain_idx in range(self.num_chains):
r_squared = np.ones((self.num_params, self.num_params))
for i, j in itertools.combinations(range(self.num_params), 2):
_, _, r_value, _, _ = scipy.stats.linregress(
self.samples[chain_idx].iloc[:, i],
self.samples[chain_idx].iloc[:, j]
)
r_squared[i, j] = r_squared[j, i] = r_value ** 2
r_squared_df = pd.DataFrame(r_squared, index=self.param_names,
columns=self.param_names)
r_squared_df.to_csv(
os.path.join(self.output_dir,
f'chain_{chain_idx}_r_squared.csv'),
float_format='%.8f'
)
def get_mixed_chains(self, rhat_upper_bound: float = 4.0,
return_rhat: bool = False) -> Union[None, List, Tuple]:
"""Get a combination of chains such that their $\hat{R}$ for log
posteriors is below a threshold.
Args:
rhat_upper_bound (float, optional): Maximum $\hat{R}$ for mixed
chains. Defaults to 4.0.
return_rhat (bool, optional): Return $hat{R}$ along with list of
mixed chains if True. Defaults to False.
Returns:
Union[None, List, Tuple]: If return_rhat is set to False, indices
of mixed chains are returned as a list. Otherwise, $hat{R}$ is
returned along with mixed chains.
"""
if self.num_chains <= 2 or \
not isinstance(self.raw_samples, az.InferenceData):
return None
# check R_hat of all chains together
sample_rhat = az.rhat(self.raw_samples.sample_stats[['lp']],
method='split')
lp_rhat = sample_rhat['lp'].item()
# All chains are mixed, return all chains
if 0.9 <= lp_rhat <= rhat_upper_bound:
all_chains = list(range(self.num_chains))
if return_rhat:
return all_chains, lp_rhat
else:
return all_chains
best_combo = None
best_rhat = np.inf
best_rhat_dist = np.inf
# check if we can remove one bad chain and have others mixed
# if there are multiple combinations of mixed chains, return the one
# with smallest R_hat
for chain_combo in itertools.combinations(range(self.num_chains),
self.num_chains - 1):
chain_combo = list(chain_combo)
combo_data = self.raw_samples.sel(chain=chain_combo)
combo_stats_rhat = az.rhat(combo_data.sample_stats[['lp']],
method='split')
combo_lp_rhat = combo_stats_rhat['lp'].item()
combo_lp_rhat_dist = np.abs(combo_lp_rhat - 1.0)
if combo_lp_rhat_dist < best_rhat_dist:
best_combo = chain_combo
best_rhat = combo_lp_rhat
best_rhat_dist = combo_lp_rhat_dist
if 0.9 <= best_rhat <= rhat_upper_bound:
if return_rhat:
return best_combo, best_rhat
else:
return best_combo
else:
if return_rhat:
return None, None
else:
return None
def get_samples(self, rhat_upper_bound=4.0, excluded_params=None):
"""Get sampled parameters of mixed chains"""
mixed_chains = self.get_mixed_chains(rhat_upper_bound=rhat_upper_bound)
if not mixed_chains:
return None
mixed_samples = pd.concat([self.samples[c] for c in mixed_chains])
if excluded_params is not None:
mixed_samples.drop(labels=excluded_params, axis=1, inplace=True)
return mixed_samples
def get_sample_means(self, rhat_upper_bound: float = 4.0) -> pd.Series:
"""Get means of all sampled parameters in mixed MCMC chains.
Args:
rhat_upper_bound (float, optional): Maximum $\hat{R}$ for mixed
chains. Defaults to 4.0.
Returns:
pd.Series: means of sampled parameters in mixed MCMC chains.
"""
mixed_chains = self.get_mixed_chains(rhat_upper_bound=rhat_upper_bound)
if not mixed_chains:
return None
mixed_samples = pd.concat([self.samples[c] for c in mixed_chains])
sample_means = mixed_samples.mean()
return sample_means
def get_sample_modes(self, method: str = 'kde', bins: int = 100,
rhat_upper_bound: float = 4.0) -> pd.Series:
"""Get modes of all sampled parameters in mixed MCMC chains.
Args:
method (str, optional): Method for estimating posterior mode.
Can be either 'kde' and 'histogram'. Defaults to 'kde'.
bins (int, optional): Number of bins if method is 'histogram'.
Defaults to 100.
rhat_upper_bound (float, optional): Maximum $\hat{R}$ for mixed
chains. Defaults to 4.0.
Returns:
pd.Series: modes of sampled parameters in mixed MCMC chains.
"""
mixed_chains = self.get_mixed_chains(rhat_upper_bound=rhat_upper_bound)
if not mixed_chains:
return None
mixed_samples = pd.concat([self.samples[c] for c in mixed_chains])
sample_modes = pd.Series(index=self.param_names)
for param in self.param_names:
sample_modes[param] = get_mode_continuous_rv(
mixed_samples[param], method=method, bins=bins)
return sample_modes
def get_mean_log_posteriors(self) -> np.ndarray:
"""Get mean of log posterior densities of all MCMC chains.
Returns:
np.ndarray: mean of log posterior densities of length num_chains.
"""
return np.array([np.mean(lp) for lp in self.log_posterior])
def get_log_posteriors(self, include_warmup: bool = True) -> np.ndarray:
"""Get log posterior densities of all MCMC chains.
Args:
include_warmup (bool, optional): Flag for including warmup
iterations in return log posterior densities. Defaults to True.
Returns:
np.ndarray: log posterior densities of all MCMC chains of shape
(num_chains, num_iterations), where num_iterations is either
number of sampling iterations if include_warmup is set to
False, or number of of warmup and sampling iterations
otherwise.
"""
# load sample files
if self.sample_source == 'sample_files':
samples = self.raw_samples
else:
samples = []
for chain_idx in range(self.num_chains):
# get raw samples
sample_path = os.path.join(
self.output_dir, 'chain_{}.csv'.format(chain_idx))
sample = pd.read_csv(sample_path, index_col=False, comment='#')
sample.set_index(pd.RangeIndex(sample.shape[0]), inplace=True)
samples.append(sample)
# remove warmup iterations if specified
if not include_warmup:
for i in range(len(samples)):
samples[i] = samples[i].loc[self.warmup:, :]
lps = np.array([s['lp__'].to_numpy() for s in samples])
return lps
def plot_log_posteriors(self, include_warmup: bool = True):
"""Plot log posterior densities of all MCMC chains.
Each trace in the plot shows log posterior densities of all draws from
one MCMC chain. Warmup iterations are included if specified.
Args:
include_warmup (bool, optional): Flag for including warmup
iterations in return log posterior densities. Defaults to True.
"""
print('Plotting log posterior likelihoods of all chains...', flush=True)
lps = self.get_log_posteriors(include_warmup=include_warmup)
plt.figure(figsize=(6, 4), dpi=300)
plt.plot(lps.T)
plt.ylim((0, np.amax(lps)))
plt.tight_layout()
figure_path = os.path.join(self.output_dir, 'log_posterior_trace.png')
plt.savefig(figure_path)
plt.close()
class StanMultiSessionAnalyzer:
def __init__(self, session_list, output_dir, session_output_dirs,
sample_source='arviz_inf_data', num_chains=4, warmup=1000,
param_names=None, rhat_upper_bound=4.0):
self.output_dir = output_dir
self.full_session_output_dirs = session_output_dirs
self.full_session_list = session_list
self.sample_source = sample_source
self.num_chains = num_chains
self.warmup = warmup
self.param_names = param_names
self.rhat_upper_bound = rhat_upper_bound
# initialize sample analyzers for all cells
self.session_list = []
self.session_out_dirs = []
self.session_analyzers = []
for session_name, output_dir in zip(session_list, session_output_dirs):
analyzer = StanSessionAnalyzer(
output_dir, sample_source=self.sample_source,
num_chains=self.num_chains, warmup=self.warmup,
param_names=self.param_names)
mixed_chains = analyzer.get_mixed_chains(
rhat_upper_bound=rhat_upper_bound)
if mixed_chains is not None:
self.session_list.append(session_name)
self.session_out_dirs.append(output_dir)
self.session_analyzers.append(analyzer)
self.num_sessions = len(self.session_list)
self.session_list = np.array(self.session_list)
# set default parameter names if not given
if self.param_names is None:
self.num_params = self.session_analyzers[0].samples[0].shape[1]
self.param_names = ['sigma'] + \
[f'theta_{i}' for i in range(self.num_params - 1)]
else:
self.num_params = len(param_names)
# make a directory for result
if not os.path.exists(self.output_dir):
os.mkdir(self.output_dir)
def get_sample_means(self):
'''Get sample means for all sessions'''
self.sample_means = pd.DataFrame(columns=self.param_names)
for analyzer in self.session_analyzers:
session_means = analyzer.get_sample_means(