%4) Find anomalies in new data sets given previously trained anomaly OCSVM.
%******************************************************************************************

tic
%Run data_anoalyocsvm first to get mdl, x, and anomalies
Xa = xo3; %this is selected in data_anomalyocsvm.mqw Ya=y03
Xn=xind; %select array other than x to test for novelties
Yn=yind; %select array other than x to test for novelties

threshold = Mdl.ScoreThreshold; %comes from data_anomalyocsvm.m
[Nn Mn] = size(Xa);

%object Mdl and returns the logical array tf, whose elements are true when an anomaly is
%detected in the corresponding row of x.n
rng("default") % For reproducibility 
[tfn,sn] = isanomaly(Mdl,Xn,ScoreThreshold= threshold); % A negative score value with large magnitude indicates a normal observation, and a large positive value indicates an anomaly.
figure
histogram(sn, Normalization="probability")
hold on 
histogram(sn,Normalization="probability")
xline(threshold,"k-",join(["Threshold =" threshold ]))
legend("Training data","Test data",Location="southeast")
title("Histograms of Anomaly Scores for One-Class SVM")
hold off

idn = find(tfn);
idn=idn';
NFn = 100*sum(tfn) / Nn

% Remove
%Xn=xo;
xdc2022b=[];
ydc2022b=[];
xdc2022n=Xn;
ydc2022n=Yn;
xo=Xn;
yo=Yn;
idremoven = flip(idn);
J=length(idremoven);
%get outliers and test spectra
idremoven=flip(idn); %remove lines starting from the bottom up 
for j=1:J
  xdc2022b(j,:) = xo(idremoven(j),:);
  ydc2022b(j) = yo(idremoven(j));
end

for j=1:J
   xdc2022n(idremoven(j),:) = [];
   ydc2022n(idremoven(j)) = [];
end
xprd1=xdc2022n;
yprd1=ydc2022n';

Rn = 100*length(idn) / Nn;
toc
%*******************************************************************************************