Slide_Simulink_model_development - Real

advertisement
CSE 522
Simulink
Computer Science & Engineering Department
Arizona State University
Tempe, AZ 85287
Dr. Yann-Hang Lee
yhlee@asu.edu
(480) 727-7507
Some of the slides were based on lectures by
Lee & Seshia (UC Berkeley) and Fainekos (ASU)
Actor-Oriented Design
 Object orientation:
What flows through
an object is
sequential control
class name
data
methods
call
return
 Actor orientation:
What flows through
an object is data
streams
actor name
data (state)
Input data
parameters
ports
Output data
(http://ptolemy.eecs.berkeley.edu/presentations/04/Parc_Lee.ppt)
Actor Orientation vs. Object Orientation
Actor oriented
Object oriented
TextToSpeech
initialize(): void
notify(): void
isReady(): boolean
getSpeech(): double[]
OO interface definition gives
procedures that have to be invoked in
an order not specified as part of the
interface definition.
actor-oriented interface definition
says “Give me text and I’ll give you
speech”
 Identified limitations of object orientation:
 Says little or nothing about concurrency and time
 Concurrency typically expressed with threads, monitors, semaphores
 Components tend to implement low-level communication protocols
 Re-use potential is disappointing
(http://ptolemy.eecs.berkeley.edu/presentations/04/Parc_Lee.ppt)
3
Example of an Actor-Oriented Framework
 Signal flow graph with linear, time-invariant components
 Synchronous concurrent composition of components
 basic abstraction mechanism is hierarchy.
(http://ptolemy.eecs.berkeley.edu/pres
entations/04/Parc_Lee.ppt)
4
Matlab/Simulink
 Developed by Mathworks (http://www.mathworks.com/)
 Matlab
 An high-level programming language and interactive
environment for scientific computing
 good quality numerical algorithms
 easy-to-use graphics and visualization capabilities
 real and complex vectors and matrices (including sparse matrices)
 The syntax of the language closely resembles the way we write
mathematical equations
 Easy extensibility, by the user or via packages of M-files (which
contains a computer code) and GUIs known as toolboxes
 It has a large number of toolboxes as add-ons
 The academic and scientific communities also create toolboxes
5
Example Mathlab Code
 Trapezoidal Rule
function y = corrtrap(fname, fpname, a, b)
%
%
%
%
Corrected trapezoidal rule y.
fname - the m-file used to evaluate the integrand,
fpname - the m-file used to evaluate the first derivative
a,b - endpoinds of the interval of integration.
h = b - a;
y = (h/2)*(feval(fname,a) + feval(fname,b))+ (h^2)/12*(feval(fpname,a) feval(fpname,b));
6
Simulink
 A graphical environment for multi-domain simulation and
Model-Based Design for dynamic and embedded
systems.
 Based on block diagrams and data flow modeling
 Not a programming language
 Hierarchical, component-based modeling
 Extensive library of predefined blocks
 MATLAB integration
 Application-specific libraries available
 Open Application Program Interface (API)
 It has a large number of toolboxes as add-ons
 Code generation
 Verification, Validation, and Test
7
Verification Methodology (1)
 Model in the loop
 Define mathematical models of the plant and the controller.
sensor
controller
(model)
test vectors
plant
(model)
actuator
Test process
outputs
Simulation platform
 Can the controller and algorithm fulfill the specification?
 The set of tests will be used as “an oracle” in the next steps.
8
Verification Methodology (2)
 Software (code) in
controller
(software)
plant
(model)
the loop
Test process
Simulation platform
 Hardware in the loop
Simulation platform
 Processor in the
processor
(software)
plant
(model)
loop
Test process
9
Simulink Blocks (1)
 Block: an actor
 Consists of some functionality and an arbitrary number of ports
 can be pre-defined blocks from Simulink library, S-function blocks
(writing your own function in C, Fortran, etc.), or subsystem blocks
 S-functions are dynamically linked subroutines that the MATLAB
interpreter can automatically load and execute
 Signals connect block‘s ports to pass data between blocks
 To calculate the values of the
output ports based on the values
of the input ports and the internal states.
 Sample time: how often and when the functionality of a block is
evaluated.
10
Simulink Blocks (2)
 Continuous blocks
 have an infinitesimal sample time, e.g., integrator and derivative blocks
 Discrete block
 configured by a sample time parameter
 can be inherited either from the block connected to its input
(inheritance) of its output (back inheritance).
 Block update (for all blocks within a system): to compute
 the block‘s outputs, the block‘s states, and the time for the next time
step
 Direct feed-through ports
 The calculation of the output values depends on the input values of the
current sample time, e.g., sum block
 An algebraic loop occurs when a signal loop exists with only direct
feed-through blocks within the loop
11
Simulink Signal and Subsystem
 Each Signal Object is associated to:
 Data Type, dimension, sample rate, complexity (real, complex or auto),
minimum/maximum values, initial value, unit of measure (only for doc),
description
 Subsystems -- decompose the model in components and reuse
subsystems
virtual
non-virtual
atomic
documentation
library
conditional
enabled
triggered
control flow
12
Conditionally Executed Subsystems
 A subsystem whose execution depends on the value of an input
signal.
 Enabled Subsystem
 Executed if the control signal has a positive value
 Control Flow Subsystem
 Executed if the control flow condition (e.g., if, while) evaluated to true
 Triggered Subsystem: execute each time a trigger event occurs
 positive or negative edges
 function call signals (from function-call generator blocks or S-function
blocks)
13
Mathlab/Simulink Code Generation
(formerly Real-Time Workshop)
 Embedded MATLAB:
(http://blogs.mathworks.com/seth/2011/04/
08/welcome-to-the-coders/)
 a subset of the MATLAB language that supports efficient code generation for
deployment in embedded systems
 can use Real-Time Workshop to convert MATLAB programs to C programs
 Generated code can run in real time (physical clock) or simulated time (steps)
14
Simulink Model Execution (1)
 Model compilation
 Identification of the signal types, sizes
 Propagation of the types
 Optimization of the structure
 Flattening of the virtual subsystems
 Link phase
 Allocation of memory structures
 Connection between elements
 Loop phase
15
Simulink Model Execution (2)
 Block defines the time
invariant relation between its
input and its output.
 Virtual time –
 computation takes no time
and when it is done,
advance to next time step.
 Major step to produce
output
 Minor step to improve the
accuracy of continuous
solvers
(http://synchron2011.di.ens.fr/slides/chapoutot_
simulink_semantics.pdf )
input: x0, d0, t0, h0;
n = 0;
loop until tn  tend
evaluate g(tn, xn, dn) ;
update d = fd (tn, xn, dn) ;
solve ẋ(t) = fx (t, x(t), dn) over
interval [tn, tn + hn] to get
x(tn + hn) ;
find zero crossing ;
compute hn+1 ;
compute tn+1 ;
dn+1 = d; xn+1 = x(tn + hn) ;
n=n+1;
end loop
16
Simulink Model Execution (3)
 Order of block updates
 Updated before any of the blocks if it drives via direct-feed-through ports
 Blocks that do not have direct-feed-through inputs can be updated in any
order.
 Atomic (compute at once) to Virtual Subsystem (flattened to the level of the
parent system)
 Block priority
17
Execution Models of Generated Code (1)
single-rate
multi-rate
multi-rate
singletasking
• model_main() spawns a base rate task, tBaseRate, which is
task is activated by a clock semaphore and calls model_step
singletasking
• model_main() spawns only a base rate task, tBaseRate. All
rates run under this task.
• The base rate task is activated by a clock semaphore
provided by VxWorks.
• On each activation, tBaseRate calls model_step.
• model_step in turn calls the rate_monotonic_scheduler
utility, which maintains the scheduling counters that
determine which rates should execute.
multitasking
• model_main() spawns a base rate task and sub-rate tasks
which call model_step with their associated tids.
• The base rate task and model_step are responsible for
maintaining event flags and scheduling counter.
• Task priorities are assigned by rate.
18
Execution Scheduling
 In simulation: computation results occur instantaneously
 In real execution
 non-zero non-deterministic block execution time
 task overrun detection
 communication through data variables in memory
 Single-tasking multiple-rate execution
 rates are harmonic
 a timer ISR to drive at base rate
 assume 3 tasks of sampling times of 1, 2 and 4
T1 T2 T4
T1
T1 T2
T1
T1 T2 T4
(from Simulink Coder User Guide)
19
RTW Main program (no RTOS)
main()
{
Initialization (including installation of rt_OneStep as an interrupt service
routine for a real-time clock)
Initialize and start timer hardware
Enable interrupts
While(not Error) and (time < final time)
Background task
EndWhile
Disable interrupts (Disable rt_OneStep from executing)
Complete any background tasks
Shutdown
}
(from RTW Embedded Coder User Guide)
 Periodically interrupted by a timer.
 rt_OneStep is either installed as a timer interrupt service routine (ISR), or
called from a timer ISR at each clock step
20
RTW Main program (no RTOS)
rt_OneStep()
{
Check for base-rate interrupt overrun
Enable "rt_OneStep" interrupt
Determine which rates need to run this time step
Model_Step0() -- run base-rate time step code
For N=1:NumTasks-1 -- iterate over sub-rate tasks
If (sub-rate task N is scheduled)
Check for sub-rate interrupt overrun
Model_StepN() -- run sub-rate time step code
EndIf
EndFor
(from RTW Embedded Coder User Guide)
}
 sequences calls to the model_step functions for multi-rate model
 reinterruption of rt_OneStep by the timer is an error condition and
rt_OneStep signals an error and returns immediately.
21
Rate Transition (1)
 Multi-rate and multi-tasking model
 multiple threads (tasks) with preemption
 one thread for each rate and, for periodic tasks, the faster rate task has
higher priority
 Faster to slower transition
 The input of slower block may be changed during its execution
 Slower to faster transition
(from Simulink Coder User Guide)
22
Rate Transition (2)
 Rate transition block to copy data
 runs in high priority, but low rate
 output value is held constant
while the slower block executes
 rate transition update and output
(from Simulink Coder User Guide)
23
Semantics-preserving (1)
 Synchronous:
 atomic reactions indexed by a global logical clock,
 each reaction computes new events for its outputs based on its
internal state and on the input values
 the communication of all events between components occur
synchronously during each reaction.
 Cycles of reading inputs, computing reaction and
producing outputs
 Synchronous = 0-delay = within the same cycle
 No interference between I/O and computation
 Why?
 deterministic semantics in the presence of concurrency.
24
Semantics-preserving (2)
A_2
A_1
a high priority task B arrives and receives
inputs from A (from A_1 or A_2?)
A_1
A_1
C
B
C
A_2
A_2
B
C
B
if Pri(A) > Pri(C)>Pri(B), depending upon the execution
time of C, B may receive inputs from A_1 or A_2
25
Semantics-preserving (3)
 If execution time = 0, then the computation is determined by the
order of arrivals, not the arrival instances, nor execution time
 Can we memorize the arrival order and then fetch data from buffer
 Unit delay is necessary when a higher priority task reads from a
lower priority task
A_1
C
B
A_2
B
A_2
C B
y_1
A_1
C
y_1
y_2
26
Asynchronous Support in RTW/vxWorks
 Asyns interrupt -- generate interrupt-level code
 Task sync -- spawn a vxWorks task that calls a function call subsystem
 Protected RT -- enable data integrity when transferring data between
blocks running as different tasks
 Unprotected RT -- use an unprotected/nondeterministic mode
27
Download