load boilerA.mat;
load labl.mat;
load lbl_binary;
data=[kbs_frate,steam_frate,kbs_prss,steam_prss,steam_tmpr];
alldata = data(1:1440*20,:);
% alldata = (data(1:1440*20,:));

j=1;
figure
for i = 1:20
X = alldata(j:j+720/2,:);
input = X(:,1);
output = X(:,2);
mydata = [input,output];
prss = X(:,4);
p1(i,:) = polyfit(input,output,1);
f1(:,i) = polyval(p1(i,:), input);
res1 = polyval(p1(i,:),input)-output;
    if i>=2
    fn(:,i) = polyval(p1(i-1,:), input);
    resn = polyval(p1(i-1,:),input)-mean(output);
    rmsen(i,:) = sqrt(sum(resn.^2)/(length(resn)));
    R(i,:) = sum(resn.^2)/sum((output-mean(output)).^2);
    end
% figure
hold all
plot(input,output,'.'), hold on, plot(input,f1(:,i),'--');
rmse(i,:) = sqrt(sum(res1.^2)/(length(res1)));
R2(i,:) = sum(res1.^2)/sum((output-mean(output)).^2);
[IDX, isnoise]=DBSCAN(mydata,1.3,11);
RealData = table(mydata,IDX);
j = i*720/2;
end
[pks,locs] = findpeaks(rmsen)
 percntiles = prctile(res1,[2.5 97.5]); %5th and 95th percentile
 outlierIndex = res1 < percntiles(1) | res1 > percntiles(2);
 outl = input .* double(outlierIndex);
 t = table(input,output, outlierIndex);
 
 percntiles = prctile(res1,[2.5 97.5]); %5th and 95th percentile
 outlierIndex = res1 < percntiles(1) | res1 > percntiles(2);
 outl = input .* double(outlierIndex);
 t = table(input,output, outlierIndex);
 
 
figure
hold all,plot(input),plot(output), plot(outl,'k+')
figure
plot(alldata(1:7200,1),'r'), hold on, plot(alldata(1:7200,2),'b');
figure
hist(alldata(1:7200,1),600),hold all,hist(alldata(1:7200,2),600)

% [X,Y] = meshgrid(res1,res1);
% Z = peaks(res1);
% figure
% surf(X,Y,Z);
% contour(X,Y,Z,10)
 
 %  SEM = std(res1)/sqrt(length(res1));               % Standard Error
% ts = tinv([0.025  0.975],length(res1)-1);      % T-Score
% CI = mean(res1) + ts*SEM;    
% figure
% plot(input, res1,'r*')
% hist(res1,30)

%%