Create and test ion channel model


In [1]:
from experiments.icat_markov import (nguyen_iv,
                                     nguyen_inact,
                                     deng_rec)


INFO:myokit:Loading Myokit version 1.28.3

In [2]:
from ionchannelABC.experiment import setup

In [3]:
modelfile = 'models/icat_markov.mmt'

In [4]:
observations, model, summary_statistics = setup(modelfile,
                                                nguyen_iv,
                                                nguyen_inact,
                                                deng_rec)

In [5]:
assert(len(observations)==len(summary_statistics(model({}))))

Set limits and generate uniform initial priors


In [6]:
from pyabc import Distribution, RV
limits = {'icat.g_CaT': (0., 2.),
          'icat.E_Ca_offset': (0., 200.),
          'log_icat.p_1': (-7., 3.),
          'icat.p_2': (1e-7, 0.4),
          'log_icat.p_3': (-7., 3.),
          'icat.p_4': (1e-7, 0.4),
          'log_icat.p_5': (-7., 3.),
          'icat.p_6': (1e-7, 0.4),
          'log_icat.p_7': (-7., 3.),
          'icat.p_8': (1e-7, 0.4)}
prior = Distribution(**{key: RV("uniform", a, b - a)
                        for key, (a,b) in limits.items()})

Run ABC calibration


In [7]:
import os, tempfile
db_path = ("sqlite:///" +
           os.path.join(tempfile.gettempdir(), "hl1_icat.db"))

In [8]:
# Let's log all the sh!t
import logging
logging.basicConfig()
abc_logger = logging.getLogger('ABC')
abc_logger.setLevel(logging.DEBUG)
eps_logger = logging.getLogger('Epsilon')
eps_logger.setLevel(logging.DEBUG)

In [9]:
from pyabc.populationstrategy import AdaptivePopulationSize, ConstantPopulationSize
from ionchannelABC import theoretical_population_size
pop_size = theoretical_population_size(2, len(limits))
print("Theoretical minimum population size is {} particles".format(pop_size))


Theoretical minimum population size is 1024 particles

In [11]:
from pyabc import ABCSMC
from pyabc.epsilon import MedianEpsilon
from pyabc.sampler import MulticoreEvalParallelSampler, SingleCoreSampler
from ionchannelABC import IonChannelDistance, EfficientMultivariateNormalTransition, IonChannelAcceptor

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(5000),
             summary_statistics=summary_statistics,
             transitions=EfficientMultivariateNormalTransition(),
             eps=MedianEpsilon(initial_epsilon=20),
             sampler=MulticoreEvalParallelSampler(n_procs=6),
             acceptor=IonChannelAcceptor())


DEBUG:ABC:ion channel weights: {'0': 1.1328095197739978, '1': 1.1328095197739978, '2': 1.1328095197739978, '3': 1.1328095197739978, '4': 1.1328095197739978, '5': 0.9427898583925535, '6': 0.541231215003132, '7': 0.45666383765889307, '8': 0.45666383765889307, '9': 0.45666383765889307, '10': 0.44963824015644904, '11': 0.47139492919627674, '12': 0.5219015287530194, '13': 0.48710809350281936, '14': 0.5514431247201723, '15': 0.6353583828297648, '16': 0.6958687050040283, '17': 0.7493970669274139, '18': 0.9427898583925535, '19': 1.0078098486265201, '20': 1.1328095197739978, '21': 1.1328095197739978, '22': 1.1328095197739978, '23': 1.6745879857528663, '24': 1.6745879857528663, '25': 1.6745879857528663, '26': 1.6745879857528663, '27': 1.6745879857528663, '28': 1.6745879857528663, '29': 1.1432519768736087, '30': 1.4499481340055325, '31': 1.6745879857528663, '32': 1.6745879857528663, '33': 1.6745879857528663, '34': 1.6745879857528663, '35': 1.7238405735691273, '36': 1.7238405735691273, '37': 0.5132592645781386, '38': 0.42927138491989675, '39': 0.38704797000974284, '40': 0.4372208550110062, '41': 0.38704797000974284, '42': 0.6053827223229319, '43': 0.6944095932527747, '44': 0.655831282516511, '45': 0.6745693191598379}
DEBUG:Epsilon:init quantile_epsilon initial_epsilon=20, quantile_multiplier=1

In [13]:
obs = observations.to_dict()['y']
obs = {str(k): v for k, v in obs.items()}

In [14]:
abc_id = abc.new(db_path, obs)


INFO:History:Start <ABCSMC(id=1, start_time=2019-07-18 08:22:04.565648, end_time=None)>

In [ ]:
history = abc.run(minimum_epsilon=0.1, max_nr_populations=200, min_acceptance_rate=0.005)


INFO:ABC:t:0 eps:20
DEBUG:ABC:now submitting population 0
DEBUG:ABC:population 0 done
DEBUG:ABC:
total nr simulations up to t =0 is 6119
DEBUG:Epsilon:new eps, t=1, eps=5.9439881040753155
INFO:ABC:t:1 eps:5.9439881040753155
DEBUG:ABC:now submitting population 1
DEBUG:ABC:population 1 done
DEBUG:ABC:
total nr simulations up to t =1 is 16697
DEBUG:Epsilon:new eps, t=2, eps=4.627091011870805
INFO:ABC:t:2 eps:4.627091011870805
DEBUG:ABC:now submitting population 2
DEBUG:ABC:population 2 done
DEBUG:ABC:
total nr simulations up to t =2 is 30437
DEBUG:Epsilon:new eps, t=3, eps=4.081053423726376
INFO:ABC:t:3 eps:4.081053423726376
DEBUG:ABC:now submitting population 3
DEBUG:ABC:population 3 done
DEBUG:ABC:
total nr simulations up to t =3 is 45250
DEBUG:Epsilon:new eps, t=4, eps=3.2120514001989355
INFO:ABC:t:4 eps:3.2120514001989355
DEBUG:ABC:now submitting population 4
DEBUG:ABC:population 4 done
DEBUG:ABC:
total nr simulations up to t =4 is 57786
DEBUG:Epsilon:new eps, t=5, eps=2.645190762691818
INFO:ABC:t:5 eps:2.645190762691818
DEBUG:ABC:now submitting population 5
DEBUG:ABC:population 5 done
DEBUG:ABC:
total nr simulations up to t =5 is 71278
DEBUG:Epsilon:new eps, t=6, eps=2.194439218135261
INFO:ABC:t:6 eps:2.194439218135261
DEBUG:ABC:now submitting population 6
DEBUG:ABC:population 6 done
DEBUG:ABC:
total nr simulations up to t =6 is 84986
DEBUG:Epsilon:new eps, t=7, eps=2.005689978909324
INFO:ABC:t:7 eps:2.005689978909324
DEBUG:ABC:now submitting population 7
DEBUG:ABC:population 7 done
DEBUG:ABC:
total nr simulations up to t =7 is 100044
DEBUG:Epsilon:new eps, t=8, eps=1.912767084432608
INFO:ABC:t:8 eps:1.912767084432608
DEBUG:ABC:now submitting population 8
DEBUG:ABC:population 8 done
DEBUG:ABC:
total nr simulations up to t =8 is 119752
DEBUG:Epsilon:new eps, t=9, eps=1.7339950017727843
INFO:ABC:t:9 eps:1.7339950017727843
DEBUG:ABC:now submitting population 9
DEBUG:ABC:population 9 done
DEBUG:ABC:
total nr simulations up to t =9 is 136225
DEBUG:Epsilon:new eps, t=10, eps=1.5831051668689882
INFO:ABC:t:10 eps:1.5831051668689882
DEBUG:ABC:now submitting population 10
DEBUG:ABC:population 10 done
DEBUG:ABC:
total nr simulations up to t =10 is 152211
DEBUG:Epsilon:new eps, t=11, eps=1.4946984580559062
INFO:ABC:t:11 eps:1.4946984580559062
DEBUG:ABC:now submitting population 11
DEBUG:ABC:population 11 done
DEBUG:ABC:
total nr simulations up to t =11 is 169623
DEBUG:Epsilon:new eps, t=12, eps=1.4476642372050836
INFO:ABC:t:12 eps:1.4476642372050836
DEBUG:ABC:now submitting population 12

In [ ]:
history = abc.run(minimum_epsilon=0.0, max_nr_populations=100, min_acceptance_rate=0.001)

Results analysis


In [16]:
from pyabc import History

In [17]:
history = History(db_path)
history.all_runs()


Out[17]:
[<ABCSMC(id=1, start_time=2019-07-18 08:22:04.565648, end_time=2019-07-21 14:09:33.799263)>]

In [18]:
history.id = 1

In [19]:
df, w = history.get_distribution(m=0)

In [20]:
df.describe()


Out[20]:
name icat.E_Ca_offset icat.g_CaT icat.p_2 icat.p_4 icat.p_6 icat.p_8 log_icat.p_1 log_icat.p_3 log_icat.p_5 log_icat.p_7
count 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000
mean 70.235023 0.158523 0.027162 0.186357 0.169601 0.051547 2.470910 -0.904688 0.923305 -3.829859
std 2.636887 0.004980 0.001786 0.001795 0.001107 0.000923 0.053579 0.066487 0.034504 0.032051
min 62.465855 0.143973 0.021783 0.180377 0.166577 0.048439 2.286447 -1.116441 0.828407 -3.923020
25% 70.242450 0.158387 0.025906 0.185188 0.168777 0.050896 2.445140 -0.928635 0.897636 -3.853198
50% 71.243244 0.160379 0.026996 0.186333 0.169560 0.051582 2.478733 -0.890688 0.921704 -3.831133
75% 71.762397 0.161468 0.028383 0.187441 0.170392 0.052221 2.508504 -0.859395 0.947750 -3.807146
max 73.195300 0.164538 0.033917 0.193562 0.173181 0.054214 2.590635 -0.770929 1.036807 -3.722263

In [21]:
from ionchannelABC import plot_parameters_kde
g = plot_parameters_kde(df, w, limits, aspect=12,height=0.6)


/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/seaborn/axisgrid.py:848: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  self.fig.tight_layout()
/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/seaborn/axisgrid.py:848: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  self.fig.tight_layout()
/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/seaborn/axisgrid.py:848: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  self.fig.tight_layout()
/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/seaborn/axisgrid.py:848: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  self.fig.tight_layout()
/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/seaborn/axisgrid.py:848: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  self.fig.tight_layout()

Samples for quantitative analysis


In [22]:
# Generate parameter samples
n_samples = 100
df, w = history.get_distribution(m=0)
th_samples = df.sample(n=n_samples, weights=w, replace=True).to_dict(orient='records')

In [23]:
# Generate sim results samples
import pandas as pd
samples = pd.DataFrame({})
for i, th in enumerate(th_samples):
    results = summary_statistics(model(th))
    output = pd.DataFrame({'x': observations.x, 'y': list(results.values()),
                           'exp_id': observations.exp_id})
    #output = model.sample(pars=th, n_x=50)
    output['sample'] = i
    output['distribution'] = 'post'
    samples = samples.append(output, ignore_index=True)

In [24]:
from ionchannelABC import plot_sim_results
import seaborn as sns
sns.set_context('talk')
g = plot_sim_results(samples, obs=observations)

# Set axis labels
#xlabels = ["voltage, mV", "voltage, mV", "voltage, mV", "time, ms"]#, "time, ms","voltage, mV"]
#ylabels = ["normalised current density, pA/pF", "activation", "inactivation", "recovery"]#, "normalised current","current density, pA/pF"]
#for ax, xl in zip(g.axes.flatten(), xlabels):
#    ax.set_xlabel(xl)
#for ax, yl in zip(g.axes.flatten(), ylabels):
#    ax.set_ylabel(yl)



In [31]:
#g.savefig('results/icat-generic/icat_sim_results.pdf')

In [103]:
def plot_sim_results_all(samples: pd.DataFrame):
    with sns.color_palette("gray"):
        grid = sns.relplot(x='x', y='y',
                           col='exp',
                           units='sample',
                           kind='line',
                           data=samples,
                           estimator=None, lw=0.5,
                           alpha=0.5,
                           #estimator=np.median,
                           facet_kws={'sharex': 'col',
                                      'sharey': 'col'})
    return grid

In [104]:
grid2 = plot_sim_results_all(samples)



In [33]:
#grid2.savefig('results/icat-generic/icat_sim_results_all.pdf')

In [35]:
import numpy as np

In [42]:
# Mean current density
print(np.mean(samples[samples.exp=='0'].groupby('sample').min()['y']))
# Std current density
print(np.std(samples[samples.exp=='0'].groupby('sample').min()['y']))


-0.9792263129382246
0.060452038127623814

In [43]:
import scipy.stats as st
peak_current = samples[samples['exp']=='0'].groupby('sample').min()['y'].tolist()
rv = st.rv_discrete(values=(peak_current, [1/len(peak_current),]*len(peak_current)))

In [44]:
print("median: {}".format(rv.median()))
print("95% CI: {}".format(rv.interval(0.95)))


median: -0.9929750589235674
95% CI: (-1.0714884415582595, -0.8489199437971181)

In [45]:
# Voltage of peak current density
idxs = samples[samples.exp=='0'].groupby('sample').idxmin()['y']
print("mean: {}".format(np.mean(samples.iloc[idxs]['x'])))
print("STD: {}".format(np.std(samples.iloc[idxs]['x'])))


mean: -20.1
STD: 0.7

In [46]:
voltage_peak = samples.iloc[idxs]['x'].tolist()
rv = st.rv_discrete(values=(voltage_peak, [1/len(voltage_peak),]*len(voltage_peak)))
print("median: {}".format(rv.median()))
print("95% CI: {}".format(rv.interval(0.95)))


median: -20.0
95% CI: (-20.0, -20.0)

In [48]:
# Half activation potential
# Fit of activation to Boltzmann equation
from scipy.optimize import curve_fit
grouped = samples[samples['exp']=='1'].groupby('sample')
def fit_boltzmann(group):
    def boltzmann(V, Vhalf, K):
        return 1/(1+np.exp((Vhalf-V)/K))
    guess = (-30, 10)
    popt, _ = curve_fit(boltzmann, group.x, group.y)
    return popt
output = grouped.apply(fit_boltzmann).apply(pd.Series)

In [49]:
print(np.mean(output))
print(np.std(output))


0   -33.399071
1     5.739255
dtype: float64
0    0.823473
1    0.366996
dtype: float64

In [50]:
Vhalf = output[0].tolist()
rv = st.rv_discrete(values=(Vhalf, [1/len(Vhalf),]*len(Vhalf)))
print("median: {}".format(rv.median()))
print("95% CI: {}".format(rv.interval(0.95)))


median: -33.407394098238164
95% CI: (-34.93130871417603, -31.973122716861205)

In [51]:
slope = output[1].tolist()
rv = st.rv_discrete(values=(slope, [1/len(slope),]*len(slope)))
print("median: {}".format(rv.median()))
print("95% CI: {}".format(rv.interval(0.95)))


median: 5.728938366573993
95% CI: (5.117385157850234, 6.485585591389819)

In [52]:
# Half activation potential
grouped = samples[samples['exp']=='2'].groupby('sample')
def fit_boltzmann(group):
    def boltzmann(V, Vhalf, K):
        return 1-1/(1+np.exp((Vhalf-V)/K))
    guess = (-100, 10)
    popt, _ = curve_fit(boltzmann, group.x, group.y,
                        bounds=([-100, 1], [0, 30]))
    return popt
output = grouped.apply(fit_boltzmann).apply(pd.Series)

In [53]:
print(np.mean(output))
print(np.std(output))


0   -49.011222
1     4.399126
dtype: float64
0    0.613833
1    0.306758
dtype: float64

In [54]:
Vhalf = output[0].tolist()
rv = st.rv_discrete(values=(Vhalf, [1/len(Vhalf),]*len(Vhalf)))
print("median: {}".format(rv.median()))
print("95% CI: {}".format(rv.interval(0.95)))


median: -49.01404281457659
95% CI: (-50.06478757419054, -47.57952101705519)

In [55]:
slope = output[1].tolist()
rv = st.rv_discrete(values=(slope, [1/len(slope),]*len(slope)))
print("median: {}".format(rv.median()))
print("95% CI: {}".format(rv.interval(0.95)))


median: 4.420440009120772
95% CI: (3.7821747606540193, 4.959106709731536)

In [56]:
# Recovery time constant
grouped = samples[samples.exp=='3'].groupby('sample')
def fit_single_exp(group):
    def single_exp(t, I_max, tau):
        return I_max*(1-np.exp(-t/tau))
    guess = (1, 50)
    popt, _ = curve_fit(single_exp, group.x, group.y, guess)
    return popt[1]
output = grouped.apply(fit_single_exp)

In [57]:
print(np.mean(output))
print(np.std(output))


114.50830523453935
5.781251582667316

In [58]:
tau = output.tolist()
rv = st.rv_discrete(values=(tau, [1/len(tau),]*len(tau)))
print("median: {}".format(rv.median()))
print("95% CI: {}".format(rv.interval(0.95)))


median: 113.75533911706513
95% CI: (104.11137902797657, 125.98102619971708)

In [ ]: