rm(list = ls())

library(ncdf4)
library(s2dv)
library(ggplot2)
library(akima)

lats <- rep(rlat_ecearth, length(lev_ecearth))
levels <- sort(rep(lev_ecearth, length(rlat_ecearth)))
datos <- data.frame(lats = lats, levels = levels, 
                    data = as.vector(t(diff_ecearth_yr_ens_mvolc)))

lats_trans <- lm(y~x, data = data.frame(x = rlat_ecearth, 
                                        y = seq(0,99.9, 100/292)))
lats_trans$fitted.values
lev_trans <- lm(y~x, data = data.frame(x = lev_ecearth,
                                       y = seq(0, 99.9, 100/75)))
lev_trans$fitted.values

lats_t_target <- lats_trans$coeff[1] + lats_trans$coeff[2]* (-30:60)
lev_t_target <- lev_trans$coeff[1] + lev_trans$coeff[2]* c(5,10,20,30,40,50,60,70,80,90,100,150,200,300,400,500,600,700,800,900,1000,1250,1500,1750,2000,2250,2500,2750,3000,3250,3500,3750,4000,4250,4500)


rep(rlat_ecearth, length(lev_ecearth))
sort(rep(lev_ecearth, length(rlat_ecearth)))

inter_lin = interp(rep(lats_trans$fitted.values, length(lev_ecearth)), 
                   sort(rep(lev_trans$fitted.values, length(rlat_ecearth))), 
                    datos$data,
                    xo = lats_t_target,
                    yo = lev_t_target,
                   linear = TRUE, extrap = TRUE)

dev.new()
PlotSection(t(inter_lin$z), inter_lin$x, inter_lin$y, toptitle = 'Interpolation', cols=jBrewColorsano, brks=brks_def, drawleg=F, sizetit = 0.5)

(lev_t_target - lev_trans$coeff[1]) / lev_trans$coeff[2]



inter_lin = interp(lats, levels, datos$data,
                    xo = -80:85,
                    yo = c(5,10,20,30,40,50,60,70,80,90,100,150,200,300,400,500,600,700,800,900,1000,1250,1500,1750,2000,2250,2500,2750,3000,3250,3500,3750,4000,4250,4500),
#                   xo = seq(min(lats), max(lats), length = 100),
#                   yo = seq(min(levels), max(levels), length = 100),
                   linear = TRUE, extrap = TRUE)

dev.new()
PlotSection(t(inter_lin$z), inter_lin$x, inter_lin$y, toptitle = 'Interpolation', cols=jBrewColorsano, brks=brks_def, drawleg=F, sizetit = 0.5)



