%% Schedule Subsystems to Execute at Specific Times
% This example shows how to design a _temporal logic scheduler_ in
% Stateflow(R). The temporal logic scheduler design pattern allows you to
% schedule Simulink(R) subsystems to execute at specified times.

% Copyright 2007-2019 The MathWorks, Inc.

%%
model = 'sf_temporal_logic_scheduler';
load_system(model)

% Delete all annotations at the top level of the model
ah = find_system(model, 'FindAll', 'on', 'type', 'annotation');
for i = 1:length(ah)
   ao = get_param(ah(i), 'Object');
   ao.delete;
end

% Update chart
set_param(model,'SimulationCommand','Update')

open_system(model)

%% Key Behavior of the Temporal Logic Scheduler
% In this example, the Temporal Logic Scheduler chart contains two states
% that schedule the execution of three function-call subsystems (A1, A2,
% and A3) at different rates, as determined by the temporal logic operator
% |<docid:stateflow_ref#every every>|.

open_system([model '/Temporal Logic Scheduler']);

%% 
% When the |FastScheduler| state is active, the chart schedules function
% calls to different Simulink subsystems at a fraction of the base rate at
% which the input event |call| wakes up the chart.
% 
% * The chart sends an event to execute subsystem A1 at the base rate.
% * The chart sends an event to execute subsystem A2 at half the base rate.
% * The chart sends an event to execute subsystem A3 at one quarter the
% base rate.
%
% When the |SlowScheduler| state is active, the chart schedules function
% calls for A1, A2, and A3 at 1/8, 1/16, and 1/32 times the base rate.
%
% The chart switches between the fast and slow execution modes after every
% 100 invocations of the |call| event.

%% Run the Temporal Logic Scheduler
% When you simulate the model, the scope displays the value of y at each
% time step.

sim(model);
open_system([model '/Scope']);

%%
% The changes in value illustrate the different rates of execution.
%
% * When the chart executes the subsystems at a slow rate (for example,
% from $t=4.5$ to $t=4.6$, from $t=4.7$ to $t=4.8$, and from $t=4.9$ to
% $t=5.0$), the values change slowly.
% * When the chart executes the subsystems at a fast rate (for example,
% from $t=4.6$ to $t=4.7$ and from $t=4.8$ to $t=4.9$), the values change
% rapidly.

