Create and test ion channel model


In [1]:
from channels.cm_ina_markov import (protocols,
                                    observations,
                                    simulations,
                                    times,
                                    summary_statistics)


INFO:myokit:Loading Myokit version 1.28.3

In [2]:
from functools import wraps

def simulate_model(**pars):
    """Wrapper function around simulations."""
    data = []
    for sim, time in zip(simulations, times):
        for p, v in pars.items():
            try:
                sim.set_constant(p, v)
            except:
                raise RuntimeWarning('Could not set value of {}'.format(p))
                return None
        sim.reset()
        try:
            data.append(sim.run(time, log=['environment.time','ina.i_Na','ina.g','ina.m','ina.h','membrane.V']))
        except:
            # Failed simulation
            del(data)
            return None
    return data

def log_transform(f):
    @wraps(f)
    def log_transformed(**log_kwargs):
        kwargs = dict([(key[4:], 10**value) if key.startswith("log")
                       else (key, value)
                       for key, value in log_kwargs.items()])
        return f(**kwargs)
    return log_transformed

def log_model(x):
    return log_transform(simulate_model)(**x)

In [3]:
test = simulate_model()

In [4]:
ss = summary_statistics(test)

In [5]:
assert(len(ss)==len(observations))

In [6]:
import matplotlib.pyplot as plt
key = observations.exp_id=='0'
plt.plot(observations[key].x, observations[key].y, '.')
plt.plot(observations[key].x, list(ss.values())[:13])


Out[6]:
[<matplotlib.lines.Line2D at 0x7fe298359f98>]

Set limits and generate uniform initial priors


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

In [8]:
print(prior.rvs())
test = log_model(prior.rvs())


<Parameter 'log_ina.p_1': -4.730772158126457, 'ina.p_2': 0.11538931843749385, 'log_ina.p_3': -1.657933373606971, 'ina.p_4': 0.2246286185257344, 'log_ina.p_5': 2.6313573175611538, 'ina.p_6': 0.09271178987141845, 'log_ina.p_7': 1.8539034917104296, 'ina.p_8': 0.29622821126990845>

Run ABC calibration


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


sqlite:////scratch/cph211/tmp/cm_ina_markov.db

In [10]:
# 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)
cv_logger = logging.getLogger('CV Estimation')
cv_logger.setLevel(logging.DEBUG)

In [11]:
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 256 particles

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

abc = ABCSMC(models=log_model,
             parameter_priors=prior,
             distance_function=IonChannelDistance(
                 exp_id=list(observations.exp_id),
                 variance=list(observations.variance),
                 delta=0.05),
             population_size=ConstantPopulationSize(5000),
             #population_size=AdaptivePopulationSize(
             #    start_nr_particles=10000,
             #    mean_cv=0.4,
             #    max_population_size=30000,
             #    min_population_size=pop_size),
             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.5585327376534017, '1': 1.5585327376534017, '2': 1.5585327376534017, '3': 1.5585327376534017, '4': 1.5585327376534017, '5': 0.5922502978635686, '6': 0.48479560247060055, '7': 0.6880033400331257, '8': 0.9191724622842619, '9': 1.5585327376534017, '10': 1.5585327376534017, '11': 1.5585327376534017, '12': 1.5585327376534017, '13': 1.6660177540432917, '14': 1.6660177540432917, '15': 1.6660177540432917, '16': 1.6660177540432917, '17': 1.6660177540432917, '18': 0.6141022916123275, '19': 0.4000666394868585, '20': 0.46000171656354155, '21': 0.7676278645154099, '22': 1.6660177540432917, '23': 1.6660177540432917, '24': 0.02906218941217941, '25': 0.03367374906920667, '26': 0.03457895737751867, '27': 0.046999392320876986, '28': 0.08141374774960093, '29': 0.10610649611527939, '30': 0.20902979734710037, '31': 0.07785094873262584, '32': 0.2188793689498433, '33': 0.05927794792597441, '34': 0.11670345997926211, '35': 0.16237003127549512, '36': 0.2667507656668848, '37': 1.988472803212961, '38': 1.988472803212961, '39': 1.988472803212961, '40': 1.988472803212961, '41': 1.988472803212961}
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=6, start_time=2019-06-29 10:09:07.637847, end_time=None)>

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


INFO:ABC:t:0 eps:20
DEBUG:ABC:now submitting population 0

Results analysis


In [16]:
from pyabc import History

In [17]:
history = History('sqlite:////scratch/cph211/tmp/cm_ina_markov.db')
history.all_runs()


Out[17]:
[<ABCSMC(id=1, start_time=2019-06-18 14:52:12.431003, end_time=None)>,
 <ABCSMC(id=2, start_time=2019-06-18 20:11:26.143916, end_time=None)>,
 <ABCSMC(id=3, start_time=2019-06-18 20:29:22.954218, end_time=None)>,
 <ABCSMC(id=4, start_time=2019-06-19 10:20:59.428907, end_time=None)>,
 <ABCSMC(id=5, start_time=2019-06-29 10:08:20.338693, end_time=None)>,
 <ABCSMC(id=6, start_time=2019-06-29 10:09:07.637847, end_time=None)>]

In [18]:
history.id = 6

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

In [20]:
df.describe()


Out[20]:
name ina.p_2 ina.p_4 ina.p_6 ina.p_8 log_ina.p_1 log_ina.p_3 log_ina.p_5 log_ina.p_7
count 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000 5000.000000
mean 0.049582 0.035859 0.055313 0.080864 1.671760 -0.219698 0.479220 -3.887915
std 0.001082 0.001934 0.000556 0.000681 0.034047 0.046252 0.016921 0.025445
min 0.046032 0.029836 0.053545 0.078735 1.549543 -0.398926 0.423652 -3.972059
25% 0.048846 0.034449 0.054911 0.080376 1.650153 -0.250974 0.467000 -3.905972
50% 0.049610 0.035858 0.055316 0.080872 1.674283 -0.219722 0.479291 -3.888102
75% 0.050355 0.037270 0.055714 0.081346 1.695769 -0.188508 0.491190 -3.869600
max 0.052571 0.041473 0.056880 0.083155 1.760951 -0.061034 0.527093 -3.804887

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/matplotlib/tight_layout.py:211: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  warnings.warn('Tight layout not applied. '
/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/matplotlib/tight_layout.py:211: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  warnings.warn('Tight layout not applied. '
/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/matplotlib/tight_layout.py:211: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  warnings.warn('Tight layout not applied. '
/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/matplotlib/tight_layout.py:211: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  warnings.warn('Tight layout not applied. '
/scratch/cph211/miniconda3/envs/ionchannelABC/lib/python3.7/site-packages/matplotlib/tight_layout.py:211: UserWarning: Tight layout not applied. tight_layout cannot make axes height small enough to accommodate all axes decorations
  warnings.warn('Tight layout not applied. '

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 [9]:
plotting_obs = observations.copy()

In [10]:
plotting_obs.rename({'exp_id': 'exp', 'variance': 'errs'}, axis=1, inplace=True)

In [11]:
import numpy as np
plotting_obs['errs'] = np.sqrt(plotting_obs['errs'])

In [23]:
# Generate sim results samples
import pandas as pd
samples = pd.DataFrame({})
for i, th in enumerate(th_samples):
    results = summary_statistics(log_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 = ["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 [51]:
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 [52]:
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 [ ]: