tutorial for simulation of a batch...
TRANSCRIPT
1 | P a g e
Tutorial for Simulation of a Batch Process
tbco 3/27/2016, 3/27/2017
Scenario:
Once two tanks have been filled to desired levels, they are drained simultaneously and process
repeats for the next batch.
Part 1. Dynamic Simulation of Level Dynamics of Two Tanks
I. Obtain Dynamic Models
𝑑ℎ1
𝑑𝑡=
1
𝐴1(𝑘𝑖𝑛1𝐹𝑖𝑛1,𝑚𝑎𝑥 − 𝑘𝑣1ℎ1)
𝑑ℎ2
𝑑𝑡=
1
𝐴2(𝑘𝑖𝑛2𝐹𝑖𝑛2,𝑚𝑎𝑥 − 𝑘𝑣2ℎ2)
ℎ1(0) = ℎ10 ; ℎ2(0) = ℎ20
II. Open a Simulink page
1. Open MATLAB, and type in command line: simulink
2. After Simulink browser pops out, click menu icon to open “new model”.
3. A simulink window will appear where we will drop various blocks. See Figure 1.
Figure 1. Starting simulink window.
2 | P a g e
III. Generate Model for Tank 1.
1. Select “Commonly Used Blocks” from left portion of browser window, then drag-drop
the following items into the simulink window: (see Figure 2)
a) Three “Constant” blocks
b) Two “Product” blocks
c) One “Sum” block
d) One “Gain” block
e) One “Integrator” block
f) One “Scope” block
Figure 2. Drag-drop blocks into the Simulink window.
2. Change the properties of the sum block to make it a difference block.
a. Double-click on the sum block icon to get the properties window.
b. Change the entry in the <List of Signs> to be “+-“.
c. (Optional) You can change the shape to be “rectangular”.
d. Remember to click “OK”. Otherwise the changes will not be applied.
e. If necessary, you can resize the blocks.
3 | P a g e
Figure 3. Change the properties of the “sum” block.
3. Rename blocks (double-click and then edit) then connect lines (click-drag from one port
to the other port) among the blocks as shown in Figure 4. (Hint: for the line from “hout”
to “Product1”, click on the inport of “Product1” then drag to the “hout” line.)
Figure 4. After renaming blocks and connecting the lines.
4. Set constant values: kin=0.9, FinMax=0.1 and kvout=0.5. This is done by double-clicking
on the the respective icons, then change the values in the “Constant value” entry in the
properties window that pop-up. (Remember to click “OK” to apply the changes.)
4 | P a g e
5. Simulate the process to check if the model is reasonable.
a. Modify the simulation parameters
(i) Key-in [Ctrl-E] to access the simulation configuration window
(ii) Change the “Stop time” entry to 30
(iii) (Optional but recommended) Change the “relative tolerance” entry to 1e-6.
(see Figure 5.)
Figure 5. Changing simulation configuration.
b. Run the simulation. Click on the “Play (Run)” button. See Figure 6. ( Note the first
time you click this button, the program will be compiling the model which will take
some time, so just wait unit you get back the “Ready” prompt at the bottom of the
simulink window before proceeding to next step.
Figure 6. Click on the “Run” button to start simulation.
c. Double click on the “Scope” icon (or the one renamed as “hout”). The graph
window should pop-out. Right-click on the window and select “Autoscale” to see
the shape. See Figure 7.
Figure 7. The response as shown in the scope.
5 | P a g e
IV. Simulating two tanks via subsystems
1. Select all the components in the simulink window, except the three “constant” blocks
and the “hout” block.
2. Right-click the selection then key-in [Ctrl-G] to shrink the group into a subsystem.
(You can resize the box).
3. Double click on the subsystem block to zoom-in the details of the subsystem.
4. Rename the inports In1, In2 and In3 to be kin, FinMax and kvout, respectively. Also,
rename the outport Out1 to be hout.
5. Click the top-left tab, e.g. “untitled” for now, to return to the top level of the model. See
Figure 8.
Figure 8. After renaming inports and outports,
click on “untitled” tab to return to top level.
6. Generate a copy of the subsystem together with the inputs. On the top (“untitled”)
level of the model, select all blocks except the “scope” block. Then right-click-select
<copy> and right-click-select <paste>.
7. Rename the blocks and the subsystems. Hint: first change the new set of constant
blocks to kin2, FinMax2 and kvout2 then change the old set of constant blocks to kin1,
FinMax1 and kvout1, respectively. Also, change the subsystems to “Tank_subsystem1”
and “Tank_subsystem2”.
8. From the browser window, drag-drop an “mux” (multiplexer) block into the simulink
window.
9. Change the values of kin2=0.8, FinMax2=0.2 and kvout2=0.4 to be
10. Reconnect the output values to mux block then to the scope block. Remove the original
line from hout1 to the scope then include instead the lines as shown in Figure 9.
11. Run the simulation and you should get the response shown in Figure 10.
12. Save the model. For our purposes we will assume the name to be
“twotanks_with_sfc_tutorial” (saved as *.slx file)
6 | P a g e
Figure 9. Model with two tanks.
Figure 10. Simulation output from model shown in Figure 9.
7 | P a g e
Part 2. Converting SFC into Stateflow block
Assume that we have the sequential function chart shown in Figure 11 which is based on the following
recipe:
1. Initialize by transferring recipe parameters and empty both tanks.
2. After both tanks are empty, start filling both tanks simultaneously.
3. When either tank reaches its maximum level, put it on “standby” mode.
4. After both tanks are in the “standby” modes, drain both tanks simultaneously.
5. When either tank reaches its minimum level, put it on “stop drain” mode.
6. After both tanks are in the “stop drain” mode, repeat from step 2.
Figure 11. Sequential function chart for two-tank filling unit.
8 | P a g e
I. Prepare a stateflow chart.
1. Include a stateflow chart. From the left-side of the simulink browser window, select the
“stateflow” item then click-drag a “chart” block into the simulink window as shown in Figure
12 (preferably to the left of the other continuous blocks).
Figure 12. Including a stateflow chart into the simulink window.
2. Open the chart editor. Double-clicking on the “chart” icon. This will replace the current
simulink window with the stateflow editor as shown in Figure 13.
Figure 13. The stateflow editor. Note the “Chart” menu item which
will be needed to add input and output ports.
3. Include a set of input ports. We want to use information about the heights in both tanks.
Click on the “Chart” menu item (see Figure 13) (or alternatively right-click to pop-up a menu
list) and select the submenu item [Add Inputs & Outputs][Data Input from Simulink] and a
9 | P a g e
window should pop-up to allow the definition of a input port. Change the entry for the
“Name” to “hout1” then click [Ok] as shown in Figure 14. Repeat the process in add another
input port named “hout2”.
Figure 14. Modifying an input port.
4. Include a set of output ports. We want to send information about the valve settings to
manipulate flow in and out of both tanks. Click on the “Chart” menu item (see Figure 13) (or
alternatively right-click to pop-up a menu list) and select the submenu item [Add Inputs &
Outputs][Data Output from Simulink] and a window should pop-up to allow the definition
of a output port. Change the entry for the “Name” to “kin1”, plus change the selection of
“type” to be “double” then click [Ok] as shown in Figure 15. Repeat the process to add
three more output ports named “kvout1”, “kin2” and “kvout2”, all with the type “double”.
10 | P a g e
Figure 15. Modifying an output port.
5. Include an event port. We want the ability to trigger (or wake-up) the chart when events
occur from outside the chart. In our example, we will use a square wave to be our clock
which will wake-up our stateflow chart when the wave jumps up or down. Click on the
“Chart” menu item (see Figure 13) (or alternatively right-click to pop-up a menu list) and
select the submenu item [Add Inputs & Outputs][Event Input from Simulink] and a
window should pop-up to allow the definition of an event port. Change the entry for the
“Name” to “clock”, plus change the selection of “Trigger” to be “Either” then click [Ok] as
shown in Figure 16.
Figure 16. Modifying an event property.
11 | P a g e
6. (Optional) Verify the initialization phase of the chart. When the chart editor page is active,
one can bring up a summary page by right-clicking to select “explore”. A summary such as
the one shown in Figure 17 will pop-up. Check that the names and types are the ones
selected. (If editing was done using the right-pane during the editing, it is necessary to click
[apply] to accept the changes.) After the summary has been checked, just exit the window.
Note: it is quite common that compilation errors based on typographical errors, new
variables may be created automatically for those misspelled variables (including wrong
lower or upper case settings). Thus, it is strongly suggested to check the spelling, as well as
the selection types. To remove unwanted variables, one can select the particular item and
tjust press delete ([Del]) key.
7. Link (connect wires) input and output information streams. Go to the parent (simulink) level
by clicking the tab in the upper left portion. (In our case, our simulink file was saved as
“twotanks_with_sfc_tutorial”) as shown in Figure 17. This should return us to the simulink
view. Click on the “icon” and resize the icon to show the various ports clearly (see Figure
17). Delete the constants blocks named kin1, kvout1, kin2 and kvout2 and then connect the
input lines as well as the output lines as shown in Figure 18.
Figure 17. Flipping back to simulink view.
12 | P a g e
Figure 18. Linking chart input and output ports to other simulink ports.
13 | P a g e
8. Add a square signal block to act as clock mechanism. From the simulink library browser,
select [Source] item in the left pane, then drag-drop a [Signal Generator] block into the
simulink window as shown in Figure 19. Optional: rename the label as “Clock”. Double-click
on the “Clock” icon. A properties window should pop-up. Choose [square] under “Wave-
form” and also input “500” for frequency (see Figure 20.) then click [OK].
Figure 19. Include a [Signal Generator] block.
Figure 20. Change the parameters of signal generator (renamed as “Clock” here).
14 | P a g e
9. Link the clock output to the event input port (the pulse symbol on top) of the chart. (see
Figure 21).
Figure 21. Linking Signal Generator (clock) to event port.
10. Setup local variables. We will include four local variables, namely hmin1, hmax1, hmin2 and
hmax2, which are the minimum and maximum set levels for each tank. To do so, first
double-click on the Chart block to open the chart editor. Click on the “Chart” menu item
(see Figure 13) (or alternatively right-click to pop-up a menu list) and select the submenu
item [Add Other Elements][Local Data…] and a window should pop-up. Change the entry
for the “Name” to “hmin1”, plus change the selection of “type” to be “double” then click
[Ok].
Repeat the process to define “hmax1”, “hmin2” and “hmax2”, all set to “double” type.
Figure 22. Modifying a “local variable” property window.
15 | P a g e
II. Program the SFC into Stateflow Chart. (See Figure 11 for reference)
1. Open the Chart editor. (double-click on the chart icon)
2. Include a [State] block into the chart to contain the initialization actions. Drag a [State] icon
(rounded box icon) from the selection list on the left edge of the editor (see Figure 22.) Name
the state (shown initially as a question mark inside the rounded box) as “Initialize” then resize
the block and enter the action lines shown in Figure 22. The actions essentially closes the feed
lines to the tanks while opening the drain lines of both tanks, while the last four lines just sets
up the values for set maximum and set minimum levels of the tanks for the particular process
recipe.
Figure 22. Include a state block into the chart.
Resize, name it then type in action commands.
Notes:
a) The line “en:” is a prefix denoting the lines and commands that follow to the right or below it
are the actions “upon entry”, equivalently “upon activation”, of the state.
b) Each command must be ended by a semicolon.
3. Include another [State] block into the chart that will contain the filling actions.
a) Drag another [State] block into the simulink page. Name this block as “FillBoth”. This block
will need to be enlarged to contain sub-states. (Note that this block will stand for the set of
states in the SFC shown in Figure 11 contained between the first two pairs of parallel lines.)
b) While the cursor is inside this block, right-click to pop a menu then select
[Decomposition][AND (Parallel)].
16 | P a g e
c) Now drag two more [State] blocks inside the “FillBoth” block. (Note that the boundary will
show up as dotted lines to indicate that these boxes will be activated in parallel.) Name
each block as “Tank1” and “Tank2” (see Figure 23).
Figure 23. Including two sub-[State] blocks that are treated
as parallel states inside the parent block which is the [FillBoth] block.
d) Include two more [State] blocks inside each parallel block. Name the two blocks inside
“Tank1” as “Fill” and “Standby”. Do the same for the two blocks inside “Tank2”.
e) Enter the actions for each sub-sub-state blocks. See Figure 24 for the required action lines.
Figure 24. The actions inside the sub-substates of FillBoth.
17 | P a g e
4. Include another [State] block into the chart that will contain the draining actions. Follow the
same sequence as in step 3 above but replacing the names and actions to match those shown in
Figure 25. (Note that these states and their corresponding actions are those contained between
the two pair of parallel lines in the SFC shown in Figure 11.)
Figure 25. The actions inside the sub-substates of DrainBoth.
5. Introduce a transition between the state blocks “Initialize” and “FillBoth”. Move the cursor and
hover it around an edge of the source [State] block (e.g. the bottom edge of the “Initialize”
block) until the arrow cursor changes to a cross symbol. Next, click-drag the resulting arrow
until the arrowhead lands in the desired edge of the target [State] block (e.g. the top edge of the
“FillBoth” block). An arrow should now join the two blocks. A question mark should be
available for inclusion of conditions (or permissives) of the transition. For the transition from
“Initialize” to “FillBoth”, include the following condition as shown in Figure 26:
[(hout1==0) && (hout2==0)]
Note: The square brackets are needed to collect logical conditions while the parentheses are
used to sub-group logical conditions. The double equal sign (“==”) is used to compare
the values of both sides of the symbols and yields a TRUE value if they are the same. The
double ampersand (“&&”) is used for logical AND evaluation. The transition
condition/commands can be moved around the page by click-dragging it to the desired
location (however, you may need to click somewhere else first in order to release it from
edit mode). Also, the tail and arrow head of the transition can be moved around and
reshaped.
18 | P a g e
Figure 26. Adding a transition from “Initialize” to “FillBoth” states.
6. Add a transition from “FillBoth” to “DrainBoth”. Similar to step 5 above, except the transition
can be conditioned as follows : (see Figure 27)
[in(FillBoth.Tank1.Standby)&&in(FillBoth.Tank2.Standby)]
Note: The function in( state_x ) becomes true if state_x is currently active (or enabled). The
syntax for labeling the substates require the hierarchy in which it belongs using a period
to indicate the order of inclusion. For example, FillBoth.Tank1.Standby is the state
referring to the “Standby” state inside “Tank1” which in turn is inside “FillBoth”.
Figure 27. Adding a transition from “FillBoth” to “DrainBoth” states.
19 | P a g e
7. Add a transition from “DrainBoth” back to “FillBoth”. This means once both tanks have finish
draining, we want to repeat the cycle starting with filling both tanks again. Similar to step 5 or 6
above, the transition can be conditioned as follows : (see Figure 29)
[ in(DrainBoth.Tank1.StopDrain) && in(DrainBoth.Tank1.StopDrain) ]
Note that you may need to reshape the transition arrow as well as move the condition label to
improve clarity of the transition. Also, if the condition label gets too long, it could be broken to
several lines but with ellipses, i.e. three lower dots, to act as “to be continued by the next line”.
(see Figure 27)
Figure 27. Adding a transition from “DrainBoth” to “FillBoth” states.
20 | P a g e
8. Add transitions from “Fill” to “Standy” inside both “Tank1” and “Tank2” sub-states of “FillBoth”.
The condition for going from “Fill” to “Standby” inside tank 1 will be: “ [hout1>=hmax1] “, while
for tank2 it is: “ [hout2>=hmax2] “ (see Figure 28).
Figure 28. Adding transitions from “Fill” to “Standby” states inside “Tank1” and “Tank2”.
9. Add transitions from “Drain” to “StopDrain” in both “Tank1” and “Tank2” sub-states of
“DrainBoth” . The condition for going from “Drain” to “StopDrain” inside tank 1 will be: “
[hout1<=hmin1] “, while for tank2 it is: “ [hout2<=hmin2] “ (see Figure 29).
Figure 28. Adding transitions from “Drain” to “StopDrain” states inside “Tank1” and “Tank2”.
21 | P a g e
10. Include default transitions inside parallel blocks. Since the states could transition into cycles,
stateflow needs to know which state it should activate within blocks inside a parallel block
(blocks bounded by dashed lines) once the flow enters that block. Click-drag on the arrow icon
in the left edge of the chart editor window, and drop it near the location when the cursor
changes to an arrow. (If you released the mouse prematurely, you might introduce a default
transition that includes a “junction point” represented by a small orange circle. If so, you can
delete the junction point and then move the arrow head to link to the desired state.) Include
four default transitions as shown in Figure 29.
Figure 29. Adding default transitions inside
parallel blocks (blocks with dashed boundaries).
22 | P a g e
11. Include one more default transition to point at the “Initialize” state block.
Figure 30. Adding a default transition in the main chart level
(in our case, we want “Initialize” to be the default state once stateflow is started.
Brief Summary of the Stateflow program steps used:
1. Define/add input ports, output ports, an event port and local data variables (and other variable
definitions).
2. Link the ports to other simulink elements including blocks that can act as event generators.
3. Using a recipe (such as those constructed as sequential function charts (SFC)) include the
different states starting with the exclusive-OR blocks (blocks with solid-line boundaries).
Consider the block containing parallel states as one of these blocks. (When building the parallel
states make you can change the [Decompostion] type to [AND] mode.)
4. Include the transition arrows and attach them with the appropriate condition labels.
5. Add a default transition arrow inside each parallel/AND block (blocks with dashed-line
boundaries) to point at the block that stateflow will activate upon its entry into that
parallel/AND block.
6. Add one more default transition arrow to point at the state block in the main chart.
Some Tips:
1. To open the chart editor from the simulink page, just double-click on the chart block. From a
chart editor, you can go to the upper level by clicking the tab with the simulink model file
located in the upper left area of the chart editor.
2. Inside the chart editor, one can always check the variables and state defined by right-click then
select the [Explore]. In the explore window, you can edit or delete the variables as needed.
3. Lenghty transition commands can be broken up to several line using elipses (“…”) as
continuation marks.
4. It is strongly suggested to periodically save the simulink file because some underpowered
computers may hang and lead to lost work.
23 | P a g e
III. Run the Simulation
1. When you start the simulation, simulink will firt compile the stateflow program. The most usual
errors involve typographical errors of the States or conditions. In case, a variable has been
mistyped, stateflow might create a new variable. You may need to correct the chart by using
the [Explore] option either modify or delete some variables.
2. Assuming no compilation errors, the model should run to its final simulation time.
3. If the simulation was run while the chart editor is open, one option is to watch the activity flow
of the states via animated highlighting. For example, you can select the menu under
[Simulation][Stateflow Animation][Slow] (see Figure 31). Then after click on the play
button to begin the simulation, different parts of the stateflow will be highlighted. You can
[Pause] the simulation anytime. A sample snapshot is shown in Figure 32 to show a situation
where tank 2 has finish filling but tank 1 has not.
Figure 31. Selecting the Stateflow Animation mode.
24 | P a g e
Figure 32. Pausing the stateflow animation shows
which states are active at some instant in the simulation.
4. In some cases, where the data need to be collected for further analysis or reporting, one could
add another block in the simulink page to send the data to a Matlab as an array. To do so, drag-
drop a [to Workspace] block (first select [sinks] at the left pane of the simulink browser) into the
simulink page and tap into the line that goes to the scope (see Figure 33).
25 | P a g e
Figure 33. Adding a [simout] block.
Double-click on [To Workspace] block (named ‘simout’ for now) to pop-up a properties window
(see Figure 34) and change the entries accordingly.
Figure 34. The property window of a [To Workspace] block.
26 | P a g e
After a simulation, data will be available in the main Matlab workspace as the variable heights.
We could extract the data into one large array using the following command:
>> twotankheights = [heights.Time, heights.Data];
This array will contain three columns in which the first column is the time data, the second and
third columns are the heights of tank1 and tank2, respectively. One could then export this array
as a text file using the following command:
>> save('two_tanks_output.dat','-ascii','-double','twotankheights')
The text file ‘twotanks_output.dat’ can then be imported by other programs such as Microsoft
Excel. For instance, in the Excel program, one can select [Data][From Text], then choose the
text file just saved.