from rpy2.robjects.packages import importr
from rpy2 import robjects

import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()

import numpy as np

def sim_xy(n, p, nval, rho=0, s=5, beta_type=2, snr=1):
    robjects.r('''
    source('~/best-subset/bestsubset/R/sim.R')
    ''')

    r_simulate = robjects.globalenv['sim.xy']
    sim = r_simulate(n, p, nval, rho, s, beta_type, snr)
    X = np.array(sim.rx2('x'))
    y = np.array(sim.rx2('y'))
    X_val = np.array(sim.rx2('xval'))
    y_val = np.array(sim.rx2('yval'))
    Sigma = np.array(sim.rx2('Sigma'))
    beta = np.array(sim.rx2('beta'))
    sigma = np.array(sim.rx2('sigma'))

    return X, y, X_val, y_val, Sigma, beta, sigma

sim_xy(n=50, p=10, nval=50)

def tuned_lasso(X, Y, X_val,Y_val):
    robjects.r('''
        source('~/best-subset/bestsubset/R/lasso.R')
        tuned_lasso_estimator = function(X,Y,X.val,Y.val){
        Y = as.matrix(Y)
        X = as.matrix(X)
        Y.val = as.vector(Y.val)
        X.val = as.matrix(X.val)

        rel.lasso = lasso(X,Y,intercept=TRUE, nrelax=5, nlam=50)
        beta.hat = as.matrix(coef(rel.lasso))

        muhat.val = as.matrix(predict(rel.lasso, X.val))
        err.val = colMeans((muhat.val - Y.val)^2)
        return(beta.hat[,which.min(err.val)])
        }''')

    r_lasso = robjects.globalenv['tuned_lasso_estimator']

    n, p = X.shape
    nval, _ = X_val.shape
    r_X = robjects.r.matrix(X, nrow=n, ncol=p)
    r_y = robjects.r.matrix(Y, nrow=n, ncol=1)

    r_X_val = robjects.r.matrix(X_val, nrow=nval, ncol=p)
    r_y_val = robjects.r.matrix(Y_val, nrow=nval, ncol=1)
    estimator = r_lasso(r_X, r_y, r_X_val, r_y_val)
    return (estimator)

#print(tuned_lasso(np.random.standard_normal((50,10)), np.random.standard_normal(50),
#                  np.random.standard_normal((50,10)), np.random.standard_normal(50)))
@@ -692,37 +692,8 @@
 ma%0A%0A
-sim_xy(n=50, p=10, nval=50)%0A%0A
 def 
@@ -711,17 +711,17 @@
 (X, 
-Y
+y
 , X_val,
 Y_va
@@ -716,17 +716,17 @@
 , X_val,
-Y
+y
 _val):%0A 
@@ -1016,11 +1016,12 @@
 ept=
-TRU
+FALS
 E, n
@@ -1026,17 +1026,18 @@
  nrelax=
-5
+10
 , nlam=5
@@ -1433,17 +1433,17 @@
 .matrix(
-Y
+y
 , nrow=n
@@ -1543,17 +1543,17 @@
 .matrix(
-Y
+y
 _val, nr
@@ -1585,16 +1585,25 @@
 mator = 
+np.array(
 r_lasso(
@@ -1625,24 +1625,25 @@
 al, r_y_val)
+)
 %0A    return 
@@ -1642,17 +1642,16 @@
  return 
-(
 estimato
@@ -1655,179 +1655,192 @@
 ator
-)
 %0A%0A
-#print(tuned_lasso(np.random.standard_normal((50,10)), np.random.standard_normal(50),%0A#                  np.random.standard_normal((50,10)), np.random.standard_normal(50)))
+X, y, X_val, y_val, Sigma, beta, sigma = sim_xy(n=500, p=100, nval=500, rho=0.35, s=5, beta_type=2, snr=0.2)%0Arel_LASSO = tuned_lasso(X, y, X_val,y_val)%0Aprint(%22relaxed LASSO%22, rel_LASSO)%0A

return tuned relaxed lasso est