function xdot=f(t,x)
% This is file nonlin.m
% Test of how PI control works on nonlinear process
% Last updated on 12Jun02.
% In fact, at ys=2, the new operating point is unstable,
% and there is a MSS (u=0.27 gives both y=0.4 and y=2).
% Usage:  
% ys=1.0;Kc=0.5; Ki=0.5; global ys Kc Ki; 
% [T,Y]=  ode15s('nonlinpi',[1 10],[0 0]); t1=T; y1=Y(:,1); plot(T,Y)
% SEE end of file for how to generate figure in Bio-presentation


% Data
global ys Kc Ki;


% Extract states
y = x(1);
ei= x(2);

% PI controller (computes y from u)
e = y - ys;
ucl = -Kc*e - Ki*ei; uol=ys*exp(-ys);
u=ucl;

% process (gives y from u)
k=exp(y); tau1=1;
dydt = (k*u - y)/tau1;

% Derivatives

xdot = [dydt; e];

% ys=1; [T,Y]=  ode15s('nonlinpi',[1 10],[0 0]); t1=T; y1=Y(:,1); plot(T,Y)
% e=Y(:,1)-ys;ei=Y(:,2);u = -Kc*e - Ki*ei; u1=u; % To plot inputs afterwards
% ys=2; [T,Y]=  ode15s('nonlinpi',[10 20],[1 ei(length(ei))]); t2=T; y2=Y(:,1); plot(T,Y)
% e=Y(:,1)-ys;ei=Y(:,2);u = -Kc*e - Ki*ei; u2=u; % To plot inputs afterwards
% ys=5; [T,Y]=  ode15s('nonlinpi',[20 30],[2 ei(length(ei))]); t3=T; y3=Y(:,1); plot(T,Y)
% e=Y(:,1)-ys;ei=Y(:,2);u = -Kc*e - Ki*ei; u3=u; % To plot inputs afterwards
% ys=0; [T,Y]=  ode15s('nonlinpi',[30 40],[5 ei(length(ei))]); t4=T; y4=Y(:,1); plot(T,Y)
% e=Y(:,1)-ys;ei=Y(:,2);u = -Kc*e - Ki*ei; u4=u; % To plot inputs afterwards
%figure(1);plot([0 1],[0 0], 'r',t1, y1, 'r',t2, y2, 'r',t3, y3, 'r',t4, y4, 'r')
%figure(2);plot([0 1],[0 0], 'b',t1,u1, 'b',t2,u2, 'b',t3,u3, 'b',t4,u4,'b')
%
% ys=1; [T,Y]=  ode15s('nonlinpi',[1 10],[0 0]); t1=T; y1=Y(:,1);  u1=ys*exp(-ys);
% ys=2; [T,Y]=  ode15s('nonlinpi',[10 20],[y1(length(y1)) 0]); t2=T; y2=Y(:,1); u2=ys*exp(-ys);
% ys=5; [T,Y]=  ode15s('nonlinpi',[20 30],[y2(length(y2)) 0]); t3=T; y3=Y(:,1); u3=ys*exp(-ys);
% ys=0; [T,Y]=  ode15s('nonlinpi',[30 40],[y3(length(y3)) 0]); t4=T; y4=Y(:,1); u4=ys*exp(-ys);
%figure(1);hold;plot([0 1],[0 0], 'r:',t1, y1, 'r:',t2, y2, 'r:',t3, y3, 'r:',t4, y4, 'r:')
%figure(2);hold;plot([0 1],[0 0],'b:',[1 10],[u1 u1],'b:',[10 20],[u2 u2],'b:',[20 30],[u3 u3],'b:',[30 40],[u4 u4],'b:')
%%%%%
