% Neural Fuzzy Model to Simulate
% neurofuz.m
clc;clear;clg;clf;
% ----------- GENERATE TRAINING DATA MATRIX
%y(1)=0.1;
%y(2)=0.01;
%for t=3:1500;
%    y(t)=(0.8-0.5*exp(-y(t-1)^2))*y(t-1)-(0.3+0.9*exp(-y(t-1)^2))*...
%         y(t-2)+0.1*sin(pi*y(t-1))+0.1*randn(1.0);
%end
%x=[y(1),y(2)];
%for t=4:1500;
%    x=[x;y(t-2),y(t-1)];
%end 
%i=1:1498;
%d(i)=y(i+2); 
%TrainData = [x d'];

% ----------- GENERATE CHECKING DATA MATRIX
%y1(1)=0.2;
%y1(2)=0.5;
%for t=3:1500;
%    y1(t)=(0.8-0.5*exp(-y1(t-1)^2))*y1(t-1)-(0.3+0.9*exp(-y1(t-1)^2))*...
%         y1(t-2)+0.1*sin(pi*y1(t-1))+0.1*randn(1.0);
%end
%x1=[y1(1),y1(2)];
%for t=4:1500;
%    x1=[x1;y1(t-2),y1(t-1)];
%end 
%i=1:1498;
%d1(i)=y1(i+2); 

load d:\matlab\testhw\check.dat;
load d:\matlab\testhw\tran.dat;
CHK_DATA = check;
TrainData = tran;
x=TrainData(:,1:3);
d=TrainData(:,4);
x1= CHK_DATA(:,1:3);
d1= CHK_DATA(:,4);
%CHK_DATA = [x1 d1'];

%--------- initial time
t0 = clock;

% --------------- GENERATE INITIAL FIS MATRIX
 NumMfs = 4;
 MfType = 'gbellmf';
 InputFismat = genfis1(TrainData, NumMfs, MfType);

% ---------------- TRAINING OPTIONS
 NumEpochs = 100;
 error_goal=0;
 ss = 0.1;
 ss_dec_rate=0.5;
 ss_inc_rate=1.5;

% ---------------- start ANFIS trainig
 [trn_out_fismat trn_error step_size chk_out_fismat chk_error] = ...
             anfis(TrainData, InputFismat, ...
             [NumEpochs error_goal ss ss_dec_rate ss_inc_rate],...
             [1 0 0 1],CHK_DATA);

% ------caculate using time
using_time = etime(clock,t0)

% ---------------- Output Caculation for Training Data
 yy = evalfis(x, trn_out_fismat);
 figure(1);
 j=1000:1100;
 plot(j,d(j),'-', j, yy(j), '-.');
 xlabel('Time (sec)');ylabel('y(t)');
 legend('Training Data', 'ANFIS Output');

% ---------------- Output Caculation for Checking Data
 dd = evalfis(x1, chk_out_fismat);
 figure(2);
 j=150:250;
 plot(j,d1(j),'-', j, dd(j), '-.');
 xlabel('Time (sec)');ylabel('y(t)');
 legend('Checking Data', 'ANFIS Output');
OutputFismat = anfis(TrainData, InputFismat, [NumEpochs nan step_size]);
writefis(OutputFismat,'nerofuz.dat');
% ====== plot initial and final MFs on brand, voltage , interval  
figure(3);
subplot(2,3,1);
plotmf(InputFismat, 'input', 1);
title('Initial MFs on brand');

subplot(2,3,2);
plotmf(InputFismat, 'input', 2);
title('Initial MFs on voltage');

subplot(2,3,3);
plotmf(InputFismat, 'input', 3);
title('Initial MFs on interval');

subplot(2,3,4);
plotmf(trn_out_fismat, 'input', 1);
title('Final MFs on brand');

subplot(2,3,5);
plotmf(trn_out_fismat, 'input', 2);
title('Final MFs on voltage');

subplot(2,3,6);
plotmf(trn_out_fismat, 'input', 3);
title('Final MFs on interval');
