Difference between revisions of "Dynamic Simulation Tutorial with DWSIM and Python, Part 3: Adding a PID Controller"
Line 259: | Line 259: | ||
<h2><span class="mw-headline" id="Download_File">Download File</span></h2> | <h2><span class="mw-headline" id="Download_File">Download File</span></h2> | ||
<p>Download the simulation file with what has been done so far: [http://dwsim.inforside.com.br/files/dynamic_part3.dwxmz dynamic_part3.dwxmz] | <p>Download the simulation file with what has been done so far: [http://dwsim.inforside.com.br/files/dynamic_part3.dwxmz dynamic_part3.dwxmz] | ||
− | </p><p>Return to [[ | + | </p><p>Return to [[Dynamic Simulation Tutorial with DWSIM and Python, Part 2: Building the Dynamic Model]] |
− | </p><p>Proceeed to [[ | + | </p><p>Proceeed to [[Dynamic Simulation Tutorial with DWSIM and Python, Part 4: Tuning the PID Controller through Non-Linear Optimization]] |
</p> | </p> |
Revision as of 19:33, 1 July 2019
This tutorial requires advanced or above average Python programming skills. |
You'll need at least DWSIM v5.1 on Windows, Linux or macOS to follow/reproduce the tasks within this tutorial. |
Contents
Introduction
We will add a PID Controller to control the outlet hot water temperature (PV) at 50 C (SP) by changing the cooling water flow using the valve opening as the manipulated variable (MV).
The PID class
Our PID code uses a modified version of the Python PID Class which can be found here: https://github.com/ivmech/ivPID
Create a new script and name it 'PID'. Add the following content to it:
#!/usr/bin/python # # This file is part of IvPID. # Copyright (C) 2015 Ivmech Mechatronics Ltd. <bilgi@ivmech.com> # # IvPID is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # IvPID is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # title :PID.py # description :python pid controller # author :Caner Durmusoglu # date :20151218 # version :0.1 # notes : # python_version :2.7 # ============================================================================== import clr from System import DateTime """Ivmech PID Controller is simple implementation of a Proportional-Integral-Derivative (PID) Controller in the Python Programming Language. More information about PID Controller: http://en.wikipedia.org/wiki/PID_controller """ class PID: """PID Controller """ def __init__(self, P=0.2, I=0.0, D=0.0): self.Kp = P self.Ki = I self.Kd = D self.sample_time = 0.00 self.current_time = 0.00 self.last_time = self.current_time self.clear() def clear(self): """Clears PID computations and coefficients""" self.SetPoint = 0.0 self.PTerm = 0.0 self.ITerm = 0.0 self.DTerm = 0.0 self.last_error = 0.0 # Windup Guard self.int_error = 0.0 self.windup_guard = 20.0 self.output = 0.0 def update(self, feedback_value, currentime): """Calculates PID value for given reference feedback .. math:: u(t) = K_p e(t) + K_i \int_{0}^{t} e(t)dt + K_d {de}/{dt} .. figure:: images/pid_1.png :align: center Test PID with Kp=1.2, Ki=1, Kd=0.001 (test_pid.py) """ error = self.SetPoint - feedback_value self.current_time = currentime delta_time = self.current_time - self.last_time delta_error = error - self.last_error if (delta_time >= self.sample_time): self.PTerm = self.Kp * error self.ITerm += error * delta_time if (self.ITerm < -self.windup_guard): self.ITerm = -self.windup_guard elif (self.ITerm > self.windup_guard): self.ITerm = self.windup_guard self.DTerm = 0.0 if delta_time > 0: self.DTerm = delta_error / delta_time # Remember last time and last error for next calculation self.last_time = self.current_time self.last_error = error self.output = self.PTerm + (self.Ki * self.ITerm) + (self.Kd * self.DTerm) def setKp(self, proportional_gain): """Determines how aggressively the PID reacts to the current error with setting Proportional Gain""" self.Kp = proportional_gain def setKi(self, integral_gain): """Determines how aggressively the PID reacts to the current error with setting Integral Gain""" self.Ki = integral_gain def setKd(self, derivative_gain): """Determines how aggressively the PID reacts to the current error with setting Derivative Gain""" self.Kd = derivative_gain def setWindup(self, windup): """Integral windup, also known as integrator windup or reset windup, refers to the situation in a PID feedback controller where a large change in setpoint occurs (say a positive change) and the integral terms accumulates a significant error during the rise (windup), thus overshooting and continuing to increase as this accumulated error is unwound (offset by errors in the other direction). The specific problem is the excess overshooting. """ self.windup_guard = windup def setSampleTime(self, sample_time): """PID that should be updated at a regular interval. Based on a pre-determined sampe time, the PID decides if it should compute or return immediately. """ self.sample_time = sample_time
Adding a PID
For illustration purposes, add a new Adjust object to the flowsheet and set its manipulated object to 'FV-01' and controlled object to 'cooled_water'. The actual controlling won't be done by this object calculation routine, but rather by our PID script.
Running the Closed-Loop Dynamic Model
Create a new script and name it 'RunDynamicProcess_ClosedLoop', with the following content:
import clr import System from System import * from System.Threading import * clr.AddReference('System.Core') clr.AddReference('DWSIM.GlobalSettings') clr.ImportExtensions(System.Linq) from DWSIM.GlobalSettings import * source = Flowsheet.Scripts.Values.Where(lambda x: x.Title == 'Functions').FirstOrDefault().ScriptText.replace('\r', '') exec(source) initvars = Flowsheet.Scripts.Values.Where(lambda x: x.Title == 'InitVars').FirstOrDefault().ScriptText.replace('\r', '') exec(initvars) pidclass = Flowsheet.Scripts.Values.Where(lambda x: x.Title == 'PID').FirstOrDefault().ScriptText.replace('\r', '') exec(pidclass) maxtime = Flowsheet.ExtraProperties.MaxTime length = maxtime / Flowsheet.ExtraProperties.TimeStep time = [0.0 + x*(maxtime - 0.0)/length for x in range(int(length))] source_level = {} sink_level = {} hot_water_flow = {} hot_water_temp = {} cooling_water_flow = {} cooling_water_temp = {} valve_opening = {} pid_sp = {} pid_pv = {} pid_mv = {} perturbed_hotwater = False controller = Flowsheet.GetFlowsheetSimulationObject("PID Controller") P = 0.5 I = 0.01 D = 0.1 pid = PID(P, I, D) pid.SetPoint = 1.0 pid.sample_time = 0.01 controller.ExtraProperties.TotalError = 0.0 for t in time: Flowsheet.SupressMessages = False Flowsheet.WriteMessage("Time Step: " + str(int(t+1)) + "/" + str(int(maxtime))) Flowsheet.SupressMessages = True Flowsheet.ExtraProperties.CurrentTime = t if (t >= Flowsheet.ExtraProperties.HotWaterPerturbationTime and not perturbed_hotwater): StorePrePerturbationVariables() SetHotWaterMassFlow(Flowsheet.ExtraProperties.PerturbationValue) Flowsheet.ExtraProperties.LastPerturbationTime = t perturbed_hotwater = True Flowsheet.SolveFlowsheet2() CalcSourceTankLevel() CalcSinkTankLevel() source_level[t] = GetSourceTankLevel() sink_level[t] = GetSinkTankLevel() hot_water_flow[t] = GetHotWaterMassFlow() hot_water_temp[t] = GetHotWaterOutletTemperature() cooling_water_flow[t] = GetCoolingWaterMassFlow() cooling_water_temp[t] = GetCoolingWaterOutletTemperature() valve_opening[t] = GetValveOpening() pid_sp[t] = 1.0 pid_pv[t] = GetHotWaterOutletTemperature()/(50.0 + 273.15) pid.update(GetHotWaterOutletTemperature()/(50.0 + 273.15), t) pid_mv[t] = (pid.SetPoint - pid.output) * GetValveOpening()/50.0 SetValveOpening((pid.SetPoint - pid.output) * GetValveOpening()) controller.ExtraProperties.TotalError += ((pid_sp[t] - pid_pv[t]) * Flowsheet.ExtraProperties.TimeStep) ** 2 Flowsheet.SupressMessages = False outputresults = Flowsheet.Scripts.Values.Where(lambda x: x.Title == 'GenerateCharts').FirstOrDefault().ScriptText.replace('\r', '') exec(outputresults)
Notice that our PID variables (SP, PV and MV) are normalized (SP = 1.0).
We will run our PID controller initially with Kp = 0.5, Ki = 0.01 and Kd = 0.1.
Modify the 'GenerateCharts' script to include the following commands before the last one:
if (controller != None): chart3 = Plot() chart3.Model = Common.CreatePlotModel(Array[float](time), Array[float](pid_sp.values()), "PID Output", "P = " + str(P) + ", I = " + str(I) + ", D = " + str(D), "time (s)", "SP") chart3.Model.AddYAxis("PV", "pv", OxyPlot.Axes.AxisPosition.Right, 1) chart3.Model.AddLineSeries(Array[float](time), Array[float](pid_mv.values()), "MV") chart3.Model.AddLineSeriesWithKeys(Array[float](time), Array[float](pid_pv.values()), "PV", "pv", "x") chart3.Model.InvalidatePlot(True) form3 = Common.GetDefaultEditorForm("PID Output", 600, 600, chart3, False) form3.Show()
Run the closed loop model. You should get the following after a successful run:
Download File
Download the simulation file with what has been done so far: dynamic_part3.dwxmz
Return to Dynamic Simulation Tutorial with DWSIM and Python, Part 2: Building the Dynamic Model