In [1]:
# PyABC imports
from pyabc import (ABCSMC, Distribution, RV,
History, MedianEpsilon)
from pyabc.populationstrategy import AdaptivePopulationSize
from pyabc.epsilon import MedianEpsilon
from pyabc.sampler import MulticoreEvalParallelSampler
In [2]:
# Custom imports
from ionchannelABC import (ion_channel_sum_stats_calculator,
IonChannelAcceptor,
IonChannelDistance,
EfficientMultivariateNormalTransition,
calculate_parameter_sensitivity,
plot_parameters_kde,
plot_parameter_sensitivity,
plot_regression_fit)
In [3]:
# Other necessary imports
import numpy as np
import subprocess
import pandas as pd
import io
import os
import tempfile
In [4]:
# Plotting imports
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
%config Inline.Backend.figure_format = 'retina'
In [5]:
from channels.ical_generic import ical as model
model.sample({})
Out[5]:
In [10]:
measurements = model.get_experiment_data()
obs = measurements.to_dict()['y']
exp = measurements.to_dict()['exp']
errs = measurements.to_dict()['errs']
In [11]:
limits = dict(g_CaL=(0, 10),
v_offset=(0, 100),
Vhalf_d=(-100,100),
k_d=(0,50),
c_bd=(0,10),
c_ad=(0,10),
sigma_d=(0,100),
Vmax_d=(-100,100),
Vhalf_f=(-100,100),
k_f=(-50,0),
c_bf=(0,1000),
c_af=(0,10000),
sigma_f=(0,100),
Vmax_f=(-100,100),
ca_dep_fCa=(0, 1),
tau_fCa=(0,100))
prior = Distribution(**{key: RV("uniform", a, b - a)
for key, (a,b) in limits.items()})
In [8]:
parameters = ['ical.'+k for k in limits.keys()]
In [9]:
distance_fn=IonChannelDistance(
obs=obs,
exp_map=exp,
err_bars=errs,
err_th=0.1)
In [10]:
from ionchannelABC import plot_distance_weights
sns.set_context('talk')
grid = plot_distance_weights(model, distance_fn)
grid.savefig('results/ical-generic/dist_weights.pdf')
In [11]:
fitted, regression_fit, r2 = calculate_parameter_sensitivity(
model,
parameters,
distance_fn,
sigma=0.05,
n_samples=1000)
In [12]:
sns.set_context('talk')
grid = plot_parameter_sensitivity(fitted, plot_cutoff=0.05)
In [13]:
grid2 = plot_regression_fit(regression_fit, r2)
In [14]:
grid.savefig('results/ical-generic/sensitivity.pdf')
grid2.savefig('results/ical-generic/sensitivity_fit.pdf')
In [18]:
# Finding insensitive parameters
cutoff = 0.04
fitted_pivot = fitted.pivot(index='param',columns='exp')
insensitive_params = fitted_pivot[(abs(fitted_pivot['beta'][0])<cutoff) & (abs(fitted_pivot['beta'][1])<cutoff) &
(abs(fitted_pivot['beta'][2])<cutoff) & (abs(fitted_pivot['beta'][3])<cutoff)].index.values
In [19]:
insensitive_limits = dict((k, limits[k[5:]]) for k in insensitive_params)
insensitive_prior = Distribution(**{key: RV("uniform", a, b - a)
for key, (a,b) in insensitive_limits.items()})
In [20]:
insensitive_limits
Out[20]:
In [65]:
# Generate random samples for insensitive parameters
def generate_sample(insensitive_prior, n):
samples = [dict() for i in range(n)]
for i in range(n):
parameters = insensitive_prior.rvs()
sample = {key: value for key, value in parameters.items()}
samples[i].update(sample)
return samples
In [68]:
samples = generate_sample(insensitive_prior, 1000)
In [69]:
model.add_external_par_samples(samples)
In [70]:
# New limits eliminating insensitive parameters
limits = dict((k, limits[k]) for k in limits if k[5:] not in insensitive_params)
In [7]:
# Eliminate ca-dependent parameters as we don't explicitly test for ca_dependence
# but it will interact with other parameters
limits = dict(g_CaL=(0, 0.01),
v_offset=(0, 200),
Vhalf_d=(-200,200),
k_d=(0,50),
c_bd=(0,100),
c_ad=(0,1000),
sigma_d=(0,100),
Vmax_d=(-200,200),
Vhalf_f=(-100,100),
k_f=(-50,0),
c_bf=(0,1000),
c_af=(0,10000),
sigma_f=(0,100),
Vmax_f=(-100,100),
ca_dep_fCa=(0, 1),
tau_fCa=(0,100))
prior = Distribution(**{key: RV("uniform", a, b - a)
for key, (a,b) in limits.items()})
In [23]:
db_path = ('sqlite:///' +
os.path.join(tempfile.gettempdir(), "hl-1_ical-generic.db"))
print(db_path)
In [24]:
# 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 [25]:
from pyabc.populationstrategy import ConstantPopulationSize
In [26]:
abc = ABCSMC(models=model,
parameter_priors=prior,
distance_function=IonChannelDistance(
obs=obs,
exp_map=exp,
err_bars=errs,
err_th=0.1),
population_size=ConstantPopulationSize(2000),
#population_size=AdaptivePopulationSize(
# start_nr_particles=2000,
# mean_cv=0.4,
# max_population_size=2000,
# min_population_size=100),
summary_statistics=ion_channel_sum_stats_calculator,
transitions=EfficientMultivariateNormalTransition(),
eps=MedianEpsilon(),
sampler=MulticoreEvalParallelSampler(n_procs=12),
acceptor=IonChannelAcceptor())
In [27]:
abc_id = abc.new(db_path, obs)
In [ ]:
history = abc.run(minimum_epsilon=0.01, max_nr_populations=30, min_acceptance_rate=0.01)
In [ ]:
history = abc.run(minimum_epsilon=0.01, max_nr_populations=30, min_acceptance_rate=0.005)
In [50]:
history = abc.run(minimum_epsilon=0.01, max_nr_populations=20, min_acceptance_rate=0.01)
In [6]:
db_path = "sqlite:////scratch/cph211/ion-channel-ABC/docs/examples/results/ical-generic/hl-1_ical-generic.db"
history = History(db_path)
history.all_runs()
Out[6]:
In [7]:
history.id = 4
In [8]:
sns.set_context('talk')
In [49]:
evolution = history.get_all_populations()
grid = sns.relplot(x='t', y='epsilon', size='samples', data=evolution[evolution.t>=0])
grid.savefig('results/ical-generic/eps_evolution.pdf')
In [12]:
df, w = history.get_distribution(m=0)
g = plot_parameters_kde(df, w, limits, aspect=12, height=0.6)
In [13]:
g.savefig('results/ical-generic/parameters_kde.pdf')
In [44]:
# 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 [45]:
# Generate sim results samples
samples = pd.DataFrame({})
for i, th in enumerate(th_samples):
output = model.sample(pars=th, n_x=50)
output['sample'] = i
output['distribution'] = 'post'
samples = samples.append(output, ignore_index=True)
In [46]:
from ionchannelABC import plot_sim_results
sns.set_context('talk')
g = plot_sim_results(samples, obs=measurements)
# Set axis labels
xlabels = ["voltage, mV", "voltage, mV", "voltage, mV", "time, ms"]
ylabels = ["current density, pA/pF", "activation", "activation time constant", "recovery"]
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 [47]:
g.savefig('results/ical-generic/ical_sim_results.pdf')
In [50]:
# Peak current density
grouped = samples[samples['exp']==0].groupby('sample')
output = grouped.apply(min)['y']
print(output.mean())
print(output.std())
In [51]:
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 [52]:
print("median: {}".format(rv.median()))
print("95% CI: {}".format(rv.interval(0.95)))
In [53]:
# Half-activation voltage and slope factor
grouped = samples[samples['exp']==1].groupby('sample')
from scipy.optimize import curve_fit
def fit_boltzmann(group):
def boltzmann(V, Vhalf, Shalf):
return 1/(1+np.exp((Vhalf-V)/Shalf))
guess = (-10, 5)
popt, _ = curve_fit(boltzmann, group.x, group.y, guess)
return popt
output = grouped.apply(fit_boltzmann).apply(pd.Series)
In [54]:
print(output.mean())
print(output.std())
In [55]:
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 [56]:
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 [57]:
# Half-inactivation voltage and slope factor
grouped = samples[samples['exp']==2].groupby('sample')
from scipy.optimize import curve_fit
def fit_boltzmann(group):
def boltzmann(V, Vhalf, Shalf):
return 1/(1+np.exp((Vhalf-V)/Shalf))
guess = (-30, -5)
popt, _ = curve_fit(boltzmann, group.x, group.y, guess)
return popt
output = grouped.apply(fit_boltzmann).apply(pd.Series)
In [58]:
print(output.mean())
print(output.std())
In [59]:
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 [60]:
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 [61]:
# Recovery dynamics
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, 100)
popt, _ = curve_fit(single_exp, group.x, group.y, guess)
return popt[1]
output = grouped.apply(fit_single_exp).apply(pd.Series)
In [62]:
print(output.mean())
print(output.std())
In [63]:
tau = output[0].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 [ ]: