import os, tempfile
import logging
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

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

from pyabc import Distribution, RV, History, ABCSMC
from pyabc.epsilon import MedianEpsilon
from pyabc.sampler import MulticoreEvalParallelSampler, SingleCoreSampler
from pyabc.populationstrategy import ConstantPopulationSize

"""
Explanation: ABC calibration of $I_\text{CaL}$ in standardised model to unified dataset.
End of explanation
"""


from experiments.ical_li import (li_act_and_tau,
                                 li_inact_1000,
                                 li_inact_kin_80,
                                 li_recov)

modelfile = 'models/standardised_ical.mmt'

"""
Explanation: Initial set-up
Load experiments used for unified dataset calibration:
 - Steady-state activation [Li1997]
 - Activation time constant [Li1997]
 - Steady-state inactivation [Li1997]
 - Inactivation time constant (fast+slow) [Li1997]
 - Recovery time constant (fast+slow) [Li1997]
End of explanation
"""


from ionchannelABC.visualization import plot_variables

sns.set_context('poster')

V = np.arange(-80, 40, 0.01)

sta_par_map = {'di': 'ical.d_ss',
            'fi1': 'ical.f_ss',
            'fi2': 'ical.f_ss',
            'dt':  'ical.tau_d',
            'ft1': 'ical.tau_f1',
            'ft2': 'ical.tau_f2'}

f, ax = plot_variables(V, sta_par_map, 'models/standardised_ical.mmt', figshape=(3,2))

"""
Explanation: Plot steady-state and tau functions of original model (pretty much meaningless for standardised)
End of explanation
"""


observations, model, summary_statistics = setup(modelfile,
                                                li_act_and_tau,
                                                li_inact_1000,
                                                li_inact_kin_80,
                                                li_recov)

assert len(observations)==len(summary_statistics(model({})))

"""
Explanation: Combine model and experiments to produce:
 - observations dataframe
 - model function to run experiments and return traces
 - summary statistics function to accept traces
End of explanation
"""


limits = {'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),
          'log_ical.A': (0., 3.)}
prior = Distribution(**{key: RV("uniform", a, b - a)
                        for key, (a,b) in limits.items()})

# Test this works correctly with set-up functions
assert len(observations) == len(summary_statistics(model(prior.rvs())))

"""
Explanation: Set up prior ranges for each parameter in the model.
See the modelfile for further information on specific parameters. Prepending `log_' has the effect of setting the parameter in log space.
End of explanation
"""


db_path = ("sqlite:///" + os.path.join(tempfile.gettempdir(), "standardised_ical.db"))

logging.basicConfig()
abc_logger = logging.getLogger('ABC')
abc_logger.setLevel(logging.DEBUG)
eps_logger = logging.getLogger('Epsilon')
eps_logger.setLevel(logging.DEBUG)

pop_size = theoretical_population_size(2, len(limits))
print("Theoretical minimum population size is {} particles".format(pop_size))

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())

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

abc_id = abc.new(db_path, obs)

history = abc.run(minimum_epsilon=0., max_nr_populations=100, min_acceptance_rate=0.01)

history = abc.run(minimum_epsilon=0., max_nr_populations=100, min_acceptance_rate=0.01)

"""
Explanation: Run ABC calibration
End of explanation
"""


history = History(db_path)

df, w = history.get_distribution(m=0)

df.describe()

sns.set_context('poster')

mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14


g = plot_sim_results(modelfile,
                     li_act_and_tau,
                     li_inact_1000,
                     li_inact_kin_80,
                     li_recov,
                     df=df, w=w)

plt.tight_layout()

import pandas as pd
N = 100
sta_par_samples = df.sample(n=N, weights=w, replace=True)
sta_par_samples = sta_par_samples.set_index([pd.Index(range(N))])
sta_par_samples = sta_par_samples.to_dict(orient='records')

sns.set_context('poster')
mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14

V = np.arange(-140, 50, 0.01)

sta_par_map = {'di': 'ical.d_ss',
               'fi1': 'ical.f_ss',
               'fi2': 'ical.f_ss',
               'dt': 'ical.tau_d',
               'ft1': 'ical.tau_f1',
               'ft2': 'ical.tau_f2'}

f, ax = plot_variables(V, sta_par_map, 
                       'models/standardised_ical.mmt', 
                       [sta_par_samples],
                       figshape=(3,2))

m,_,_ = myokit.load(modelfile)

sns.set_context('paper')
g = plot_kde_matrix_custom(df, w, limits=limits)
plt.tight_layout()

"""
Explanation: Analysis of results
End of explanation
"""


