107506 Laboratório de Controle de Processos

29
107506– Laboratório de Controle de Processos Prof. Eduardo Stockler Tognetti Departamento de Engenharia Elétrica Universidade de Brasília 1º Semestre 2020 Aula: Simulink Extração de Dados e S – Functions

Transcript of 107506 Laboratório de Controle de Processos

Page 1: 107506 Laboratório de Controle de Processos

107506– Laboratório de Controle de Processos

Prof. Eduardo Stockler Tognetti

Departamento de Engenharia Elétrica

Universidade de Brasília

1º Semestre 2020

Aula: Simulink Extração de Dados e S – Functions

Page 2: 107506 Laboratório de Controle de Processos

Extraindo Dados do Simulink

• Blocos: – Scope

– To Workspace...

– To File...

• Parâmetros – Path

– File name & Variable name

– Sample Time

– Estrutura: Array; Structure; Structure w/ Time; Time Series

Page 3: 107506 Laboratório de Controle de Processos

Exemplo

Atenção: cada vez que o Simulink é executado (“Run” ) os dados no Workspace e o arquivo são substiuídos!

Path:

Page 4: 107506 Laboratório de Controle de Processos

Blocos de Extração de dados do Simulink

Page 5: 107506 Laboratório de Controle de Processos

Manipulando Dados do Simulink no Matlab

• Lendo os dados do arquivo: >> load('arquivo.mat')

– Ex:

• Manipulando arrays – Vetor tempo: t = varout1(1,:);

– Vetor dados: x = varout1(2,:); y = varout1(3,:);

– Gráfico: plot(t,x,’r’); hold on; plot(t,y,’r’); hold off;

Page 6: 107506 Laboratório de Controle de Processos

Manipulando Dados do Simulink no Matlab

• Lendo os dados do arquivo: >> load('arquivo.mat')

– Ex:

• Manipulando Structure’s

>> t = varout2.time; >> x1 = varout2.signals.values(:,1); >> x2 = varout2.signals.values(:,2); >> x3 = varout2.signals.values(:,3); >> x4 = varout2.signals.values(:,4); >> figure; >> plot(t,x1,’r’);

Page 7: 107506 Laboratório de Controle de Processos

Manipulando Dados do Simulink no Matlab

• Manipulando Timeseries:

>> t = varout3.Time;

>> x = varout3.Data;

>> whos

>> x1 = x(:,1); x2 = x(:,2);

>> x3 = x(:,3); x4 = x(:,4);

>> plot(t,x1,'r',t,x2,'b'); grid;

Page 8: 107506 Laboratório de Controle de Processos

Simulando sistemas dinâmicos via “S-functions”

Page 9: 107506 Laboratório de Controle de Processos

S-functions (system-functions)

• Forma de descrever sistemas dinâmicos

• Linguagens: Matlab ou C (MEX-files)

• Permite adicionar algoritmos a modelos Simulink

• Pode descrever sistemas contínuos, discretos ou hibrídos

Page 10: 107506 Laboratório de Controle de Processos

Usando S-functions

Page 11: 107506 Laboratório de Controle de Processos

Usando S-functions

Exemplo com múltiplas entradas.

Exemplo com uma entrada.

Page 12: 107506 Laboratório de Controle de Processos

Exemplo

Page 13: 107506 Laboratório de Controle de Processos

Script “sfunctionname.m” function[sys, xo] = sfunctionname(t, x, u, flag)

% function [sys, init. cond.] = file-name(time,states,inputs,flag)

if flag == 1 % Derivatives of the state variable

sys(1) = -0.3*sqrt(x(1))+3*u(1); %dx(1)/dt = -0.3* ...

elseif flag == 3 % Calculate outputs

sys = x; % output 1 = x(1)

elseif flag == 0 % Initialize:

%[# continuous states, # discrete states, # outputs, # inputs ]

%[# direct feedtrough: deve ser 1 se u usado em flag=3

%[# sample time (for discrete-time systems)]

sys = [1 0 1 1 0 0];

xo = [9]; % Initial condition for states xo=[x1(0); x2(0); ...]

else

sys =[];

end

end

Page 14: 107506 Laboratório de Controle de Processos

• S-Function com 2 entradas e 3 saídas

Usando S-functions

• Bloco S-function Nome da função

(arquivo .m)

[Opcional] Parâmetros

(ex.: cond. Inicial)

Page 15: 107506 Laboratório de Controle de Processos

Script “sfuntank1.m” function [sys, xo] = sfuntank1(t, x, u, flag)

% function [sys, init. cond.] = file-name(time,states,inputs,flag)

A = 50; % Parameters

if flag == 1 % Derivatives of the state variables

Fin1 = u(1); Fin2 = u(2); % Inputs

h1 = x(1); h2 = x(2); % States

f12 = sign(h1-h2)*5*sqrt(abs(h1-h2));

sys(1) = 1/(A)*(0.5*Fin1 - 5*sqrt(max([0 h1])) -f12); %dx1/dt

sys(2) = 1/(A)*(0.5*Fin2 - 5*sqrt(max([0 h2])) +f12); %dx2/dt

elseif flag == 3 % Calculate outputs

sys(1) = x(1); % output 1: h1

sys(2) = x(2); % output 2: h2

sys(3) = sign(x(1)-x(2))*5*sqrt(abs(x(1)-x(2)));%output3: f12

elseif flag == 0 % Initialize:

%[# continuous states, # discrete states, # outputs, # inputs ]

%[# direct feedtrough: deve ser 1 se u usado em flag=3

%[# sample time (for discrete-time systems)]

sys = [2 0 3 2 0 0];

xo = [40 60]; % Initial condition for states xo=[x1(0) x2(0)]

else

sys =[];

end

end

Page 16: 107506 Laboratório de Controle de Processos

Exemplo de sistema em malha fechada

Page 17: 107506 Laboratório de Controle de Processos

Função de transferência

Implementação da função de transferência de um atuador ou transmissor.

Page 18: 107506 Laboratório de Controle de Processos

Controlador

Controlador PI com anti-windup.

Controlador PI.

Page 19: 107506 Laboratório de Controle de Processos

PID com anti-windup

Page 20: 107506 Laboratório de Controle de Processos

Estrutura e argumentos de S-functions

Page 21: 107506 Laboratório de Controle de Processos

S-functions: inputs arguments

• (1) t - the time variable • (2) x - the column-vector of

state variables • (3) u - the column-vector of

input variables (whose value will come from other Simulink blocks)

• (4) flag - indicator of which group of information and/or calculations is being requested by Simulink.

• (5) Cinit,Tinit - additional supplied parameters

Page 22: 107506 Laboratório de Controle de Processos

S-functions: outputs arguments

• (1) sys - the main vector of results requested by Simulink.

Only when flag=0: • (2) x0 - column vector of initial

conditions. • (3) str - need to be set to null.

This is reserved for use in future versions of

• Simulink. • (4) ts - an array of two columns

to specify sampling time and time offsets. Since our example will deal only with continuous systems, this will be set to [0 0] during initiation phase.

Page 23: 107506 Laboratório de Controle de Processos

S-functions: structure

Page 24: 107506 Laboratório de Controle de Processos

• Simulando sistemas dinâmicos com S-functions

Exemplo de aplicação de S-functions.

S-functions: exemplo

Page 25: 107506 Laboratório de Controle de Processos

S-functions: exemplo function [sys, x0] = sftank(t,x,u,flag,par) %function [sys, x0] = sftank(t,x,u,flag,par) % dh/dt = (fi-K*sqrt(h))/(rho*A); % h(t0) = h0; % parameters: k, rho % inputs: fi % outputs: h, f0=K*sqrt(h) if ~exist('par') par = [1 1 .2 100]; % Valores padrão dos parâmetros end % Parâmetros K = par(1); %kg m^-0,5 s^-1 ro = par(2); %kg/m^3 A = par(3); %m^2 h0 = par(4); %m switch flag case 0 x0 = h0; % Condições iniciais sys = [1 0 2 1 0 0]'; % Tamanho dos vetores: 2 saídas, 1 entrada % sys = %estados contínuos = 1 %estadosdiscretos = 0 %saídas = 2 %entradas = 1

%raizes continuas. reservado deve ser 0 %direct feedtrough deve ser 1 se u usado em flag=3 %sample times = 0 %str=[]; % ts Matriz com duas colunas contendo o intervalo de amostragem, ts = [-2 0]; %tempo de amostragem variável %Se sys(6)=1, declarar ts = [0 0]; %Exemplo: sys = [1 0 2 1 0 1]'; ts = [0 0]; str=[]; case 1 if x >= 0, fs = K*sqrt(x); else fs = 0; end sys = (u-fs)/(ro*A); % EDO do sist. case 3 if x >= 0, fs = K*sqrt(x); else fs = 0; end sys(1) = x; % h (nível do tanque) sys(2) = fs; % Fs (vazão de saída) case {1, 2, 4, 9} %case {2, 4, 9} % 2:discrete % 4:calcTimeHit % 9:termination sys = []; % Não utilizar flags otherwise error(['unhandled flag =',num2str(flag)]) ; end

Page 26: 107506 Laboratório de Controle de Processos

Exemplo: coluna de destilação

Page 27: 107506 Laboratório de Controle de Processos

Arquivo Distillation.m function [sys, xo] = Distillation(t, x, u, flag) % t = time (independent) variable; x = state variable vector % u = input variable vector % flag (See below. Set by Simulink according to the stage of the problem) % % Binary distillatin column with 6 equilibrium stages, feed on stage 4 % Equimolal overflow, constant relative volatility, constant pressure xL = zeros(1,6); y = zeros(1,6); % Set problem constants here Alpha = 2.46; % Relative volatility LambdaV = 13860; % Latent heat of vapors, BTU/lbmole LambdaS = 952; % Latent heat of steam, BTU/lb (sat.15 psig steam) Mi = 450; % Tray hold-up, lbmoles MDmin = 50; % minimum accumulator hold-up, lbmoles MDmax = 550; % maximum accumulator hold-up, lbmoles MBmin = 100; % minimum bottoms hold-up, lbmoles MBmax = 1100; % maximum bottoms hold-up, lbmoles if flag == 1 % Calculation of the derivatives of the state variables % Input variables Feed = u(1)/60; % Feed rate, lbmoles/min xF = u(2); % Feed mole fraction q = u(3); % Feed fraction liquid Lr = u(4)/60; % Reflux flow, lbmoles/min D = u(5)/60; % Distillate rate, lbmoles/min Ws = u(6)/60; % Steam flow to reboiler, lb/min B = u(7)/60; % Bottoms flow, lbmoles/min % Initial calculations Ls = Lr + q*Feed; % stripping liquid flow, lbmoles/min Vs = Ws*LambdaS/LambdaV; % stripping vapor rate, lbmoles/min Vr = Vs + (1-q)*Feed; % rectifying vapor rate, lbmoles/min

% State variables for i = 1:6 xL(i) = x(i); y(i) = Alpha*xL(i)/(1+(Alpha - 1)*xL(i)); end xD = x(7); xB = x(8); MD = x(9); MB = x(10); yB = Alpha*xB/(1+(Alpha - 1)*xB); % Calculate the derivatives sys(i) = dx(i)/dt of the state variables sys(1) = (Lr*(xD - xL(1)) + Vr*(y(2) - y(1)))/Mi; % Stage 1 sys(2) = (Lr*(xL(1) - xL(2)) + Vr*(y(3) - y(2)))/Mi; % Stage 2 sys(3) = (Lr*(xL(2) - xL(3)) + Vr*(y(4) - y(3)))/Mi; % Stage 3 sys(4) = (Lr*xL(3) + Feed*xF - Ls*xL(4) + Vs*y(5) - Vr*y(4))/Mi; % Feed stg sys(5) = (Ls*(xL(4) - xL(5)) + Vs*(y(6) - y(5)))/Mi; % Stage 5 sys(6) = (Ls*(xL(5) - xL(6)) + Vs*(yB - y(6)))/Mi; % Stage 6 sys(7) = Vr*(y(1) - xD)/MD; % Distillate mole fraction sys(8) = (Ls*(xL(6) - xB) - Vs*(yB - xB))/MB; % Bottoms mole fraction sys(9) = Vr - Lr - D; % Accumulator hold-up sys(10) = Ls - Vs - B; % Bottoms hold-up elseif flag == 3 % Calculate outputs sys(1) = x(7); % Distillate mole fraction sys(2) = x(8); % Bottoms mole fraction Dlevel = (x(9) - MDmin)/(MDmax - MDmin)*100; %TO accmulator level Dlevel = min( [Dlevel 100] ); sys(3) = max ( [Dlevel 0] ); Blevel = (x(10) - MBmin)/(MBmax - MBmin)*100; %TO bottoms level Blevel = min( [Blevel 100] ); sys(4) = max( [Blevel 0] ); elseif flag == 0 % Initialize: [# cont.states, # disc.states=0, sys = [10, 0, 4, 7, 0, 0]; % # outputs, # inputs ] MDo = MDmin + 0.5*(MDmax - MDmin); % Initial hold-up for level at 50%TO MBo = MBmin + 0.5*(MBmax - MBmin); % Initial compositions and hold-ups xo = [0.8274,0.7037,0.5703,0.4524,0.3188,0.19285,0.9206,0.09929,MDo,MBo]; else sys =[]; end

Page 28: 107506 Laboratório de Controle de Processos

S-function template (sfuntemplate.m) - Extra function [sys,x0,str,ts,simStateCompliance] = sfuntemplate(t,x,u,flag)

%SFUNTMPL General MATLAB S-Function Template

% With MATLAB S-functions, you can define you own ordinary differential

% equations (ODEs), discrete system equations, and/or just about

% any type of algorithm to be used within a Simulink block diagram.

%

% The general form of an MATLAB S-function syntax is:

% [SYS,X0,STR,TS,SIMSTATECOMPLIANCE] = SFUNC(T,X,U,FLAG,P1,...,Pn)

%

% What is returned by SFUNC at a given point in time, T, depends on the

% value of the FLAG, the current state vector, X, and the current

% input vector, U.

%

% FLAG RESULT DESCRIPTION

% ----- ------ --------------------------------------------

% 0 [SIZES,X0,STR,TS] Initialization, return system sizes in SYS,

% initial state in X0, state ordering strings

% in STR, and sample times in TS.

% 1 DX Return continuous state derivatives in SYS.

% 2 DS Update discrete states SYS = X(n+1)

% 3 Y Return outputs in SYS.

% 4 TNEXT Return next time hit for variable step sample

% time in SYS.

% 5 Reserved for future (root finding).

% 9 [] Termination, perform any cleanup SYS=[].

%

%

% The state vectors, X and X0 consists of continuous states followed

% by discrete states.

%

% Optional parameters, P1,...,Pn can be provided to the S-function and

% used during any FLAG operation.

%

% When SFUNC is called with FLAG = 0, the following information

% should be returned:

%

% SYS(1) = Number of continuous states.

% SYS(2) = Number of discrete states.

% SYS(3) = Number of outputs.

% SYS(4) = Number of inputs.

% Any of the first four elements in SYS can be specified

% as -1 indicating that they are dynamically sized. The

% actual length for all other flags will be equal to the

% length of the input, U.

% SYS(5) = Reserved for root finding. Must be zero.

% SYS(6) = Direct feedthrough flag (1=yes, 0=no). The s-function

% has direct feedthrough if U is used during the FLAG=3

% call. Setting this to 0 is akin to making a promise that

% U will not be used during FLAG=3. If you break the promise

% then unpredictable results will occur.

% SYS(7) = Number of sample times. This is the number of rows in TS.

%

%

% X0 = Initial state conditions or [] if no states.

%

% STR = State ordering strings which is generally specified as [].

%

% TS = An m-by-2 matrix containing the sample time

% (period, offset) information. Where m = number of sample

% times. The ordering of the sample times must be:

%

% TS = [0 0, : Continuous sample time.

% 0 1, : Continuous, but fixed in minor step

% sample time.

% PERIOD OFFSET, : Discrete sample time where

% PERIOD > 0 & OFFSET < PERIOD.

% -2 0]; : Variable step discrete sample time

% where FLAG=4 is used to get time of

% next hit.

%

% There can be more than one sample time providing

% they are ordered such that they are monotonically

% increasing. Only the needed sample times should be

% specified in TS. When specifying more than one

% sample time, you must check for sample hits explicitly by

% seeing if

% abs(round((T-OFFSET)/PERIOD) - (T-OFFSET)/PERIOD)

% is within a specified tolerance, generally 1e-8. This

% tolerance is dependent upon your model's sampling times

% and simulation time.

%

% You can also specify that the sample time of the S-function

% is inherited from the driving block. For functions which

% change during minor steps, this is done by

% specifying SYS(7) = 1 and TS = [-1 0]. For functions which

% are held during minor steps, this is done by specifying

% SYS(7) = 1 and TS = [-1 1].

%

% SIMSTATECOMPLIANCE = Specifices how to handle this block when saving and

% restoring the complete simulation state of the

% model. The allowed values are: 'DefaultSimState',

% 'HasNoSimState' or 'DisallowSimState'. If this value

% is not speficified, then the block's compliance with

% simState feature is set to 'UknownSimState'.

% Copyright 1990-2010 The MathWorks, Inc.

% $Revision: 1.18.2.5 $

%

% The following outlines the general structure of an S-function.

%

switch flag,

%%%%%%%%%%%%%%%%%%

% Initialization %

%%%%%%%%%%%%%%%%%%

case 0,

[sys,x0,str,ts,simStateCompliance]=mdlInitializeSizes;

%%%%%%%%%%%%%%%

% Derivatives %

%%%%%%%%%%%%%%%

case 1,

sys=mdlDerivatives(t,x,u);

%%%%%%%%%%

% Update %

%%%%%%%%%%

case 2,

sys=mdlUpdate(t,x,u);

%%%%%%%%%%%

% Outputs %

%%%%%%%%%%%

case 3,

sys=mdlOutputs(t,x,u);

%%%%%%%%%%%%%%%%%%%%%%%

% GetTimeOfNextVarHit %

%%%%%%%%%%%%%%%%%%%%%%%

case 4,

sys=mdlGetTimeOfNextVarHit(t,x,u);

%%%%%%%%%%%%%

% Terminate %

%%%%%%%%%%%%%

case 9,

sys=mdlTerminate(t,x,u);

%%%%%%%%%%%%%%%%%%%%

% Unexpected flags %

%%%%%%%%%%%%%%%%%%%%

otherwise

DAStudio.error('Simulink:blocks:unhandledFlag', num2str(flag));

end

% end sfuntmpl

%

%=============================================================================

% mdlInitializeSizes

% Return the sizes, initial conditions, and sample times for the S-function.

%=============================================================================

%

function [sys,x0,str,ts,simStateCompliance]=mdlInitializeSizes

%

% call simsizes for a sizes structure, fill it in and convert it to a

% sizes array.

%

% Note that in this example, the values are hard coded. This is not a

% recommended practice as the characteristics of the block are typically

% defined by the S-function parameters.

%

sizes = simsizes;

sizes.NumContStates = 0;

sizes.NumDiscStates = 0;

sizes.NumOutputs = 0;

sizes.NumInputs = 0;

sizes.DirFeedthrough = 1;

sizes.NumSampleTimes = 1; % at least one sample time is needed

sys = simsizes(sizes);

%

% initialize the initial conditions

%

x0 = [];

%

% str is always an empty matrix

%

str = [];

%

% initialize the array of sample times

%

ts = [0 0];

% Specify the block simStateCompliance. The allowed values are:

% 'UnknownSimState', < The default setting; warn and assume DefaultSimState

% 'DefaultSimState', < Same sim state as a built-in block

% 'HasNoSimState', < No sim state

% 'DisallowSimState' < Error out when saving or restoring the model sim state

simStateCompliance = 'UnknownSimState';

% end mdlInitializeSizes

%

%=============================================================================

% mdlDerivatives

% Return the derivatives for the continuous states.

%=============================================================================

%

function sys=mdlDerivatives(t,x,u)

sys = [];

% end mdlDerivatives

%

%=============================================================================

% mdlUpdate

% Handle discrete state updates, sample time hits, and major time step

% requirements.

%=============================================================================

%

function sys=mdlUpdate(t,x,u)

sys = [];

% end mdlUpdate

%

%=============================================================================

% mdlOutputs

% Return the block outputs.

%=============================================================================

%

function sys=mdlOutputs(t,x,u)

sys = [];

% end mdlOutputs

%

%=============================================================================

% mdlGetTimeOfNextVarHit

% Return the time of the next hit for this block. Note that the result is

% absolute time. Note that this function is only used when you specify a

% variable discrete-time sample time [-2 0] in the sample time array in

% mdlInitializeSizes.

%=============================================================================

%

function sys=mdlGetTimeOfNextVarHit(t,x,u)

sampleTime = 1; % Example, set the next hit to be one second later.

sys = t + sampleTime;

% end mdlGetTimeOfNextVarHit

%

%=============================================================================

% mdlTerminate

% Perform any end of simulation tasks.

%=============================================================================

%

function sys=mdlTerminate(t,x,u)

sys = [];

% end mdlTerminate

Page 29: 107506 Laboratório de Controle de Processos

Bibliografia

• Simulink dynamic system simulation for Matlab, Writing S-functions

• C. A. Smith e A. Corripio, Príncipios e Prática do Controle Automático de Processo, 3ª. Edição, Ed. LTC, 2012.