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{to}$ in Nygren model to unified dataset.
End of explanation
"""


from experiments.ito_wang import wang_act, wang_inact
from experiments.ito_courtemanche import courtemanche_kin, courtemanche_rec, courtemanche_deact

modelfile = 'models/nygren_ito.mmt'

"""
Explanation: Initial set-up
Load experiments used for unified dataset calibration:
 - Steady-state activation [Wang1993]
 - Activation time constant [Courtemanche1998]
 - Deactivation time constant [Courtemanche1998]
 - Steady-state inactivation [Wang1993]
 - Inactivation time constant [Courtemanche1998]
 - Recovery time constant [Courtemanche1998]
End of explanation
"""


from ionchannelABC.visualization import plot_variables

sns.set_context('talk')

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

nyg_par_map = {'ri': 'ito.r_inf',
            'si': 'ito.s_inf',
            'rt': 'ito.tau_r',
            'st': 'ito.tau_s'}

f, ax = plot_variables(V, nyg_par_map, modelfile, figshape=(2,2))

"""
Explanation: Plot steady-state and time constant functions of original model
End of explanation
"""


observations, model, summary_statistics = setup(modelfile,
                                                wang_act,
                                                wang_inact,
                                                courtemanche_kin,
                                                courtemanche_deact,
                                                courtemanche_rec)

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

g = plot_sim_results(modelfile,
                     wang_act,
                     wang_inact,
                     courtemanche_kin,
                     courtemanche_deact,
                     courtemanche_rec)

"""
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 = {'ito.p1': (-100, 100),
          'ito.p2': (1e-7, 50),
          'log_ito.p3': (-7, 0),
          'ito.p4': (1e-7, 50),
          'log_ito.p5': (-7, 0),
          'ito.q1': (-100, 100),
          'ito.q2': (1e-7, 50),
          'log_ito.q3': (-5, 1),
          'ito.q4': (-100, 100),
          'ito.q5': (1e-7, 50),
          'log_ito.q6': (-7, 0)}
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(), "nygren_ito_unified.db"))

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

"""
Explanation: Run ABC-SMC inference
Set-up path to results database.
End of explanation
"""


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

"""
Explanation: Test theoretical number of particles for approximately 2 particles per dimension in the initial sampling of the parameter hyperspace.
End of explanation
"""


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)

"""
Explanation: Initialise ABCSMC (see pyABC documentation for further details).
IonChannelDistance calculates the weighting applied to each datapoint based on the experimental variance.
End of explanation
"""


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

"""
Explanation: Run calibration with stopping criterion of particle 1\% acceptance rate.
End of explanation
"""


history = History('sqlite:///results/nygren/ito/unified/nygren_ito_unified.db')

df, w = history.get_distribution()

df.describe()

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


sns.set_context('poster')

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

g = plot_sim_results(modelfile,
                     wang_act,
                     wang_inact,
                     courtemanche_kin,
                     courtemanche_deact,
                     courtemanche_rec,
                     df=df, w=w)

plt.tight_layout()

"""
Explanation: Plot summary statistics compared to calibrated model output.
End of explanation
"""


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

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

f, ax = plot_variables(V, nyg_par_map, 
                       'models/nygren_ito.mmt', 
                       [nyg_par_samples],
                       figshape=(2,2))

"""
Explanation: Plot gating functions
End of explanation
"""


from ionchannelABC.visualization import plot_kde_matrix_custom
import myokit
import numpy as np

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

originals = {}
for name in limits.keys():
    if name.startswith("log"):
        name_ = name[4:]
    else:
        name_ = name
    val = m.value(name_)
    if name.startswith("log"):
        val_ = np.log10(val)
    else:
        val_ = val
    originals[name] = val_

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

"""
Explanation: Plot parameter posteriors
End of explanation
"""


