diff --git a/.nojekyll b/.nojekyll index 2030e0242..d31b58c5f 100644 --- a/.nojekyll +++ b/.nojekyll @@ -1 +1 @@ -4ea83fa1 \ No newline at end of file +776982b2 \ No newline at end of file diff --git a/build/index.html b/build/index.html index 6120809c6..c1a535c5d 100644 --- a/build/index.html +++ b/build/index.html @@ -262,11 +262,11 @@

solve!
  • BMI.finalize
  • -

    source

    +

    source

    # Ribasim.configModule.

    module config

    Ribasim.config is a submodule of Ribasim to handle the configuration of a Ribasim model. It is implemented using the Configurations package. A full configuration is represented by Config, which is the main API. Ribasim.config is a submodule mainly to avoid name clashes between the configuration sections and the rest of Ribasim.

    -

    source

    +

    source

    @@ -275,7 +275,7 @@

    # Ribasim.AllocationModelType.

    Store information for a subnetwork used for allocation.

    nodeid: All the IDs of the nodes that are in this subnetwork nodeidmapping: Mapping Dictionary; modelnodeid => AGnodeid where such a correspondence exists (all AG node ids are in the values) nodeidmappinginverse: The inverse of nodeidmapping, Dictionary; AG node ID => model node ID Source edge mapping: AG source node ID => subnetwork source edge ID graphallocation: The graph used for the allocation problems capacity: The capacity per edge of the allocation graph, as constrained by nodes that have a maxflowrate problem: The JuMP.jl model for solving the allocation problem Δtallocation: The time interval between consecutive allocation solves

    -

    source

    +

    source

    # Ribasim.AllocationModelMethod.

    Construct the JuMP.jl problem for allocation.

    Definitions

    @@ -287,7 +287,7 @@

    source

    +

    source

    # Ribasim.BasinType.

    Requirements:

      @@ -297,24 +297,24 @@

      source

      +

      source

      # Ribasim.ConnectivityType.

      Store the connectivity information

      graphflow, graphcontrol: directed graph with vertices equal to ids flow: store the flow on every flow edge edgeidsflow, edgeidscontrol: get the external edge id from (src, dst) edgeconnectiontypeflow, edgeconnectiontypescontrol: get (srcnodetype, dstnodetype) from edge id

      if autodiff T = DiffCache{SparseArrays.SparseMatrixCSC{Float64, Int64}, Vector{Float64}} else T = SparseMatrixCSC{Float64, Int} end

      -

      source

      +

      source

      # Ribasim.DiscreteControlType.

      nodeid: node ID of the DiscreteControl node; these are not unique but repeated by the amount of conditions of this DiscreteControl node listenfeatureid: the ID of the node/edge being condition on variable: the name of the variable in the condition greaterthan: The threshold value in the condition conditionvalue: The current value of each condition controlstate: Dictionary: node ID => (control state, control state start) logic_mapping: Dictionary: (control node ID, truth state) => control state record: Namedtuple with discrete control information for results

      -

      source

      +

      source

      # Ribasim.FlatVectorType.

      struct FlatVector{T} <: AbstractVector{T}

      A FlatVector is an AbstractVector that iterates the T of a Vector{Vector{T}}.

      Each inner vector is assumed to be of equal length.

      It is similar to Iterators.flatten, though that doesn’t work with the Tables.Column interface, which needs length and getindex support.

      -

      source

      +

      source

      # Ribasim.FlowBoundaryType.

      nodeid: node ID of the FlowBoundary node active: whether this node is active and thus contributes flow flowrate: target flow rate

      -

      source

      +

      source

      # Ribasim.FractionalFlowType.

      Requirements:

        @@ -323,10 +323,10 @@

        source

        +

        source

        # Ribasim.LevelBoundaryType.

        node_id: node ID of the LevelBoundary node active: whether this node is active level: the fixed level of this ‘infinitely big basin’

        -

        source

        +

        source

        # Ribasim.LinearResistanceType.

        Requirements:

          @@ -334,7 +334,7 @@

          source

          +

          source

          # Ribasim.ManningResistanceType.

          This is a simple Manning-Gauckler reach connection.

            @@ -364,39 +364,39 @@

            source

            +

            source

            # Ribasim.ModelType.

            Model(config_path::AbstractString)
             Model(config::Config)

            Initialize a Model.

            The Model struct is an initialized model, combined with the Config used to create it and saved results. The Basic Model Interface (BMI) is implemented on the Model. A Model can be created from the path to a TOML configuration file, or a Config object.

            -

            source

            +

            source

            # Ribasim.OutletType.

            nodeid: node ID of the Outlet node active: whether this node is active and thus contributes flow flowrate: target flow rate minflowrate: The minimal flow rate of the outlet maxflowrate: The maximum flow rate of the outlet controlmapping: dictionary from (nodeid, controlstate) to target flow rate ispid_controlled: whether the flow rate of this outlet is governed by PID control

            -

            source

            +

            source

            # Ribasim.PidControlType.

            PID control currently only supports regulating basin levels.

            nodeid: node ID of the PidControl node active: whether this node is active and thus sets flow rates listennodeid: the id of the basin being controlled pidparams: a vector interpolation for parameters changing over time. The parameters are respectively target, proportional, integral, derivative, where the last three are the coefficients for the PID equation. error: the current error; basintarget - currentlevel

            -

            source

            +

            source

            # Ribasim.PumpType.

            nodeid: node ID of the Pump node active: whether this node is active and thus contributes flow flowrate: target flow rate minflowrate: The minimal flow rate of the pump maxflowrate: The maximum flow rate of the pump controlmapping: dictionary from (nodeid, controlstate) to target flow rate ispid_controlled: whether the flow rate of this pump is governed by PID control

            -

            source

            +

            source

            # Ribasim.TabulatedRatingCurveType.

            struct TabulatedRatingCurve{C}

            Rating curve from level to discharge. The rating curve is a lookup table with linear interpolation in between. Relation can be updated in time, which is done by moving data from the time field into the tables, which is done in the update_tabulated_rating_curve callback.

            Type parameter C indicates the content backing the StructVector, which can be a NamedTuple of Vectors or Arrow Primitives, and is added to avoid type instabilities.

            nodeid: node ID of the TabulatedRatingCurve node active: whether this node is active and thus contributes flows tables: The current Q(h) relationships time: The time table used for updating the tables controlmapping: dictionary from (nodeid, controlstate) to Q(h) and/or active state

            -

            source

            +

            source

            # Ribasim.TerminalType.

            node_id: node ID of the Terminal node

            -

            source

            +

            source

            # Ribasim.UserType.

            demand: water flux demand of user per priority over time active: whether this node is active and thus demands water allocated: water flux currently allocated to user per priority returnfactor: the factor in [0,1] of how much of the abstracted water is given back to the system minlevel: The level of the source basin below which the user does not abstract priorities: All used priority values. Each user has a demand for all these priorities, which is always 0.0 if it is not provided explicitly.

            -

            source

            +

            source

            # Ribasim.config.ConfigMethod.

            Config(config_path::AbstractString; kwargs...)

            Parse a TOML file to a Config. Keys can be overruled using keyword arguments. To overrule keys from a subsection, e.g. dt from the solver section, use underscores: solver_dt.

            -

            source

            +

            source

            @@ -405,35 +405,35 @@

            # BasicModelInterface.finalizeMethod.

            BMI.finalize(model::Model)::Model

            Write all results to the configured files.

            -

            source

            +

            source

            # BasicModelInterface.initializeMethod.

            BMI.initialize(T::Type{Model}, config_path::AbstractString)::Model

            Initialize a Model from the path to the TOML configuration file.

            -

            source

            +

            source

            # BasicModelInterface.initializeMethod.

            BMI.initialize(T::Type{Model}, config::Config)::Model

            Initialize a Model from a Config.

            -

            source

            +

            source

            # CommonSolve.solve!Method.

            solve!(model::Model)::ODESolution

            Solve a Model until the configured endtime.

            -

            source

            +

            source

            # Ribasim.add_constraints_basin_allocation!Method.

            Add the basin allocation constraints to the allocation problem; the allocations to the basins are bounded from above by the basin demand (these are set before each allocation solve). The constraint indices are allocation graph basin node IDs.

            Constraint: allocation to basin <= basin demand

            -

            source

            +

            source

            # Ribasim.add_constraints_capacity!Method.

            Add the flow capacity constraints to the allocation problem. Only finite capacities get a constraint. The constraint indices are the allocation graph edge IDs.

            Constraint: flow over edge <= edge capacity

            -

            source

            +

            source

            # Ribasim.add_constraints_flow_conservation!Method.

            Add the flow conservation constraints to the allocation problem. The constraint indices are allocgraph user node IDs.

            Constraint: sum(flows out of node node) <= flows into node + flow from storage and vertical fluxes

            -

            source

            +

            source

            # Ribasim.add_constraints_source!Method.

            Add the source constraints to the allocation problem. The actual threshold values will be set before each allocation solve. The constraint indices are the allocation graph source node IDs.

            Constraint: flow over source edge <= source flow in subnetwork

            -

            source

            +

            source

            # Ribasim.add_constraints_user_allocation!Method.

            Add the user allocation constraints to the allocation problem:

              @@ -443,81 +443,81 @@

              source

              +

              source

              # Ribasim.add_constraints_user_returnflow!Method.

              Add the user returnflow constraints to the allocation problem. The constraint indices are allocation graph user node IDs.

              Constraint: outflow from user = return factor * inflow to user

              -

              source

              +

              source

              # Ribasim.add_objective_function!Method.

              Add the objective function to the allocation problem. Objective function: linear combination of allocations to the basins and users, where basin allocations get a weight of 1.0 and user allocations get a weight of 2^(-priority index).

              -

              source

              +

              source

              # Ribasim.add_variables_allocation_basin!Method.

              Add the basin allocation variables A_basin to the allocation problem. The variable indices are the allocation graph basin node IDs. Non-negativivity constraints are also immediately added to the basin allocation variables.

              -

              source

              +

              source

              # Ribasim.add_variables_allocation_user!Method.

              Add the user allocation variables Auser{i} to the allocation problem. The variable name indices i are the allocation graph user node IDs, The variable indices are the priorities.

              -

              source

              +

              source

              # Ribasim.add_variables_flow!Method.

              Add the flow variables F to the allocation problem. The variable indices are the allocation graph edge IDs. Non-negativivity constraints are also immediately added to the flow variables.

              -

              source

              +

              source

              # Ribasim.allocate!Method.

              Update the allocation optimization problem for the given subnetwork with the problem state and flows, solve the allocation problem and assign the results to the users.

              -

              source

              +

              source

              # Ribasim.allocation_graphMethod.

              Build the graph used for the allocation problem.

              -

              source

              +

              source

              # Ribasim.allocation_problemMethod.

              Construct the allocation problem for the current subnetwork as a JuMP.jl model.

              -

              source

              +

              source

              # Ribasim.assign_allocations!Method.

              Assign the allocations to the users as determined by the solution of the allocation problem.

              -

              source

              +

              source

              # Ribasim.avoid_using_own_returnflow!Method.

              Remove user return flow edges that are upstream of the user itself, and collect the IDs of the allocation graph node IDs of the users that do not have this problem.

              -

              source

              +

              source

              # Ribasim.basin_bottomMethod.

              Return the bottom elevation of the basin with index i, or nothing if it doesn’t exist

              -

              source

              +

              source

              # Ribasim.basin_bottomsMethod.

              Get the bottom on both ends of a node. If only one has a bottom, use that for both.

              -

              source

              +

              source

              # Ribasim.basin_tableMethod.

              Create the basin result table from the saved data

              -

              source

              +

              source

              # Ribasim.create_callbacksMethod.

              Create the different callbacks that are used to store results and feed the simulation with new data. The different callbacks are combined to a CallbackSet that goes to the integrator. Returns the CallbackSet and the SavedValues for flow.

              -

              source

              +

              source

              # Ribasim.create_graphMethod.

              Return a directed graph, and a mapping from source and target nodes to edge fid.

              -

              source

              +

              source

              # Ribasim.create_storage_tablesMethod.

              Read the Basin / profile table and return all area and level and computed storage values

              -

              source

              +

              source

              # Ribasim.datetime_sinceMethod.

              datetime_since(t::Real, t0::DateTime)::DateTime

              Convert a Real that represents the seconds passed since the simulation start to the nearest DateTime. This is used to convert between the solver’s inner float time, and the calendar.

              -

              source

              +

              source

              # Ribasim.datetimesMethod.

              Get all saved times as a Vector{DateTime}

              -

              source

              +

              source

              # Ribasim.discrete_control_affect!Method.

              Change parameters based on the control logic.

              -

              source

              +

              source

              # Ribasim.discrete_control_affect_downcrossing!Method.

              An downcrossing means that a condition (always greater than) becomes false.

              -

              source

              +

              source

              # Ribasim.discrete_control_affect_upcrossing!Method.

              An upcrossing means that a condition (always greater than) becomes true.

              -

              source

              +

              source

              # Ribasim.discrete_control_conditionMethod.

              Listens for changes in condition truths.

              -

              source

              +

              source

              # Ribasim.discrete_control_tableMethod.

              Create a discrete control result table from the saved data

              -

              source

              +

              source

              # Ribasim.expand_logic_mappingMethod.

              Replace the truth states in the logic mapping which contain wildcards with all possible explicit truth states.

              -

              source

              +

              source

              # Ribasim.find_allocation_graph_edges!Method.

              This loop finds allocgraph edges in several ways:

                @@ -525,26 +525,26 @@

                source

                +

                source

                # Ribasim.findlastgroupMethod.

                For an element id and a vector of elements ids, get the range of indices of the last consecutive block of id. Returns the empty range 1:0 if id is not in ids.

                #                         1 2 3 4 5 6 7 8 9
                 Ribasim.findlastgroup(2, [5,4,2,2,5,2,2,2,1])
                 # output
                 6:8
                -

                source

                +

                source

                # Ribasim.findsortedMethod.

                Find the index of element x in a sorted collection a. Returns the index of x if it exists, or nothing if it doesn’t. If x occurs more than once, throw an error.

                -

                source

                +

                source

                # Ribasim.flow_tableMethod.

                Create a flow result table from the saved data

                -

                source

                +

                source

                # Ribasim.formulate_basins!Method.

                Smoothly let the evaporation flux go to 0 when at small water depths Currently at less than 0.1 m.

                -

                source

                +

                source

                # Ribasim.formulate_flow!Method.

                Directed graph: outflow is positive!

                -

                source

                +

                source

                # Ribasim.formulate_flow!Method.

                Conservation of energy for two basins, a and b:

                h_a + v_a^2 / (2 * g) = h_b + v_b^2 / (2 * g) + S_f * L + C / 2 * g * (v_b^2 - v_a^2)
                @@ -572,91 +572,91 @@

                source

                +

                source

                # Ribasim.formulate_flow!Method.

                Directed graph: outflow is positive!

                -

                source

                +

                source

                # Ribasim.get_area_and_levelMethod.

                Compute the area and level of a basin given its storage. Also returns darea/dlevel as it is needed for the Jacobian.

                -

                source

                +

                source

                # Ribasim.get_compressorMethod.

                Get the compressor based on the Results section

                -

                source

                +

                source

                # Ribasim.get_fractional_flow_connected_basinsMethod.

                Get the node type specific indices of the fractional flows and basins, that are consecutively connected to a node of given id.

                -

                source

                +

                source

                # Ribasim.get_jac_prototypeMethod.

                Get a sparse matrix whose sparsity matches the sparsity of the Jacobian of the ODE problem. All nodes are taken into consideration, also the ones that are inactive.

                In Ribasim the Jacobian is typically sparse because each state only depends on a small number of other states.

                Note: the name ‘prototype’ does not mean this code is a prototype, it comes from the naming convention of this sparsity structure in the differentialequations.jl docs.

                -

                source

                +

                source

                # Ribasim.get_levelMethod.

                Get the current water level of a node ID. The ID can belong to either a Basin or a LevelBoundary. storage: tells ForwardDiff whether this call is for differentiation or not

                -

                source

                +

                source

                # Ribasim.get_node_id_mappingMethod.

                Get:

                • The mapping from subnetwork node IDs to allocation graph node IDs
                • The mapping from allocation graph source node IDs to subnetwork source edge IDs
                -

                source

                +

                source

                # Ribasim.get_node_in_out_edgesMethod.

                Get two dictionaries, where:

                • The first one gives the IDs of the inedges for each node ID in the graph
                • The second one gives the IDs of the outedges for each node ID in the graph
                -

                source

                +

                source

                # Ribasim.get_scalar_interpolationMethod.

                Linear interpolation of a scalar with constant extrapolation.

                -

                source

                +

                source

                # Ribasim.get_storage_from_levelMethod.

                Get the storage of a basin from its level.

                -

                source

                +

                source

                # Ribasim.get_storages_and_levelsMethod.

                Get the storage and level of all basins as matrices of nbasin × ntime

                -

                source

                +

                source

                # Ribasim.get_storages_from_levelsMethod.

                Compute the storages of the basins based on the water level of the basins.

                -

                source

                +

                source

                # Ribasim.get_tstopsMethod.

                From an iterable of DateTimes, find the times the solver needs to stop

                -

                source

                +

                source

                # Ribasim.get_valueMethod.

                Get a value for a condition. Currently supports getting levels from basins and flows from flow boundaries.

                -

                source

                +

                source

                # Ribasim.id_indexMethod.

                Get the index of an ID in a set of indices.

                -

                source

                +

                source

                # Ribasim.input_pathMethod.

                Construct a path relative to both the TOML directory and the optional input_dir

                -

                source

                +

                source

                # Ribasim.is_flow_constrainingMethod.

                Whether the given node node is flow constraining by having a maximum flow rate.

                -

                source

                +

                source

                # Ribasim.is_flow_direction_constrainingMethod.

                Whether the given node is flow direction constraining (only in direction of edges).

                -

                source

                +

                source

                # Ribasim.load_dataMethod.

                load_data(db::DB, config::Config, nodetype::Symbol, kind::Symbol)::Union{Table, Query, Nothing}

                Load data from Arrow files if available, otherwise the database. Returns either an Arrow.Table, SQLite.Query or nothing if the data is not present.

                -

                source

                +

                source

                # Ribasim.load_structvectorMethod.

                load_structvector(db::DB, config::Config, ::Type{T})::StructVector{T}

                Load data from Arrow files if available, otherwise the database. Always returns a StructVector of the given struct type T, which is empty if the table is not found. This function validates the schema, and enforces the required sort order.

                -

                source

                +

                source

                # Ribasim.nodefieldsMethod.

                Get all node fieldnames of the parameter object.

                -

                source

                +

                source

                # Ribasim.nodetypeMethod.

                From a SchemaVersion(“ribasim.flowboundary.static”, 1) return (:FlowBoundary, :static)

                -

                source

                +

                source

                # Ribasim.parse_static_and_timeMethod.

                Process the data in the static and time tables for a given node type. The ‘defaults’ named tuple dictates how missing data is filled in. ‘time_interpolatables’ is a vector of Symbols of parameter names for which a time interpolation (linear) object must be constructed. The control mapping for DiscreteControl is also constructed in this function. This function currently does not support node states that are defined by more than one row in a table, as is the case for TabulatedRatingCurve.

                -

                source

                +

                source

                # Ribasim.path_exists_in_graphMethod.

                Find out whether a path exists between a start node and end node in the given graph.

                -

                source

                +

                source

                # Ribasim.process_allocation_graph_edges!Method.

                For the composite allocgraph edges:

                  @@ -664,37 +664,37 @@

                  source

                  +

                  source

                  # Ribasim.profile_storageMethod.

                  Calculate a profile storage by integrating the areas over the levels

                  -

                  source

                  +

                  source

                  # Ribasim.qh_interpolationMethod.

                  From a table with columns nodeid, discharge (Q) and level (h), create a LinearInterpolation from level to discharge for a given nodeid.

                  -

                  source

                  +

                  source

                  # Ribasim.reduction_factorMethod.

                  Function that goes smoothly from 0 to 1 in the interval [0,threshold], and is constant outside this interval.

                  -

                  source

                  +

                  source

                  # Ribasim.results_pathMethod.

                  Construct a path relative to both the TOML directory and the optional results_dir

                  -

                  source

                  +

                  source

                  # Ribasim.runMethod.

                  run(config_file::AbstractString)::Model
                   run(config::Config)::Model

                  Run a Model, given a path to a TOML configuration file, or a Config object. Running a model includes initialization, solving to the end with [solve!](@ref) and writing results with BMI.finalize.

                  -

                  source

                  +

                  source

                  # Ribasim.save_flowMethod.

                  Copy the current flow to the SavedValues

                  -

                  source

                  +

                  source

                  # Ribasim.scalar_interpolation_derivativeMethod.

                  Derivative of scalar interpolation.

                  -

                  source

                  +

                  source

                  # Ribasim.seconds_sinceMethod.

                  seconds_since(t::DateTime, t0::DateTime)::Float64

                  Convert a DateTime to a float that is the number of seconds since the start of the simulation. This is used to convert between the solver’s inner float time, and the calendar.

                  -

                  source

                  +

                  source

                  # Ribasim.set_current_value!Method.

                  From a timeseries table time, load the most recent applicable data into table. table must be a NamedTuple of vectors with all variables that must be loaded. The most recent applicable data is non-NaN data for a given ID that is on or before t.

                  -

                  source

                  +

                  source

                  # Ribasim.set_model_state_in_allocation!Method.

                  Update the allocation problem with model data at the current:

                    @@ -702,38 +702,38 @@

                    source

                    +

                    source

                    # Ribasim.set_static_value!Method.

                    Load data from a source table static into a destination table. Data is matched based on the node_id, which is sorted.

                    -

                    source

                    +

                    source

                    # Ribasim.set_table_row!Method.

                    Update table at row index i, with the values of a given row. table must be a NamedTuple of vectors with all variables that must be loaded. The row must contain all the column names that are present in the table. If a value is NaN, it is not set.

                    -

                    source

                    +

                    source

                    # Ribasim.sorted_table!Method.

                    Depending on if a table can be sorted, either sort it or assert that it is sorted.

                    Tables loaded from the database into memory can be sorted. Tables loaded from Arrow files are memory mapped and can therefore not be sorted.

                    -

                    source

                    +

                    source

                    # Ribasim.timestepsMethod.

                    Get all saved times in seconds since start

                    -

                    source

                    +

                    source

                    # Ribasim.update_basinMethod.

                    Load updates from ‘Basin / time’ into the parameters

                    -

                    source

                    +

                    source

                    # Ribasim.update_jac_prototype!Method.

                    Method for nodes that do not contribute to the Jacobian

                    -

                    source

                    +

                    source

                    # Ribasim.update_jac_prototype!Method.

                    The controlled basin affects itself and the basins upstream and downstream of the controlled pump affect eachother if there is a basin upstream of the pump. The state for the integral term and the controlled basin affect eachother, and the same for the integral state and the basin upstream of the pump if it is indeed a basin.

                    -

                    source

                    +

                    source

                    # Ribasim.update_jac_prototype!Method.

                    If both the unique node upstream and the unique node downstream of these nodes are basins, then these directly depend on eachother and affect the Jacobian 2x Basins always depend on themselves.

                    -

                    source

                    +

                    source

                    # Ribasim.update_jac_prototype!Method.

                    If both the unique node upstream and the nodes down stream (or one node further if a fractional flow is in between) are basins, then the downstream basin depends on the upstream basin(s) and affect the Jacobian as many times as there are downstream basins Upstream basins always depend on themselves.

                    -

                    source

                    +

                    source

                    # Ribasim.update_tabulated_rating_curve!Method.

                    Load updates from ‘TabulatedRatingCurve / time’ into the parameters

                    -

                    source

                    +

                    source

                    # Ribasim.valid_discrete_controlMethod.

                    Check:

                      @@ -741,41 +741,41 @@

                      source

                      +

                      source

                      # Ribasim.valid_edge_typesMethod.

                      Check that only supported edge types are declared.

                      -

                      source

                      +

                      source

                      # Ribasim.valid_edgesMethod.

                      Test for each node given its node type whether the nodes that

                      are downstream (‘down-edge’) of this node are of an allowed type

                      -

                      source

                      +

                      source

                      # Ribasim.valid_flow_ratesMethod.

                      Test whether static or discrete controlled flow rates are indeed non-negative.

                      -

                      source

                      +

                      source

                      # Ribasim.valid_fractional_flowMethod.

                      Check that nodes that have fractional flow outneighbors do not have any other type of outneighbor, that the fractions leaving a node add up to ≈1 and that the fractions are non-negative.

                      -

                      source

                      +

                      source

                      # Ribasim.valid_n_neighborsMethod.

                      Test for each node given its node type whether it has an allowed number of flow/control inneighbors and outneighbors

                      -

                      source

                      +

                      source

                      # Ribasim.valid_profilesMethod.

                      Check whether the profile data has no repeats in the levels and the areas start positive.

                      -

                      source

                      +

                      source

                      # Ribasim.valid_sourcesMethod.

                      The source nodes must only have one outneighbor.

                      -

                      source

                      +

                      source

                      # Ribasim.water_balance!Method.

                      The right hand side function of the system of ODEs set up by Ribasim.

                      -

                      source

                      +

                      source

                      # Ribasim.write_arrowMethod.

                      Write a result table to disk as an Arrow file

                      -

                      source

                      +

                      source

                      # Ribasim.config.algorithmMethod.

                      Create an OrdinaryDiffEqAlgorithm from solver config

                      -

                      source

                      +

                      source

                      # Ribasim.config.snake_caseMethod.

                      Convert a string from CamelCase to snake_case.

                      -

                      source

                      +

                      source

                      @@ -796,7 +796,7 @@

                      source

                      +

                      source

                      @@ -804,10 +804,10 @@

                      1.5 Macros

                      # Ribasim.config.@addfieldsMacro.

                      Add fieldnames with Union{String, Nothing} type to struct expression. Requires (option?) use before it.

                      -

                      source

                      +

                      source

                      # Ribasim.config.@addnodetypesMacro.

                      Add all TableOption subtypes as fields to struct expression. Requires (option?) use before it.

                      -

                      source

                      +

                      source

                      @@ -817,8 +817,8 @@

                      Ribasim.Ribasim
                    • Ribasim.config
                    • Ribasim.config.algorithms
                    • -
                    • Ribasim.AllocationModel
                    • Ribasim.AllocationModel
                    • +
                    • Ribasim.AllocationModel
                    • Ribasim.Basin
                    • Ribasim.Connectivity
                    • Ribasim.DiscreteControl
                    • @@ -876,8 +876,8 @@

                      Ribasim.findsorted
                    • Ribasim.flow_table
                    • Ribasim.formulate_basins!
                    • -
                    • Ribasim.formulate_flow!
                    • Ribasim.formulate_flow!
                    • +
                    • Ribasim.formulate_flow!
                    • Ribasim.formulate_flow!
                    • Ribasim.get_area_and_level
                    • Ribasim.get_compressor
                    • @@ -918,10 +918,10 @@

                      Ribasim.sorted_table!
                    • Ribasim.timesteps
                    • Ribasim.update_basin
                    • +
                    • Ribasim.update_jac_prototype!
                    • Ribasim.update_jac_prototype!
                    • Ribasim.update_jac_prototype!
                    • Ribasim.update_jac_prototype!
                    • -
                    • Ribasim.update_jac_prototype!
                    • Ribasim.update_tabulated_rating_curve!
                    • Ribasim.valid_discrete_control
                    • Ribasim.valid_edge_types
                    • diff --git a/python/examples.html b/python/examples.html index 546c10d82..1e77cbeae 100644 --- a/python/examples.html +++ b/python/examples.html @@ -545,7 +545,7 @@

                      2 Update the basi ax = df_flow.pivot_table(index="time", columns="edge", values="flow_m3d").plot() ax.legend(bbox_to_anchor=(1.3, 1), title="Edge")
                      -
                      <matplotlib.legend.Legend at 0x7f164810bad0>
                      +
                      <matplotlib.legend.Legend at 0x7f01301eb010>

                      diff --git a/search.json b/search.json index 3ad596ced..73a1db128 100644 --- a/search.json +++ b/search.json @@ -1,4 +1,144 @@ [ + { + "objectID": "core/equations.html", + "href": "core/equations.html", + "title": "Equations", + "section": "", + "text": "Ribasim currently simulates the following “natural” water balance terms:\nAdditionally, Ribasim simulates the following “allocated” water balance terms:\nDepending on the type of boundary conditions, Ribasim requires relation between storage volume and wetted area \\(A\\), and between the storage volume and the water level \\(h\\). These are (currently) represented by piecewise linear relationships." + }, + { + "objectID": "core/equations.html#the-jacobian", + "href": "core/equations.html#the-jacobian", + "title": "Equations", + "section": "1.1 The Jacobian", + "text": "1.1 The Jacobian\nThe Jacobian is a \\(n\\times n\\) matrix where \\(n\\) is the number of states in the simulation. The Jacobian is computed either using finite difference methods or automatic differentiation. For more details on the computation of the Jacobian and how it is used in the solvers see numerical considerations.\nThe entries of the Jacobian \\(J\\) are given by \\[\nJ[i,j] = \\frac{\\partial f_j}{\\partial u_i},\n\\]\nhence \\(J[i,j]\\) quantifies how \\(f_j\\), the derivative of state \\(j\\) with respect to time, changes with a change in state \\(i\\). If a node creates dependendies between basin storages (or other states), then this yields contributions to the Jacobian. If \\(j\\) corresponds to a storage state, then\n\\[\nJ[i,j] = \\sum_{(i',j') \\in E | j' = i} \\frac{\\partial Q_{i',j'}}{\\partial u_i} - \\sum_{(i',j') \\in E | i' = i} \\frac{\\partial Q_{i',j'}}{\\partial u_i},\n\\]\nMost of these terms are always \\(0\\), because a flow over an edge only depends on a small number of states. Therefore the matrix \\(J\\) is very sparse.\nFor many contributions to the Jacobian the derivative of the level \\(l(S)\\) of a basin with respect to its storage \\(S\\) is required. To get an expression for this, we first look at the storage as a function of the level:\n\\[\nS(l) = \\int_{l_0}^l A(\\ell)d\\ell.\n\\]\nFrom this we obtain \\(S'(l) = A(l)\\) and thus \\[\n\\frac{\\text{d}l}{\\text{d}S} = \\frac{1}{A(S)}.\n\\]\n\n\n\n\n\n\nNote\n\n\n\nThe presence of division by the basin area means that areas of size zero are not allowed." + }, + { + "objectID": "core/equations.html#sec-reduction_factor", + "href": "core/equations.html#sec-reduction_factor", + "title": "Equations", + "section": "2.1 The reduction factor", + "text": "2.1 The reduction factor\nAt several points in the equations below a reduction factor is used. This is a term that makes certain transitions more smooth, for instance when a pump stops providing water when its source basin dries up. The reduction factor is given by\n\\[\n \\phi(x; p) =\n \\begin{align}\n \\begin{cases}\n 0 &\\text{if}\\quad x < 0 \\\\\n -2 \\left(\\frac{x}{p}\\right)^3 + 3\\left(\\frac{x}{p}\\right)^2 &\\text{if}\\quad 0 \\le x \\le p \\\\\n 1 &\\text{if}\\quad x > p\n \\end{cases}\n \\end{align},\n\\]\nwhere \\(p > 0\\) is the threshold value which determines the interval \\([0,p]\\) of the smooth transition between \\(0\\) and \\(1\\), see the plot below.\n\n\nCode\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x, p = 3):\n x_scaled = x / p\n phi = (-2 * x_scaled + 3) * x_scaled**2\n phi = np.where(x < 0, 0, phi)\n phi = np.where(x > p, 1, phi)\n\n return phi\n\nfontsize = 15\np = 3\nN = 100\nx_min = -1\nx_max = 4\nx = np.linspace(x_min,x_max,N)\nphi = f(x,p)\n\nfig,ax = plt.subplots(dpi=80)\nax.plot(x,phi)\n\ny_lim = ax.get_ylim()\n\nax.set_xticks([0,p], [0,\"$p$\"], fontsize=fontsize)\nax.set_yticks([0,1], [0,1], fontsize=fontsize)\nax.hlines([0,1],x_min,x_max, color = \"k\", ls = \":\", zorder=-1)\nax.vlines([0,p], *y_lim, color = \"k\", ls = \":\")\nax.set_xlim(x_min,x_max)\nax.set_xlabel(\"$x$\", fontsize=fontsize)\nax.set_ylabel(\"$\\phi(x;p)$\", fontsize=fontsize)\nax.set_ylim(y_lim)\n\nfig.tight_layout()\nplt.show()" + }, + { + "objectID": "core/equations.html#precipitation", + "href": "core/equations.html#precipitation", + "title": "Equations", + "section": "2.2 Precipitation", + "text": "2.2 Precipitation\nThe precipitation term is given by\n\\[\n Q_P = P \\cdot A(S).\n\\tag{2}\\]\nHere \\(P = P(t)\\) is the precipitation rate and \\(A\\) is the wetted area. \\(A\\) is a function of the storage \\(S = S(t)\\): as the volume of water changes, the area of the free water surface may change as well, depending on the slopes of the surface waters." + }, + { + "objectID": "core/equations.html#evaporation", + "href": "core/equations.html#evaporation", + "title": "Equations", + "section": "2.3 Evaporation", + "text": "2.3 Evaporation\nThe evaporation term is given by\n\\[\n Q_E = E_\\text{pot} \\cdot A(S) \\cdot \\phi(d;0.1).\n\\tag{3}\\]\nHere \\(E_\\text{pot} = E_\\text{pot}(t)\\) is the potential evaporation rate and \\(A\\) is the wetted area. \\(\\phi\\) is the reduction factor which depends on the depth \\(d\\). It provides a smooth gradient as \\(S \\rightarrow 0\\).\nA straightforward formulation \\(Q_E = \\mathrm{max}(E_\\text{pot} A(S), 0)\\) is unsuitable, as \\(\\frac{\\mathrm{d}Q_E}{\\mathrm{d}S}(S=0)\\) is then not well-defined.\n\nA non-smooth derivative results in extremely small timesteps and long computation time: ModelingToolkit identifies the singular behavior and adjusts its timestepping. In a physical interpretation, evaporation is switched on or off per individual droplet of water. In general, the effect of the reduction term is negligible, or not even necessary. As a surface water dries, its wetted area decreases and so does the evaporative flux. However, for (simplified) cases with constant wetted surface (a rectangular profile), evaporation only stops at \\(S = 0\\)." + }, + { + "objectID": "core/equations.html#infiltration-and-drainage", + "href": "core/equations.html#infiltration-and-drainage", + "title": "Equations", + "section": "2.4 Infiltration and Drainage", + "text": "2.4 Infiltration and Drainage\nInfiltration is provided as a lump sum for the basin. If Ribasim is coupled with MODFLOW 6, the infiltration is computed as the sum of all positive flows of the MODFLOW 6 boundary conditions in the basin:\n\\[\n Q_\\text{inf} = \\sum_{i=1}^{n} \\sum_{j=1}^{m} \\max(Q_{\\mathrm{mf6}_{i,j}}, 0.0)\n\\] {#eq-inf}.\nWhere \\(i\\) is the index of the boundary condition, \\(j\\) the MODFLOW 6 cell index, \\(n\\) the number of boundary conditions, and \\(m\\) the number of MODFLOW 6 cells in the basin. \\(Q_{\\mathrm{mf6}_{i,j}}\\) is the flow computed by MODFLOW 6 for cell \\(j\\) for boundary condition \\(i\\).\nDrainage is a lump sump for the basin, and consists of the sum of the absolute value of all negative flows of the MODFLOW 6 boundary conditions in the basin.\n\\[\n Q_\\text{drn} = \\sum_{i=1}^{n} \\sum_{j=1}^{m} \\left| \\min(Q_{\\mathrm{mf6}_{i,j}}, 0.0) \\right|\n\\tag{4}\\]\nThe interaction with MODFLOW 6 boundary conditions is explained in greater detail in the the MODFLOW coupling section of the documentation." + }, + { + "objectID": "core/equations.html#upstream-and-downstream-flow", + "href": "core/equations.html#upstream-and-downstream-flow", + "title": "Equations", + "section": "2.5 Upstream and downstream flow", + "text": "2.5 Upstream and downstream flow\nRibasim’s basins can be connected to each other, and each basin expects an explicit connection. These connections are currently available for inter-basin flows:\n\n\nPump\nTabulatedRatingCurve\nLinearResistance\nManningResistance\n\nThe flow direction of the basin is not pre-determined: flow directions may freely reverse, provided the connection allows it. Currently, a LinearResistance allows bidirectional flow, but the\nAdditionally, three additional “connections” area available for the “outmost” basins (external nodes) in a network.\n\nTerminal\nLevelBoundary\nFlowBoundary\n\n\n2.5.1 Pump\nThe behaviour of pumps is very straight forward if these nodes are not PID controlled. Their flow is given by a fixed flow rate \\(q\\), multiplied by a reduction factor: \\[\nQ_\\text{pump} = \\phi(u; 10.0)q\n\\]\nHere \\(u\\) is the storage of the upstream basin. The reduction factor \\(\\phi\\) makes sure that the flow of the pump goes smootly to \\(0\\) as the upstream basin dries out.\n\n\n2.5.2 Outlet\nThe outlet is very similar to the pump, but it has a few extra reduction factors for physical constraints: \\[\nQ_\\text{outlet} = \\phi(u_a; 10.0)\\phi(\\Delta h; 0.1) \\phi(h_a-h_\\text{min};0.1)q.\n\\] The subscript \\(a\\) denotes the upstream node and \\(b\\) the downstream node. The first reduction factor is equivalent to the one for the pump. The second one makes sure that the outlet flow goes to zero as the head difference \\(\\Delta h = h_a - h_b\\) goes to zero. The last one makes sure that the outlet only produces flow when the upstream level is above the minimum chrest level \\(h_\\text{min}\\).\nNot all node types upstream or downstream of the outlet have a defined level. If this is the case, and therefore the reduction factor cannot be computed, it is defined to be \\(1.0\\).\n\n\n2.5.3 TabulatedRatingCurve\nThe Tabulated Rating Curve is a tabulation of a basin’s discharge behavior. It describes a piecewise linear relationship between the basin’s level and its discharge. It can be understood as an empirical description of a basin’s properties. This can include an outlet, but also the lumped hydraulic behavior of the upstream channels.\n\nThe Tabulated Rating Curve should indicate at which volume no discharge occurs (the dead storage volume).\n\n\n\n\n\n\nNote\n\n\n\nCurrently, the discharge relies only on the basin’s level; it could also use the volume of both connected basins to simulate backwater effects, submersion of outlets, or even reversal of flows for high precipitation events.\n\n\n\n\n2.5.4 LinearResistance\nA LinearResistance connects two basins together. The flow between the two basins is determined by a linear relationship:\n\\[\n Q = \\frac{h_a - h_b}{R}\n\\tag{5}\\]\nHere \\(h_a\\) is the water level in the first basin, \\(h_b\\) is the water level in the second basin, and \\(R\\) is the resistance of the link. A LinearResistance makes no assumptions about the direction of the flow: water flows from high to low.\n\n\n2.5.5 Terminal\nThis only allows outflow from a basin into a terminal node.\n\n\n2.5.6 LevelBoundary\nThis can be connected to a basin via a LinearResistance. This boundary node will then exchange water with the basin based on the difference in water level between the two.\n\n\n2.5.7 FlowBoundary\nThis can be connected directly to a basin and prescribes the flow to or from that basin. We require that the edge connecting the flow boundary to the basin should point towards the basin, so that positive flow corresponds to water being added to the model.\n\n\n2.5.8 Manning connection\nRibasim is capable of simulating steady flow between basins through a reach described by a trapezoidal profile and a Manning roughness coefficient.\nWe describe the discharge from basin \\(a\\) to basin \\(b\\) solely as a function of the water levels in \\(a\\) and \\(b\\).\n\\[\nQ = f(h_a, h_b)\n\\]\nwhere:\n\nThe subscripts \\(a,b\\) denote basins\n\\(h\\) is the hydraulic head, or water level\n\nThe energy equation for open channel flow is:\n\\[\nH = h + \\frac{v^2}{2g}\n\\]\nWhere\n\n\\(H\\) is total head\n\\(v\\) is average water velocity\n\\(g\\) is gravitational acceleration\n\nThe discharge \\(Q\\) is defined as:\n\\[\nQ = Av\n\\]\nwhere \\(A\\) is cross-sectional area.\nWe use conservation of energy to relate the total head at \\(a\\) to \\(b\\), with \\(H_a > H_b\\) as follows:\n\\[\nH_a = H_b + h_{\\text{loss}}\n\\]\nOr:\n\\[\nh_a + \\frac{v_a^2}{2g} = h_b + \\frac{v_b^2}{2g} + h_{\\text{loss}}\n\\]\nWhere \\(v\\) is the average water velocity. \\(h_{\\text{loss}}\\) is a combination of friction and contraction/expansion losses:\n\\[\nh_{\\text{loss}} = S_f L + \\frac{C}{2g} \\left(v_b^2 - v_a^2\\right)\n\\]\nWhere:\n\n\\(L\\) is the reach length\n\\(S_f\\) is the representative friction slope\n\\(C\\) is the expansion or contraction coefficient, \\(0 \\le C \\le1\\)\n\nWe assume velocity differences in a connection are negligible (\\(v_a = v_b\\)):\n\\[\nh_a = h_b + S_f L\n\\]\nFriction losses are computed with the Gauckler-Manning formula:\n\\[\nQ = \\frac{A}{n} R_h^\\frac{2}{3} \\sqrt{S_f}\n\\]\nWhere:\n\n\\(A\\) is the representative area.\n\\(R_h\\) is the representative wetted radius.\n\\(S_f\\) is the representative friction slope.\n\\(n\\) is Manning’s roughness coefficient.\n\nWe can rewrite to express \\(S_f\\) in terms of Q:\n\\[\nS_f = Q^2 \\frac{n^2}{A^2 R_h^{4/3}}\n\\]\nNo water is added or removed in a connection:\n\\[\nQ_a = Q_b = Q\n\\]\nSubstituting:\n\\[\nh_a = h_b + Q^2 \\frac{n^2}{A^2 R_h^{4/3}} L\n\\]\nWe can then express \\(Q\\) as a function of head difference \\(\\Delta h\\):\n\\[\nQ = \\textrm{sign}(\\Delta h) \\frac{A}{n} R_h^{2/3}\\sqrt{\\frac{|\\Delta h|}{L} }\n\\]\nThe \\(\\textrm{sign}(\\Delta h)\\) term causes the direction of the flow to reverse if the head in basin \\(b\\) is larger than in basin \\(a\\).\nThis expression however leads to problems in simulation since the derivative of \\(Q\\) with respect to \\(\\Delta h\\) tends to \\(\\pm \\infty\\) as \\(\\Delta h\\) tends to 0. Therefore we use the slightly modified expression\n\\[\nQ = \\textrm{sign}(\\Delta h) \\frac{A}{n} R_h^{2/3}\\sqrt{\\frac{\\Delta h}{L} s(\\Delta h)}\n\\]\nto smooth out this problem. Here \\(s(x) = \\frac{2}{\\pi}\\arctan{1000x}\\) can be thought of as a smooth approximation of the sign function.\n\n\n\n\n\n\nNote\n\n\n\nThe computation of \\(S_f\\) is not exact: we base it on a representative area and hydraulic radius, rather than integrating \\(S_f\\) along the length of a reach. Direct analytic solutions exist for e.g. parabolic profiles (Tolkmitt), but other profiles requires relatively complicated approaches (such as approximating the profile with a polynomial).\nWe use the average value of the cross-sectional area, the average value of the water depth, and the average value of the hydraulic radius to compute a friction slope. The size of the resulting error will depend on the water depth difference between the upstream and downstream basin.\n\n\nThe cross sectional area for a trapezoidal or rectangular profile:\n\\[\nA = w d + \\frac{\\Delta y}{\\Delta z} d^2\n\\]\nWhere\n\n\\(w\\) is the width at \\(d = 0\\) (A triangular profile has \\(w = 0\\))\n\\(\\frac{\\Delta y}{\\Delta z}\\) is the slope of the profile expressed as the horizontal length for one unit in the vertical (A slope of 45 degrees has \\(\\frac{\\Delta y}{\\Delta z} = 1\\); a rectangular profile 0).\n\nAccordingly, the wetted perimeter is:\n\\[\nB = w + 2 d \\sqrt{\\left(\\frac{\\Delta y}{\\Delta z}\\right)^2 + 1}\n\\]" + }, + { + "objectID": "core/equations.html#the-derivative-term", + "href": "core/equations.html#the-derivative-term", + "title": "Equations", + "section": "3.1 The derivative term", + "text": "3.1 The derivative term\nWhen \\(K_d \\ne 0\\) this adds a level of complexity. We can see this by looking at the error derivative more closely: \\[\n\\frac{\\text{d}e}{\\text{d}t} = \\frac{\\text{d}\\text{SP}}{\\text{d}t} - \\frac{1}{A(u_\\text{PID})}\\frac{\\text{d}u_\\text{PID}}{\\text{d}t},\n\\] where \\(A(u_\\text{PID})\\) is the area of the controlled basin as a function of the storage of the controlled basin \\(u_\\text{PID}\\). The complexity arises from the fact that \\(Q_\\text{PID}\\) is a contribution to \\(\\frac{\\text{d}u_\\text{PID}}{\\text{d}t} = f_\\text{PID}\\), which makes Equation 7 an implicit equation for \\(Q_\\text{PID}\\). We define\n\\[\nf_\\text{PID} = \\hat{f}_\\text{PID} \\pm Q_\\text{pump/outlet},\n\\]\nthat is, \\(\\hat{f}_\\text{PID}\\) is the right hand side of the ODE for the controlled basin storage state without the contribution of the PID controlled pump. The plus sign holds for an outlet and the minus sign for a pump, dictated by the way the pump and outlet connectivity to the controlled basin is enforced.\nUsing this, solving Equation 7 for \\(Q_\\text{PID}\\) yields \\[\nQ_\\text{pump/outlet} = \\text{clip}\\left(\\phi(u_\\text{us})\\frac{K_pe + K_iI + K_d \\left(\\frac{\\text{d}\\text{SP}}{\\text{d}t}-\\frac{\\hat{f}_\\text{PID}}{A(u_\\text{PID})}\\right)}{1\\pm\\phi(u_\\text{us})\\frac{K_d}{A(u_\\text{PID})}};Q_\\min,Q_\\max\\right),\n\\] where the clipping is again done last. Note that to compute this, \\(\\hat{f}_\\text{PID}\\) has to be known first, meaning that the PID controlled pump/outlet flow rate has to be computed after all other contributions to the PID controlled basin’s storage are known." + }, + { + "objectID": "core/equations.html#the-sign-of-the-parameters", + "href": "core/equations.html#the-sign-of-the-parameters", + "title": "Equations", + "section": "3.2 The sign of the parameters", + "text": "3.2 The sign of the parameters\nNote by Equation 6 that the error is positive if the setpoint is larger than the basin level and negative if the setpoint is smaller than the basin level.\nWe enforce the convention that when a pump is controlled, its edge points away from the basin, and when an outlet is controlled, its edge points towards the basin, so that the main flow direction along these edges is positive. Therefore, positive flows of the pump and outlet have opposite effects on the basin, and thus the parameters \\(K_p,K_i,K_d\\) of the pump and outlet must have oppositive signs to achieve the same goal." + }, + { + "objectID": "core/index.html", + "href": "core/index.html", + "title": "Julia core", + "section": "", + "text": "With the term “core”, we mean the computational engine of Ribasim. As detailed in the usage documentation, it is generally used as a command line tool.\nThe theory is described on the equations page, and more in-depth numerical considerations are described on the numerical considerations page. As allocation is a large and self-contained part of the Ribasim core, it is described on the separate allocation page.\nThe core is implemented in the Julia programming language, and can be found in the Ribasim repository under the core/ folder. For developers we also advise to read the developer documentation." + }, + { + "objectID": "core/allocation.html", + "href": "core/allocation.html", + "title": "Allocation", + "section": "", + "text": "Allocation is the process of assigning an allocated abstraction flow rate to user nodes in the model based on information about sources, user demands over various priorities, constraints introduced by nodes, local water availability and graph topology. The allocation procedure implemented in Ribasim is heavily inspired by the maximum flow problem.\nThe allocation problem is solved per subnetwork of the Ribasim model. The subnetwork is used to formulate an optimization problem with the JuMP package, which is solved using the HiGHS solver. See also the example of solving the maximum flow problem with JuMP.jl here." + }, + { + "objectID": "core/allocation.html#allocation-problem-input", + "href": "core/allocation.html#allocation-problem-input", + "title": "Allocation", + "section": "1.1 Allocation problem input", + "text": "1.1 Allocation problem input\n\n1.1.1 The subnetwork\nThe allocation problem is solved per subgraph, where a subgraph is given by a subset \\(S \\subset V\\) of node ids. Different subgraphs are disjoint from eachother.\n\n\n1.1.2 Source flows\nSources are indicated by a set of edges in the subnetwork \\[\nE_S^\\text{source} \\subset \\left(S \\times S\\right) \\cap E.\n\\] That is, if \\((i,j) \\in E_S^\\text{source}\\), then \\(Q_{ij}\\) is treated as a source flow in the allocation problem.\n\n\n1.1.3 User demands\nThe subnetwork contains a subset of user nodes \\(U_S \\subset S\\), who all have time varying demands over various priorities \\(p\\): \\[\n d^p_i(t), \\quad i \\in U_S, p = 1,2,\\ldots, p_{\\max}.\n\\]\n\n\n\n\n\n\nNote\n\n\n\nOn this page we assume that the priorities are given by all integers from \\(1\\) to some \\(p_{\\max} \\in \\mathbb{N}\\). However, in the Ribasim input this is not a requirement; some of these in between priority values can be missing, only the ordering of the given priorities is taken into account.\n\n\n\n\n1.1.4 Vertical fluxes and local storage\nApart from the source flows denoted by edges, there are other sources of water in the subnetwork, associated with the basins in the subnetwork \\(B_S = B \\cap S\\). Firstly there is the sum of the vertical fluxes (precipitation, evaporation, infiltration and drainage) for each basin \\[\n \\phi_i(t), \\quad \\forall i \\in B_S.\n\\]\nSecondly, there is the available water in each basin above the minimum level \\(l_{\\min,i}\\) \\[\n u_i(t)-S(l_{\\min,i}), \\quad \\forall i \\in B_S.\n\\] Note that this value can be negative, which we interpret as a demand from the basin.\n\n\n1.1.5 Flow magnitude and direction constraints\nNodes in the Ribasim model that have a max_flow_rate, i.e. pumps and outlets, put a constraint on the flow through that node. Some nodes only allow flow in one direction, like pumps, outlets and tabulated rating curves.\n\n\n1.1.6 Fractional flows and user return flows\nBoth fractional flow nodes and user nodes dictate proportional relationships between flows over edges in the subnetwork. Users have a return factor \\(r_i, i \\in U_S\\)." + }, + { + "objectID": "core/allocation.html#the-allocation-optimization-problem", + "href": "core/allocation.html#the-allocation-optimization-problem", + "title": "Allocation", + "section": "1.2 The allocation optimization problem", + "text": "1.2 The allocation optimization problem\n\n1.2.1 The allocation graph\nA new graph is created from the subnetwork, which we call the allocation graph. To indicate the difference between subnetwork data and allocation graph data, the allocation graph data is denoted with a hat. The allocation graph consists of:\n\nNodes \\(\\hat{V_S}\\), where each basin, source and user in the subnetwork get a node in the allocation graph. Also nodes that have fractional flow outneighbors get a node in the allocation graph. The implementation makes heavy use of the node id mapping \\(m_S : i \\mapsto \\hat{i}\\) to translate from subnetwork node IDs to allocation graph node IDs. Unless specified otherwise, we assume this relationship between index symbols that appear both with and without a hat.\nEdges \\(\\hat{E_S}\\), where the edges in the allocation graph are given by one or more edges in the subnetwork, where those edges connect nodes in the subnetwork that have an equivalent in the allocation graph. The direction of the edges in the allocation graph is given by the direction constraints in the subnetwork.\n\nFor notational convenience, we use the notation \\[\n \\begin{align}\n \\hat{V}^{\\text{out}}_S(\\hat{i}) = \\left\\{\\hat{j} \\in \\hat{V}_S : (\\hat{i},\\hat{j}) \\in \\hat{E}_S\\right\\} \\\\\n \\hat{V}^{\\text{in}}_S(\\hat{j}) = \\left\\{\\hat{i} \\in \\hat{V}_S : (\\hat{i},\\hat{j}) \\in \\hat{E}_S\\right\\}\n \\end{align}\n\\] for the set of in-neighbors and out-neighbors of a node in the allocation graph respectively.\n\n\n1.2.2 The allocation graph capacities\nThe capacities of the edges of the allocation graph are collected in the sparse capacity matrix \\(\\hat{C}_S \\in \\overline{\\mathbb{R}}_{\\ge 0}^{\\hat{n}\\times\\hat{n}}\\) where \\(\\hat{n}\\) is the number of nodes in the allocation graph. The capacities can be infinite.\nThe capacities are determined in 3 different ways:\n\nIf an edge does not exist, i.e. \\((\\hat{i},\\hat{j}) \\notin \\hat{E}\\) for certain \\(1 \\le \\hat{i},\\hat{j}\\le \\hat{n}\\), then \\((\\hat{C}_S)_{\\hat{i},\\hat{j}} = 0\\);\nThe capacity of the edge \\(\\hat{e} \\in \\hat{E_S}\\) is given by the smallest max_flow_rate of the nodes along the equivalent edges in the subnetwork. If there are no nodes with a max_flow_rate, the edge capacity is infinite;\nIf the edge is a source, the capacity of the edge is given by the flow rate of that source.\n\n\n\n1.2.3 The optimization variables\nThere are several types of variables whose value has to be determined to solve the allocation problem:\n\nThe flows \\(F \\in \\mathbb{R}_{\\ge 0}^{\\hat{n}\\times\\hat{n}}\\) over the edges in the allocation graph;\nThe allocations to the users \\[\n A^\\text{user}_{\\hat{i},p} \\ge 0, \\quad \\forall \\hat{i} \\in \\hat{U}_S, \\forall p \\in \\{1,2,\\ldots, p_\\max\\},\n\\] where \\(\\hat{U}_S = m_S(U_S) \\subset \\hat{V}_S\\) is the set of user node ids in the allocation graph;\nThe allocations to the basins \\[\n A^\\text{basin}_{\\hat{i}} \\ge 0, \\quad \\hat{B}_S,\n\\] where \\(\\hat{B} = m_S(B_S) \\subset \\hat{V}_S\\) is the set of basin node ids in the allocation graph.\n\n\n\n1.2.4 The optimization objective\nThe goal of allocation is to maximize the flow to the users. However, basins can also demand water if their level is below the minimum abstraction level, which we give a higher priority than user demands. Therefore, we use the following optimization objective: \\[\n \\max \\sum_{\\hat{i} \\in \\hat{B}_S} A^\\text{basin}_{\\hat{i}} + \\sum_{\\hat{i}\\in \\hat{U}_S} \\sum_{p=1}^{p_\\max} 2^{-p} A^\\text{user}_{\\hat{i},p}.\n\\tag{1}\\] This is a linear combination of all allocations, where allocations to basins get a weight of \\(1\\) and allocations to users get a weight of \\(2^{-p}\\) where \\(p\\) is the priority.\n\n\n1.2.5 The optimization variable constraints\n\nSource flows: for the source edges we have that \\[\nF_{\\hat{i}\\hat{j}} \\le Q_{ij} \\quad \\forall (i,j) \\in E_S^\\text{source}.\n\\] Note that we do not require equality here; not all source flow has to be used.\nFlow conservation: For the basins in the allocation graph we have that \\[\n \\sum_{\\hat{j}=1}^{\\hat{n}} F_{\\hat{k}\\hat{j}} \\le \\sum_{\\hat{i}=1}^{\\hat{n}} F_{\\hat{i}\\hat{k}} + \\Phi_{\\hat{k}}, \\quad \\forall\\hat{k} \\in \\hat{B}_S.\n\\tag{2}\\] Note that we do not require equality here; in the allocation we do not mind that excess flow is ‘forgotten’ if it cannot contribute to the allocation to the users. \\(\\Phi_{\\hat{k}}\\) is the local water supply of the basins: \\[\n \\Phi_{\\hat{k}} = \\max\\left(\\phi_k(t) + \\frac{u_k(t)-S(l_{\\min,k})}{\\Delta t_\\text{alloc}}, 0.0 \\right).\n\\tag{3}\\] Here the first term denotes the vertical fluxes and the second term the flow that can be supplied by the water in the basin above its minimum level, where \\(\\Delta t_\\text{alloc}\\) is the allocation solve timestep.\nCapacity: the flows over the edges are positive and bounded by the edge capacity: \\[\n F_{\\hat{i}\\hat{j}} \\le \\left(\\hat{C}_S\\right)_{\\hat{i}\\hat{j}}, \\quad \\forall(\\hat{i},\\hat{j}) \\in \\hat{E}_S.\n\\tag{4}\\]\nUser outflow: The outflow of the user is dictated by the inflow and the return factor: \\[\n\\begin{align}\n F_{\\hat{i}\\hat{k}} = r_k \\cdot F_{\\hat{k}\\hat{j}}\\\\\n \\quad \\forall\\hat{k} \\in \\hat{U}_s, \\\\\n \\hat{V}^{\\text{in}}_S(\\hat{k}) = \\{\\hat{i}\\},\\\\\n \\hat{V}^{\\text{out}}_S(\\hat{k}) = \\{\\hat{j}\\}.\n\\end{align}\n\\tag{5}\\] Here we use that each user node in the allocation graph has an unique in-edge and out-edge.\nUser allocation: The flow over the edge to the user is equal to the sum of the allocations to the user: \\[\n F_{\\hat{i}\\hat{k}} = \\sum_{p=1}^{p_\\max} A^\\text{user}_{\\hat{k},p}, \\quad \\forall \\hat{k} \\in \\hat{U}_S, \\hat{V}^{\\text{out}}_s(\\hat{k}) = \\{\\hat{i}\\}.\n\\tag{6}\\] Here we use that each user has an unique out-edge.\nUser demand: what is allocated to the user is bounded above by the user demand: \\[\n A_{\\hat{i},p}^\\text{user} \\leq d_i^p(t) \\quad \\forall\\hat{i} \\in \\hat{U}_S, \\; p = 1,\\ldots,p_\\max.\n\\]\nBasin allocation: If the flow supplied by a basin (as determined in Equation 3) is negative, it is a demand: \\[\nA^\\text{basin}_{\\hat{i}} = \\max\\left(-\\left(\\phi_i(t) + \\frac{u_i(t)-S(l_{\\min,k})}{\\Delta t_\\text{alloc}}\\right), 0.0 \\right), \\quad \\forall \\hat{i} \\in \\hat{B}_S.\n\\tag{7}\\]\nFractinal flow: Let \\(\\hat{L}_S \\subset \\hat{V}_S\\) be the set of nodes in the max flow graph with fractional flow outneighbors, and \\(f_j\\) the flow fraction associated with fractional flow node \\(j \\in V_S\\). Then \\[\n\\begin{align}\n F_{\\hat{i}\\hat{j}} = f_j \\sum_{k\\in \\hat{V}^\\text{in}_S(\\hat{i})} F_{\\hat{k}\\hat{i}} \\\\\n \\forall \\hat{i} \\in \\hat{L}_S, \\\\\n \\hat{j} \\in \\hat{V}_S^\\text{out}(\\hat{i}).\n\\end{align}\n\\tag{8}\\]\nFlow sign: Furthermore there are the non-negativity constraints for the flows and allocations, see The optimization variables." + }, + { + "objectID": "core/allocation.html#final-notes-on-the-allocation-problem", + "href": "core/allocation.html#final-notes-on-the-allocation-problem", + "title": "Allocation", + "section": "1.3 Final notes on the allocation problem", + "text": "1.3 Final notes on the allocation problem\n\n1.3.1 Users using their own return flow\nIf not explicitly avoided, users can use their own return flow in this allocation problem formulation. Therefore, return flow of users is only taken into account by allocation if that return flow is downstream of the user where it comes from. That is, if there is no path in the directed allocation graph from the user outflow node back to the user." + }, + { + "objectID": "qgis/index.html", + "href": "qgis/index.html", + "title": "QGIS plugin", + "section": "", + "text": "Install QGIS version 3.28 or higher.\n\n\nDownload ribasim_qgis.zip, see the download section.\nPlugins menu > Manage and Install Plugins…\n\n\n\n\n\nSelect “Install from ZIP”:\n\nBrowse to the ribasim_qgis.zip file containing the plugin that was downloaded earlier\nClick “Install Plugin”\n\n\n\n\n\n\nStart the Ribasim plugin.\n\n\n\n\n\n\n\n\nIn QGIS, navigate to “Plugins > Manage and Install Plugins > All”. In the search bar, type: “iMOD”. Select the iMOD plugin, and click “Install”.\nAt least version 0.4.0 of the iMOD plugin is required.\nThe Time Series widget from the iMOD plugin is used for visualizing Ribasim results, which is described in Section 1.5. Documentation on the Time Series widget can be found in the iMOD documentation.\n\n\n\nOpen example model database.gpkg or create a new model.\n\n\n\n\n\nCheck if your coordinate reference system (CRS) is set correctly.\n\n\n\n\n\nIf you are working with an unknown CRS, right click the model database group in Layers, and click “Set Group CRS…”.\n\n\n\n\n\nIf you are modeling the Netherlands, select “Amersfoort / RD New” (EPSG:28992).\n\n\n\n\n\n\n\n\n\n\n\nSelect the Node layer.\n\n\n\n\n\nTurn on the edit mode to be able to add nodes on the map.\n\n\n\n\n\nAdd nodes to the map with a left click and select the node type.\n\n\n\n\n\nTurn the edit mode off and save the edits to the Nodes layer.\n\n\n\n\n\n\n\n\nRight click a layer and select “Open Attribute Table”.\n\n\n\n\n\nClick the yellow pencil icon on the top left to enable editing, and copy and paste a record. A record can be selected by clicking on the row number.\n\n\n\n\n\nAdjust the content. If you prefer, it also works to copy data with the same columns from Excel. Turn off edit mode and save changes to the layer.\n\n\n\n\n\n\n\n\n\n\n\nMake sure the Snapping Toolbar is visible, by going to the View > Toolbars menu. Turn on snapping mode by clicking the magnet and set the snapping distance to 25 pixels.\n\n\n\n\n\n\n\n\nSelect the Edge layer and turn on the edit mode.\n\n\n\n\n\nSelect “Add line feature”.\n\n\n\n\n\nCreate a connection by left clicking a source node and right clicking the destination node.\n\n\n\n\n\nNow leave the edit mode and save the results to the layer.\n\n\n\n\n\nOpen a text editor and create an empty file next to your database, with the .toml extension.\nAdd the following content to the TOML file:\n\n\n\nribasim.toml\n\nstarttime = 2020-01-01 00:00:00\nendtime = 2021-01-01 00:00:00\ndatabase = \"database.gpkg\"\n\n\nUnzip the Ribasim command line interface, ribasim_cli.zip\nOpen your terminal and go to the directory where your TOML is stored. Now run path/to/ribasim_cli/ribasim ribasim.toml. Adjust the path to the ribasim_cli folder to where you placed it. This runs the model.\nIn your model directory there is now a results/ folder with basin.arrow and flow.arrow output files.\n\n\n\n\n\n\nIn QGIS select the model group.\n\n\n\n\n\nIn the Ribasim plugin widget, select the Results tab and click “Associate Results”.\n\n\n\n\n\nSelect results/basin.arrow.\n\n\n\n\n\nThis adds metadata to the model that the iMOD plugin can use to find the timeseries data that is associated to the model nodes.\n\n\n\nClick the “Time Series” button of the iMOD plugin.\n\n\n\n\n\nSelect the variables that you want to plot.\n\n\n\n\n\nClick “Select points” and select a node by dragging a rectangle around it on the map. Hold the Ctrl key to select multiple nodes. Currently only the Basin nodes can be plotted.\n\n\n\n\n\nThe associated time series are shown the the graph." + }, + { + "objectID": "qgis/index.html#start", + "href": "qgis/index.html#start", + "title": "QGIS plugin", + "section": "", + "text": "Install QGIS version 3.28 or higher.\n\n\nDownload ribasim_qgis.zip, see the download section.\nPlugins menu > Manage and Install Plugins…\n\n\n\n\n\nSelect “Install from ZIP”:\n\nBrowse to the ribasim_qgis.zip file containing the plugin that was downloaded earlier\nClick “Install Plugin”\n\n\n\n\n\n\nStart the Ribasim plugin.\n\n\n\n\n\n\n\n\nIn QGIS, navigate to “Plugins > Manage and Install Plugins > All”. In the search bar, type: “iMOD”. Select the iMOD plugin, and click “Install”.\nAt least version 0.4.0 of the iMOD plugin is required.\nThe Time Series widget from the iMOD plugin is used for visualizing Ribasim results, which is described in Section 1.5. Documentation on the Time Series widget can be found in the iMOD documentation.\n\n\n\nOpen example model database.gpkg or create a new model.\n\n\n\n\n\nCheck if your coordinate reference system (CRS) is set correctly.\n\n\n\n\n\nIf you are working with an unknown CRS, right click the model database group in Layers, and click “Set Group CRS…”.\n\n\n\n\n\nIf you are modeling the Netherlands, select “Amersfoort / RD New” (EPSG:28992)." + }, + { + "objectID": "qgis/index.html#edit-nodes", + "href": "qgis/index.html#edit-nodes", + "title": "QGIS plugin", + "section": "", + "text": "Select the Node layer.\n\n\n\n\n\nTurn on the edit mode to be able to add nodes on the map.\n\n\n\n\n\nAdd nodes to the map with a left click and select the node type.\n\n\n\n\n\nTurn the edit mode off and save the edits to the Nodes layer.\n\n\n\n\n\n\n\n\nRight click a layer and select “Open Attribute Table”.\n\n\n\n\n\nClick the yellow pencil icon on the top left to enable editing, and copy and paste a record. A record can be selected by clicking on the row number.\n\n\n\n\n\nAdjust the content. If you prefer, it also works to copy data with the same columns from Excel. Turn off edit mode and save changes to the layer." + }, + { + "objectID": "qgis/index.html#connect-nodes", + "href": "qgis/index.html#connect-nodes", + "title": "QGIS plugin", + "section": "", + "text": "Make sure the Snapping Toolbar is visible, by going to the View > Toolbars menu. Turn on snapping mode by clicking the magnet and set the snapping distance to 25 pixels.\n\n\n\n\n\n\n\n\nSelect the Edge layer and turn on the edit mode.\n\n\n\n\n\nSelect “Add line feature”.\n\n\n\n\n\nCreate a connection by left clicking a source node and right clicking the destination node.\n\n\n\n\n\nNow leave the edit mode and save the results to the layer." + }, + { + "objectID": "qgis/index.html#run-a-model", + "href": "qgis/index.html#run-a-model", + "title": "QGIS plugin", + "section": "", + "text": "Open a text editor and create an empty file next to your database, with the .toml extension.\nAdd the following content to the TOML file:\n\n\n\nribasim.toml\n\nstarttime = 2020-01-01 00:00:00\nendtime = 2021-01-01 00:00:00\ndatabase = \"database.gpkg\"\n\n\nUnzip the Ribasim command line interface, ribasim_cli.zip\nOpen your terminal and go to the directory where your TOML is stored. Now run path/to/ribasim_cli/ribasim ribasim.toml. Adjust the path to the ribasim_cli folder to where you placed it. This runs the model.\nIn your model directory there is now a results/ folder with basin.arrow and flow.arrow output files." + }, + { + "objectID": "qgis/index.html#sec-results", + "href": "qgis/index.html#sec-results", + "title": "QGIS plugin", + "section": "", + "text": "In QGIS select the model group.\n\n\n\n\n\nIn the Ribasim plugin widget, select the Results tab and click “Associate Results”.\n\n\n\n\n\nSelect results/basin.arrow.\n\n\n\n\n\nThis adds metadata to the model that the iMOD plugin can use to find the timeseries data that is associated to the model nodes.\n\n\n\nClick the “Time Series” button of the iMOD plugin.\n\n\n\n\n\nSelect the variables that you want to plot.\n\n\n\n\n\nClick “Select points” and select a node by dragging a rectangle around it on the map. Hold the Ctrl key to select multiple nodes. Currently only the Basin nodes can be plotted.\n\n\n\n\n\nThe associated time series are shown the the graph." + }, { "objectID": "build/index.html#modules", "href": "build/index.html#modules", @@ -42,158 +182,123 @@ "text": "1.6 Index\n\nRibasim.Ribasim\nRibasim.config\nRibasim.config.algorithms\nRibasim.AllocationModel\nRibasim.AllocationModel\nRibasim.Basin\nRibasim.Connectivity\nRibasim.DiscreteControl\nRibasim.FlatVector\nRibasim.FlowBoundary\nRibasim.FractionalFlow\nRibasim.LevelBoundary\nRibasim.LinearResistance\nRibasim.ManningResistance\nRibasim.Model\nRibasim.Outlet\nRibasim.PidControl\nRibasim.Pump\nRibasim.TabulatedRatingCurve\nRibasim.Terminal\nRibasim.User\nRibasim.config.Config\nBasicModelInterface.finalize\nBasicModelInterface.initialize\nBasicModelInterface.initialize\nCommonSolve.solve!\nRibasim.add_constraints_basin_allocation!\nRibasim.add_constraints_capacity!\nRibasim.add_constraints_flow_conservation!\nRibasim.add_constraints_source!\nRibasim.add_constraints_user_allocation!\nRibasim.add_constraints_user_returnflow!\nRibasim.add_objective_function!\nRibasim.add_variables_allocation_basin!\nRibasim.add_variables_allocation_user!\nRibasim.add_variables_flow!\nRibasim.allocate!\nRibasim.allocation_graph\nRibasim.allocation_problem\nRibasim.assign_allocations!\nRibasim.avoid_using_own_returnflow!\nRibasim.basin_bottom\nRibasim.basin_bottoms\nRibasim.basin_table\nRibasim.config.algorithm\nRibasim.config.snake_case\nRibasim.create_callbacks\nRibasim.create_graph\nRibasim.create_storage_tables\nRibasim.datetime_since\nRibasim.datetimes\nRibasim.discrete_control_affect!\nRibasim.discrete_control_affect_downcrossing!\nRibasim.discrete_control_affect_upcrossing!\nRibasim.discrete_control_condition\nRibasim.discrete_control_table\nRibasim.expand_logic_mapping\nRibasim.find_allocation_graph_edges!\nRibasim.findlastgroup\nRibasim.findsorted\nRibasim.flow_table\nRibasim.formulate_basins!\nRibasim.formulate_flow!\nRibasim.formulate_flow!\nRibasim.formulate_flow!\nRibasim.get_area_and_level\nRibasim.get_compressor\nRibasim.get_fractional_flow_connected_basins\nRibasim.get_jac_prototype\nRibasim.get_level\nRibasim.get_node_id_mapping\nRibasim.get_node_in_out_edges\nRibasim.get_scalar_interpolation\nRibasim.get_storage_from_level\nRibasim.get_storages_and_levels\nRibasim.get_storages_from_levels\nRibasim.get_tstops\nRibasim.get_value\nRibasim.id_index\nRibasim.input_path\nRibasim.is_flow_constraining\nRibasim.is_flow_direction_constraining\nRibasim.load_data\nRibasim.load_structvector\nRibasim.nodefields\nRibasim.nodetype\nRibasim.parse_static_and_time\nRibasim.path_exists_in_graph\nRibasim.process_allocation_graph_edges!\nRibasim.profile_storage\nRibasim.qh_interpolation\nRibasim.reduction_factor\nRibasim.results_path\nRibasim.run\nRibasim.save_flow\nRibasim.scalar_interpolation_derivative\nRibasim.seconds_since\nRibasim.set_current_value!\nRibasim.set_model_state_in_allocation!\nRibasim.set_static_value!\nRibasim.set_table_row!\nRibasim.sorted_table!\nRibasim.timesteps\nRibasim.update_basin\nRibasim.update_jac_prototype!\nRibasim.update_jac_prototype!\nRibasim.update_jac_prototype!\nRibasim.update_jac_prototype!\nRibasim.update_tabulated_rating_curve!\nRibasim.valid_discrete_control\nRibasim.valid_edge_types\nRibasim.valid_edges\nRibasim.valid_flow_rates\nRibasim.valid_fractional_flow\nRibasim.valid_n_neighbors\nRibasim.valid_profiles\nRibasim.valid_sources\nRibasim.water_balance!\nRibasim.write_arrow\nRibasim.config.@addfields\nRibasim.config.@addnodetypes" }, { - "objectID": "python/reference/LevelBoundary.html", - "href": "python/reference/LevelBoundary.html", - "title": "1 LevelBoundary", + "objectID": "contribute/release.html", + "href": "contribute/release.html", + "title": "Release process", "section": "", - "text": "LevelBoundary()\nStores water at a given level unaffected by flow, like an infinitely large basin.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable with the constant water levels.\nrequired" + "text": "The Ribasim repository contains several components, e.g., the Julia core, the Python tooling and QGIS plugin. The components are currently only guaranteed to work together if they are built at the same time. Therefore we release Ribasim as a collection of all the components at once. For maximum interoperability it is suggested to only release all components together, and not individually.\nFor these releases we use Calender Versioning, which makes it clear in which month the release was made." }, { - "objectID": "python/reference/LevelBoundary.html#parameters", - "href": "python/reference/LevelBoundary.html#parameters", - "title": "1 LevelBoundary", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable with the constant water levels.\nrequired" + "objectID": "contribute/release.html#pre-release-checks", + "href": "contribute/release.html#pre-release-checks", + "title": "Release process", + "section": "2.1 Pre-release checks", + "text": "2.1 Pre-release checks\nBefore starting the release process, ensure that all tests are passing and that all features intended for the release are complete and merged into the main branch." }, { - "objectID": "python/reference/TabulatedRatingCurve.html", - "href": "python/reference/TabulatedRatingCurve.html", - "title": "1 TabulatedRatingCurve", - "section": "", - "text": "TabulatedRatingCurve()\nLinearly interpolates discharge between a tabulation of level and discharge.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with constant rating curves.\nrequired\n\n\ntime\npandas.DataFrame\nTable with time-varying rating curves.\nrequired" + "objectID": "contribute/release.html#update-version-numbers-of-the-components-as-needed", + "href": "contribute/release.html#update-version-numbers-of-the-components-as-needed", + "title": "Release process", + "section": "2.2 Update version numbers of the components as needed", + "text": "2.2 Update version numbers of the components as needed\nThe components have their own version number which generally uses Semantic Versioning, with minor version signifying a breaking release for pre-1.0 versions, as documented here. If a component did not change at all between releases, the version number can stay the same.\nNow submit a pull request which updates the version numbers of the components as needed. You can use PR #623 as an example.\nIn general for Python packages the version number is in __init__.py, for Julia it is Project.toml, and for QGIS metadata.txt" }, { - "objectID": "python/reference/TabulatedRatingCurve.html#parameters", - "href": "python/reference/TabulatedRatingCurve.html#parameters", - "title": "1 TabulatedRatingCurve", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with constant rating curves.\nrequired\n\n\ntime\npandas.DataFrame\nTable with time-varying rating curves.\nrequired" + "objectID": "contribute/release.html#sec-wheel-links", + "href": "contribute/release.html#sec-wheel-links", + "title": "Release process", + "section": "2.3 Update the wheel links", + "text": "2.3 Update the wheel links\nThe nightly download links for the Ribasim Python wheels contain the version number. Search for “any.whl” and update these to the new version number of Ribasim Python." }, { - "objectID": "python/reference/Edge.html", - "href": "python/reference/Edge.html", - "title": "1 Edge", - "section": "", - "text": "Edge()\nDefines the connections between nodes.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable describing the flow connections.\nrequired\n\n\n\n\n\n\n\n\n\nName\nDescription\n\n\n\n\nwrite_layer\nWrite the contents of the input to a database.\n\n\n\n\n\nEdge.write_layer(path)\nWrite the contents of the input to a database.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\n\nrequired" + "objectID": "contribute/release.html#create-a-new-release", + "href": "contribute/release.html#create-a-new-release", + "title": "Release process", + "section": "2.4 Create a new release", + "text": "2.4 Create a new release\nCreate a new release. Give it a tag like v2023.08.0, filling in the current year, month and a sequential “MICRO” number. This follows vYYYY.0M.MICRO from calver. For v2023.09.0 I used the “Generate release notes” button, which I then manually edited to copy the most important changes for users to the top in the form of Keep a Changelog. The possibly long list of generated release notes can put below an “All changes” collapsed item as such:\n<details>\n<summary>\nAll changes\n</summary>\n\n# Put Github flavored markdown here\n\n</details>" }, { - "objectID": "python/reference/Edge.html#parameters", - "href": "python/reference/Edge.html#parameters", - "title": "1 Edge", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable describing the flow connections.\nrequired" + "objectID": "contribute/release.html#release-ribasim-python-to-pypi", + "href": "contribute/release.html#release-ribasim-python-to-pypi", + "title": "Release process", + "section": "2.5 Release Ribasim Python to PyPI", + "text": "2.5 Release Ribasim Python to PyPI\nTo be able to do pip install ribasim, Ribasim Python needs to be released on the Python Package Index, see these instructions" }, { - "objectID": "python/reference/Edge.html#methods", - "href": "python/reference/Edge.html#methods", - "title": "1 Edge", - "section": "", - "text": "Name\nDescription\n\n\n\n\nwrite_layer\nWrite the contents of the input to a database.\n\n\n\n\n\nEdge.write_layer(path)\nWrite the contents of the input to a database.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\n\nrequired" + "objectID": "contribute/release.html#sec-teamcity", + "href": "contribute/release.html#sec-teamcity", + "title": "Release process", + "section": "2.6 Wait for TeamCity to build the new release", + "text": "2.6 Wait for TeamCity to build the new release\nCurrently TeamCity is set to build a release at the night after it has been tagged.\nIf this succeeds, the release assets are uploaded to an S3 link with the version number in the URL, as show here:\nhttps://ribasim.s3.eu-west-3.amazonaws.com/teamcity/Ribasim_Ribasim/BuildRibasimCliWindows/v2023.07.0/ribasim_cli.zip\nhttps://ribasim.s3.eu-west-3.amazonaws.com/teamcity/Ribasim_Ribasim/BuildRibasimCliWindows/v2023.07.0/ribasim-0.4.0-py3-none-any.whl\nhttps://ribasim.s3.eu-west-3.amazonaws.com/teamcity/Ribasim_Ribasim/BuildRibasimCliWindows/v2023.07.0/ribasim_qgis.zip\n\n\n\n\n\n\nNote\n\n\n\nA non-existent version number v2023.07.0 is used in these links. Replace with the version number of the new release. Similarly the filename of the Ribasim Python wheel needs to be updated as in Section 2.3." }, { - "objectID": "python/reference/utils.connectivity_from_geometry.html", - "href": "python/reference/utils.connectivity_from_geometry.html", - "title": "1 utils.connectivity_from_geometry", - "section": "", - "text": "utils.connectivity_from_geometry(node, lines)\nDerive from_node_id and to_node_id for every edge in lines. LineStrings may be used to connect multiple nodes in a sequence, but every linestring vertex must also a node.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nnode\nNode\n\nrequired\n\n\nlines\nnp.ndarray\nArray of shapely linestrings.\nrequired\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nnp.ndarray of int\n\n\n\nnp.ndarray of int" + "objectID": "contribute/release.html#do-manual-checks", + "href": "contribute/release.html#do-manual-checks", + "title": "Release process", + "section": "2.7 Do manual checks", + "text": "2.7 Do manual checks\nOur continuous integration (CI) should have caught most issues. A current weak spot in our testing is the QGIS plugin, so it is a good idea to do some manual checks to see if it works properly. It is a good idea to load new test models if there are any, or test any other changed functionality." }, { - "objectID": "python/reference/utils.connectivity_from_geometry.html#parameters", - "href": "python/reference/utils.connectivity_from_geometry.html#parameters", - "title": "1 utils.connectivity_from_geometry", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nnode\nNode\n\nrequired\n\n\nlines\nnp.ndarray\nArray of shapely linestrings.\nrequired" + "objectID": "contribute/release.html#generate-and-upload-test-models", + "href": "contribute/release.html#generate-and-upload-test-models", + "title": "Release process", + "section": "2.8 Generate and upload test models", + "text": "2.8 Generate and upload test models\nThe test models are currently not automatically uploaded. Create them locally with:\npixi run generate-testmodels\nNote that this only includes the test model data, no results. And zip the generated_testmodels directory to generated_testmodels.zip, and add these to the release assets. Click the edit pencil icon to be able to upload it." }, { - "objectID": "python/reference/utils.connectivity_from_geometry.html#returns", - "href": "python/reference/utils.connectivity_from_geometry.html#returns", - "title": "1 utils.connectivity_from_geometry", - "section": "", - "text": "Type\nDescription\n\n\n\n\nnp.ndarray of int\n\n\n\nnp.ndarray of int" + "objectID": "contribute/release.html#upload-artifacts-from-s3-to-github-release-assets", + "href": "contribute/release.html#upload-artifacts-from-s3-to-github-release-assets", + "title": "Release process", + "section": "2.9 Upload artifacts from S3 to GitHub release assets", + "text": "2.9 Upload artifacts from S3 to GitHub release assets\nAgain edit the release assets. Now upload the files downloaded from S3 as mentioned in Section 2.6." }, { - "objectID": "python/reference/ManningResistance.html", - "href": "python/reference/ManningResistance.html", - "title": "1 ManningResistance", - "section": "", - "text": "ManningResistance()\nFlow through this connection is estimated by conservation of energy and the Manning-Gauckler formula to estimate friction losses.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with the constant Manning parameters.\nrequired" + "objectID": "contribute/release.html#announce-release", + "href": "contribute/release.html#announce-release", + "title": "Release process", + "section": "2.10 Announce release", + "text": "2.10 Announce release\nAnnounce the release in appropriate channels. Include a link to the release notes and assets, which is whatever this resolves to at that time. Also include a link to the documentation." }, { - "objectID": "python/reference/ManningResistance.html#parameters", - "href": "python/reference/ManningResistance.html#parameters", - "title": "1 ManningResistance", + "objectID": "contribute/addnode.html", + "href": "contribute/addnode.html", + "title": "Adding node types", "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with the constant Manning parameters.\nrequired" + "text": "Several parts of the code have to be made aware of the new node type. In the rest of this page we shall call our new node type NewNodeType." }, { - "objectID": "python/reference/utils.geometry_from_connectivity.html", - "href": "python/reference/utils.geometry_from_connectivity.html", - "title": "1 utils.geometry_from_connectivity", - "section": "", - "text": "utils.geometry_from_connectivity(node, from_id, to_id)\nCreate edge shapely geometries from connectivities.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nnode\nRibasim.Node\n\nrequired\n\n\nfrom_id\nSequence[int]\nFirst node of every edge.\nrequired\n\n\nto_id\nSequence[int]\nSecond node of every edge.\nrequired\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nnp.ndarray\nArray of shapely LineStrings." - }, - { - "objectID": "python/reference/utils.geometry_from_connectivity.html#parameters", - "href": "python/reference/utils.geometry_from_connectivity.html#parameters", - "title": "1 utils.geometry_from_connectivity", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nnode\nRibasim.Node\n\nrequired\n\n\nfrom_id\nSequence[int]\nFirst node of every edge.\nrequired\n\n\nto_id\nSequence[int]\nSecond node of every edge.\nrequired" - }, - { - "objectID": "python/reference/utils.geometry_from_connectivity.html#returns", - "href": "python/reference/utils.geometry_from_connectivity.html#returns", - "title": "1 utils.geometry_from_connectivity", - "section": "", - "text": "Type\nDescription\n\n\n\n\nnp.ndarray\nArray of shapely LineStrings." - }, - { - "objectID": "python/reference/Model.html", - "href": "python/reference/Model.html", - "title": "1 Model", - "section": "", - "text": "Model()\nA full Ribasim model schematisation with all input.\nRibasim model containing the location of the nodes, the edges between the nodes, and the node parametrization.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nnode\nNode\nThe ID, type and geometry of each node.\nrequired\n\n\nedge\nEdge\nHow the nodes are connected.\nrequired\n\n\nbasin\nBasin\nThe waterbodies.\nrequired\n\n\nfractional_flow\nOptional[FractionalFlow]\nSplit flows into fractions.\nrequired\n\n\nlevel_boundary\nOptional[LevelBoundary]\nBoundary condition specifying the water level.\nrequired\n\n\nflow_boundary\nOptional[FlowBoundary]\nBoundary conditions specifying the flow.\nrequired\n\n\nlinear_resistance\n\nLinear flow resistance.\nrequired\n\n\nmanning_resistance\nOptional[ManningResistance]\nFlow resistance based on the Manning formula.\nrequired\n\n\ntabulated_rating_curve\nOptional[TabulatedRatingCurve]\nTabulated rating curve describing flow based on the upstream water level.\nrequired\n\n\npump\nOptional[Pump]\nPrescribed flow rate from one basin to the other.\nrequired\n\n\noutlet\nOptional[Outlet]\nPrescribed flow rate from one basin to the other.\nrequired\n\n\nterminal\nOptional[Terminal]\nWater sink without state or properties.\nrequired\n\n\ndiscrete_control\nOptional[DiscreteControl]\nDiscrete control logic.\nrequired\n\n\npid_control\nOptional[PidControl]\nPID controller attempting to set the level of a basin to a desired value using a pump/outlet.\nrequired\n\n\nuser\nOptional[User]\nUser node type with demand and priority.\nrequired\n\n\nstarttime\nUnion[str, datetime.datetime]\nStarting time of the simulation.\nrequired\n\n\nendtime\nUnion[str, datetime.datetime]\nEnd time of the simulation.\nrequired\n\n\nsolver\nOptional[Solver]\nSolver settings.\nrequired\n\n\nlogging\nOptional[logging]\nLogging settings.\nrequired\n\n\n\n\n\n\n\n\n\nName\nDescription\n\n\n\n\nfields\nReturn the names of the fields contained in the Model.\n\n\nfrom_toml\nInitialize a model from the TOML configuration file.\n\n\nplot\nPlot the nodes and edges of the model.\n\n\nsort\nSort all input tables as required.\n\n\nvalidate_model\nValidate the model.\n\n\nvalidate_model_node_IDs\nCheck whether the node IDs in the node field correspond to the node IDs on the node type fields.\n\n\nvalidate_model_node_field_IDs\nCheck whether the node IDs of the node_type fields are valid.\n\n\nvalidate_model_node_types\nCheck whether all node types in the node field are valid.\n\n\nwrite\nWrite the contents of the model to a database and a TOML configuration file.\n\n\n\n\n\nModel.fields()\nReturn the names of the fields contained in the Model.\n\n\n\nModel.from_toml(path)\nInitialize a model from the TOML configuration file.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\nPath to the configuration TOML file.\nrequired\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nModel\n\n\n\n\n\n\n\n\nModel.plot(ax=None)\nPlot the nodes and edges of the model.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nax\nmatplotlib.pyplot.Artist\nAxes on which to draw the plot.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nmatplotlib.pyplot.Artist\n\n\n\n\n\n\n\n\nModel.sort()\nSort all input tables as required.\nTables are sorted by “node_id”, unless otherwise specified. Sorting is done automatically before writing the table.\n\n\n\nModel.validate_model()\nValidate the model.\nChecks: - Whether all node types in the node field are valid - Whether the node IDs of the node_type fields are valid - Whether the node IDs in the node field correspond to the node IDs on the node type fields\n\n\n\nModel.validate_model_node_IDs()\nCheck whether the node IDs in the node field correspond to the node IDs on the node type fields.\n\n\n\nModel.validate_model_node_field_IDs()\nCheck whether the node IDs of the node_type fields are valid.\n\n\n\nModel.validate_model_node_types()\nCheck whether all node types in the node field are valid.\n\n\n\nModel.write(directory)\nWrite the contents of the model to a database and a TOML configuration file.\nIf directory does not exist, it is created before writing.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\ndirectory\nFilePath\n\nrequired" - }, - { - "objectID": "python/reference/Model.html#parameters", - "href": "python/reference/Model.html#parameters", - "title": "1 Model", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nnode\nNode\nThe ID, type and geometry of each node.\nrequired\n\n\nedge\nEdge\nHow the nodes are connected.\nrequired\n\n\nbasin\nBasin\nThe waterbodies.\nrequired\n\n\nfractional_flow\nOptional[FractionalFlow]\nSplit flows into fractions.\nrequired\n\n\nlevel_boundary\nOptional[LevelBoundary]\nBoundary condition specifying the water level.\nrequired\n\n\nflow_boundary\nOptional[FlowBoundary]\nBoundary conditions specifying the flow.\nrequired\n\n\nlinear_resistance\n\nLinear flow resistance.\nrequired\n\n\nmanning_resistance\nOptional[ManningResistance]\nFlow resistance based on the Manning formula.\nrequired\n\n\ntabulated_rating_curve\nOptional[TabulatedRatingCurve]\nTabulated rating curve describing flow based on the upstream water level.\nrequired\n\n\npump\nOptional[Pump]\nPrescribed flow rate from one basin to the other.\nrequired\n\n\noutlet\nOptional[Outlet]\nPrescribed flow rate from one basin to the other.\nrequired\n\n\nterminal\nOptional[Terminal]\nWater sink without state or properties.\nrequired\n\n\ndiscrete_control\nOptional[DiscreteControl]\nDiscrete control logic.\nrequired\n\n\npid_control\nOptional[PidControl]\nPID controller attempting to set the level of a basin to a desired value using a pump/outlet.\nrequired\n\n\nuser\nOptional[User]\nUser node type with demand and priority.\nrequired\n\n\nstarttime\nUnion[str, datetime.datetime]\nStarting time of the simulation.\nrequired\n\n\nendtime\nUnion[str, datetime.datetime]\nEnd time of the simulation.\nrequired\n\n\nsolver\nOptional[Solver]\nSolver settings.\nrequired\n\n\nlogging\nOptional[logging]\nLogging settings.\nrequired" - }, - { - "objectID": "python/reference/Model.html#methods", - "href": "python/reference/Model.html#methods", - "title": "1 Model", - "section": "", - "text": "Name\nDescription\n\n\n\n\nfields\nReturn the names of the fields contained in the Model.\n\n\nfrom_toml\nInitialize a model from the TOML configuration file.\n\n\nplot\nPlot the nodes and edges of the model.\n\n\nsort\nSort all input tables as required.\n\n\nvalidate_model\nValidate the model.\n\n\nvalidate_model_node_IDs\nCheck whether the node IDs in the node field correspond to the node IDs on the node type fields.\n\n\nvalidate_model_node_field_IDs\nCheck whether the node IDs of the node_type fields are valid.\n\n\nvalidate_model_node_types\nCheck whether all node types in the node field are valid.\n\n\nwrite\nWrite the contents of the model to a database and a TOML configuration file.\n\n\n\n\n\nModel.fields()\nReturn the names of the fields contained in the Model.\n\n\n\nModel.from_toml(path)\nInitialize a model from the TOML configuration file.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\nPath to the configuration TOML file.\nrequired\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nModel\n\n\n\n\n\n\n\n\nModel.plot(ax=None)\nPlot the nodes and edges of the model.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nax\nmatplotlib.pyplot.Artist\nAxes on which to draw the plot.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nmatplotlib.pyplot.Artist\n\n\n\n\n\n\n\n\nModel.sort()\nSort all input tables as required.\nTables are sorted by “node_id”, unless otherwise specified. Sorting is done automatically before writing the table.\n\n\n\nModel.validate_model()\nValidate the model.\nChecks: - Whether all node types in the node field are valid - Whether the node IDs of the node_type fields are valid - Whether the node IDs in the node field correspond to the node IDs on the node type fields\n\n\n\nModel.validate_model_node_IDs()\nCheck whether the node IDs in the node field correspond to the node IDs on the node type fields.\n\n\n\nModel.validate_model_node_field_IDs()\nCheck whether the node IDs of the node_type fields are valid.\n\n\n\nModel.validate_model_node_types()\nCheck whether all node types in the node field are valid.\n\n\n\nModel.write(directory)\nWrite the contents of the model to a database and a TOML configuration file.\nIf directory does not exist, it is created before writing.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\ndirectory\nFilePath\n\nrequired" + "objectID": "contribute/addnode.html#parameters", + "href": "contribute/addnode.html#parameters", + "title": "Adding node types", + "section": "1.1 Parameters", + "text": "1.1 Parameters\nThe parameters object (defined in solve.jl) passed to the ODE solver must be made aware of the new node type. Therefore define a struct in solve.jl which holds the data for each node of the new node type:\nstruct NewNodeType\n node_id::Vector{Int}\n # Other fields\nend\nThese fields do not have to correspond 1:1 with the input tables (see below). The vector with all node IDs that are of the new type in a given model is a mandatory field. Now you can:\n\nAdd new_node_type::NewNodeType to the Parameters object;\nAdd new_node_type = NewNodeType(db,config) to the function Parameters in create.jl and add new_node_type at the proper location in the Parameters constructor call." }, { - "objectID": "index.html", - "href": "index.html", - "title": "Ribasim", - "section": "", - "text": "Ribasim is a water resources model, designed to be the replacement of the regional surface water modules Mozart and SIMRES in the Netherlands Hydrological Instrument (NHI). Ribasim is a work in progress, it is a prototype that demonstrates all essential functionalities. Further development of the prototype in a software release is planned in 2022 and 2023.\nRibasim is written in the Julia programming language and is built on top of the SciML: Open Source Software for Scientific Machine Learning libraries, notably DifferentialEquations.jl." + "objectID": "contribute/addnode.html#reading-from-configuration", + "href": "contribute/addnode.html#reading-from-configuration", + "title": "Adding node types", + "section": "1.2 Reading from configuration", + "text": "1.2 Reading from configuration\nThere can be several schemas associated with a single node type. To define a schema for the new node type, add the following to validation.jl:\n@schema \"ribasim.newnodetype.static\" NewNodeTypeStatic\n\n\"\"\"\nnode_id: node ID of the NewNodeType node\n\"\"\"\n@version NewNodeTypeStaticV1 begin\n node_id::Int\n # Other fields\nend\nHere Static refers to data that does not change over time. For naming conventions of these schemas see Node usage.\nvalidation.jl also deals with checking and applying a specific sorting order for the tabular data (default is sorting by node ID only), see sort_by_function and sorted_table!.\nNow we define the function that is called in the second bullet above, in create.jl:\nfunction NewNodeType(db::DB, config::Config)::NewNodeType\n static = load_structvector(db, config, NewNodeTypeStaticV1)\n defaults = (; foo = 1, bar = false)\n # Process potential control states in the static data\n parsed_parameters, valid = parse_static_and_time(db, config, \"Outlet\"; static, defaults)\n\n if !valid\n error(\"Errors occurred when parsing NewNodeType data.\")\n end\n\n # Unpack the fields of static as inputs for the NewNodeType constructor\n return NewNodeType(\n parsed_parameters.node_id,\n parsed_parameters.some_property,\n parsed_parameters.control_mapping)\nend" }, { - "objectID": "index.html#water-balance-equations", - "href": "index.html#water-balance-equations", - "title": "Ribasim", - "section": "3.1 Water balance equations", - "text": "3.1 Water balance equations\nThe water balance equation for a drainage basin (Wikipedia contributors 2022) can be defined by a first-order ordinary differential equation (ODE), where the change of the storage \\(S\\) over time is determined by the inflow fluxes minus the outflow fluxes.\n\\[\n\\frac{\\mathrm{d}S}{\\mathrm{d}t} = Q_{in} - Q_{out}\n\\]\nWe can split out the fluxes into separate terms, such as precipitation \\(P\\), evapotranspiration \\(ET\\) and runoff \\(R\\). For now other fluxes are combined into \\(Q_{rest}\\). If we define all fluxes entering our reservoir as positive, and those leaving the system as negative, all fluxes can be summed up.\n\\[\n\\frac{\\mathrm{d}S}{\\mathrm{d}t} = R + P + ET + Q_{rest}\n\\]" + "objectID": "contribute/addnode.html#node-behavior", + "href": "contribute/addnode.html#node-behavior", + "title": "Adding node types", + "section": "1.3 Node behavior", + "text": "1.3 Node behavior\nIn general if the new node type dictates flow, the behaviour of the new node in the Ribasim core is defined in a method of the formulate_flow! function, which is called within the water_balance! (both in solve.jl) function being the right hand side of the system of differential equations solved by Ribasim. Here the details depend highly on the specifics of the node type. An example structure of a formulate_flow! method is given below.\nfunction formulate_flow!(new_node_type::NewNodeType, p::Parameters)::Nothing\n # Retrieve relevant parameters\n (; connectivity) = p\n (; flow) = connectivity\n (; node_id, param_1, param_2) = new_node_type\n\n # Loop over nodes of NewNodeType\n for (i, id) in enumerate(node_id)\n # compute e.g. flow based on param_1[i], param_2[i]\n end\n\n return nothing\nend\nIf the new node type is non-conservative, meaning it either adds or removes water from the model, these boundary flows also need to be recorded. This is done by storing it on the diagonal of the flow[from, to] matrix, e.g. flow[id, id] = q, where q is positive for water added to the model. Non-conservative node types need to be added to the nonconservative_nodetypes set such that this diagonal is set to a nonzero on creating the flow sparse matrix in the Connectivity constructor." }, { - "objectID": "index.html#time", - "href": "index.html#time", - "title": "Ribasim", - "section": "3.2 Time", - "text": "3.2 Time\nThe water balance equation can be applied on many timescales; years, weeks, days or hours. Depending on the application and available data any of these can be the best choice. In Ribasim, we make use of DifferentialEquations.jl and its ODE solvers. Many of these solvers are based on adaptive time stepping, which means the solver will decide how large the time steps can be depending on the state of the system.\nThe forcing, like precipitation, is generally provided as a time series. Ribasim is set up to support unevenly spaced timeseries. The solver will stop on timestamps where new forcing values are available, so they can be loaded as the new value.\nRibasim is essentially a continuous model, rather than daily or hourly. If you want to use hourly forcing, you only need to make sure that your forcing data contains hourly updates. The output frequency can be configured independently. To be able to write a closed water balance, we accumulate the fluxes. This way any variations in between timesteps are also included, and we can output in m³ rather than m³s⁻¹." + "objectID": "contribute/addnode.html#the-jacobian", + "href": "contribute/addnode.html#the-jacobian", + "title": "Adding node types", + "section": "1.4 The Jacobian", + "text": "1.4 The Jacobian\nSee Equations for a mathematical description of the Jacobian.\nBefore the Julia core runs its simulation, the sparsity structure jac_prototype of \\(J\\) is determined with get_jac_prototype in utils.jl. This function runs trough all node types and looks for nodes that create dependencies between states. It creates a sparse matrix of zeros and ones, where the ones denote locations of possible non-zeros in \\(J\\).\nWe divide the various node types in groups based on what type of state dependencies they yield, and these groups are discussed below. Each group has its own method update_jac_prototype! in utils.jl for the sparsity structure induced by nodes of that group. NewNodeType should be added to the signature of one these methods, or to the list of node types that do not contribute to the Jacobian in the method of update_jac_prototype! whose signature contains node::AbstractParameterNode. Of course it is also possible that a new method of update_jac_prototype! has to be introduced.\nThe current dependency groups are:\n\nOut-neighbor dependencies: examples are TabulatedRatingCurve, Pump (the latter only in the reduction factor regime and not PID controlled). If the in-neighbor of a node of this group is a basin, then the storage of this basin affects itself and the storage of the outneighbor (or the basin one node further if it is connected with a FractionalFlow in between) if that is also a basin;\nEither-neighbor dependencies: examples are LinearResistance, ManningResistance. If either the in-neighbor or out-neighbor of a node of this group is a basin, the storage of this basin depends on itself. If both the in-neighbor and the out-neighbor are basins, their storages also depend on eachother.\nThe PidControl node is a special case which is discussed in equations.\n\nUsing jac_prototype the Jacobian of water_balance! is computed automatically using ForwardDiff.jl with memory management provided by PreallocationTools.jl. These computations make use of DiffCache and dual numbers." }, { - "objectID": "index.html#sec-space", - "href": "index.html#sec-space", - "title": "Ribasim", - "section": "3.3 Space", - "text": "3.3 Space\nThe water balance equation can be applied on different spatial scales. Besides modelling a single lumped watershed, it allows you to divide the area into a network of connected representative elementary watersheds (REWs) (Reggiani, Sivapalan, and Majid Hassanizadeh 1998). At this scale global water balance laws can be formulated by means of integration of point-scale conservation equations over control volumes. Such an approach makes Ribasim a semi-distributed model. In this document we typically use the term “basin” to refer to the REW. (In Mozart the spatial unit was called Local Surface Water (LSW)). Each basin has an associated polygon, and the set of basins is connected to each other as described by a graph, which we call the network. Below is a representation of both on the map.\n\n\n\nMozart Local Surface Water polygons and their drainage.\n\n\nThe network is described as graph. Flow can be bi-directional, and the graph does not have to be acyclic.\n\n\n\n\ngraph LR;\n A[\"basin A\"] --- B[\"basin B\"];\n A --- C[\"basin C\"];\n B --- D[\"basin D\"];\n C --- D;\n\n\n\n\n\nInternally a directed graph is used. The direction is defined to be the positive flow direction, and is generally set in the dominant flow direction. The basins are the nodes of the network graph. Basin states and properties such storage volume and wetted area are associated with the nodes (A, B, C, D), as are most forcing data such as precipitation, evaporation, or water demand. Basin connection properties and interbasin flows are associated with the edges (the lines between A, B, C, and D) instead.\nMultiple basins may exist within the same spatial polygon, representing different aspects of the surface water system (perennial ditches, ephemeral ditches, or even surface ponding). Figure 1, Figure 2, Figure 3 show the 25.0 m rasterized primary, secondary, and tertiary surface waters as identified by BRT TOP10NL (PDOK 2022) in the Hupsel basin (as defined in the Mozart LSW’s). These systems may represented in multiple ways.\n\n\n\nFigure 1: Hupsel: primary surface water.\n\n\n\n\n\nFigure 2: Hupsel: secondary surface water.\n\n\n\n\n\nFigure 3: Hupsel: tertiary surface water.\n\n\nAs a single basin (A) containing all surface water, discharging to its downstream basin to the west (B):\n\n\n\n\ngraph LR;\n A[\"basin A\"] --> B[\"basin B\"];\n\n\n\n\n\nSuch a system may be capable of representing discharge, but it cannot represent residence times or differences in solute concentrations: within a single basin, drop of water is mixed instantaneously. Instead, we may the group primary (P), secondary (S), and tertiary (T) surface waters. Then T may flow into S, S into P, and P discharges to the downstream basin (B.)\n\n\n\n\ngraph LR;\n T[\"basin T\"] --> S[\"basin S\"];\n S --> P[\"basin P\"];\n P --> B[\"basin B\"];\n\n\n\n\n\nAs each (sub)basin has its own volume, low throughput (high volume, low discharge, long residence time) and high throughput (low volume, high discharge, short residence time) systems can be represented in a lumped manner; of course, more detail requires more parameters." + "objectID": "contribute/addnode.html#python-class", + "href": "contribute/addnode.html#python-class", + "title": "Adding node types", + "section": "2.1 Python class", + "text": "2.1 Python class\nCreate a new file python/ribasim/ribasim/node_types/new_node_type.py which is structured as follows:\nfrom typing import Optional\n\nimport pandera as pa\nfrom pandera.engines.pandas_engine import PydanticModel\nfrom pandera.typing import DataFrame\n\nfrom ribasim import models\nfrom ribasim.input_base import TableModel\n\n__all__ = (\"NewNodeType\",)\n\nclass StaticSchema(pa.SchemaModel):\n class Config:\n \"\"\"Config with dataframe-level data type.\"\"\"\n\n dtype = PydanticModel(models.NewNodeTypeStatic)\n\n# Possible other schemas\n\n\nclass NewNodeType(TableModel):\n \"\"\"\n Description of this node type.\n\n Parameters\n ----------\n static: pandas.DataFrame\n table with data for this node type.\n\n possible other schemas\n \"\"\"\n\n static: Optional[DataFrame[StaticSchema]] = None\n # possible other schemas\n\n class Config:\n validate_assignment = True\n\n def sort(self):\n self.static.sort_values(\"node_id\", ignore_index=True, inplace=True)\nThe sort method should implement the same sorting as in validation.jl.\nNow in both python/ribasim/ribasim/__init__.py and python/ribasim/ribasim/node_types/__init__.py add\n\nfrom ribasim.node_types.new_node_type import NewNodeType;\n\"NewNodeType\" to __all__.\n\nIn python/ribasim/ribasim/model.py, add\n\nfrom ribasim.new_node_type import NewNodeType;\nnew_node_type as a parameter and in the docstring of the Model class.\n\nIn python/ribasim/ribasim/geometry/node.py add a color and shape description in the MARKERS and COLORS dictionaries." }, { "objectID": "couple/modflow.html", @@ -245,263 +350,298 @@ "text": "3.1 Parametrization\nIn coupling Ribasim to MODFLOW 6, relations translating the Ribasim volume must be given for every every cell of every boundary condition. These consist of piecewise linear relationships between the basin volume and its associated water level for the boundary condition in the cell.\nThese values are stored in a netCDF dataset. This dataset must meet the following requirements:\n\nIt must contain a x and y coordinate. The extent and cell size of these coordinates must match the domain of the coupled MODFLOW 6 model exactly.\nIt must contain a variable (x, y) denoting the basin IDs.\nIt must contain a volume-level variable (x, y, row, column) for every coupled MODFLOW 6 boundary condition, describing the volume-level lookup table per cell.\n\n\n\n\n\n\n\nNote\n\n\n\nThe x and y coordinates are valid for structured MODFLOW 6 models (DIS). Discretized-by-vertices (DISV) and fully unstructured discretization (DISU). are not yet supported, but require no fundamental changes: one basin is connected to multiple MODFLOW 6 cells, and the coupling parameters must match the (structured, unstructured) grid of the MODFLOW 6 model exactly.\n\n\nThe MODFLOW 6 coupling example cases show examples of such a parametrization." }, { - "objectID": "core/index.html", - "href": "core/index.html", - "title": "Julia core", + "objectID": "couple/index.html", + "href": "couple/index.html", + "title": "Coupled models", "section": "", - "text": "With the term “core”, we mean the computational engine of Ribasim. As detailed in the usage documentation, it is generally used as a command line tool.\nThe theory is described on the equations page, and more in-depth numerical considerations are described on the numerical considerations page. As allocation is a large and self-contained part of the Ribasim core, it is described on the separate allocation page.\nThe core is implemented in the Julia programming language, and can be found in the Ribasim repository under the core/ folder. For developers we also advise to read the developer documentation." + "text": "Ribasim can be coupled to other software, for instance to model another process or domain, or to control a simulation from another process.\nTo enable this, Ribasim can be compiled as a shared library (libribasim) instead of a command line interface (ribasim). This shared library exposes a C API in the form of the Basic Model Interface (BMI). Other software can then load libribasim and load a Ribasim model, exchange data, and control the time stepping.\nAn initial coupling to MODFLOW 6 was done in 2022 inside the Julia core as a proof of concept. Read about the coupling setup and see the demonstration. Going forward this and other coupling codes will be implemented outside of the core, by making use of iMOD Coupler and libribasim. iMOD Coupler is a generic coupling tool, and can be used to couple to other models as well." }, { - "objectID": "core/usage.html", - "href": "core/usage.html", - "title": "Usage", + "objectID": "python/reference/LevelBoundary.html", + "href": "python/reference/LevelBoundary.html", + "title": "1 LevelBoundary", "section": "", - "text": "Ribasim is typically used as a command-line interface (CLI). It is distributed as a .zip archive, that must be downloaded and unpacked. It can be placed anywhere, however it is important that the contents of the zip file are kept together in a directory. The Ribasim CLI executable is in the bin directory.\nTo download ribasim_cli.zip, see the download section.\nTo check whether the installation was performed successfully, run ribasim with no arguments in the command line. This will give the following message:" - }, - { - "objectID": "core/usage.html#sec-solver-settings", - "href": "core/usage.html#sec-solver-settings", - "title": "Usage", - "section": "1.1 Solver settings", - "text": "1.1 Solver settings\nThe solver section in the configuration file is entirely optional, since we aim to use defaults that will generally work well. Common reasons to modify the solver settings are to adjust the calculation or result stepsizes: adaptive, dt, and saveat. If your model does not converge, or your performance is lower than expected, it can help to adjust other solver settings as well.\nThe default solver algorithm = \"QNDF\", which is a multistep method similar to Matlab’s ode15s (Shampine and Reichelt 1997). It is an implicit method that supports the default adaptive = true timestepping. The full list of available solvers is: QNDF, Rosenbrock23, TRBDF2, Rodas5, KenCarp4, Tsit5, RK4, ImplicitEuler, Euler. Information on the solver algorithms can be found on the ODE solvers page.\nThe dt controls the stepsize. When adaptive = true, dt only applies to the initial stepsize, and by default it is automatically determined. When adaptive = false a suitable dt must always be provided. The value is in seconds, so dt = 3600.0 corresponds to an hourly timestep. When adaptive = true, dtmin and dtmax control the minimum and maximum allowed dt. By default these depend on the problem and algorithm. If a smaller dt than dtmin is needed to meet the set error tolerances, the simulation stops, unless force_dtmin is set to true. force_dtmin is off by default to ensure an accurate solution.\nBy default the calculation and result stepsize are the same, with saveat = [], which will save every timestep. saveat can be a number, which is the saving interval in seconds, or it can be a list of numbers, which are the times in seconds since start that are saved. For instance, saveat = 86400.0 will save results after every day that passed.\nThe Jacobian matrix provides information about the local sensitivity of the model with respect to changes in the states. For implicit solvers it must be calculated often, which can be expensive to do. There are several methods to do this. By default Ribasim uses a Jacobian derived automatically using ForwardDiff.jl with memory management provided by PreallocationTools.jl. If this is not used by setting autodiff = false, the Jacobian is calculated with a finite difference method, which can be less accurate and more expensive.\nBy default the Jacobian matrix is a sparse matrix (sparse = true). Since each state typically only depends on a small number of other states, this is generally more efficient, especially for larger models. The sparsity structure is calculated from the network and provided as a Jacobian prototype to the solver. For small or highly connected models it could be faster to use a dense Jacobian matrix instead by setting sparse = false.\nThe total maximum number of iterations maxiters = 1e9, can normally stay as-is unless doing extremely long simulations.\nThe absolute and relative tolerance for adaptive timestepping can be set with abstol and reltol. For more information on these and other solver options, see the DifferentialEquations.jl docs." + "text": "LevelBoundary()\nStores water at a given level unaffected by flow, like an infinitely large basin.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable with the constant water levels.\nrequired" }, { - "objectID": "core/usage.html#basin-time", - "href": "core/usage.html#basin-time", - "title": "Usage", - "section": "5.1 Basin / time", - "text": "5.1 Basin / time\nThis table is the transient form of the Basin table. The only difference is that a time column is added. The table must by sorted by time, and per time it must be sorted by node_id. A linear interpolation between the given timesteps is currently done if the solver takes timesteps between the given data points. More options will be available later." + "objectID": "python/reference/LevelBoundary.html#parameters", + "href": "python/reference/LevelBoundary.html#parameters", + "title": "1 LevelBoundary", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable with the constant water levels.\nrequired" }, { - "objectID": "core/usage.html#basin-state", - "href": "core/usage.html#basin-state", - "title": "Usage", - "section": "5.2 Basin / state", - "text": "5.2 Basin / state\nThe state table aims to capture the full state of the Basin, such that it can be used as an initial condition, potentially the outcome of an earlier simulation. Currently only the Basin node types have state.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\nlevel\nFloat64\n\\(m\\)\n\\(\\ge\\) basin bottom\n\n\n\nEach Basin ID needs to be in the table." + "objectID": "python/reference/Edge.html", + "href": "python/reference/Edge.html", + "title": "1 Edge", + "section": "", + "text": "Edge()\nDefines the connections between nodes.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable describing the flow connections.\nrequired\n\n\n\n\n\n\n\n\n\nName\nDescription\n\n\n\n\nwrite_layer\nWrite the contents of the input to a database.\n\n\n\n\n\nEdge.write_layer(path)\nWrite the contents of the input to a database.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\n\nrequired" }, { - "objectID": "core/usage.html#basin-profile", - "href": "core/usage.html#basin-profile", - "title": "Usage", - "section": "5.3 Basin / profile", - "text": "5.3 Basin / profile\nThe profile table defines the physical dimensions of the storage reservoir of each basin.\n\n\n\n\n\n\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\narea\nFloat64\n\\(m^2\\)\nnon-negative, per node_id: start positive and increasing\n\n\nlevel\nFloat64\n\\(m\\)\nper node_id: increasing\n\n\n\nThe level is the level at the basin outlet. All levels are defined in meters above a datum that is the same for the entire model. An example of the first 5 rows of such a table is given below. The first 4 rows define the profile of ID 2. The number of rows can vary per ID. Using a very large number of rows may impact performance.\n\n\n\nnode_id\narea\nlevel\n\n\n\n\n2\n1.0\n6.0\n\n\n2\n1000.0\n7.0\n\n\n2\n1000.0\n9.0\n\n\n3\n1.0\n2.2\n\n\n\nWe use the symbol \\(A\\) for area, \\(h\\) for level and \\(S\\) for storage. The profile provides a function \\(A(h)\\) for each basin. Internally this get converted to two functions, \\(A(S)\\) and \\(h(S)\\), by integrating over the function, setting the storage to zero for the bottom of the profile. The minimum area cannot be zero to avoid numerical issues. The maximum area is used to convert the precipitation flux into an inflow." + "objectID": "python/reference/Edge.html#parameters", + "href": "python/reference/Edge.html#parameters", + "title": "1 Edge", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable describing the flow connections.\nrequired" }, { - "objectID": "core/usage.html#basin-results", - "href": "core/usage.html#basin-results", - "title": "Usage", - "section": "5.4 Basin results", - "text": "5.4 Basin results\nThe basin table contains results of the storage and level of each basin at every solver timestep. The initial condition is also written to the file.\n\n\n\ncolumn\ntype\nunit\n\n\n\n\ntime\nDateTime\n-\n\n\nnode_id\nInt\n-\n\n\nstorage\nFloat64\n\\(m^3\\)\n\n\nlevel\nFloat64\n\\(m\\)\n\n\n\nThe table is sorted by time, and per time it is sorted by node_id." + "objectID": "python/reference/Edge.html#methods", + "href": "python/reference/Edge.html#methods", + "title": "1 Edge", + "section": "", + "text": "Name\nDescription\n\n\n\n\nwrite_layer\nWrite the contents of the input to a database.\n\n\n\n\n\nEdge.write_layer(path)\nWrite the contents of the input to a database.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\n\nrequired" }, { - "objectID": "core/usage.html#flow-results", - "href": "core/usage.html#flow-results", - "title": "Usage", - "section": "5.5 Flow results", - "text": "5.5 Flow results\nThe flow table contains results of the flow on every edge in the model, for each solver timestep.\n\n\n\ncolumn\ntype\nunit\n\n\n\n\ntime\nDateTime\n-\n\n\nedge_id\nUnion{Int, Missing}\n-\n\n\nfrom_node_id\nInt\n-\n\n\nto_node_id\nInt\n-\n\n\nflow\nFloat64\n\\(m^3 s^{-1}\\)\n\n\n\nThe table is sorted by time, and per time the same edge_id order is used, though not sorted. Flows that are added to the model at a node, have a missing edge_id, and identical from_node_id and to_node_id. Flows out of the model always have a negative sign, and additions a positive sign." + "objectID": "python/reference/ManningResistance.html", + "href": "python/reference/ManningResistance.html", + "title": "1 ManningResistance", + "section": "", + "text": "ManningResistance()\nFlow through this connection is estimated by conservation of energy and the Manning-Gauckler formula to estimate friction losses.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with the constant Manning parameters.\nrequired" }, { - "objectID": "core/usage.html#tabulatedratingcurve-time", - "href": "core/usage.html#tabulatedratingcurve-time", - "title": "Usage", - "section": "7.1 TabulatedRatingCurve / time", - "text": "7.1 TabulatedRatingCurve / time\nThis table is the transient form of the TabulatedRatingCurve table. The only difference is that a time column is added. The table must by sorted by time, and per time it must be sorted by node_id. With this the rating curves can be updated over time. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\ntime\nDateTime\n-\nsorted\n\n\nnode_id\nInt\n-\nsorted per time\n\n\nlevel\nFloat64\n\\(m\\)\n-\n\n\ndischarge\nFloat64\n\\(m^3 s^{-1}\\)\nnon-negative" + "objectID": "python/reference/ManningResistance.html#parameters", + "href": "python/reference/ManningResistance.html#parameters", + "title": "1 ManningResistance", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with the constant Manning parameters.\nrequired" }, { - "objectID": "core/usage.html#user-time", - "href": "core/usage.html#user-time", - "title": "Usage", - "section": "10.1 User / time", - "text": "10.1 User / time\nThis table is the transient form of the User table. The only difference is that a time column is added and activity is assumed to be true. The table must by sorted by time, and per time it must be sorted by node_id. With this the demand can be updated over time. In between the given times the demand is interpolated linearly, and outside the demand is constant given by the nearest time value. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\n\n\n\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\ntime\nDateTime\n-\nsorted per priority per node id\n\n\ndemand\nFloat64\n\\(m^3 s^{-1}\\)\n-\n\n\nreturn_factor\nFloat64\n-\nbetween [0 - 1]\n\n\nmin_level\nFloat64\n\\(m\\)\n(optional)\n\n\npriority\nInt\n-\nsorted per node id" + "objectID": "python/reference/FractionalFlow.html", + "href": "python/reference/FractionalFlow.html", + "title": "1 FractionalFlow", + "section": "", + "text": "FractionalFlow()\nReceives a fraction of the flow. The fractions must sum to 1.0 for a furcation.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable with the constant flow fractions.\nrequired" }, { - "objectID": "core/usage.html#levelboundary-time", - "href": "core/usage.html#levelboundary-time", - "title": "Usage", - "section": "11.1 LevelBoundary / time", - "text": "11.1 LevelBoundary / time\nThis table is the transient form of the LevelBoundary table. The only difference is that a time column is added and activity is assumed to be true. The table must by sorted by time, and per time it must be sorted by node_id. With this the levels can be updated over time. In between the given times the level is interpolated linearly, and outside the flow rate is constant given by the nearest time value. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\ntime\nDateTime\n-\nsorted\n\n\nnode_id\nInt\n-\nsorted per time\n\n\nlevel\nFloat64\n\\(m\\)\n-" + "objectID": "python/reference/FractionalFlow.html#parameters", + "href": "python/reference/FractionalFlow.html#parameters", + "title": "1 FractionalFlow", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable with the constant flow fractions.\nrequired" }, { - "objectID": "core/usage.html#flowboundary-time", - "href": "core/usage.html#flowboundary-time", - "title": "Usage", - "section": "12.1 FlowBoundary / time", - "text": "12.1 FlowBoundary / time\nThis table is the transient form of the FlowBoundary table. The only differences are that a time column is added and the nodes are assumed to be active so this column is removed. The table must by sorted by time, and per time it must be sorted by node_id. With this the flow rates can be updated over time. In between the given times the flow rate is interpolated linearly, and outside the flow rate is constant given by the nearest time value. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\ntime\nDateTime\n-\nsorted\n\n\nnode_id\nInt\n-\nsorted per time\n\n\nflow_rate\nFloat64\n\\(m^3 s^{-1}\\)\nnon-negative" + "objectID": "python/reference/utils.geometry_from_connectivity.html", + "href": "python/reference/utils.geometry_from_connectivity.html", + "title": "1 utils.geometry_from_connectivity", + "section": "", + "text": "utils.geometry_from_connectivity(node, from_id, to_id)\nCreate edge shapely geometries from connectivities.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nnode\nRibasim.Node\n\nrequired\n\n\nfrom_id\nSequence[int]\nFirst node of every edge.\nrequired\n\n\nto_id\nSequence[int]\nSecond node of every edge.\nrequired\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nnp.ndarray\nArray of shapely LineStrings." }, { - "objectID": "core/usage.html#sec-condition", - "href": "core/usage.html#sec-condition", - "title": "Usage", - "section": "16.1 DiscreteControl / condition", - "text": "16.1 DiscreteControl / condition\nThe condition schema defines conditions of the form ‘the discrete_control node with this node id listens to whether the given variable of the node with the given listen feature id is grater than the given value’. If the condition variable comes from a time-series, a look ahead \\(\\Delta t\\) can be supplied.\n\n\n\n\n\n\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\nlisten_feature_id\nInt\n-\n-\n\n\nvariable\nString\n-\nmust be “level” or “flow_rate”\n\n\ngreater_than\nFloat64\nvarious\n-\n\n\nlook_ahead\nFloat64\n\\(s\\)\nOnly on transient boundary conditions, non-negative (optional, default 0)" + "objectID": "python/reference/utils.geometry_from_connectivity.html#parameters", + "href": "python/reference/utils.geometry_from_connectivity.html#parameters", + "title": "1 utils.geometry_from_connectivity", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nnode\nRibasim.Node\n\nrequired\n\n\nfrom_id\nSequence[int]\nFirst node of every edge.\nrequired\n\n\nto_id\nSequence[int]\nSecond node of every edge.\nrequired" }, { - "objectID": "core/usage.html#discretecontrol-logic", - "href": "core/usage.html#discretecontrol-logic", - "title": "Usage", - "section": "16.2 DiscreteControl / logic", - "text": "16.2 DiscreteControl / logic\nThe logic schema defines which control states are triggered based on the truth of the conditions a discrete_control node listens to. DiscreteControl is applied in the Julia core as follows:\n\nDuring the simulation it is checked whether the truth of any of the conditions changes.\nWhen a condition changes, the corresponding discrrete_control node id is retrieved (node_id in the condition schema above).\nThe truth value of all the conditions this discrete_control node lisens to are retrieved, in the order as they are specified in the condition schema. This is then converted into a string of “T” for true and “F” for false. This string we call the truth state.*\nThe table below determines for the given discrete_control node ID and truth state what the corresponding control state is.\nFor all the nodes this discrete_control node affects (as given by the “control” edges in Edges / static), their parameters are set to those parameters in NodeType / static corresponding to the determined control state.\n\n*. There is also a second truth state created in which for the last condition that changed it is specified whether it was an upcrossing (“U”) or downcrossing (“D”) of the threshold (greater than) value. If a control state is specified for a truth state that is crossing-specific, this takes precedence over the control state for the truth state that contains only “T” and “F”.\n\n\n\n\n\n\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\ntruth_state\nString\n-\nConsists of the characters “T” (true), “F” (false), “U” (upcrossing), “D” (downcrossing) and “*” (any)\n\n\ncontrol_state\nString\n-" + "objectID": "python/reference/utils.geometry_from_connectivity.html#returns", + "href": "python/reference/utils.geometry_from_connectivity.html#returns", + "title": "1 utils.geometry_from_connectivity", + "section": "", + "text": "Type\nDescription\n\n\n\n\nnp.ndarray\nArray of shapely LineStrings." }, { - "objectID": "core/usage.html#discretecontrol-results", - "href": "core/usage.html#discretecontrol-results", - "title": "Usage", - "section": "16.3 DiscreteControl results", - "text": "16.3 DiscreteControl results\nThe control table contains a record of each change of control state: when it happened, which control node was involved, to which control state it changed and based on which truth state.\n\n\n\ncolumn\ntype\n\n\n\n\ntime\nDateTime\n\n\ncontrol_node_id\nInt\n\n\ntruth_state\nString\n\n\ncontrol_state\nString" + "objectID": "python/reference/Basin.html", + "href": "python/reference/Basin.html", + "title": "1 Basin", + "section": "", + "text": "Basin()\nInput for a (sub-)basin: an area of land where all flowing surface water converges to a single point.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nprofile\npandas.DataFrame\nTable describing the geometry.\nrequired\n\n\nstatic\npandas.DataFrame\nTable describing the constant fluxes.\nrequired\n\n\ntime\npandas.DataFrame\nTable describing the time-varying fluxes.\nrequired\n\n\nstate\npandas.DataFrame\nTable describing the initial condition.\nrequired" }, { - "objectID": "core/usage.html#pidcontrol-time", - "href": "core/usage.html#pidcontrol-time", - "title": "Usage", - "section": "17.1 PidControl / time", - "text": "17.1 PidControl / time\nThis table is the transient form of the PidControl table. The differences are that a time column is added and the nodes are assumed to be active so this column is removed. The table must by sorted by time, and per time it must be sorted by node_id. With this the target level and PID coefficients can be updated over time. In between the given times the these values interpolated linearly, and outside these values area constant given by the nearest time value. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted per time\n\n\ntime\nDateTime\n-\nsorted\n\n\nlisten_node_id\nInt\n-\n-\n\n\ntarget\nFloat64\n\\(m\\)\n-\n\n\nproportional\nFloat64\n\\(s^{-1}\\)\n-\n\n\nintegral\nFloat64\n\\(s^{-2}\\)\n-\n\n\nderivative\nFloat64\n-\n-" + "objectID": "python/reference/Basin.html#parameters", + "href": "python/reference/Basin.html#parameters", + "title": "1 Basin", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nprofile\npandas.DataFrame\nTable describing the geometry.\nrequired\n\n\nstatic\npandas.DataFrame\nTable describing the constant fluxes.\nrequired\n\n\ntime\npandas.DataFrame\nTable describing the time-varying fluxes.\nrequired\n\n\nstate\npandas.DataFrame\nTable describing the initial condition.\nrequired" }, { - "objectID": "core/numerics.html", - "href": "core/numerics.html", - "title": "Numerical considerations", + "objectID": "python/index.html", + "href": "python/index.html", + "title": "Python tooling", "section": "", - "text": "We want to solve the following initial value problem: \\[\n\\begin{cases}\n \\frac{\\text{d}\\mathbf{u}}{\\text{d}t} = \\mathbf{f}(\\mathbf{u},t) \\quad t_0 < t < t_\\text{end} \\\\\n \\mathbf{u}(t_0) = \\mathbf{u}_0\n\\end{cases},\n\\tag{1}\\]\nwhere \\(\\mathbf{f}\\) denotes water_balance! and \\(\\mathbf{u_0}\\) the initial storages (and the PID integrals which start out at \\(0\\)).\nIn general \\(\\mathbf{f}\\) is a non-linear function in \\(\\mathbf{u}\\). These non-linearities are introduced by:\nThe problem Equation 1 can be solved by various numerical time-integration methods. To do this the time interval \\([t_0,t_\\text{end}]\\) is discretized into a finite number of time points \\(t_0 < t_1 < \\ldots < t_N = t_\\text{end}\\) for which approximate solutions \\(\\mathbf{w}_n \\approx \\mathbf{u}(t_n)\\) are computed. In general we do not assume a fixed timestep (the interval between successive points in time). Rather, the solver attempts to make as large a step as possible while keeping error tolerances within requirements. The solver settings section details the available configuration options." + "text": "The Ribasim Python package (named ribasim) aims to make it easy to build, update and analyze Ribasim models programmatically.\nThe Ribasim QGIS plugin allows users to construct a model from scratch without programming. For specific tasks, like adding observed rainfall timeseries, it can be faster to use Python instead.\nOne can also use Ribasim Python to build entire models from base data, such that your model setup is fully reproducible.\nThe package is registered in PyPI and can therefore be installed with pip:\npip install ribasim\nFor wheel (.whl) downloads, including nightly builds, see the download section. After downloading wheels can be installed by referring to the correct path:\npip install path/to/ribasim-*.whl\nFor documentation please see the examples and API reference." }, { - "objectID": "core/numerics.html#euler-forward", - "href": "core/numerics.html#euler-forward", - "title": "Numerical considerations", - "section": "1.1 Euler forward", - "text": "1.1 Euler forward\nThe simplest numerical method is Euler forward: \\[\n\\mathbf{w}_{n+1} = \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{w}_n, t_n).\n\\tag{2}\\]\nHere \\(\\mathbf{w}_{n+1}\\) is given as a simple explicit function of \\(\\mathbf{w}_n\\)." + "objectID": "python/examples.html", + "href": "python/examples.html", + "title": "Examples", + "section": "", + "text": "1 Basic model with static forcing\n\nfrom pathlib import Path\n\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport ribasim\n\nSetup the basins:\n\nprofile = pd.DataFrame(\n data={\n \"node_id\": [1, 1, 3, 3, 6, 6, 9, 9],\n \"area\": [0.01, 1000.0] * 4,\n \"level\": [0.0, 1.0] * 4,\n }\n)\n\n# Convert steady forcing to m/s\n# 2 mm/d precipitation, 1 mm/d evaporation\nseconds_in_day = 24 * 3600\nprecipitation = 0.002 / seconds_in_day\nevaporation = 0.001 / seconds_in_day\n\nstatic = pd.DataFrame(\n data={\n \"node_id\": [0],\n \"drainage\": [0.0],\n \"potential_evaporation\": [evaporation],\n \"infiltration\": [0.0],\n \"precipitation\": [precipitation],\n \"urban_runoff\": [0.0],\n }\n)\nstatic = static.iloc[[0, 0, 0, 0]]\nstatic[\"node_id\"] = [1, 3, 6, 9]\n\nbasin = ribasim.Basin(profile=profile, static=static)\n\nSetup linear resistance:\n\nlinear_resistance = ribasim.LinearResistance(\n static=pd.DataFrame(\n data={\"node_id\": [10, 12], \"resistance\": [5e3, (3600.0 * 24) / 100.0]}\n )\n)\n\nSetup Manning resistance:\n\nmanning_resistance = ribasim.ManningResistance(\n static=pd.DataFrame(\n data={\n \"node_id\": [2],\n \"length\": [900.0],\n \"manning_n\": [0.04],\n \"profile_width\": [6.0],\n \"profile_slope\": [3.0],\n }\n )\n)\n\nSet up a rating curve node:\n\n# Discharge: lose 1% of storage volume per day at storage = 1000.0.\nq1000 = 1000.0 * 0.01 / seconds_in_day\n\nrating_curve = ribasim.TabulatedRatingCurve(\n static=pd.DataFrame(\n data={\n \"node_id\": [4, 4],\n \"level\": [0.0, 1.0],\n \"discharge\": [0.0, q1000],\n }\n )\n)\n\nSetup fractional flows:\n\nfractional_flow = ribasim.FractionalFlow(\n static=pd.DataFrame(\n data={\n \"node_id\": [5, 8, 13],\n \"fraction\": [0.3, 0.6, 0.1],\n }\n )\n)\n\nSetup pump:\n\npump = ribasim.Pump(\n static=pd.DataFrame(\n data={\n \"node_id\": [7],\n \"flow_rate\": [0.5 / 3600],\n }\n )\n)\n\nSetup level boundary:\n\nlevel_boundary = ribasim.LevelBoundary(\n static=pd.DataFrame(\n data={\n \"node_id\": [11, 17],\n \"level\": [0.5, 1.5],\n }\n )\n)\n\nSetup flow boundary:\n\nflow_boundary = ribasim.FlowBoundary(\n static=pd.DataFrame(\n data={\n \"node_id\": [15, 16],\n \"flow_rate\": [1e-4, 1e-4],\n }\n )\n)\n\nSetup terminal:\n\nterminal = ribasim.Terminal(\n static=pd.DataFrame(\n data={\n \"node_id\": [14],\n }\n )\n)\n\nSet up the nodes:\n\nxy = np.array(\n [\n (0.0, 0.0), # 1: Basin,\n (1.0, 0.0), # 2: ManningResistance\n (2.0, 0.0), # 3: Basin\n (3.0, 0.0), # 4: TabulatedRatingCurve\n (3.0, 1.0), # 5: FractionalFlow\n (3.0, 2.0), # 6: Basin\n (4.0, 1.0), # 7: Pump\n (4.0, 0.0), # 8: FractionalFlow\n (5.0, 0.0), # 9: Basin\n (6.0, 0.0), # 10: LinearResistance\n (2.0, 2.0), # 11: LevelBoundary\n (2.0, 1.0), # 12: LinearResistance\n (3.0, -1.0), # 13: FractionalFlow\n (3.0, -2.0), # 14: Terminal\n (3.0, 3.0), # 15: FlowBoundary\n (0.0, 1.0), # 16: FlowBoundary\n (6.0, 1.0), # 17: LevelBoundary\n ]\n)\nnode_xy = gpd.points_from_xy(x=xy[:, 0], y=xy[:, 1])\n\nnode_id, node_type = ribasim.Node.get_node_ids_and_types(\n basin,\n manning_resistance,\n rating_curve,\n pump,\n fractional_flow,\n linear_resistance,\n level_boundary,\n flow_boundary,\n terminal,\n)\n\n# Make sure the feature id starts at 1: explicitly give an index.\nnode = ribasim.Node(\n static=gpd.GeoDataFrame(\n data={\"type\": node_type},\n index=pd.Index(node_id, name=\"fid\"),\n geometry=node_xy,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the edges:\n\nfrom_id = np.array(\n [1, 2, 3, 4, 4, 5, 6, 8, 7, 9, 11, 12, 4, 13, 15, 16, 10], dtype=np.int64\n)\nto_id = np.array(\n [2, 3, 4, 5, 8, 6, 7, 9, 9, 10, 12, 3, 13, 14, 6, 1, 17], dtype=np.int64\n)\nlines = ribasim.utils.geometry_from_connectivity(node, from_id, to_id)\nedge = ribasim.Edge(\n static=gpd.GeoDataFrame(\n data={\n \"from_node_id\": from_id,\n \"to_node_id\": to_id,\n \"edge_type\": len(from_id) * [\"flow\"],\n },\n geometry=lines,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup a model:\n\nmodel = ribasim.Model(\n node=node,\n edge=edge,\n basin=basin,\n level_boundary=level_boundary,\n flow_boundary=flow_boundary,\n pump=pump,\n linear_resistance=linear_resistance,\n manning_resistance=manning_resistance,\n tabulated_rating_curve=rating_curve,\n fractional_flow=fractional_flow,\n terminal=terminal,\n starttime=\"2020-01-01 00:00:00\",\n endtime=\"2021-01-01 00:00:00\",\n)\n\nLet’s take a look at the model:\n\nmodel.plot()\n\n<Axes: >\n\n\n\n\n\nWrite the model to a TOML and GeoPackage:\n\ndatadir = Path(\"data\")\nmodel.write(datadir / \"basic\")\n\n\n\n2 Update the basic model with transient forcing\nThis assumes you have already created the basic model with static forcing.\n\nimport numpy as np\nimport pandas as pd\nimport ribasim\nimport xarray as xr\n\n\nmodel = ribasim.Model.from_toml(datadir / \"basic/ribasim.toml\")\n\n\ntime = pd.date_range(model.starttime, model.endtime)\nday_of_year = time.day_of_year.to_numpy()\nseconds_per_day = 24 * 60 * 60\nevaporation = (\n (-1.0 * np.cos(day_of_year / 365.0 * 2 * np.pi) + 1.0) * 0.0025 / seconds_per_day\n)\nrng = np.random.default_rng(seed=0)\nprecipitation = (\n rng.lognormal(mean=-1.0, sigma=1.7, size=time.size) * 0.001 / seconds_per_day\n)\n\nWe’ll use xarray to easily broadcast the values.\n\ntimeseries = (\n pd.DataFrame(\n data={\n \"node_id\": 1,\n \"time\": time,\n \"drainage\": 0.0,\n \"potential_evaporation\": evaporation,\n \"infiltration\": 0.0,\n \"precipitation\": precipitation,\n \"urban_runoff\": 0.0,\n }\n )\n .set_index(\"time\")\n .to_xarray()\n)\n\nbasin_ids = model.basin.static[\"node_id\"].to_numpy()\nbasin_nodes = xr.DataArray(\n np.ones(len(basin_ids)), coords={\"node_id\": basin_ids}, dims=[\"node_id\"]\n)\nforcing = (timeseries * basin_nodes).to_dataframe().reset_index()\n\n\nstate = pd.DataFrame(\n data={\n \"node_id\": basin_ids,\n \"level\": 1.4,\n \"concentration\": 0.0,\n }\n)\n\n\nmodel.basin.time = forcing\nmodel.basin.state = state\n\n\nmodel.write(datadir / \"basic_transient\")\n\nNow run the model with ribasim basic-transient/ribasim.toml. After running the model, read back the results:\n\ndf_basin = pd.read_feather(datadir / \"basic_transient/results/basin.arrow\")\ndf_basin_wide = df_basin.pivot_table(\n index=\"time\", columns=\"node_id\", values=[\"storage\", \"level\"]\n)\ndf_basin_wide[\"level\"].plot()\n\n<Axes: xlabel='time'>\n\n\n\n\n\n\ndf_flow = pd.read_feather(datadir / \"basic_transient/results/flow.arrow\")\ndf_flow[\"edge\"] = list(zip(df_flow.from_node_id, df_flow.to_node_id))\ndf_flow[\"flow_m3d\"] = df_flow.flow * 86400\nax = df_flow.pivot_table(index=\"time\", columns=\"edge\", values=\"flow_m3d\").plot()\nax.legend(bbox_to_anchor=(1.3, 1), title=\"Edge\")\n\n<matplotlib.legend.Legend at 0x7f01301eb010>\n\n\n\n\n\n\ntype(df_flow)\n\npandas.core.frame.DataFrame\n\n\n\n\n3 Model with discrete control\nThe model constructed below consists of a single basin which slowly drains trough a TabulatedRatingCurve, but is held within a range around a target level (setpoint) by two connected pumps. These two pumps behave like a reversible pump. When pumping can be done in only one direction, and the other direction is only possible under gravity, use an Outlet for that direction.\nSet up the nodes:\n\nxy = np.array(\n [\n (0.0, 0.0), # 1: Basin\n (1.0, 1.0), # 2: Pump\n (1.0, -1.0), # 3: Pump\n (2.0, 0.0), # 4: LevelBoundary\n (-1.0, 0.0), # 5: TabulatedRatingCurve\n (-2.0, 0.0), # 6: Terminal\n (1.0, 0.0), # 7: DiscreteControl\n ]\n)\n\nnode_xy = gpd.points_from_xy(x=xy[:, 0], y=xy[:, 1])\n\nnode_type = [\n \"Basin\",\n \"Pump\",\n \"Pump\",\n \"LevelBoundary\",\n \"TabulatedRatingCurve\",\n \"Terminal\",\n \"DiscreteControl\",\n]\n\n# Make sure the feature id starts at 1: explicitly give an index.\nnode = ribasim.Node(\n static=gpd.GeoDataFrame(\n data={\"type\": node_type},\n index=pd.Index(np.arange(len(xy)) + 1, name=\"fid\"),\n geometry=node_xy,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the edges:\n\nfrom_id = np.array([1, 3, 4, 2, 1, 5, 7, 7], dtype=np.int64)\nto_id = np.array([3, 4, 2, 1, 5, 6, 2, 3], dtype=np.int64)\n\nedge_type = 6 * [\"flow\"] + 2 * [\"control\"]\n\nlines = ribasim.utils.geometry_from_connectivity(node, from_id, to_id)\nedge = ribasim.Edge(\n static=gpd.GeoDataFrame(\n data={\"from_node_id\": from_id, \"to_node_id\": to_id, \"edge_type\": edge_type},\n geometry=lines,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the basins:\n\nprofile = pd.DataFrame(\n data={\n \"node_id\": [1, 1],\n \"area\": [1000.0, 1000.0],\n \"level\": [0.0, 1.0],\n }\n)\n\nstatic = pd.DataFrame(\n data={\n \"node_id\": [1],\n \"drainage\": [0.0],\n \"potential_evaporation\": [0.0],\n \"infiltration\": [0.0],\n \"precipitation\": [0.0],\n \"urban_runoff\": [0.0],\n }\n)\n\nstate = pd.DataFrame(data={\"node_id\": [1], \"level\": [20.0]})\n\nbasin = ribasim.Basin(profile=profile, static=static, state=state)\n\nSetup the discrete control:\n\ncondition = pd.DataFrame(\n data={\n \"node_id\": 3 * [7],\n \"listen_feature_id\": 3 * [1],\n \"variable\": 3 * [\"level\"],\n \"greater_than\": [5.0, 10.0, 15.0], # min, setpoint, max\n }\n)\n\nlogic = pd.DataFrame(\n data={\n \"node_id\": 5 * [7],\n \"truth_state\": [\"FFF\", \"U**\", \"T*F\", \"**D\", \"TTT\"],\n \"control_state\": [\"in\", \"in\", \"none\", \"out\", \"out\"],\n }\n)\n\ndiscrete_control = ribasim.DiscreteControl(condition=condition, logic=logic)\n\nThe above control logic can be summarized as follows: - If the level gets above the maximum, activate the control state “out” until the setpoint is reached; - If the level gets below the minimum, active the control state “in” until the setpoint is reached; - Otherwise activate the control state “none”.\nSetup the pump:\n\npump = ribasim.Pump(\n static=pd.DataFrame(\n data={\n \"node_id\": 3 * [2] + 3 * [3],\n \"control_state\": 2 * [\"none\", \"in\", \"out\"],\n \"flow_rate\": [0.0, 2e-3, 0.0, 0.0, 0.0, 2e-3],\n }\n )\n)\n\nThe pump data defines the following:\n\n\n\nControl state\nPump #2 flow rate (m/s)\nPump #3 flow rate (m/s)\n\n\n\n\n“none”\n0.0\n0.0\n\n\n“in”\n2e-3\n0.0\n\n\n“out”\n0.0\n2e-3\n\n\n\nSetup the level boundary:\n\nlevel_boundary = ribasim.LevelBoundary(\n static=pd.DataFrame(data={\"node_id\": [4], \"level\": [10.0]})\n)\n\nSetup the rating curve:\n\nrating_curve = ribasim.TabulatedRatingCurve(\n static=pd.DataFrame(\n data={\"node_id\": 2 * [5], \"level\": [2.0, 15.0], \"discharge\": [0.0, 1e-3]}\n )\n)\n\nSetup the terminal:\n\nterminal = ribasim.Terminal(static=pd.DataFrame(data={\"node_id\": [6]}))\n\nSetup a model:\n\nmodel = ribasim.Model(\n node=node,\n edge=edge,\n basin=basin,\n pump=pump,\n level_boundary=level_boundary,\n tabulated_rating_curve=rating_curve,\n terminal=terminal,\n discrete_control=discrete_control,\n starttime=\"2020-01-01 00:00:00\",\n endtime=\"2021-01-01 00:00:00\",\n)\n\nLet’s take a look at the model:\n\nmodel.plot()\n\n<Axes: >\n\n\n\n\n\nListen edges are plotted with a dashed line since they are not present in the “Edge / static” schema but only in the “Control / condition” schema.\n\ndatadir = Path(\"data\")\nmodel.write(datadir / \"level_setpoint_with_minmax\")\n\nNow run the model with level_setpoint_with_minmax/ribasim.toml. After running the model, read back the results:\n\nfrom matplotlib.dates import date2num\n\ndf_basin = pd.read_feather(datadir / \"level_setpoint_with_minmax/results/basin.arrow\")\ndf_basin_wide = df_basin.pivot_table(\n index=\"time\", columns=\"node_id\", values=[\"storage\", \"level\"]\n)\n\nax = df_basin_wide[\"level\"].plot()\n\ngreater_than = model.discrete_control.condition.greater_than\n\nax.hlines(\n greater_than,\n df_basin.time[0],\n df_basin.time.max(),\n lw=1,\n ls=\"--\",\n color=\"k\",\n)\n\ndf_control = pd.read_feather(\n datadir / \"level_setpoint_with_minmax/results/control.arrow\"\n)\n\ny_min, y_max = ax.get_ybound()\nax.fill_between(df_control.time[:2], 2 * [y_min], 2 * [y_max], alpha=0.2, color=\"C0\")\nax.fill_between(df_control.time[2:4], 2 * [y_min], 2 * [y_max], alpha=0.2, color=\"C0\")\n\nax.set_xticks(\n date2num(df_control.time).tolist(),\n df_control.control_state.tolist(),\n rotation=50,\n)\n\nax.set_yticks(greater_than, [\"min\", \"setpoint\", \"max\"])\nax.set_ylabel(\"level\")\nplt.show()\n\n\n\n\nThe highlighted regions show where a pump is active.\nLet’s print an overview of what happened with control:\n\nmodel.print_discrete_control_record(\n datadir / \"level_setpoint_with_minmax/results/control.arrow\"\n)\n\n0. At 2020-01-01 00:00:00 the control node with ID 7 reached truth state TTT:\n For node ID 1 (Basin): level > 5.0\n For node ID 1 (Basin): level > 10.0\n For node ID 1 (Basin): level > 15.0\n\n This yielded control state \"out\":\n For node ID 2 (Pump): flow_rate = 0.0\n For node ID 3 (Pump): flow_rate = 0.002\n\n1. At 2020-02-09 01:17:29.324000 the control node with ID 7 reached truth state TFF:\n For node ID 1 (Basin): level > 5.0\n For node ID 1 (Basin): level < 10.0\n For node ID 1 (Basin): level < 15.0\n\n This yielded control state \"none\":\n For node ID 2 (Pump): flow_rate = 0.0\n For node ID 3 (Pump): flow_rate = 0.0\n\n2. At 2020-07-05 13:24:51.165000 the control node with ID 7 reached truth state FFF:\n For node ID 1 (Basin): level < 5.0\n For node ID 1 (Basin): level < 10.0\n For node ID 1 (Basin): level < 15.0\n\n This yielded control state \"in\":\n For node ID 2 (Pump): flow_rate = 0.002\n For node ID 3 (Pump): flow_rate = 0.0\n\n3. At 2020-08-11 11:49:59.015000 the control node with ID 7 reached truth state TTF:\n For node ID 1 (Basin): level > 5.0\n For node ID 1 (Basin): level > 10.0\n For node ID 1 (Basin): level < 15.0\n\n This yielded control state \"none\":\n For node ID 2 (Pump): flow_rate = 0.0\n For node ID 3 (Pump): flow_rate = 0.0\n\n\n\nNote that crossing direction specific truth states (containing “U”, “D”) are not present in this overview even though they are part of the control logic. This is because in the control logic for this model these truth states are only used to sustain control states, while the overview only shows changes in control states.\n\n\n4 Model with PID control\nSet up the nodes:\n\nxy = np.array(\n [\n (0.0, 0.0), # 1: FlowBoundary\n (1.0, 0.0), # 2: Basin\n (2.0, 0.5), # 3: Pump\n (3.0, 0.0), # 4: LevelBoundary\n (1.5, 1.0), # 5: PidControl\n (2.0, -0.5), # 6: outlet\n (1.5, -1.0), # 7: PidControl\n ]\n)\n\nnode_xy = gpd.points_from_xy(x=xy[:, 0], y=xy[:, 1])\n\nnode_type = [\n \"FlowBoundary\",\n \"Basin\",\n \"Pump\",\n \"LevelBoundary\",\n \"PidControl\",\n \"Outlet\",\n \"PidControl\",\n]\n\n# Make sure the feature id starts at 1: explicitly give an index.\nnode = ribasim.Node(\n static=gpd.GeoDataFrame(\n data={\"type\": node_type},\n index=pd.Index(np.arange(len(xy)) + 1, name=\"fid\"),\n geometry=node_xy,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the edges:\n\nfrom_id = np.array([1, 2, 3, 4, 6, 5, 7], dtype=np.int64)\nto_id = np.array([2, 3, 4, 6, 2, 3, 6], dtype=np.int64)\n\nlines = ribasim.utils.geometry_from_connectivity(node, from_id, to_id)\nedge = ribasim.Edge(\n static=gpd.GeoDataFrame(\n data={\n \"from_node_id\": from_id,\n \"to_node_id\": to_id,\n \"edge_type\": 5 * [\"flow\"] + 2 * [\"control\"],\n },\n geometry=lines,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the basins:\n\nprofile = pd.DataFrame(\n data={\"node_id\": [2, 2], \"level\": [0.0, 1.0], \"area\": [1000.0, 1000.0]}\n)\n\nstatic = pd.DataFrame(\n data={\n \"node_id\": [2],\n \"drainage\": [0.0],\n \"potential_evaporation\": [0.0],\n \"infiltration\": [0.0],\n \"precipitation\": [0.0],\n \"urban_runoff\": [0.0],\n }\n)\n\nstate = pd.DataFrame(\n data={\n \"node_id\": [2],\n \"level\": [6.0],\n }\n)\n\nbasin = ribasim.Basin(profile=profile, static=static, state=state)\n\nSetup the pump:\n\npump = ribasim.Pump(\n static=pd.DataFrame(\n data={\n \"node_id\": [3],\n \"flow_rate\": [0.0], # Will be overwritten by PID controller\n }\n )\n)\n\nSetup the outlet:\n\noutlet = ribasim.Outlet(\n static=pd.DataFrame(\n data={\n \"node_id\": [6],\n \"flow_rate\": [0.0], # Will be overwritten by PID controller\n }\n )\n)\n\nSetup flow boundary:\n\nflow_boundary = ribasim.FlowBoundary(\n static=pd.DataFrame(data={\"node_id\": [1], \"flow_rate\": [1e-3]})\n)\n\nSetup flow boundary:\n\nlevel_boundary = ribasim.LevelBoundary(\n static=pd.DataFrame(\n data={\n \"node_id\": [4],\n \"level\": [1.0], # Not relevant\n }\n )\n)\n\nSetup PID control:\n\npid_control = ribasim.PidControl(\n time=pd.DataFrame(\n data={\n \"node_id\": 4 * [5, 7],\n \"time\": [\n \"2020-01-01 00:00:00\",\n \"2020-01-01 00:00:00\",\n \"2020-05-01 00:00:00\",\n \"2020-05-01 00:00:00\",\n \"2020-07-01 00:00:00\",\n \"2020-07-01 00:00:00\",\n \"2020-12-01 00:00:00\",\n \"2020-12-01 00:00:00\",\n ],\n \"listen_node_id\": 4 * [2, 2],\n \"target\": [5.0, 5.0, 5.0, 5.0, 7.5, 7.5, 7.5, 7.5],\n \"proportional\": 4 * [-1e-3, 1e-3],\n \"integral\": 4 * [-1e-7, 1e-7],\n \"derivative\": 4 * [0.0, 0.0],\n }\n )\n)\n\nNote that the coefficients for the pump and the outlet are equal in magnitude but opposite in sign. This way the pump and the outlet equally work towards the same goal, while having opposite effects on the controlled basin due to their connectivity to this basin.\nSetup a model:\n\nmodel = ribasim.Model(\n node=node,\n edge=edge,\n basin=basin,\n flow_boundary=flow_boundary,\n level_boundary=level_boundary,\n pump=pump,\n outlet=outlet,\n pid_control=pid_control,\n starttime=\"2020-01-01 00:00:00\",\n endtime=\"2020-12-01 00:00:00\",\n)\n\nLet’s take a look at the model:\n\nmodel.plot()\n\n<Axes: >\n\n\n\n\n\nWrite the model to a TOML and GeoPackage:\n\ndatadir = Path(\"data\")\nmodel.write(datadir / \"pid_control\")\n\nNow run the model with ribasim pid_control/ribasim.toml. After running the model, read back the results:\n\nfrom matplotlib.dates import date2num\n\ndf_basin = pd.read_feather(datadir / \"pid_control/results/basin.arrow\")\ndf_basin_wide = df_basin.pivot_table(\n index=\"time\", columns=\"node_id\", values=[\"storage\", \"level\"]\n)\nax = df_basin_wide[\"level\"].plot()\nax.set_ylabel(\"level [m]\")\n\n# Plot target level\ntarget_levels = model.pid_control.time.target.to_numpy()[::2]\ntimes = date2num(model.pid_control.time.time)[::2]\nax.plot(times, target_levels, color=\"k\", ls=\":\", label=\"target level\")\npass" }, { - "objectID": "core/numerics.html#euler-backward", - "href": "core/numerics.html#euler-backward", - "title": "Numerical considerations", - "section": "1.2 Euler backward", - "text": "1.2 Euler backward\nEuler backward is formulated as follows: \\[\n\\mathbf{w}_{n+1} = \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{w}_{n+1},t_{n+1}).\n\\tag{3}\\]\nNote that this is an implicit equation for \\(\\mathbf{w}_{n+1}\\), which is non-linear because of the non-linearity of \\(\\mathbf{f}\\).\nGenerally one of the following iterative methods is used for finding solutions to non-linear equations like this:\n\nPicard iteration for fixed points. This method aims to approximate \\(\\mathbf{w}_{n+1}\\) as a fixed point of the function \\[\n\\mathbf{g}(\\mathbf{x}) = \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{x},t_{n+1})\n\\] by iterating \\(\\mathbf{g}\\) on an initial guess of \\(\\mathbf{w}_{n+1}\\);\nNewton-Raphson iterations: approximate \\(\\mathbf{w}_{n+1}\\) as a root of the function \\[\n\\mathbf{h}(\\mathbf{x}) = \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{x},t_{n+1}) - \\mathbf{x},\n\\] by iteratively finding the root of its linearized form: \\[\n\\begin{align}\n\\mathbf{0} =& \\mathbf{h}(\\mathbf{w}_{n+1}^k) + \\mathbf{J}(\\mathbf{h})(\\mathbf{w}_{n+1}^k)(\\mathbf{w}_{n+1}^{k+1}-\\mathbf{w}_{n+1}^k) \\\\\n=& \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{w}_{n+1}^k,t_{n+1}) - \\mathbf{w}_{n+1}^k \\\\ +&\\left[(t_{n+1}-t_n)\\mathbf{J}(\\mathbf{f})(\\mathbf{w}_{n+1}^k)-\\mathbf{I}\\right](\\mathbf{w}_{n+1}^{k+1}-\\mathbf{w}_{n+1}^k).\n\\end{align}\n\\tag{4}\\] Note that this thus requires an evaluation of the Jacobian of \\(\\mathbf{f}\\) and solving a linear system per iteration." + "objectID": "python/reference/LinearResistance.html", + "href": "python/reference/LinearResistance.html", + "title": "1 LinearResistance", + "section": "", + "text": "LinearResistance()\nFlow through this connection linearly depends on the level difference between the two connected basins.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with the constant resistances.\nrequired" }, { - "objectID": "core/numerics.html#basin-profiles", - "href": "core/numerics.html#basin-profiles", - "title": "Numerical considerations", - "section": "4.1 Basin profiles", - "text": "4.1 Basin profiles\nThe basin profiles affect \\(\\mathbf{f}\\) in many ways, anywhere where a basin level or area is required.\n\n\n\n\n\n\nNote\n\n\n\nThis section needs to be updated and extended after once this issue is resolved." + "objectID": "python/reference/LinearResistance.html#parameters", + "href": "python/reference/LinearResistance.html#parameters", + "title": "1 LinearResistance", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with the constant resistances.\nrequired" }, { - "objectID": "core/numerics.html#qh-relations", - "href": "core/numerics.html#qh-relations", - "title": "Numerical considerations", - "section": "4.2 Q(h) relations", - "text": "4.2 Q(h) relations\nTabulatedRatingCurve nodes contribute to \\(\\mathbf{f}\\) with terms of the following form:\n\\[\n Q(h(S))\n\\]\nwhere the continuity of this term is given by the least continuous of \\(Q\\) and \\(h\\)." + "objectID": "python/reference/Node.html", + "href": "python/reference/Node.html", + "title": "1 Node", + "section": "", + "text": "Node()\nThe Ribasim nodes as Point geometries.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\ngeopandas.GeoDataFrame\nTable with node ID, type and geometry.\nrequired\n\n\n\n\n\n\n\n\n\nName\nDescription\n\n\n\n\nplot\nPlot the nodes. Each node type is given a separate marker.\n\n\nwrite_layer\nWrite the contents of the input to a database.\n\n\n\n\n\nNode.plot(ax=None, zorder=None)\nPlot the nodes. Each node type is given a separate marker.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nax\nOptional\nThe axis on which the nodes will be plotted.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nNone\n\n\n\n\n\n\n\n\nNode.write_layer(path)\nWrite the contents of the input to a database.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\n\nrequired" }, { - "objectID": "core/numerics.html#empty-basins", - "href": "core/numerics.html#empty-basins", - "title": "Numerical considerations", - "section": "4.3 Empty basins", - "text": "4.3 Empty basins\nReduction factors are introduced at several points in the definition of \\(\\mathbf{f}\\) to smooth out otherwise discontinuous transitions (e.g. the flow rate of a pump going to zero when the source basin dries out). If flows are not too large with respect to basin storage, this will prevent basins from reaching 0. Rather, the basin gets a very small storage. The reduction factors help with performance, but are also an important tool to avoid getting negative storage in basins. Negative storage needs to be avoided since it is not a real solution, and would introduce water into the model that doesn’t exist. Another tool used to avoid negative storage is the isoutoutofdomain option, which Ribasim makes use of. This reject timesteps that lead to negative storage, instead retrying with a smaller timestep." + "objectID": "python/reference/Node.html#parameters", + "href": "python/reference/Node.html#parameters", + "title": "1 Node", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\ngeopandas.GeoDataFrame\nTable with node ID, type and geometry.\nrequired" }, { - "objectID": "qgis/index.html", - "href": "qgis/index.html", - "title": "QGIS plugin", + "objectID": "python/reference/Node.html#methods", + "href": "python/reference/Node.html#methods", + "title": "1 Node", "section": "", - "text": "Install QGIS version 3.28 or higher.\n\n\nDownload ribasim_qgis.zip, see the download section.\nPlugins menu > Manage and Install Plugins…\n\n\n\n\n\nSelect “Install from ZIP”:\n\nBrowse to the ribasim_qgis.zip file containing the plugin that was downloaded earlier\nClick “Install Plugin”\n\n\n\n\n\n\nStart the Ribasim plugin.\n\n\n\n\n\n\n\n\nIn QGIS, navigate to “Plugins > Manage and Install Plugins > All”. In the search bar, type: “iMOD”. Select the iMOD plugin, and click “Install”.\nAt least version 0.4.0 of the iMOD plugin is required.\nThe Time Series widget from the iMOD plugin is used for visualizing Ribasim results, which is described in Section 1.5. Documentation on the Time Series widget can be found in the iMOD documentation.\n\n\n\nOpen example model database.gpkg or create a new model.\n\n\n\n\n\nCheck if your coordinate reference system (CRS) is set correctly.\n\n\n\n\n\nIf you are working with an unknown CRS, right click the model database group in Layers, and click “Set Group CRS…”.\n\n\n\n\n\nIf you are modeling the Netherlands, select “Amersfoort / RD New” (EPSG:28992).\n\n\n\n\n\n\n\n\n\n\n\nSelect the Node layer.\n\n\n\n\n\nTurn on the edit mode to be able to add nodes on the map.\n\n\n\n\n\nAdd nodes to the map with a left click and select the node type.\n\n\n\n\n\nTurn the edit mode off and save the edits to the Nodes layer.\n\n\n\n\n\n\n\n\nRight click a layer and select “Open Attribute Table”.\n\n\n\n\n\nClick the yellow pencil icon on the top left to enable editing, and copy and paste a record. A record can be selected by clicking on the row number.\n\n\n\n\n\nAdjust the content. If you prefer, it also works to copy data with the same columns from Excel. Turn off edit mode and save changes to the layer.\n\n\n\n\n\n\n\n\n\n\n\nMake sure the Snapping Toolbar is visible, by going to the View > Toolbars menu. Turn on snapping mode by clicking the magnet and set the snapping distance to 25 pixels.\n\n\n\n\n\n\n\n\nSelect the Edge layer and turn on the edit mode.\n\n\n\n\n\nSelect “Add line feature”.\n\n\n\n\n\nCreate a connection by left clicking a source node and right clicking the destination node.\n\n\n\n\n\nNow leave the edit mode and save the results to the layer.\n\n\n\n\n\nOpen a text editor and create an empty file next to your database, with the .toml extension.\nAdd the following content to the TOML file:\n\n\n\nribasim.toml\n\nstarttime = 2020-01-01 00:00:00\nendtime = 2021-01-01 00:00:00\ndatabase = \"database.gpkg\"\n\n\nUnzip the Ribasim command line interface, ribasim_cli.zip\nOpen your terminal and go to the directory where your TOML is stored. Now run path/to/ribasim_cli/ribasim ribasim.toml. Adjust the path to the ribasim_cli folder to where you placed it. This runs the model.\nIn your model directory there is now a results/ folder with basin.arrow and flow.arrow output files.\n\n\n\n\n\n\nIn QGIS select the model group.\n\n\n\n\n\nIn the Ribasim plugin widget, select the Results tab and click “Associate Results”.\n\n\n\n\n\nSelect results/basin.arrow.\n\n\n\n\n\nThis adds metadata to the model that the iMOD plugin can use to find the timeseries data that is associated to the model nodes.\n\n\n\nClick the “Time Series” button of the iMOD plugin.\n\n\n\n\n\nSelect the variables that you want to plot.\n\n\n\n\n\nClick “Select points” and select a node by dragging a rectangle around it on the map. Hold the Ctrl key to select multiple nodes. Currently only the Basin nodes can be plotted.\n\n\n\n\n\nThe associated time series are shown the the graph." + "text": "Name\nDescription\n\n\n\n\nplot\nPlot the nodes. Each node type is given a separate marker.\n\n\nwrite_layer\nWrite the contents of the input to a database.\n\n\n\n\n\nNode.plot(ax=None, zorder=None)\nPlot the nodes. Each node type is given a separate marker.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nax\nOptional\nThe axis on which the nodes will be plotted.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nNone\n\n\n\n\n\n\n\n\nNode.write_layer(path)\nWrite the contents of the input to a database.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\n\nrequired" }, { - "objectID": "qgis/index.html#start", - "href": "qgis/index.html#start", - "title": "QGIS plugin", + "objectID": "python/reference/Model.html", + "href": "python/reference/Model.html", + "title": "1 Model", "section": "", - "text": "Install QGIS version 3.28 or higher.\n\n\nDownload ribasim_qgis.zip, see the download section.\nPlugins menu > Manage and Install Plugins…\n\n\n\n\n\nSelect “Install from ZIP”:\n\nBrowse to the ribasim_qgis.zip file containing the plugin that was downloaded earlier\nClick “Install Plugin”\n\n\n\n\n\n\nStart the Ribasim plugin.\n\n\n\n\n\n\n\n\nIn QGIS, navigate to “Plugins > Manage and Install Plugins > All”. In the search bar, type: “iMOD”. Select the iMOD plugin, and click “Install”.\nAt least version 0.4.0 of the iMOD plugin is required.\nThe Time Series widget from the iMOD plugin is used for visualizing Ribasim results, which is described in Section 1.5. Documentation on the Time Series widget can be found in the iMOD documentation.\n\n\n\nOpen example model database.gpkg or create a new model.\n\n\n\n\n\nCheck if your coordinate reference system (CRS) is set correctly.\n\n\n\n\n\nIf you are working with an unknown CRS, right click the model database group in Layers, and click “Set Group CRS…”.\n\n\n\n\n\nIf you are modeling the Netherlands, select “Amersfoort / RD New” (EPSG:28992)." + "text": "Model()\nA full Ribasim model schematisation with all input.\nRibasim model containing the location of the nodes, the edges between the nodes, and the node parametrization.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nnode\nNode\nThe ID, type and geometry of each node.\nrequired\n\n\nedge\nEdge\nHow the nodes are connected.\nrequired\n\n\nbasin\nBasin\nThe waterbodies.\nrequired\n\n\nfractional_flow\nOptional[FractionalFlow]\nSplit flows into fractions.\nrequired\n\n\nlevel_boundary\nOptional[LevelBoundary]\nBoundary condition specifying the water level.\nrequired\n\n\nflow_boundary\nOptional[FlowBoundary]\nBoundary conditions specifying the flow.\nrequired\n\n\nlinear_resistance\n\nLinear flow resistance.\nrequired\n\n\nmanning_resistance\nOptional[ManningResistance]\nFlow resistance based on the Manning formula.\nrequired\n\n\ntabulated_rating_curve\nOptional[TabulatedRatingCurve]\nTabulated rating curve describing flow based on the upstream water level.\nrequired\n\n\npump\nOptional[Pump]\nPrescribed flow rate from one basin to the other.\nrequired\n\n\noutlet\nOptional[Outlet]\nPrescribed flow rate from one basin to the other.\nrequired\n\n\nterminal\nOptional[Terminal]\nWater sink without state or properties.\nrequired\n\n\ndiscrete_control\nOptional[DiscreteControl]\nDiscrete control logic.\nrequired\n\n\npid_control\nOptional[PidControl]\nPID controller attempting to set the level of a basin to a desired value using a pump/outlet.\nrequired\n\n\nuser\nOptional[User]\nUser node type with demand and priority.\nrequired\n\n\nstarttime\nUnion[str, datetime.datetime]\nStarting time of the simulation.\nrequired\n\n\nendtime\nUnion[str, datetime.datetime]\nEnd time of the simulation.\nrequired\n\n\nsolver\nOptional[Solver]\nSolver settings.\nrequired\n\n\nlogging\nOptional[logging]\nLogging settings.\nrequired\n\n\n\n\n\n\n\n\n\nName\nDescription\n\n\n\n\nfields\nReturn the names of the fields contained in the Model.\n\n\nfrom_toml\nInitialize a model from the TOML configuration file.\n\n\nplot\nPlot the nodes and edges of the model.\n\n\nsort\nSort all input tables as required.\n\n\nvalidate_model\nValidate the model.\n\n\nvalidate_model_node_IDs\nCheck whether the node IDs in the node field correspond to the node IDs on the node type fields.\n\n\nvalidate_model_node_field_IDs\nCheck whether the node IDs of the node_type fields are valid.\n\n\nvalidate_model_node_types\nCheck whether all node types in the node field are valid.\n\n\nwrite\nWrite the contents of the model to a database and a TOML configuration file.\n\n\n\n\n\nModel.fields()\nReturn the names of the fields contained in the Model.\n\n\n\nModel.from_toml(path)\nInitialize a model from the TOML configuration file.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\nPath to the configuration TOML file.\nrequired\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nModel\n\n\n\n\n\n\n\n\nModel.plot(ax=None)\nPlot the nodes and edges of the model.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nax\nmatplotlib.pyplot.Artist\nAxes on which to draw the plot.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nmatplotlib.pyplot.Artist\n\n\n\n\n\n\n\n\nModel.sort()\nSort all input tables as required.\nTables are sorted by “node_id”, unless otherwise specified. Sorting is done automatically before writing the table.\n\n\n\nModel.validate_model()\nValidate the model.\nChecks: - Whether all node types in the node field are valid - Whether the node IDs of the node_type fields are valid - Whether the node IDs in the node field correspond to the node IDs on the node type fields\n\n\n\nModel.validate_model_node_IDs()\nCheck whether the node IDs in the node field correspond to the node IDs on the node type fields.\n\n\n\nModel.validate_model_node_field_IDs()\nCheck whether the node IDs of the node_type fields are valid.\n\n\n\nModel.validate_model_node_types()\nCheck whether all node types in the node field are valid.\n\n\n\nModel.write(directory)\nWrite the contents of the model to a database and a TOML configuration file.\nIf directory does not exist, it is created before writing.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\ndirectory\nFilePath\n\nrequired" }, { - "objectID": "qgis/index.html#edit-nodes", - "href": "qgis/index.html#edit-nodes", - "title": "QGIS plugin", + "objectID": "python/reference/Model.html#parameters", + "href": "python/reference/Model.html#parameters", + "title": "1 Model", "section": "", - "text": "Select the Node layer.\n\n\n\n\n\nTurn on the edit mode to be able to add nodes on the map.\n\n\n\n\n\nAdd nodes to the map with a left click and select the node type.\n\n\n\n\n\nTurn the edit mode off and save the edits to the Nodes layer.\n\n\n\n\n\n\n\n\nRight click a layer and select “Open Attribute Table”.\n\n\n\n\n\nClick the yellow pencil icon on the top left to enable editing, and copy and paste a record. A record can be selected by clicking on the row number.\n\n\n\n\n\nAdjust the content. If you prefer, it also works to copy data with the same columns from Excel. Turn off edit mode and save changes to the layer." + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nnode\nNode\nThe ID, type and geometry of each node.\nrequired\n\n\nedge\nEdge\nHow the nodes are connected.\nrequired\n\n\nbasin\nBasin\nThe waterbodies.\nrequired\n\n\nfractional_flow\nOptional[FractionalFlow]\nSplit flows into fractions.\nrequired\n\n\nlevel_boundary\nOptional[LevelBoundary]\nBoundary condition specifying the water level.\nrequired\n\n\nflow_boundary\nOptional[FlowBoundary]\nBoundary conditions specifying the flow.\nrequired\n\n\nlinear_resistance\n\nLinear flow resistance.\nrequired\n\n\nmanning_resistance\nOptional[ManningResistance]\nFlow resistance based on the Manning formula.\nrequired\n\n\ntabulated_rating_curve\nOptional[TabulatedRatingCurve]\nTabulated rating curve describing flow based on the upstream water level.\nrequired\n\n\npump\nOptional[Pump]\nPrescribed flow rate from one basin to the other.\nrequired\n\n\noutlet\nOptional[Outlet]\nPrescribed flow rate from one basin to the other.\nrequired\n\n\nterminal\nOptional[Terminal]\nWater sink without state or properties.\nrequired\n\n\ndiscrete_control\nOptional[DiscreteControl]\nDiscrete control logic.\nrequired\n\n\npid_control\nOptional[PidControl]\nPID controller attempting to set the level of a basin to a desired value using a pump/outlet.\nrequired\n\n\nuser\nOptional[User]\nUser node type with demand and priority.\nrequired\n\n\nstarttime\nUnion[str, datetime.datetime]\nStarting time of the simulation.\nrequired\n\n\nendtime\nUnion[str, datetime.datetime]\nEnd time of the simulation.\nrequired\n\n\nsolver\nOptional[Solver]\nSolver settings.\nrequired\n\n\nlogging\nOptional[logging]\nLogging settings.\nrequired" }, { - "objectID": "qgis/index.html#connect-nodes", - "href": "qgis/index.html#connect-nodes", - "title": "QGIS plugin", + "objectID": "python/reference/Model.html#methods", + "href": "python/reference/Model.html#methods", + "title": "1 Model", "section": "", - "text": "Make sure the Snapping Toolbar is visible, by going to the View > Toolbars menu. Turn on snapping mode by clicking the magnet and set the snapping distance to 25 pixels.\n\n\n\n\n\n\n\n\nSelect the Edge layer and turn on the edit mode.\n\n\n\n\n\nSelect “Add line feature”.\n\n\n\n\n\nCreate a connection by left clicking a source node and right clicking the destination node.\n\n\n\n\n\nNow leave the edit mode and save the results to the layer." + "text": "Name\nDescription\n\n\n\n\nfields\nReturn the names of the fields contained in the Model.\n\n\nfrom_toml\nInitialize a model from the TOML configuration file.\n\n\nplot\nPlot the nodes and edges of the model.\n\n\nsort\nSort all input tables as required.\n\n\nvalidate_model\nValidate the model.\n\n\nvalidate_model_node_IDs\nCheck whether the node IDs in the node field correspond to the node IDs on the node type fields.\n\n\nvalidate_model_node_field_IDs\nCheck whether the node IDs of the node_type fields are valid.\n\n\nvalidate_model_node_types\nCheck whether all node types in the node field are valid.\n\n\nwrite\nWrite the contents of the model to a database and a TOML configuration file.\n\n\n\n\n\nModel.fields()\nReturn the names of the fields contained in the Model.\n\n\n\nModel.from_toml(path)\nInitialize a model from the TOML configuration file.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\nPath to the configuration TOML file.\nrequired\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nModel\n\n\n\n\n\n\n\n\nModel.plot(ax=None)\nPlot the nodes and edges of the model.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nax\nmatplotlib.pyplot.Artist\nAxes on which to draw the plot.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nmatplotlib.pyplot.Artist\n\n\n\n\n\n\n\n\nModel.sort()\nSort all input tables as required.\nTables are sorted by “node_id”, unless otherwise specified. Sorting is done automatically before writing the table.\n\n\n\nModel.validate_model()\nValidate the model.\nChecks: - Whether all node types in the node field are valid - Whether the node IDs of the node_type fields are valid - Whether the node IDs in the node field correspond to the node IDs on the node type fields\n\n\n\nModel.validate_model_node_IDs()\nCheck whether the node IDs in the node field correspond to the node IDs on the node type fields.\n\n\n\nModel.validate_model_node_field_IDs()\nCheck whether the node IDs of the node_type fields are valid.\n\n\n\nModel.validate_model_node_types()\nCheck whether all node types in the node field are valid.\n\n\n\nModel.write(directory)\nWrite the contents of the model to a database and a TOML configuration file.\nIf directory does not exist, it is created before writing.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\ndirectory\nFilePath\n\nrequired" }, { - "objectID": "qgis/index.html#run-a-model", - "href": "qgis/index.html#run-a-model", - "title": "QGIS plugin", + "objectID": "python/reference/index.html", + "href": "python/reference/index.html", + "title": "1 API Reference", "section": "", - "text": "Open a text editor and create an empty file next to your database, with the .toml extension.\nAdd the following content to the TOML file:\n\n\n\nribasim.toml\n\nstarttime = 2020-01-01 00:00:00\nendtime = 2021-01-01 00:00:00\ndatabase = \"database.gpkg\"\n\n\nUnzip the Ribasim command line interface, ribasim_cli.zip\nOpen your terminal and go to the directory where your TOML is stored. Now run path/to/ribasim_cli/ribasim ribasim.toml. Adjust the path to the ribasim_cli folder to where you placed it. This runs the model.\nIn your model directory there is now a results/ folder with basin.arrow and flow.arrow output files." + "text": "The Model class represents an entire Ribasim model.\n\n\n\nModel\nA full Ribasim model schematisation with all input.\n\n\n\n\n\n\nThe Node and Edge database layers define the network layout.\n\n\n\nNode\nThe Ribasim nodes as Point geometries.\n\n\nEdge\nDefines the connections between nodes.\n\n\n\n\n\n\nAvailable node types to model different situations.\n\n\n\nBasin\nInput for a (sub-)basin: an area of land where all flowing surface water converges to a single point.\n\n\nFractionalFlow\nReceives a fraction of the flow. The fractions must sum to 1.0 for a furcation.\n\n\nLevelBoundary\nStores water at a given level unaffected by flow, like an infinitely large basin.\n\n\nLinearResistance\nFlow through this connection linearly depends on the level difference\n\n\nManningResistance\nFlow through this connection is estimated by conservation of energy and the\n\n\nPump\nPump water from a source node to a destination node.\n\n\nTabulatedRatingCurve\nLinearly interpolates discharge between a tabulation of level and discharge.\n\n\n\n\n\n\nCollection of utility functions.\n\n\n\nutils.geometry_from_connectivity\nCreate edge shapely geometries from connectivities.\n\n\nutils.connectivity_from_geometry\nDerive from_node_id and to_node_id for every edge in lines. LineStrings" }, { - "objectID": "qgis/index.html#sec-results", - "href": "qgis/index.html#sec-results", - "title": "QGIS plugin", + "objectID": "python/reference/index.html#model", + "href": "python/reference/index.html#model", + "title": "1 API Reference", "section": "", - "text": "In QGIS select the model group.\n\n\n\n\n\nIn the Ribasim plugin widget, select the Results tab and click “Associate Results”.\n\n\n\n\n\nSelect results/basin.arrow.\n\n\n\n\n\nThis adds metadata to the model that the iMOD plugin can use to find the timeseries data that is associated to the model nodes.\n\n\n\nClick the “Time Series” button of the iMOD plugin.\n\n\n\n\n\nSelect the variables that you want to plot.\n\n\n\n\n\nClick “Select points” and select a node by dragging a rectangle around it on the map. Hold the Ctrl key to select multiple nodes. Currently only the Basin nodes can be plotted.\n\n\n\n\n\nThe associated time series are shown the the graph." + "text": "The Model class represents an entire Ribasim model.\n\n\n\nModel\nA full Ribasim model schematisation with all input." }, { - "objectID": "contribute/core.html", - "href": "contribute/core.html", - "title": "Julia core development", + "objectID": "python/reference/index.html#network", + "href": "python/reference/index.html#network", + "title": "1 API Reference", "section": "", - "text": "Install Julia via Juliaup as described in its README.\n\n\n\nStart the Julia REPL by executing julia in your terminal. Within the REPL type ] to enter the Pkg REPL. For more information on how to use Pkg, see the Getting Started page in its documentation. There you can add Revise and TestEnv to your global environment.\npkg> add Revise TestEnv\n\n\n\nRevise.jl is a library that allows you to modify code and use the changes without restarting Julia. You can let it start automatically by following these instructions.\n\n\n\nIn order to have the Ribasim repository locally available, you can clone it with Git. Git can be installed from git-scm.com. Once installed, run the following command at a directory of your choice:\nIn order to have the Ribasim repository locally available, run the following command at a directory of your choice:\ngit clone https://github.com/Deltares/Ribasim.git\nTo continue with the following steps, make the root of the repository your working directory by running\ncd Ribasim\n\n\n\nThere is a section on editors and IDEs for Julia on https://julialang.org/, scroll down to see it. We use and recommend Microsoft’s free editor Visual Studio Code. When combined with the Julia extension it provides a powerful and interactive development experience." + "text": "The Node and Edge database layers define the network layout.\n\n\n\nNode\nThe Ribasim nodes as Point geometries.\n\n\nEdge\nDefines the connections between nodes." }, { - "objectID": "contribute/core.html#install-julia-via-juliaup", - "href": "contribute/core.html#install-julia-via-juliaup", - "title": "Julia core development", + "objectID": "python/reference/index.html#node-types", + "href": "python/reference/index.html#node-types", + "title": "1 API Reference", "section": "", - "text": "Install Julia via Juliaup as described in its README." + "text": "Available node types to model different situations.\n\n\n\nBasin\nInput for a (sub-)basin: an area of land where all flowing surface water converges to a single point.\n\n\nFractionalFlow\nReceives a fraction of the flow. The fractions must sum to 1.0 for a furcation.\n\n\nLevelBoundary\nStores water at a given level unaffected by flow, like an infinitely large basin.\n\n\nLinearResistance\nFlow through this connection linearly depends on the level difference\n\n\nManningResistance\nFlow through this connection is estimated by conservation of energy and the\n\n\nPump\nPump water from a source node to a destination node.\n\n\nTabulatedRatingCurve\nLinearly interpolates discharge between a tabulation of level and discharge." }, { - "objectID": "contribute/core.html#install-julia-libraries", - "href": "contribute/core.html#install-julia-libraries", - "title": "Julia core development", + "objectID": "python/reference/index.html#utility-functions", + "href": "python/reference/index.html#utility-functions", + "title": "1 API Reference", "section": "", - "text": "Start the Julia REPL by executing julia in your terminal. Within the REPL type ] to enter the Pkg REPL. For more information on how to use Pkg, see the Getting Started page in its documentation. There you can add Revise and TestEnv to your global environment.\npkg> add Revise TestEnv" + "text": "Collection of utility functions.\n\n\n\nutils.geometry_from_connectivity\nCreate edge shapely geometries from connectivities.\n\n\nutils.connectivity_from_geometry\nDerive from_node_id and to_node_id for every edge in lines. LineStrings" }, { - "objectID": "contribute/core.html#setup-revise.jl", - "href": "contribute/core.html#setup-revise.jl", - "title": "Julia core development", + "objectID": "python/reference/utils.connectivity_from_geometry.html", + "href": "python/reference/utils.connectivity_from_geometry.html", + "title": "1 utils.connectivity_from_geometry", "section": "", - "text": "Revise.jl is a library that allows you to modify code and use the changes without restarting Julia. You can let it start automatically by following these instructions." + "text": "utils.connectivity_from_geometry(node, lines)\nDerive from_node_id and to_node_id for every edge in lines. LineStrings may be used to connect multiple nodes in a sequence, but every linestring vertex must also a node.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nnode\nNode\n\nrequired\n\n\nlines\nnp.ndarray\nArray of shapely linestrings.\nrequired\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nnp.ndarray of int\n\n\n\nnp.ndarray of int" }, { - "objectID": "contribute/core.html#clone-ribasim", - "href": "contribute/core.html#clone-ribasim", - "title": "Julia core development", + "objectID": "python/reference/utils.connectivity_from_geometry.html#parameters", + "href": "python/reference/utils.connectivity_from_geometry.html#parameters", + "title": "1 utils.connectivity_from_geometry", "section": "", - "text": "In order to have the Ribasim repository locally available, you can clone it with Git. Git can be installed from git-scm.com. Once installed, run the following command at a directory of your choice:\nIn order to have the Ribasim repository locally available, run the following command at a directory of your choice:\ngit clone https://github.com/Deltares/Ribasim.git\nTo continue with the following steps, make the root of the repository your working directory by running\ncd Ribasim" + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nnode\nNode\n\nrequired\n\n\nlines\nnp.ndarray\nArray of shapely linestrings.\nrequired" }, { - "objectID": "contribute/core.html#install-visual-studio-code-optional", - "href": "contribute/core.html#install-visual-studio-code-optional", - "title": "Julia core development", + "objectID": "python/reference/utils.connectivity_from_geometry.html#returns", + "href": "python/reference/utils.connectivity_from_geometry.html#returns", + "title": "1 utils.connectivity_from_geometry", "section": "", - "text": "There is a section on editors and IDEs for Julia on https://julialang.org/, scroll down to see it. We use and recommend Microsoft’s free editor Visual Studio Code. When combined with the Julia extension it provides a powerful and interactive development experience." + "text": "Type\nDescription\n\n\n\n\nnp.ndarray of int\n\n\n\nnp.ndarray of int" }, { - "objectID": "contribute/core.html#sec-test", - "href": "contribute/core.html#sec-test", - "title": "Julia core development", - "section": "2.1 Running tests", - "text": "2.1 Running tests\nYou will want to run the testsuite on a regular basis to check if your changes had unexpected side effects. It is also a good way to find out if your development environment is set up correctly.\nBefore the tests can run, you need to prepare model input.\nWith the root of the repository as your working directory you can start the REPL with activated Ribasim environment by running the following:\njulia --project=core\nWhile not technically required, it is advised to import Ribasim first to catch installation issues early on.\njulia> using Ribasim\nThen open the Pkg REPL by typing ] and execute:\npkg> test\nIf you are in a different environment that depends on Ribasim, you can test Ribasim with the following command:\npkg> test Ribasim\nIn order to debug tests, it is very useful to run them in a REPL. However, here, you don’t have the dependencies available in the [extras] section of your Project.toml. TestEnv.jl that we installed earlier solves that problem.\nWhen you then debug your tests inside the REPL, you can include the [extras] dependencies as follows:\nusing TestEnv\nTestEnv.activate()\n\n\n\n\n\n\nTip\n\n\n\nThe Julia VS Code extension allows you to open a REPL with the Ribasim environment already activated: \"julia.environmentPath\": \"Ribasim/core\". That way you don’t have to type activate core every time you open the REPL." + "objectID": "python/reference/TabulatedRatingCurve.html", + "href": "python/reference/TabulatedRatingCurve.html", + "title": "1 TabulatedRatingCurve", + "section": "", + "text": "TabulatedRatingCurve()\nLinearly interpolates discharge between a tabulation of level and discharge.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with constant rating curves.\nrequired\n\n\ntime\npandas.DataFrame\nTable with time-varying rating curves.\nrequired" }, { - "objectID": "contribute/core.html#render-documentation", - "href": "contribute/core.html#render-documentation", - "title": "Julia core development", - "section": "2.2 Render documentation", - "text": "2.2 Render documentation\nExample models are created and simulated as part of the rendering of the documentation. The Julia API reference is created using Documenter.jl by running this command:\npixi run build-julia-docs\nIn order to preview documentation you can run the following command from the docs/ folder. Afterwards, a browser tab will open with the rendered documentation, updating it as you make changes.\npixi run quarto-preview\nThe documentation also includes Jupyter notebooks. Note that they are stored in the repository without any output, and this should stay this way to keep the repository small. The documentation rendering process adds the output by running the notebooks.\n\n\n\n\n\n\nTip\n\n\n\nThe Jupyter VS Code extension allows you to run Jupyter notebooks directly in VS Code." + "objectID": "python/reference/TabulatedRatingCurve.html#parameters", + "href": "python/reference/TabulatedRatingCurve.html#parameters", + "title": "1 TabulatedRatingCurve", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with constant rating curves.\nrequired\n\n\ntime\npandas.DataFrame\nTable with time-varying rating curves.\nrequired" }, { - "objectID": "contribute/core.html#run-ribasim-simulations", - "href": "contribute/core.html#run-ribasim-simulations", - "title": "Julia core development", - "section": "2.3 Run Ribasim simulations", - "text": "2.3 Run Ribasim simulations\nAssuming your working directory is the root of the repository, you can activate this project by entering the Pkg mode of the REPL with ] and execute:\npkg> activate core\npkg> instantiate\nPress backspace to go back to the Julia REPL. There you can run a model with:\njulia> Ribasim.run(\"path/to/model/ribasim.toml\")\n\n\n\n\n\n\nTip\n\n\n\nThe Julia VS Code extension allows you to execute code cells in REPL. This is a very convenient way of executing only parts of your source file." + "objectID": "python/reference/Pump.html", + "href": "python/reference/Pump.html", + "title": "1 Pump", + "section": "", + "text": "Pump()\nPump water from a source node to a destination node. The set flow rate will be pumped unless the intake storage is less than 10m3, in which case the flow rate will be linearly reduced to 0 m3/s. Negative flow rates are not supported. Note that the intake must always be a Basin.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with constant flow rates.\nrequired" + }, + { + "objectID": "python/reference/Pump.html#parameters", + "href": "python/reference/Pump.html#parameters", + "title": "1 Pump", + "section": "", + "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with constant flow rates.\nrequired" + }, + { + "objectID": "couple/modflow-demo.html", + "href": "couple/modflow-demo.html", + "title": "MODFLOW 6 Demonstration", + "section": "", + "text": "In our test cases, we will work with the Dutch national groundwater model (LHM). For testing, we simplify the top boundary conditions to just three surface water “systems”, from large to small:\n\nPrimary\nSecondary\nTertiary\n\nThese systems are separated in the groundwater model schematization due to the relatively small size of the surface waters (several meters in width) in comparison with relatively coarse cells of the groundwater model (250 m): most cells in the LHM contain more than one surface water, and are included via representative parameters which take the physical scaling into account. In case of sufficiently small cell sizes, no overlap occurs and all surface waters can be represented in a single grid.\nRibasim has no knowledge of these systems unless explicitly separated into different (sub-)basins. In the examples below, these three systems are represented by one basin with a single volume. For the purposes of testing, we have not yet created empirical volume-level relationships for the surface water of every cell extracted from a hydraulic model. Instead, we have chosen an (over)simplified parametrization of the hydraulic properties, which makes it easy to verify the behavior of Ribasim and the coupling procedures:\n\nPrimary, secondary, and tertiary systems have a rectangular profile: the area of the surface water does not change with water level or volume.\nWater depth is constant for a system within a basin.\nWater depth increases linearly with volume. (This follows from 1.)\nWater depth is distributed across the systems in a geometric progression: when the tertiary system contains 0.1 m of water, the secondary system contains 0.2 m, and the primary system contains 0.4 m.\nWater depth is 0.0 m for all systems when basin volume is 0.0. (This follows from 4.)\nThe distribution of water occurs according to the surface water area (width times length) used for the LHM parametrization of river bed conductance.\n\nFor freely draining basins, a simplified storage-discharge relationship has been derived as follows:\n\nThe area of the basin polygon has been multiplied by 1 mm/d (roughly the average precipitation excess in the Netherlands). This yields a “normative discharge”.\nA corresponding normative volume has been chosen, corresponding with water depths of 0.4, 0.2, and 0.1 m for the primary, secondary, and tertiary surface waters respectively.\nA dead storage volume has been chosen, corresponding with water depths of 0.2, 0.1, and 0.05 m for the primary, secondary, and tertiary surface waters respectively. The basin only starts discharging when the storage volume exceeds this value.\n\n\n\n\n\n\n\nNote\n\n\n\nRibasim is not limited to such oversimplified parametrization! Ribasim uses tabulations and therefore supports arbitrary (piecewise linear) volume-depth and volume-discharge relationships.\n\n\nA visual representation of this simplified conceptual schematization is given in Figure 1 and Figure 2.\n\n\n\nFigure 1: Distribution of water depths over the primary, secondary, and tertiary system.\n\n\n\n\n\nFigure 2: Discharge as a function of basin storage volume.\n\n\nAn example of the resulting parameters for a single cell is shown in Table 1. The first row shows the water levels when the basin is empty. The level for primary, secondary, and tertiary are equal to the bottom elevation of the surface waters. The second row shows the volume and levels for water depths of 0.4, 0.2, and 0.1 m. The third row shows the volume and levels for a tenfold larger volume. This results in implausible water levels with depths of 4.0, 2.0 and 1.0 m; the water level in the primary system is over two meters higher than in the tertiary system. In reality, the surface waters would overflow and surface ponding would occur; this mechanism is ignored in the test cases for the sake of simplicity.\n\n\nTable 1: Volume-level table for a single cell in the Hupsel basin.\n\n\nVolume (m3)\nPrimary (m NAP)\nSecondary (m NAP)\nTertiary (m NAP)\n\n\n\n\n0.0\n25.65\n25.83\n26.60\n\n\n6843.1\n26.05\n26.03\n26.70\n\n\n68431.0\n29.65\n27.83\n27.60\n\n\n\n\nFigure 3 shows the volume of the first row of the cell based input for the primary system. Symbology is set to unique values. While water levels differ per cell in this parametrization, the “normative volume” defined above is shared by all cells in a basin.\n\n\n\nFigure 3: Basin normative volume of the primary system.\n\n\nFigure 3 shows the water level corresponding to the normative storage volume based input for the primary system (it corresponds to the value shown in the first row of the primary column in Table 1). We see a clear gradient from west to east: as our simplified parametrization assumes a constant water depth for all cells in a single system, water levels spatially fall and rise with the bottom elevation.\n\n\n\nFigure 4: Water level corresponding to the normative basin volume of the primary system." + }, + { + "objectID": "couple/modflow-demo.html#example-parametrization", + "href": "couple/modflow-demo.html#example-parametrization", + "title": "MODFLOW 6 Demonstration", + "section": "", + "text": "In our test cases, we will work with the Dutch national groundwater model (LHM). For testing, we simplify the top boundary conditions to just three surface water “systems”, from large to small:\n\nPrimary\nSecondary\nTertiary\n\nThese systems are separated in the groundwater model schematization due to the relatively small size of the surface waters (several meters in width) in comparison with relatively coarse cells of the groundwater model (250 m): most cells in the LHM contain more than one surface water, and are included via representative parameters which take the physical scaling into account. In case of sufficiently small cell sizes, no overlap occurs and all surface waters can be represented in a single grid.\nRibasim has no knowledge of these systems unless explicitly separated into different (sub-)basins. In the examples below, these three systems are represented by one basin with a single volume. For the purposes of testing, we have not yet created empirical volume-level relationships for the surface water of every cell extracted from a hydraulic model. Instead, we have chosen an (over)simplified parametrization of the hydraulic properties, which makes it easy to verify the behavior of Ribasim and the coupling procedures:\n\nPrimary, secondary, and tertiary systems have a rectangular profile: the area of the surface water does not change with water level or volume.\nWater depth is constant for a system within a basin.\nWater depth increases linearly with volume. (This follows from 1.)\nWater depth is distributed across the systems in a geometric progression: when the tertiary system contains 0.1 m of water, the secondary system contains 0.2 m, and the primary system contains 0.4 m.\nWater depth is 0.0 m for all systems when basin volume is 0.0. (This follows from 4.)\nThe distribution of water occurs according to the surface water area (width times length) used for the LHM parametrization of river bed conductance.\n\nFor freely draining basins, a simplified storage-discharge relationship has been derived as follows:\n\nThe area of the basin polygon has been multiplied by 1 mm/d (roughly the average precipitation excess in the Netherlands). This yields a “normative discharge”.\nA corresponding normative volume has been chosen, corresponding with water depths of 0.4, 0.2, and 0.1 m for the primary, secondary, and tertiary surface waters respectively.\nA dead storage volume has been chosen, corresponding with water depths of 0.2, 0.1, and 0.05 m for the primary, secondary, and tertiary surface waters respectively. The basin only starts discharging when the storage volume exceeds this value.\n\n\n\n\n\n\n\nNote\n\n\n\nRibasim is not limited to such oversimplified parametrization! Ribasim uses tabulations and therefore supports arbitrary (piecewise linear) volume-depth and volume-discharge relationships.\n\n\nA visual representation of this simplified conceptual schematization is given in Figure 1 and Figure 2.\n\n\n\nFigure 1: Distribution of water depths over the primary, secondary, and tertiary system.\n\n\n\n\n\nFigure 2: Discharge as a function of basin storage volume.\n\n\nAn example of the resulting parameters for a single cell is shown in Table 1. The first row shows the water levels when the basin is empty. The level for primary, secondary, and tertiary are equal to the bottom elevation of the surface waters. The second row shows the volume and levels for water depths of 0.4, 0.2, and 0.1 m. The third row shows the volume and levels for a tenfold larger volume. This results in implausible water levels with depths of 4.0, 2.0 and 1.0 m; the water level in the primary system is over two meters higher than in the tertiary system. In reality, the surface waters would overflow and surface ponding would occur; this mechanism is ignored in the test cases for the sake of simplicity.\n\n\nTable 1: Volume-level table for a single cell in the Hupsel basin.\n\n\nVolume (m3)\nPrimary (m NAP)\nSecondary (m NAP)\nTertiary (m NAP)\n\n\n\n\n0.0\n25.65\n25.83\n26.60\n\n\n6843.1\n26.05\n26.03\n26.70\n\n\n68431.0\n29.65\n27.83\n27.60\n\n\n\n\nFigure 3 shows the volume of the first row of the cell based input for the primary system. Symbology is set to unique values. While water levels differ per cell in this parametrization, the “normative volume” defined above is shared by all cells in a basin.\n\n\n\nFigure 3: Basin normative volume of the primary system.\n\n\nFigure 3 shows the water level corresponding to the normative storage volume based input for the primary system (it corresponds to the value shown in the first row of the primary column in Table 1). We see a clear gradient from west to east: as our simplified parametrization assumes a constant water depth for all cells in a single system, water levels spatially fall and rise with the bottom elevation.\n\n\n\nFigure 4: Water level corresponding to the normative basin volume of the primary system." + }, + { + "objectID": "couple/modflow-demo.html#example-configuration", + "href": "couple/modflow-demo.html#example-configuration", + "title": "MODFLOW 6 Demonstration", + "section": "2 Example: Configuration", + "text": "2 Example: Configuration\nAn example of the MODFLOW 6 section of TOML configuration required for a coupled run can be seen below:\n[modflow]\nsimulation = \"../data/hupsel/mfsim.nam\"\nmode = \"sequential\"\ntimestep = 86400.0\n\n[modflow.models]\n\n[modflow.models.gwf]\ntype = \"gwf\"\ndataset = \"../data/volume_level_profile-hupsel.nc\"\nbasins = \"basin_id\"\n\n[[modflow.models.gwf.bounds]]\nriver = \"RIV_P\"\ndrain = \"DRN_P\"\nprofile = \"profile_primary\"\n\n[[modflow.models.gwf.bounds]]\nriver = \"RIV_S\"\ndrain = \"DRN_S\"\nprofile = \"profile_secondary\"\n\n[[modflow.models.gwf.bounds]]\ndrain = \"DRN_T\"\nprofile = \"profile_tertiary\"\nThe section starts by stating the path to the MODFLOW 6 simulation name file (simulation). The next section contains the information regarding the MODFLOW 6 model(s) to couple to Ribasim’s basins. Per model, a path to the coupling parameter dataset is provided (dataset), along with the variable to use as the basin identification number (basins). Next, for every boundary condition that should be coupled to Ribasim, the package names (river, drain) used by MODFLOW 6 must be specified (as we look for these names in the MODFLOW 6 memory), along with the name of the variable in the coupling dataset which provides the volume-level relationship (profile).\nAs can be seen in the example, the coupling mechanism supports coupling of:\n\nA single drainage package (drain entry).\nA single river package (river entry).\nA combination of river and drainage package (when infiltration conductance does not equal drainage conductance) both (river and drain entry)." + }, + { + "objectID": "couple/modflow-demo.html#test-case-hupsel", + "href": "couple/modflow-demo.html#test-case-hupsel", + "title": "MODFLOW 6 Demonstration", + "section": "3 Test case: Hupsel", + "text": "3 Test case: Hupsel\nTo test the coupling, the following simulations have been setup and run:\n\nA standalone MODFLOW 6 run of sequential steady-states (i.e. no storage) with differing groundwater recharge values.\nA coupled run where the MODFLOW 6 stages are updated by the Ribasim coupler process, but without Ribasim. This results in volumes of 0.0, so all MODFLOW 6 water levels are set equal to bed elevation.\nA coupled run where the water levels are updated by Ribasim.\n\nFrom these tests, we expect the following behavior:\n\nDrainage terms should remain largely the same when the water level is lowered in a steady-state: the amount of recharge is fixed, and this is locally drained.\nIn case of negative recharge (evapotranspiration), infiltration occurs in the surface waters. Infiltration should be zero when the basin volume is 0.\n\n\n\n\nFigure 5: Water balance of the MODFLOW 6 boundary conditions for the Hupsel basin for a standalone MODFLOW 6 run. The four sequential steady states (01, 02, 03, 04) use net groundwater recharge values of 1.0, 0.5, -0.05 and -0.1 mm/d.\n\n\nFigure 5 shows the water balance of steady-state for submodel of the LHM that has been by selecting the cells belonging to the district containing the Hupsel catch, the Berkel.\nThe Hupsel basin show the expected behavior: for a net groundwater recharge of 1.0 mm/d, most is precipitation with a minor part lateral inflow from higher areas. In terms of outgoing flows, most of the precipitation ends up in the surface water, primarily in the many ditches of the tertiary system. Only a relatively small part of the water leaves the basin via the groundwater. Interbasin flows through the groundwater form such a minor role, as the aquifer is thin and transmissivity is limited.\nReducing groundwater recharge to 0.5 mm/d reduces all flows, with the tertiary system playing a less dominant role, relatively speaking: as its elevation is the highest compared to the primary and secondary system, the head difference is reduced strongest for the tertiary system.\nWith evapotranspiration (ET) excess (-0.05 and 0.1 mm/d; low values are chosen here since most ET would be drawn from storage, which is not available in a steady-state model), the surface waters provide mostly inflow, and recharge is a negative term. In this case, the secondary system provides a small amount of infiltration; most of the water is drawn from the surroundings instead.\n\n\n\nFigure 6: Water balance of the MODFLOW 6 boundary conditions for the Hupsel basin for a zero volume run. The four sequential steady states (01, 02, 03, 04) use net groundwater recharge values of 1.0, 0.5, -0.05 and -0.1 mm/d.\n\n\nFigure 6 shows the same model, with 0-basin volume which causes water levels to be set equal to bed elevation. Consequently, primary and secondary outflow terms are larger for positive groundwater recharge as they drain at a lower level and intercept the water before the tertiary system does. Secondly, with negative groundwater recharge, no infiltration occurs and the water is drawn from the surroundings instead. This shows the coupling mechanism adjusting MODFLOW 6 water levels successfully." + }, + { + "objectID": "couple/modflow-demo.html#test-case-de-tol", + "href": "couple/modflow-demo.html#test-case-de-tol", + "title": "MODFLOW 6 Demonstration", + "section": "4 Test case: de Tol", + "text": "4 Test case: de Tol\nTo test the coupling, the following simulations have been setup and run:\n\nA standalone MODFLOW 6 run of sequential steady-states (i.e. no storage) with differing groundwater recharge values.\nA coupled run where the MODFLOW 6 stages are updated by the Ribasim coupler process, but without Ribasim. This results in volumes of 0.0, so all MODFLOW 6 water levels are set equal to bed elevation.\nA coupled run where the water levels are updated by Ribasim.\n\n\n\n\nFigure 7: Water balance of the MODFLOW 6 boundary conditions for De Tol basin for a standalone MODFLOW 6 run. The four sequential steady states (01, 02, 03, 04) use net groundwater recharge values of 1.0, 0.5, -0.05 and -0.1 mm/d.\n\n\nFigure 7 shows the water balance of steady-state for a submodel of the LHM for the Polder de Tol and its surroundings. While groundwater recharge is the dominant ingoing flow, lateral groundwater flow (over the entire depth of the groundwater model) is a sizable inflow for the area; the larger lateral inflow shows that De Tol is a net receiver of groundwater which is mostly discharged through the secondary system. In contrast to the Hupsel, the tertiary system is almost entirely absent: drainage occurs not through ephemeral tertiary ditches, but by the permanently water-bearing ditches of the primary and secondary system. Unlike the Hupsel, the water balance does not shrink to very small discharges, as there is sizable regional groundwater flow.\n\n\n\nFigure 8: Water balance of the MODFLOW 6 boundary conditions for De Tol basin for a zero volume run. The four sequential steady states (01, 02, 03, 04) use net groundwater recharge values of 1.0, 0.5, -0.05 and -0.1 mm/d.\n\n\nFigure 8 shows the same model, with 0-basin volume which causes water levels to be set equal to bed elevation. The total discharge is larger: the primary and secondary systems are set to lower levels, and so the head difference is larger. While De Tol’s evapotranspiration excess can be fed by the regional groundwater, the primary and secondary ditches also provide some part; as expected, they do not feed when the coupling mechanism adjusts MODFLOW 6’s water levels." }, { "objectID": "contribute/python.html", @@ -560,81 +700,67 @@ "text": "To run our linting suite locally, execute:\npixi run lint" }, { - "objectID": "contribute/release.html", - "href": "contribute/release.html", - "title": "Release process", + "objectID": "contribute/core.html", + "href": "contribute/core.html", + "title": "Julia core development", "section": "", - "text": "The Ribasim repository contains several components, e.g., the Julia core, the Python tooling and QGIS plugin. The components are currently only guaranteed to work together if they are built at the same time. Therefore we release Ribasim as a collection of all the components at once. For maximum interoperability it is suggested to only release all components together, and not individually.\nFor these releases we use Calender Versioning, which makes it clear in which month the release was made." + "text": "Install Julia via Juliaup as described in its README.\n\n\n\nStart the Julia REPL by executing julia in your terminal. Within the REPL type ] to enter the Pkg REPL. For more information on how to use Pkg, see the Getting Started page in its documentation. There you can add Revise and TestEnv to your global environment.\npkg> add Revise TestEnv\n\n\n\nRevise.jl is a library that allows you to modify code and use the changes without restarting Julia. You can let it start automatically by following these instructions.\n\n\n\nIn order to have the Ribasim repository locally available, you can clone it with Git. Git can be installed from git-scm.com. Once installed, run the following command at a directory of your choice:\nIn order to have the Ribasim repository locally available, run the following command at a directory of your choice:\ngit clone https://github.com/Deltares/Ribasim.git\nTo continue with the following steps, make the root of the repository your working directory by running\ncd Ribasim\n\n\n\nThere is a section on editors and IDEs for Julia on https://julialang.org/, scroll down to see it. We use and recommend Microsoft’s free editor Visual Studio Code. When combined with the Julia extension it provides a powerful and interactive development experience." }, { - "objectID": "contribute/release.html#pre-release-checks", - "href": "contribute/release.html#pre-release-checks", - "title": "Release process", - "section": "2.1 Pre-release checks", - "text": "2.1 Pre-release checks\nBefore starting the release process, ensure that all tests are passing and that all features intended for the release are complete and merged into the main branch." + "objectID": "contribute/core.html#install-julia-via-juliaup", + "href": "contribute/core.html#install-julia-via-juliaup", + "title": "Julia core development", + "section": "", + "text": "Install Julia via Juliaup as described in its README." }, { - "objectID": "contribute/release.html#update-version-numbers-of-the-components-as-needed", - "href": "contribute/release.html#update-version-numbers-of-the-components-as-needed", - "title": "Release process", - "section": "2.2 Update version numbers of the components as needed", - "text": "2.2 Update version numbers of the components as needed\nThe components have their own version number which generally uses Semantic Versioning, with minor version signifying a breaking release for pre-1.0 versions, as documented here. If a component did not change at all between releases, the version number can stay the same.\nNow submit a pull request which updates the version numbers of the components as needed. You can use PR #623 as an example.\nIn general for Python packages the version number is in __init__.py, for Julia it is Project.toml, and for QGIS metadata.txt" + "objectID": "contribute/core.html#install-julia-libraries", + "href": "contribute/core.html#install-julia-libraries", + "title": "Julia core development", + "section": "", + "text": "Start the Julia REPL by executing julia in your terminal. Within the REPL type ] to enter the Pkg REPL. For more information on how to use Pkg, see the Getting Started page in its documentation. There you can add Revise and TestEnv to your global environment.\npkg> add Revise TestEnv" }, { - "objectID": "contribute/release.html#sec-wheel-links", - "href": "contribute/release.html#sec-wheel-links", - "title": "Release process", - "section": "2.3 Update the wheel links", - "text": "2.3 Update the wheel links\nThe nightly download links for the Ribasim Python wheels contain the version number. Search for “any.whl” and update these to the new version number of Ribasim Python." + "objectID": "contribute/core.html#setup-revise.jl", + "href": "contribute/core.html#setup-revise.jl", + "title": "Julia core development", + "section": "", + "text": "Revise.jl is a library that allows you to modify code and use the changes without restarting Julia. You can let it start automatically by following these instructions." }, { - "objectID": "contribute/release.html#create-a-new-release", - "href": "contribute/release.html#create-a-new-release", - "title": "Release process", - "section": "2.4 Create a new release", - "text": "2.4 Create a new release\nCreate a new release. Give it a tag like v2023.08.0, filling in the current year, month and a sequential “MICRO” number. This follows vYYYY.0M.MICRO from calver. For v2023.09.0 I used the “Generate release notes” button, which I then manually edited to copy the most important changes for users to the top in the form of Keep a Changelog. The possibly long list of generated release notes can put below an “All changes” collapsed item as such:\n<details>\n<summary>\nAll changes\n</summary>\n\n# Put Github flavored markdown here\n\n</details>" + "objectID": "contribute/core.html#clone-ribasim", + "href": "contribute/core.html#clone-ribasim", + "title": "Julia core development", + "section": "", + "text": "In order to have the Ribasim repository locally available, you can clone it with Git. Git can be installed from git-scm.com. Once installed, run the following command at a directory of your choice:\nIn order to have the Ribasim repository locally available, run the following command at a directory of your choice:\ngit clone https://github.com/Deltares/Ribasim.git\nTo continue with the following steps, make the root of the repository your working directory by running\ncd Ribasim" }, { - "objectID": "contribute/release.html#release-ribasim-python-to-pypi", - "href": "contribute/release.html#release-ribasim-python-to-pypi", - "title": "Release process", - "section": "2.5 Release Ribasim Python to PyPI", - "text": "2.5 Release Ribasim Python to PyPI\nTo be able to do pip install ribasim, Ribasim Python needs to be released on the Python Package Index, see these instructions" - }, - { - "objectID": "contribute/release.html#sec-teamcity", - "href": "contribute/release.html#sec-teamcity", - "title": "Release process", - "section": "2.6 Wait for TeamCity to build the new release", - "text": "2.6 Wait for TeamCity to build the new release\nCurrently TeamCity is set to build a release at the night after it has been tagged.\nIf this succeeds, the release assets are uploaded to an S3 link with the version number in the URL, as show here:\nhttps://ribasim.s3.eu-west-3.amazonaws.com/teamcity/Ribasim_Ribasim/BuildRibasimCliWindows/v2023.07.0/ribasim_cli.zip\nhttps://ribasim.s3.eu-west-3.amazonaws.com/teamcity/Ribasim_Ribasim/BuildRibasimCliWindows/v2023.07.0/ribasim-0.4.0-py3-none-any.whl\nhttps://ribasim.s3.eu-west-3.amazonaws.com/teamcity/Ribasim_Ribasim/BuildRibasimCliWindows/v2023.07.0/ribasim_qgis.zip\n\n\n\n\n\n\nNote\n\n\n\nA non-existent version number v2023.07.0 is used in these links. Replace with the version number of the new release. Similarly the filename of the Ribasim Python wheel needs to be updated as in Section 2.3." - }, - { - "objectID": "contribute/release.html#do-manual-checks", - "href": "contribute/release.html#do-manual-checks", - "title": "Release process", - "section": "2.7 Do manual checks", - "text": "2.7 Do manual checks\nOur continuous integration (CI) should have caught most issues. A current weak spot in our testing is the QGIS plugin, so it is a good idea to do some manual checks to see if it works properly. It is a good idea to load new test models if there are any, or test any other changed functionality." + "objectID": "contribute/core.html#install-visual-studio-code-optional", + "href": "contribute/core.html#install-visual-studio-code-optional", + "title": "Julia core development", + "section": "", + "text": "There is a section on editors and IDEs for Julia on https://julialang.org/, scroll down to see it. We use and recommend Microsoft’s free editor Visual Studio Code. When combined with the Julia extension it provides a powerful and interactive development experience." }, { - "objectID": "contribute/release.html#generate-and-upload-test-models", - "href": "contribute/release.html#generate-and-upload-test-models", - "title": "Release process", - "section": "2.8 Generate and upload test models", - "text": "2.8 Generate and upload test models\nThe test models are currently not automatically uploaded. Create them locally with:\npixi run generate-testmodels\nNote that this only includes the test model data, no results. And zip the generated_testmodels directory to generated_testmodels.zip, and add these to the release assets. Click the edit pencil icon to be able to upload it." + "objectID": "contribute/core.html#sec-test", + "href": "contribute/core.html#sec-test", + "title": "Julia core development", + "section": "2.1 Running tests", + "text": "2.1 Running tests\nYou will want to run the testsuite on a regular basis to check if your changes had unexpected side effects. It is also a good way to find out if your development environment is set up correctly.\nBefore the tests can run, you need to prepare model input.\nWith the root of the repository as your working directory you can start the REPL with activated Ribasim environment by running the following:\njulia --project=core\nWhile not technically required, it is advised to import Ribasim first to catch installation issues early on.\njulia> using Ribasim\nThen open the Pkg REPL by typing ] and execute:\npkg> test\nIf you are in a different environment that depends on Ribasim, you can test Ribasim with the following command:\npkg> test Ribasim\nIn order to debug tests, it is very useful to run them in a REPL. However, here, you don’t have the dependencies available in the [extras] section of your Project.toml. TestEnv.jl that we installed earlier solves that problem.\nWhen you then debug your tests inside the REPL, you can include the [extras] dependencies as follows:\nusing TestEnv\nTestEnv.activate()\n\n\n\n\n\n\nTip\n\n\n\nThe Julia VS Code extension allows you to open a REPL with the Ribasim environment already activated: \"julia.environmentPath\": \"Ribasim/core\". That way you don’t have to type activate core every time you open the REPL." }, { - "objectID": "contribute/release.html#upload-artifacts-from-s3-to-github-release-assets", - "href": "contribute/release.html#upload-artifacts-from-s3-to-github-release-assets", - "title": "Release process", - "section": "2.9 Upload artifacts from S3 to GitHub release assets", - "text": "2.9 Upload artifacts from S3 to GitHub release assets\nAgain edit the release assets. Now upload the files downloaded from S3 as mentioned in Section 2.6." + "objectID": "contribute/core.html#render-documentation", + "href": "contribute/core.html#render-documentation", + "title": "Julia core development", + "section": "2.2 Render documentation", + "text": "2.2 Render documentation\nExample models are created and simulated as part of the rendering of the documentation. The Julia API reference is created using Documenter.jl by running this command:\npixi run build-julia-docs\nIn order to preview documentation you can run the following command from the docs/ folder. Afterwards, a browser tab will open with the rendered documentation, updating it as you make changes.\npixi run quarto-preview\nThe documentation also includes Jupyter notebooks. Note that they are stored in the repository without any output, and this should stay this way to keep the repository small. The documentation rendering process adds the output by running the notebooks.\n\n\n\n\n\n\nTip\n\n\n\nThe Jupyter VS Code extension allows you to run Jupyter notebooks directly in VS Code." }, { - "objectID": "contribute/release.html#announce-release", - "href": "contribute/release.html#announce-release", - "title": "Release process", - "section": "2.10 Announce release", - "text": "2.10 Announce release\nAnnounce the release in appropriate channels. Include a link to the release notes and assets, which is whatever this resolves to at that time. Also include a link to the documentation." + "objectID": "contribute/core.html#run-ribasim-simulations", + "href": "contribute/core.html#run-ribasim-simulations", + "title": "Julia core development", + "section": "2.3 Run Ribasim simulations", + "text": "2.3 Run Ribasim simulations\nAssuming your working directory is the root of the repository, you can activate this project by entering the Pkg mode of the REPL with ] and execute:\npkg> activate core\npkg> instantiate\nPress backspace to go back to the Julia REPL. There you can run a model with:\njulia> Ribasim.run(\"path/to/model/ribasim.toml\")\n\n\n\n\n\n\nTip\n\n\n\nThe Julia VS Code extension allows you to execute code cells in REPL. This is a very convenient way of executing only parts of your source file." }, { "objectID": "contribute/index.html", @@ -643,48 +769,6 @@ "section": "", "text": "Ribasim welcomes contributions.\nThere is developer documentation for the Julia core and Python tooling. A guide on how to add a new node type to both is written in adding node types. Release process describes the steps to follow when creating a new Ribasim release." }, - { - "objectID": "contribute/addnode.html", - "href": "contribute/addnode.html", - "title": "Adding node types", - "section": "", - "text": "Several parts of the code have to be made aware of the new node type. In the rest of this page we shall call our new node type NewNodeType." - }, - { - "objectID": "contribute/addnode.html#parameters", - "href": "contribute/addnode.html#parameters", - "title": "Adding node types", - "section": "1.1 Parameters", - "text": "1.1 Parameters\nThe parameters object (defined in solve.jl) passed to the ODE solver must be made aware of the new node type. Therefore define a struct in solve.jl which holds the data for each node of the new node type:\nstruct NewNodeType\n node_id::Vector{Int}\n # Other fields\nend\nThese fields do not have to correspond 1:1 with the input tables (see below). The vector with all node IDs that are of the new type in a given model is a mandatory field. Now you can:\n\nAdd new_node_type::NewNodeType to the Parameters object;\nAdd new_node_type = NewNodeType(db,config) to the function Parameters in create.jl and add new_node_type at the proper location in the Parameters constructor call." - }, - { - "objectID": "contribute/addnode.html#reading-from-configuration", - "href": "contribute/addnode.html#reading-from-configuration", - "title": "Adding node types", - "section": "1.2 Reading from configuration", - "text": "1.2 Reading from configuration\nThere can be several schemas associated with a single node type. To define a schema for the new node type, add the following to validation.jl:\n@schema \"ribasim.newnodetype.static\" NewNodeTypeStatic\n\n\"\"\"\nnode_id: node ID of the NewNodeType node\n\"\"\"\n@version NewNodeTypeStaticV1 begin\n node_id::Int\n # Other fields\nend\nHere Static refers to data that does not change over time. For naming conventions of these schemas see Node usage.\nvalidation.jl also deals with checking and applying a specific sorting order for the tabular data (default is sorting by node ID only), see sort_by_function and sorted_table!.\nNow we define the function that is called in the second bullet above, in create.jl:\nfunction NewNodeType(db::DB, config::Config)::NewNodeType\n static = load_structvector(db, config, NewNodeTypeStaticV1)\n defaults = (; foo = 1, bar = false)\n # Process potential control states in the static data\n parsed_parameters, valid = parse_static_and_time(db, config, \"Outlet\"; static, defaults)\n\n if !valid\n error(\"Errors occurred when parsing NewNodeType data.\")\n end\n\n # Unpack the fields of static as inputs for the NewNodeType constructor\n return NewNodeType(\n parsed_parameters.node_id,\n parsed_parameters.some_property,\n parsed_parameters.control_mapping)\nend" - }, - { - "objectID": "contribute/addnode.html#node-behavior", - "href": "contribute/addnode.html#node-behavior", - "title": "Adding node types", - "section": "1.3 Node behavior", - "text": "1.3 Node behavior\nIn general if the new node type dictates flow, the behaviour of the new node in the Ribasim core is defined in a method of the formulate_flow! function, which is called within the water_balance! (both in solve.jl) function being the right hand side of the system of differential equations solved by Ribasim. Here the details depend highly on the specifics of the node type. An example structure of a formulate_flow! method is given below.\nfunction formulate_flow!(new_node_type::NewNodeType, p::Parameters)::Nothing\n # Retrieve relevant parameters\n (; connectivity) = p\n (; flow) = connectivity\n (; node_id, param_1, param_2) = new_node_type\n\n # Loop over nodes of NewNodeType\n for (i, id) in enumerate(node_id)\n # compute e.g. flow based on param_1[i], param_2[i]\n end\n\n return nothing\nend\nIf the new node type is non-conservative, meaning it either adds or removes water from the model, these boundary flows also need to be recorded. This is done by storing it on the diagonal of the flow[from, to] matrix, e.g. flow[id, id] = q, where q is positive for water added to the model. Non-conservative node types need to be added to the nonconservative_nodetypes set such that this diagonal is set to a nonzero on creating the flow sparse matrix in the Connectivity constructor." - }, - { - "objectID": "contribute/addnode.html#the-jacobian", - "href": "contribute/addnode.html#the-jacobian", - "title": "Adding node types", - "section": "1.4 The Jacobian", - "text": "1.4 The Jacobian\nSee Equations for a mathematical description of the Jacobian.\nBefore the Julia core runs its simulation, the sparsity structure jac_prototype of \\(J\\) is determined with get_jac_prototype in utils.jl. This function runs trough all node types and looks for nodes that create dependencies between states. It creates a sparse matrix of zeros and ones, where the ones denote locations of possible non-zeros in \\(J\\).\nWe divide the various node types in groups based on what type of state dependencies they yield, and these groups are discussed below. Each group has its own method update_jac_prototype! in utils.jl for the sparsity structure induced by nodes of that group. NewNodeType should be added to the signature of one these methods, or to the list of node types that do not contribute to the Jacobian in the method of update_jac_prototype! whose signature contains node::AbstractParameterNode. Of course it is also possible that a new method of update_jac_prototype! has to be introduced.\nThe current dependency groups are:\n\nOut-neighbor dependencies: examples are TabulatedRatingCurve, Pump (the latter only in the reduction factor regime and not PID controlled). If the in-neighbor of a node of this group is a basin, then the storage of this basin affects itself and the storage of the outneighbor (or the basin one node further if it is connected with a FractionalFlow in between) if that is also a basin;\nEither-neighbor dependencies: examples are LinearResistance, ManningResistance. If either the in-neighbor or out-neighbor of a node of this group is a basin, the storage of this basin depends on itself. If both the in-neighbor and the out-neighbor are basins, their storages also depend on eachother.\nThe PidControl node is a special case which is discussed in equations.\n\nUsing jac_prototype the Jacobian of water_balance! is computed automatically using ForwardDiff.jl with memory management provided by PreallocationTools.jl. These computations make use of DiffCache and dual numbers." - }, - { - "objectID": "contribute/addnode.html#python-class", - "href": "contribute/addnode.html#python-class", - "title": "Adding node types", - "section": "2.1 Python class", - "text": "2.1 Python class\nCreate a new file python/ribasim/ribasim/node_types/new_node_type.py which is structured as follows:\nfrom typing import Optional\n\nimport pandera as pa\nfrom pandera.engines.pandas_engine import PydanticModel\nfrom pandera.typing import DataFrame\n\nfrom ribasim import models\nfrom ribasim.input_base import TableModel\n\n__all__ = (\"NewNodeType\",)\n\nclass StaticSchema(pa.SchemaModel):\n class Config:\n \"\"\"Config with dataframe-level data type.\"\"\"\n\n dtype = PydanticModel(models.NewNodeTypeStatic)\n\n# Possible other schemas\n\n\nclass NewNodeType(TableModel):\n \"\"\"\n Description of this node type.\n\n Parameters\n ----------\n static: pandas.DataFrame\n table with data for this node type.\n\n possible other schemas\n \"\"\"\n\n static: Optional[DataFrame[StaticSchema]] = None\n # possible other schemas\n\n class Config:\n validate_assignment = True\n\n def sort(self):\n self.static.sort_values(\"node_id\", ignore_index=True, inplace=True)\nThe sort method should implement the same sorting as in validation.jl.\nNow in both python/ribasim/ribasim/__init__.py and python/ribasim/ribasim/node_types/__init__.py add\n\nfrom ribasim.node_types.new_node_type import NewNodeType;\n\"NewNodeType\" to __all__.\n\nIn python/ribasim/ribasim/model.py, add\n\nfrom ribasim.new_node_type import NewNodeType;\nnew_node_type as a parameter and in the docstring of the Model class.\n\nIn python/ribasim/ribasim/geometry/node.py add a color and shape description in the MARKERS and COLORS dictionaries." - }, { "objectID": "src/index.html", "href": "src/index.html", @@ -728,262 +812,178 @@ "text": "Modules = [Ribasim, Ribasim.config]\nOrder = [:macro]" }, { - "objectID": "core/equations.html", - "href": "core/equations.html", - "title": "Equations", - "section": "", - "text": "Ribasim currently simulates the following “natural” water balance terms:\nAdditionally, Ribasim simulates the following “allocated” water balance terms:\nDepending on the type of boundary conditions, Ribasim requires relation between storage volume and wetted area \\(A\\), and between the storage volume and the water level \\(h\\). These are (currently) represented by piecewise linear relationships." - }, - { - "objectID": "core/equations.html#the-jacobian", - "href": "core/equations.html#the-jacobian", - "title": "Equations", - "section": "1.1 The Jacobian", - "text": "1.1 The Jacobian\nThe Jacobian is a \\(n\\times n\\) matrix where \\(n\\) is the number of states in the simulation. The Jacobian is computed either using finite difference methods or automatic differentiation. For more details on the computation of the Jacobian and how it is used in the solvers see numerical considerations.\nThe entries of the Jacobian \\(J\\) are given by \\[\nJ[i,j] = \\frac{\\partial f_j}{\\partial u_i},\n\\]\nhence \\(J[i,j]\\) quantifies how \\(f_j\\), the derivative of state \\(j\\) with respect to time, changes with a change in state \\(i\\). If a node creates dependendies between basin storages (or other states), then this yields contributions to the Jacobian. If \\(j\\) corresponds to a storage state, then\n\\[\nJ[i,j] = \\sum_{(i',j') \\in E | j' = i} \\frac{\\partial Q_{i',j'}}{\\partial u_i} - \\sum_{(i',j') \\in E | i' = i} \\frac{\\partial Q_{i',j'}}{\\partial u_i},\n\\]\nMost of these terms are always \\(0\\), because a flow over an edge only depends on a small number of states. Therefore the matrix \\(J\\) is very sparse.\nFor many contributions to the Jacobian the derivative of the level \\(l(S)\\) of a basin with respect to its storage \\(S\\) is required. To get an expression for this, we first look at the storage as a function of the level:\n\\[\nS(l) = \\int_{l_0}^l A(\\ell)d\\ell.\n\\]\nFrom this we obtain \\(S'(l) = A(l)\\) and thus \\[\n\\frac{\\text{d}l}{\\text{d}S} = \\frac{1}{A(S)}.\n\\]\n\n\n\n\n\n\nNote\n\n\n\nThe presence of division by the basin area means that areas of size zero are not allowed." - }, - { - "objectID": "core/equations.html#sec-reduction_factor", - "href": "core/equations.html#sec-reduction_factor", - "title": "Equations", - "section": "2.1 The reduction factor", - "text": "2.1 The reduction factor\nAt several points in the equations below a reduction factor is used. This is a term that makes certain transitions more smooth, for instance when a pump stops providing water when its source basin dries up. The reduction factor is given by\n\\[\n \\phi(x; p) =\n \\begin{align}\n \\begin{cases}\n 0 &\\text{if}\\quad x < 0 \\\\\n -2 \\left(\\frac{x}{p}\\right)^3 + 3\\left(\\frac{x}{p}\\right)^2 &\\text{if}\\quad 0 \\le x \\le p \\\\\n 1 &\\text{if}\\quad x > p\n \\end{cases}\n \\end{align},\n\\]\nwhere \\(p > 0\\) is the threshold value which determines the interval \\([0,p]\\) of the smooth transition between \\(0\\) and \\(1\\), see the plot below.\n\n\nCode\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef f(x, p = 3):\n x_scaled = x / p\n phi = (-2 * x_scaled + 3) * x_scaled**2\n phi = np.where(x < 0, 0, phi)\n phi = np.where(x > p, 1, phi)\n\n return phi\n\nfontsize = 15\np = 3\nN = 100\nx_min = -1\nx_max = 4\nx = np.linspace(x_min,x_max,N)\nphi = f(x,p)\n\nfig,ax = plt.subplots(dpi=80)\nax.plot(x,phi)\n\ny_lim = ax.get_ylim()\n\nax.set_xticks([0,p], [0,\"$p$\"], fontsize=fontsize)\nax.set_yticks([0,1], [0,1], fontsize=fontsize)\nax.hlines([0,1],x_min,x_max, color = \"k\", ls = \":\", zorder=-1)\nax.vlines([0,p], *y_lim, color = \"k\", ls = \":\")\nax.set_xlim(x_min,x_max)\nax.set_xlabel(\"$x$\", fontsize=fontsize)\nax.set_ylabel(\"$\\phi(x;p)$\", fontsize=fontsize)\nax.set_ylim(y_lim)\n\nfig.tight_layout()\nplt.show()" - }, - { - "objectID": "core/equations.html#precipitation", - "href": "core/equations.html#precipitation", - "title": "Equations", - "section": "2.2 Precipitation", - "text": "2.2 Precipitation\nThe precipitation term is given by\n\\[\n Q_P = P \\cdot A(S).\n\\tag{2}\\]\nHere \\(P = P(t)\\) is the precipitation rate and \\(A\\) is the wetted area. \\(A\\) is a function of the storage \\(S = S(t)\\): as the volume of water changes, the area of the free water surface may change as well, depending on the slopes of the surface waters." - }, - { - "objectID": "core/equations.html#evaporation", - "href": "core/equations.html#evaporation", - "title": "Equations", - "section": "2.3 Evaporation", - "text": "2.3 Evaporation\nThe evaporation term is given by\n\\[\n Q_E = E_\\text{pot} \\cdot A(S) \\cdot \\phi(d;0.1).\n\\tag{3}\\]\nHere \\(E_\\text{pot} = E_\\text{pot}(t)\\) is the potential evaporation rate and \\(A\\) is the wetted area. \\(\\phi\\) is the reduction factor which depends on the depth \\(d\\). It provides a smooth gradient as \\(S \\rightarrow 0\\).\nA straightforward formulation \\(Q_E = \\mathrm{max}(E_\\text{pot} A(S), 0)\\) is unsuitable, as \\(\\frac{\\mathrm{d}Q_E}{\\mathrm{d}S}(S=0)\\) is then not well-defined.\n\nA non-smooth derivative results in extremely small timesteps and long computation time: ModelingToolkit identifies the singular behavior and adjusts its timestepping. In a physical interpretation, evaporation is switched on or off per individual droplet of water. In general, the effect of the reduction term is negligible, or not even necessary. As a surface water dries, its wetted area decreases and so does the evaporative flux. However, for (simplified) cases with constant wetted surface (a rectangular profile), evaporation only stops at \\(S = 0\\)." - }, - { - "objectID": "core/equations.html#infiltration-and-drainage", - "href": "core/equations.html#infiltration-and-drainage", - "title": "Equations", - "section": "2.4 Infiltration and Drainage", - "text": "2.4 Infiltration and Drainage\nInfiltration is provided as a lump sum for the basin. If Ribasim is coupled with MODFLOW 6, the infiltration is computed as the sum of all positive flows of the MODFLOW 6 boundary conditions in the basin:\n\\[\n Q_\\text{inf} = \\sum_{i=1}^{n} \\sum_{j=1}^{m} \\max(Q_{\\mathrm{mf6}_{i,j}}, 0.0)\n\\] {#eq-inf}.\nWhere \\(i\\) is the index of the boundary condition, \\(j\\) the MODFLOW 6 cell index, \\(n\\) the number of boundary conditions, and \\(m\\) the number of MODFLOW 6 cells in the basin. \\(Q_{\\mathrm{mf6}_{i,j}}\\) is the flow computed by MODFLOW 6 for cell \\(j\\) for boundary condition \\(i\\).\nDrainage is a lump sump for the basin, and consists of the sum of the absolute value of all negative flows of the MODFLOW 6 boundary conditions in the basin.\n\\[\n Q_\\text{drn} = \\sum_{i=1}^{n} \\sum_{j=1}^{m} \\left| \\min(Q_{\\mathrm{mf6}_{i,j}}, 0.0) \\right|\n\\tag{4}\\]\nThe interaction with MODFLOW 6 boundary conditions is explained in greater detail in the the MODFLOW coupling section of the documentation." - }, - { - "objectID": "core/equations.html#upstream-and-downstream-flow", - "href": "core/equations.html#upstream-and-downstream-flow", - "title": "Equations", - "section": "2.5 Upstream and downstream flow", - "text": "2.5 Upstream and downstream flow\nRibasim’s basins can be connected to each other, and each basin expects an explicit connection. These connections are currently available for inter-basin flows:\n\n\nPump\nTabulatedRatingCurve\nLinearResistance\nManningResistance\n\nThe flow direction of the basin is not pre-determined: flow directions may freely reverse, provided the connection allows it. Currently, a LinearResistance allows bidirectional flow, but the\nAdditionally, three additional “connections” area available for the “outmost” basins (external nodes) in a network.\n\nTerminal\nLevelBoundary\nFlowBoundary\n\n\n2.5.1 Pump\nThe behaviour of pumps is very straight forward if these nodes are not PID controlled. Their flow is given by a fixed flow rate \\(q\\), multiplied by a reduction factor: \\[\nQ_\\text{pump} = \\phi(u; 10.0)q\n\\]\nHere \\(u\\) is the storage of the upstream basin. The reduction factor \\(\\phi\\) makes sure that the flow of the pump goes smootly to \\(0\\) as the upstream basin dries out.\n\n\n2.5.2 Outlet\nThe outlet is very similar to the pump, but it has a few extra reduction factors for physical constraints: \\[\nQ_\\text{outlet} = \\phi(u_a; 10.0)\\phi(\\Delta h; 0.1) \\phi(h_a-h_\\text{min};0.1)q.\n\\] The subscript \\(a\\) denotes the upstream node and \\(b\\) the downstream node. The first reduction factor is equivalent to the one for the pump. The second one makes sure that the outlet flow goes to zero as the head difference \\(\\Delta h = h_a - h_b\\) goes to zero. The last one makes sure that the outlet only produces flow when the upstream level is above the minimum chrest level \\(h_\\text{min}\\).\nNot all node types upstream or downstream of the outlet have a defined level. If this is the case, and therefore the reduction factor cannot be computed, it is defined to be \\(1.0\\).\n\n\n2.5.3 TabulatedRatingCurve\nThe Tabulated Rating Curve is a tabulation of a basin’s discharge behavior. It describes a piecewise linear relationship between the basin’s level and its discharge. It can be understood as an empirical description of a basin’s properties. This can include an outlet, but also the lumped hydraulic behavior of the upstream channels.\n\nThe Tabulated Rating Curve should indicate at which volume no discharge occurs (the dead storage volume).\n\n\n\n\n\n\nNote\n\n\n\nCurrently, the discharge relies only on the basin’s level; it could also use the volume of both connected basins to simulate backwater effects, submersion of outlets, or even reversal of flows for high precipitation events.\n\n\n\n\n2.5.4 LinearResistance\nA LinearResistance connects two basins together. The flow between the two basins is determined by a linear relationship:\n\\[\n Q = \\frac{h_a - h_b}{R}\n\\tag{5}\\]\nHere \\(h_a\\) is the water level in the first basin, \\(h_b\\) is the water level in the second basin, and \\(R\\) is the resistance of the link. A LinearResistance makes no assumptions about the direction of the flow: water flows from high to low.\n\n\n2.5.5 Terminal\nThis only allows outflow from a basin into a terminal node.\n\n\n2.5.6 LevelBoundary\nThis can be connected to a basin via a LinearResistance. This boundary node will then exchange water with the basin based on the difference in water level between the two.\n\n\n2.5.7 FlowBoundary\nThis can be connected directly to a basin and prescribes the flow to or from that basin. We require that the edge connecting the flow boundary to the basin should point towards the basin, so that positive flow corresponds to water being added to the model.\n\n\n2.5.8 Manning connection\nRibasim is capable of simulating steady flow between basins through a reach described by a trapezoidal profile and a Manning roughness coefficient.\nWe describe the discharge from basin \\(a\\) to basin \\(b\\) solely as a function of the water levels in \\(a\\) and \\(b\\).\n\\[\nQ = f(h_a, h_b)\n\\]\nwhere:\n\nThe subscripts \\(a,b\\) denote basins\n\\(h\\) is the hydraulic head, or water level\n\nThe energy equation for open channel flow is:\n\\[\nH = h + \\frac{v^2}{2g}\n\\]\nWhere\n\n\\(H\\) is total head\n\\(v\\) is average water velocity\n\\(g\\) is gravitational acceleration\n\nThe discharge \\(Q\\) is defined as:\n\\[\nQ = Av\n\\]\nwhere \\(A\\) is cross-sectional area.\nWe use conservation of energy to relate the total head at \\(a\\) to \\(b\\), with \\(H_a > H_b\\) as follows:\n\\[\nH_a = H_b + h_{\\text{loss}}\n\\]\nOr:\n\\[\nh_a + \\frac{v_a^2}{2g} = h_b + \\frac{v_b^2}{2g} + h_{\\text{loss}}\n\\]\nWhere \\(v\\) is the average water velocity. \\(h_{\\text{loss}}\\) is a combination of friction and contraction/expansion losses:\n\\[\nh_{\\text{loss}} = S_f L + \\frac{C}{2g} \\left(v_b^2 - v_a^2\\right)\n\\]\nWhere:\n\n\\(L\\) is the reach length\n\\(S_f\\) is the representative friction slope\n\\(C\\) is the expansion or contraction coefficient, \\(0 \\le C \\le1\\)\n\nWe assume velocity differences in a connection are negligible (\\(v_a = v_b\\)):\n\\[\nh_a = h_b + S_f L\n\\]\nFriction losses are computed with the Gauckler-Manning formula:\n\\[\nQ = \\frac{A}{n} R_h^\\frac{2}{3} \\sqrt{S_f}\n\\]\nWhere:\n\n\\(A\\) is the representative area.\n\\(R_h\\) is the representative wetted radius.\n\\(S_f\\) is the representative friction slope.\n\\(n\\) is Manning’s roughness coefficient.\n\nWe can rewrite to express \\(S_f\\) in terms of Q:\n\\[\nS_f = Q^2 \\frac{n^2}{A^2 R_h^{4/3}}\n\\]\nNo water is added or removed in a connection:\n\\[\nQ_a = Q_b = Q\n\\]\nSubstituting:\n\\[\nh_a = h_b + Q^2 \\frac{n^2}{A^2 R_h^{4/3}} L\n\\]\nWe can then express \\(Q\\) as a function of head difference \\(\\Delta h\\):\n\\[\nQ = \\textrm{sign}(\\Delta h) \\frac{A}{n} R_h^{2/3}\\sqrt{\\frac{|\\Delta h|}{L} }\n\\]\nThe \\(\\textrm{sign}(\\Delta h)\\) term causes the direction of the flow to reverse if the head in basin \\(b\\) is larger than in basin \\(a\\).\nThis expression however leads to problems in simulation since the derivative of \\(Q\\) with respect to \\(\\Delta h\\) tends to \\(\\pm \\infty\\) as \\(\\Delta h\\) tends to 0. Therefore we use the slightly modified expression\n\\[\nQ = \\textrm{sign}(\\Delta h) \\frac{A}{n} R_h^{2/3}\\sqrt{\\frac{\\Delta h}{L} s(\\Delta h)}\n\\]\nto smooth out this problem. Here \\(s(x) = \\frac{2}{\\pi}\\arctan{1000x}\\) can be thought of as a smooth approximation of the sign function.\n\n\n\n\n\n\nNote\n\n\n\nThe computation of \\(S_f\\) is not exact: we base it on a representative area and hydraulic radius, rather than integrating \\(S_f\\) along the length of a reach. Direct analytic solutions exist for e.g. parabolic profiles (Tolkmitt), but other profiles requires relatively complicated approaches (such as approximating the profile with a polynomial).\nWe use the average value of the cross-sectional area, the average value of the water depth, and the average value of the hydraulic radius to compute a friction slope. The size of the resulting error will depend on the water depth difference between the upstream and downstream basin.\n\n\nThe cross sectional area for a trapezoidal or rectangular profile:\n\\[\nA = w d + \\frac{\\Delta y}{\\Delta z} d^2\n\\]\nWhere\n\n\\(w\\) is the width at \\(d = 0\\) (A triangular profile has \\(w = 0\\))\n\\(\\frac{\\Delta y}{\\Delta z}\\) is the slope of the profile expressed as the horizontal length for one unit in the vertical (A slope of 45 degrees has \\(\\frac{\\Delta y}{\\Delta z} = 1\\); a rectangular profile 0).\n\nAccordingly, the wetted perimeter is:\n\\[\nB = w + 2 d \\sqrt{\\left(\\frac{\\Delta y}{\\Delta z}\\right)^2 + 1}\n\\]" - }, - { - "objectID": "core/equations.html#the-derivative-term", - "href": "core/equations.html#the-derivative-term", - "title": "Equations", - "section": "3.1 The derivative term", - "text": "3.1 The derivative term\nWhen \\(K_d \\ne 0\\) this adds a level of complexity. We can see this by looking at the error derivative more closely: \\[\n\\frac{\\text{d}e}{\\text{d}t} = \\frac{\\text{d}\\text{SP}}{\\text{d}t} - \\frac{1}{A(u_\\text{PID})}\\frac{\\text{d}u_\\text{PID}}{\\text{d}t},\n\\] where \\(A(u_\\text{PID})\\) is the area of the controlled basin as a function of the storage of the controlled basin \\(u_\\text{PID}\\). The complexity arises from the fact that \\(Q_\\text{PID}\\) is a contribution to \\(\\frac{\\text{d}u_\\text{PID}}{\\text{d}t} = f_\\text{PID}\\), which makes Equation 7 an implicit equation for \\(Q_\\text{PID}\\). We define\n\\[\nf_\\text{PID} = \\hat{f}_\\text{PID} \\pm Q_\\text{pump/outlet},\n\\]\nthat is, \\(\\hat{f}_\\text{PID}\\) is the right hand side of the ODE for the controlled basin storage state without the contribution of the PID controlled pump. The plus sign holds for an outlet and the minus sign for a pump, dictated by the way the pump and outlet connectivity to the controlled basin is enforced.\nUsing this, solving Equation 7 for \\(Q_\\text{PID}\\) yields \\[\nQ_\\text{pump/outlet} = \\text{clip}\\left(\\phi(u_\\text{us})\\frac{K_pe + K_iI + K_d \\left(\\frac{\\text{d}\\text{SP}}{\\text{d}t}-\\frac{\\hat{f}_\\text{PID}}{A(u_\\text{PID})}\\right)}{1\\pm\\phi(u_\\text{us})\\frac{K_d}{A(u_\\text{PID})}};Q_\\min,Q_\\max\\right),\n\\] where the clipping is again done last. Note that to compute this, \\(\\hat{f}_\\text{PID}\\) has to be known first, meaning that the PID controlled pump/outlet flow rate has to be computed after all other contributions to the PID controlled basin’s storage are known." - }, - { - "objectID": "core/equations.html#the-sign-of-the-parameters", - "href": "core/equations.html#the-sign-of-the-parameters", - "title": "Equations", - "section": "3.2 The sign of the parameters", - "text": "3.2 The sign of the parameters\nNote by Equation 6 that the error is positive if the setpoint is larger than the basin level and negative if the setpoint is smaller than the basin level.\nWe enforce the convention that when a pump is controlled, its edge points away from the basin, and when an outlet is controlled, its edge points towards the basin, so that the main flow direction along these edges is positive. Therefore, positive flows of the pump and outlet have opposite effects on the basin, and thus the parameters \\(K_p,K_i,K_d\\) of the pump and outlet must have oppositive signs to achieve the same goal." - }, - { - "objectID": "core/allocation.html", - "href": "core/allocation.html", - "title": "Allocation", + "objectID": "index.html", + "href": "index.html", + "title": "Ribasim", "section": "", - "text": "Allocation is the process of assigning an allocated abstraction flow rate to user nodes in the model based on information about sources, user demands over various priorities, constraints introduced by nodes, local water availability and graph topology. The allocation procedure implemented in Ribasim is heavily inspired by the maximum flow problem.\nThe allocation problem is solved per subnetwork of the Ribasim model. The subnetwork is used to formulate an optimization problem with the JuMP package, which is solved using the HiGHS solver. See also the example of solving the maximum flow problem with JuMP.jl here." - }, - { - "objectID": "core/allocation.html#allocation-problem-input", - "href": "core/allocation.html#allocation-problem-input", - "title": "Allocation", - "section": "1.1 Allocation problem input", - "text": "1.1 Allocation problem input\n\n1.1.1 The subnetwork\nThe allocation problem is solved per subgraph, where a subgraph is given by a subset \\(S \\subset V\\) of node ids. Different subgraphs are disjoint from eachother.\n\n\n1.1.2 Source flows\nSources are indicated by a set of edges in the subnetwork \\[\nE_S^\\text{source} \\subset \\left(S \\times S\\right) \\cap E.\n\\] That is, if \\((i,j) \\in E_S^\\text{source}\\), then \\(Q_{ij}\\) is treated as a source flow in the allocation problem.\n\n\n1.1.3 User demands\nThe subnetwork contains a subset of user nodes \\(U_S \\subset S\\), who all have time varying demands over various priorities \\(p\\): \\[\n d^p_i(t), \\quad i \\in U_S, p = 1,2,\\ldots, p_{\\max}.\n\\]\n\n\n\n\n\n\nNote\n\n\n\nOn this page we assume that the priorities are given by all integers from \\(1\\) to some \\(p_{\\max} \\in \\mathbb{N}\\). However, in the Ribasim input this is not a requirement; some of these in between priority values can be missing, only the ordering of the given priorities is taken into account.\n\n\n\n\n1.1.4 Vertical fluxes and local storage\nApart from the source flows denoted by edges, there are other sources of water in the subnetwork, associated with the basins in the subnetwork \\(B_S = B \\cap S\\). Firstly there is the sum of the vertical fluxes (precipitation, evaporation, infiltration and drainage) for each basin \\[\n \\phi_i(t), \\quad \\forall i \\in B_S.\n\\]\nSecondly, there is the available water in each basin above the minimum level \\(l_{\\min,i}\\) \\[\n u_i(t)-S(l_{\\min,i}), \\quad \\forall i \\in B_S.\n\\] Note that this value can be negative, which we interpret as a demand from the basin.\n\n\n1.1.5 Flow magnitude and direction constraints\nNodes in the Ribasim model that have a max_flow_rate, i.e. pumps and outlets, put a constraint on the flow through that node. Some nodes only allow flow in one direction, like pumps, outlets and tabulated rating curves.\n\n\n1.1.6 Fractional flows and user return flows\nBoth fractional flow nodes and user nodes dictate proportional relationships between flows over edges in the subnetwork. Users have a return factor \\(r_i, i \\in U_S\\)." + "text": "Ribasim is a water resources model, designed to be the replacement of the regional surface water modules Mozart and SIMRES in the Netherlands Hydrological Instrument (NHI). Ribasim is a work in progress, it is a prototype that demonstrates all essential functionalities. Further development of the prototype in a software release is planned in 2022 and 2023.\nRibasim is written in the Julia programming language and is built on top of the SciML: Open Source Software for Scientific Machine Learning libraries, notably DifferentialEquations.jl." }, { - "objectID": "core/allocation.html#the-allocation-optimization-problem", - "href": "core/allocation.html#the-allocation-optimization-problem", - "title": "Allocation", - "section": "1.2 The allocation optimization problem", - "text": "1.2 The allocation optimization problem\n\n1.2.1 The allocation graph\nA new graph is created from the subnetwork, which we call the allocation graph. To indicate the difference between subnetwork data and allocation graph data, the allocation graph data is denoted with a hat. The allocation graph consists of:\n\nNodes \\(\\hat{V_S}\\), where each basin, source and user in the subnetwork get a node in the allocation graph. Also nodes that have fractional flow outneighbors get a node in the allocation graph. The implementation makes heavy use of the node id mapping \\(m_S : i \\mapsto \\hat{i}\\) to translate from subnetwork node IDs to allocation graph node IDs. Unless specified otherwise, we assume this relationship between index symbols that appear both with and without a hat.\nEdges \\(\\hat{E_S}\\), where the edges in the allocation graph are given by one or more edges in the subnetwork, where those edges connect nodes in the subnetwork that have an equivalent in the allocation graph. The direction of the edges in the allocation graph is given by the direction constraints in the subnetwork.\n\nFor notational convenience, we use the notation \\[\n \\begin{align}\n \\hat{V}^{\\text{out}}_S(\\hat{i}) = \\left\\{\\hat{j} \\in \\hat{V}_S : (\\hat{i},\\hat{j}) \\in \\hat{E}_S\\right\\} \\\\\n \\hat{V}^{\\text{in}}_S(\\hat{j}) = \\left\\{\\hat{i} \\in \\hat{V}_S : (\\hat{i},\\hat{j}) \\in \\hat{E}_S\\right\\}\n \\end{align}\n\\] for the set of in-neighbors and out-neighbors of a node in the allocation graph respectively.\n\n\n1.2.2 The allocation graph capacities\nThe capacities of the edges of the allocation graph are collected in the sparse capacity matrix \\(\\hat{C}_S \\in \\overline{\\mathbb{R}}_{\\ge 0}^{\\hat{n}\\times\\hat{n}}\\) where \\(\\hat{n}\\) is the number of nodes in the allocation graph. The capacities can be infinite.\nThe capacities are determined in 3 different ways:\n\nIf an edge does not exist, i.e. \\((\\hat{i},\\hat{j}) \\notin \\hat{E}\\) for certain \\(1 \\le \\hat{i},\\hat{j}\\le \\hat{n}\\), then \\((\\hat{C}_S)_{\\hat{i},\\hat{j}} = 0\\);\nThe capacity of the edge \\(\\hat{e} \\in \\hat{E_S}\\) is given by the smallest max_flow_rate of the nodes along the equivalent edges in the subnetwork. If there are no nodes with a max_flow_rate, the edge capacity is infinite;\nIf the edge is a source, the capacity of the edge is given by the flow rate of that source.\n\n\n\n1.2.3 The optimization variables\nThere are several types of variables whose value has to be determined to solve the allocation problem:\n\nThe flows \\(F \\in \\mathbb{R}_{\\ge 0}^{\\hat{n}\\times\\hat{n}}\\) over the edges in the allocation graph;\nThe allocations to the users \\[\n A^\\text{user}_{\\hat{i},p} \\ge 0, \\quad \\forall \\hat{i} \\in \\hat{U}_S, \\forall p \\in \\{1,2,\\ldots, p_\\max\\},\n\\] where \\(\\hat{U}_S = m_S(U_S) \\subset \\hat{V}_S\\) is the set of user node ids in the allocation graph;\nThe allocations to the basins \\[\n A^\\text{basin}_{\\hat{i}} \\ge 0, \\quad \\hat{B}_S,\n\\] where \\(\\hat{B} = m_S(B_S) \\subset \\hat{V}_S\\) is the set of basin node ids in the allocation graph.\n\n\n\n1.2.4 The optimization objective\nThe goal of allocation is to maximize the flow to the users. However, basins can also demand water if their level is below the minimum abstraction level, which we give a higher priority than user demands. Therefore, we use the following optimization objective: \\[\n \\max \\sum_{\\hat{i} \\in \\hat{B}_S} A^\\text{basin}_{\\hat{i}} + \\sum_{\\hat{i}\\in \\hat{U}_S} \\sum_{p=1}^{p_\\max} 2^{-p} A^\\text{user}_{\\hat{i},p}.\n\\tag{1}\\] This is a linear combination of all allocations, where allocations to basins get a weight of \\(1\\) and allocations to users get a weight of \\(2^{-p}\\) where \\(p\\) is the priority.\n\n\n1.2.5 The optimization variable constraints\n\nSource flows: for the source edges we have that \\[\nF_{\\hat{i}\\hat{j}} \\le Q_{ij} \\quad \\forall (i,j) \\in E_S^\\text{source}.\n\\] Note that we do not require equality here; not all source flow has to be used.\nFlow conservation: For the basins in the allocation graph we have that \\[\n \\sum_{\\hat{j}=1}^{\\hat{n}} F_{\\hat{k}\\hat{j}} \\le \\sum_{\\hat{i}=1}^{\\hat{n}} F_{\\hat{i}\\hat{k}} + \\Phi_{\\hat{k}}, \\quad \\forall\\hat{k} \\in \\hat{B}_S.\n\\tag{2}\\] Note that we do not require equality here; in the allocation we do not mind that excess flow is ‘forgotten’ if it cannot contribute to the allocation to the users. \\(\\Phi_{\\hat{k}}\\) is the local water supply of the basins: \\[\n \\Phi_{\\hat{k}} = \\max\\left(\\phi_k(t) + \\frac{u_k(t)-S(l_{\\min,k})}{\\Delta t_\\text{alloc}}, 0.0 \\right).\n\\tag{3}\\] Here the first term denotes the vertical fluxes and the second term the flow that can be supplied by the water in the basin above its minimum level, where \\(\\Delta t_\\text{alloc}\\) is the allocation solve timestep.\nCapacity: the flows over the edges are positive and bounded by the edge capacity: \\[\n F_{\\hat{i}\\hat{j}} \\le \\left(\\hat{C}_S\\right)_{\\hat{i}\\hat{j}}, \\quad \\forall(\\hat{i},\\hat{j}) \\in \\hat{E}_S.\n\\tag{4}\\]\nUser outflow: The outflow of the user is dictated by the inflow and the return factor: \\[\n\\begin{align}\n F_{\\hat{i}\\hat{k}} = r_k \\cdot F_{\\hat{k}\\hat{j}}\\\\\n \\quad \\forall\\hat{k} \\in \\hat{U}_s, \\\\\n \\hat{V}^{\\text{in}}_S(\\hat{k}) = \\{\\hat{i}\\},\\\\\n \\hat{V}^{\\text{out}}_S(\\hat{k}) = \\{\\hat{j}\\}.\n\\end{align}\n\\tag{5}\\] Here we use that each user node in the allocation graph has an unique in-edge and out-edge.\nUser allocation: The flow over the edge to the user is equal to the sum of the allocations to the user: \\[\n F_{\\hat{i}\\hat{k}} = \\sum_{p=1}^{p_\\max} A^\\text{user}_{\\hat{k},p}, \\quad \\forall \\hat{k} \\in \\hat{U}_S, \\hat{V}^{\\text{out}}_s(\\hat{k}) = \\{\\hat{i}\\}.\n\\tag{6}\\] Here we use that each user has an unique out-edge.\nUser demand: what is allocated to the user is bounded above by the user demand: \\[\n A_{\\hat{i},p}^\\text{user} \\leq d_i^p(t) \\quad \\forall\\hat{i} \\in \\hat{U}_S, \\; p = 1,\\ldots,p_\\max.\n\\]\nBasin allocation: If the flow supplied by a basin (as determined in Equation 3) is negative, it is a demand: \\[\nA^\\text{basin}_{\\hat{i}} = \\max\\left(-\\left(\\phi_i(t) + \\frac{u_i(t)-S(l_{\\min,k})}{\\Delta t_\\text{alloc}}\\right), 0.0 \\right), \\quad \\forall \\hat{i} \\in \\hat{B}_S.\n\\tag{7}\\]\nFractinal flow: Let \\(\\hat{L}_S \\subset \\hat{V}_S\\) be the set of nodes in the max flow graph with fractional flow outneighbors, and \\(f_j\\) the flow fraction associated with fractional flow node \\(j \\in V_S\\). Then \\[\n\\begin{align}\n F_{\\hat{i}\\hat{j}} = f_j \\sum_{k\\in \\hat{V}^\\text{in}_S(\\hat{i})} F_{\\hat{k}\\hat{i}} \\\\\n \\forall \\hat{i} \\in \\hat{L}_S, \\\\\n \\hat{j} \\in \\hat{V}_S^\\text{out}(\\hat{i}).\n\\end{align}\n\\tag{8}\\]\nFlow sign: Furthermore there are the non-negativity constraints for the flows and allocations, see The optimization variables." + "objectID": "index.html#water-balance-equations", + "href": "index.html#water-balance-equations", + "title": "Ribasim", + "section": "3.1 Water balance equations", + "text": "3.1 Water balance equations\nThe water balance equation for a drainage basin (Wikipedia contributors 2022) can be defined by a first-order ordinary differential equation (ODE), where the change of the storage \\(S\\) over time is determined by the inflow fluxes minus the outflow fluxes.\n\\[\n\\frac{\\mathrm{d}S}{\\mathrm{d}t} = Q_{in} - Q_{out}\n\\]\nWe can split out the fluxes into separate terms, such as precipitation \\(P\\), evapotranspiration \\(ET\\) and runoff \\(R\\). For now other fluxes are combined into \\(Q_{rest}\\). If we define all fluxes entering our reservoir as positive, and those leaving the system as negative, all fluxes can be summed up.\n\\[\n\\frac{\\mathrm{d}S}{\\mathrm{d}t} = R + P + ET + Q_{rest}\n\\]" }, { - "objectID": "core/allocation.html#final-notes-on-the-allocation-problem", - "href": "core/allocation.html#final-notes-on-the-allocation-problem", - "title": "Allocation", - "section": "1.3 Final notes on the allocation problem", - "text": "1.3 Final notes on the allocation problem\n\n1.3.1 Users using their own return flow\nIf not explicitly avoided, users can use their own return flow in this allocation problem formulation. Therefore, return flow of users is only taken into account by allocation if that return flow is downstream of the user where it comes from. That is, if there is no path in the directed allocation graph from the user outflow node back to the user." + "objectID": "index.html#time", + "href": "index.html#time", + "title": "Ribasim", + "section": "3.2 Time", + "text": "3.2 Time\nThe water balance equation can be applied on many timescales; years, weeks, days or hours. Depending on the application and available data any of these can be the best choice. In Ribasim, we make use of DifferentialEquations.jl and its ODE solvers. Many of these solvers are based on adaptive time stepping, which means the solver will decide how large the time steps can be depending on the state of the system.\nThe forcing, like precipitation, is generally provided as a time series. Ribasim is set up to support unevenly spaced timeseries. The solver will stop on timestamps where new forcing values are available, so they can be loaded as the new value.\nRibasim is essentially a continuous model, rather than daily or hourly. If you want to use hourly forcing, you only need to make sure that your forcing data contains hourly updates. The output frequency can be configured independently. To be able to write a closed water balance, we accumulate the fluxes. This way any variations in between timesteps are also included, and we can output in m³ rather than m³s⁻¹." }, { - "objectID": "couple/modflow-demo.html", - "href": "couple/modflow-demo.html", - "title": "MODFLOW 6 Demonstration", - "section": "", - "text": "In our test cases, we will work with the Dutch national groundwater model (LHM). For testing, we simplify the top boundary conditions to just three surface water “systems”, from large to small:\n\nPrimary\nSecondary\nTertiary\n\nThese systems are separated in the groundwater model schematization due to the relatively small size of the surface waters (several meters in width) in comparison with relatively coarse cells of the groundwater model (250 m): most cells in the LHM contain more than one surface water, and are included via representative parameters which take the physical scaling into account. In case of sufficiently small cell sizes, no overlap occurs and all surface waters can be represented in a single grid.\nRibasim has no knowledge of these systems unless explicitly separated into different (sub-)basins. In the examples below, these three systems are represented by one basin with a single volume. For the purposes of testing, we have not yet created empirical volume-level relationships for the surface water of every cell extracted from a hydraulic model. Instead, we have chosen an (over)simplified parametrization of the hydraulic properties, which makes it easy to verify the behavior of Ribasim and the coupling procedures:\n\nPrimary, secondary, and tertiary systems have a rectangular profile: the area of the surface water does not change with water level or volume.\nWater depth is constant for a system within a basin.\nWater depth increases linearly with volume. (This follows from 1.)\nWater depth is distributed across the systems in a geometric progression: when the tertiary system contains 0.1 m of water, the secondary system contains 0.2 m, and the primary system contains 0.4 m.\nWater depth is 0.0 m for all systems when basin volume is 0.0. (This follows from 4.)\nThe distribution of water occurs according to the surface water area (width times length) used for the LHM parametrization of river bed conductance.\n\nFor freely draining basins, a simplified storage-discharge relationship has been derived as follows:\n\nThe area of the basin polygon has been multiplied by 1 mm/d (roughly the average precipitation excess in the Netherlands). This yields a “normative discharge”.\nA corresponding normative volume has been chosen, corresponding with water depths of 0.4, 0.2, and 0.1 m for the primary, secondary, and tertiary surface waters respectively.\nA dead storage volume has been chosen, corresponding with water depths of 0.2, 0.1, and 0.05 m for the primary, secondary, and tertiary surface waters respectively. The basin only starts discharging when the storage volume exceeds this value.\n\n\n\n\n\n\n\nNote\n\n\n\nRibasim is not limited to such oversimplified parametrization! Ribasim uses tabulations and therefore supports arbitrary (piecewise linear) volume-depth and volume-discharge relationships.\n\n\nA visual representation of this simplified conceptual schematization is given in Figure 1 and Figure 2.\n\n\n\nFigure 1: Distribution of water depths over the primary, secondary, and tertiary system.\n\n\n\n\n\nFigure 2: Discharge as a function of basin storage volume.\n\n\nAn example of the resulting parameters for a single cell is shown in Table 1. The first row shows the water levels when the basin is empty. The level for primary, secondary, and tertiary are equal to the bottom elevation of the surface waters. The second row shows the volume and levels for water depths of 0.4, 0.2, and 0.1 m. The third row shows the volume and levels for a tenfold larger volume. This results in implausible water levels with depths of 4.0, 2.0 and 1.0 m; the water level in the primary system is over two meters higher than in the tertiary system. In reality, the surface waters would overflow and surface ponding would occur; this mechanism is ignored in the test cases for the sake of simplicity.\n\n\nTable 1: Volume-level table for a single cell in the Hupsel basin.\n\n\nVolume (m3)\nPrimary (m NAP)\nSecondary (m NAP)\nTertiary (m NAP)\n\n\n\n\n0.0\n25.65\n25.83\n26.60\n\n\n6843.1\n26.05\n26.03\n26.70\n\n\n68431.0\n29.65\n27.83\n27.60\n\n\n\n\nFigure 3 shows the volume of the first row of the cell based input for the primary system. Symbology is set to unique values. While water levels differ per cell in this parametrization, the “normative volume” defined above is shared by all cells in a basin.\n\n\n\nFigure 3: Basin normative volume of the primary system.\n\n\nFigure 3 shows the water level corresponding to the normative storage volume based input for the primary system (it corresponds to the value shown in the first row of the primary column in Table 1). We see a clear gradient from west to east: as our simplified parametrization assumes a constant water depth for all cells in a single system, water levels spatially fall and rise with the bottom elevation.\n\n\n\nFigure 4: Water level corresponding to the normative basin volume of the primary system." + "objectID": "index.html#sec-space", + "href": "index.html#sec-space", + "title": "Ribasim", + "section": "3.3 Space", + "text": "3.3 Space\nThe water balance equation can be applied on different spatial scales. Besides modelling a single lumped watershed, it allows you to divide the area into a network of connected representative elementary watersheds (REWs) (Reggiani, Sivapalan, and Majid Hassanizadeh 1998). At this scale global water balance laws can be formulated by means of integration of point-scale conservation equations over control volumes. Such an approach makes Ribasim a semi-distributed model. In this document we typically use the term “basin” to refer to the REW. (In Mozart the spatial unit was called Local Surface Water (LSW)). Each basin has an associated polygon, and the set of basins is connected to each other as described by a graph, which we call the network. Below is a representation of both on the map.\n\n\n\nMozart Local Surface Water polygons and their drainage.\n\n\nThe network is described as graph. Flow can be bi-directional, and the graph does not have to be acyclic.\n\n\n\n\ngraph LR;\n A[\"basin A\"] --- B[\"basin B\"];\n A --- C[\"basin C\"];\n B --- D[\"basin D\"];\n C --- D;\n\n\n\n\n\nInternally a directed graph is used. The direction is defined to be the positive flow direction, and is generally set in the dominant flow direction. The basins are the nodes of the network graph. Basin states and properties such storage volume and wetted area are associated with the nodes (A, B, C, D), as are most forcing data such as precipitation, evaporation, or water demand. Basin connection properties and interbasin flows are associated with the edges (the lines between A, B, C, and D) instead.\nMultiple basins may exist within the same spatial polygon, representing different aspects of the surface water system (perennial ditches, ephemeral ditches, or even surface ponding). Figure 1, Figure 2, Figure 3 show the 25.0 m rasterized primary, secondary, and tertiary surface waters as identified by BRT TOP10NL (PDOK 2022) in the Hupsel basin (as defined in the Mozart LSW’s). These systems may represented in multiple ways.\n\n\n\nFigure 1: Hupsel: primary surface water.\n\n\n\n\n\nFigure 2: Hupsel: secondary surface water.\n\n\n\n\n\nFigure 3: Hupsel: tertiary surface water.\n\n\nAs a single basin (A) containing all surface water, discharging to its downstream basin to the west (B):\n\n\n\n\ngraph LR;\n A[\"basin A\"] --> B[\"basin B\"];\n\n\n\n\n\nSuch a system may be capable of representing discharge, but it cannot represent residence times or differences in solute concentrations: within a single basin, drop of water is mixed instantaneously. Instead, we may the group primary (P), secondary (S), and tertiary (T) surface waters. Then T may flow into S, S into P, and P discharges to the downstream basin (B.)\n\n\n\n\ngraph LR;\n T[\"basin T\"] --> S[\"basin S\"];\n S --> P[\"basin P\"];\n P --> B[\"basin B\"];\n\n\n\n\n\nAs each (sub)basin has its own volume, low throughput (high volume, low discharge, long residence time) and high throughput (low volume, high discharge, short residence time) systems can be represented in a lumped manner; of course, more detail requires more parameters." }, { - "objectID": "couple/modflow-demo.html#example-parametrization", - "href": "couple/modflow-demo.html#example-parametrization", - "title": "MODFLOW 6 Demonstration", + "objectID": "core/usage.html", + "href": "core/usage.html", + "title": "Usage", "section": "", - "text": "In our test cases, we will work with the Dutch national groundwater model (LHM). For testing, we simplify the top boundary conditions to just three surface water “systems”, from large to small:\n\nPrimary\nSecondary\nTertiary\n\nThese systems are separated in the groundwater model schematization due to the relatively small size of the surface waters (several meters in width) in comparison with relatively coarse cells of the groundwater model (250 m): most cells in the LHM contain more than one surface water, and are included via representative parameters which take the physical scaling into account. In case of sufficiently small cell sizes, no overlap occurs and all surface waters can be represented in a single grid.\nRibasim has no knowledge of these systems unless explicitly separated into different (sub-)basins. In the examples below, these three systems are represented by one basin with a single volume. For the purposes of testing, we have not yet created empirical volume-level relationships for the surface water of every cell extracted from a hydraulic model. Instead, we have chosen an (over)simplified parametrization of the hydraulic properties, which makes it easy to verify the behavior of Ribasim and the coupling procedures:\n\nPrimary, secondary, and tertiary systems have a rectangular profile: the area of the surface water does not change with water level or volume.\nWater depth is constant for a system within a basin.\nWater depth increases linearly with volume. (This follows from 1.)\nWater depth is distributed across the systems in a geometric progression: when the tertiary system contains 0.1 m of water, the secondary system contains 0.2 m, and the primary system contains 0.4 m.\nWater depth is 0.0 m for all systems when basin volume is 0.0. (This follows from 4.)\nThe distribution of water occurs according to the surface water area (width times length) used for the LHM parametrization of river bed conductance.\n\nFor freely draining basins, a simplified storage-discharge relationship has been derived as follows:\n\nThe area of the basin polygon has been multiplied by 1 mm/d (roughly the average precipitation excess in the Netherlands). This yields a “normative discharge”.\nA corresponding normative volume has been chosen, corresponding with water depths of 0.4, 0.2, and 0.1 m for the primary, secondary, and tertiary surface waters respectively.\nA dead storage volume has been chosen, corresponding with water depths of 0.2, 0.1, and 0.05 m for the primary, secondary, and tertiary surface waters respectively. The basin only starts discharging when the storage volume exceeds this value.\n\n\n\n\n\n\n\nNote\n\n\n\nRibasim is not limited to such oversimplified parametrization! Ribasim uses tabulations and therefore supports arbitrary (piecewise linear) volume-depth and volume-discharge relationships.\n\n\nA visual representation of this simplified conceptual schematization is given in Figure 1 and Figure 2.\n\n\n\nFigure 1: Distribution of water depths over the primary, secondary, and tertiary system.\n\n\n\n\n\nFigure 2: Discharge as a function of basin storage volume.\n\n\nAn example of the resulting parameters for a single cell is shown in Table 1. The first row shows the water levels when the basin is empty. The level for primary, secondary, and tertiary are equal to the bottom elevation of the surface waters. The second row shows the volume and levels for water depths of 0.4, 0.2, and 0.1 m. The third row shows the volume and levels for a tenfold larger volume. This results in implausible water levels with depths of 4.0, 2.0 and 1.0 m; the water level in the primary system is over two meters higher than in the tertiary system. In reality, the surface waters would overflow and surface ponding would occur; this mechanism is ignored in the test cases for the sake of simplicity.\n\n\nTable 1: Volume-level table for a single cell in the Hupsel basin.\n\n\nVolume (m3)\nPrimary (m NAP)\nSecondary (m NAP)\nTertiary (m NAP)\n\n\n\n\n0.0\n25.65\n25.83\n26.60\n\n\n6843.1\n26.05\n26.03\n26.70\n\n\n68431.0\n29.65\n27.83\n27.60\n\n\n\n\nFigure 3 shows the volume of the first row of the cell based input for the primary system. Symbology is set to unique values. While water levels differ per cell in this parametrization, the “normative volume” defined above is shared by all cells in a basin.\n\n\n\nFigure 3: Basin normative volume of the primary system.\n\n\nFigure 3 shows the water level corresponding to the normative storage volume based input for the primary system (it corresponds to the value shown in the first row of the primary column in Table 1). We see a clear gradient from west to east: as our simplified parametrization assumes a constant water depth for all cells in a single system, water levels spatially fall and rise with the bottom elevation.\n\n\n\nFigure 4: Water level corresponding to the normative basin volume of the primary system." - }, - { - "objectID": "couple/modflow-demo.html#example-configuration", - "href": "couple/modflow-demo.html#example-configuration", - "title": "MODFLOW 6 Demonstration", - "section": "2 Example: Configuration", - "text": "2 Example: Configuration\nAn example of the MODFLOW 6 section of TOML configuration required for a coupled run can be seen below:\n[modflow]\nsimulation = \"../data/hupsel/mfsim.nam\"\nmode = \"sequential\"\ntimestep = 86400.0\n\n[modflow.models]\n\n[modflow.models.gwf]\ntype = \"gwf\"\ndataset = \"../data/volume_level_profile-hupsel.nc\"\nbasins = \"basin_id\"\n\n[[modflow.models.gwf.bounds]]\nriver = \"RIV_P\"\ndrain = \"DRN_P\"\nprofile = \"profile_primary\"\n\n[[modflow.models.gwf.bounds]]\nriver = \"RIV_S\"\ndrain = \"DRN_S\"\nprofile = \"profile_secondary\"\n\n[[modflow.models.gwf.bounds]]\ndrain = \"DRN_T\"\nprofile = \"profile_tertiary\"\nThe section starts by stating the path to the MODFLOW 6 simulation name file (simulation). The next section contains the information regarding the MODFLOW 6 model(s) to couple to Ribasim’s basins. Per model, a path to the coupling parameter dataset is provided (dataset), along with the variable to use as the basin identification number (basins). Next, for every boundary condition that should be coupled to Ribasim, the package names (river, drain) used by MODFLOW 6 must be specified (as we look for these names in the MODFLOW 6 memory), along with the name of the variable in the coupling dataset which provides the volume-level relationship (profile).\nAs can be seen in the example, the coupling mechanism supports coupling of:\n\nA single drainage package (drain entry).\nA single river package (river entry).\nA combination of river and drainage package (when infiltration conductance does not equal drainage conductance) both (river and drain entry)." - }, - { - "objectID": "couple/modflow-demo.html#test-case-hupsel", - "href": "couple/modflow-demo.html#test-case-hupsel", - "title": "MODFLOW 6 Demonstration", - "section": "3 Test case: Hupsel", - "text": "3 Test case: Hupsel\nTo test the coupling, the following simulations have been setup and run:\n\nA standalone MODFLOW 6 run of sequential steady-states (i.e. no storage) with differing groundwater recharge values.\nA coupled run where the MODFLOW 6 stages are updated by the Ribasim coupler process, but without Ribasim. This results in volumes of 0.0, so all MODFLOW 6 water levels are set equal to bed elevation.\nA coupled run where the water levels are updated by Ribasim.\n\nFrom these tests, we expect the following behavior:\n\nDrainage terms should remain largely the same when the water level is lowered in a steady-state: the amount of recharge is fixed, and this is locally drained.\nIn case of negative recharge (evapotranspiration), infiltration occurs in the surface waters. Infiltration should be zero when the basin volume is 0.\n\n\n\n\nFigure 5: Water balance of the MODFLOW 6 boundary conditions for the Hupsel basin for a standalone MODFLOW 6 run. The four sequential steady states (01, 02, 03, 04) use net groundwater recharge values of 1.0, 0.5, -0.05 and -0.1 mm/d.\n\n\nFigure 5 shows the water balance of steady-state for submodel of the LHM that has been by selecting the cells belonging to the district containing the Hupsel catch, the Berkel.\nThe Hupsel basin show the expected behavior: for a net groundwater recharge of 1.0 mm/d, most is precipitation with a minor part lateral inflow from higher areas. In terms of outgoing flows, most of the precipitation ends up in the surface water, primarily in the many ditches of the tertiary system. Only a relatively small part of the water leaves the basin via the groundwater. Interbasin flows through the groundwater form such a minor role, as the aquifer is thin and transmissivity is limited.\nReducing groundwater recharge to 0.5 mm/d reduces all flows, with the tertiary system playing a less dominant role, relatively speaking: as its elevation is the highest compared to the primary and secondary system, the head difference is reduced strongest for the tertiary system.\nWith evapotranspiration (ET) excess (-0.05 and 0.1 mm/d; low values are chosen here since most ET would be drawn from storage, which is not available in a steady-state model), the surface waters provide mostly inflow, and recharge is a negative term. In this case, the secondary system provides a small amount of infiltration; most of the water is drawn from the surroundings instead.\n\n\n\nFigure 6: Water balance of the MODFLOW 6 boundary conditions for the Hupsel basin for a zero volume run. The four sequential steady states (01, 02, 03, 04) use net groundwater recharge values of 1.0, 0.5, -0.05 and -0.1 mm/d.\n\n\nFigure 6 shows the same model, with 0-basin volume which causes water levels to be set equal to bed elevation. Consequently, primary and secondary outflow terms are larger for positive groundwater recharge as they drain at a lower level and intercept the water before the tertiary system does. Secondly, with negative groundwater recharge, no infiltration occurs and the water is drawn from the surroundings instead. This shows the coupling mechanism adjusting MODFLOW 6 water levels successfully." + "text": "Ribasim is typically used as a command-line interface (CLI). It is distributed as a .zip archive, that must be downloaded and unpacked. It can be placed anywhere, however it is important that the contents of the zip file are kept together in a directory. The Ribasim CLI executable is in the bin directory.\nTo download ribasim_cli.zip, see the download section.\nTo check whether the installation was performed successfully, run ribasim with no arguments in the command line. This will give the following message:" }, { - "objectID": "couple/modflow-demo.html#test-case-de-tol", - "href": "couple/modflow-demo.html#test-case-de-tol", - "title": "MODFLOW 6 Demonstration", - "section": "4 Test case: de Tol", - "text": "4 Test case: de Tol\nTo test the coupling, the following simulations have been setup and run:\n\nA standalone MODFLOW 6 run of sequential steady-states (i.e. no storage) with differing groundwater recharge values.\nA coupled run where the MODFLOW 6 stages are updated by the Ribasim coupler process, but without Ribasim. This results in volumes of 0.0, so all MODFLOW 6 water levels are set equal to bed elevation.\nA coupled run where the water levels are updated by Ribasim.\n\n\n\n\nFigure 7: Water balance of the MODFLOW 6 boundary conditions for De Tol basin for a standalone MODFLOW 6 run. The four sequential steady states (01, 02, 03, 04) use net groundwater recharge values of 1.0, 0.5, -0.05 and -0.1 mm/d.\n\n\nFigure 7 shows the water balance of steady-state for a submodel of the LHM for the Polder de Tol and its surroundings. While groundwater recharge is the dominant ingoing flow, lateral groundwater flow (over the entire depth of the groundwater model) is a sizable inflow for the area; the larger lateral inflow shows that De Tol is a net receiver of groundwater which is mostly discharged through the secondary system. In contrast to the Hupsel, the tertiary system is almost entirely absent: drainage occurs not through ephemeral tertiary ditches, but by the permanently water-bearing ditches of the primary and secondary system. Unlike the Hupsel, the water balance does not shrink to very small discharges, as there is sizable regional groundwater flow.\n\n\n\nFigure 8: Water balance of the MODFLOW 6 boundary conditions for De Tol basin for a zero volume run. The four sequential steady states (01, 02, 03, 04) use net groundwater recharge values of 1.0, 0.5, -0.05 and -0.1 mm/d.\n\n\nFigure 8 shows the same model, with 0-basin volume which causes water levels to be set equal to bed elevation. The total discharge is larger: the primary and secondary systems are set to lower levels, and so the head difference is larger. While De Tol’s evapotranspiration excess can be fed by the regional groundwater, the primary and secondary ditches also provide some part; as expected, they do not feed when the coupling mechanism adjusts MODFLOW 6’s water levels." + "objectID": "core/usage.html#sec-solver-settings", + "href": "core/usage.html#sec-solver-settings", + "title": "Usage", + "section": "1.1 Solver settings", + "text": "1.1 Solver settings\nThe solver section in the configuration file is entirely optional, since we aim to use defaults that will generally work well. Common reasons to modify the solver settings are to adjust the calculation or result stepsizes: adaptive, dt, and saveat. If your model does not converge, or your performance is lower than expected, it can help to adjust other solver settings as well.\nThe default solver algorithm = \"QNDF\", which is a multistep method similar to Matlab’s ode15s (Shampine and Reichelt 1997). It is an implicit method that supports the default adaptive = true timestepping. The full list of available solvers is: QNDF, Rosenbrock23, TRBDF2, Rodas5, KenCarp4, Tsit5, RK4, ImplicitEuler, Euler. Information on the solver algorithms can be found on the ODE solvers page.\nThe dt controls the stepsize. When adaptive = true, dt only applies to the initial stepsize, and by default it is automatically determined. When adaptive = false a suitable dt must always be provided. The value is in seconds, so dt = 3600.0 corresponds to an hourly timestep. When adaptive = true, dtmin and dtmax control the minimum and maximum allowed dt. By default these depend on the problem and algorithm. If a smaller dt than dtmin is needed to meet the set error tolerances, the simulation stops, unless force_dtmin is set to true. force_dtmin is off by default to ensure an accurate solution.\nBy default the calculation and result stepsize are the same, with saveat = [], which will save every timestep. saveat can be a number, which is the saving interval in seconds, or it can be a list of numbers, which are the times in seconds since start that are saved. For instance, saveat = 86400.0 will save results after every day that passed.\nThe Jacobian matrix provides information about the local sensitivity of the model with respect to changes in the states. For implicit solvers it must be calculated often, which can be expensive to do. There are several methods to do this. By default Ribasim uses a Jacobian derived automatically using ForwardDiff.jl with memory management provided by PreallocationTools.jl. If this is not used by setting autodiff = false, the Jacobian is calculated with a finite difference method, which can be less accurate and more expensive.\nBy default the Jacobian matrix is a sparse matrix (sparse = true). Since each state typically only depends on a small number of other states, this is generally more efficient, especially for larger models. The sparsity structure is calculated from the network and provided as a Jacobian prototype to the solver. For small or highly connected models it could be faster to use a dense Jacobian matrix instead by setting sparse = false.\nThe total maximum number of iterations maxiters = 1e9, can normally stay as-is unless doing extremely long simulations.\nThe absolute and relative tolerance for adaptive timestepping can be set with abstol and reltol. For more information on these and other solver options, see the DifferentialEquations.jl docs." }, { - "objectID": "couple/index.html", - "href": "couple/index.html", - "title": "Coupled models", - "section": "", - "text": "Ribasim can be coupled to other software, for instance to model another process or domain, or to control a simulation from another process.\nTo enable this, Ribasim can be compiled as a shared library (libribasim) instead of a command line interface (ribasim). This shared library exposes a C API in the form of the Basic Model Interface (BMI). Other software can then load libribasim and load a Ribasim model, exchange data, and control the time stepping.\nAn initial coupling to MODFLOW 6 was done in 2022 inside the Julia core as a proof of concept. Read about the coupling setup and see the demonstration. Going forward this and other coupling codes will be implemented outside of the core, by making use of iMOD Coupler and libribasim. iMOD Coupler is a generic coupling tool, and can be used to couple to other models as well." + "objectID": "core/usage.html#basin-time", + "href": "core/usage.html#basin-time", + "title": "Usage", + "section": "5.1 Basin / time", + "text": "5.1 Basin / time\nThis table is the transient form of the Basin table. The only difference is that a time column is added. The table must by sorted by time, and per time it must be sorted by node_id. A linear interpolation between the given timesteps is currently done if the solver takes timesteps between the given data points. More options will be available later." }, { - "objectID": "python/examples.html", - "href": "python/examples.html", - "title": "Examples", - "section": "", - "text": "1 Basic model with static forcing\n\nfrom pathlib import Path\n\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport ribasim\n\nSetup the basins:\n\nprofile = pd.DataFrame(\n data={\n \"node_id\": [1, 1, 3, 3, 6, 6, 9, 9],\n \"area\": [0.01, 1000.0] * 4,\n \"level\": [0.0, 1.0] * 4,\n }\n)\n\n# Convert steady forcing to m/s\n# 2 mm/d precipitation, 1 mm/d evaporation\nseconds_in_day = 24 * 3600\nprecipitation = 0.002 / seconds_in_day\nevaporation = 0.001 / seconds_in_day\n\nstatic = pd.DataFrame(\n data={\n \"node_id\": [0],\n \"drainage\": [0.0],\n \"potential_evaporation\": [evaporation],\n \"infiltration\": [0.0],\n \"precipitation\": [precipitation],\n \"urban_runoff\": [0.0],\n }\n)\nstatic = static.iloc[[0, 0, 0, 0]]\nstatic[\"node_id\"] = [1, 3, 6, 9]\n\nbasin = ribasim.Basin(profile=profile, static=static)\n\nSetup linear resistance:\n\nlinear_resistance = ribasim.LinearResistance(\n static=pd.DataFrame(\n data={\"node_id\": [10, 12], \"resistance\": [5e3, (3600.0 * 24) / 100.0]}\n )\n)\n\nSetup Manning resistance:\n\nmanning_resistance = ribasim.ManningResistance(\n static=pd.DataFrame(\n data={\n \"node_id\": [2],\n \"length\": [900.0],\n \"manning_n\": [0.04],\n \"profile_width\": [6.0],\n \"profile_slope\": [3.0],\n }\n )\n)\n\nSet up a rating curve node:\n\n# Discharge: lose 1% of storage volume per day at storage = 1000.0.\nq1000 = 1000.0 * 0.01 / seconds_in_day\n\nrating_curve = ribasim.TabulatedRatingCurve(\n static=pd.DataFrame(\n data={\n \"node_id\": [4, 4],\n \"level\": [0.0, 1.0],\n \"discharge\": [0.0, q1000],\n }\n )\n)\n\nSetup fractional flows:\n\nfractional_flow = ribasim.FractionalFlow(\n static=pd.DataFrame(\n data={\n \"node_id\": [5, 8, 13],\n \"fraction\": [0.3, 0.6, 0.1],\n }\n )\n)\n\nSetup pump:\n\npump = ribasim.Pump(\n static=pd.DataFrame(\n data={\n \"node_id\": [7],\n \"flow_rate\": [0.5 / 3600],\n }\n )\n)\n\nSetup level boundary:\n\nlevel_boundary = ribasim.LevelBoundary(\n static=pd.DataFrame(\n data={\n \"node_id\": [11, 17],\n \"level\": [0.5, 1.5],\n }\n )\n)\n\nSetup flow boundary:\n\nflow_boundary = ribasim.FlowBoundary(\n static=pd.DataFrame(\n data={\n \"node_id\": [15, 16],\n \"flow_rate\": [1e-4, 1e-4],\n }\n )\n)\n\nSetup terminal:\n\nterminal = ribasim.Terminal(\n static=pd.DataFrame(\n data={\n \"node_id\": [14],\n }\n )\n)\n\nSet up the nodes:\n\nxy = np.array(\n [\n (0.0, 0.0), # 1: Basin,\n (1.0, 0.0), # 2: ManningResistance\n (2.0, 0.0), # 3: Basin\n (3.0, 0.0), # 4: TabulatedRatingCurve\n (3.0, 1.0), # 5: FractionalFlow\n (3.0, 2.0), # 6: Basin\n (4.0, 1.0), # 7: Pump\n (4.0, 0.0), # 8: FractionalFlow\n (5.0, 0.0), # 9: Basin\n (6.0, 0.0), # 10: LinearResistance\n (2.0, 2.0), # 11: LevelBoundary\n (2.0, 1.0), # 12: LinearResistance\n (3.0, -1.0), # 13: FractionalFlow\n (3.0, -2.0), # 14: Terminal\n (3.0, 3.0), # 15: FlowBoundary\n (0.0, 1.0), # 16: FlowBoundary\n (6.0, 1.0), # 17: LevelBoundary\n ]\n)\nnode_xy = gpd.points_from_xy(x=xy[:, 0], y=xy[:, 1])\n\nnode_id, node_type = ribasim.Node.get_node_ids_and_types(\n basin,\n manning_resistance,\n rating_curve,\n pump,\n fractional_flow,\n linear_resistance,\n level_boundary,\n flow_boundary,\n terminal,\n)\n\n# Make sure the feature id starts at 1: explicitly give an index.\nnode = ribasim.Node(\n static=gpd.GeoDataFrame(\n data={\"type\": node_type},\n index=pd.Index(node_id, name=\"fid\"),\n geometry=node_xy,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the edges:\n\nfrom_id = np.array(\n [1, 2, 3, 4, 4, 5, 6, 8, 7, 9, 11, 12, 4, 13, 15, 16, 10], dtype=np.int64\n)\nto_id = np.array(\n [2, 3, 4, 5, 8, 6, 7, 9, 9, 10, 12, 3, 13, 14, 6, 1, 17], dtype=np.int64\n)\nlines = ribasim.utils.geometry_from_connectivity(node, from_id, to_id)\nedge = ribasim.Edge(\n static=gpd.GeoDataFrame(\n data={\n \"from_node_id\": from_id,\n \"to_node_id\": to_id,\n \"edge_type\": len(from_id) * [\"flow\"],\n },\n geometry=lines,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup a model:\n\nmodel = ribasim.Model(\n node=node,\n edge=edge,\n basin=basin,\n level_boundary=level_boundary,\n flow_boundary=flow_boundary,\n pump=pump,\n linear_resistance=linear_resistance,\n manning_resistance=manning_resistance,\n tabulated_rating_curve=rating_curve,\n fractional_flow=fractional_flow,\n terminal=terminal,\n starttime=\"2020-01-01 00:00:00\",\n endtime=\"2021-01-01 00:00:00\",\n)\n\nLet’s take a look at the model:\n\nmodel.plot()\n\n<Axes: >\n\n\n\n\n\nWrite the model to a TOML and GeoPackage:\n\ndatadir = Path(\"data\")\nmodel.write(datadir / \"basic\")\n\n\n\n2 Update the basic model with transient forcing\nThis assumes you have already created the basic model with static forcing.\n\nimport numpy as np\nimport pandas as pd\nimport ribasim\nimport xarray as xr\n\n\nmodel = ribasim.Model.from_toml(datadir / \"basic/ribasim.toml\")\n\n\ntime = pd.date_range(model.starttime, model.endtime)\nday_of_year = time.day_of_year.to_numpy()\nseconds_per_day = 24 * 60 * 60\nevaporation = (\n (-1.0 * np.cos(day_of_year / 365.0 * 2 * np.pi) + 1.0) * 0.0025 / seconds_per_day\n)\nrng = np.random.default_rng(seed=0)\nprecipitation = (\n rng.lognormal(mean=-1.0, sigma=1.7, size=time.size) * 0.001 / seconds_per_day\n)\n\nWe’ll use xarray to easily broadcast the values.\n\ntimeseries = (\n pd.DataFrame(\n data={\n \"node_id\": 1,\n \"time\": time,\n \"drainage\": 0.0,\n \"potential_evaporation\": evaporation,\n \"infiltration\": 0.0,\n \"precipitation\": precipitation,\n \"urban_runoff\": 0.0,\n }\n )\n .set_index(\"time\")\n .to_xarray()\n)\n\nbasin_ids = model.basin.static[\"node_id\"].to_numpy()\nbasin_nodes = xr.DataArray(\n np.ones(len(basin_ids)), coords={\"node_id\": basin_ids}, dims=[\"node_id\"]\n)\nforcing = (timeseries * basin_nodes).to_dataframe().reset_index()\n\n\nstate = pd.DataFrame(\n data={\n \"node_id\": basin_ids,\n \"level\": 1.4,\n \"concentration\": 0.0,\n }\n)\n\n\nmodel.basin.time = forcing\nmodel.basin.state = state\n\n\nmodel.write(datadir / \"basic_transient\")\n\nNow run the model with ribasim basic-transient/ribasim.toml. After running the model, read back the results:\n\ndf_basin = pd.read_feather(datadir / \"basic_transient/results/basin.arrow\")\ndf_basin_wide = df_basin.pivot_table(\n index=\"time\", columns=\"node_id\", values=[\"storage\", \"level\"]\n)\ndf_basin_wide[\"level\"].plot()\n\n<Axes: xlabel='time'>\n\n\n\n\n\n\ndf_flow = pd.read_feather(datadir / \"basic_transient/results/flow.arrow\")\ndf_flow[\"edge\"] = list(zip(df_flow.from_node_id, df_flow.to_node_id))\ndf_flow[\"flow_m3d\"] = df_flow.flow * 86400\nax = df_flow.pivot_table(index=\"time\", columns=\"edge\", values=\"flow_m3d\").plot()\nax.legend(bbox_to_anchor=(1.3, 1), title=\"Edge\")\n\n<matplotlib.legend.Legend at 0x7f164810bad0>\n\n\n\n\n\n\ntype(df_flow)\n\npandas.core.frame.DataFrame\n\n\n\n\n3 Model with discrete control\nThe model constructed below consists of a single basin which slowly drains trough a TabulatedRatingCurve, but is held within a range around a target level (setpoint) by two connected pumps. These two pumps behave like a reversible pump. When pumping can be done in only one direction, and the other direction is only possible under gravity, use an Outlet for that direction.\nSet up the nodes:\n\nxy = np.array(\n [\n (0.0, 0.0), # 1: Basin\n (1.0, 1.0), # 2: Pump\n (1.0, -1.0), # 3: Pump\n (2.0, 0.0), # 4: LevelBoundary\n (-1.0, 0.0), # 5: TabulatedRatingCurve\n (-2.0, 0.0), # 6: Terminal\n (1.0, 0.0), # 7: DiscreteControl\n ]\n)\n\nnode_xy = gpd.points_from_xy(x=xy[:, 0], y=xy[:, 1])\n\nnode_type = [\n \"Basin\",\n \"Pump\",\n \"Pump\",\n \"LevelBoundary\",\n \"TabulatedRatingCurve\",\n \"Terminal\",\n \"DiscreteControl\",\n]\n\n# Make sure the feature id starts at 1: explicitly give an index.\nnode = ribasim.Node(\n static=gpd.GeoDataFrame(\n data={\"type\": node_type},\n index=pd.Index(np.arange(len(xy)) + 1, name=\"fid\"),\n geometry=node_xy,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the edges:\n\nfrom_id = np.array([1, 3, 4, 2, 1, 5, 7, 7], dtype=np.int64)\nto_id = np.array([3, 4, 2, 1, 5, 6, 2, 3], dtype=np.int64)\n\nedge_type = 6 * [\"flow\"] + 2 * [\"control\"]\n\nlines = ribasim.utils.geometry_from_connectivity(node, from_id, to_id)\nedge = ribasim.Edge(\n static=gpd.GeoDataFrame(\n data={\"from_node_id\": from_id, \"to_node_id\": to_id, \"edge_type\": edge_type},\n geometry=lines,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the basins:\n\nprofile = pd.DataFrame(\n data={\n \"node_id\": [1, 1],\n \"area\": [1000.0, 1000.0],\n \"level\": [0.0, 1.0],\n }\n)\n\nstatic = pd.DataFrame(\n data={\n \"node_id\": [1],\n \"drainage\": [0.0],\n \"potential_evaporation\": [0.0],\n \"infiltration\": [0.0],\n \"precipitation\": [0.0],\n \"urban_runoff\": [0.0],\n }\n)\n\nstate = pd.DataFrame(data={\"node_id\": [1], \"level\": [20.0]})\n\nbasin = ribasim.Basin(profile=profile, static=static, state=state)\n\nSetup the discrete control:\n\ncondition = pd.DataFrame(\n data={\n \"node_id\": 3 * [7],\n \"listen_feature_id\": 3 * [1],\n \"variable\": 3 * [\"level\"],\n \"greater_than\": [5.0, 10.0, 15.0], # min, setpoint, max\n }\n)\n\nlogic = pd.DataFrame(\n data={\n \"node_id\": 5 * [7],\n \"truth_state\": [\"FFF\", \"U**\", \"T*F\", \"**D\", \"TTT\"],\n \"control_state\": [\"in\", \"in\", \"none\", \"out\", \"out\"],\n }\n)\n\ndiscrete_control = ribasim.DiscreteControl(condition=condition, logic=logic)\n\nThe above control logic can be summarized as follows: - If the level gets above the maximum, activate the control state “out” until the setpoint is reached; - If the level gets below the minimum, active the control state “in” until the setpoint is reached; - Otherwise activate the control state “none”.\nSetup the pump:\n\npump = ribasim.Pump(\n static=pd.DataFrame(\n data={\n \"node_id\": 3 * [2] + 3 * [3],\n \"control_state\": 2 * [\"none\", \"in\", \"out\"],\n \"flow_rate\": [0.0, 2e-3, 0.0, 0.0, 0.0, 2e-3],\n }\n )\n)\n\nThe pump data defines the following:\n\n\n\nControl state\nPump #2 flow rate (m/s)\nPump #3 flow rate (m/s)\n\n\n\n\n“none”\n0.0\n0.0\n\n\n“in”\n2e-3\n0.0\n\n\n“out”\n0.0\n2e-3\n\n\n\nSetup the level boundary:\n\nlevel_boundary = ribasim.LevelBoundary(\n static=pd.DataFrame(data={\"node_id\": [4], \"level\": [10.0]})\n)\n\nSetup the rating curve:\n\nrating_curve = ribasim.TabulatedRatingCurve(\n static=pd.DataFrame(\n data={\"node_id\": 2 * [5], \"level\": [2.0, 15.0], \"discharge\": [0.0, 1e-3]}\n )\n)\n\nSetup the terminal:\n\nterminal = ribasim.Terminal(static=pd.DataFrame(data={\"node_id\": [6]}))\n\nSetup a model:\n\nmodel = ribasim.Model(\n node=node,\n edge=edge,\n basin=basin,\n pump=pump,\n level_boundary=level_boundary,\n tabulated_rating_curve=rating_curve,\n terminal=terminal,\n discrete_control=discrete_control,\n starttime=\"2020-01-01 00:00:00\",\n endtime=\"2021-01-01 00:00:00\",\n)\n\nLet’s take a look at the model:\n\nmodel.plot()\n\n<Axes: >\n\n\n\n\n\nListen edges are plotted with a dashed line since they are not present in the “Edge / static” schema but only in the “Control / condition” schema.\n\ndatadir = Path(\"data\")\nmodel.write(datadir / \"level_setpoint_with_minmax\")\n\nNow run the model with level_setpoint_with_minmax/ribasim.toml. After running the model, read back the results:\n\nfrom matplotlib.dates import date2num\n\ndf_basin = pd.read_feather(datadir / \"level_setpoint_with_minmax/results/basin.arrow\")\ndf_basin_wide = df_basin.pivot_table(\n index=\"time\", columns=\"node_id\", values=[\"storage\", \"level\"]\n)\n\nax = df_basin_wide[\"level\"].plot()\n\ngreater_than = model.discrete_control.condition.greater_than\n\nax.hlines(\n greater_than,\n df_basin.time[0],\n df_basin.time.max(),\n lw=1,\n ls=\"--\",\n color=\"k\",\n)\n\ndf_control = pd.read_feather(\n datadir / \"level_setpoint_with_minmax/results/control.arrow\"\n)\n\ny_min, y_max = ax.get_ybound()\nax.fill_between(df_control.time[:2], 2 * [y_min], 2 * [y_max], alpha=0.2, color=\"C0\")\nax.fill_between(df_control.time[2:4], 2 * [y_min], 2 * [y_max], alpha=0.2, color=\"C0\")\n\nax.set_xticks(\n date2num(df_control.time).tolist(),\n df_control.control_state.tolist(),\n rotation=50,\n)\n\nax.set_yticks(greater_than, [\"min\", \"setpoint\", \"max\"])\nax.set_ylabel(\"level\")\nplt.show()\n\n\n\n\nThe highlighted regions show where a pump is active.\nLet’s print an overview of what happened with control:\n\nmodel.print_discrete_control_record(\n datadir / \"level_setpoint_with_minmax/results/control.arrow\"\n)\n\n0. At 2020-01-01 00:00:00 the control node with ID 7 reached truth state TTT:\n For node ID 1 (Basin): level > 5.0\n For node ID 1 (Basin): level > 10.0\n For node ID 1 (Basin): level > 15.0\n\n This yielded control state \"out\":\n For node ID 2 (Pump): flow_rate = 0.0\n For node ID 3 (Pump): flow_rate = 0.002\n\n1. At 2020-02-09 01:17:29.324000 the control node with ID 7 reached truth state TFF:\n For node ID 1 (Basin): level > 5.0\n For node ID 1 (Basin): level < 10.0\n For node ID 1 (Basin): level < 15.0\n\n This yielded control state \"none\":\n For node ID 2 (Pump): flow_rate = 0.0\n For node ID 3 (Pump): flow_rate = 0.0\n\n2. At 2020-07-05 13:24:51.165000 the control node with ID 7 reached truth state FFF:\n For node ID 1 (Basin): level < 5.0\n For node ID 1 (Basin): level < 10.0\n For node ID 1 (Basin): level < 15.0\n\n This yielded control state \"in\":\n For node ID 2 (Pump): flow_rate = 0.002\n For node ID 3 (Pump): flow_rate = 0.0\n\n3. At 2020-08-11 11:49:59.015000 the control node with ID 7 reached truth state TTF:\n For node ID 1 (Basin): level > 5.0\n For node ID 1 (Basin): level > 10.0\n For node ID 1 (Basin): level < 15.0\n\n This yielded control state \"none\":\n For node ID 2 (Pump): flow_rate = 0.0\n For node ID 3 (Pump): flow_rate = 0.0\n\n\n\nNote that crossing direction specific truth states (containing “U”, “D”) are not present in this overview even though they are part of the control logic. This is because in the control logic for this model these truth states are only used to sustain control states, while the overview only shows changes in control states.\n\n\n4 Model with PID control\nSet up the nodes:\n\nxy = np.array(\n [\n (0.0, 0.0), # 1: FlowBoundary\n (1.0, 0.0), # 2: Basin\n (2.0, 0.5), # 3: Pump\n (3.0, 0.0), # 4: LevelBoundary\n (1.5, 1.0), # 5: PidControl\n (2.0, -0.5), # 6: outlet\n (1.5, -1.0), # 7: PidControl\n ]\n)\n\nnode_xy = gpd.points_from_xy(x=xy[:, 0], y=xy[:, 1])\n\nnode_type = [\n \"FlowBoundary\",\n \"Basin\",\n \"Pump\",\n \"LevelBoundary\",\n \"PidControl\",\n \"Outlet\",\n \"PidControl\",\n]\n\n# Make sure the feature id starts at 1: explicitly give an index.\nnode = ribasim.Node(\n static=gpd.GeoDataFrame(\n data={\"type\": node_type},\n index=pd.Index(np.arange(len(xy)) + 1, name=\"fid\"),\n geometry=node_xy,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the edges:\n\nfrom_id = np.array([1, 2, 3, 4, 6, 5, 7], dtype=np.int64)\nto_id = np.array([2, 3, 4, 6, 2, 3, 6], dtype=np.int64)\n\nlines = ribasim.utils.geometry_from_connectivity(node, from_id, to_id)\nedge = ribasim.Edge(\n static=gpd.GeoDataFrame(\n data={\n \"from_node_id\": from_id,\n \"to_node_id\": to_id,\n \"edge_type\": 5 * [\"flow\"] + 2 * [\"control\"],\n },\n geometry=lines,\n crs=\"EPSG:28992\",\n )\n)\n\nSetup the basins:\n\nprofile = pd.DataFrame(\n data={\"node_id\": [2, 2], \"level\": [0.0, 1.0], \"area\": [1000.0, 1000.0]}\n)\n\nstatic = pd.DataFrame(\n data={\n \"node_id\": [2],\n \"drainage\": [0.0],\n \"potential_evaporation\": [0.0],\n \"infiltration\": [0.0],\n \"precipitation\": [0.0],\n \"urban_runoff\": [0.0],\n }\n)\n\nstate = pd.DataFrame(\n data={\n \"node_id\": [2],\n \"level\": [6.0],\n }\n)\n\nbasin = ribasim.Basin(profile=profile, static=static, state=state)\n\nSetup the pump:\n\npump = ribasim.Pump(\n static=pd.DataFrame(\n data={\n \"node_id\": [3],\n \"flow_rate\": [0.0], # Will be overwritten by PID controller\n }\n )\n)\n\nSetup the outlet:\n\noutlet = ribasim.Outlet(\n static=pd.DataFrame(\n data={\n \"node_id\": [6],\n \"flow_rate\": [0.0], # Will be overwritten by PID controller\n }\n )\n)\n\nSetup flow boundary:\n\nflow_boundary = ribasim.FlowBoundary(\n static=pd.DataFrame(data={\"node_id\": [1], \"flow_rate\": [1e-3]})\n)\n\nSetup flow boundary:\n\nlevel_boundary = ribasim.LevelBoundary(\n static=pd.DataFrame(\n data={\n \"node_id\": [4],\n \"level\": [1.0], # Not relevant\n }\n )\n)\n\nSetup PID control:\n\npid_control = ribasim.PidControl(\n time=pd.DataFrame(\n data={\n \"node_id\": 4 * [5, 7],\n \"time\": [\n \"2020-01-01 00:00:00\",\n \"2020-01-01 00:00:00\",\n \"2020-05-01 00:00:00\",\n \"2020-05-01 00:00:00\",\n \"2020-07-01 00:00:00\",\n \"2020-07-01 00:00:00\",\n \"2020-12-01 00:00:00\",\n \"2020-12-01 00:00:00\",\n ],\n \"listen_node_id\": 4 * [2, 2],\n \"target\": [5.0, 5.0, 5.0, 5.0, 7.5, 7.5, 7.5, 7.5],\n \"proportional\": 4 * [-1e-3, 1e-3],\n \"integral\": 4 * [-1e-7, 1e-7],\n \"derivative\": 4 * [0.0, 0.0],\n }\n )\n)\n\nNote that the coefficients for the pump and the outlet are equal in magnitude but opposite in sign. This way the pump and the outlet equally work towards the same goal, while having opposite effects on the controlled basin due to their connectivity to this basin.\nSetup a model:\n\nmodel = ribasim.Model(\n node=node,\n edge=edge,\n basin=basin,\n flow_boundary=flow_boundary,\n level_boundary=level_boundary,\n pump=pump,\n outlet=outlet,\n pid_control=pid_control,\n starttime=\"2020-01-01 00:00:00\",\n endtime=\"2020-12-01 00:00:00\",\n)\n\nLet’s take a look at the model:\n\nmodel.plot()\n\n<Axes: >\n\n\n\n\n\nWrite the model to a TOML and GeoPackage:\n\ndatadir = Path(\"data\")\nmodel.write(datadir / \"pid_control\")\n\nNow run the model with ribasim pid_control/ribasim.toml. After running the model, read back the results:\n\nfrom matplotlib.dates import date2num\n\ndf_basin = pd.read_feather(datadir / \"pid_control/results/basin.arrow\")\ndf_basin_wide = df_basin.pivot_table(\n index=\"time\", columns=\"node_id\", values=[\"storage\", \"level\"]\n)\nax = df_basin_wide[\"level\"].plot()\nax.set_ylabel(\"level [m]\")\n\n# Plot target level\ntarget_levels = model.pid_control.time.target.to_numpy()[::2]\ntimes = date2num(model.pid_control.time.time)[::2]\nax.plot(times, target_levels, color=\"k\", ls=\":\", label=\"target level\")\npass" + "objectID": "core/usage.html#basin-state", + "href": "core/usage.html#basin-state", + "title": "Usage", + "section": "5.2 Basin / state", + "text": "5.2 Basin / state\nThe state table aims to capture the full state of the Basin, such that it can be used as an initial condition, potentially the outcome of an earlier simulation. Currently only the Basin node types have state.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\nlevel\nFloat64\n\\(m\\)\n\\(\\ge\\) basin bottom\n\n\n\nEach Basin ID needs to be in the table." }, { - "objectID": "python/reference/Pump.html", - "href": "python/reference/Pump.html", - "title": "1 Pump", - "section": "", - "text": "Pump()\nPump water from a source node to a destination node. The set flow rate will be pumped unless the intake storage is less than 10m3, in which case the flow rate will be linearly reduced to 0 m3/s. Negative flow rates are not supported. Note that the intake must always be a Basin.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with constant flow rates.\nrequired" + "objectID": "core/usage.html#basin-profile", + "href": "core/usage.html#basin-profile", + "title": "Usage", + "section": "5.3 Basin / profile", + "text": "5.3 Basin / profile\nThe profile table defines the physical dimensions of the storage reservoir of each basin.\n\n\n\n\n\n\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\narea\nFloat64\n\\(m^2\\)\nnon-negative, per node_id: start positive and increasing\n\n\nlevel\nFloat64\n\\(m\\)\nper node_id: increasing\n\n\n\nThe level is the level at the basin outlet. All levels are defined in meters above a datum that is the same for the entire model. An example of the first 5 rows of such a table is given below. The first 4 rows define the profile of ID 2. The number of rows can vary per ID. Using a very large number of rows may impact performance.\n\n\n\nnode_id\narea\nlevel\n\n\n\n\n2\n1.0\n6.0\n\n\n2\n1000.0\n7.0\n\n\n2\n1000.0\n9.0\n\n\n3\n1.0\n2.2\n\n\n\nWe use the symbol \\(A\\) for area, \\(h\\) for level and \\(S\\) for storage. The profile provides a function \\(A(h)\\) for each basin. Internally this get converted to two functions, \\(A(S)\\) and \\(h(S)\\), by integrating over the function, setting the storage to zero for the bottom of the profile. The minimum area cannot be zero to avoid numerical issues. The maximum area is used to convert the precipitation flux into an inflow." }, { - "objectID": "python/reference/Pump.html#parameters", - "href": "python/reference/Pump.html#parameters", - "title": "1 Pump", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with constant flow rates.\nrequired" + "objectID": "core/usage.html#basin-results", + "href": "core/usage.html#basin-results", + "title": "Usage", + "section": "5.4 Basin results", + "text": "5.4 Basin results\nThe basin table contains results of the storage and level of each basin at every solver timestep. The initial condition is also written to the file.\n\n\n\ncolumn\ntype\nunit\n\n\n\n\ntime\nDateTime\n-\n\n\nnode_id\nInt\n-\n\n\nstorage\nFloat64\n\\(m^3\\)\n\n\nlevel\nFloat64\n\\(m\\)\n\n\n\nThe table is sorted by time, and per time it is sorted by node_id." }, { - "objectID": "python/reference/Basin.html", - "href": "python/reference/Basin.html", - "title": "1 Basin", - "section": "", - "text": "Basin()\nInput for a (sub-)basin: an area of land where all flowing surface water converges to a single point.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nprofile\npandas.DataFrame\nTable describing the geometry.\nrequired\n\n\nstatic\npandas.DataFrame\nTable describing the constant fluxes.\nrequired\n\n\ntime\npandas.DataFrame\nTable describing the time-varying fluxes.\nrequired\n\n\nstate\npandas.DataFrame\nTable describing the initial condition.\nrequired" + "objectID": "core/usage.html#flow-results", + "href": "core/usage.html#flow-results", + "title": "Usage", + "section": "5.5 Flow results", + "text": "5.5 Flow results\nThe flow table contains results of the flow on every edge in the model, for each solver timestep.\n\n\n\ncolumn\ntype\nunit\n\n\n\n\ntime\nDateTime\n-\n\n\nedge_id\nUnion{Int, Missing}\n-\n\n\nfrom_node_id\nInt\n-\n\n\nto_node_id\nInt\n-\n\n\nflow\nFloat64\n\\(m^3 s^{-1}\\)\n\n\n\nThe table is sorted by time, and per time the same edge_id order is used, though not sorted. Flows that are added to the model at a node, have a missing edge_id, and identical from_node_id and to_node_id. Flows out of the model always have a negative sign, and additions a positive sign." }, { - "objectID": "python/reference/Basin.html#parameters", - "href": "python/reference/Basin.html#parameters", - "title": "1 Basin", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nprofile\npandas.DataFrame\nTable describing the geometry.\nrequired\n\n\nstatic\npandas.DataFrame\nTable describing the constant fluxes.\nrequired\n\n\ntime\npandas.DataFrame\nTable describing the time-varying fluxes.\nrequired\n\n\nstate\npandas.DataFrame\nTable describing the initial condition.\nrequired" + "objectID": "core/usage.html#tabulatedratingcurve-time", + "href": "core/usage.html#tabulatedratingcurve-time", + "title": "Usage", + "section": "7.1 TabulatedRatingCurve / time", + "text": "7.1 TabulatedRatingCurve / time\nThis table is the transient form of the TabulatedRatingCurve table. The only difference is that a time column is added. The table must by sorted by time, and per time it must be sorted by node_id. With this the rating curves can be updated over time. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\ntime\nDateTime\n-\nsorted\n\n\nnode_id\nInt\n-\nsorted per time\n\n\nlevel\nFloat64\n\\(m\\)\n-\n\n\ndischarge\nFloat64\n\\(m^3 s^{-1}\\)\nnon-negative" }, { - "objectID": "python/reference/LinearResistance.html", - "href": "python/reference/LinearResistance.html", - "title": "1 LinearResistance", - "section": "", - "text": "LinearResistance()\nFlow through this connection linearly depends on the level difference between the two connected basins.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with the constant resistances.\nrequired" + "objectID": "core/usage.html#user-time", + "href": "core/usage.html#user-time", + "title": "Usage", + "section": "10.1 User / time", + "text": "10.1 User / time\nThis table is the transient form of the User table. The only difference is that a time column is added and activity is assumed to be true. The table must by sorted by time, and per time it must be sorted by node_id. With this the demand can be updated over time. In between the given times the demand is interpolated linearly, and outside the demand is constant given by the nearest time value. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\n\n\n\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\ntime\nDateTime\n-\nsorted per priority per node id\n\n\ndemand\nFloat64\n\\(m^3 s^{-1}\\)\n-\n\n\nreturn_factor\nFloat64\n-\nbetween [0 - 1]\n\n\nmin_level\nFloat64\n\\(m\\)\n(optional)\n\n\npriority\nInt\n-\nsorted per node id" }, { - "objectID": "python/reference/LinearResistance.html#parameters", - "href": "python/reference/LinearResistance.html#parameters", - "title": "1 LinearResistance", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npd.DataFrame\nTable with the constant resistances.\nrequired" + "objectID": "core/usage.html#levelboundary-time", + "href": "core/usage.html#levelboundary-time", + "title": "Usage", + "section": "11.1 LevelBoundary / time", + "text": "11.1 LevelBoundary / time\nThis table is the transient form of the LevelBoundary table. The only difference is that a time column is added and activity is assumed to be true. The table must by sorted by time, and per time it must be sorted by node_id. With this the levels can be updated over time. In between the given times the level is interpolated linearly, and outside the flow rate is constant given by the nearest time value. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\ntime\nDateTime\n-\nsorted\n\n\nnode_id\nInt\n-\nsorted per time\n\n\nlevel\nFloat64\n\\(m\\)\n-" }, { - "objectID": "python/reference/FractionalFlow.html", - "href": "python/reference/FractionalFlow.html", - "title": "1 FractionalFlow", - "section": "", - "text": "FractionalFlow()\nReceives a fraction of the flow. The fractions must sum to 1.0 for a furcation.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable with the constant flow fractions.\nrequired" + "objectID": "core/usage.html#flowboundary-time", + "href": "core/usage.html#flowboundary-time", + "title": "Usage", + "section": "12.1 FlowBoundary / time", + "text": "12.1 FlowBoundary / time\nThis table is the transient form of the FlowBoundary table. The only differences are that a time column is added and the nodes are assumed to be active so this column is removed. The table must by sorted by time, and per time it must be sorted by node_id. With this the flow rates can be updated over time. In between the given times the flow rate is interpolated linearly, and outside the flow rate is constant given by the nearest time value. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\ntime\nDateTime\n-\nsorted\n\n\nnode_id\nInt\n-\nsorted per time\n\n\nflow_rate\nFloat64\n\\(m^3 s^{-1}\\)\nnon-negative" }, { - "objectID": "python/reference/FractionalFlow.html#parameters", - "href": "python/reference/FractionalFlow.html#parameters", - "title": "1 FractionalFlow", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\npandas.DataFrame\nTable with the constant flow fractions.\nrequired" + "objectID": "core/usage.html#sec-condition", + "href": "core/usage.html#sec-condition", + "title": "Usage", + "section": "16.1 DiscreteControl / condition", + "text": "16.1 DiscreteControl / condition\nThe condition schema defines conditions of the form ‘the discrete_control node with this node id listens to whether the given variable of the node with the given listen feature id is grater than the given value’. If the condition variable comes from a time-series, a look ahead \\(\\Delta t\\) can be supplied.\n\n\n\n\n\n\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\nlisten_feature_id\nInt\n-\n-\n\n\nvariable\nString\n-\nmust be “level” or “flow_rate”\n\n\ngreater_than\nFloat64\nvarious\n-\n\n\nlook_ahead\nFloat64\n\\(s\\)\nOnly on transient boundary conditions, non-negative (optional, default 0)" }, { - "objectID": "python/reference/Node.html", - "href": "python/reference/Node.html", - "title": "1 Node", - "section": "", - "text": "Node()\nThe Ribasim nodes as Point geometries.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nstatic\ngeopandas.GeoDataFrame\nTable with node ID, type and geometry.\nrequired\n\n\n\n\n\n\n\n\n\nName\nDescription\n\n\n\n\nplot\nPlot the nodes. Each node type is given a separate marker.\n\n\nwrite_layer\nWrite the contents of the input to a database.\n\n\n\n\n\nNode.plot(ax=None, zorder=None)\nPlot the nodes. Each node type is given a separate marker.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nax\nOptional\nThe axis on which the nodes will be plotted.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nNone\n\n\n\n\n\n\n\n\nNode.write_layer(path)\nWrite the contents of the input to a database.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\n\nrequired" + "objectID": "core/usage.html#discretecontrol-logic", + "href": "core/usage.html#discretecontrol-logic", + "title": "Usage", + "section": "16.2 DiscreteControl / logic", + "text": "16.2 DiscreteControl / logic\nThe logic schema defines which control states are triggered based on the truth of the conditions a discrete_control node listens to. DiscreteControl is applied in the Julia core as follows:\n\nDuring the simulation it is checked whether the truth of any of the conditions changes.\nWhen a condition changes, the corresponding discrrete_control node id is retrieved (node_id in the condition schema above).\nThe truth value of all the conditions this discrete_control node lisens to are retrieved, in the order as they are specified in the condition schema. This is then converted into a string of “T” for true and “F” for false. This string we call the truth state.*\nThe table below determines for the given discrete_control node ID and truth state what the corresponding control state is.\nFor all the nodes this discrete_control node affects (as given by the “control” edges in Edges / static), their parameters are set to those parameters in NodeType / static corresponding to the determined control state.\n\n*. There is also a second truth state created in which for the last condition that changed it is specified whether it was an upcrossing (“U”) or downcrossing (“D”) of the threshold (greater than) value. If a control state is specified for a truth state that is crossing-specific, this takes precedence over the control state for the truth state that contains only “T” and “F”.\n\n\n\n\n\n\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted\n\n\ntruth_state\nString\n-\nConsists of the characters “T” (true), “F” (false), “U” (upcrossing), “D” (downcrossing) and “*” (any)\n\n\ncontrol_state\nString\n-" }, { - "objectID": "python/reference/Node.html#parameters", - "href": "python/reference/Node.html#parameters", - "title": "1 Node", - "section": "", - "text": "Name\nType\nDescription\nDefault\n\n\n\n\nstatic\ngeopandas.GeoDataFrame\nTable with node ID, type and geometry.\nrequired" + "objectID": "core/usage.html#discretecontrol-results", + "href": "core/usage.html#discretecontrol-results", + "title": "Usage", + "section": "16.3 DiscreteControl results", + "text": "16.3 DiscreteControl results\nThe control table contains a record of each change of control state: when it happened, which control node was involved, to which control state it changed and based on which truth state.\n\n\n\ncolumn\ntype\n\n\n\n\ntime\nDateTime\n\n\ncontrol_node_id\nInt\n\n\ntruth_state\nString\n\n\ncontrol_state\nString" }, { - "objectID": "python/reference/Node.html#methods", - "href": "python/reference/Node.html#methods", - "title": "1 Node", - "section": "", - "text": "Name\nDescription\n\n\n\n\nplot\nPlot the nodes. Each node type is given a separate marker.\n\n\nwrite_layer\nWrite the contents of the input to a database.\n\n\n\n\n\nNode.plot(ax=None, zorder=None)\nPlot the nodes. Each node type is given a separate marker.\n\n\n\n\n\n\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\nax\nOptional\nThe axis on which the nodes will be plotted.\nNone\n\n\n\n\n\n\n\n\n\nType\nDescription\n\n\n\n\nNone\n\n\n\n\n\n\n\n\nNode.write_layer(path)\nWrite the contents of the input to a database.\n\n\n\n\n\nName\nType\nDescription\nDefault\n\n\n\n\npath\nFilePath\n\nrequired" + "objectID": "core/usage.html#pidcontrol-time", + "href": "core/usage.html#pidcontrol-time", + "title": "Usage", + "section": "17.1 PidControl / time", + "text": "17.1 PidControl / time\nThis table is the transient form of the PidControl table. The differences are that a time column is added and the nodes are assumed to be active so this column is removed. The table must by sorted by time, and per time it must be sorted by node_id. With this the target level and PID coefficients can be updated over time. In between the given times the these values interpolated linearly, and outside these values area constant given by the nearest time value. Note that a node_id can be either in this table or in the static one, but not both.\n\n\n\ncolumn\ntype\nunit\nrestriction\n\n\n\n\nnode_id\nInt\n-\nsorted per time\n\n\ntime\nDateTime\n-\nsorted\n\n\nlisten_node_id\nInt\n-\n-\n\n\ntarget\nFloat64\n\\(m\\)\n-\n\n\nproportional\nFloat64\n\\(s^{-1}\\)\n-\n\n\nintegral\nFloat64\n\\(s^{-2}\\)\n-\n\n\nderivative\nFloat64\n-\n-" }, { - "objectID": "python/reference/index.html", - "href": "python/reference/index.html", - "title": "1 API Reference", + "objectID": "core/numerics.html", + "href": "core/numerics.html", + "title": "Numerical considerations", "section": "", - "text": "The Model class represents an entire Ribasim model.\n\n\n\nModel\nA full Ribasim model schematisation with all input.\n\n\n\n\n\n\nThe Node and Edge database layers define the network layout.\n\n\n\nNode\nThe Ribasim nodes as Point geometries.\n\n\nEdge\nDefines the connections between nodes.\n\n\n\n\n\n\nAvailable node types to model different situations.\n\n\n\nBasin\nInput for a (sub-)basin: an area of land where all flowing surface water converges to a single point.\n\n\nFractionalFlow\nReceives a fraction of the flow. The fractions must sum to 1.0 for a furcation.\n\n\nLevelBoundary\nStores water at a given level unaffected by flow, like an infinitely large basin.\n\n\nLinearResistance\nFlow through this connection linearly depends on the level difference\n\n\nManningResistance\nFlow through this connection is estimated by conservation of energy and the\n\n\nPump\nPump water from a source node to a destination node.\n\n\nTabulatedRatingCurve\nLinearly interpolates discharge between a tabulation of level and discharge.\n\n\n\n\n\n\nCollection of utility functions.\n\n\n\nutils.geometry_from_connectivity\nCreate edge shapely geometries from connectivities.\n\n\nutils.connectivity_from_geometry\nDerive from_node_id and to_node_id for every edge in lines. LineStrings" + "text": "We want to solve the following initial value problem: \\[\n\\begin{cases}\n \\frac{\\text{d}\\mathbf{u}}{\\text{d}t} = \\mathbf{f}(\\mathbf{u},t) \\quad t_0 < t < t_\\text{end} \\\\\n \\mathbf{u}(t_0) = \\mathbf{u}_0\n\\end{cases},\n\\tag{1}\\]\nwhere \\(\\mathbf{f}\\) denotes water_balance! and \\(\\mathbf{u_0}\\) the initial storages (and the PID integrals which start out at \\(0\\)).\nIn general \\(\\mathbf{f}\\) is a non-linear function in \\(\\mathbf{u}\\). These non-linearities are introduced by:\nThe problem Equation 1 can be solved by various numerical time-integration methods. To do this the time interval \\([t_0,t_\\text{end}]\\) is discretized into a finite number of time points \\(t_0 < t_1 < \\ldots < t_N = t_\\text{end}\\) for which approximate solutions \\(\\mathbf{w}_n \\approx \\mathbf{u}(t_n)\\) are computed. In general we do not assume a fixed timestep (the interval between successive points in time). Rather, the solver attempts to make as large a step as possible while keeping error tolerances within requirements. The solver settings section details the available configuration options." }, { - "objectID": "python/reference/index.html#model", - "href": "python/reference/index.html#model", - "title": "1 API Reference", - "section": "", - "text": "The Model class represents an entire Ribasim model.\n\n\n\nModel\nA full Ribasim model schematisation with all input." + "objectID": "core/numerics.html#euler-forward", + "href": "core/numerics.html#euler-forward", + "title": "Numerical considerations", + "section": "1.1 Euler forward", + "text": "1.1 Euler forward\nThe simplest numerical method is Euler forward: \\[\n\\mathbf{w}_{n+1} = \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{w}_n, t_n).\n\\tag{2}\\]\nHere \\(\\mathbf{w}_{n+1}\\) is given as a simple explicit function of \\(\\mathbf{w}_n\\)." }, { - "objectID": "python/reference/index.html#network", - "href": "python/reference/index.html#network", - "title": "1 API Reference", - "section": "", - "text": "The Node and Edge database layers define the network layout.\n\n\n\nNode\nThe Ribasim nodes as Point geometries.\n\n\nEdge\nDefines the connections between nodes." + "objectID": "core/numerics.html#euler-backward", + "href": "core/numerics.html#euler-backward", + "title": "Numerical considerations", + "section": "1.2 Euler backward", + "text": "1.2 Euler backward\nEuler backward is formulated as follows: \\[\n\\mathbf{w}_{n+1} = \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{w}_{n+1},t_{n+1}).\n\\tag{3}\\]\nNote that this is an implicit equation for \\(\\mathbf{w}_{n+1}\\), which is non-linear because of the non-linearity of \\(\\mathbf{f}\\).\nGenerally one of the following iterative methods is used for finding solutions to non-linear equations like this:\n\nPicard iteration for fixed points. This method aims to approximate \\(\\mathbf{w}_{n+1}\\) as a fixed point of the function \\[\n\\mathbf{g}(\\mathbf{x}) = \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{x},t_{n+1})\n\\] by iterating \\(\\mathbf{g}\\) on an initial guess of \\(\\mathbf{w}_{n+1}\\);\nNewton-Raphson iterations: approximate \\(\\mathbf{w}_{n+1}\\) as a root of the function \\[\n\\mathbf{h}(\\mathbf{x}) = \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{x},t_{n+1}) - \\mathbf{x},\n\\] by iteratively finding the root of its linearized form: \\[\n\\begin{align}\n\\mathbf{0} =& \\mathbf{h}(\\mathbf{w}_{n+1}^k) + \\mathbf{J}(\\mathbf{h})(\\mathbf{w}_{n+1}^k)(\\mathbf{w}_{n+1}^{k+1}-\\mathbf{w}_{n+1}^k) \\\\\n=& \\mathbf{w}_n + (t_{n+1}-t_n)\\mathbf{f}(\\mathbf{w}_{n+1}^k,t_{n+1}) - \\mathbf{w}_{n+1}^k \\\\ +&\\left[(t_{n+1}-t_n)\\mathbf{J}(\\mathbf{f})(\\mathbf{w}_{n+1}^k)-\\mathbf{I}\\right](\\mathbf{w}_{n+1}^{k+1}-\\mathbf{w}_{n+1}^k).\n\\end{align}\n\\tag{4}\\] Note that this thus requires an evaluation of the Jacobian of \\(\\mathbf{f}\\) and solving a linear system per iteration." }, { - "objectID": "python/reference/index.html#node-types", - "href": "python/reference/index.html#node-types", - "title": "1 API Reference", - "section": "", - "text": "Available node types to model different situations.\n\n\n\nBasin\nInput for a (sub-)basin: an area of land where all flowing surface water converges to a single point.\n\n\nFractionalFlow\nReceives a fraction of the flow. The fractions must sum to 1.0 for a furcation.\n\n\nLevelBoundary\nStores water at a given level unaffected by flow, like an infinitely large basin.\n\n\nLinearResistance\nFlow through this connection linearly depends on the level difference\n\n\nManningResistance\nFlow through this connection is estimated by conservation of energy and the\n\n\nPump\nPump water from a source node to a destination node.\n\n\nTabulatedRatingCurve\nLinearly interpolates discharge between a tabulation of level and discharge." + "objectID": "core/numerics.html#basin-profiles", + "href": "core/numerics.html#basin-profiles", + "title": "Numerical considerations", + "section": "4.1 Basin profiles", + "text": "4.1 Basin profiles\nThe basin profiles affect \\(\\mathbf{f}\\) in many ways, anywhere where a basin level or area is required.\n\n\n\n\n\n\nNote\n\n\n\nThis section needs to be updated and extended after once this issue is resolved." }, { - "objectID": "python/reference/index.html#utility-functions", - "href": "python/reference/index.html#utility-functions", - "title": "1 API Reference", - "section": "", - "text": "Collection of utility functions.\n\n\n\nutils.geometry_from_connectivity\nCreate edge shapely geometries from connectivities.\n\n\nutils.connectivity_from_geometry\nDerive from_node_id and to_node_id for every edge in lines. LineStrings" + "objectID": "core/numerics.html#qh-relations", + "href": "core/numerics.html#qh-relations", + "title": "Numerical considerations", + "section": "4.2 Q(h) relations", + "text": "4.2 Q(h) relations\nTabulatedRatingCurve nodes contribute to \\(\\mathbf{f}\\) with terms of the following form:\n\\[\n Q(h(S))\n\\]\nwhere the continuity of this term is given by the least continuous of \\(Q\\) and \\(h\\)." }, { - "objectID": "python/index.html", - "href": "python/index.html", - "title": "Python tooling", - "section": "", - "text": "The Ribasim Python package (named ribasim) aims to make it easy to build, update and analyze Ribasim models programmatically.\nThe Ribasim QGIS plugin allows users to construct a model from scratch without programming. For specific tasks, like adding observed rainfall timeseries, it can be faster to use Python instead.\nOne can also use Ribasim Python to build entire models from base data, such that your model setup is fully reproducible.\nThe package is registered in PyPI and can therefore be installed with pip:\npip install ribasim\nFor wheel (.whl) downloads, including nightly builds, see the download section. After downloading wheels can be installed by referring to the correct path:\npip install path/to/ribasim-*.whl\nFor documentation please see the examples and API reference." + "objectID": "core/numerics.html#empty-basins", + "href": "core/numerics.html#empty-basins", + "title": "Numerical considerations", + "section": "4.3 Empty basins", + "text": "4.3 Empty basins\nReduction factors are introduced at several points in the definition of \\(\\mathbf{f}\\) to smooth out otherwise discontinuous transitions (e.g. the flow rate of a pump going to zero when the source basin dries out). If flows are not too large with respect to basin storage, this will prevent basins from reaching 0. Rather, the basin gets a very small storage. The reduction factors help with performance, but are also an important tool to avoid getting negative storage in basins. Negative storage needs to be avoided since it is not a real solution, and would introduce water into the model that doesn’t exist. Another tool used to avoid negative storage is the isoutoutofdomain option, which Ribasim makes use of. This reject timesteps that lead to negative storage, instead retrying with a smaller timestep." } ] \ No newline at end of file