--- ---
On March 5-6th 2016, communities across Canada are organizing events about using open data and civic tech for positive impact. Get involved!
For global event listings, visit Code For America and Open Data Day.
This site was created by Adrianne H Lee and Urban+Digital.


Internal Functions¶
This section documents the functions that are going on behaind the scenes, for the benefit of developers.
Special functions needed for model execution¶
These functions have no direct analog in the standard python data analytics stack, or require information about the internal state of the system beyond what is present in the function call. We provide them in a structure that makes it easy for the model elements to call.
-
class
pysd.functions.
Functions
(component_class)[source]¶ Provides SD-specific calculations that are not available in python standard libraries, or have a different functional form to those specified in the libraries, and therefore are in need of translation.
This is implemented as a class, with a local pointer to the model components class, because some of these functions need to reference the internal state of the model. Mostly they are just referencing the simulation time.
-
bounded_normal
(minimum, maximum, mean, std, seed)[source]¶ Implements vensim’s BOUNDED NORMAL function
-
if_then_else
(condition, val_if_true, val_if_false)[source]¶ Replicates vensim’s IF THEN ELSE function.
-
Building the python model file¶
These elements are used by the translator to construct the model from the interpreted results. It is technically possible to use these functions to build a model from scratch. But - it would be rather error prone.
-
class
pysd.builder.
ComponentClass
[source]¶ This is a template class to be subclassed and fleshed out by the translation tools.
A function should be added for every flow or auxiliary variable, having the name of that variable, taking no parameters, which calculates the value of the variable.
A function should be added for each stock called d<stockname>_dt() which calculates the net inflow to the stock as a function of the flows.
A function should be added for each stock called <stockname>_init() which calculates the (potentially dynamically generated) initial value for the stock.
This docstring will be rewritten and dynamically generated.
-
d_dt
(state_vector, t)[source]¶ The primary purpose of this function is to interact with the integrator. It takes a state vector, sets the state of the system based on that vector, and returns a derivative of the state vector
-
doc
()[source]¶ This function returns an aggregation of all of the docstrings of all of the elements in the model.
-
initial_time
()[source]¶ This function represents the initial time as set in the model file It should be overwritten during the class extension.
-
-
pysd.builder.
new_model
(filename)[source]¶ Starts a new python file (saved under filename) where translations from the vensim model file or XMILE model file will be implemented as a python class.
-
pysd.builder.
add_stock
(filename, identifier, expression, initial_condition)[source]¶ Adds a stock to the python model file based upon the interpreted expressions for the initial condition.
- identifier: <string> valid python identifier
- Our translators are responsible for translating the model identifiers into something that python can use as a function name.
- expression: <string>
- Note that these expressions will be added as a function body within the model class. They need to be written with with appropriate syntax, ie: self.functioncall() * self.otherfunctioncall()
- initial_condition: <string>
- An expression that defines the value that the stock should take on when the model is initialized. This may be a constant, or a call to other model elements.
-
pysd.builder.
add_flaux
(filename, identifier, expression, doc='')[source]¶ Adds a flow or auxiliary element to the model.
- identifier: <string> valid python identifier
- Our translators are responsible for translating the model identifiers into something that python can use as a function name.
- expression: <string>
- Note that these expressions will be added as a function body within the model class. They need to be written with with appropriate syntax, ie: self.functioncall() * self.otherfunctioncall()
-
pysd.builder.
add_lookup
(filename, identifier, valid_range, copair_list)[source]¶ Constructs a function that implements a lookup. The function encodes the coordinate pairs as numeric values in the python file.
- identifier: <string> valid python identifier
- Our translators are responsible for translating the model identifiers into something that python can use as a function name.
- range: tuple
- Minimum and maximum bounds on the lookup. Currently, we don’t do anything with this, but in the future, may use it to implement some error checking.
- copair_list: a list of tuples, eg. [(0, 1), (1, 5), (2, 15)]
- The coordinates of the lookup formatted in coordinate pairs.
-
pysd.builder.
add_n_delay
(filename, delay_input, delay_time, initial_value, order)[source]¶ Constructs stock and flow chains that implement the calculation of a delay.
- delay_input: <string>
- Reference to the model component that is the input to the delay
- delay_time: <string>
- Can be a number (in string format) or a reference to another model element which will calculate the delay. This is calculated throughout the simulation at runtime.
- initial_value: <string>
- This is used to initialize the stocks that are present in the delay. We initialize the stocks with equal values so that the outflow in the first timestep is equal to this value.
- order: int
- The number of stocks in the delay pipeline. As we construct the delays at build time, this must be an integer and cannot be calculated from other model components. Anything else will yield a ValueError.


openfam::fam::fam_put
Copy a segment of memory from local memory to FAM.
Synopsis
int fam_put_blocking(void *local, Fam_Descriptor *descriptor, uint64_t
offset, uint64_t nbytes);
void fam_put_nonblocking(void *local, Fam_Descriptor *descriptor, uint64_t
offset, uint64_t nbytes);
Description
Copy (part of) some data item from local memory to FAM.
Input Arguments
| Name | Description |
|---|---|
| Local | Appropriately sized area of local memory to use as source. |
| Descriptor | Descriptor associated with the data item in FAM for the destination. |
| Offset | Byte offset from the start of the data item in FAM. |
| Nbytes | Number of bytes to copy. |
Return Values
The non-blocking call does not return a value on success; the blocking call returns an integer value following normal C convention of 0 for successful completion. Both non-blocking and blocking call throws an exception on error.
Exceptions
| Exception | Description |
|---|---|
| Fam_InvalidOption_Exception | incorrect parameters are passed. |
| Fam_Datapath_Exception | error occurred during write operation over fabric. |
| FAM_ERR_LIBFABRIC | libfabric error occurred. |
| Fam_Timeout_Exception | number of libfabric retry count reached the timeout limit. (Only for blocking call) |
| FAM_ERR_NOPERM | Caller does not have access rights |
| FAM_ERR_ALREADYEXIST | the data item name is already present in FAM |
| FAM_ERR_GRPC | there is a communication error with memory server |
| FAM_ERR_RPC_CLIENT_NOTFOUND | Memory server initialization failure |
Notes
See notes for fam_get.
Example
#include <string.h> #include <fam/fam.h> #include <fam/fam_exception.h> using namespace std; using namespace openfam; int main(void) { fam *myFam = new fam(); // ... Initialization code here try { // look up the descriptor to a previously allocated data item // (a 50 element integer array) Fam_Descriptor *descriptor = myFam->fam_lookup("myItem", "myRegion"); // allocate an integer array and initialize it int local[] = {0,1,2,3,4,5,6,7,8,9}; // replace elements 6-15 of the data item in FAM with values in local memory myFam->fam_put_blocking(local, descriptor, 6*sizeof(int), 10*sizeof(int)); // ... we now have completed a copy from local memory to FAM printf("Completed a copy from local memory to FAM\n"); } catch (Fam_Exception &e) { printf("fam API failed: %d: %s\n", e.fam_error(), e.fam_error_msg()); } // ... Finalization code follows }


Ocean [an83], ocean, in The Outer Sea
Last updated Turn #136
Ocean [an83], ocean, in The Outer Sea
------------------------------------------------------------------------
17: Sirocco Traveller [ja8y], ship, 10 hulls, 1 rowing port, 30 sails,
17: 4% damaged, arrived from Ocean [an82], owner:
17: Toulouse [h1q], Pen, with one peasant, one worker, 32 sailors
17: Audrey [j9v], Pen, with 38 lt. xbowmen, three skirmishers,
17: three riding horses, accompanied by:
17: Cindy [z1c], Pen, with 38 pikemen
17: Herbal Harriet [w3d], refugee, prisoner
18: Sirocco Traveller [ja8y], ship, 10 hulls, 1 rowing port, 30 sails,
18: 4% damaged, departed for Island [aa2y].
18: Sirocco Traveller [ja8y], ship, 10 hulls, 1 rowing port, 30 sails,
18: 4% damaged, arrived from Ocean [an83], owner:
18: Toulouse [h1q], Pen, with one peasant, one worker, 32 sailors
18: Audrey [j9v], Pen, with 38 lt. xbowmen, three skirmishers,
18: three riding horses, accompanied by:
18: Cindy [z1c], Pen, with 38 pikemen
18: Herbal Harriet [w3d], refugee, prisoner
19: Audrey [j9v], Pen, with 38 lt. xbowmen, three skirmishers,
19: three riding horses, exited Sirocco Traveller [ja8y], accompanied by:
19: Cindy [z1c], Pen, with 38 pikemen
19: Toulouse [h1q], Pen, with one peasant, one worker, 32 sailors
19: Herbal Harriet [w3d], refugee, prisoner
19: Giant spider [ca3r] attacks Audrey [j9v]!
19:
19: Giant spider [ca3r], giant spiders, number: 12
19:
19: Audrey [j9v], Pen, behind 9, with 38 lt. xbowmen,
19: three skirmishers, three riding horses, accompanied by:
19: Cindy [z1c], Pen, with 38 pikemen
19: Toulouse [h1q], Pen, behind 5, with one peasant, one worker,
19: 32 sailors
19:
19: Initial missile round for the defense (Audrey [j9v]):
19: Zero missile hits!
19:
19: Combat round: one
19: Missile phase:
19: Audrey's forces hit with two missiles.
19: Giant spider [ca3r] loses two giant spiders [278].
19: Melee phase:
19: Giant spider's forces hit ten times.
19: Audrey's forces hit three times.
19: Giant spider [ca3r] loses three giant spiders [278].
19: Cindy [z1c] loses ten pikemen [16].
19: Combat round: two
19: Missile phase:
19: Audrey's forces hit with six missiles.
19: Giant spider [ca3r] loses six giant spiders [278].
19: Melee phase:
19: Giant spider's forces hit one time.
19: Audrey's forces miss!
19: Cindy [z1c] loses one pikeman [16].
19: Combat round: three
19: Missile phase:
19: Audrey's forces hit with two missiles.
19: Giant spider [ca3r] suffers a hit!
19:
19: Audrey [j9v] is victorious!
19:
19: Audrey lost 11 pikemen.
19:
19: Giant spider lost 11 giant spiders.
19: Giant spider [ca3r] was killed.
19:
19: Pirate [is2b] attacks Audrey [j9v]!
19:
19: Pirate [is2b], pirates, number: 14
19:
19: Audrey [j9v], Pen, behind 9, with 38 lt. xbowmen,
19: three skirmishers, three riding horses, accompanied by:
19: Cindy [z1c], Pen, with 27 pikemen
19: Toulouse [h1q], Pen, behind 5, with one peasant, one worker,
19: 32 sailors
19:
19: Initial missile round for the defense (Audrey [j9v]):
19: 11 missiles hit!
19: Pirate [is2b] loses 11 pirates [24].
19:
19: Combat round: one
19: Missile phase:
19: Audrey's forces hit with 15 missiles.
19: Pirate [is2b] loses two pirates [24].
19: Melee phase:
19: Pirate's forces hit one time.
19: Audrey's forces hit two times.
19: Pirate [is2b] suffers a hit!
19: Cindy [z1c] loses one pikeman [16].
19:
19: Audrey [j9v] is victorious!
19:
19: Audrey lost one pikeman.
19:
19: Pirate lost 13 pirates.
19: Pirate [is2b] was killed.
19:
26: Audrey [j9v], Pen, with 38 lt. xbowmen, three skirmishers,
26: three riding horses, entered Sirocco Traveller [ja8y],
26: accompanied by:
26: Cindy [z1c], Pen, with 26 pikemen
26: Toulouse [h1q], Pen, with one peasant, one worker, 32 sailors
26: Herbal Harriet [w3d], refugee, prisoner
26: Old man [hn0y], refugee, prisoner
26: Sirocco Traveller [ja8y], ship, 10 hulls, 1 rowing port, 30 sails,
26: 4% damaged, departed for Ocean [an83].
26: Sirocco Traveller [ja8y], ship, 10 hulls, 1 rowing port, 30 sails,
26: 4% damaged, arrived from Island [aa2y], owner:
26: Toulouse [h1q], Pen, with one peasant, one worker, 32 sailors,
26: accompanied by:
26: Audrey [j9v], Pen, with 38 lt. xbowmen, three skirmishers,
26: three riding horses
26: Cindy [z1c], Pen, with 26 pikemen
26: Herbal Harriet [w3d], refugee, prisoner
26: Old man [hn0y], refugee, prisoner
27: Sirocco Traveller [ja8y], ship, 10 hulls, 1 rowing port, 30 sails,
27: 4% damaged, departed for Ocean [an84].
30: It has stopped raining.
Routes leaving Ocean:
North, to Ocean [am83], 6 days
East, to Ocean [an84], 5 days
South, to Ocean [ao83], 6 days
West, to Ocean [an82], 5 days
Inner locations:
Island [aa2y], island, 1 day
It is windy.


Randomize words
Generate Password
Password will appear here.
Please type the keywords you actually see in the above password here.
Generate Sentence
Sentence will appear here.


Hybrid Equations (HyEQ) Toolbox v2.04
A Toolbox for Simulating Hybrid Systems in
MATLAB/Simulink®;
Ricardo G. Sanfelice
University of California
Santa Cruz, CA 95064
USA
David A. Copp
University of California
Santa Barbara, CA 93109
USA
Pablo Nanez
Universidad de Los Andes
Colombia
May 17, 2017
Abstract
This note describes the Hybrid Equations (HyEQ) Toolbox implemented in MATLAB/Simulink for the simulation of hybrid dynamical systems. This toolbox is capable of simulating individual and interconnected hybrid systems where multiple hybrid systems are connected and interact such as a bouncing ball on a moving platform, fireflies synchronizing their flashing, and more. The Simulink implementation includes four basic blocks that define the dynamics of a hybrid system. These include a flow map, flow set, jump map, and jump set. The flows and jumps of the system are computed by the integrator system which is comprised of blocks that compute the continuous dynamics of the hybrid system, trigger jumps, update the state of the system and simulation time at jumps, and stop the simulation. We also describe a “lite simulator” which allows for faster simulation.
To get started, a webinar introducing the HyEQ Toolbox is available at
http://www.mathworks.com/videos/hyeq-a-toolbox-for-simulation-of-hybrid-dynamical-systems-81992.html
A free two-step registration is required by Mathworks.
A hybrid system is a dynamical system with continuous and discrete dynamics. Several mathematical models for hybrid systems have appeared in literature. In this paper, we consider the framework for hybrid systems used in [?, ?, ?, ?], where a hybrid system on a state space ℝn with input space ℝm is defined by the following objects:
We consider the simulation in MATLAB/Simulink of hybrid systems = (C,f,D,g) written as
The flow map f defines the continuous dynamics on the flow set C, while the jump map g defines the discrete dynamics on the jump set D. These objects are referred to as the data of the hybrid system , which at times is explicitly denoted as = (C,f,D,g). We illustrate this framework in a simple, yet rich in behavior, hybrid system.
Example 1.1 (bouncing ball system) Consider a model for a bouncing ball written as
where γ > 0 is the gravity constant and λ ∈ [0,1) is the restitution coefficient. In this model, we consider the ball to be bouncing on a floor at a height of 0. This model is re-visited as an example in Section 3 and Section 5. _The remainder of this note is organized as follows. In Section 2, we describe how to install the HyEQ Toolbox in MATLAB. In Section 3, we introduce the Lite HyEQ Simulator for solving hybrid systems without inputs. In Section 4, we introduce the HyEQ Simulator implemented in Simulink for solving single and interconnected hybrid systems with inputs. In Section 5, we work through several examples for the simulation of single and interconnected hybrid systems. In Section ??, we give directions to where the simulator files can be downloaded.
The following procedure describes how to install the Hybrid Equations (HyEQ) Toolbox in MATLAB. This installation adds useful .m files to the MATLAB library and several blocks to the Simulink block library.
Steps for installation:
Now the HyEQ Toolbox is ready for use.
If you wish to uninstall the HyEQ Toolbox from MATLAB, simply run the tbclean.m file inside the HyEQ_Toolbox_V2_04 folder, and follow the on-screen prompts.
One way to simulate hybrid systems is to use ODE function calls with events in MATLAB. Such an implementation gives fast simulation of a hybrid system.
In the lite HyEQ solver, four basic functions are used to define the data of the hybrid system as in (1) (without inputs):
Our Lite HyEQ Simulator uses a main function run.m to initialize, run, and plot solutions for the simulation, functions f.m, C.m, g.m, and D.m to implement the data of the hybrid system, and HyEQsolver.m which will solve the differential equations by integrating the continuous dynamics, ẋ = f(x), and jumping by the update law x+ = g(x). The ODE solver called in HyEQsolver.m initially uses the initial or most recent step size, and after each integration, the algorithms in HyEQsolver.m check to see if the solution is in the set C, D, or neither. Depending on which set the solution is in, the simulation is accordingly reset following the dynamics given in f or g, or the simulation is stopped. This implementation is fast because it also does not store variables to the workspace and only uses built-in ODE function calls.
Time and jump horizons are set for the simulation using TSPAN = [TSTART TFINAL] as the time interval of the simulation and JSPAN = [JSTART JSTOP] as the interval for the number of discrete jumps allowed. The simulation stops when either the time or jump horizon, i.e. the final value of either interval, is reached.
The example below shows how to use the HyEQ solver to simulate a bouncing ball.
Example 3.1 (bouncing ball with Lite HyEQ Solver) Consider the hybrid system model for the bouncing ball with data given in Example 1.1.
For this example, we consider the ball to be bouncing on a floor at zero height. The constants for the bouncing ball system are γ = 9.81 and λ = 0.8. The following procedure is used to simulate this example in the Lite HyEQ Solver:
Example code for each of the MATLAB files run.m, f.m, C.m, g.m, and D.m is given below.
1 %--------------------------------------------------------------------------
2 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
3 % https://hybrid.soe.ucsc.edu/software
4 % http://hybridsimulator.wordpress.com/
5 % Filename: run_ex1_2a.m
6 %--------------------------------------------------------------------------
7 % Project: Simulation of a hybrid system (bouncing ball)
8 %--------------------------------------------------------------------------
9 %--------------------------------------------------------------------------
10 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
11 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
12 % Copyright @ Hybrid Systems Laboratory (HSL),
13 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
14
15 function run_ex1_2a
16 % initial conditions
17 x1_0 = 1;
18 x2_0 = 0;
19 x0 = [x1_0;x2_0];
20
21 % physical variables
22 global gamma lambda
23 gamma = -9.81; % gravity constant
24 lambda = 0.8; % restitution coefficent
25
26 % simulation horizon
27 TSPAN=[0 10];
28 JSPAN = [0 20];
29
30 % rule for jumps
31 % rule = 1 -> priority for jumps
32 % rule = 2 -> priority for flows
33 rule = 1;
34
35 options = odeset('RelTol',1e-6,'MaxStep',.1);
36
37 % simulate
38 [t j x] = HyEQsolver( @f_ex1_2a,@g_ex1_2a,@C_ex1_2a,@D_ex1_2a,...
39 x0,TSPAN,JSPAN,rule,options);
40
41 % plot solution
42 figure(1) % position
43 clf
44 subplot(2,1,1), plotHarc(t,j,x(:,1));
45 grid on
46 ylabel('x_1 position')
47 subplot(2,1,2), plotHarc(t,j,x(:,2));
48 grid on
49 ylabel('x_2 velocity')
50
51 % plot phase plane
52 figure(2) % position
53 clf
54 plotHarcColor(x(:,1),j,x(:,2),t);
55 xlabel('x_1')
56 ylabel('x_2')
57 grid on
58
59 % plot hybrid arc
60 figure(3)
61 plotHybridArc(t,j,x)
62 xlabel('j')
63 ylabel('t')
64 zlabel('x1')
65
1 function xdot = f_ex1_2a(x)
2 %--------------------------------------------------------------------------
3 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
4 % https://hybrid.soe.ucsc.edu/software
5 % http://hybridsimulator.wordpress.com/
6 % Filename: f_ex1_2a.m
7 %--------------------------------------------------------------------------
8 % Project: Simulation of a hybrid system (bouncing ball)
9 % Description: Flow map
10 %--------------------------------------------------------------------------
11 %--------------------------------------------------------------------------
12 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
13 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
14 % Copyright @ Hybrid Systems Laboratory (HSL),
15 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
16
17 % state
18 x1 = x(1);
19 x2 = x(2);
20
21 global gamma
22
23 % differential equations
24 xdot = [x2 ; gamma];
25 end
1 function [value] = C_ex1_2a(x)
2 %--------------------------------------------------------------------------
3 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
4 % https://hybrid.soe.ucsc.edu/software
5 % http://hybridsimulator.wordpress.com/
6 % Filename: C_ex1_2a.m
7 %--------------------------------------------------------------------------
8 % Description: Flow set
9 % Return 0 if outside of C, and 1 if inside C
10 %--------------------------------------------------------------------------
11 %--------------------------------------------------------------------------
12 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
13 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
14 % Copyright @ Hybrid Systems Laboratory (HSL),
15 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
16
17
18 x1 = x(1);
19
20 if x1 >= 0
21 value = 1;
22 else
23 value = 0;
24 end
25 end
1 function xplus = g_ex1_2a(x)
2 %--------------------------------------------------------------------------
3 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
4 % https://hybrid.soe.ucsc.edu/software
5 % http://hybridsimulator.wordpress.com/
6 % Filename: g_ex1_2a.m
7 %--------------------------------------------------------------------------
8 % Project: Simulation of a hybrid system (bouncing ball)
9 % Description: Jump map
10 %--------------------------------------------------------------------------
11 %--------------------------------------------------------------------------
12 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
13 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
14 % Copyright @ Hybrid Systems Laboratory (HSL),
15 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
16
17 % state
18 x1 = x(1);
19 x2 = x(2);
20
21 global lambda
22
23 xplus = [-x1 ; -lambda⋆x2];
24 end
1 function inside = D_ex1_2a(x)
2 %--------------------------------------------------------------------------
3 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
4 % https://hybrid.soe.ucsc.edu/software
5 % http://hybridsimulator.wordpress.com/
6 % Filename: D_ex1_2a.m
7 %--------------------------------------------------------------------------
8 % Description: Jump set
9 % Return 0 if outside of D, and 1 if inside D
10 %--------------------------------------------------------------------------
11 %--------------------------------------------------------------------------
12 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
13 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
14 % Copyright @ Hybrid Systems Laboratory (HSL),
15 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
16
17 x1 = x(1);
18 x2 = x(2);
19 if (x1 <= 0 && x2 <= 0)
20 inside = 1;
21 else
22 inside = 0;
23 end
24 end
A solution to the bouncing ball system from x(0,0) = [1,0]⊤ and with TSPAN = [0 10],JSPAN = [0 20], rule = 1, is depicted in Figure 1(a) (height) and Figure 1(b) (velocity). Both the projection onto t and j are shown. Figure 2 depicts the corresponding hybrid arc for the position state.
For MATLAB files of this example, see Examples/Example_1.2. _
The solver function HyEQsolver solves the hybrid system using three different functions as shown below. First, the
flows are calculated using the built-in ODE solver function ODE45 in MATLAB. If the solution leaves the flow set C,
the discrete event is detected using the function zeroevents as shown in Section 3.1.1. When the state jumps, the
next value of the state is calculated via the jump map g using the function jump as shown in Section
3.1.2.
1 function [t j x] = HyEQsolver(f,g,C,D,x0,TSPAN,JSPAN,rule,options,solver,E)
2 %HYEQSOLVER solves hybrid equations.
3 % Syntax: [t j x] = HYEQSOLVER(f,g,C,D,x0,TSPAN,JSPAN,rule,options,solver,E)
4 % computes solutions to the hybrid equations
5 %
6 % \dot{x} = f(x,t,j) x \in C x^+ = g(x,t,j) x \in D
7 %
8 % where x is the state, f is the flow map, g is the jump map, C is the
9 % flow set, and D is the jump set. It outputs the state trajectory (t,j)
10 % -> x(t,j), where t is the flow time parameter and j is the jump
11 % parameter.
12 %
13 % x0 defines the initial condition for the state.
14 %
15 % TSPAN = [TSTART TFINAL] is the time interval. JSPAN = [JSTART JSTOP] is
16 % the interval for discrete jumps. The algorithm stop when the first
17 % stop condition is reached.
18 %
19 % rule (optional parameter) - rule for jumps
20 % rule = 1 (default) -> priority for jumps rule = 2 -> priority for
21 % flows
22 %
23 % options (optional parameter) - options for the solver see odeset f.ex.
24 % options = odeset('RelTol',1e-6);
25 % options = odeset('InitialStep',eps);
26 %
27 % solver (optional parameter. String) - selection of the desired ode
28 % solver. All ode solvers are suported, exept for ode15i. See help
29 % odeset for detailed information.
30 %
31 % E (optional parameter) - Mass matrix [constant matrix | function_handle]
32 % For problems:
33 % E⋆\dot{x} = f(x) x \in C
34 % x^+ = g(x) x \in D
35 % set this property to the value of the constant mass matrix. For
36 % problems with time- or state-dependent mass matrices, set this
37 % property to a function that evaluates the mass matrix. See help
38 % odeset for detailed information.
39 %
40 % Example: Bouncing ball with Lite HyEQ Solver
41 %
42 % % Consider the hybrid system model for the bouncing ball with data given in
43 % % Example 1.2. For this example, we consider the ball to be bouncing on a
44 % % floor at zero height. The constants for the bouncing ball system are
45 % % \gamma=9.81 and \lambda=0.8. The following procedure is used to
46 % % simulate this example in the Lite HyEQ Solver:
47 %
48 % % ⋆ Inside the MATLAB script run_ex1_2.m, initial conditions, simulation
49 % % horizons, a rule for jumps, ode solver options, and a step size
50 % % coefficient are defined. The function HYEQSOLVER.m is called in order to
51 % % run the simulation, and a script for plotting solutions is included.
52 % % ⋆ Then the MATLAB functions f_ex1_2.m, C_ex1_2.m, g_ex1_2.m, D_ex1_2.m
53 % % are edited according to the data given below.
54 % % ⋆ Finally, the simulation is run by clicking the run button in
55 % % run_ex1_2.m or by calling run_ex1_2.m in the MATLAB command window.
56 %
57 % % For further information, type in the command window:
58 % web(['Example_1_2.html']);
59 %
60 % % Define initial conditions
61 % x1_0 = 1;
62 % x2_0 = 0;
63 % x0 = [x1_0; x2_0];
64 %
65 % % Set simulation horizon
66 % TSPAN = [0 10];
67 % JSPAN = [0 20];
68 %
69 % % Set rule for jumps and ODE solver options
70 % %
71 % % rule = 1 -> priority for jumps
72 % %
73 % % rule = 2 -> priority for flows
74 % %
75 % % set the maximum step length. At each run of the
76 % % integrator the option 'MaxStep' is set to
77 % % (time length of last integration)⋆maxStepCoefficient.
78 % % Default value = 0.1
79 %
80 % rule = 1;
81 %
82 % options = odeset('RelTol',1e-6,'MaxStep',.1);
83 %
84 % % Simulate using the HYEQSOLVER script
85 % % Given the matlab functions that models the flow map, jump map,
86 % % flow set and jump set (f_ex1_2, g_ex1_2, C_ex1_2, and D_ex1_2
87 % % respectively)
88 %
89 % [t j x] = HYEQSOLVER( @f_ex1_2,@g_ex1_2,@C_ex1_2,@D_ex1_2,...
90 % x0,TSPAN,JSPAN,rule,options,'ode45');
91 %
92 % % plot solution
93 %
94 % figure(1) % position
95 % clf
96 % subplot(2,1,1),plotflows(t,j,x(:,1))
97 % grid on
98 % ylabel('x1')
99 %
100 % subplot(2,1,2),plotjumps(t,j,x(:,1))
101 % grid on
102 % ylabel('x1')
103 %
104 % figure(2) % velocity
105 % clf
106 % subplot(2,1,1),plotflows(t,j,x(:,2))
107 % grid on
108 % ylabel('x2')
109 %
110 % subplot(2,1,2),plotjumps(t,j,x(:,2))
111 % grid on
112 % ylabel('x2')
113 %
114 % % plot hybrid arc
115 %
116 % figure(3)
117 % plotHybridArc(t,j,x)
118 % xlabel('j')
119 % ylabel('t')
120 % zlabel('x1')
121 %
122 % % plot solution using plotHarc and plotHarcColor
123 %
124 % figure(4) % position
125 % clf
126 % subplot(2,1,1), plotHarc(t,j,x(:,1));
127 % grid on
128 % ylabel('x_1 position')
129 % subplot(2,1,2), plotHarc(t,j,x(:,2));
130 % grid on
131 % ylabel('x_2 velocity')
132 %
133 %
134 % % plot a phase plane
135 % figure(5) % position
136 % clf
137 % plotHarcColor(x(:,1),j,x(:,2),t);
138 % xlabel('x_1')
139 % ylabel('x_2')
140 % grid on
141 %
142 %--------------------------------------------------------------------------
143 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
144 % https://hybrid.soe.ucsc.edu/software
145 % http://hybridsimulator.wordpress.com/
146 % Filename: HYEQSOLVER.m
147 %--------------------------------------------------------------------------
148 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
149 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
150 % Copyright @ Hybrid Systems Laboratory (HSL),
151 % Revision: <IP_ADDRESS> Date: 04/6/2017 16:26:00
152
153
154 if ~exist('rule','var')
155 rule = 1;
156 end
157
158 if ~exist('options','var')
159 options = odeset();
160 end
161 if exist('E','var') && ~exist('solver','var')
162 solver = 'ode15s';
163 end
164 if ~exist('solver','var')
165 solver = 'ode45';
166 end
167 if ~exist('E','var')
168 E = [];
169 end
170 % mass matrix (if existent)
171 isDAE = false;
172 if ~isempty(E)
173 isDAE = true;
174 switch isa(E,'function_handle')
175 case true % Function E(x)
176 M = E;
177 options = odeset(options,'Mass',M,'Stats','off',...
178 'MassSingular','maybe','MStateDependence','strong',...
179 'InitialSlope',f_hdae(x0,TSPAN(1)));
180 case false % Constant double matrix
181 M = double(E);
182 options = odeset(options,'Mass',M,'Stats','off',...
183 'MassSingular','maybe','MStateDependence','none');
184 end
185 end
186
187 odeX = str2func(solver);
188 nargf = nargin(f);
189 nargg = nargin(g);
190 nargC = nargin(C);
191 nargD = nargin(D);
192
193
194
195 % simulation horizon
196 tstart = TSPAN(1);
197 tfinal = TSPAN(end);
198 jout = JSPAN(1);
199 j = jout(end);
200
201 % simulate
202 tout = tstart;
203 [rx,cx] = size(x0);
204 if rx == 1
205 xout = x0;
206 elseif cx == 1
207 xout = x0.';
208 else
209 error('Error, x0 does not have the proper size')
210 end
211
212 % Jump if jump is prioritized:
213 if rule == 1
214 while (j<JSPAN(end))
215 % Check if value it is possible to jump current position
216 insideD = fun_wrap(xout(end,:).',tout(end),j,D,nargD);
217 if insideD == 1
218 [j tout jout xout] = jump(g,j,tout,jout,xout,nargg);
219 else
220 break;
221 end
222 end
223 end
224 fprintf('Completed: %3.0f%%',0);
225 while (j < JSPAN(end) && tout(end) < TSPAN(end))
226 options = odeset(options,'Events',@(t,x) zeroevents(x,t,j,C,D,...
227 rule,nargC,nargD));
228 % Check if it is possible to flow from current position
229 insideC = fun_wrap(xout(end,:).',tout(end),j,C,nargC);
230 if insideC == 1
231 if isDAE
232 options = odeset(options,'InitialSlope',f(xout(end,:).',tout(end)));
233 end
234 [t,x] = odeX(@(t,x) fun_wrap(x,t,j,f,nargf),[tout(end) tfinal],...
235 xout(end,:).', options);
236 nt = length(t);
237 tout = [tout; t];
238 xout = [xout; x];
239 jout = [jout; j⋆ones(1,nt)'];
240 end
241
242 %Check if it is possible to jump
243 insideD = fun_wrap(xout(end,:).',tout(end),j,D,nargD);
244 if insideD == 0
245 break;
246 else
247 if rule == 1
248 while (j<JSPAN(end))
249 % Check if it is possible to jump from current position
250 insideD = fun_wrap(xout(end,:).',tout(end),j,D,nargD);
251 if insideD == 1
252 [j tout jout xout] = jump(g,j,tout,jout,xout,nargg);
253 else
254 break;
255 end
256 end
257 else
258 [j tout jout xout] = jump(g,j,tout,jout,xout,nargg);
259 end
260 end
261 fprintf('\b\b\b\b%3.0f%%',max(100⋆j/JSPAN(end),100⋆tout(end)/TSPAN(end)));
262 end
263 t = tout;
264 x = xout;
265 j = jout;
266 fprintf('\nDone\n');
267 end
268
1 function [value,isterminal,direction] = zeroevents(x,t,j,C,D,rule,nargC,nargD)
2 switch rule
3 case 1 % -> priority for jumps
4 isterminal(1) = 1; % InsideC
5 isterminal(2) = 1; % Inside(C \cap D)
6 isterminal(3) = 1; % OutsideC
7 direction(1) = -1; % InsideC
8 direction(2) = -1; % Inside(C \cap D)
9 direction(3) = 1; % OutsideC
10 case 2 %(default) -> priority for flows
11 isterminal(1) = 1; % InsideC
12 isterminal(2) = 0; % Inside(C \cap D)
13 isterminal(3) = 1; % OutsideC
14 direction(1) = -1; % InsideC
15 direction(2) = -1; % Inside(C \cap D)
16 direction(3) = 1; % OutsideC
17 end
18
19 insideC = fun_wrap(x,t,j,C,nargC);
20 insideD = fun_wrap(x,t,j,D,nargD);
21 outsideC = -fun_wrap(x,t,j,C,nargC);
22
23
24 value(1) = 2⋆insideC;
25 value(2) = 2-insideC - insideD;
26 value(3) = 2⋆outsideC;
27
28 end
29
1 function [j tout jout xout] = jump(g,j,tout,jout,xout,nargfun)
2 % Jump
3 j = j+1;
4 y = fun_wrap(xout(end,:).',tout(end),jout(end),g,nargfun);
5 % Save results
6 tout = [tout; tout(end)];
7 xout = [xout; y.'];
8 jout = [jout; j];
9 end
10
1 function xdelta = fun_wrap(x,t,j,h,nargfun)
2 %fun_wrap Variable input arguments function (easy use for users).
3 % fun_wrap(x,t,j,h,nargfun) depending on the function h written by the
4 % user, this script selects how the HyEQ solver should call that
5 % function.
6 % x: state
7 % t: time
8 % j: discrete time
9 % h: function handle
10 % nargfun: number of input arguments of function h
11 %--------------------------------------------------------------------------
12 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
13 % https://hybrid.soe.ucsc.edu/software
14 % http://hybridsimulator.wordpress.com/
15 % Filename: fun_wrap.m
16 %--------------------------------------------------------------------------
17 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
18 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
19 % Copyright @ Hybrid Systems Laboratory (HSL),
20 % Revision: <IP_ADDRESS> Date: 01/28/2016 5:12:00
21
22
23 switch nargfun
24 case 1
25 xdelta = h(x);
26 case 2
27 xdelta = h(x,t);
28 case 3
29 xdelta = h(x,t,j);
30 end
31 end
In order to run simulations using the Lite HyEQ Simulator, MATLAB R13 or newer is required.
Before a simulation is started, it is important to determine the needed integrator scheme, zero-cross detection settings, precision, and other tolerances. Using the default settings does not always give the most efficient or most accurate simulations. In the Lite HyEQ Simulator, these parameters are edited in the run.m file using
The Lite HyEQ Simulator is initialized and run by calling the function run.m. Inside run.m, the initial conditions,
simulation horizons TSPAN and JSPAN, a rule for jumps, and simulation tolerances are defined. After all of the
parameters are defined, the function HyEQsolver is called, and the simulation runs. See below for sample code to
initialize and run the bouncing ball example, Example 3.1.
1 % initial conditions
2 x1_0 = 1;
3 x2_0 = 0;
4 x0 = [x1_0;x2_0];
5 % simulation horizon
6 TSPAN=[0,10];
7 JSPAN = [0,20];
8 % rule for jumps
9 % rule = 1 -> priority for jumps
10 % rule = 2 -> priority for flows
11 rule = 1;
12 options = odeset('RelTol',1e-6,'MaxStep',.1);
13 % simulate
14 [t,j,x] = HyEQsolver(@f,@g,@C,@D,x0,TSPAN,JSPAN,rule,options);
The function run.m is also used to plot solutions after the simulations is complete. See below for sample code to plot solutions to the bouncing ball example, Example 3.1.
1 % plot solution
2 figure(1) % position
3 clf
4 subplot(2,1,1),plotflows(t,j,x(:,1))
5 grid on
6 ylabel('x1')
7 subplot(2,1,2),plotjumps(t,j,x(:,1))
8 grid on
9 ylabel('x1')
10 figure(2) % velocity
11 clf
12 subplot(2,1,1),plotflows(t,j,x(:,2))
13 grid on
14 ylabel('x2')
15 subplot(2,1,2),plotjumps(t,j,x(:,2))
16 grid on
17 ylabel('x2')
18 % plot hybrid arc
19 figure(2)
20 plotHybridArc(t,j,x)
21 xlabel('j')
22 ylabel('t')
23 zlabel('x1')
24 grid on
25 view(37.5,30)
The following functions are used to generate the plots:
The HyEQ Toolbox includes three main Simulink library blocks that allow for simulation of a hybrid system = (C,f,D,g) using either externally defined functions or embedded MATLAB functions, and a single hybrid system or interconnected hybrid systems with inputs using embedded MATLAB functions. Figure 3 shows these blocks in the Simulink Library Browser.
Figure 4 shows a Simulink implementation for simulating a hybrid system with inputs using embedded MATLAB functions. In this implementation, four basic blocks are used to define the data of the hybrid system :
In our implementation, MATLAB .m files are used. The file initialization.m is used to define initial variables before simulation. The file postprocessing.m is used to plot the solutions after a simulation is complete. These two .m files are called by double-clicking the Double Click to... blocks at the top of the Simulink Model (see Section 4.6 for more information on these .m files and their use).
The HyEQ Toolbox includes a series of blocks that model elements of a cyber-physical system (CPS). Those models are special instances of the hybrid systems blocks described above, particularly the blocks that use embedded MATLAB functions. A cyber-physical system is given by the interconnection between a physical process, the plant, a computer algorithm used for control, the controller; and the subsystems needed to interconnect the plant and the controller, i.e., the interfaces, converters, and signal conditioners. Most of the elements described in this section are presented in an extended form in [?].
In these notes, the temporal evolution of the variables of a cyber-physical system are captured using dynamical models. In this document, we advocate that hybrid dynamical system models can be employed to capture the behavior of cyber-physical systems. More precisely, the evolution of the continuous variables is captured by differential equations while the evolution of the discrete variables is captured by difference equations. These equations are typically nonlinear due to the complexity of the dynamics of those variables. Furthermore, conditions determining the change of the continuous and discrete variables according to the said equations/inclusions can be conveniently captured by functions of the variables, inputs, and outputs. In Figure 5, cyber and physical blocks are implemented within the HyEQ simulator.
The physical components of a cyber-physical system include the analog elements, physical systems, and the environment. Consider a model of a physical system given by a differential equation ẋ = f(x,u) and a output map y = h(x,u). Among the many possible models available, we capture the dynamics of the physical components by using the hybrid systems framework by
Particularly, the model in (4) can be implemented in the simulink block HSu in Figures 4) and 5).
The cyber components of a cyber-physical system include those in charge of performing computations, implementing algorithms, and transmitting digital data over networks. The tasks performed by the code (at the software level) and the logic-based mechanisms (at the circuit level) involve variables that only change at discrete events, not necessarily periodically.
We denote the state variable of the cyber components by xc ∈ ϒ, where ϒ ⊂ ℝnC is the state space. The dynamics of η are defined by a difference equation with right-hand side defined by the map Gc. We let v ∈⊂ ℝmC denote the input signals affecting the cyber components and ζ ∈ ℝrC to be the output defined by the output function κ, which is a function of the state xc and of the input v. With these definitions, the general mathematical description of the cyber component is
In certain cases, it would be needed to impose restrictions on the state and inputs to the cyber component. Such conditions can be modeled imposing that xc and v belong to a subset of their state space, namely,|
| (6) |
The model of the cyber components is given by (5)-(6). Next, we provide specific constructions of models of cyber components.
The model for the sampling device we propose has both continuous and discrete dynamics. If the timer state has not reached Ts*, then the dynamics are such that the timer state increases continuously with a constant, unitary rate. When Ts* is reached, the timer state is reset to zero and the sample state is mapped to the inputs of the sampling device. To implement this mechanism, we employ a timer state τs ∈ ℝ≥0 and a sample state ms ∈ ℝrP. The input to the sampling device is denoted by vs ∈ ℝrp. The model of the sampling devices is
In practice, there exists a time, usually called the ADC acquisition time, between the triggering of the ADC with the sampling device and the update of its output. Such a delay limits the number of samples per second that the ADC can provide. Additionally, an ADC can store and process finite-length digital words, which causes quantization. The model above omits effects such as acquisition delays and quantization effects, but those can be incorporated if needed. In particular, quantization effects can be added to the model in (8)-(9) by replacing the update law for ms to ms+ = round(vs), where the function round is such that round(vs) is the closest number to vs that the machine precision can represent.
At every ti, the information at the input vN of the communication link is used to update the internal variable mN, which is accessible at the output end of the network and remains constant between communication events. This internal variable acts as an information buffer, which can contain not only the latest piece of information transmitted but also previously transmitted information. A record of the number of communication events is logged in the internal variable jN. At communication events, the value of jN gets updated and remains constant in-between events. A mathematical model capturing the said mechanism is given by
Note that the update law for τN at jumps is given in terms of a difference inclusion, which implies that the new value of τN is taken from the set [TN* min,TN* max]. The dimension of the states and the input would depend on the type of components that connect to and from it, and also the size of data transmitted and buffered. Similar to the models proposed for conversion, the model of the digital link (12)-(13) does not include delays nor quantization, but such effects can be incorporated if needed.
In this section we discuss the internals of the Integrator System shown in Figure 6.
This block is shown in Figure 7. It defines the continuous-time (CT) dynamics by assembling the time derivative of the state [t j x⊤]⊤. States t and j are considered states of the system because they need to be updated throughout the simulation in order to keep track of the time and number of jumps. Without t and j, solutions could not be plotted accurately. This is given by
This block is shown in Figure 8. The inputs to the jump logic block are the output of the blocks C and D indicating whether the state is in those sets or not, and a random signal with uniform distribution in [0,1]. Figure 8 shows the Simulink blocks used to implement the Jump Logic. The variable rule defines whether the simulator gives priority to jumps, priority to flows, or no priority. It is initialized in initialization.m.
The output of the Jump Logic is equal to one when:
Under these events, the output of this block, which is connected to the integrator external reset input, triggers a reset of the integrator, that is, a jump of . The reset or jump is activated since the configuration of the reset input is set to “level hold”, which executes resets when this external input is equal to one (if the next input remains set to one, multiple resets would be triggered). Otherwise, the output is equal to zero.
This block is shown in Figure 9. The update logic uses the state port information of the integrator. This port reports the value of the state of the integrator, [t j x⊤]⊤, at the exact instant that the reset condition becomes true. Notice that x- differs from x since at a jump, x- indicates the value of the state that triggers the jump, but it is never assigned as the output of the integrator. In other words, “x ∈ D” is checked using x- and if true, x is reset to g(x-,u). Notice, however, that u is the same because at a jump, u indicates the next evaluated value of the input, and it is assigned as the output of the integrator. The flow time t is kept constant at jumps and j is incremented by one. More precisely
This block is shown in Figure 10. It stops the simulation under any of the following events:
Under any of these events, the output of the logic operator connected to the Stop block becomes one, stopping the simulation. Note that the inputs C and D are routed from the output of the blocks computing whether the state is in C or D and use the value of x-.
In order to run simulations of single hybrid systems using externally defined functions, MATLAB with Simulink is required.
In order to run simulations using the HyEQ Simulator with embedded MATLAB functions, MATLAB/Simulink and a supported ANSI, C, or C++ 32-bit compiler must be installed. We now briefly describe how to install necessary compilers for Windows and Mac/Linux. For more information on supported compilers, please visit http://www.mathworks.com/support/compilers/R2012b/win64.html.
For 32-bit Windows, the LCC compiler is included with MATLAB. First, open MATLAB and then locate and choose a compiler for building MEX-files by typing
into the MATLAB command window. Then, follow the prompts as shown below.
For 64-bit Windows, a C-compiler is not supplied with MATLAB. Before running the HyEQ Toolbox in MATLAB/Simulink, please follow the following steps:
As of October 10, 2013, when installing the toolbox in Windows 8, please follow the next steps.
x86 version: http://www.microsoft.com/en-us/download/details.aspx?id=5555
x64 version: http://www.microsoft.com/en-us/download/details.aspx?id=14632
From a terminal window, check that the file gcc is in the folder /usr/bin. If it is not there, make a symbolic link. You might require to install the latest version of Xcode first. In order to generate a symbolic link for gcc, that MATLAB can find to compile the simulation files (see http://www.mathworks.com/support/sysreq/previous_releases.html), change folder to /usr/bin and then
Then, it should be possible to setup the gcc compiler in matlab as follows:
The options files available for MEX are:
At this point, it is possible to check if the gcc is properly setup by testing any of the Simulink examples with embedded functions (see Figure 3) (e.g., Examples 5.1, 5.2, 5.3, 5.4, 5.5 or 5.6).
If an error regarding “gmake” similar to “No supported compiler or SDK was found” and/or a warning “no such sysrooot directory: ′Developer/SDKs/MacOSX10.X.sdk′” is shown when compiling, please consider the following procedure.
The compiler can not find the appropriate path. It is necesary to change some lines in the file “mexopts.sh” (copied previously in the folder “SOME_FOLDER”) .
First, locate the Xcode-SDK in your hard drive. Open a terminal window and execute the following command
which returns the location of MacOSX10.9.sdk, denoted here as SDK_FOLDER. Now, in the MATLAB command window locate the file “mexopts.sh” by typing
Then, open the file
and edit the lines
to
and
to
Now, it is possible to test if the compiler works. If the following error appears “unknown type name ’char16_t’,” some flags must be changed to avoid this problem. It is required to add -Dchar16_t=UINT16_T and -std=c++11 to the flags CFLAGS and CFLAGS respectively, e.g., change
to
and
to
Finally, restart matlab and test any of the aforementioned Simulink examples. for more information visit http://www.mathworks.com/matlabcentral/answers/121315-how-to-set-the-c-compiler-of-matlab2013a-in-osx-10-9
First, locate the Xcode-SDK in your hard drive. It may be SDK 10.9, 10.10, 10.11, here we are going to denote it as 10.X. Open a terminal window and execute the following command
which returns the location of MacOSX10.X.sdk. We are interested in the last portion of the path, specifically after /Applications/Xcode.app/.Contents/Developer/, denoted here as SDK_FOLDER. Now, locate and edit the following files
Inside those files there are the lines
edit (or add below those lines) the lines
and
Finally, restart matlab and test any of the aforementioned Simulink examples. for more information visit https://bitbucket.org/d2d-development/d2d-software/issues/46/xcode-7-on-osx-with-matlab-r2015a-b
Before a simulation is started, it is important to determine the needed integrator scheme, zero-cross detection
settings, precision, and other tolerances. Using the default settings does not always give the most efficient
or most accurate simulations. One way to edit these settings is to open the Simulink Model, select
Simulation>Configuration Parameters>Solver, and change the settings there. We have made this simple by
defining variables for configuration parameters in the initialization.m file. The last few lines of the
initialization.m file look like that given below.
1 %configuration of solver
2 RelTol = 1e-8;
3 MaxStep = .001;
In these lines, “RelTol = 1e-8” and “MaxStep = .001” define the relative tolerance and maximum step size of the ODE solver, respectively. These parameters greatly affect the speed and accuracy of solutions.
When the block labeled Double Click to Initialize at the top of the Simulink Model is double-clicked, the simulation
variables are initialized by calling the script initialization.m. The script initialization.m defines the initial
conditions by defining the initial values of the state components, any necessary parameters, the maximum flow time
specified by T, the maximum number of jumps specified by J, and tolerances used when simulating. These can be
changed by editing the script file initialization.m. See below for sample code to initialize the bouncing ball
example, Example 5.1.
1 % initialization for bouncing ball example
2 clear all
3 % initial conditions
4 x0 = [1;0];
5 % simulation horizon
6 T = 10;
7 J = 20;
8 % rule for jumps
9 % rule = 1 -> priority for jumps
10 % rule = 2 -> priority for flows
11 % rule = 3 -> no priority, random selection when simultaneous conditions
12 rule = 1;
13 %configuration of solver
14 RelTol = 1e-8;
It is important to note that variables called in the Embedded MATLAB function blocks must be added as inputs and labeled as “parameters”. This can be done by opening the Embedded MATLAB function block selecting Tools>Edit Data/Ports and setting the scope to Parameter.
After the block labeled Double Click to Initialize is double-clicked and the variables initialized, the simulation is run by clicking the run button or selecting Simulation>Start.
A similar procedure is used to define the plots of solutions after the simulation is run. The solutions can be
plotted by double-clicking on the block at the top of the Simulink Model labeled Double Click to Plot
Solutions which calls the script postprocessing.m. The script postprocessing.m may be edited to
include the desired postprocessing and solution plots. See below for sample code to plot solutions to
the bouncing ball example, Example 5.1. The functions used to generate the plots are described in
Section 3.5.
1 %postprocessing for the bouncing ball example
2 % plot solution
3 figure(1)
4 clf
5 subplot(2,1,1),plotflows(t,j,x)
6 grid on
7 ylabel('x')
8 subplot(2,1,2),plotjumps(t,j,x)
9 grid on
10 ylabel('x')
11 % plot hybrid arc
12 figure(2)
13 plotHybridArc(t,j,x)
14 xlabel('j')
15 ylabel('t')
16 zlabel('x')
17 grid on
18 view(37.5,30)
The examples below illustrate the use of the Simulink implementation above.
Example 5.1 (bouncing ball with input) For the simulation of the bouncing ball system with a constant input and regular data given by
The following procedure is used to simulate this example using the model in the file Example_1_2a.slx:
Flow map
1 function xdot = f_ex1_2a(x)
2 %--------------------------------------------------------------------------
3 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
4 % https://hybrid.soe.ucsc.edu/software
5 % http://hybridsimulator.wordpress.com/
6 % Filename: f_ex1_2a.m
7 %--------------------------------------------------------------------------
8 % Project: Simulation of a hybrid system (bouncing ball)
9 % Description: Flow map
10 %--------------------------------------------------------------------------
11 %--------------------------------------------------------------------------
12 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
13 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
14 % Copyright @ Hybrid Systems Laboratory (HSL),
15 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
16
17 % state
18 x1 = x(1);
19 x2 = x(2);
20
21 global gamma
22
23 % differential equations
24 xdot = [x2 ; gamma];
25 end
Flow set
1 function [value] = C_ex1_2a(x)
2 %--------------------------------------------------------------------------
3 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
4 % https://hybrid.soe.ucsc.edu/software
5 % http://hybridsimulator.wordpress.com/
6 % Filename: C_ex1_2a.m
7 %--------------------------------------------------------------------------
8 % Description: Flow set
9 % Return 0 if outside of C, and 1 if inside C
10 %--------------------------------------------------------------------------
11 %--------------------------------------------------------------------------
12 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
13 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
14 % Copyright @ Hybrid Systems Laboratory (HSL),
15 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
16
17
18 x1 = x(1);
19
20 if x1 >= 0
21 value = 1;
22 else
23 value = 0;
24 end
25 end
Jump map
1 function xplus = g_ex1_2a(x)
2 %--------------------------------------------------------------------------
3 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
4 % https://hybrid.soe.ucsc.edu/software
5 % http://hybridsimulator.wordpress.com/
6 % Filename: g_ex1_2a.m
7 %--------------------------------------------------------------------------
8 % Project: Simulation of a hybrid system (bouncing ball)
9 % Description: Jump map
10 %--------------------------------------------------------------------------
11 %--------------------------------------------------------------------------
12 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
13 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
14 % Copyright @ Hybrid Systems Laboratory (HSL),
15 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
16
17 % state
18 x1 = x(1);
19 x2 = x(2);
20
21 global lambda
22
23 xplus = [-x1 ; -lambda⋆x2];
24 end
Jump set
1 function inside = D_ex1_2a(x)
2 %--------------------------------------------------------------------------
3 % Matlab M-file Project: HyEQ Toolbox @ Hybrid Systems Laboratory (HSL),
4 % https://hybrid.soe.ucsc.edu/software
5 % http://hybridsimulator.wordpress.com/
6 % Filename: D_ex1_2a.m
7 %--------------------------------------------------------------------------
8 % Description: Jump set
9 % Return 0 if outside of D, and 1 if inside D
10 %--------------------------------------------------------------------------
11 %--------------------------------------------------------------------------
12 % See also HYEQSOLVER, PLOTARC, PLOTARC3, PLOTFLOWS, PLOTHARC,
13 % PLOTHARCCOLOR, PLOTHARCCOLOR3D, PLOTHYBRIDARC, PLOTJUMPS.
14 % Copyright @ Hybrid Systems Laboratory (HSL),
15 % Revision: <IP_ADDRESS> Date: 05/20/2015 3:42:00
16
17 x1 = x(1);
18 x2 = x(2);
19 if (x1 <= 0 && x2 <= 0)
20 inside = 1;
21 else
22 inside = 0;
23 end
24 end
A solution to the bouncing ball system from x(0,0) = [1,0]⊤ and with T = 10,J = 20, rule = 1, is depicted in Figure 11(a) (height) and Figure 11(b) (velocity). Both the projection onto t and j are shown. Figure 12 depicts the corresponding hybrid arc for the position state.
These simulations reflect the expected behavior of the bouncing ball model. Note the only difference between this example and the example of a bouncing ball without a constant input is that, in this example, the ball bounces on a platform at a height of the chosen input value 0.2 rather than the ground at a value of 0.
For MATLAB/Simulink files of this example, see Examples/Example_1.2a. _
Example 5.2 (alternate way to simulate the bouncing ball)
Consider the bouncing ball system with a constant input and regular data as given in Example 5.1. This example shows that a MATLAB function block, such as the jump set D, can be replaced with operational blocks in Simulink. Figure 13 shows this implementation. The other functions and solutions are the same as in Example 5.1.
For MATLAB/Simulink files of this example, see Examples/Example_1.3 and Examples/Example_1.4. _
Example 5.3 (vehicle following a track with boundaries) Consider a vehicle modeled by a Dubins vehicle model traveling along a given track with state vector x = [ξ1,ξ2,ξ3]⊤ with dynamics given by = ucosξ3, = usinξ3, and = -ξ3 + r(q). The input u is the tangential velocity of the vehicle, ξ1 and ξ2 describe the vehicle’s position on the plane, and ξ3 is the vehicle’s orientation angle. Also consider a switching controller attempting to keep the vehicle inside the boundaries of a track given by {(ξ1,ξ2) : -1 ≤ ξ1 ≤ 1}. A state q ∈{1,2} is used to define the modes of operation of the controller. When q = 1, the vehicle is traveling to the left, and when q = 2, the vehicle is traveling to the right. A logic variable r is defined in order to steer the vehicle back inside the boundary. The state of the closed-loop system is given by x := [ξ⊤ q]⊤. A model of such a closed-loop system is given by
The MATLAB scripts in each of the function blocks of the implementation above are given as follows. The tangential velocity of the vehicle is chosen to be u = 1, the initial position on the plane is chosen to be (ξ1,ξ2) = (0,0), and the initial orientation angle is chosen to be ξ3 = radians.
Flow map
1 function xdot = f(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (Vehicle Traveling on a Track)
7 %
8 % Name: f.m
9 %
10 % Description: Flow map
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 xtemp = zeros(4,1);
17 xtemp = x;
18 x = xtemp;
19
20 % state
21 xi1 = x(1); %x-position
22 xi2 = x(2); %y-position
23 xi3 = x(3); %orientation angle
24 q = x(4);
25
26 % q = 1 --> going left
27 % q = 2 --> going right
28
29 if q == 1
30 r = 3⋆pi/4;
31 elseif q == 2
32 r = pi/4;
33 else
34 r = 0;
35 end
36
37 % flow map: xidot=f(xi,u);
38 xi1dot = u⋆cos(xi3); %tangential velocity in x-direction
39 xi2dot = u⋆sin(xi3); %tangential velocity in y-direction
40 xi3dot = -xi3 + r; %angular velocity
41 qdot = 0;
42
43 xdot = [xi1dot;xi2dot;xi3dot;qdot];
Flow set
1 function v = C(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (Vehicle Traveling on a Track)
7 %
8 % Name: C.m
9 %
10 % Description: Flow set
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 xtemp = zeros(4,1);
17 xtemp = x;
18 x = xtemp;
19
20 % state
21 xi1 = x(1); %x-position
22 xi2 = x(2); %y-position
23 xi3 = x(3); %orientation angle
24 q = x(4);
25
26 % q = 1 --> going left
27 % q = 2 --> going right
28
29 if ((xi1 < 1) && (q == 2)) || ((xi1 > -1) && (q == 1)) % flow condition
30 v = 1; % report flow
31 else
32 v = 0; % do not report flow
33 end
Jump map
1 function xplus = g(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (Vehicle Traveling on a Track)
7 %
8 % Name: g.m
9 %
10 % Description: Jump map
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 xtemp = zeros(4,1);
17 xtemp = x;
18 x = xtemp;
19 % state
20 xi1 = x(1); %x-position
21 xi2 = x(2); %y-position
22 xi3 = x(3); %orientation angle
23 q = x(4);
24
25 % q = 1 --> going left
26 % q = 2 --> going right
27 xi1plus=xi1;
28 xi2plus=xi2;
29 xi3plus=xi3;
30 qplus=q;
31
32 % jump map
33 if ((xi1 >= 1) && (q == 2)) || ((xi1 <= -1) && (q == 1))
34 qplus = 3-q;
35 else
36 qplus = q;
37 end
38
39 xplus = [xi1plus;xi2plus;xi3plus;qplus];
Jump set
1 function v = D(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (Vehicle Traveling on a Track)
7 %
8 % Name: D.m
9 %
10 % Description: Jump set
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 xtemp = zeros(4,1);
17 xtemp = x;
18 x = xtemp;
19
20 % state
21 xi1 = x(1); %x-position
22 xi2 = x(2); %y-position
23 xi3 = x(3); %orientation angle
24 q = x(4);
25
26 % q = 1 --> going left
27 % q = 2 --> going right
28
29 if ((xi1 >= 1) && (q == 2)) || ((xi1 <= -1) && (q == 1)) % jump condition
30 v = 1; % report jump
31 else
32 v = 0; % do not report jump
33 end
A solution to the system of a vehicle following a track in {(ξ1,ξ2) : -1 ≤ ξ1 ≤ 1}, and with T = 15,J = 10, rule = 1, is depicted in Figure 14(a) (trajectory). Both the projection onto t and j are shown. Figure 14(b) depicts the corresponding hybrid arc.
For MATLAB/Simulink files of this example, see Examples/Example_1.5. _
Example 5.4 (interconnection of hybrid systems 1 (bouncing ball) and 2 (moving platform)) Consider a bouncing ball (1) bouncing on a platform (2) at some initial height and converging to the ground at zero height. This is an interconnection problem because the current states of each system affect the behavior of the other system. In this interconnection, the bouncing ball will contact the platform, bounce back up, and cause a jump in height of the platform so that it gets closer to the ground. After some time, both the ball and the platform will converge to the ground. In order to model this system, the output of the bouncing ball becomes the input of the moving platform, and vice versa. For the simulation of the described system with regular data where 1 is given by
Therefore, the interconnection may be defined by the input assignment
|
| (24) |
The signals v1 and v2 are included as external inputs in the model in order to simulate the effects of environmental perturbations, such as a wind gust, on the system.
The MATLAB scripts in each of the function blocks of the implementation above are given as follows. The constants for the interconnected system are γ = 0.8, b = 0.1, and α1,α2 = 0.1.
Flow map
1 function xdot = f(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: f.m
9 %
10 % Description: Flow map
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % state
17 xi1 = x(1);
18 xi2 = x(2);
19
20 %input
21 y2 = u(1);
22 v11 = u(2);
23 v12 = u(3);
24
25 % flow map
26 %xdot=f(x,u);
27 xi1dot = xi2;
28 xi2dot = -0.8-0.1⋆xi2+v11;
29
30 xdot = [xi1dot;xi2dot];
Flow set
1 function v = C(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: C.m
9 %
10 % Description: Flow set
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % state
17 xi1 = x(1);
18 xi2 = x(2);
19
20 %input
21 y2 = u(1);
22 v11 = u(2);
23 v12 = u(3);
24
25 if (xi1 >= y2) % flow condition
26 v = 1; % report flow
27 else
28 v = 0; % do not report flow
29 end
Jump map
1 function xplus = g(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: g.m
9 %
10 % Description: Jump map
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % state
17 xi1 = x(1);
18 xi2 = x(2);
19
20 %input
21 y2 = u(1);
22 v11 = u(2);
23 v12 = u(3);
24
25 xi1plus=y2+0.1⋆xi2^2;
26 xi2plus=0.8⋆abs(xi2)+v12;
27
28 xplus = [xi1plus;xi2plus];
Jump set
1 function v = D(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: D.m
9 %
10 % Description: Jump set
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % state
17 xi1 = x(1);
18 xi2 = x(2);
19
20 %input
21 y2 = u(1);
22 v11 = u(2);
23 v12 = u(3);
24
25
26 if (xi1 <= y2) % jump condition
27 v = 1; % report jump
28 else
29 v = 0; % do not report jump
30 end
Flow map
1 function xdot = f(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: f.m
9 %
10 % Description: Flow map
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16
17 % state
18 eta1 = x(1);
19 eta2 = x(2);
20
21 %input
22 y1 = u(1);
23 v21 = u(2);
24 v22 = u(3);
25
26 % flow map
27 eta1dot = eta2;
28 eta2dot = -eta1-2⋆eta2+v21;
29
30 xdot = [eta1dot;eta2dot];
Flow set
1 function v = C(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: C.m
9 %
10 % Description: Flow set
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % state
17 eta1 = x(1);
18 eta2 = x(2);
19
20 %input
21 y1 = u(1);
22 v21 = u(2);
23 v22 = u(3);
24
25 if (eta1 <= y1) % flow condition
26 v = 1; % report flow
27 else
28 v = 0; % do not report flow
29 end
Jump map
1 function xplus = g(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: g.m
9 %
10 % Description: Jump map
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % state
17 eta1 = x(1);
18 eta2 = x(2);
19
20 %input
21 y1 = u(1);
22 v21 = u(2);
23 v22 = u(3);
24
25 % jump map
26 eta1plus = y1-0.1⋆abs(eta2);
27 eta2plus = -0.8⋆abs(eta2)+v22;
28
29 xplus = [eta1plus;eta2plus];
Jump set
1 function v = D(x, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system
7 %
8 % Name: D.m
9 %
10 % Description: Jump set
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % state
17 eta1 = x(1);
18 eta2 = x(2);
19
20 %input
21 y1 = u(1);
22 v21 = u(2);
23 v22 = u(3);
24
25
26 if (eta1 >= y1) % jump condition
27 v = 1; % report jump
28 else
29 v = 0; % do not report jump
30 end
A solution to the interconnection of hybrid systems 1 and 2 with T = 18,J = 20, rule = 1, is depicted in Figure 16. Both the projection onto t and j are shown. A solution to the hybrid system 1 is depicted in Figure 17(a) (height) and Figure 17(b) (velocity). A solution to the hybrid system 2 is depicted in Figure 18(a) (height) and Figure 18(b) (velocity).
These simulations reflect the expected behavior of the interconnected hybrid systems.
For MATLAB/Simulink files of this example, see Examples/Example_1.6. _
Example 5.5 (biological example: synchronization of two fireflies) Consider a biological example of the synchronization of two fireflies flashing. The fireflies can be modeled mathematically as periodic oscillators which tend to synchronize their flashing until they are flashing in phase with each other. A state value of τi = 1 corresponds to a flash, and after each flash, the firefly automatically resets its internal timer (periodic cycle) to τi = 0. The synchronization of the fireflies can be modeled as an interconnection of two hybrid systems because every time one firefly flashes, the other firefly notices and jumps ahead in its internal timer τ by (1 + ε)τ, where ε is a biologically determined coefficient. This happens until eventually both fireflies synchronize their internal timers and are flashing simultaneously.
Each firefly can be modeled as a hybrid system given by
For hybrid system i, i = 1,2:
Flow map
1 function taudot = f(tau, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: f.m
9 %
10 % Description: Flow map
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % flow map
17 taudot = 1;
Flow set
1 function v = C(tau, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: C.m
9 %
10 % Description: Flow set
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 %flow set
17 if ((tau > 0) && (tau < 1)) || ((u > 0) && (u <= 1)) % flow condition
18 v = 1; % report flow
19 else
20 v = 0; % do not report flow
21 end
Jump map
1 function tauplus = g(tau, u, e)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: g.m
9 %
10 % Description: Jump map
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 % jump map
17 if (1+e)⋆tau < 1
18 tauplus = (1+e)⋆tau;
19 elseif (1+e)⋆tau >= 1
20 tauplus = 0;
21 else
22 tauplus = tau;
23 end
Jump set
1 function v = D(tau, u)
2
3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4 % Matlab Function Author: Ricardo Sanfelice
5 %
6 % Project: Simulation of a hybrid system (interconnection)
7 %
8 % Name: D.m
9 %
10 % Description: Jump set
11 %
12 % Version: 1.0
13 % Required files: -
14 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
15
16 if (u >= 1) || (tau >= 1) % jump condition
17 v = 1; % report jump
18 else
19 v = 0; % do not report jump
20 end
A solution to the interconnection of hybrid systems 1 and 2 with T = 15,J = 15, rule = 1, ε = 0.3 is depicted in Figure 21. Both the projection onto t and j are shown. A solution to the hybrid system 1 is depicted in Figure 20(a). A solution to the hybrid system 2 is depicted in Figure 20(b).
These simulations reflect the expected behavior of the interconnected hybrid systems. The fireflies initially flash out of phase with one another and then synchronize to flash in the same phase.
For MATLAB/Simulink files of this example, see Examples/Example_1.7. _
Example 5.6 (a simple mathematical example to show different type of simulation results) Consider the hybrid system with data
Note that solutions from ξ = 1 and ξ = 2 are nonunique. The following simulations show the use of the variable rule in the Jump Logic block.
Jumps enforced: A solution from x0 = 1 with T = 10,J = 20, rule = 1 is depicted in Figure 22(a). The solution jumps from 1 to 2, and from 2 to 1 repetitively.
Flows enforced: A solution from x0 = 1 with T = 10,J = 20, rule = 2 is depicted in Figure 22(b). The solution flows for all time and converges exponentially to zero.
Random rule: A solution from x0 = 1 with T = 10,J = 20, rule = 3 is depicted in Figure 23(a). The solution jumps to 2, then jumps to 1 and flows for the rest of the time converging to zero exponentially. Enlarging D to
This simulation also reveals that this implementation does not precisely generate hybrid arcs. The maximum step size was set to 0.1e - 3. The solution flows during the first two steps of the integration of the flows with maximum step size. The value at t = 0.1e - 3 is very close to 1. At t = 0.2e - 3, instead of assuming a value given by the flow map, the value of the solution is about 0.5, which is the result of the jump occurring at (0.2e - 3,0). This is the value stored in x at such time by the integrator. Note that the value of x′ at (0.2e - 3,0) is the one given by the flow map that triggers the jump, and if available for recording, it should be stored in (0.2e - 3,0). This is a limitation of the current implementation.
The following simulations show the Stop Logic block stopping the simulation at different events.
Solution outside C ∪ D: Taking D = {1}, a simulation starting from x0 = 1 with T = 10,J = 20, rule = 1 stops since the solution leaves C ∪ D. Figure 24(a) shows this.
Solution reaches the boundary of C from where jumps are not possible: Replacing the flow set by [1∕2,1] a solution starting from x0 = 1 with T = 10,J = 20 and rule = 2 flows for all time until it reaches the boundary of C where jumps are not possible. Figure 24(b) shows this.
Note that in this implementation, the Stop Logic is such that when the state of the hybrid system is not in (C ∪ D), then the simulation is stopped. In particular, if this condition becomes true while flowing, then the last value of the computed solution will not belong to C. It could be desired to be able to recompute the solution so that its last point belongs to the corresponding set. From that point, it should be the case that solutions cannot be continued.
For MATLAB/Simulink files of this example, see Examples/Example_1.8. _
Example 5.7 (Linear time-invariant plant)
Following the model of a physical component in (4), a linear time-invariant model of the physical component is defined by
Example 5.8 (Implementation of a FSM)
Transitions of the state of a FSM are triggered by changes of its input v. The system can be modeled as a cascade of two systems, in which an external signal drives the FSM. The FSM is modeled as the difference equation in (7). Assuming that the input feeds the input u of the FSM, the state of the FSM is updated according to the transition function evaluated at the current input, that is, q is updated according to


The MatDialog
service can be used to open modal dialogs with Material Design styling and
animations.
A dialog is opened by calling the open
method with a component to be loaded and an optional
config object. The open
method will return an instance of MatDialogRef
:
let dialogRef = dialog.open(UserProfileComponent, {
height: '400px',
width: '600px',
});
The MatDialogRef
provides a handle on the opened dialog. It can be used to close the dialog and to
receive notification when the dialog has been closed.
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog result: ${result}`); // Pizza!
});
dialogRef.close('Pizza!');
Components created via MatDialog
can inject MatDialogRef
and use it to close the dialog
in which they are contained. When closing, an optional result value can be provided. This result
value is forwarded as the result of the afterClosed
promise.
@Component({/* ... */})
export class YourDialog {
constructor(public dialogRef: MatDialogRef<YourDialog>) { }
closeDialog() {
this.dialogRef.close('Pizza!');
}
}
entryComponents
Because MatDialog
instantiates components at run-time, the Angular compiler needs extra
information to create the necessary ComponentFactory
for your dialog content component.
For any component loaded into a dialog, you must include your component class in the list of
entryComponents
in your NgModule definition so that the Angular compiler knows to create
the ComponentFactory
for it.
@NgModule({
imports: [
// ...
MatDialogModule
],
declarations: [
AppComponent,
ExampleDialogComponent
],
entryComponents: [
ExampleDialogComponent
],
bootstrap: [AppComponent]
})
export class AppModule {}
Default dialog options can be specified by providing an instance of MatDialogConfig
for
MAT_DIALOG_DEFAULT_OPTIONS in your application's root module.
@NgModule({
providers: [
{provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: {hasBackdrop: false}}
]
})
If you want to share data with your dialog, you can use the data
option to pass information to the dialog component.
let dialogRef = dialog.open(YourDialog, {
data: { name: 'austin' },
});
To access the data in your dialog component, you have to use the MAT_DIALOG_DATA injection token:
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material/dialog';
@Component({
selector: 'your-dialog',
template: 'passed in {{ data.name }}',
})
export class YourDialog {
constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }
}
Note that if you're using a template dialog (one that was opened with a TemplateRef
), the data
will be available implicitly in the template:
<ng-template let-data>
Hello, {{data.name}}
</ng-template>
Several directives are available to make it easier to structure your dialog content:
| Name | Description |
|---|---|
mat-dialog-title |
[Attr] Dialog title, applied to a heading element (e.g., <h1> , <h2> ) |
<mat-dialog-content> |
Primary scrollable content of the dialog. |
<mat-dialog-actions> |
Container for action buttons at the bottom of the dialog. Button alignment can be controlled via the align attribute which can be set to end and center . |
mat-dialog-close |
[Attr] Added to a <button> , makes the button close the dialog with an optional result from the bound value. |
For example:
<h2 mat-dialog-title>Delete all elements?</h2>
<mat-dialog-content>This will delete all elements that are currently on this page and cannot be undone.</mat-dialog-content>
<mat-dialog-actions>
<button mat-button mat-dialog-close>Cancel</button>
<!-- The mat-dialog-close directive optionally accepts a value as a result for the dialog. -->
<button mat-button [mat-dialog-close]="true">Delete</button>
</mat-dialog-actions>
Once a dialog opens, the dialog will automatically focus the first tabbable element.
You can control which elements are tab stops with the tabindex
attribute
<button mat-button tabindex="-1">Not Tabbable</button>
By default, each dialog has role="dialog"
on the root element. The role can be changed to
alertdialog
via the MatDialogConfig
when opening.
The aria-label
, aria-labelledby
, and aria-describedby
attributes can all be set to the
dialog element via the MatDialogConfig
as well. Each dialog should typically have a label
set via aria-label
or aria-labelledby
.
When a dialog is opened, it will move focus to the first focusable element that it can find. In order to prevent users from tabbing into elements in the background, the Material dialog uses a focus trap to contain focus within itself. Once a dialog is closed, it will return focus to the element that was focused before the dialog was opened.
If you're adding a close button that doesn't have text (e.g. a purely icon-based button), make sure
that it has a meaningful aria-label
so that users with assistive technology know what it is used
for.
By default, the first tabbable element within the dialog will receive focus upon open. This can
be configured by setting the cdkFocusInitial
attribute on another focusable element.
Tabbing through the elements of the dialog will keep focus inside of the dialog element, wrapping back to the first tabbable element when reaching the end of the tab sequence.
By default pressing the escape key will close the dialog. While this behavior can
be turned off via the disableClose
option, users should generally avoid doing so
as it breaks the expected interaction pattern for screen-reader users.


Test_java_net_URL.test_getContent()
.
It contains the string
A Seemingly Non Important String
. Which is
looked for in the testcase.
A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph. A bunch of text representing part of a paragraph.
The End.


Some text inside the dialog
More text inside the dialog
This is the first tab contents
Looks nice, rights?
This is the second tab contents
Easy to use, right?


Images
Home
(current)
Progressive
Responsive Progressive
Image Effect
Chroma Sampling
Decode Promise


Write a script that allocates array of 20 integers and initializes each element by its index multiplied
by 5.
Print the obtained array on the console.
Problem 2. Lexicographical comparison
Write a script that compares two char arrays lexicographically (letter by letter).
Problem 3. Maximal sequence
Write a script that finds the maximal sequence of equal elements in an array.
Problem 4. Maximal increasing sequence
Write a script that finds the maximal increasing sequence in an array.
Problem 5. Selection sort
Write a script to sort an array
Use the selection sort algorithm: Find the smallest element, move it at the first position, find the
smallest from the rest, move it at the second position, etc.
Hint: Use a second array
Problem 6. Most frequent number
Write a program that finds the most frequent number in an array.
Problem 7. Binary search
Write a program that finds the index of given element in a sorted array of integers by using the binary
search algorithm


Speech
Ofsted's Chief Inspector, Sir Michael Wilshaw, spoke to the Fair Education Alliance in London about addressing educational inequality.
Good evening everyone. I am really pleased to have been asked to take part in this event to mark the launch of your latest annual report card.
As I approach the end of my tenure as Her Majesty’s Chief Inspector, I am saddened, but not surprised, by many of your findings. My motivation and commitment to the cause of educational equality and social mobility remains as strong today as it did on the day I first entered a classroom in Bermondsey nearly half a century ago. And let me tell you about that first class, because it has a bearing on what I’m going to say tonight.
Since Tracey disappeared into the mists of East London to do an unskilled job, somewhere on the Bermondsey dockside, the world has changed. The world economy has changed, and expectations have changed. Quite rightly we have much higher expectations of what our children can achieve to prepare them for this vastly different economic landscape.
If Tracey were growing up in today’s world she would have more choices and better options. Children from all walks of life should now be able to achieve any goal. Expectations are higher, our schools are better – in part thanks to Ofsted – and there is definitely more opportunity for all.
The fact that many more of our children from across the social spectrum are doing well is a cause for optimism.
So why am I standing here making this speech? Because, although we are doing better, we are not doing anywhere near well enough to compete with the best jurisdictions in the world. And we are certainly not doing well enough for our poorest children. What is particularly worrying is that we are not doing well enough for our brightest children coming from poor backgrounds.
There’s that damning statistic, the one that keeps me awake at night, from the Sutton Trust. Seven thousand of our brightest children, mainly from poorer backgrounds, were in the top 10% nationally at age 11 but were not in the top 25% at GCSE 5 years later.
I therefore applaud the collective efforts of the people in this room who have come together under the umbrella of the Fair Education Alliance to try to do something about educational inequality.
And let’s be clear. This isn’t simply about doing right by a certain sector of society. Tackling inequality benefits the whole of our education system. When we improve standards for the most disadvantaged then standards improve nationally. As Lord Adonis, the pioneer of the original academies programme, understood, if you tackle problems at the bottom end there will be a trickle-up effect through the whole sector.
One of my first acts as Chief Inspector was to assemble an expert panel of head teachers, academics and educational leaders to undertake an in-depth study into the educational achievements of England’s poorest children. This was a follow-up to the landmark reports published by 2 of my predecessors in 1993 and in 2003.
My report on access and achievement, entitled Unseen Children , concluded that poverty of expectation had become a greater problem than material poverty. The children of poor parents with high expectations were doing much better academically than those whose parents and teachers expected little of them.
The report also found that the distribution of underachievement had shifted. Twenty or 30 years ago, the problems were in urban areas, especially inner London schools. At that time these were the worst-achieving in the country.
By 2013, schools in inner as well as outer London had become the highest performing in England. Instead, we found that many of the poor children being let down by the system in recent times attended schools either in generally affluent areas with small numbers of free school meal children or in places that were relatively isolated, such as rural communities and coastal towns.
I made a series of recommendations for politicians and policy-makers on the back of these findings.
Among the most important of these were:
The report also recognised the fundamental importance of early years in shaping the future prospects of young people.
Of course there is no magic bullet or shortcut to success. The Fair Education Alliance ( FEA ) itself sets out an ambitious array of recommendations for how we can make things better. Tonight I would like to concentrate on progress we have seen and the challenges that still lie ahead.
I have said many times before that underachievement starts from birth. Too many children are given a poor start in the essential early years. I whole-heartedly support the recommendations of your report for more use of qualified teachers in this sector.
Children who fall behind in the early years of their life struggle to make up for it in later years. If by age 7, a child cannot read, the odds are stacked against them. If children cannot count, sit still, follow instructions or hold a pencil properly when they leave Reception, they will always be playing catch-up.
This is why I have long argued that effective nursery and primary schools are the best places for very young children from disadvantaged homes. In these schools, clear routines bring order and security into the lives of young children and help build self-assurance as well as awareness of the needs of others.
In our last Annual Report for the Early Years , I suggested that there was a strong case for schools taking many more of the poorest children from the age of 2. Schools have the in-built advantage of being able to offer continuity across the transition to Reception, have more access to specialist support, employ well-qualified graduate teachers and are familiar with tracking children’s development.
I also called for much more to be done to encourage parents of the poorest 2-year-old children to take up the offer of a funded place in a high-quality provider. We found that nearly half of all 2-year-olds (around 113,000) eligible for 15 hours of free early education had not taken up their place in any type of setting. It is essential that more is done, through children’s centres and health visitors, to promote greater take-up.
It is vital that we do far more to attract and incentivise the best people to lead underperforming schools in challenging areas. All my experience has taught me that when schools are chaotic it is the poor and vulnerable who suffer most. The lack of structure at home is replicated at school and, unlike their peers from middle class backgrounds, poor parents often lack the capacity to compensate for deficiencies in the school and in the classroom. Therefore getting good leadership into these areas is of fundamental importance.
The government’s recently published White Paper talks about “rebalancing incentives” and “investing in targeted initiatives” to boost leadership capacity in challenging areas and to create career pathways for people who want to work in the areas where they are most needed.
This is certainly something I welcome, along with the emerging National Teachers Service, particularly given they were a key feature of my report, and I look forward to hearing more detail about these measures and, more important, seeing them bearing fruit.
The FEA proposals for incentivising teachers to different areas, with schemes such as mortgage-deposit support, are exactly the sort of innovative thinking that we should be exploring to help with this challenge. We need to get vocational and post 16 education right.
The Unseen Children report expressed my concerns about the overall quality of provision for the many children who would prefer an alternative to university. Our system is adept at guiding students into higher education. However, as the House of Lords social mobility committee found last week, it still struggles, despite the recent focus on apprenticeships, to inform them about alternative career pathways available to them.
We simply have to improve the quality of our technical provision and present it as a valid educational path if we are to equip youngsters – especially those from poorer backgrounds – with the skills they need and employers want.
We are making strides in the right direction here, with ambitious targets for the creation and quality of apprenticeships and a growing number of university technical colleges coming into the system.
As the Alliance report card recognises, we need to ensure that careers advice in schools improves so that young people understand the different options in front of them and can make informed choices about their future.
We need more focus on those areas that are not delivering the necessary high standards for their children. I welcome the government’s White Paper proposals for focusing efforts in ‘Achieving Excellence Areas’. This version of my suggestion of ‘sub-regional challenges’ will only succeed if local politicians, be they mayors, council leaders or cabinet members, are prepared to take ownership of school performance no matter what the governance structure and status of the school.
We need them to be visible, high-profile figures that people can recognise as education champions. The great success stories in London would not have happened without the drive and commitment of the likes of Jules Pipe and Sir Robin Wales in Hackney and in Newham, respectively.
There is ultimately, however, only so much that the school can achieve without the commitment of parents and carers.
We need to ensure schools do more to engage with those parents who don’t care enough about their children’s education.
As the chief executive of Centre Forum observed last week, many white British pupils are falling behind students from other ethnic backgrounds by the time they take their GCSEs because of a lack of support from their parents.
The family is the great educator. We need more leaders who have no qualms about reminding parents of their obligation to be a good parent – coming to open evenings, making sure their child does their homework, reading to them and listening to them read.
I know this is a difficult task but it is not impossible.
As I recounted in a radio interview just this morning, it can be tough to get these parents on board. I often speculate on how useful it would be for heads to have the ability to fine those who have the capacity but wilfully choose not to engage.
Let’s not allow ourselves to be too pessimistic.
I do not underestimate how difficult it is to educate children who are poor and who lack all the advantages that a more affluent background confers. I understand that it’s a lot easier to teach children who don’t come to school hungry, who live in homes filled with books, who have parents that are employed, let alone university educated.
I spent most of my professional career trying to enthuse children whom others had written off. It isn’t easy for schools to compensate for social disadvantage. But never make the mistake that because it’s difficult, schools cannot make a difference. They can.
We know that we can overcome the challenges of poverty because we have seen it happen. In London, with effective, tenacious leadership and political will, failure turned into stunning success over a relatively short period of time. There is no reason, in my view, that this sort of success cannot be replicated elsewhere.
This FEA report has focused on the progress that is being made in the North East of England. We also know there are schools in places like Portsmouth and Barking and Dagenham that are now bucking the trend in terms of the achievement of poorer children, especially from white British backgrounds.
It is not only a moral imperative that we should do better for our poorest youngsters, but also crucial if we are going to become a more productive nation and a more socially-cohesive one.
If we are to compete with the best jurisdictions in the world then we need more organisations, politicians and leaders to collaborate and support schools, and ensure that every young person gets the standard of education they deserve.
It’s only through commitment, ambition and determination that we will break the pattern of underachievement in challenging areas of the country and create a more fair and equal society. A society where every child has the same life chances regardless of where they live.
I commend all of you in this room for your commitment to those goals.