
%2) Detect and remove outlier spectra based on residuals determined by Exp-GPR regression
%*****************************************************************************************************
xo=xcal3;
yo=ycal3;

%*********************************************************************************************

avgxo = mean(xo);
stdxo=std(xo);
idr0 = flip(idtest);
[N M] = size(xo);

xo2=xo;
yo2=yo;

%*********************************************************************************************
tic
%perform calibration to determine residuals
%k2 = 0.2; %select % mg/dL threshold value for residuals
[trainedModel, validationRMSE] = trainRegressionModelEGPR64(xo2, yo2);
partitionedModel = crossval(trainedModel.RegressionGP, 'KFold', 5);
zoe0 = kfoldPredict(partitionedModel);
residualoe0= yo2-zoe0;
TMe640=trainedModel; %save model
resper = 100*k2 / max(residualoe0);

% Identify
[I J] = size(residualoe0);
for i=1:I
  if  zoe0(i) - yo2(i)*(1+k2)  >= 0  oids2(i) = 1; else oids2(i) = 0; end
 end
idr2=find(oids2);

% Remove
idremove2=flip(idr2);
idremove2=idremove2';
for j=1:length(idremove2)
  xo2b(j,:) = xo(idremove2(j),:);
  yo2b(j) = yo(idremove2(j));
end
for j=1:length(idremove2)
   xo2(idremove2(j),:) = [];
   yo2(idremove2(j)) = [];
end
yo2b=yo2b';
toc
%***************************************************************************************

%xcal1=xo; 
%ycal1=yo; 
xcal2=xo2;
ycal2=yo2;
%xcal2=xo3;
%ycal2=yo3;
%*******************************************************************************************

% Save data and parameters
%save('cal_model_res','TMe0');
%save('dat_d1r0c0sPamDC');
%*******************************************************************************************

