Cyber-Physical Systems (BIL-435), week 3 of 14

Discrete and Hybrid Dynamics: State Machines, Thermostats and Protection Relays

Prof. Dr. Utku Kose, Süleyman Demirel University

Overview

Week 2 described quantities that change smoothly with time. Many parts of the campus also switch between a few distinct modes. A charger waits, charges or reports a fault. A thermostat turns the heater on and off, a relay trips a breaker, and the whole campus can leave the city grid and run as an island. This week models such behaviour with state machines. It then joins them with the differential equations of Week 2 into hybrid automata [1, 2].

flowchart LR
  A["Finite state machines"] --> B["Hybrid automata: The thermostat"]
  B --> C["Protection: The overcurrent relay"]
  C --> D["The microgrid as a hybrid system"]
  D --> S["The campus microgrid, stage 3"]
  S --> FT["In the field: A relay"]
  FT --> H["Learning state machines from data"]
Python code of this week

Every method on this page is also written as Python code in the Colab notebook of the week. Its code is divided into numbered sections. Each orange box on this page names the section whose code carries out what the text above the box explains. The box says what to run and what to look at in that section, and its button opens the Colab notebook at that place. The virtual laboratories, the practice parts and the self-assessment of the week are in the interactive lab. Each blue box opens one part of the interactive lab. The part ends with a link back to its box on this page, and the Colab notebook is always opened from the orange boxes here.

Python step 3: States and transitions

Open in Colab

Python code in the Colab notebook, right after Section 0 (setup). Open the Colab notebook and run this step cell by cell: It consists of short pieces of Python code with their explanations, a quick check and three exercises. Topics: Dictionaries as tables · Tuples as keys: A transition table · Sets: The states that can be reached · Formatted traces.

The step works with the built-in types of Python [3]. It writes a transition table as a dictionary whose keys are pairs of a state and an event. It then collects the states that a machine can reach in a set and prints traces with formatted strings. Students who have never programmed start with the start-here notebook of the course.

The campus microgrid so far

Week 1 computed the balance of the campus hour by hour, and Week 2 gave the battery, the library and the frequency of the island their dynamics. The evening shaving of Week 2 leaves the battery at a state of charge of 0.144 at 21:00.

This week adds the modes of the campus: The chargers, the thermostat of the library, the protection of the feeders and the controller of the island.

The campus microgrid through the fourteen weeks of the course. The figure marks the stage of this week.
The campus microgrid through the fourteen weeks of the course. The figure marks the stage of this week.

Finite state machines: Modes and events

A finite state machine has a finite set of states, a set of input events and a transition function. The function names the next state for each pair of a state and an event [1]. Each state can set outputs, for example a contact that is open or closed. The machine is deterministic when every pair leads to at most one next state:

\[s_{k+1} = \delta(s_k, e_k), \qquad y_k = \lambda(s_k)\]

\(s_k\) is the state after \(k\) events, \(e_k\) the next event, \(\delta\) the transition function and \(\lambda\) the output function. An event without a transition is ignored, and the state stays. The sequence of states is the trace of the machine.

Each charger of the car park is such a machine. The International Electrotechnical Commission (IEC) defines its states in the standard IEC 61851-1 for the charging of electric vehicles [4]. The states follow the voltage of the control pilot, a signal wire in the charging cable. In state A, no car is connected, and the pilot carries +12 V. In state B, a car is connected and pulls the pilot down to +9 V. In state C, the car is ready, the pilot reads +6 V and the charger closes its contactor. In state F, the charger is not available and drives the pilot to -12 V [4].

The charger also announces the current that the car may draw, with the duty cycle \(D\) of a square wave on the pilot. For duty cycles from 10 to 85 percent, the current is \(I = D \times 0.6\) A, with \(D\) in percent [4]. A charger of 22 kW on three phases allows 32 A, a duty cycle of \(32/0.6 = 53.3\) percent.

The state machine of a charger of the car park, with the voltage of the control pilot and the contactor of each state. An event without an arrow leaves the state unchanged.
The state machine of a charger of the car park, with the voltage of the control pilot and the contactor of each state. An event without an arrow leaves the state unchanged.

A worked example. A charger in state A receives the events plug, ready, full, ready and unplug. Its trace is A, B, C, B, C, A, and the contactor closes twice. The table holds 9 of the 24 possible pairs of a state and an event; the other 15 pairs leave the state unchanged. A safety property is a condition that must hold in every state that some sequence of events can reach. For the charger, the contactor is closed in state C and only there.

Scene: The charger as a state machine. A charger of the car park with a car in the bay. The buttons send the events plug, ready, full, unplug, fault and reset. The state, the voltage of the control pilot and the contactor follow the table of the lecture, and an event without a transition is ignored. The grey buttons have no transition in the current state, and the diagram below the view marks the state and the last transition.

Check your understanding. A charger in state B receives the event full. What happens?

Open in Colab

Python code in the Colab notebook, Section 1. Open Section 1 of the Colab notebook and run it. The dictionary CHARGER holds the transition table of this section, and run carries out the transition function for a list of events. The code prints the trace of the worked example, the states that can be reached and the check of the safety property.

Discuss: What the table leaves out
  1. The table of the charger ignores every event that it does not list. When is ignoring an event safe, and when should a machine report it?
  2. How would you test that a real charger behaves as its table says?

Hybrid automata: The thermostat of the library

A hybrid automaton joins a state machine with continuous dynamics [5]. Each discrete state, called a mode, has its own differential equation, the flow. An invariant says how long the system may stay in a mode, and a guard on the continuous state enables a transition. A transition can also reset continuous variables, for example a timer.

The thermostat of the library is a hybrid automaton with two modes, written in capitals as OFF and ON [1]. In mode OFF, the room cools as in Week 2. In mode ON, the heater adds its power:

\[\text{OFF:}\ C\,\dot{T} = \frac{T_{out} - T}{R},\ T \ge T_{lo} \qquad \text{ON:}\ C\,\dot{T} = \frac{T_{out} - T}{R} + P,\ T \le T_{hi}\]

The thermostat switches the heater on when the temperature falls to \(T_{lo} = T_{set} - h/2\), and off when it rises to \(T_{hi} = T_{set} + h/2\). The band \(h\) of the hysteresis keeps the heater from switching at every small change of the measurement [6]. Between the switchings, the temperature follows the exponential curves of Week 2, which gives the duration of each mode:

\[t_{on} = \tau \ln\frac{T_{ss,on} - T_{lo}}{T_{ss,on} - T_{hi}}, \qquad t_{off} = \tau \ln\frac{T_{hi} - T_{out}}{T_{lo} - T_{out}}, \qquad T_{ss,on} = T_{out} + R\,P\]

→ These formulas with numbers, step by step: Lab Part A, calculator, steps 1 to 5.

A worked example. The thermostat holds 21 °C with a band of 1 K, so \(T_{lo} = 20.5\) °C and \(T_{hi} = 21.5\) °C. At 5 °C outside, the heater of 60 kW aims at \(T_{ss,on} = 29\) °C. It runs for \(t_{on} \)​\({}= 12 \ln(8.5/7.5) \)​\({}= 12 \times 0.1252 \)​\({}= 1.502\) h, or 90.1 min. The room then cools for \(t_{off} \)​\({}= 12 \ln(16.5/15.5) \)​\({}= 12 \times 0.0625 \)​\({}= 0.750\) h, or 45.0 min. One cycle lasts 2.252 h, so the heater switches \(48/2.252 = 21.3\) times a day, with an average power of \(60 \times 1.502/2.252 = 40.0\) kW.

The average power equals the 40 kW that holds 21 °C in Week 2. The band only trades the swing of the temperature against the wear of the contactor: Half the band halves both times and doubles the switchings. A band of zero would ask for infinitely many switchings, which no contactor can follow.

Animation. The thermostat of the library over 24 hours. The sliders set the band of the hysteresis and the outdoor temperature, and the orange bars mark the heater on. The readouts give the on time, the off time, the switchings a day and the average power. Try a band of 0.2, 1 and 2 K, and an outdoor temperature of -4 °C.

Left: The library with a band of 1 K at 5 °C outside on its second day, with the heater on in the orange bars. Right: The switchings of the heater a day against the band of the hysteresis.
Left: The library with a band of 1 K at 5 °C outside on its second day, with the heater on in the orange bars. Right: The switchings of the heater a day against the band of the hysteresis.

Check your understanding. The band of the thermostat shrinks from 1 K to 0.5 K. What happens?

Open lab Part A

Interactive lab, Part A. The thermostat step by step: The thresholds, the steady state with the heater on, the on time, the off time and the switchings a day.

Open in Colab

Python code in the Colab notebook, Section 2. Open Section 2 of the Colab notebook and run it. The function thermostat simulates the two modes and their guards minute by minute, and cycle_times carries out the formulas of this section. The code compares the simulated cycle with the formulas and plots the switchings against the band.

Discuss: Comfort against wear
  1. A contactor is rated for a limited number of operations. How would you choose the band of the thermostat of the library?
  2. Why does the room swing a little beyond the thresholds in the simulation, and what does a real thermostat do about it?

Protection: The overcurrent relay

A short circuit on a feeder lets the current rise to many times its rating within milliseconds. Cables heat with the square of the current, so the fault must be cleared before they are damaged. An overcurrent relay measures the current through a current transformer and opens the breaker of the feeder. The relays are selective when only the breaker nearest to the fault opens, and the rest of the campus keeps its supply.

An inverse-time relay trips the faster, the higher the current. The IEC defines its standard inverse characteristic with a time multiplier setting (TMS) [7]:

\[t = TMS \cdot \frac{0.14}{M^{0.02} - 1}, \qquad M = \frac{I}{I_s}\]

\(I\) is the measured current, \(I_s\) the pickup current above which the relay starts, and \(M\) the multiple of the pickup. The time multiplier setting scales the whole curve, so the same characteristic serves relays at different places. At \(M = 10\) and \(TMS = 1\), the curve gives 2.97 s.

→ This formula with numbers, step by step: Lab Part B, calculator, steps 1 to 4.

As a hybrid automaton, the relay has the modes NORMAL, PICKUP and TRIP. In the model of this course, an internal timer grows at the rate \(1/t(M)\) in PICKUP, and the relay trips when the timer reaches 1. If the current falls below the pickup first, the relay returns to NORMAL. A constant current thus gives the time of the formula, and a changing current is summed up over the whole event.

A worked example. At \(M = 6\) and \(TMS = 0.2\), the relay trips after \(0.2 \times 0.14 / (6^{0.02} - 1) \)​\({}= 0.028 / 0.03649 \)​\({}= 0.767\) s. A fault of 5 kA on the feeder of the library, with \(I_s = 250\) A and \(TMS = 0.10\), gives \(M = 20\). That relay trips after \(0.014/0.06175 = 0.227\) s. The incomer of the transformer, with \(I_s = 1600\) A, sees the same fault at \(M = 3.125\), where the curve gives \(0.14/0.02305 = 6.074\) s for \(TMS = 1\). To trip at least 0.3 s later, it needs \(TMS \ge 0.527/6.074 = 0.0868\). It is set to 0.09 and trips after 0.547 s, a margin of 0.320 s.

The grading margin of 0.3 s covers the opening time of the breaker and the tolerances of both relays. In island mode, the protection meets a further problem. Inverters limit their fault current to little more than their rated current. A fault may then never reach the pickup of relays that are set for the city grid [8].

Left: The standard inverse curve for five time multipliers. Right: The feeder of the library and the incomer of the transformer, with the fault of 5 kA and the grading margin.
Left: The standard inverse curve for five time multipliers. Right: The feeder of the library and the incomer of the transformer, with the fault of 5 kA and the grading margin.

Check your understanding. Why must the incomer trip later than the relay of the faulted feeder?

Open lab Part B

Interactive lab, Part B. The relay test bench in 3D: A secondary injection test set with the relays of the feeder and of the incomer. Measure the curve of the feeder relay and set the incomer for a margin of 0.3 s. The results can be copied into the Colab notebook.

Open in Colab

Python code in the Colab notebook, Section 3. Open Section 3 of the Colab notebook and run it. The function t_iec carries out the formula of this section, and relay simulates the timer of the relay. The code repeats the worked example and finds the setting of the incomer. Paste the results of Part B into MY_TESTS, and the code fits the time multiplier and the fixed delay of your relay.

Discuss: Fast or selective?
  1. A faster trip protects the cables better but endangers the selectivity. Who should decide the margin, and on what basis?
  2. Why can the start of a large machine look like a fault to the relay?

The microgrid as a hybrid system

The campus is connected to the city grid at the point of common coupling (PCC). When the city grid fails, the breaker at the PCC opens, and the campus goes dark. The battery can then form a grid of its own, set the voltage and the frequency and supply the campus as an island. The controller of the microgrid is a hybrid automaton with five modes, written in capitals. RESYNC is short for resynchronisation:

ModeWhat the campus doesLeaves the mode when
GRIDDraws from the city grid; the battery follows its frequencyThe grid is lost
DARKHas no supplyThe island is formed, or the grid returns
ISLANDThe battery forms the grid; loads are shed by priority until they fit the inverter of 250 kWThe state of charge falls below 0.30 or to 0.10, a load overloads the inverter, or the grid returns
SHEDSupplies only the library and the laboratoriesThe state of charge falls to 0.10, or the grid returns
RESYNCMatches its frequency, voltage and phase to the returning city gridThe phase angle lies within the window: The breaker at the PCC closes

The guards of ISLAND and SHED watch the state of charge (SoC), which falls as in Week 2. The guard of RESYNC compares the island with the returning grid. Interconnection standards allow the closing of the breaker only when the differences of frequency, voltage and phase angle are small. The Institute of Electrical and Electronics Engineers (IEEE) sets such limits in its standard IEEE 1547 [9]. For a generation of 500 to 1500 kVA, they are 0.2 Hz, 5 percent and 15 degrees. The campus, with about 900 kVA of solar plant, wind turbine and battery, adopts these limits. With a difference of frequency \(\Delta f\), the phase angle between the island and the grid turns steadily:

\[\Delta\varphi(t) = \Delta\varphi_0 + 360\,\Delta f\,t \ \ (\text{degrees}), \qquad \text{close when } |\Delta\varphi| \le 15^\circ\]
The controller of the microgrid as a hybrid automaton, with the guards of its transitions.
The controller of the microgrid as a hybrid automaton, with the guards of its transitions.

A worked example. The city grid fails at 21:00. The campus draws 390 kW, the car park 22 kW, and the wind turbine delivers 10.3 kW. The inverter can carry 250 kW, so the controller sheds the car park, the sports hall B4 and the engineering building B1. The island keeps 239.6 kW for the dormitory, the library and the laboratories. The evening shaving of Week 2 leaves a state of charge of 0.144, so the guard \(SoC < 0.30\) holds at once. The controller then sheds the dormitory as well. The battery reaches 0.10 at 21:09, and the campus stays dark until the grid returns at 23:00.

When the grid returns at a phase difference of 120 degrees and the island runs 0.1 Hz apart, the angle turns at 36 degrees a second. It enters the window at 345 degrees after \((345 - 120)/36 = 6.25\) s, and the breaker closes.

Check your understanding. The island runs 0.2 Hz faster than the returning city grid. How long does one full turn of the phase angle take?

Open lab Part C

Interactive lab, Part C. The switchboard of the campus in 3D: The breaker at the PCC, a synchroscope, the inverter of the battery and six feeder breakers. Run the outage of 21:00 as the controller of the campus and close the breaker in phase. The event log can be copied into the Colab notebook.

Open in Colab

Python code in the Colab notebook, Section 4. Open Section 4 of the Colab notebook and run it. The function outage carries out the controller of this section minute by minute, and sync_wait the closing in phase. Paste the event log of Part C into MY_LOG, and the code checks each of your transitions against the table of the controller.

Discuss: Who decides in the dark?
  1. Which loads of a campus should be the last to lose their supply, and who should decide the order?
  2. An automatic controller forms the island within a second. What can an operator do that the controller cannot?

Development templates of the week

The folder templates/ of the repository collects small working programs that carry out the methods of the course. Week 3 adds two of them, each with a description, its inputs and outputs and an example run.

TemplateWhat it does
state_machine_toolkit.pyRuns, tests and checks state machines given as tables: Traces, reachable states, states without a way out, safety properties and the conformance of logs
overcurrent_coordination.pyComputes the trip times of the IEC curves for overcurrent relays and the time multiplier of an upstream relay for a grading margin

The engineering side: Testing machines with modes

A state machine is small enough to be tested completely. Transition coverage asks that every arrow of the diagram is taken at least once in some test. A conformance check replays the logs of the real system through the table and reports every transition that the table does not allow. Protection relays are tested on site with secondary injection: A test set feeds known currents into the relay and times its trip.

MethodWhat it checksIn this week
Transition coverageEvery transition of the table is taken in some testThe events of the worked example and of Exercise A for the charger
ReachabilityWhich states some sequence of events reaches, and whether a safety property holds in all of themreachable and the contactor of the charger
Conformance of logsWhether the logged transitions of a real system are allowed by the tableMY_LOG of Part C
Secondary injectionWhether a relay trips at the times of its curveThe relay test bench of Part B
In everyday life: A washing machine

A washing machine fills, washes, drains and spins, and a door opened at the wrong moment stops it in an error state. Its program is a state machine, and its water level and temperature follow differential equations. Its float switch works with a hysteresis: A household hybrid automaton.

Discuss: Enough tests?
  1. The charger has 24 pairs of a state and an event. How many tests cover all of them, and is that enough?
  2. Why is a relay tested on site, although its manufacturer has tested it in the factory?

The campus microgrid, stage 3: Operating modes and protection

Stage 3 asks three questions. How often does the thermostat of the library switch? How must the incomer be set so that a fault on a feeder stays local? Which state of charge must the battery hold at 21:00 to ride through an outage of two hours?

QuestionResultModel
Cycle of the thermostat, band 1 K at 5 °COn 90.1 min, off 45.0 min, 21.3 switchings a dayHybrid automaton
Setting of the incomer for a fault of 5 kAFeeder 0.227 s; incomer TMS 0.09, 0.547 s; margin 0.320 sRelay
Outage at 21:00 with the state of charge of Week 2Dark from 21:09 until the grid returns at 23:00Controller of the microgrid
State of charge at 21:00 that rides through until 23:000.815Controller of the microgrid

The evening shaving of Weeks 1 and 2 saves money but leaves the battery almost empty at 21:00. An outage of two hours at that time needs a state of charge of 0.815, an outage of one hour 0.472. The controller acts only at whole minutes, so a slightly higher state of charge can delay the shedding by one minute and cost more than it adds. The Colab notebook therefore tries every state of charge in steps of 0.001. Week 9 will weigh the saving of the shaving against such a reserve with an optimisation.

The campus microgrid, stage 3. Left: The outage of 21:00 with the state of charge of Week 2 and with the reserve of 0.815. Right: The state of charge needed at 21:00 for outages of different lengths. The values come from Section 5 of the Colab notebook.
The campus microgrid, stage 3. Left: The outage of 21:00 with the state of charge of Week 2 and with the reserve of 0.815. Right: The state of charge needed at 21:00 for outages of different lengths. The values come from Section 5 of the Colab notebook.

Check your understanding. Why does the campus go dark at 21:09 in the worked example?

Open lab Part D

Interactive lab, Part D. Stage 3 by hand: The on time of the thermostat, the trip time of a relay and the time of a resynchronisation.

Open in Colab

Python code in the Colab notebook, Section 5. Open Section 5 of the Colab notebook and run it. The code collects the results of stage 3 in the dictionary STAGE3 and finds the state of charge that rides through the outage. A figure draws the outage with both states of charge.

In the field: Setting a relay through its front panel

A protection study ends in a sheet of settings, and on site an engineer enters these settings into each relay. The relay measures only secondary currents, so the ratio of its current transformers comes first. The pickup is then set as a multiple of the rated current \(I_n\): With current transformers of 250/1 A, a pickup of 250 A is \(1.00 \times I_n\). Many relays label the standard inverse (SI) curve of this week IEC SI [7].

A secondary injection then checks the settings, as on the bench of Part B. A test set injects twice the pickup, here 2 A, and its timer stops when the trip contact closes. The relay must trip after \(0.10 \times 0.14/(2^{0.02} - 1) \)​\({}= 1.003\) s, plus the 20 ms of its contact. Finally, the engineer reads the trip record and resets the trip lamp, so that an old trip does not hide the next one.

Open lab Part E

Interactive lab, Part E. The field task: The front panel of the feeder relay and a secondary test set. Enter the protection study through the menu of the relay and check it with an injection.

Your application

State machines run many devices of daily life. The Colab notebook holds an application switch with six machines. They are the charger, a traffic light, the door of an elevator, a washing machine, a water pump with a float switch and a vending machine.

Open in Colab

Python code in the Colab notebook, Section 6. Open Section 6 of the Colab notebook, set APP to one of the six names in the comment and run the cell. The code runs twelve random events and lists the reachable states and the states without a way out.

Learning state machines from data

The table of a machine is often unknown, for example in old software or in a device of another manufacturer. Model learning constructs a state machine from observations of the inputs and outputs of a black box [10]. Active methods choose the inputs themselves and test the learned model against the system until no difference is found.

For the campus, the logs of the chargers and of the controller of the microgrid are a rich source. A learned machine shows which transitions really occur, and a transition that it has never seen marks an anomaly. Week 10 returns to anomalies, and Week 11 to attacks that hide in such logs.

A learned model of the car park

Suppose that the team logs the states of the ten chargers for a month and learns a state machine from the logs. The learned machine of one charger moves from C to F ten times more often than the others. The team inspects the charger and finds a worn contactor before it fails completely.

Discuss: Learned or specified?
  1. When would you trust a learned state machine more than the one in the manual of the device?
  2. What can a learned machine not know about a device that has never failed?

Review cards

Select a card to turn it over.

Finite state machine
A finite set of states, input events and a transition function \(\delta(s, e) = s'\) [1].
Trace
The sequence of states that a machine passes for a sequence of events.
Reachable state
A state that some sequence of events leads to from the initial state.
Safety property
A condition that must hold in every reachable state, such as a contactor that is closed only while charging.
Control pilot
The signal wire of a charging cable whose voltage gives the state of the charger: +12, +9, +6 or -12 V [4].
Hybrid automaton
Modes with flows, invariants, guards and resets [5].
Guard
The condition on the continuous state that enables a transition.
Hysteresis
Two thresholds that keep a switch from chattering: On at \(T_{lo}\), off at \(T_{hi}\).
Standard inverse curve
\(t = TMS \cdot 0.14/(M^{0.02} - 1)\) with \(M = I/I_s\) [7].
Selectivity
Only the breaker nearest to a fault opens.
Grading margin
The time by which an upstream relay trips later than the relay nearest to the fault, here 0.3 s.
Island mode
The campus runs without the city grid, and the battery forms the grid.
Synchronisation
Closing the PCC only when frequency, voltage and phase are close: 0.2 Hz, 5 percent and 15 degrees for 500 to 1500 kVA [9].
Model learning
Constructing a state machine from observations of a black box [10].

References

[1] Lee, E. A., & Seshia, S. A. (2017). Introduction to Embedded Systems: A Cyber-Physical Systems Approach (2nd ed.). MIT Press. https://ptolemy.berkeley.edu/books/leeseshia/

[2] Alur, R. (2015). Principles of Cyber-Physical Systems. MIT Press. https://cis.upenn.edu/~alur/pcps.html

[3] Van Rossum, G., & Drake, F. L. (2009). Python 3 Reference Manual. CreateSpace.

[4] International Electrotechnical Commission. (2017). Electric vehicle conductive charging system - Part 1: General requirements (IEC 61851-1:2017, Edition 3.0). IEC.

[5] Henzinger, T. A. (1996). The theory of hybrid automata. In Proceedings of the 11th Annual IEEE Symposium on Logic in Computer Science (pp. 278-292). IEEE. https://doi.org/10.1109/LICS.1996.561342

[6] Åström, K. J., & Murray, R. M. (2021). Feedback Systems: An Introduction for Scientists and Engineers (2nd ed.). Princeton University Press.

[7] International Electrotechnical Commission. (2009). Measuring relays and protection equipment - Part 151: Functional requirements for over/under current protection (IEC 60255-151:2009, Edition 1.0). IEC.

[8] Brearley, B. J., & Prabu, R. R. (2017). A review on issues and approaches for microgrid protection. Renewable and Sustainable Energy Reviews, 67, 988-997. https://doi.org/10.1016/j.rser.2016.09.047

[9] Institute of Electrical and Electronics Engineers. (2018). IEEE Standard for Interconnection and Interoperability of Distributed Energy Resources with Associated Electric Power Systems Interfaces (IEEE Std 1547-2018). IEEE.

[10] Vaandrager, F. (2017). Model learning. Communications of the ACM, 60(2), 86-95. https://doi.org/10.1145/2967606