













Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!














class NomeDaClasse
Type NomeDaVariavel(Modifications); ...
equation
(Equaçoes diferenciais, algébricas e conectores); ...
end NomeDaClasse;
Andressa Apio, MSc. Eng.
elétrica, mecânica, termodinâmica, hidraulica, bioquímica, controle.
In [55]:
In [56]:
Modelar Simular Automatizar Visualizar
Out[55]:
Out[56]:
from IPython.display import Image Image(filename='Figuras/Tabela_classes.png')
from IPython.display import Image Image(filename='Figuras/Tank.png')
In [13]:
Final Run Statistics: Tank Number of steps : 79 Number of function evaluations : 107 Number of Jacobian evaluations : 3 Number of function eval. due to Jacobian eval. : 3 Number of error test failures : 1 Number of nonlinear iterations : 103 Number of nonlinear convergence failures : 0 Solver options:
Solver : CVode Linear multistep method : BDF Nonlinear solver : Newton Linear solver type : DENSE Maximal order : 5 Tolerances (absolute) : 1e- Tolerances (relative) : 0.
Simulation interval : 0.0 - 10.0 seconds. Elapsed simulation time: 0.00923897884938 seconds.
model_Tank.reset() # Reseta-se o modelo sempre que for rodar a simulação de novo.
tempo_final=10; amostragem=0.1;
opts = model_Tank.simulate_options() opts['ncp']= tempo_final/amostragem; res_Tank = model_Tank.simulate(start_time=0.,final_time=tempo_final,options=opts)
In [41]:
In [40]:
h_treal = [] time = res_Tank['time'] model_Tank.reset() # Resetando o modelo para os valores origitais model_Tank.initialize() # Inicializando o experimento opts['CVode_options']['verbosity'] = 50 # Sem output opts['initialize'] = False # Isso quer dizer que o experimento continua de onde el
for i in range(0, int(tempo_final/amostragem)): res_Tankr = model_Tank.simulate(start_time=(time[i]),final_time=(time[i+1]),op if i == 0: # Valor da altura quando t = 0 h_treal.append(res_Tankr['h'][0]) h_treal.append(res_Tankr['h'][-1])
plt.plot(time,res_Tank['h'], '-', time,h_treal, '--') plt.ylabel('altura [m]') plt.xlabel('tempo [s]') plt.legend(['normal', 'tempo real']) plt.grid()
In [8]:
%%file modelTankSeries.mo
package modelTankSeries
connector ReadLevel "Reading fluid level" Real val(unit="m"); end ReadSignal;
record TankData parameter Real A=1; parameter Real k=0.2; constant Real g=Modelica.Constants.g_n; end TankData;
function LimVal input Real pMin, pMax, p; output Real pLim; algorithm pLim := if p>pMax then pMax else if p In [58]:
In [60]:
In [9]:
Overwriting modelTankSeries.mo
Out[58]:
Out[60]:
end Sim; end modelTankSeries;
Image(filename='Figuras/3Tank01.png')
Image(filename='Figuras/3Tank02.png')
fmu_name = compile_fmu("modelTankSeries.Sim","modelTankSeries.mo") model_sim = load_fmu(fmu_name)
In [61]:
=
dh dt
Fin −Fout A
outCtr = K (
error + (^) ∫ error dt + T )
1 T
d(error) dt
outCtr = K (
error + ∫
error dt )
1 T
Out[61]:
Image(filename='Figuras/TankPID.png')
In [62]:
In [63]:
Out[62]:
Out[63]:
Image(filename='Figuras/TankPID01.png')
Image(filename='Figuras/TankPID02.png')
In [3]:
%%file TankPID.mo
connector LiquidFlow "Vazão de líquido nas entradas e saídas" Real lflow(unit="m3/s"); end LiquidFlow;
connector ReadSignal "Leitura do nível do fluido" Real val(unit="m"); end ReadSignal;
connector ActSignal "Sinal para o atuador para ajustar a posição da válvula" Real act; end ActSignal;
function LimitValue input Real pMin; input Real pMax; input Real p; output Real pLim; algorithm pLim := if p>pMax then pMax else if p150 then 3*flowLevel else flowLevel; end LiquidSource;
partial model BaseController parameter Real Ts=0.1; //“Periodo de tempo entre as amostras discretas” parameter Real K=2; // “Ganho” parameter Real T=10; // “Constante de tempo” ReadSignal cIn; // “Entrada do sensor de nivel, conector” ActSignal cOut; //“Controle para atuador, conector” parameter Real ref; // “Nivel de referencia” Real error; // “Desvio do nivel de referencia” Real outCtr; // “Saida do sinal do controlador” equation error = ref-cIn.val;
cOut.act = outCtr; end BaseController;
model PIDcontinuousController extends BaseController(K=2,T=10); Real x; // Variavel de estado do controlador PID continuo Real y; // Variavel de estado do controlador PID continuo equation der(x) = error/T; y = Tder(error); outCtr = K(error + x + y); end PIDcontinuousController;
model PIcontinuousController extends BaseController(K=2,T=10); Real x; // Variavel de estado do controlador PID continuo equation der(x) = error/T; outCtr = K*(error + x); end PIcontinuousController;
model Tank ReadSignal tSensor; // “Conector, sensor lendo o nivel do tanque (m)” ActSignal tActuator; // “Conector, atuador controlando entrada da vazao” LiquidFlow Fin; //“Conector, vazao (m3/s) atraves da valvula de entrada” LiquidFlow Fout; // “Conector, vazao (m3/s) atraves da valvula de saida” parameter Real area(unit="m2") = 0.5; parameter Real flowGain(unit="m2/s") = 0.05; parameter Real minV=0, maxV=10; // Limites para a saida da vazao da valvula Real h(start=0.0, unit="m"); //"Nivel do tanque"; equation assert (minV>=0,"minV valor minimo da valvula deve ser >= 0"); der(h)=(Fin.lflow-Fout.lflow)/area;// Mass balance equation Fout.lflow = LimitValue(minV,maxV,
model TankPID LiquidSource source(flowLevel=0.02); PIDcontinuousController pidContinuous(ref=0.25); Tank tank(area=1); equation connect(source.Fout, tank.Fin); connect(tank.tActuator, pidContinuous.cOut);
In [7]:
(https://bokeh.pydata.org) Loading BokehJS ...
from bokeh.models.widgets import Panel, Tabs from bokeh.io import output_notebook, show from bokeh.plotting import figure from bokeh.models import HoverTool
output_notebook() hover = HoverTool(tooltips=[("(x,y)", "($x, $y)")]) p1 = figure(plot_width=600, plot_height=400,tools=[hover]) p1.line(resPID['time'],resPID['tank.h'], legend="Simulado PID", line_width=2,colo p1.line(resPID['time'],resPID['pidContinuous.ref'], legend="Set point PID", line_w p1.line(resPI['time'],resPI['tank.h'], line_dash=(4, 4), legend="Simulado PI", li p1.line(resPI['time'],resPI['pidContinuous.ref'],line_dash=(4, 4), legend="Set poi p1.legend.click_policy="hide" p1.yaxis.axis_label = "Altura [m]" p1.xaxis.axis_label = "Tempo [s]" tab1 = Panel(child=p1, title="PV")
p2 = figure(plot_width=600, plot_height=400,tools=[hover]) p2.line(resPID['time'],resPID['tank.Fin.lflow'], legend="Entrada PID", line_width= p2.line(resPID['time'],resPID['tank.Fout.lflow'], legend="Saída PID", line_width= p2.line(resPI['time'],resPI['tank.Fin.lflow'],line_dash=(4, 4), legend="Entrada PI p2.line(resPI['time'],resPI['tank.Fout.lflow'], line_dash=(4, 4), legend="Saída PI p2.legend.click_policy="hide" p2.yaxis.axis_label = "Vazão [m³/s]" p2.xaxis.axis_label = "Tempo [s]" tab2 = Panel(child=p2, title="MV")
tabs = Tabs(tabs=[ tab1, tab2 ])
show(tabs)
In [66]:
In [59]:
In [60]:
Out[66]:
Image(filename='Figuras/Tank_est.png')
import numpy as np import nlopt
par = ['k'] # Parâmetro a ser estimado lolim=[-100] # Limite inferior uplim=[100] # Limite superior guess = [50] # Chute inicial t_exp= np.hstack(res_Tank['time']); # Valores experimentais h_exp = np.hstack(res_Tank['h'])+ 0.05np.mean(res_Tank['h'])np.random.randn(len(
fmu_Tank = compile_fmu("Tank","modelTank.mo",version ='2.0' , compiler_log_level=" compiler_options = {'generate_block_jacobian':True,'generate_ode_jacobian':True}) model_Tank = load_fmu(fmu_Tank)
In [65]:
In [33]:
Out[65]:
Out[33]:
matrix([[-0.65418972]])
plt.plot(t_exp,h_exp, 'b:', res_['time'],res_['h'],'r-') plt.legend(['Experimental','Simulado']) plt.grid() plt.ylabel('altura [m]') plt.xlabel('tempo [s]')
[a,b,c,d] = model_Tank.get_state_space_representation(A=True, B=False, C=True, D=F A = np.matrix(a.toarray()) A
In [34]:
In [35]:
https://openmodelica.org/useresresources/modelica-courses (https://openmodelica.org/useresresources/modelica-courses);
WARNING:root:The sensitivity parameters must be specified as inputs inorder to se t up the sensitivity equations using directional derivatives. Disabling and using finite differences instead.
Out[35]:
model_Tank.reset() opts = model_Tank.simulate_options() opts['sensitivities'] = ['A'] opts['CVode_options']['verbosity'] = 50 # Sem output res = model_Tank.simulate(start_time=0.,final_time=10,options=opts)
plt.plot(res['time'],res['dh/dA'],'m-') plt.grid() plt.ylabel('altura [m]') plt.xlabel('area [m2]')