.. _events:

Events
------

.. index:: ! events

In the first chapter on :ref:`basic-equations` we saw examples of how
to describe continuous behavior.  The equations introduced in that
chapter applied at all times and the solutions to those equations were
always continuous.  In this chapter, we discussed the various ways in
Modelica to describe discrete behavior.  Events are the root cause of
all discrete behavior in Modelica.

Conditional Expressions
^^^^^^^^^^^^^^^^^^^^^^^

.. index:: time events

.. index:: ! time

Events are generated in one of two ways.  First, they can be generated
by conditional expressions.  In the first few examples in this
chapter, we saw that conditional expressions can trigger events.  If
these conditional expressions only involve the variable ``time``, then
we call them "time events".  The ``time`` variable is a built-in,
global variable that is treated as an "input" to all models.

.. index:: state events

If events are generated because of conditional expressions that
involve solution variables, then we call them "state events".  The
important distinctions between time events and state events were
discussed in the :ref:`first <cooling-revisited>` and :ref:`second
<bouncing-ball>` sections of this chapter, respectively.

Conditional expressions can be created using the relational operators
(``>``, ``>=``, ``<``, ``<=``, ``==``) and logical operators (``not``,
``and``, ``or``).  As we saw in our discussion of :ref:`no-event`, it
is possible to suppress the events generated by these conditional
expressions by surrounding them with the ``noEvent`` operator.

Frequently, these event generating conditional expressions occur in
the context of an ``if`` statement or an ``if`` expression.  But it
should also be noted that even a simple variable assignment, *e.g.,*

.. code-block:: modelica

      Boolean late;
    equation
      late = time>=5.0 "This will generate an event";

can trigger an event to be generated.

Piecewise Constructions
***********************

There is an important special case when dealing with conditional
expressions.  In some cases, it is useful to create an expression that
is constructed piecewise.  For example,

.. code-block:: modelica

    x = if (x<0) then 0 else x^3;

It is hard for a Modelica compiler to reliably determine that such a
function is continuous and has continuous derivatives.  For
this reason, Modelica includes the ``smooth`` operator to explicitly
express such conditions.  For example, using the ``smooth`` operator
as follows:

.. code-block:: modelica

    x = smooth(2, if (x<0) then 0 else x^3);

indicates that the expression is continuous as is and will remain
continuous if differentiated up to 2 times because

.. math::

   x' & =
     \begin{cases}
       0,        & \text{for } x < 0, \\
       3 \, x^2, & \text{otherwise,}
     \end{cases} \\
   x'' & =
     \begin{cases}
       0,        & \text{for } x < 0, \\
       6 \, x, \phantom{^2} & \text{otherwise,}
     \end{cases} \\
   x''' & =
     \begin{cases}
       0,        & \text{for } x < 0, \\
       6, \phantom{6 \, ^2}& \text{otherwise.}
     \end{cases}

Hence, the function, its first and second derivatives are continuous
at :math:`x=0`, but the third derivative is discontinuous.

Note that the ``smooth`` operator requires an upper bound
to be specified.

Events and Functions
^^^^^^^^^^^^^^^^^^^^

In addition to being generated by conditional expressions, events can
also be generated by certain functions in Modelica.

Event Generating Functions
**************************

The following is a list of functions that generate events wherever the
return value has a discontinuity.

====================  ========================================================
Function               Description
--------------------  --------------------------------------------------------
``div(x,y)``           Algebraic quotient with fractional part discarded.
``mod(x,y)``           Modulus of ``x``/``y``
``rem(x,y)``           Remainder from the algebraic quotient
``ceil(x)``            Smallest integer not less than ``x``
``floor(x)``           Largest integer not greater than ``x`` (returns a ``Real``)
``integer(x)``         Largest integer not greater than ``x`` (returns an ``Integer``)
``initial()``          ``true`` during initialization, otherwise ``false``
``terminal()``         ``true`` at end of simulation, otherwise ``false``
``sample(t0,dt)``      Generates an event at ``t0`` and every ``dt`` seconds later
``edge(x)``            ``true`` only at the instant that ``x`` is ``true``
``change(x)``          ``true`` whenever ``x`` changes value
====================  ========================================================

Non-Event Generating Functions
******************************

The following is a table of functions that do **not** generate events:

====================  ========================================================
Function               Description
--------------------  --------------------------------------------------------
``abs(x)``             Absolute value of ``x``
``sign(x)``            Sign of ``x`` (-1, 0, or 1)
``sqrt(x)``            Square root of ``x``
``min(x,y)``           Minimum value between ``x`` and ``y``
``max(x,y)``           Maximum value between ``x`` and ``y``
====================  ========================================================

Event Related Operators
***********************

The following operators provide special information about event
generating signals:

======================  ========================================================
Function                 Description
----------------------  --------------------------------------------------------
``pre(x)``               During an event, holds the value of ``x`` before the event
``previous(x)``          During clock tick, value of ``x`` during previous clock tick
``hold(x)``              Anytime, value of ``x`` during previous clock tick
``sample(expr,clock)``   During clock tick, value of ``expr``
``noEvent(expr)``        Suppresses events generated by ``expr``
``smooth(p,expr)``       Indicates ``expr`` can be safely differentiated ``p`` times.
======================  ========================================================

Clock Related Operators
***********************

The following operators are used to create a manipulate clocks (event
generators that trigger at regular intervals):

======================  ========================================================
Function                 Description
----------------------  --------------------------------------------------------
``Clock(i,r)``           A clock that fires every :math:`\frac{i}{r}` seconds where ``i`` and ``r`` are both of type ``Integer``
``Clock(dt)``            A clock that fires every :math:`dt` seconds where ``dt`` is a ``Real``
``subSample(u,s)``       A clock that samples ``s`` times slower than the clock used to sample ``u`` where ``s`` is an ``Integer``
``superSample(u,s)``     A clock that samples ``s`` times as fast as the clock used to sample ``u`` where ``s`` is an ``Integer``
======================  ========================================================

Note that the ``Clock`` constructor function is overloaded (*i.e.,*
can take different arguments).  It is worth reiterating that the
synchronous clock features in Modelica are relatively new.  As such,
they are not yet supported by all Modelica compilers.  To learn more
about these synchronous features and their applications see
[Elmqvist]_ and/or the Modelica Specification, version 3.3 or later.
