Skip to main content

DiscreteControl

Set parameters of other nodes based on model state conditions (e.g. Basin level). The table below shows which parameters are controllable for a given node type.

Code
using Ribasim
using DataFrames: DataFrame
using MarkdownTables
using PythonCall
# Render matplotlib figures off-screen; they are displayed by ending a cell with the figure
pyimport("matplotlib").use("Agg")
include("../../../utils/gen_docs_table.jl")

node_names = Symbol[]
controllable_parameters = String[]

for node_type in fieldtypes(Ribasim.ParametersIndependent)
    if node_type <: Ribasim.AbstractParameterNode
        node_name = nameof(node_type)
        controllable_fields = Ribasim.controllablefields(node_name)
        controllable_fields = sort!(string.(controllable_fields))
        if node_name == :TabulatedRatingCurve
            controllable_fields = map(
                s -> replace(s, "table" => "q(h) relationship (given by level, flow_rate)"),
                controllable_fields,
            )
        end
        if !isempty(controllable_fields)
            push!(node_names, Ribasim.snake_case(node_name))
            push!(controllable_parameters, join(controllable_fields, ", "))
        end
    end
end

df = DataFrame(:node => node_names, :controllable_parameters => controllable_parameters)

markdown_table(df)
node controllable_parameters
linear_resistance resistance
manning_resistance manning_n
tabulated_rating_curve q(h) relationship (given by level, flow_rate)
pump flow_rate
outlet flow_rate
pid_control derivative, integral, proportional, target

1 Schematic

Code
include("../../../utils/docs_plots.jl")

control_diagram = plot(;
    xlims = (0, 11), ylims = (-4, 7), size = (768, 730),
    aspect_ratio = :equal,
    axis = false, ticks = false, grid = false, legend = false,
    margin = 5Plots.mm,
)

control_states = ["off", "low", "high"]
active_state = "low"
state_flow_rates = [0.0, 0.5, 1.0]
selector_x, selector_y = 2.5, 4.5
pump_x = 8.35
basin_xs = [selector_x, pump_x]
basin_y = -2.2
radius = 1.6

for (i, state) in enumerate(control_states)
    active = state == active_state
    start_angle = -pi / 2 + (i - 1) * 2pi / length(control_states)
    end_angle = start_angle + 2pi / length(control_states)
    angles = range(start_angle, end_angle; length = 60)
    middle_angle = (start_angle + end_angle) / 2
    plot!(
        control_diagram,
        Shape(
            [selector_x; selector_x .+ radius .* cos.(angles); selector_x],
            [selector_y; selector_y .+ radius .* sin.(angles); selector_y],
        );
        fillcolor = active ? :lightgreen : :lightgrey,
        linecolor = :white, linewidth = 2,
    )
    annotate!(
        control_diagram,
        selector_x + 0.7radius * cos(middle_angle),
        selector_y + 0.7radius * sin(middle_angle),
        text(state, 11),
    )

    y = 6.1 - (i - 1) * 1.2
    plot!(
        control_diagram,
        Shape(
            [6.2, 10.5, 10.5, 6.2],
            [y - 0.45, y - 0.45, y + 0.45, y + 0.45],
        );
        fillcolor = active ? :lightgreen : :white,
        linecolor = active ? :darkgreen : :grey,
        linewidth = active ? 2 : 1,
    )
    annotate!(
        control_diagram, pump_x, y,
        text("$state: flow_rate = $(state_flow_rates[i])", 10),
    )
end

plot!(
    control_diagram, [selector_x, selector_x], [2.9, 1.8];
    color = :grey, linestyle = :dot,
)
plot!(
    control_diagram, [pump_x, pump_x], [3.25, 1.8];
    color = :grey, linestyle = :dot,
)
plot!(
    control_diagram, [selector_x, pump_x], [1.4, 1.4];
    color = "#808080", linewidth = 2,
)
for basin_x in basin_xs
    start_x = basin_x == selector_x ? basin_x : basin_x - 0.18
    start_y = basin_y + 0.15
    end_x = selector_x
    end_y = 1.4
    middle_x = (start_x + end_x) / 2
    middle_y = (start_y + end_y) / 2
    direction_x = end_x - start_x
    direction_y = end_y - start_y
    direction_length = hypot(direction_x, direction_y)
    unit_x = direction_x / direction_length
    unit_y = direction_y / direction_length
    perpendicular_x = -unit_y
    perpendicular_y = unit_x
    arrow_length = 0.16
    arrow_half_width = 0.07
    base_x = middle_x - unit_x * arrow_length / 2
    base_y = middle_y - unit_y * arrow_length / 2
    plot!(
        control_diagram,
        [start_x, end_x], [start_y, end_y];
        color = "#808080", linestyle = :dash, linewidth = 2,
    )
    plot!(
        control_diagram,
        Shape(
            [
                middle_x + unit_x * arrow_length / 2,
                base_x + perpendicular_x * arrow_half_width,
                base_x - perpendicular_x * arrow_half_width,
            ],
            [
                middle_y + unit_y * arrow_length / 2,
                base_y + perpendicular_y * arrow_half_width,
                base_y - perpendicular_y * arrow_half_width,
            ],
        );
        fillcolor = "#808080", linecolor = "#808080",
    )
end
scatter!(
    control_diagram, [(selector_x + pump_x) / 2], [1.4];
    markershape = :rtriangle, markersize = 6, color = "#808080",
)
scatter!(
    control_diagram, [selector_x], [1.4];
    markershape = :star5, markersize = 20, color = "#984EA3",
)
scatter!(
    control_diagram, [pump_x], [1.4];
    markershape = :hexagon, markersize = 18, color = :grey,
)
annotate!(control_diagram, 1.0, 1.4, text("DiscreteControl", 11))
annotate!(control_diagram, pump_x, 0.65, text("Pump", 11))
annotate!(
    control_diagram, (selector_x + pump_x) / 2, 1.8,
    text("control", 10),
)

for basin_x in basin_xs
    annotate!(
        control_diagram,
        basin_x == selector_x ? selector_x + 0.35 : 5.45,
        basin_x == selector_x ? -0.2 : -0.05,
        text("listen", 10),
    )
end

for basin_x in basin_xs
    plot!(
        control_diagram,
        Shape(
            [basin_x - 0.18, basin_x + 0.18, basin_x + 0.09, basin_x - 0.09],
            [basin_y + 0.15, basin_y + 0.15, basin_y - 0.15, basin_y - 0.15],
        );
        fillcolor = "#0072b2", linecolor = :black, linewidth = 1.5,
    )
    annotate!(
        control_diagram, basin_x, basin_y - 0.4, text("Basin", 10),
    )
end
control_diagram

2 Tables

2.1 Variable

The compound variable schema defines combinations of variables which can be used in conditions. This means that this schema defines new variables with the given compound_variable_id that look like \[ \text{coefficient}_1 * f_1(\text{weight}_1 * \text{variable}_1 + \text{offset}_1) + \text{coefficient}_2 * f_2(\text{weight}_2 * \text{variable}_2 + \text{offset}_2) + \ldots, \]

which can be for instance an average or a difference of variables, but also contain non-linear terms. If a variable comes from a time-series, a look ahead \(\Delta t\) can be supplied.

The function \(f\) is set per row with function, and can be one of

function \(f(x)\)
identity (default) \(x\)
exponential \(e^x\)
inverse \(\frac{1}{x}\)
power(n), with n an integer \(x^n\)
sin \(\sin(x)\)

Take care that the argument stays within the domain of the function, e.g. inverse is undefined at zero. A variable can also be compound_variable.<id>, which refers to the compound variable with that compound_variable_id of the same node, so expressions can be nested. In that case listen_node_id must be left empty. Referring to a compound variable cyclically is an error. To add a constant to the compound variable, use a row with weight = 0 and the constant as offset.

Compound variables that are only referred to by others do not need conditions.

Code
table_from_schema(
    Ribasim.Schema.DiscreteControl.Variable;
    restrictions = Dict(
        :compound_variable_id => "groups the rows of one compound variable, which the conditions refer to",
        :listen_node_id => "a Junction only with variable `flow_rate`, required unless `variable` is `compound_variable.<id>`, then it must be empty",
        :variable => "must be `level`, `storage`, `flow_rate`, `concentration.<substance>`, `concentration_external.<substance>` or `compound_variable.<id>` with the `compound_variable_id` of another compound variable of this node, not creating a cycle",
        :look_ahead => "only on transient boundary conditions, non-negative",
        :function => "must be `identity`, `exponential`, `inverse`, `power(n)` with `n` an integer, or `sin`; the argument must be in the domain of the function",
    ),
)
column type unit optional default restriction
node_id Int32 - x - -
compound_variable_id Int32 - x - groups the rows of one compound variable, which the conditions refer to
listen_node_id Int32 - ✓ - a Junction only with variable flow_rate, required unless variable is compound_variable.<id>, then it must be empty
variable String - x - must be level, storage, flow_rate, concentration.<substance>, concentration_external.<substance> or compound_variable.<id> with the compound_variable_id of another compound variable of this node, not creating a cycle
weight Float64 - ✓ 1.0 -
look_ahead Float64 s ✓ 0.0 only on transient boundary conditions, non-negative
function String - ✓ identity must be identity, exponential, inverse, power(n) with n an integer, or sin; the argument must be in the domain of the function
coefficient Float64 various ✓ 1.0 -
offset Float64 various ✓ 0.0 -

These variables can be listened to:

  • The storage of a Basin
  • The level of a Basin
  • The level of a LevelBoundary (supports look ahead)
  • The flow rate through one of these node types: Pump, Outlet, TabulatedRatingCurve, LinearResistance, ManningResistance
  • The inflow rate of a UserDemand
  • The flow rate of a FlowBoundary (supports look ahead)
  • The flow rate of a Junction
  • The concentration of a substance in a Basin, with variable concentration.<substance>, e.g. concentration.Cl
  • The external concentration of a substance in a Basin, with variable concentration_external.<substance>, as given in the Basin / concentration_external table

2.2 Condition

The condition schema defines conditions of the form the discrete_control node with this node_id listens to whether the variable given by the node_id and compound_variable_id is greater than threshold_high (at time \(t\)) when the condition was false previously, or threshold_low when true previously, adding hysteresis. Using threshold_low is optional and defaults to threshold_high. We recommend setting threshold_low below threshold_high to create a range that avoids frequent control state changes from small fluctuations and improves model performance. In equation form:

\[ \text{condition}=\begin{cases} \text{weight}_1 * \text{variable}_1 + \text{weight}_2 * \text{variable}_2 + \ldots > \text{greater\_than}(t), !\text{condition\_prev} \\ \text{weight}_1 * \text{variable}_1 + \text{weight}_2 * \text{variable}_2 + \ldots \geq \text{less\_than}(t), \text{condition\_prev} \end{cases} \]

Multiple conditions with different threshold_high and/or threshold_low values can be defined on the same compound_variable, each with their own unique condition_id.

At the start of the simulation, a condition is true if its variable exceeds the midpoint of threshold_low and threshold_high (which equals threshold_high without hysteresis).

Code
table_from_schema(
    Ribasim.Schema.DiscreteControl.Condition;
    restrictions = Dict(:threshold_low => "≤ threshold_high"),
    defaults_override = Dict(:threshold_low => "threshold_high"),
)
column type unit optional default restriction
node_id Int32 - x - -
compound_variable_id Int32 - x - -
condition_id Int32 - x - -
threshold_high Float64 various x - -
threshold_low Float64 various ✓ threshold_high ≤ threshold_high
time DateTime - ✓ - -

When no (or only a single) time is supplied for a given condition_id, the threshold_high value of this condition is unchanging over time. When multiple times are supplied, in between the given times the threshold_high and threshold_low values are block interpolated (forward fill), and outside they are constant given by the nearest time value. It is possible to configure a DiscreteControl node such that it very rapidly oscillates between control states, which isn’t realistic behavior. See the example model below.

from ribasim import Model, Node
from ribasim.nodes import basin, discrete_control, flow_boundary, pump
from shapely.geometry import Point
import matplotlib.pyplot as plt

model = Model(starttime="2020-01-01", endtime="2021-01-01", crs="EPSG:4326")

fb = model.flow_boundary.add(
    Node(1, Point(0, 0)), [flow_boundary.Static(flow_rate=[1.0])]
)

bsn = model.basin.add(
    Node(2, Point(1, 0)), [basin.Profile(area=[100.0, 100.0], level=[0.0, 1.0])]
)

pmp = model.pump.add(Node(3, Point(2, 0)), [pump.Static(flow_rate=[1.0])])

t = model.terminal.add(Node(4, Point(3, 0)))

dc = model.discrete_control.add(
    Node(5, Point(1.5, -1)),
    [
        discrete_control.Variable(
            compound_variable_id=[1], listen_node_id=[2], variable=["level"]
        )
    ],
)

model.link.add(fb, bsn)
model.link.add(bsn, pmp)
model.link.add(pmp, t)
model.link.add(dc, pmp)

ax = model.plot()
ax.figure.tight_layout()
ax.figure

Say there is constant inflow from the FlowBoundary node and there are no vertical forcings on the Basin. Say furthermore that the Pump is active only when the Basin level is above a reference value, with a flow greater than the boundary flow. In this case the Pump will rapidly turn on and off as the Basin level oscillates around the reference value.

To make you aware of these oscillations, Ribasim will give a warning if successive control state changes of a DiscreteControl node in simulated time are closer than min_discrete_control_interval, which is configurable and defaults to 1 second. The warning is given once per DiscreteControl node, for at most 10 nodes. Set min_discrete_control_interval to 0.0 to disable these warnings.

By default the conditions are evaluated after every timestep. To evaluate them only at fixed times, for instance daily, set the solver setting discrete_control_interval, see usage.

2.3 Logic

The logic schema defines which control states are triggered based on the truth of the conditions a DiscreteControl node listens to. DiscreteControl is applied in the Julia core as follows:

  • During the simulation it is checked whether the truth of any of the conditions changes.
  • When a condition changes, the corresponding DiscreteControl node ID is retrieved (node_id in the condition schema above).
  • The truth value of all the conditions this DiscreteControl node listens to are retrieved, in the order of the condition IDs. This is then converted into a string of “T” for true and “F” for false. This string we call the truth state.
  • The table below determines for the given DiscreteControl node ID and truth state what the corresponding control state is.
  • For all the nodes this DiscreteControl node affects (as given by the “control” links in Links / static), their parameters are set to those parameters in NodeType / static corresponding to the determined control state.
Code
table_from_schema(
    Ribasim.Schema.DiscreteControl.Logic;
    restrictions = Dict(
        :truth_state => "consists of the characters `T` (true), `F` (false) and `*` (any)",
    ),
)
column type optional restriction
node_id Int32 x -
truth_state String x consists of the characters T (true), F (false) and * (any)
control_state String x -

3 Examples

The examples below use the Python API and go from simple to complex. Each one shows the Variable and Condition tables of DiscreteControl node 10, and the Logic table that maps the truth state of the conditions to a control state. The control states are defined in the Static table of the controlled node, which has a control link from node 10. The behavior that results is described per example.

3.1 1. Level threshold

Pump 20 is controlled with the control states Off (flow rate \(0\) m³/s) and On (\(2\) m³/s). It is switched on when the level of Basin 1 exceeds \(1.0\) m, and off when the level is below that. Without a threshold_low the condition has no hysteresis.

pump.Static(control_state=["Off", "On"], flow_rate=[0.0, 2.0])
discrete_control.Variable(
    node_id=10, compound_variable_id=1, listen_node_id=[1], variable="level"
)
discrete_control.Condition(
    node_id=10, compound_variable_id=1, condition_id=1, threshold_high=[1.0]
)
discrete_control.Logic(node_id=10, truth_state=["F", "T"], control_state=["Off", "On"])

3.2 2. Hysteresis

The same Pump, but it is switched on when the level rises above \(1.0\) m and only switched off again when it falls below \(0.8\) m. Between \(0.8\) and \(1.0\) m it keeps its current state, which prevents frequent switching.

discrete_control.Condition(
    node_id=10,
    compound_variable_id=1,
    condition_id=1,
    threshold_high=[1.0],
    threshold_low=[0.8],
)
discrete_control.Logic(node_id=10, truth_state=["F", "T"], control_state=["Off", "On"])

3.3 3. Multiple conditions

Several conditions on the same compound variable give more than two control states. Here Pump 20 has the control states Off (\(0\) m³/s), Low (\(1\) m³/s) and High (\(3\) m³/s). With thresholds \(0.5\) and \(1.0\) m on the level of Basin 1, the truth states are FF (below \(0.5\) m: the Pump is off), TF (between \(0.5\) and \(1.0\) m: low) and TT (above \(1.0\) m: high).

pump.Static(control_state=["Off", "Low", "High"], flow_rate=[0.0, 1.0, 3.0])
discrete_control.Condition(
    node_id=10, compound_variable_id=1, condition_id=[1, 2], threshold_high=[0.5, 1.0]
)
discrete_control.Logic(
    node_id=10,
    truth_state=["FF", "TF", "TT"],
    control_state=["Off", "Low", "High"],
)

3.4 4. Compound variable: level difference

Pump 20 (Off \(0\) m³/s, On \(2\) m³/s) is switched on when Basin 1 is more than \(0.1\) m higher than Basin 2, using weights \(1\) and \(-1\), and off when the difference is smaller.

discrete_control.Variable(
    node_id=10,
    compound_variable_id=1,
    listen_node_id=[1, 2],
    variable="level",
    weight=[1.0, -1.0],
)
discrete_control.Condition(
    node_id=10, compound_variable_id=1, condition_id=1, threshold_high=[0.1]
)
discrete_control.Logic(node_id=10, truth_state=["F", "T"], control_state=["Off", "On"])

3.5 5. Look ahead on a boundary condition

Pump 20 is switched on when the discharge of FlowBoundary 3 in 6 hours (look_ahead is in seconds) is forecasted to exceed \(200\) m³/s, so that Basin 1 is lowered in advance of a peak. It is switched off again when the forecast drops below that.

discrete_control.Variable(
    node_id=10,
    compound_variable_id=1,
    listen_node_id=[3],
    variable="flow_rate",
    look_ahead=6 * 3600.0,
)
discrete_control.Condition(
    node_id=10, compound_variable_id=1, condition_id=1, threshold_high=[200.0]
)
discrete_control.Logic(node_id=10, truth_state=["F", "T"], control_state=["Off", "On"])

3.6 6. Non-linear relation

Outlet 20 lets in fresh water, with the control states Closed (\(0\) m³/s) and Open (\(5\) m³/s). It opens when the salt concentration at an intake gets too high, which is estimated in mg/l from the discharge \(Q_a\) of a river (FlowBoundary 3) and the discharge \(Q_b\) of a tributary (FlowBoundary 4):

\[ c = 20 + 450 e^{-0.012 (Q_a + 25)} + \frac{3000}{Q_b}. \]

Since \(e^{-0.012 (Q_a + 25)} = e^{-0.012 Q_a - 0.3}\), the first term has weight = -0.012 and offset = -0.3. The constant \(20\) is made with a weight of zero, as then only the offset remains. The outlet opens above \(150\) mg/l and closes again below \(100\) mg/l. For \(Q_a = 100\) and \(Q_b = 1500\) m³/s the concentration is about \(122\) mg/l, so the outlet stays in its current state. When \(Q_a\) drops to \(50\) m³/s the concentration rises to about \(20 + 450 e^{-0.9} + 2 \approx 205\) mg/l and the outlet opens.

outlet.Static(control_state=["Closed", "Open"], flow_rate=[0.0, 5.0])
discrete_control.Variable(
    node_id=10,
    compound_variable_id=1,
    listen_node_id=[3, 4, 3],
    variable="flow_rate",
    weight=[-0.012, 1.0, 0.0],
    offset=[-0.3, 0.0, 20.0],
    function=["exponential", "inverse", "identity"],
    coefficient=[450.0, 3000.0, 1.0],
)
discrete_control.Condition(
    node_id=10,
    compound_variable_id=1,
    condition_id=1,
    threshold_high=[150.0],
    threshold_low=[100.0],
)
discrete_control.Logic(
    node_id=10, truth_state=["F", "T"], control_state=["Closed", "Open"]
)

3.7 7. Nested compound variables

A variable can refer to another compound variable of the same node as compound_variable.<id>, with an empty listen_node_id. Here \(Q_a\) of the previous example is not measured directly, but is the sum of the flow rates of Pump 5 and Pump 6, which is compound variable 1. Compound variable 2 is the salt concentration, and is the only one with conditions. The resulting behavior of Outlet 20 is the same as in the previous example, with \(Q_a\) the sum of the Pump flow rates.

discrete_control.Variable(
    node_id=10,
    compound_variable_id=[1, 1, 2, 2, 2],
    listen_node_id=[5, 6, None, 4, 4],
    variable=[
        "flow_rate",
        "flow_rate",
        "compound_variable.1",
        "flow_rate",
        "flow_rate",
    ],
    weight=[1.0, 1.0, -0.012, 1.0, 0.0],
    offset=[0.0, 0.0, -0.3, 0.0, 20.0],
    function=["identity", "identity", "exponential", "inverse", "identity"],
    coefficient=[1.0, 1.0, 450.0, 3000.0, 1.0],
)
discrete_control.Condition(
    node_id=10,
    compound_variable_id=2,
    condition_id=1,
    threshold_high=[150.0],
    threshold_low=[100.0],
)
discrete_control.Logic(
    node_id=10, truth_state=["F", "T"], control_state=["Closed", "Open"]
)

Compound variables can be nested to any depth, but not refer to themselves, directly or indirectly.

4 Behavior in allocation

Allocation uses the parameters that DiscreteControl has set at the moment allocation runs, at each intervention time. It cannot foresee that DiscreteControl changes them before the next intervention time, set by intervention_interval in the allocation settings, so after such a change the simulated flows can differ from what allocation planned. Since allocation_controlled of a Pump, Outlet or TabulatedRatingCurve can differ per control state, DiscreteControl can switch allocation control of these nodes on and off.