clear all
cd ('\\stat.ad.ncsu.edu\Redirect\cwang19\Desktop\P3simulations')
addpath(genpath('./fslicing'))
addpath(genpath('./release2.16'))
addpath(genpath('./mvkernelsmoothing'))

rng(2016)
ntrain = 100;
ntest= 10*ntrain;
n=ntrain+ntest;
isNewSub = ntest;
kn_all = [5 10 20 30];  %sn=kn:  how many eigenvalues kept in xcov
dd_all = [1 2 2 2]; 

vary = 1;
varx = 0;

lintx = 10;
ngrid = 101;


regular = 2; % regular =  0 means creating sparse data
nsim = 100;
criteria= 1; %kernel smoothing parameter selection criteria;1 is AIC; 2 is BIC

evals = sort((0.01:0.01:1),'descend'); C1 = 0.82; model = 1;  uu =  2 ; dimCS = 1; dd = uu; %model 1 is I;  %%%%%%%%%%%%%%%%%%%%%%(a)


results = zeros(nsim,5);

FIT = 0;
alpha = 0.05;
param_X = setOptions('selection_k','AIC_R','verbose','on', 'ngrid',ngrid,'newdata',linspace(0,1,ngrid));
param_Y = setOptions('selection_k','FVE','FVE_threshold',0.9,'verbose','on');


% Create training and testing sample
[t_x, t_y, x, y, t, ~, Ey, truebeta] = getFunData_eg1(n, lintx, ngrid, model, ...
regular, varx, vary, evals, C1);

Eyte = Ey((ntrain+1):n,:);
yvar =  var(Eyte);
ytr = y(1:ntrain,:);
yte = y((ntrain+1):n,:);


K_x = []; K_y = [];
[res, xx, ~, newxscore] = FPCreg(x, t_x, ytr', t_y,param_X, param_Y,FIT,K_x,K_y,ntest,alpha); 

xi_est = getVal(xx,'xi_est');
K_x= getVal(res,'K_x');


r=ksrmv(xi_est(:,1:K_x),ytr);
r=ksrmv(xi_est(:,1:K_x),ytr, r.h ,newxscore);

newy = r.f;
next = ones(1,ntest);

ind = sum(next,1) == size(next,1); % Only consider non-extrapolated values 
% Calculate relative prediction error
petemp = sum((Eyte(ind) - newy(ind)).^2)/(sum(ind)*yvar);




