In [1]:
import os, tempfile
import logging
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
In [2]:
from ionchannelABC import theoretical_population_size
from ionchannelABC import IonChannelDistance, EfficientMultivariateNormalTransition, IonChannelAcceptor
from ionchannelABC.experiment import setup
from ionchannelABC.visualization import plot_sim_results, plot_kde_matrix_custom
import myokit
In [3]:
from pyabc import Distribution, RV, History, ABCSMC
from pyabc.epsilon import MedianEpsilon
from pyabc.sampler import MulticoreEvalParallelSampler, SingleCoreSampler
from pyabc.populationstrategy import ConstantPopulationSize
In [4]:
from experiments.ical_li import (li_act,
li_inact_1000)
from experiments.ical_sun import sun_inact_kin_slow
In [5]:
modelfile = 'models/courtemanche_ical.mmt'
Plot steady-state and time constant functions of original model
In [6]:
from ionchannelABC.visualization import plot_variables
In [7]:
sns.set_context('poster')
V = np.arange(-140, 50, 0.01)
cou_par_map = {'di': 'ical.d_inf',
'fi': 'ical.f_inf',
'dt': 'ical.tau_d',
'ft': 'ical.tau_f'}
f, ax = plot_variables(V, cou_par_map, 'models/courtemanche_ical.mmt', figshape=(2,2))
Combine model and experiments to produce:
In [8]:
observations, model, summary_statistics = setup(modelfile,
li_act)
In [9]:
assert len(observations)==len(summary_statistics(model({})))
In [10]:
g = plot_sim_results(modelfile,
li_act)
In [12]:
limits = {'ical.p1': (-100, 100),
'ical.p2': (0, 50),
'log_ical.p3': (-7, 3),
'ical.p4': (-100, 100),
'ical.p5': (0, 50)}
prior = Distribution(**{key: RV("uniform", a, b - a)
for key, (a,b) in limits.items()})
In [13]:
# Test this works correctly with set-up functions
assert len(observations) == len(summary_statistics(model(prior.rvs())))
In [14]:
db_path = ("sqlite:///" + os.path.join(tempfile.gettempdir(), "courtemanche_ical_dgate_original.db"))
In [15]:
logging.basicConfig()
abc_logger = logging.getLogger('ABC')
abc_logger.setLevel(logging.DEBUG)
eps_logger = logging.getLogger('Epsilon')
eps_logger.setLevel(logging.DEBUG)
In [16]:
pop_size = theoretical_population_size(2, len(limits))
print("Theoretical minimum population size is {} particles".format(pop_size))
In [17]:
abc = ABCSMC(models=model,
parameter_priors=prior,
distance_function=IonChannelDistance(
exp_id=list(observations.exp_id),
variance=list(observations.variance),
delta=0.05),
population_size=ConstantPopulationSize(2000),
summary_statistics=summary_statistics,
transitions=EfficientMultivariateNormalTransition(),
eps=MedianEpsilon(initial_epsilon=100),
sampler=MulticoreEvalParallelSampler(n_procs=16),
acceptor=IonChannelAcceptor())
In [18]:
obs = observations.to_dict()['y']
obs = {str(k): v for k, v in obs.items()}
In [19]:
abc_id = abc.new(db_path, obs)
In [20]:
history = abc.run(minimum_epsilon=0., max_nr_populations=100, min_acceptance_rate=0.01)
In [17]:
history = History('sqlite:///results/courtemanche/ical/original/courtemanche_ical_dgate_original.db')
In [18]:
df, w = history.get_distribution(m=0)
In [19]:
df.describe()
Out[19]:
In [20]:
sns.set_context('poster')
mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14
g = plot_sim_results(modelfile,
li_act,
df=df, w=w)
plt.tight_layout()
In [21]:
import pandas as pd
N = 100
cou_par_samples = df.sample(n=N, weights=w, replace=True)
cou_par_samples = cou_par_samples.set_index([pd.Index(range(N))])
cou_par_samples = cou_par_samples.to_dict(orient='records')
In [22]:
sns.set_context('talk')
mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14
f, ax = plot_variables(V, cou_par_map,
'models/courtemanche_ical.mmt',
[cou_par_samples],
figshape=(2,2))
plt.tight_layout()
In [23]:
m,_,_ = myokit.load(modelfile)
In [24]:
originals = {}
for name in limits.keys():
if name.startswith("log"):
name_ = name[4:]
else:
name_ = name
val = m.value(name_)
if name.startswith("log"):
val_ = np.log10(val)
else:
val_ = val
originals[name] = val_
In [25]:
sns.set_context('paper')
g = plot_kde_matrix_custom(df, w, limits=limits, refval=originals)
plt.tight_layout()
In [26]:
observations, model, summary_statistics = setup(modelfile,
li_inact_1000,
sun_inact_kin_slow)
In [27]:
assert len(observations)==len(summary_statistics(model({})))
In [28]:
g = plot_sim_results(modelfile,
li_inact_1000,
sun_inact_kin_slow)
In [29]:
limits = {'log_ical.q1': (0, 3),
'log_ical.q2': (-2, 3),
'log_ical.q3': (-4, 0),
'ical.q4': (-100, 100),
'log_ical.q5': (-4, 0),
'ical.q6': (-100, 100),
'ical.q7': (0, 50)}
prior = Distribution(**{key: RV("uniform", a, b - a)
for key, (a,b) in limits.items()})
In [30]:
# Test this works correctly with set-up functions
assert len(observations) == len(summary_statistics(model(prior.rvs())))
In [34]:
db_path = ("sqlite:///" + os.path.join(tempfile.gettempdir(), "courtemanche_ical_fgate_original.db"))
In [35]:
logging.basicConfig()
abc_logger = logging.getLogger('ABC')
abc_logger.setLevel(logging.DEBUG)
eps_logger = logging.getLogger('Epsilon')
eps_logger.setLevel(logging.DEBUG)
In [36]:
pop_size = theoretical_population_size(2, len(limits))
print("Theoretical minimum population size is {} particles".format(pop_size))
In [37]:
abc = ABCSMC(models=model,
parameter_priors=prior,
distance_function=IonChannelDistance(
exp_id=list(observations.exp_id),
variance=list(observations.variance),
delta=0.05),
population_size=ConstantPopulationSize(2000),
summary_statistics=summary_statistics,
transitions=EfficientMultivariateNormalTransition(),
eps=MedianEpsilon(initial_epsilon=100),
sampler=MulticoreEvalParallelSampler(n_procs=16),
acceptor=IonChannelAcceptor())
In [38]:
obs = observations.to_dict()['y']
obs = {str(k): v for k, v in obs.items()}
In [39]:
abc_id = abc.new(db_path, obs)
In [ ]:
history = abc.run(minimum_epsilon=0., max_nr_populations=100, min_acceptance_rate=0.01)
In [31]:
history = History('sqlite:///results/courtemanche/ical/original/courtemanche_ical_fgate_original.db')
In [32]:
history.all_runs()
Out[32]:
In [33]:
df, w = history.get_distribution(m=0)
In [34]:
df.describe()
Out[34]:
In [35]:
sns.set_context('poster')
mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14
g = plot_sim_results(modelfile,
li_inact_1000,
sun_inact_kin_slow,
df=df, w=w)
plt.tight_layout()
In [36]:
m,_,_ = myokit.load(modelfile)
In [37]:
originals = {}
for name in limits.keys():
if name.startswith("log"):
name_ = name[4:]
else:
name_ = name
val = m.value(name_)
if name.startswith("log"):
val_ = np.log10(val)
else:
val_ = val
originals[name] = val_
In [39]:
sns.set_context('paper')
g = plot_kde_matrix_custom(df, w, limits=limits, refval=originals)
plt.tight_layout()
In [40]:
N = 100
cou_par_samples = df.sample(n=N, weights=w, replace=True)
cou_par_samples = cou_par_samples.set_index([pd.Index(range(N))])
cou_par_samples = cou_par_samples.to_dict(orient='records')
In [41]:
sns.set_context('poster')
mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14
f, ax = plot_variables(V, cou_par_map,
'models/courtemanche_ical.mmt',
[cou_par_samples],
figshape=(2,2))
plt.tight_layout()