In [1]:
from experiments.ical_markov import (dias_iv,
rao_inact,
rao_rec)
In [2]:
from ionchannelABC.experiment import setup
from ionchannelABC import plot_sim_results
In [3]:
modelfile = 'models/ical_markov.mmt'
#modelfile = 'models/Korhonen2009_iCaL.mmt'
In [4]:
observations, model, summary_statistics = setup(modelfile,
dias_iv,
rao_inact,
rao_rec)
In [5]:
assert(len(observations)==len(summary_statistics(model({}))))
In [6]:
g = plot_sim_results(modelfile, dias_iv, rao_inact, rao_rec)
In [8]:
from pyabc import Distribution, RV
limits = {'ical.g_CaL': (0., 5.),
'ical.E_CaL': (0., 50.),
'log_ical.p_1': (-10., 5.),
'ical.p_2': (1e-7, 0.8),
'log_ical.p_3': (-15., 5.),
'ical.p_4': (1e-7, 1.2),
'log_ical.p_5': (-10., 5.),
'ical.p_6': (1e-7, 0.8),
'log_ical.p_7': (-10., 5.),
'ical.p_8': (1e-7, 0.8)}
prior = Distribution(**{key: RV("uniform", a, b - a)
for key, (a,b) in limits.items()})
from pyabc import Distribution, RV limits = {'ical.P_CaL': (0., 1e-2), 'ical.gamma_Ca_o': (0., 1.), 'log_ical.p_1': (-7., 3.), 'ical.p_2': (1e-7, 0.4), 'log_ical.p_3': (-7., 3.), 'ical.p_4': (1e-7, 0.4), 'log_ical.p_5': (-7., 3.), 'ical.p_6': (1e-7, 0.4), 'log_ical.p_7': (-7., 3.), 'ical.p_8': (1e-7, 0.4)} prior = Distribution(**{key: RV("uniform", a, b - a) for key, (a,b) in limits.items()})
In [9]:
import os, tempfile
db_path = ("sqlite:///" +
os.path.join(tempfile.gettempdir(), "hl1_ical.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)
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))
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=model,
parameter_priors=prior,
distance_function=IonChannelDistance(
exp_id=list(observations.exp_id),
variance=list(observations.variance),
delta=0.05),
population_size=ConstantPopulationSize(2500),
summary_statistics=summary_statistics,
transitions=EfficientMultivariateNormalTransition(),
eps=MedianEpsilon(initial_epsilon=20),
sampler=MulticoreEvalParallelSampler(n_procs=4),
acceptor=IonChannelAcceptor())
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)
In [ ]:
history = abc.run(minimum_epsilon=0., max_nr_populations=200, min_acceptance_rate=0.005)
In [10]:
from pyabc import ABCSMC
from pyabc.epsilon import MedianEpsilon
from pyabc.sampler import MulticoreEvalParallelSampler, SingleCoreSampler
from ionchannelABC import IonChannelDistance, EfficientMultivariateNormalTransition, IonChannelAcceptor
abc_continued = 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(),
sampler=MulticoreEvalParallelSampler(n_procs=6),
acceptor=IonChannelAcceptor())
In [11]:
abc_continued.load(db_path, 1)
Out[11]:
In [24]:
history = abc_continued.run(minimum_epsilon=0., max_nr_populations=200, min_acceptance_rate=0.001)
In [15]:
from pyabc import History
In [16]:
history = History('sqlite:////scratch/cph211/tmp/hl1_ical.db')
history.all_runs()
Out[16]:
In [17]:
history.id = 1
In [18]:
df, w = history.get_distribution(m=0)
In [19]:
df.describe()
Out[19]:
In [20]:
from ionchannelABC import plot_parameters_kde
g = plot_parameters_kde(df, w, limits, aspect=12,height=0.6)
In [21]:
g = plot_sim_results(modelfile, dias_iv, rao_inact, rao_rec, df=df, w=w)
In [21]:
# 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 [22]:
# 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 [23]:
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']))
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)))
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'])))
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)))
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))
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)))
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)))
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))
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)))
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)))
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))
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)))
In [ ]: