function demo_hill_valley()
fstr='Hill_Valley_without_noise_Training.data';
[P,z]=read_data(fstr);
[n d]=size(P);
rescale=max(max(abs(P)));
A=P/rescale;
h_no=6;v_no=5;
a_hill=P(h_no,:)/max(P(h_no,:));
a_valley=P(v_no,:)/max(P(v_no,:));
figure;subplot(2,1,1);plot(1:d,a_hill);title('a hill template');hold on
subplot(2,1,2);plot(1:d,a_valley);title('a valley template');
tau = 5;
% prepare paired data for modeling a hill
[x y]=moving_win(a_hill,tau);

% training an MLP network
M=10;
[E,NetDef,W1,W2]=noisecan(x,y',M);
[Y_sim,E,PI] = nneval(NetDef,W1,W2, x', y,1); 
fprintf('\n training mse %f\n',mean((Y_sim-y).^2)); 
figure;title('learning a hill,green:app, red:err');hold on;
plot(1+tau:d,y,'b');plot(1+tau:d,Y_sim,'g');plot(1+tau:d,y-Y_sim,'r');
NNH.NetDef = NetDef; NNH.W1=W1; NNH.W2=W2;
% prepare paired data for modeling a valley 
[x y]=moving_win(a_valley,tau);
% training an MLP network
M=10;
[E,NetDef,W1,W2]=noisecan(x,y',M);
[Y_sim,E,PI] = nneval(NetDef,W1,W2, x', y,1); 
fprintf('\n training mse %f\n',mean((Y_sim-y).^2)); 
figure;title('learning a hill,green:app, red:err');hold on;
plot(1+tau:d,y,'b');plot(1+tau:d,Y_sim,'g');plot(1+tau:d,y-Y_sim,'r');
NNV.NetDef = NetDef; NNV.W1=W1; NNV.W2=W2;
% Parsing
for i=1:n
    pattern=P(i,:)/max(P(i,:));
    [x y]=moving_win(pattern,tau);
    [Y_sim,E,PI] = nneval(NNH.NetDef,NNH.W1,NNH.W2, x', y,1); 
    err_H(i)=mean((Y_sim-y).^2);
    [Y_sim,E,PI] = nneval(NNV.NetDef,NNV.W1,NNV.W2, x', y,1); 
    err_V(i)=mean((Y_sim-y).^2);
end
figure; hold on
ind=find(z==0);
plot(err_V(ind),err_H(ind),'r.')
fprintf('%d valleys, %d patterns with smaller errrors parsed by valley_model\n',length(ind),sum(err_V(ind) < err_H(ind)));
ind=find(z==1);
plot(err_V(ind),err_H(ind),'b.')
fprintf('%d hill, %d patterns with smaller errrors parsed by hill_model\n',length(ind),sum(err_V(ind) > err_H(ind)));
title('red:valley, blue:hill') 

fstr='Hill_Valley_without_noise_Testing.data';
[B,testy]=read_data(fstr);
B=B/rescale;
for k=1:1
for i=1:size(B,1)
    x=B(i,:);
    c(i)=Nearest_C(A,y,x);
end
hit(k)=sum(c==testy)
rate(k)=hit(k)/size(testy,2)
end
hist(rate);

function [x y]=moving_win(pattern,tau)
d=length(pattern);
x=[];y=[];
for i=tau+1:d
    x=[x; pattern(i-tau:i-1)];
    y=[y pattern(i)];
end


