#include /include/license.stan

functions {

  #include /include/linear_interpolation.stan

  vector TKTD_varSD( real t,
                     vector y,
                     vector theta,
                     vector expo_x,
                     vector expo_y) {

    // - parameters
    real kd = theta[1];
    real hb = theta[2];
    real z = theta[3];
    real kk = theta[4];
    
    // - new variables
    vector[2] dy_dt; //
    vector[2] max_z; // 
    
    // interpolation of exposure
    real expo_t = interpolate(t, expo_x, expo_y) ;
    
    // - model
    dy_dt[1] =  kd * ( expo_t - y[1]);

    max_z[1] = 0;
    max_z[2] = y[1] - z;

    dy_dt[2] = kk * max(max_z) + hb;
    return(dy_dt);
  }
}

data {
   #include /include/data_guts.stan
   real kk_meanlog10;
   real kk_sdlog10;
   real z_meanlog10;
   real z_sdlog10;
}
parameters {
    real kd_log10, hb_log10, kk_log10, z_log10 ;
}
transformed parameters{
    // Priors
    real kd, hb, kk, z ;
    // ODE
    vector<lower=0>[2] y0;
    // remove 1e-12 to start before min time !
    real t0 = 0.0 - 1e-12;
    vector[4] theta ;
    array[n_N] vector[2] y_hat;
    // model GUTS
    vector<lower=0, upper=1>[n_N] Psurv_hat;
    vector<lower=0, upper=1>[n_N] Conditional_Psurv_hat;
    
    kd = 10^kd_log10 ;
    if(HB_FIXED == 0){
        hb = 10^hb_log10 ;
    } else{
        hb = hb_value;
    }
    kk = 10^kk_log10 ;
    z  = 10^z_log10 ;
    
    theta = [kd, hb, z, kk]';

    for (g in 1:n_group){
        array[GROUP_N[3,g]] real ts ;
        vector[GROUP_X[3,g]] exposure_t ;
        vector[GROUP_X[3,g]] exposure_v ;
        // add 1e-12 to be > 0!
        ts = time_N[GROUP_N[1,g]:GROUP_N[2,g]];
        exposure_t = to_vector(time_X[GROUP_X[1,g]:GROUP_X[2,g]]);
        exposure_v = to_vector(conc[GROUP_X[1,g]:GROUP_X[2,g]]);
        y0 = [0,0]';
        y_hat[GROUP_N[1,g]:GROUP_N[2,g],1:2]  = ode_rk45(
          TKTD_varSD, y0, t0, ts, theta, 
          exposure_t, exposure_v
        );
          
        Psurv_hat[GROUP_N[1,g]:GROUP_N[2,g]] = to_vector(exp( - y_hat[GROUP_N[1,g]:GROUP_N[2,g], 2]));
        
        for(i in GROUP_N[1,g]:GROUP_N[2,g]){
          Conditional_Psurv_hat[i] =  i == GROUP_N[1,g] ? Psurv_hat[i] : Psurv_hat[i] / Psurv_hat[i-1] ;
        }
    }
}
model {
    // PRIORS
    target += normal_lpdf(kd_log10 | kd_meanlog10, kd_sdlog10);
    target += normal_lpdf(hb_log10 | hb_meanlog10, hb_sdlog10);
    target += normal_lpdf(kk_log10 | kk_meanlog10, kk_sdlog10);
    target += normal_lpdf(z_log10  |  z_meanlog10,  z_sdlog10);
    //
    for (g in 1:n_group){
      target += binomial_lpmf(
          Nsurv[GROUP_N[1,g]:GROUP_N[2,g]] | 
          Nprec[GROUP_N[1,g]:GROUP_N[2,g]], 
          Conditional_Psurv_hat[GROUP_N[1,g]:GROUP_N[2,g]]
        );
    }
}

generated quantities {
  #include /include/generated_quantities.stan
}
