310 likes | 499 Views
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).
E N D
CSE 522Simulink Computer Science & Engineering DepartmentArizona State University Tempe, AZ 85287 Dr. Yann-Hang Leeyhlee@asu.edu(480) 727-7507 Some of the slides were based on lectures by Lee & Seshia (UC Berkeley)and Fainekos (ASU)
What flows through an object is sequential control class name data methods call return Actor-Oriented Design • Object orientation: • Actor orientation: What flows through an object is data streams actor name data (state) parameters Input data Output data ports (http://ptolemy.eecs.berkeley.edu/presentations/04/Parc_Lee.ppt)
TextToSpeech initialize(): void notify(): void isReady(): boolean getSpeech(): double[] Actor Orientation vs. Object Orientation Actor oriented Object oriented • 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 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” (http://ptolemy.eecs.berkeley.edu/presentations/04/Parc_Lee.ppt)
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/presentations/04/Parc_Lee.ppt)
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) • Thesyntax 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
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));
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
Verification Methodology (1) sensor controller (model) plant (model) actuator Test process outputs test vectors Simulation platform Model in the loop • Define mathematical models of the plant and the controller. • Can the controller and algorithm fulfill the specification? • The set of tests will be used as “an oracle” in the next steps.
Verification Methodology (2) controller (software) plant (model) Test process Simulation platform Simulation platform processor (software) plant (model) Test process Software (code) in the loop Hardware in the loop Processor in the loop
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.
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
Simulink Signal and Subsystem subsystems virtual non-virtual atomic conditional control flow documentation library triggered enabled 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
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)
Mathlab/Simulink Code Generation (formerly Real-Time Workshop) (http://blogs.mathworks.com/seth/2011/04/08/welcome-to-the-coders/) Embedded MATLAB: • 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)
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
Simulink Model Execution (2) 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 (http://synchron2011.di.ens.fr/slides/chapoutot_ simulink_semantics.pdf ) 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
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
Execution Scheduling T1 T2 T4 T1 T1 T2 T1 T1 T2 T4 (from Simulink Coder User Guide) 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
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_OneStepis either installed as a timer interrupt service routine (ISR), or called from a timer ISR at each clock step
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 reinterruptionof rt_OneStep by the timer is an error condition and rt_OneStepsignals an error and returns immediately.
Rate Transition (1) (from Simulink Coder User Guide) 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
Rate Transition (2) (from Simulink Coder User Guide) 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
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.
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_2 C B B A_1 A_2 C 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
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 A_2 C B B y_1 A_1 A_2 C C B y_1 y_2
Asynchronous Support in RTW/vxWorks Asyns interrupt -- generate interrupt-level code Task sync -- spawn a vxWorkstask 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