-
Notifications
You must be signed in to change notification settings - Fork 5
/
workflow.py
1802 lines (1503 loc) · 68.9 KB
/
workflow.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
"""Main workflow to generalise electrical models using MCMC.
See example/workflow for an example on how to run it.
TODO: improve docstrings.
"""
# Copyright (c) 2022 EPFL-BBP, All rights reserved.
#
# THIS SOFTWARE IS PROVIDED BY THE BLUE BRAIN PROJECT ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE BLUE BRAIN PROJECT
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# This work is licensed under a Creative Commons Attribution 4.0 International License.
# To view a copy of this license, visit https://creativecommons.org/licenses/by/4.0/legalcode
# or send a letter to Creative Commons, 171
# Second Street, Suite 300, San Francisco, California, 94105, USA.
import itertools
import json
import os
import shutil
from functools import partial
from pathlib import Path
import luigi
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import shap
import yaml
try:
from emodeldb.config_tools import pull_config # pylint: disable=import-error
except ImportError:
pass
from luigi_tools.target import OutputLocalTarget
from luigi_tools.task import WorkflowTask
from luigi_tools.task import WorkflowWrapperTask
from scipy.stats import pearsonr
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import RepeatedKFold
from sklearn.model_selection import RepeatedStratifiedKFold
from tqdm import tqdm
from xgboost import XGBClassifier
from xgboost import XGBRegressor
from emodel_generalisation import ALL_LABELS
from emodel_generalisation.adaptation import adapt_soma_ais
from emodel_generalisation.adaptation import build_all_resistance_models
from emodel_generalisation.adaptation import find_rho_factors
from emodel_generalisation.adaptation import make_evaluation_df
from emodel_generalisation.exemplars import generate_exemplars
from emodel_generalisation.mcmc import filter_features
from emodel_generalisation.mcmc import load_chains
from emodel_generalisation.mcmc import plot_autocorrelation
from emodel_generalisation.mcmc import plot_corner
from emodel_generalisation.mcmc import plot_feature_distributions
from emodel_generalisation.mcmc import plot_full_cost_convergence
from emodel_generalisation.mcmc import plot_reduced_feature_distributions
from emodel_generalisation.mcmc import run_several_chains
from emodel_generalisation.mcmc import save_selected_emodels
from emodel_generalisation.model.evaluation import evaluate_rho
from emodel_generalisation.model.evaluation import evaluate_rho_axon
from emodel_generalisation.model.evaluation import feature_evaluation
from emodel_generalisation.model.modifiers import synth_axon
from emodel_generalisation.model.modifiers import synth_soma
from emodel_generalisation.morph_utils import create_combos_df
from emodel_generalisation.morph_utils import rediametrize
from emodel_generalisation.select import select_valid
from emodel_generalisation.tasks.utils import EmodelAwareTask
from emodel_generalisation.tasks.utils import EmodelLocalTarget
from emodel_generalisation.tasks.utils import ParallelTask
from emodel_generalisation.utils import FEATURE_FILTER
from emodel_generalisation.utils import get_score_df
from emodel_generalisation.utils import plot_traces
from emodel_generalisation.validation import compare_adaptation
from emodel_generalisation.validation import plot_adaptation_summaries
from emodel_generalisation.validation import validate_morphologies
# pylint: disable=too-many-nested-blocks,too-many-lines,too-many-function-args,too-many-branches
class GetEmodelConfig(WorkflowTask):
"""Get config folder with emodel setting via emodeldb (not OS) or locally.
If mode =='local', use 'config_path' for the config folder, and 'mechanisms_path' for the
mechanisms folder to compile, and 'generalisation_rule' with filters for morphologies
generalisation.
"""
emodel = luigi.Parameter()
mode = luigi.ChoiceParameter(default="local", choices=["local", "emodeldb"])
config_path = luigi.Parameter(default="configs")
mechanisms_path = luigi.Parameter(default="mechanisms")
generalisation_rule_path = luigi.Parameter(default="generalisation_rule.yaml")
out_config_path = luigi.Parameter(default="configs")
emodeldb_version = luigi.Parameter(default="proj38")
def run(self):
""" """
if self.mode == "emodeldb":
data = pull_config(
self.emodel, version=self.emodeldb_version, to=self.output().pathlib_path.parent
)
with open(self.output().pathlib_path.parent / "generalisation_rule.yaml", "w") as f:
yaml.dump(data["generalisation"], f)
print("Fetching emodel:", data)
os.popen(f"nrnivmodl {self.output().pathlib_path.parent / 'mechanisms'}").read()
if self.mode == "local":
shutil.copytree(self.config_path, self.output().pathlib_path)
os.popen(f"nrnivmodl {self.mechanisms_path}").read()
shutil.copy(
self.generalisation_rule_path,
self.output().pathlib_path.parent / "generalisation_rule.yaml",
)
def output(self):
""" """
return EmodelLocalTarget(self.out_config_path)
class CreateComboDF(EmodelAwareTask, WorkflowTask):
"""Create dataframe with combos mixing mtype, etype and emodels."""
emodel = luigi.Parameter()
morphology_dataset_path = luigi.Parameter(default="dataset.csv")
combodf_path = luigi.Parameter(default="combo_df.csv")
n_morphs = luigi.IntParameter(default=None)
n_min_per_mtype = luigi.IntParameter(default=10)
def requires(self):
""" """
return GetEmodelConfig(emodel=self.emodel)
def run(self):
""" """
combos_df = create_combos_df(
self.morphology_dataset_path,
self.input().pathlib_path.parent / "generalisation_rule.yaml",
self.emodel,
self.n_min_per_mtype,
self.n_morphs,
)
combos_df.to_csv(self.output().path, index=False)
def output(self):
""" """
return EmodelLocalTarget(self.combodf_path)
class ReDiametrize(WorkflowTask):
"""Rediametrize morphologies with diameter model from exemplar."""
emodel = luigi.Parameter()
morphology_folder = luigi.Parameter(default="rediametrized_morphologies")
rediametrized_combo_df_path = luigi.Parameter(default="rediametrized_combo_df.csv")
diameter_model_path = luigi.Parameter(default="diameter_model.yaml")
mode = luigi.Parameter("simple")
def requires(self):
""" """
return CreateComboDF(emodel=self.emodel)
def run(self):
""" """
combo_df = pd.read_csv(self.input().path)
combo_df = rediametrize(
combo_df,
self.output().pathlib_path.parent,
self.diameter_model_path,
self.morphology_folder,
)
combo_df.to_csv(self.output().path, index=False)
def output(self):
""" """
return EmodelLocalTarget(self.rediametrized_combo_df_path)
class CreateExemplar(WorkflowTask):
"""Create the exemplar morphology for an emodel and a population of morphologies."""
emodel = luigi.Parameter()
exemplar_model_path = luigi.Parameter(default="exemplar_models.yaml")
surface_percentile = luigi.FloatParameter(default=25)
exemplar_path = luigi.Parameter(default=None)
def requires(self):
""" """
return {
"emodel_config": GetEmodelConfig(emodel=self.emodel),
"combodf": ReDiametrize(emodel=self.emodel),
}
def run(self):
""" """
combo_df = pd.read_csv(self.input()["combodf"].path)
exemplar_data = generate_exemplars(
combo_df,
figure_folder=self.output().pathlib_path.parent / "exemplar_figures",
surface_percentile=self.surface_percentile,
)
if self.exemplar_path is not None:
exemplar_data["paths"]["all"] = self.exemplar_path
with open(self.output().path, "w") as f:
yaml.dump(exemplar_data, f)
def output(self):
""" """
return EmodelLocalTarget(self.exemplar_model_path)
class RunMCMCBurnIn(EmodelAwareTask, ParallelTask, WorkflowTask):
"""Run burn-in phase MCMC exploration for an emodel."""
emodel = luigi.Parameter()
mcmc_df_path = luigi.Parameter(default="mcmc_df_burnin.csv")
temperature = luigi.FloatParameter(default=100.0)
n_steps = luigi.IntParameter(default=20)
n_chains = luigi.IntParameter(default=80)
proposal_std = luigi.FloatParameter(default=0.1)
def requires(self):
""" """
return {
"emodel_config": GetEmodelConfig(emodel=self.emodel),
"exemplar": CreateExemplar(emodel=self.emodel),
}
def run(self):
""" """
exemplar_data = yaml.safe_load(self.input()["exemplar"].open())
access_point = self.get_access_point(with_seeds=False)
access_point.morph_path = exemplar_data["paths"]["all"]
access_point.morph_modifiers = [
partial(synth_axon, params=exemplar_data["ais"]["popt"], scale=1.0)
]
access_point.morph_modifiers.insert(
0, partial(synth_soma, params=exemplar_data["soma"], scale=1.0)
)
frozen_params = None
if Path("frozen_parameters.json").exists():
with open("frozen_parameters.json", "r") as f:
frozen_params = json.load(f)
print("Using frozen parameters.")
run_several_chains(
proposal_params={"type": "normal", "std": self.proposal_std},
temperature=self.temperature,
n_steps=self.n_steps,
n_chains=self.n_chains,
access_point=access_point,
emodel=self.emodel,
run_df_path=self.output().path,
results_df_path=self.output().pathlib_path.parent / "chains",
parallel_lib=self.parallel_factory,
random_initial_parameters=True,
mcmc_log_file=self.output().pathlib_path.parent / "mcmc_log.txt",
frozen_params=frozen_params,
)
def complete(self):
""" """
return WorkflowTask.complete(self)
def output(self):
""" """
return EmodelLocalTarget(self.mcmc_df_path)
class RunMCMC(EmodelAwareTask, ParallelTask, WorkflowTask):
"""Run MCMC exploration for an emodel using best emodels from burn-in phase for speed up."""
emodel = luigi.Parameter()
mcmc_df_path = luigi.Parameter(default="mcmc_df.csv")
temperature = luigi.FloatParameter(default=100.0)
n_steps = luigi.IntParameter(default=500)
n_chains = luigi.IntParameter(default=80)
proposal_std = luigi.FloatParameter(default=0.1)
split_perc = luigi.FloatParameter(default=10)
resume = luigi.BoolParameter(default=False)
def requires(self):
""" """
return {
"emodel_config": GetEmodelConfig(emodel=self.emodel),
"exemplar": CreateExemplar(emodel=self.emodel),
"mcmc_burnin": RunMCMCBurnIn(emodel=self.emodel),
}
def run(self):
""" """
exemplar_data = yaml.safe_load(self.input()["exemplar"].open())
if self.resume and not Path(self.output().path).exists():
print("we cannot resume without a previous mcmc run")
self.resume = False
if self.resume:
mcmc_df = load_chains(self.output().path, with_single_origin=False)
ids = [_df.index[-1] for _, _df in mcmc_df.groupby("emodel")]
final_path = self.output().pathlib_path.parent / "final_mcmc_resume.json"
else:
mcmc_df = (
load_chains(self.input()["mcmc_burnin"].path, with_single_origin=False)
.drop_duplicates()
.reset_index(drop=True)
)
ids = mcmc_df.sort_values(by="cost").head(self.n_chains).index
final_path = self.output().pathlib_path.parent / "final_mcmc_burnin.json"
save_selected_emodels(mcmc_df, ids, emodel=self.emodel, final_path=final_path)
access_point = self.get_access_point(final_path=final_path)
access_point.morph_path = exemplar_data["paths"]["all"]
access_point.morph_modifiers = [
partial(synth_axon, params=exemplar_data["ais"]["popt"], scale=1.0)
]
access_point.morph_modifiers.insert(
0, partial(synth_soma, params=exemplar_data["soma"], scale=1.0)
)
frozen_params = None
if Path("frozen_parameters.json").exists():
with open("frozen_parameters.json", "r") as f:
frozen_params = json.load(f)
print("Using frozen parameters.")
run_several_chains(
proposal_params={"type": "normal", "std": self.proposal_std},
temperature=self.temperature,
n_steps=self.n_steps,
n_chains=1,
access_point=access_point,
emodel=None,
run_df_path=self.output().path,
results_df_path=self.output().pathlib_path.parent / "chains",
parallel_lib=self.parallel_factory,
random_initial_parameters=False,
mcmc_log_file=self.output().pathlib_path.parent / "mcmc_log.txt",
chain_df=self.output().path if self.resume else None,
frozen_params=frozen_params,
)
def complete(self):
""" """
if self.resume:
return False
return WorkflowTask.complete(self)
def output(self):
""" """
return EmodelLocalTarget(self.mcmc_df_path)
class PlotMCMCResults(EmodelAwareTask, WorkflowTask):
"""Make various plots of MCMC results."""
emodel = luigi.Parameter()
mcmc_figures_path = luigi.Parameter(default="mcmc_figures")
split = luigi.FloatParameter(default=5)
max_split = luigi.FloatParameter(default=10)
def requires(self):
""" """
return {"mcmc": RunMCMC(emodel=self.emodel), "burnin": RunMCMCBurnIn(emodel=self.emodel)}
def run(self):
""" """
self.output().pathlib_path.mkdir(parents=True)
burnin_mcmc_df = load_chains(self.input()["burnin"].path, with_single_origin=False)
burnin_mcmc_df["cost"] = np.clip(burnin_mcmc_df["cost"], 0, 20)
mcmc_df = pd.read_csv(self.input()["mcmc"].path)
# plot_step_size(mcmc_df, self.output().pathlib_path / "stepsize.pdf")
mcmc_df = load_chains(mcmc_df, with_single_origin=False)
plot_autocorrelation(mcmc_df, filename=self.output().pathlib_path / "autocorrelation.pdf")
access_point = self.get_access_point()
plot_feature_distributions(
mcmc_df[mcmc_df.cost < self.split],
self.emodel,
access_point,
filename=self.output().pathlib_path / "feature_distributions.pdf",
)
_df = filter_features(mcmc_df[mcmc_df.cost < self.split])
plot_reduced_feature_distributions(
_df,
self.emodel,
access_point,
filename=self.output().pathlib_path / "feature_distributions_reduced.pdf",
)
plot_full_cost_convergence(
burnin_mcmc_df,
mcmc_df,
clip=self.max_split,
filename=self.output().pathlib_path / "cost_convergence.pdf",
)
mcmc_df = mcmc_df[mcmc_df.cost < self.max_split].reset_index(drop=True)
# plot the number of emodel for which the given feature is the worst (score=cost)
max_feat = mcmc_df["scores"].idxmax(axis=1).value_counts(ascending=True)
plt.figure(figsize=(7, 9))
max_feat.plot.barh(ax=plt.gca())
plt.xscale("log")
plt.tight_layout()
plt.savefig(self.output().pathlib_path / "worst_features.pdf")
# plot_feature_correlations(
# mcmc_df, self.split, figure_name=self.output().pathlib_path / "feature_corrs.pdf"
# )
# plot_parameter_distributions(
# mcmc_df, self.split, filename=self.output().pathlib_path / "parameters.pdf"
# )
# plot_score_distributions(
# mcmc_df, self.split, filename=self.output().pathlib_path / "scores.pdf"
# )
mcmc_df = mcmc_df[mcmc_df.cost < self.split].reset_index(drop=True)
plot_corner(
mcmc_df.reset_index(drop=True),
feature=None,
filename=self.output().pathlib_path / "corner.pdf",
)
plot_corner(
mcmc_df.reset_index(drop=True),
feature="cost",
filename=self.output().pathlib_path / "corner_cost.pdf",
)
plt.close("all")
# plot corner for each feature starting from the worst
for feature in mcmc_df["scores"].mean(axis=0).sort_values(ascending=False).index:
print("corner plot of ", feature)
plot_corner(
mcmc_df.reset_index(drop=True),
feature=("scores", feature),
filename=self.output().pathlib_path / f"corner_{feature}.pdf",
)
plt.close()
def output(self):
""" """
return EmodelLocalTarget(self.mcmc_figures_path)
class SelectRobustParams(EmodelAwareTask, ParallelTask, WorkflowTask):
"""Select a small set of robust parameters."""
emodel = luigi.Parameter()
split = luigi.FloatParameter(default=5)
robust_emodels_path = luigi.Parameter(default="final.json")
n_emodels = luigi.IntParameter(default=10)
def requires(self):
""" """
return {
"mcmc": RunMCMC(emodel=self.emodel),
"emodel_config": GetEmodelConfig(emodel=self.emodel),
"exemplar": CreateExemplar(emodel=self.emodel),
}
def run(self):
""" """
mcmc_df = load_chains(self.input()["mcmc"].path)
mcmc_df = mcmc_df[mcmc_df.cost < self.split].reset_index(drop=True)
# if we have restarted, we rename emodels to ensure we don't have duplicates
ids = mcmc_df.sample(self.n_emodels, random_state=42).index
for gid in ids:
mcmc_df.loc[gid, "emodel"] = f"{self.emodel}_{gid}"
mcmc_df.loc[ids].to_csv(self.output().pathlib_path.parent / "emodels.csv")
save_selected_emodels(mcmc_df, ids, emodel=self.emodel, final_path=self.output().path)
df = mcmc_df.loc[ids, "normalized_parameters"]
df = df.melt(ignore_index=False)
df["emodel"] = df.index
plt.figure(figsize=(6, 20))
sns.stripplot(data=df, x="value", y="variable", ax=plt.gca())
plt.tight_layout()
plt.savefig(self.output().pathlib_path.parent / "emodel_parameters.pdf")
plt.close()
exemplar_data = yaml.safe_load(self.input()["exemplar"].open())
df_traces = pd.DataFrame()
with open(self.output().path) as f:
emodels = list(json.load(f).keys())
for i, emodel in enumerate(emodels):
df_traces.loc[i, "path"] = exemplar_data["paths"]["all"]
df_traces.loc[i, "name"] = Path(exemplar_data["paths"]["all"]).stem
df_traces.loc[i, "ais_model"] = json.dumps(exemplar_data["ais"])
df_traces.loc[i, "soma_model"] = json.dumps(exemplar_data["soma"])
df_traces.loc[i, "ais_scaler"] = 1.0
df_traces.loc[i, "soma_scaler"] = 1.0
df_traces.loc[i, "emodel"] = emodel
trace_folder = self.output().pathlib_path.parent / "robust_traces"
trace_folder.mkdir(exist_ok=True)
df_traces = feature_evaluation(
df_traces,
self.get_access_point(final_path=self.output().path),
parallel_factory=self.parallel_factory,
trace_data_path=trace_folder,
)
(self.output().pathlib_path.parent / "robust_traces_plots").mkdir(exist_ok=True)
for emodel in df_traces.emodel.unique():
plot_traces(
df_traces[df_traces.emodel == emodel],
trace_path=trace_folder,
pdf_filename=self.output().pathlib_path.parent
/ "robust_traces_plots"
/ f"trace_{emodel}.pdf",
)
def output(self):
""" """
return EmodelLocalTarget(self.robust_emodels_path)
class RhoFactors(EmodelAwareTask, ParallelTask, WorkflowTask):
"""Estimate the target rho value per me-types."""
emodel = luigi.Parameter()
rho_factors_path = luigi.Parameter(default="rhos_factors")
def requires(self):
""" """
return {
"exemplar": CreateExemplar(emodel=self.emodel),
"emodel_parameters": SelectRobustParams(emodel=self.emodel),
}
def run(self):
""" """
self.output().pathlib_path.mkdir(exist_ok=True)
exemplar_data = yaml.safe_load(self.input()["exemplar"].open())
final_path = self.input()["emodel_parameters"].path
with open(final_path) as f:
emodels = json.load(f)
access_point = self.get_access_point(final_path=final_path)
for mtype in exemplar_data["paths"].keys():
if mtype != "all":
print(f"Computing {mtype}")
target_rhos = find_rho_factors(
emodels,
exemplar_data,
mtype,
access_point,
self.parallel_factory,
self.output().pathlib_path.parent,
)
with open(self.output().pathlib_path / f"rho_factors_{mtype}.yaml", "w") as f:
yaml.dump(target_rhos, f)
def output(self):
""" """
return EmodelLocalTarget(self.rho_factors_path)
class ResistanceModels(EmodelAwareTask, WorkflowTask):
"""Constructs the AIS/soma input resistance models."""
emodel = luigi.Parameter()
resistance_model_path = luigi.Parameter(default="resistance_model.yaml")
scale_min = luigi.FloatParameter(default=-1.0)
scale_max = luigi.FloatParameter(default=1.0)
scale_n = luigi.IntParameter(default=20)
scale_lin = luigi.BoolParameter(default=False)
def requires(self):
""" """
return {
"emodel_config": GetEmodelConfig(emodel=self.emodel),
"exemplar": CreateExemplar(emodel=self.emodel),
"emodel_parameters": SelectRobustParams(emodel=self.emodel),
}
def run(self):
""" """
exemplar_data = yaml.safe_load(self.input()["exemplar"].open())
final_path = self.input()["emodel_parameters"].path
final_path = self.input()["emodel_parameters"].path
with open(final_path) as f:
emodels = json.load(f)
scales_params = {
"min": self.scale_min,
"max": self.scale_max,
"n": self.scale_n,
"lin": self.scale_lin,
}
access_point = self.get_access_point(final_path=final_path)
models = build_all_resistance_models(
access_point, emodels, exemplar_data, scales_params, self.output().pathlib_path.parent
)
with self.output().open("w") as f:
yaml.dump(models, f)
def output(self):
""" """
return EmodelLocalTarget(self.resistance_model_path)
class AdaptAisSoma(EmodelAwareTask, ParallelTask, WorkflowTask):
"""Adapt AIS and Soma."""
emodel = luigi.Parameter()
n_steps = luigi.IntParameter(default=2)
with_soma = luigi.BoolParameter(default=True)
adapted_ais_soma_path = luigi.Parameter("adapted_soma_ais.csv")
min_scale = luigi.FloatParameter(default=0.01)
max_scale = luigi.FloatParameter(default=10.0)
def requires(self):
""" """
return {
"resistance": ResistanceModels(emodel=self.emodel),
"combodb": ReDiametrize(emodel=self.emodel),
"emodel_parameters": SelectRobustParams(emodel=self.emodel),
"rhos": RhoFactors(emodel=self.emodel),
"exemplar": CreateExemplar(emodel=self.emodel),
}
def run(self):
""" """
resistance_models = yaml.safe_load(self.input()["resistance"].open())
exemplar_data = yaml.safe_load(self.input()["exemplar"].open())
final_path = self.input()["emodel_parameters"].path
emodels = list(resistance_models["ais"].keys())
combos_df = pd.read_csv(self.input()["combodb"].path)
dfs = []
for mtype in exemplar_data["paths"].keys():
if mtype != "all":
print(f"Computing {mtype}")
with open(self.input()["rhos"].pathlib_path / f"rho_factors_{mtype}.yaml") as f:
rhos = yaml.safe_load(f)
df = make_evaluation_df(
combos_df[combos_df.mtype == mtype], emodels, exemplar_data, rhos
)
df = adapt_soma_ais(
df,
access_point=self.get_access_point(final_path=final_path),
models=resistance_models,
rhos=rhos,
parallel_factory=self.parallel_factory,
n_steps=self.n_steps,
min_scale=self.min_scale,
max_scale=self.max_scale,
)
df = evaluate_rho_axon(
df,
self.get_access_point(final_path=final_path),
parallel_factory=self.parallel_factory,
)
df = evaluate_rho(
df,
self.get_access_point(final_path=final_path),
parallel_factory=self.parallel_factory,
)
dfs.append(df)
pd.concat(dfs).to_csv(self.output().path, index=False)
def output(self):
""" """
return EmodelLocalTarget(self.adapted_ais_soma_path)
def _get_shap_feature_importance(shap_values):
"""From a list of shap values per folds, compute the global shap feature importance."""
# average across folds
mean_shap_values = np.mean(shap_values, axis=0)
# average across labels
if len(np.shape(mean_shap_values)) > 2:
global_mean_shap_values = np.mean(mean_shap_values, axis=0)
mean_shap_values = list(mean_shap_values)
else:
global_mean_shap_values = mean_shap_values
# average across graphs
shap_feature_importance = np.mean(abs(global_mean_shap_values), axis=0)
return mean_shap_values, shap_feature_importance
class CreateMLRhoModels(WorkflowTask):
"""Create xgboost model of rhos factos as function of emodel parameter."""
emodel = luigi.Parameter()
rho_models_path = luigi.Parameter(default="rho_models")
n_splits = luigi.IntParameter(default=10)
n_repeats = luigi.IntParameter(default=5)
def requires(self):
""" """
return {
"emodel_parameters": SelectRobustParams(emodel=self.emodel),
"rhos": RhoFactors(emodel=self.emodel),
"exemplar": CreateExemplar(emodel=self.emodel),
}
def run(self):
""" """
self.output().pathlib_path.mkdir(exist_ok=True)
emodels_df = pd.read_csv(
self.input()["emodel_parameters"].pathlib_path.parent / "emodels.csv",
header=[0, 1],
index_col=0,
)
emodels_df = emodels_df.set_index(("emodel", emodels_df["emodel"].columns[0]))
exemplar_data = yaml.safe_load(self.input()["exemplar"].open())
for mtype in exemplar_data["paths"].keys():
if mtype != "all":
with open(self.input()["rhos"].pathlib_path / f"rho_factors_{mtype}.yaml") as f:
rhos = yaml.safe_load(f)
param_bounds = {"rho": {}, "rho_axon": {}}
for rho in ["rho", "rho_axon"]:
emodels = list(rhos[rho].keys())
df = emodels_df.loc[emodels]["normalized_parameters"]
df.loc[emodels, rho] = list(rhos[rho].values())
y = df[rho]
X = df.drop(columns=[rho])
params = []
for col in sorted(X.columns):
x = X[col]
p = pearsonr(x, y)[0]
if abs(p) > 0.4:
param_bounds[rho][col] = [
float(np.percentile(X[col], 10)),
float(np.percentile(X[col], 90)),
]
params.append(col)
plt.figure(figsize=(4, 2.5))
plt.scatter(x, y)
plt.axvline(param_bounds[rho][col][0])
plt.axvline(param_bounds[rho][col][1])
plt.xlabel(ALL_LABELS[col])
plt.ylabel(rho)
plt.tight_layout()
plt.savefig(
self.output().pathlib_path / f"corr_{mtype}_{rho}_{col}.pdf"
)
plt.close()
if not param_bounds[rho]:
param_bounds[rho] = float(y.mean())
else:
X = X[params]
model = XGBRegressor(learning_rate=0.1)
folds = RepeatedKFold(
n_splits=self.n_splits, n_repeats=self.n_repeats, random_state=42
)
acc_scores = []
shap_values = []
for indices in tqdm(
folds.split(X, y=y), total=self.n_splits * self.n_repeats
):
train_index, val_index = indices
model.fit(X.iloc[train_index], y.iloc[train_index])
acc_score = mean_absolute_error(
y.iloc[val_index], model.predict(X.iloc[val_index])
)
acc_scores.append(acc_score)
explainer = shap.TreeExplainer(model)
shap_value = explainer.shap_values(X)
shap_values.append(shap_value)
with open(self.output().pathlib_path / f"scores_{mtype}.txt", "a") as f:
print(rho, np.mean(acc_scores), np.std(acc_scores), file=f)
model.fit(X, y)
model.save_model(self.output().pathlib_path / f"model_{mtype}_{rho}.json")
shap_val, _ = _get_shap_feature_importance(shap_values)
X.columns = [ALL_LABELS.get(col, col) for col in X.columns]
shap.summary_plot(
shap_val,
X,
plot_type="bar",
max_display=5,
show=False,
plot_size=(5, 5),
)
plt.tight_layout()
plt.savefig(self.output().pathlib_path / f"bar_shap_{mtype}_{rho}.pdf")
plt.close()
shap.summary_plot(
shap_val,
X,
plot_type="dot",
max_display=5,
show=False,
color_bar_label="parameter value",
plot_size=(5, 3),
)
plt.tight_layout()
plt.savefig(self.output().pathlib_path / f"dot_shap_{mtype}_{rho}.pdf")
plt.close()
with open(self.output().pathlib_path / f"param_bounds_{mtype}.yaml", "w") as f:
yaml.dump(param_bounds, f)
def output(self):
""" """
return EmodelLocalTarget(self.rho_models_path)
class CreateMLGeneralisationModels(WorkflowTask):
"""Create an xgboost model for generalisable emodels."""
emodel = luigi.Parameter()
generalisation_models_path = luigi.Parameter(default="generalisation_models")
n_splits = luigi.IntParameter(default=10)
n_repeats = luigi.IntParameter(default=5)
def requires(self):
""" """
return {
"selected": SelectValidParameters(emodel=self.emodel),
"emodel_parameters": SelectRobustParams(emodel=self.emodel),
"exemplar": CreateExemplar(emodel=self.emodel),
"evaluate": Evaluate(emodel=self.emodel),
}
def run(self):
""" """
self.output().pathlib_path.mkdir(exist_ok=True)
df_emodel = pd.read_csv(
self.input()["emodel_parameters"].pathlib_path.parent / "emodels.csv",
header=[0, 1],
index_col=0,
)
params = [
"gNaTgbar_NaTg.axonal",
"gIhbar_Ih.somadend",
"g_pas.all",
"decay_CaDynamics_DC0.somatic",
]
exemplar_data = yaml.safe_load(self.input()["exemplar"].open())
for mtype in exemplar_data["paths"].keys():
if mtype != "all":
with open(self.input()["selected"].pathlib_path / f"selected_{mtype}.yaml") as f:
selected = yaml.safe_load(f)
y = df_emodel["emodel"].isin(selected["emodels"]).astype(int)
X = df_emodel["normalized_parameters"]
# X = X[params]
plt.figure(figsize=(5, 3))
ps = df_emodel["parameters"]
plt.scatter(ps[params[0]], ps[params[1]], c=ps[params[2]], label="good", marker="o")
plt.colorbar(label=ALL_LABELS[params[2]], shrink=0.8)
_ps = ps[y.to_numpy()[:, 0] < 1]
plt.scatter(_ps[params[0]], _ps[params[1]], label="bad", marker="+", c="r")
plt.xlabel(ALL_LABELS[params[0]])
plt.ylabel(ALL_LABELS[params[1]])
plt.tight_layout()
plt.savefig(self.output().pathlib_path / f"{mtype}.pdf")
plt.close()
model = XGBClassifier(learning_rate=0.1)
folds = RepeatedStratifiedKFold(
n_splits=self.n_splits, n_repeats=self.n_repeats, random_state=42
)
acc_scores = []
shap_values = []
for indices in tqdm(folds.split(X, y=y), total=self.n_splits * self.n_repeats):
train_index, val_index = indices
model.fit(X.iloc[train_index], y.iloc[train_index])
acc_score = accuracy_score(y.iloc[val_index], model.predict(X.iloc[val_index]))
acc_scores.append(acc_score)
explainer = shap.TreeExplainer(model)
shap_value = explainer.shap_values(X, tree_limit=model.best_ntree_limit)
shap_values.append(shap_value)
with open(self.output().pathlib_path / f"scores_{mtype}.txt", "a") as f:
print(np.mean(acc_scores), np.std(acc_scores), file=f)
model.fit(X, y)
model.save_model(self.output().pathlib_path / f"model_{mtype}.json")
shap_val, _ = _get_shap_feature_importance(shap_values)
shap.summary_plot(shap_val, X, plot_type="bar", max_display=20, show=False)
plt.savefig(self.output().pathlib_path / f"bar_shap_{mtype}.pdf")
plt.close()
X.columns = [ALL_LABELS.get(col, col) for col in X.columns]
shap.summary_plot(
shap_val,
X,
plot_type="dot",
max_display=10,
show=False,
color_bar_label="parameter value",
plot_size=(7, 4),
)
plt.tight_layout()
plt.savefig(self.output().pathlib_path / f"dot_shap_{mtype}.pdf")
plt.close()
def output(self):
""" """
return EmodelLocalTarget(self.generalisation_models_path)
class CreateMLResistanceModels(WorkflowTask):
"""Create xgboost models of resistance parameter fits."""
emodel = luigi.Parameter()
resistance_models_path = luigi.Parameter(default="resistance_models")
n_splits = luigi.IntParameter(default=10)
n_repeats = luigi.IntParameter(default=5)
def requires(self):
""" """
return {
"emodel_parameters": SelectRobustParams(emodel=self.emodel),
"resistance": ResistanceModels(emodel=self.emodel),
}
def run(self):
""" """
self.output().pathlib_path.mkdir(exist_ok=True)
resistance_models = yaml.safe_load(self.input()["resistance"].open())
df_emodel = pd.read_csv(
self.input()["emodel_parameters"].pathlib_path.parent / "emodels.csv",
header=[0, 1],
index_col=0,
)
df_emodel = df_emodel.set_index(("emodel", df_emodel["emodel"].columns[0]))
param_bounds = {"ais": {}, "soma": {}}
for tpe in ["ais", "soma"]:
emodels = list(resistance_models[tpe].keys())
X = df_emodel.loc[emodels, "normalized_parameters"]
for val_id in range(4):
y = []
for emodel in emodels:
y.append(resistance_models[tpe][emodel]["resistance"]["polyfit_params"][val_id])
params = []
param_bounds[tpe][val_id] = {}
for col in df_emodel["normalized_parameters"].columns:
x = df_emodel.loc[emodels, ("normalized_parameters", col)]
p = pearsonr(x, y)[0]
if abs(p) > 0.7:
param_bounds[tpe][val_id][col] = [
float(np.percentile(X[col], 10)),
float(np.percentile(X[col], 90)),
]
params.append(col)
plt.figure(figsize=(5, 3))