#!/usr/bin/env python3

#
# This scripts reproduce the default biochemical model used by miRBooking to
# characterize individual interactions in such a way we can fit the free
# parameters with experimental data.
#

from subprocess import check_output, DEVNULL
import yaml
import re
from math import isfinite, isnan
from scipy.optimize import minimize
from scipy.stats import pearsonr, norm
import numpy as np

R = 1.987203611e-3
T = 310.5

with open('data/single-molecule-experimental-measurements.yaml') as f:
    data = yaml.load(f, Loader=yaml.Loader)

def fold_duplex_mcff(a, b, mask=None):
    if mask is None:
        mask = (len(a) * '(') + '&' + (len(b) * ')')
    if len(a) + 1 + len(b) != len(mask):
        return 999.
    mask = 'xx'.join(mask.replace('.', 'x').split('&'))
    stdout = check_output(['mcff', '-seq', a, '-sd', b, '-mask', mask])
    return float(stdout)

def fold_duplex_RNAcofold(a, b, mask=None):
    if mask is None:
        mask = (len(a) * '(') + '&' + (len(b) * ')')
    if len(a) + 1 + len(b) != len(mask):
        return 999.
    vienna_binding_energy_re = 'delta G binding=\s*(.+)$'
    stdout = check_output(['RNAcofold', '--noPS', '-p', '-C', '-T', str(T - 273.15)], input=f'{a}&{b}\n{mask}', universal_newlines=True, stderr=DEVNULL)
    match = re.search(vienna_binding_energy_re, stdout)
    return float(match.group(1))

fold = fold_duplex_RNAcofold

def rc(a):
    return {'A': 'U', 'U': 'A', 'G': 'C', 'C': 'G', 'T': 'A'}[a]

X = []
Y = []
for experiment in data:
    target, position, mirna = experiment['target'], experiment['position'], experiment['mirna']
    X.append([
        fold(target[position:position+7], mirna[1:8], '...((((&))))...'),     # seed
        fold(target[position-3:position-3+3], mirna[8:11], '(((&)))'),        # A
        fold(target[position-6:position-6+3], mirna[11:14], '(((&)))'),       # B
        fold(target[position-9:position-9+3], mirna[14:17], '(((&)))'),       # C
        fold(target[position-12:position-12+3], mirna[17:20], '(((&)))'),     # D
        sum((target[position + 7 - i] != rc(mirna[i])) for i in range(1, 5)), # seed core mismatch
        sum((target[position + 7 - i] != rc(mirna[i])) for i in range(5, 8)), # seed supp mismatch
        target[position + 7] == 'A',                                          # t1 adenosine
        ])

    score = experiment['score']

    kf = float(score.get('kf', ['nan'])[0])
    kr = float(score.get('kr', ['nan'])[0])
    kcat = float(score.get('kcat', ['nan'])[0])
    Kd = float(score.get('Kd', ['nan'])[0])
    Km = float(score.get('Km', ['nan'])[0])

    if isnan(kr):
        kr = kf * Kd

    if isnan(kf):
        kf = kr / Kd

    if isnan(Kd):
        Kd = kr / kf

    Y.append([kf, kr, kcat, Kd, Km])

X = np.array(X)
Y = np.array(Y)

def binding_energy(G):
    G = np.array(G)
    Z = np.sum(np.exp(-G / (R * T)), axis=1)
    return np.sum(np.exp(-G/(R*T)) * G, axis=1) / Z

def binding_probability(G):
    G = np.array(G)
    Z = np.sum(np.exp(-G / (R * T)), axis=1).reshape((-1, 1))
    return np.exp(-G/(R*T)) / Z

def f(X, weights):
    # model weights
    base_kf, base_kcleave, ago2_deltaG, seed_core_mismatch_penalty, seed_supp_mismatch_penalty, t1_adenosine_score = weights
    base_kf = np.exp(base_kf)
    base_kcleave = np.exp(base_kcleave)
    seed_core_mismatch_penalty = np.exp(seed_core_mismatch_penalty)
    seed_supp_mismatch_penalty = np.exp(seed_supp_mismatch_penalty)

    # model features
    seed, A, B, C, D, seed_core_mismatches, seed_supp_mismatches, t1_adenosine = X.T

    canonical_ensemble = np.column_stack([np.zeros_like(B), B, B + C, B + C + A, B + C + A + D])

    deltaG = ago2_deltaG + (t1_adenosine * t1_adenosine_score) + seed + binding_energy(canonical_ensemble)

    Kd = 1e12 * np.exp(deltaG / (R * T))

    kf = base_kf * np.ones_like(X[:,0]) * np.power(seed_core_mismatch_penalty, seed_core_mismatches) * np.power(seed_supp_mismatch_penalty, seed_supp_mismatches)
    kr = kf * Kd

    kcleave = base_kcleave * np.ones_like(seed) * np.sum(binding_probability(canonical_ensemble)[:,3:], axis=1)
    krelease = kr
    # if any of kcleave or krelease is zero, then the corresponding kcat will
    # be zero as well
    with np.errstate(divide='ignore'):
        kcat = 1. / (1. / kcleave + 1. / krelease)

    Km = Kd + (kcat/kf)
    return np.column_stack([kf, kr, kcat, Kd, Km])

def log_rmse(x, y):
    ix = np.isfinite(x) & (x != 0) & np.isfinite(y) & (y != 0)
    n = np.count_nonzero(ix)
    return np.linalg.norm(np.log10(x[ix]) - np.log10(y[ix])) / np.sqrt(n)

def log_r2(x, y):
    ix = np.isfinite(x) & (x != 0) & np.isfinite(y) & (y != 0)
    n = np.count_nonzero(ix)
    r, pvalue = pearsonr(np.log(x[ix]), np.log(y[ix]))
    rsq = np.square(r)
    ci = np.square(np.tanh(norm.interval(0.95, np.arctanh(r), 1. / np.sqrt(n - 3))))
    return rsq, ci

def loss(X, y, weights):
    return log_rmse(f(X, weights), y)

func = lambda weights: loss(X, Y, weights)

result = minimize(func, x0=np.array([np.log(1e-5), np.log(1.), -5., np.log(1.), np.log(1.), -1]))
weights = result['x']

for i, constant in enumerate(['kf', 'kr', 'kcat', 'Kd', 'Km']):
    r2, (r2_ci_low, r2_ci_high) = log_r2(f(X, weights)[:,i], Y[:,i])
    print('{} R²:'.format(constant), '{:.2f} (95% CI: {:.2f}, {:.2f})'.format(r2, r2_ci_low, r2_ci_high))

print('RMSE:', '{:.2f}'.format(result['fun']))
print(f'''Optimal Parameters:
    base kf = {np.exp(weights[0]):.2e} pM^-1s^-1
    base kcleave = {np.exp(weights[1]):.2e} s^-1
    AGO2 entropy = {weights[2]:.2f} kcal/mol
    seed mismatch weights = {np.exp(weights[3]):.2f} and {np.exp(weights[4]):.2f}
    t1 adenosine contribution = {weights[5]:.2f} kcal/mol''')
