-
Notifications
You must be signed in to change notification settings - Fork 0
/
cell_chain_analysis_extra.py
1182 lines (1042 loc) · 45.5 KB
/
cell_chain_analysis_extra.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 os
import os.path
import itertools
import math
import json
import numpy as np
import scipy.io
import scipy.stats
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from tqdm import tqdm
from stan_helpers import StanSessionAnalyzer, StanMultiSessionAnalyzer, \
load_trajectories, get_trajectory_derivatives, simulate_trajectory, \
get_mode_continuous_rv
import calcium_models
working_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(working_dir)
# %%
# initialize cell chain analysis
# specify a cell chain
# stan_run = '1'
# stan_run = '2'
stan_runs = ['3']
# stan_run = '3-1.0'
# stan_run = '3-2.0'
# stan_run = 'simple-prior'
# stan_run = 'const-eta1'
# stan_run = 'const-Be'
# stan_runs = ['const-Be-eta1']
# stan_run = 'const-Be-eta1-mixed-2'
# stan_runs = [f'const-Be-eta1-mixed-{i}' for i in range(5)]
# stan_run = 'lemon-prior-1000'
# stan_run = 'lemon-prior-500'
# additional flags
list_ranges = [(1, 500)]
# list_ranges = [(1, 100), (1, 100), (1, 100), (1, 100), (1, 100)]
sensitive_params = calcium_models.param_names[2:]
sensitive_params.remove('Be')
sensitive_params.remove('eta1')
pca_sampled_only = False
use_custom_xticks = True
# load metadata
with open('stan_run_meta.json', 'r') as f:
stan_run_meta = json.load(f)
# get parameter names
param_mask = stan_run_meta[stan_runs[0]]['param_mask']
param_names = [calcium_models.param_names[i + 1]
for i, mask in enumerate(param_mask) if mask == "1"]
param_names = ['sigma'] + param_names
num_params = len(param_names)
# get cell list
num_runs = len(stan_runs)
session_list = []
session_dirs = []
unsampled_session_list = []
for run, lr in zip(stan_runs, list_ranges):
run_root = os.path.join('../../result', stan_run_meta[run]['output_dir'])
cell_list_path = os.path.join('cell_lists',
stan_run_meta[run]['cell_list'])
run_cell_list = pd.read_csv(cell_list_path, sep='\t')
sampled_cells = run_cell_list.iloc[lr[0]:lr[1] + 1, 0]
unsampled_cells = run_cell_list.iloc[lr[1] + 1:, 0]
session_list.extend([str(c) for c in sampled_cells])
session_dirs.extend([os.path.join(run_root, 'samples', f'cell-{c:04d}')
for c in sampled_cells])
unsampled_session_list.extend([str(c) for c in unsampled_cells])
# get directories for sampled cells, as well as output of analysis
if num_runs == 1:
output_root = stan_run_meta[stan_runs[0]]['output_dir']
else:
output_root = stan_run_meta[stan_runs[0]]['output_dir'][:-2] + '-all'
output_root = os.path.join('../../result', output_root)
output_dir = 'multi-sample-analysis'
if pca_sampled_only:
output_dir += '-pca-sampled-only'
output_dir = os.path.join(output_root, output_dir)
# load calcium trajectories
ode_variant = stan_run_meta[stan_runs[0]]['ode_variant']
calcium_ode = getattr(calcium_models, f'calcium_ode_{ode_variant}')
t0 = 200
t_downsample = 300
y_all, y0_all, ts = load_trajectories(t0, filter_type='moving_average',
moving_average_window=20, downsample_offset=t_downsample)
y_prime, _ = get_trajectory_derivatives(t0, downsample_offset=t_downsample)
# get similarity matrix
soptsc_vars = scipy.io.loadmat(
'../../result/SoptSC/SoptSC_feature_100/workspace.mat')
similarity_matrix = soptsc_vars['W']
# initialize the analyzer for the cell chain
print('Initializing the analyzer for the cell chain...')
analyzer = StanMultiSessionAnalyzer(session_list, output_dir, session_dirs,
param_names=param_names)
session_list_int = mixed_cells = [int(c) for c in analyzer.session_list]
unsampled_session_list_int = [int(c) for c in unsampled_session_list]
num_mixed_cells = analyzer.num_sessions
# initialize the analyzer for root cell
print('Initializing the analyzer for root cell...')
root_output_dir = os.path.join(
'../../result', stan_run_meta[stan_runs[0]]['root_cell_dir'])
root_analyzer = StanSessionAnalyzer(root_output_dir, param_names=param_names)
# change font settings
matplotlib.rcParams['font.sans-serif'] = ['Arial']
matplotlib.rcParams['font.size'] = 20
# set ticks on x-axis for plots
if use_custom_xticks:
if num_mixed_cells > 50:
num_xticks = int(np.round(num_mixed_cells / 20)) + 1
xtick_locs = np.arange(num_xticks) * 20 - 1
xtick_locs[0] += 1
xtick_labels = xtick_locs + 1
elif num_mixed_cells > 10:
num_xticks = int(np.round(num_mixed_cells / 5)) + 1
xtick_locs = np.arange(num_xticks) * 5
xtick_labels = xtick_locs + 1
else:
num_xticks = num_mixed_cells
xtick_locs = np.arange(num_xticks)
xtick_labels = xtick_locs + 1
xticks = {'ticks': xtick_locs, 'labels': xtick_labels}
else:
xticks = None
# %%
# simulate trajectories using sampled parameters
traj_dir = os.path.join(output_root, 'sampled-trajectories')
if not os.path.exists(traj_dir):
os.mkdir(traj_dir)
figure_paths = []
for i, cell in enumerate(mixed_cells):
cell_fps = []
cell_order = i + 1
for chain in range(analyzer.num_chains):
chain_fp = os.path.join(
traj_dir, f'{cell_order:04d}_cell_{cell}_{chain}.pdf')
cell_fps.append(chain_fp)
figure_paths.append(cell_fps)
y0_run = np.zeros((num_mixed_cells, 4))
y0_run[:, 2] = 0.7
y0_run[:, 3] = y0_all[mixed_cells]
y_run = y_all[mixed_cells, :]
analyzer.simulate_trajectories(calcium_ode, 0, ts, y0_run, y_run, 3,
output_paths=figure_paths)
# %%
from matplotlib.backends.backend_pdf import PdfPages
def plot_trajectories_pdf(y, figure_path, titles=None, num_rows=4, num_cols=2):
num_subplots_per_page = num_rows * num_cols
num_plots = num_mixed_cells
num_pages = math.ceil(num_plots / num_subplots_per_page)
with PdfPages(figure_path) as pdf:
# generate each page
for page in range(num_pages):
# set page size as US letter
plt.figure(figsize=(8.5, 11), dpi=300)
# set number of subplots in current page
if page == num_pages - 1:
num_subplots = (num_plots - 1) % num_subplots_per_page + 1
else:
num_subplots = num_subplots_per_page
# make each subplot
for plot_idx in range(num_subplots):
y_row = page * num_subplots_per_page + plot_idx
plt.subplot(num_rows, num_cols, plot_idx + 1)
plt.plot(ts, y[y_row, :])
if titles:
plt.title(mixed_cells[y_row])
plt.tight_layout()
pdf.savefig()
plt.close()
# %%
# simulate trajectories using Lemon prior
lemon_prior_spec_path = os.path.join('stan_models', ode_variant,
'calcium_model_alt_prior.txt')
lemon_prior_spec = pd.read_csv(lemon_prior_spec_path, delimiter='\t',
index_col=0)
lemon_prior = lemon_prior_spec['mu'].to_numpy()
y_lemon = np.empty((num_mixed_cells, ts.size))
for i, cell in enumerate(mixed_cells):
y_cell = simulate_trajectory(calcium_ode, lemon_prior, 0, ts,
np.array([0, 0, 0.7, y0_all[cell]]))
y_lemon[i, :] = y_cell[:, 3]
lemon_traj_path = os.path.join(
'../../result', 'trajectories',
'dfs_feature_100_root_5106_0.000_1.8_lemon_prior.pdf')
plot_trajectories_pdf(y_lemon, lemon_traj_path, titles=mixed_cells)
# %%
# simulate trajectories using mode
analyzer.get_sample_modes(method='histrogram')
y_mode = np.empty((num_mixed_cells, ts.size))
for i, cell in enumerate(mixed_cells):
thetas = analyzer.sample_modes.iloc[i, 1:].to_numpy()
y_cell = simulate_trajectory(calcium_ode, thetas, 0, ts,
np.array([0, 0, 0.7, y0_all[cell]]))
y_mode[i, :] = y_cell[:, 3]
mode_traj_path = os.path.join(output_dir, 'mode_trajectories.pdf')
plot_trajectories_pdf(y_mode, mode_traj_path, titles=mixed_cells)
# %%
# sensitivity test
use_mode = False
compare_to_sampled_trajs = False
plot_traj = False
sensitivity_dir = 'sensitivity-test'
if compare_to_sampled_trajs:
sensitivity_dir += '-ref-sampled'
if use_mode:
sensitivity_dir += '-mode'
sensitivity_dir = os.path.join(output_root, sensitivity_dir)
if not os.path.exists(sensitivity_dir):
os.mkdir(sensitivity_dir)
# temporarily change output directory
analyzer.output_dir = sensitivity_dir
figure_paths = []
for i, cell in enumerate(mixed_cells):
cell_order = i + 1
figure_paths.append(f'{cell_order:04d}_cell_{cell}')
y0_run = np.zeros((num_mixed_cells, 4))
y0_run[:, 2] = 0.7
y0_run[:, 3] = y0_all[mixed_cells]
y_run = y_all[mixed_cells, :]
if use_mode:
analyzer.run_sensitivity_test(
calcium_ode, 0, ts, y0_run, y_run, 3, sensitive_params,
test_value='mode', plot_traj=plot_traj, figure_size=(5, 3),
plot_legend=False, figure_path_prefixes=figure_paths,
sample_mode_kwargs={'method': 'histogram'})
elif compare_to_sampled_trajs:
analyzer.run_sensitivity_test(
calcium_ode, 0, ts, y0_run, y_run, 3, sensitive_params,
ref_traj_type='sampled', plot_traj=plot_traj, figure_size=(5, 3),
plot_legend=False, figure_path_prefixes=figure_paths)
else:
analyzer.run_sensitivity_test(
calcium_ode, 0, ts, y0_run, y_run, 3, sensitive_params,
plot_traj=plot_traj, figure_size=(5, 3), plot_legend=False,
figure_path_prefixes=figure_paths)
# reset output directory
analyzer.output_dir = output_dir
# %%
# visualize stats from sensitivity test
sensitivity_dir = 'sensitivity-test'
sensitivity_dir = os.path.join(output_root, sensitivity_dir)
sensitivity_stats = {}
test_quantiles = [0.01, 0.99]
for param, qt in itertools.product(sensitive_params, test_quantiles):
stats_path = os.path.join(sensitivity_dir, f'{param}_{qt}_stats.csv')
sensitivity_stats[(param, qt)] = pd.read_csv(stats_path, index_col=0)
# trajectory distances
figure_path = os.path.join(sensitivity_dir, f'{param}_{qt}_traj_dists.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.hist(sensitivity_stats[(param, qt)]['MeanTrajDist'])
plt.savefig(figure_path)
plt.close()
# differences in peak
figure_path = os.path.join(sensitivity_dir, f'{param}_{qt}_peak_diffs.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.hist(sensitivity_stats[(param, qt)]['MeanPeakDiff'])
plt.savefig(figure_path)
plt.close()
# fold changes in peak
figure_path = os.path.join(sensitivity_dir,
f'{param}_{qt}_peak_fold_changes.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.hist(sensitivity_stats[(param, qt)]['MeanPeakFoldChange'])
plt.savefig(figure_path)
plt.close()
# differences in steady state
figure_path = os.path.join(sensitivity_dir,
f'{param}_{qt}_steady_diffs.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.hist(sensitivity_stats[(param, qt)]['MeanSteadyDiff'])
plt.savefig(figure_path)
plt.close()
# differences in steady state
figure_path = os.path.join(sensitivity_dir,
f'{param}_{qt}_steady_fold_changes.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.hist(sensitivity_stats[(param, qt)]['MeanSteadyFoldChange'])
plt.savefig(figure_path)
plt.close()
# %%
# gather stats for trajectory distances from sensitivity test
test_quantiles = [0.01, 0.99]
sensitivity_dist_stats = pd.DataFrame(
columns=['Mean', 'Std', 'Mode', 'Quantile_0.75'])
for param, qt in itertools.product(sensitive_params, test_quantiles):
param_qt = f'{param}_{qt}'
stats_path = os.path.join(sensitivity_dir, f'{param_qt}_stats.csv')
stats = pd.read_csv(stats_path, index_col=0)
mean_traj_dist = stats['MeanTrajDist']
# calculate stats for the param-percentile combo
sensitivity_dist_stats.loc[param_qt, 'Mean'] = mean_traj_dist.mean()
sensitivity_dist_stats.loc[param_qt, 'Std'] = mean_traj_dist.std()
sensitivity_dist_stats.loc[param_qt, 'Mode'] = \
get_mode_continuous_rv(mean_traj_dist, method='histogram')
sensitivity_dist_stats.loc[param_qt, 'Quantile_0.75'] = \
mean_traj_dist.quantile(0.75)
# make a histogram for trajectory distances
figure_path = os.path.join(sensitivity_dir, f'{param_qt}_hist.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.hist(mean_traj_dist, bins=20)
plt.savefig(figure_path)
plt.close()
sensitivity_dist_stats.to_csv(
os.path.join(sensitivity_dir, 'sensitivity_dist_stats.csv'))
# %%
# make a heatmap for modes of trajectory distances
sensitivity_dist_stats = pd.read_csv(
os.path.join(sensitivity_dir, 'sensitivity_dist_stats.csv'), index_col=0)
test_quantiles = [0.01, 0.99]
sensitivity_dist_modes = pd.DataFrame(index=sensitive_params,
columns=test_quantiles, dtype=float)
sensitivity_dist_pct75 = pd.DataFrame(index=sensitive_params,
columns=test_quantiles, dtype=float)
for param, qt in itertools.product(sensitive_params, test_quantiles):
sensitivity_dist_modes.loc[param, qt] = \
sensitivity_dist_stats.loc[f'{param}_{qt}', 'Mode']
sensitivity_dist_pct75.loc[param, qt] = \
sensitivity_dist_stats.loc[f'{param}_{qt}', 'Quantile_0.75']
figure_path = os.path.join(sensitivity_dir,
'sensitivity_dist_modes_heatmap.pdf')
plt.figure(figsize=(7, 10), dpi=300)
ax = plt.gca()
heatmap = ax.imshow(sensitivity_dist_modes, vmin=0)
ax.set_xticks(np.arange(2))
ax.set_xticklabels(test_quantiles)
ax.set_yticks(np.arange(len(sensitive_params)))
ax.set_yticklabels(
[calcium_models.params_on_plot[p] for p in sensitive_params])
# draw text on each block
for i, j in itertools.product(range(len(sensitive_params)), range(2)):
mode = sensitivity_dist_modes.iloc[i, j]
pct75 = sensitivity_dist_pct75.iloc[i, j]
ax.text(j, i, f'{mode:.2f} ({pct75:.2f})', ha='center',
va='center', color='w')
ax.set_aspect(0.3)
ax.set_title("Sensitivity [mode (75%-tile)]", pad=12)
plt.colorbar(heatmap, shrink=0.5)
plt.tight_layout()
plt.savefig(figure_path)
plt.close()
# %%
# make a heatmap for means of trajectory distances
sensitivity_dist_stats = pd.read_csv(
os.path.join(sensitivity_dir, 'sensitivity_dist_stats.csv'), index_col=0)
test_quantiles = [0.01, 0.99]
sensitivity_dist_means = pd.DataFrame(index=sensitive_params,
columns=test_quantiles, dtype=float)
sensitivity_dist_stds = pd.DataFrame(index=sensitive_params,
columns=test_quantiles, dtype=float)
for param, qt in itertools.product(sensitive_params, test_quantiles):
sensitivity_dist_means.loc[param, qt] = \
sensitivity_dist_stats.loc[f'{param}_{qt}', 'Mean']
sensitivity_dist_stds.loc[param, qt] = \
sensitivity_dist_stats.loc[f'{param}_{qt}', 'Std']
sensitivity_dist_means_capped = np.clip(sensitivity_dist_means.values, None, 30)
figure_path = os.path.join(sensitivity_dir,
'sensitivity_dist_means_heatmap.pdf')
plt.figure(figsize=(7, 10), dpi=300)
ax = plt.gca()
heatmap = ax.imshow(sensitivity_dist_means_capped, vmin=0)
ax.set_xticks(np.arange(2))
ax.set_xticklabels(test_quantiles)
ax.set_yticks(np.arange(len(sensitive_params)))
ax.set_yticklabels(
[calcium_models.params_on_plot[p] for p in sensitive_params])
# draw text on each block
for i, j in itertools.product(range(len(sensitive_params)), range(2)):
mean = sensitivity_dist_means.iloc[i, j]
std = sensitivity_dist_stds.iloc[i, j]
mean_str = f'{mean:.2f}' if mean < 10 else f'{mean:.1f}'
std_str = f'{std:.1f}'
ax.text(j, i, f'{mean_str} ± {std_str}', ha='center', va='center',
color='w')
ax.set_aspect(0.3)
ax.set_title("Sensitivity [mean ± std]", pad=12)
cb = plt.colorbar(heatmap, shrink=0.5)
cb.set_ticks([0, 10, 20, 30])
cb.set_ticklabels(['0', '10', '20', '≥30'])
plt.tight_layout()
plt.savefig(figure_path)
plt.close()
# %%
# plot legend for perturbed trajectories in sensitivity test
import matplotlib.patches as mpatches
plt.figure(figsize=(1.8, 4.05), dpi=300)
test_percentiles = np.arange(0.1, 1, 0.1)
jet_cmap = plt.get_cmap('jet')
sensitivity_colors = jet_cmap(test_percentiles)
plt.axis('off')
legend_placeholders = [mpatches.Patch(color=c, label=p)
for c, p in zip(sensitivity_colors, test_percentiles)]
plt.legend(legend_placeholders, [f'{p:.1f}' for p in test_percentiles],
title='Sample\nquantile', loc='upper left',
bbox_to_anchor=(0.0, 0.0))
plt.tight_layout()
figure_path = os.path.join(sensitivity_dir, 'sensitivity_legend.pdf')
plt.savefig(figure_path)
plt.close('all')
# %%
# simulate trajectories using posterior of previous cell
traj_pred_dir = os.path.join(output_root, 'prediction-by-predecessor')
if not os.path.exists(traj_pred_dir):
os.mkdir(traj_pred_dir)
# simulate first cell by root cell
y_sim = root_analyzer.simulate_chains(
calcium_ode, 0, ts, np.array([0, 0, 0.7, y0_all[mixed_cells[0]]]),
subsample_step_size=50, plot=False, verbose=False)
for chain in range(analyzer.num_chains):
figure_path = os.path.join(
traj_pred_dir, f'0001_cell_{mixed_cells[0]}_{chain}.pdf')
fig = Figure(figsize=(3, 2), dpi=300)
ax = fig.gca()
ax.plot(ts, y_all[mixed_cells[0], :], 'ko', fillstyle='none')
ax.plot(ts, y_sim[chain][:, :, 3].T, color='C0', alpha=0.05)
fig.savefig(figure_path)
plt.close(fig)
# simulate all other cells
figure_paths = []
next_cells = mixed_cells[1:]
for i, cell in enumerate(next_cells):
cell_fps = []
cell_order = i + 2
for chain in range(analyzer.num_chains):
chain_fp = os.path.join(
traj_pred_dir, f'{cell_order:04d}_cell_{cell}_{chain}.pdf')
cell_fps.append(chain_fp)
figure_paths.append(cell_fps)
y0_run = np.zeros((num_mixed_cells - 1, 4))
y0_run[:, 2] = 0.7
y0_run[:, 3] = y0_all[next_cells]
y_run = y_all[next_cells, :]
analyzer.simulate_trajectories(calcium_ode, 0, ts, y0_run, y_run, 3,
exclude_sessions=[str(mixed_cells[-1])],
output_paths=figure_paths)
# %%
# plot trajectory from sample mean for sampling vs prediction
for i, cell in enumerate(mixed_cells):
# simulate trajectory using sample mean
y_sample_mean = \
analyzer.session_analyzers[i].get_sample_mean_trajectory(
calcium_ode, 0, ts, np.array([0, 0, 0.7, y0_all[cell]]))
# simulate trajectory using sample mean of previous cell
if i == 0:
y_sample_mean_pred = root_analyzer.get_sample_mean_trajectory(
calcium_ode, 0, ts, np.array([0, 0, 0.7, y0_all[cell]]))
else:
y_sample_mean_pred = \
analyzer.session_analyzers[i - 1].get_sample_mean_trajectory(
calcium_ode, 0, ts, np.array([0, 0, 0.7, y0_all[cell]]))
# plot the trajectories
figure_path = os.path.join(output_root, 'prediction-by-predecessor',
f'{i:04d}_cell_{cell:04d}_vs_sampled.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.plot(ts, y_all[cell, :], label='True')
plt.plot(ts, y_sample_mean[:, 3], label='Sampled')
plt.plot(ts, y_sample_mean_pred[:, 3], label='Predicted')
plt.legend()
plt.savefig(figure_path)
plt.close()
# %%
# get trajectory distances if predicted by sample from predecessors
traj_pred_dists = np.empty(num_mixed_cells)
# root cell
traj_pred_dists[0] = root_analyzer.get_trajectory_distance(
calcium_ode, 0, ts, np.array([0, 0, 0.7, y0_all[mixed_cells[0]]]),
y_all[mixed_cells[0], :], 3)
# all other cells
for i, cell in enumerate(mixed_cells[1:]):
traj_pred_dists[i + 1] = \
analyzer.session_analyzers[i].get_trajectory_distance(
calcium_ode, 0, ts, np.array([0, 0, 0.7, y0_all[cell]]),
y_all[cell, :], 3)
traj_dist_path = os.path.join(output_dir, 'mean_trajectory_distances.csv')
traj_stat_tables = pd.read_csv(traj_dist_path, index_col=0, header=None,
squeeze=True)
# %%
# histogram of distance from predicted to true
figure_path = os.path.join(
output_dir, 'mean_predicted_trajectory_distance.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.hist(traj_pred_dists, bins=25, range=(-50, 50))
plt.savefig(figure_path)
plt.close()
# violin plot for sampled vs predicted
figure_path = os.path.join(
output_dir, 'mean_trajectory_distances_sampled_vs_prediction.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.violinplot([traj_stat_tables, traj_pred_dists])
plt.xticks(ticks=[1, 2], labels=['From posterior', 'From prior'])
plt.savefig(figure_path)
plt.close()
# histogram of sampled vs predicted
traj_dist_diffs = traj_pred_dists - traj_stat_tables
figure_path = os.path.join(
output_dir, 'mean_trajectory_distances_sampled_vs_prediction_diff.pdf')
plt.figure(figsize=(11, 8.5), dpi=300)
plt.hist(traj_dist_diffs, bins=25, range=(-50, 50))
plt.savefig(figure_path)
plt.close()
# %%
def predict_unsampled(num_unsampled, num_sampled, figure_dir,
use_similar_cell=True, sample_marginal=False,
random_seed=0, plot_traj=False):
bit_generator = np.random.MT19937(random_seed)
rng = np.random.default_rng(bit_generator)
unsampled_cells = rng.choice(unsampled_session_list_int,
size=num_unsampled, replace=False)
sampled_cell_list = mixed_cells
traj_stats_table = pd.DataFrame(
index=range(num_unsampled),
columns=['Cell', 'SampledCell', 'Distance', 'PeakDiff',
'PeakFoldChange', 'PeakTimeDiff', 'SteadyDiff',
'SteadyFoldChange', 'DerivativeDist'])
for cell_idx, cell in enumerate(tqdm(unsampled_cells)):
if use_similar_cell:
# find the most similar cell among sampled ones
cells_by_similarity = np.argsort(similarity_matrix[cell, :])[::-1]
sampled_cell = next(c for c in cells_by_similarity
if c != cell and c in sampled_cell_list)
else:
# find a random sampled cell
sampled_cell = rng.choice(sampled_cell_list)
# predict using the selected cell
sampled_cell_order = session_list_int.index(sampled_cell)
sampled_cell_analyzer = analyzer.session_analyzers[sampled_cell_order]
mixed_chains = sampled_cell_analyzer.get_mixed_chains()
y0_cell = np.array([0, 0, 0.7, y0_all[cell]])
y_cell = y_all[cell, :]
if sample_marginal:
# predict by samples from marginal distribution
subsample_size = 10
traj_pred = []
for chain_idx in mixed_chains:
sample = sampled_cell_analyzer.samples[chain_idx]
subsample = np.empty((subsample_size, num_params - 1))
traj_chain = np.empty((subsample_size, ts.size))
# get subsample from marginal distribution for each parameter
for param_idx, param in enumerate(param_names[1:]):
subsample[:, param_idx] = sample[param].sample(
subsample_size, random_state=bit_generator)
# simulate from subsample
for theta_idx, theta in enumerate(subsample):
traj_sample = simulate_trajectory(calcium_ode, theta, 0,
ts, y0_cell)
traj_chain[theta_idx, :] = traj_sample[:, 3]
traj_pred.append(traj_chain)
traj_pred = np.concatenate(traj_pred)
else:
# predict by actual draws from sample
traj_pred = sampled_cell_analyzer.simulate_chains(
calcium_ode, 0, ts, y0_cell, subsample_step_size=50,
plot=False, verbose=False)
traj_pred = np.concatenate(
[traj_pred[c][:, :, 3] for c in mixed_chains])
# plot predicted trajectories
if plot_traj:
figure_name = f'{cell:04d}_{num_sampled}_{sampled_cell:04d}'
if sample_marginal:
figure_name += '_marginal'
figure_name += '.pdf'
figure_path = os.path.join(figure_dir, figure_name)
plt.figure()
plt.plot(ts, traj_pred.T, color='C0')
plt.plot(ts, y_cell, 'ko', fillstyle='none')
plt.savefig(figure_path)
plt.close()
# get stats of predicted trajectories
traj_stats_table.loc[cell_idx, 'Cell'] = cell
traj_stats_table.loc[cell_idx, 'SampledCell'] = sampled_cell
# trajectory distances
traj_dist = np.mean(np.linalg.norm(traj_pred - y_cell, axis=1))
traj_stats_table.loc[cell_idx, 'Distance'] = traj_dist
# peaks
traj_ref_peak = np.amax(y_cell)
traj_pred_peaks = np.amax(traj_pred, axis=1)
traj_peak_diffs = traj_pred_peaks - traj_ref_peak
traj_stats_table.loc[cell_idx, 'PeakDiff'] = np.mean(traj_peak_diffs)
traj_peak_fold_changes = np.log2(traj_pred_peaks / traj_ref_peak)
traj_stats_table.loc[cell_idx, 'PeakFoldChange'] = \
np.mean(traj_peak_fold_changes)
traj_ref_peak_time = np.amax(y_cell[:100])
traj_pred_peak_times = np.amax(traj_pred[:, :100], axis=1)
traj_stats_table.loc[cell_idx, 'PeakTimeDiff'] = \
np.mean(traj_pred_peak_times - traj_ref_peak_time)
# steady states
num_steady_pts = ts.size // 5
traj_ref_steady_state = np.mean(y_cell[-num_steady_pts:])
traj_pred_steady_states = np.mean(traj_pred[:, -num_steady_pts:],
axis=1)
traj_steady_diffs = traj_pred_steady_states - traj_ref_steady_state
traj_stats_table.loc[cell_idx, 'SteadyDiff'] = \
np.mean(traj_steady_diffs)
traj_steady_fold_changes = \
np.log2(traj_pred_steady_states / traj_ref_steady_state)
traj_stats_table.loc[cell_idx, 'SteadyFoldChange'] = \
np.mean(traj_steady_fold_changes)
# L^2 distances between derivatives
traj_prime = np.gradient(traj_pred[:, :100], axis=1)
traj_prime_dist = np.mean(
np.linalg.norm(traj_prime - y_prime[cell, :100], axis=1))
traj_stats_table.loc[cell_idx, 'DerivativeDist'] = traj_prime_dist
return traj_stats_table
# %%
# predict unsampled cells using similar or random cells
rng_seed = 0
num_unsampled = 500
unsampled_pred_dir = os.path.join(
output_root, f'prediction-unsampled-{num_unsampled}-{rng_seed}')
if not os.path.exists(unsampled_pred_dir):
os.mkdir(unsampled_pred_dir)
unsampled_traj_stats = {}
unsampled_traj_stats['similar'] = {}
unsampled_traj_stats['random'] = {}
unsampled_traj_stats['marginal'] = {}
num_sampled_for_prediction = [500, 400, 300, 200, 100]
for n in num_sampled_for_prediction:
unsampled_traj_stats['similar'][n] = predict_unsampled(
num_unsampled, n, unsampled_pred_dir, random_seed=rng_seed)
table_path = os.path.join(unsampled_pred_dir,
f'trajectory_stats_similar_{n}.csv')
unsampled_traj_stats['similar'][n].to_csv(table_path)
unsampled_traj_stats['random'][n] = predict_unsampled(
num_unsampled, n, unsampled_pred_dir, use_similar_cell=False,
random_seed=rng_seed)
table_path = os.path.join(unsampled_pred_dir,
f'trajectory_stats_random_{n}.csv')
unsampled_traj_stats['random'][n].to_csv(table_path)
unsampled_traj_stats['marginal'][n] = predict_unsampled(
num_unsampled, n, unsampled_pred_dir, use_similar_cell=False,
sample_marginal=True, random_seed=rng_seed)
table_path = os.path.join(unsampled_pred_dir,
f'trajectory_stats_marginal_{n}.csv')
unsampled_traj_stats['marginal'][n].to_csv(table_path)
# %%
# predict using lemon prior
def predict_unsampled_lemon(num_unsampled, random_seed=0):
bit_generator = np.random.MT19937(random_seed)
rng = np.random.default_rng(bit_generator)
unsampled_cells = rng.choice(unsampled_session_list_int, size=num_unsampled,
replace=False)
traj_stats_table = pd.DataFrame(
index=range(num_unsampled),
columns=['Cell', 'SampledCell', 'Distance', 'PeakDiff',
'PeakFoldChange', 'SteadyDiff', 'SteadyFoldChange',
'DerivativeDist'])
lemon_prior_spec_path = os.path.join('stan_models', ode_variant,
'calcium_model_alt_prior.txt')
lemon_prior_spec = pd.read_csv(lemon_prior_spec_path, delimiter='\t',
index_col=0)
lemon_prior = lemon_prior_spec['mu'].to_numpy()
for cell_idx, cell in enumerate(tqdm(unsampled_cells)):
traj_pred = simulate_trajectory(calcium_ode, lemon_prior, 0, ts,
np.array([0, 0, 0.7, y0_all[cell]]))
traj_pred = traj_pred[:, 3]
y_cell = y_all[cell, :]
# get stats of predicted trajectories
traj_stats_table.loc[cell_idx, 'Cell'] = cell
traj_stats_table.loc[cell_idx, 'SampledCell'] = 'Lemon'
traj_dist = np.linalg.norm(traj_pred - y_cell)
traj_stats_table.loc[cell_idx, 'Distance'] = traj_dist
# peaks
traj_ref_peak = np.amax(y_cell)
traj_pred_peaks = np.amax(traj_pred)
traj_peak_diffs = traj_pred_peaks - traj_ref_peak
traj_stats_table.loc[cell_idx, 'PeakDiff'] = traj_peak_diffs
traj_peak_fold_changes = traj_pred_peaks / traj_ref_peak
if traj_peak_fold_changes < 1:
traj_peak_fold_changes = -1 / traj_peak_fold_changes
traj_stats_table.loc[cell_idx, 'PeakFoldChange'] = \
traj_peak_fold_changes
# steady states
num_steady_pts = ts.size // 5
traj_ref_steady_state = np.mean(y_cell[-num_steady_pts:])
traj_pred_steady_states = np.mean(traj_pred[-num_steady_pts:])
traj_steady_diffs = traj_pred_steady_states - traj_ref_steady_state
traj_stats_table.loc[cell_idx, 'SteadyDiff'] = traj_steady_diffs
traj_steady_fold_changes = \
traj_pred_steady_states / traj_ref_steady_state
if traj_steady_fold_changes < 1:
traj_steady_fold_changes = -1 / traj_steady_fold_changes
traj_stats_table.loc[cell_idx, 'SteadyFoldChange'] = \
traj_steady_fold_changes
return traj_stats_table
# %%
unsampled_traj_stats['lemon'] = predict_unsampled_lemon(
num_unsampled, random_seed=rng_seed)
table_path = os.path.join(unsampled_pred_dir, 'trajectory_stats_lemon.csv')
unsampled_traj_stats['lemon'].to_csv(table_path)
# %%
# load saved statistics if necessary
rng_seed = 0
num_unsampled = 500
unsampled_pred_dir = os.path.join(
output_root, f'prediction-unsampled-{num_unsampled}-{rng_seed}')
unsampled_traj_stats = {}
unsampled_traj_stats['similar'] = {}
unsampled_traj_stats['random'] = {}
# unsampled_traj_stats['marginal'] = {}
num_sampled_for_prediction = [500]#, 400, 300, 200, 100]
# load distances from 'similar', 'random', 'marginal'
for n in num_sampled_for_prediction:
for method in unsampled_traj_stats:
table_path = os.path.join(unsampled_pred_dir,
f'trajectory_stats_{method}_{n}.csv')
unsampled_traj_stats[method][n] = pd.read_csv(table_path, index_col=0)
# load distances from 'lemon'
table_path = os.path.join(unsampled_pred_dir, 'trajectory_stats_lemon.csv')
unsampled_traj_stats['lemon'] = pd.read_csv(table_path)
# %%
# plot stats for predictions
prediction_methods = list(unsampled_traj_stats.keys())
stats_names = ['Distance', 'PeakDiff', 'PeakFoldChange', 'PeakTimeDiff',
'SteadyDiff', 'SteadyFoldChange', 'DerivativeDist']
stats_fig_names = ['mean_trajectory_distances', 'mean_peak_diffs',
'mean_peak_fold_changes', 'peak_time_diff',
'mean_steady_diffs', 'mean_steady_fold_changes',
'mean_derivative_distances']
stats_xlabels = ['Mean prediction error', 'Mean peak difference',
'Mean peak fold change', 'Man peak time difference',
'Mean steady state difference',
'Mean steady state fold change',
'Mean first derivative distance']
# %%
prediction_stats_summary = {}
for method in prediction_methods[:-1]:
prediction_stats_summary[method] = {}
for n in num_sampled_for_prediction:
prediction_stats_summary[method][n] = pd.DataFrame(
columns=['Mean', 'StdDev', 'Median'], index=stats_names)
for method, traj_stat_tables in unsampled_traj_stats.items():
if method == 'lemon':
# make histogram for prediction stats
for i in range(len(stats_names)):
if stats_names[i] not in ['PeakTimeDiff', 'DerivativeDist']:
figure_path = os.path.join(
unsampled_pred_dir,
f'{stats_fig_names[i]}_prediction_unsampled_lemon.pdf')
plt.figure(figsize=(6, 4), dpi=300)
plt.hist(traj_stat_tables[stats_names[i]], bins=20)
plt.xlabel(stats_xlabels[i])
plt.ylabel('Number of cells')
plt.tight_layout()
plt.savefig(figure_path)
plt.close()
else:
for n in num_sampled_for_prediction:
for i, stat in enumerate(stats_names):
# get summary for prediction stats
prediction_stats_summary[method][n].loc[stat, 'Mean'] = \
traj_stat_tables[n][stat].mean()
prediction_stats_summary[method][n].loc[stat, 'StdDev'] = \
traj_stat_tables[n][stat].std()
prediction_stats_summary[method][n].loc[stat, 'Median'] = \
traj_stat_tables[n][stat].std()
# make histogram for prediction stats
figure_path = os.path.join(
unsampled_pred_dir,
f'{stats_fig_names[i]}_prediction_unsampled_{method}'
+ f'_{n}.pdf')
plt.figure(figsize=(6, 4), dpi=300)
plt.hist(traj_stat_tables[n][stat], bins=20)
plt.xlabel(stats_xlabels[i])
plt.ylabel('Number of cells')
plt.tight_layout()
plt.savefig(figure_path)
plt.close()
# export summary for prediction stats
summary_path = os.path.join(
unsampled_pred_dir, f'stats_summary_{method}_{n}.csv')
prediction_stats_summary[method][n].to_csv(summary_path)
# make histogram of similarity
figure_path = os.path.join(
unsampled_pred_dir, f'unsampled_{method}_similarity_{n}.pdf')
plt.figure(figsize=(6, 4), dpi=300)
similarity = [similarity_matrix[row.Cell, row.SampledCell]
for row in traj_stat_tables[n].itertuples()]
plt.hist(similarity)
plt.tight_layout()
plt.savefig(figure_path)
plt.close()
# %%
# make histogram for multiple stats in the same figure
for n in num_sampled_for_prediction:
for i in range(len(stats_names)):
# plot all methods together
if stats_names[i] not in ['PeakTimeDiff', 'DerivativeDist']:
plt.figure(figsize=(6, 4), dpi=300)
traj_plot_stats = [unsampled_traj_stats[method][n][stats_names[i]]
for method in prediction_methods
if method != 'lemon']
traj_plot_stats = np.vstack(traj_plot_stats)
traj_plot_stats = np.vstack([
traj_plot_stats, unsampled_traj_stats['lemon'][stats_names[i]]])
traj_plot_stats = traj_plot_stats.T
traj_hist_labels = []
for method in prediction_methods:
if method == 'lemon':
traj_hist_labels.append('Lemon value')
else:
traj_hist_labels.append(f'{method.capitalize()} cells')
plt.hist(
traj_plot_stats, bins=10,
label=traj_hist_labels
)
plt.legend(title='Prediction from', fontsize='small')
if stats_names[i] == 'Distance':
plt.xlim((0, 50))
plt.xlabel(stats_xlabels[i])
plt.ylabel('Number of cells')
plt.tight_layout()
figure_path = os.path.join(
unsampled_pred_dir,
f'{stats_fig_names[i]}_prediction_unsampled_{n}.pdf'
)
plt.savefig(figure_path)
plt.close()
# %%
# get K-S stats
from scipy.stats import ks_2samp
stats_names = ['Distance', 'PeakDiff', 'PeakFoldChange', 'PeakTimeDiff',
'SteadyDiff', 'SteadyFoldChange', 'DerivativeDist']
unsampled_stats_ks_stats = {}
ks_alt_hypothesis = 'greater'
for n in num_sampled_for_prediction:
unsampled_stats_ks_stats[n] = pd.DataFrame(columns=['K-S', 'p-value'],
index=stats_names)
for stat in stats_names:
ks, p = ks_2samp(unsampled_traj_stats['similar'][n][stat],
unsampled_traj_stats['random'][n][stat],
alternative=ks_alt_hypothesis)
unsampled_stats_ks_stats[n].loc[stat, 'K-S'] = ks
unsampled_stats_ks_stats[n].loc[stat, 'p-value'] = p
unsampled_stats_ks_stats_path = os.path.join(
unsampled_pred_dir,
f'trajectory_stats_similar_vs_random_{n}_ks_{ks_alt_hypothesis}.csv')
unsampled_stats_ks_stats[n].to_csv(unsampled_stats_ks_stats_path)
# %%
# use multiple cells to predict one cell
rng_seed = 0
num_unsampled = 50
unsampled_pred_dir = os.path.join(
output_root, f'prediction-unsampled-batch-{num_unsampled}-{rng_seed}')
if not os.path.exists(unsampled_pred_dir):
os.mkdir(unsampled_pred_dir)
def predict_unsampled_batch(num_sampled, num_predictions, random_seed=0):
bit_generator = np.random.MT19937(random_seed)
rng = np.random.default_rng(bit_generator)
unsampled_cells = rng.choice(unsampled_session_list, size=num_unsampled,
replace=False)
traj_dist_table = pd.DataFrame(columns=['Cell', 'SampledCell', 'Distance'])
traj_dist_table.astype({'Cell': int, 'SampledCell': int})
sampled_cell_list = rng.choice(mixed_cells, size=num_predictions,
replace=False)
for cell in unsampled_cells:
for sampled_cell in tqdm(sampled_cell_list):
sampled_cell_order = mixed_cells.index(sampled_cell)
sampled_cell_analyzer = analyzer.session_analyzers[
sampled_cell_order]
# plot predicted trajectories
traj_pred = sampled_cell_analyzer.simulate_chains(
calcium_ode, 0, ts, np.array([0, 0, 0.7, y0_all[cell]]),
subsample_step_size=50, plot=False, verbose=False)
mixed_chains = sampled_cell_analyzer.get_mixed_chains()
traj_pred_mixed = np.concatenate(
[traj_pred[c][:, : ,3] for c in mixed_chains])
traj_pred_path = os.path.join(
unsampled_pred_dir,
f'{cell:04d}_{num_sampled}_{sampled_cell:04d}.pdf')
plt.figure()
plt.plot(ts, traj_pred_mixed.T, color='C0')
plt.plot(ts, y_all[cell, :], 'ko', fillstyle='none')
plt.savefig(traj_pred_path)
plt.close()
# get trajectory distances
traj_dist = sampled_cell_analyzer.get_trajectory_distance(
calcium_ode, 0, ts, np.array([0, 0, 0.7, y0_all[cell]]),
y_all[cell, :], 3)
traj_dist_row = {'Cell': cell, 'SampledCell': sampled_cell,
'Distance': traj_dist}