API

The following functions are designed for public use.

Network Construction API

NetworkDynamics.NetworkType
Network([g,] vertexf, edgef; kwarg...)

Construct a Network object from a graph g and edge and component models vertexf and edgef.

Arguments:

  • g::AbstractGraph: The graph on which the network is defined. Optional, can be ommittet if all component models have a defined graphelement. See vidx and src/dst keywors for VertexModel and EdgeModel constructors respectively.

  • vertexm: A single VertexModel or a vector of VertexModel objects. The order of the vertex models must mirror the order of the vertices(g) iterator.

  • edgem: A single EdgeModel or a vector of EdgeModel objects. The order of the edge models must mirror the order of the edges(g) iterator.

Optional keyword arguments:

  • execution=SequentialExecution{true}(): Execution model of the network. E.g. SequentialExecution, KAExecution, PolyesterExecution or ThreadedExecution.
  • aggregator=execution isa SequentialExecution ? SequentialAggregator(+) : PolyesterAggregator(+): Aggregation function applied to the edge models. E.g. SequentialAggregator, PolyesterAggregator, ThreadedAggregator, SparseAggregator.
  • check_graphelement=true: Check if the graphelement metadata is consistent with the graph.
  • dealias=false Check if the components alias eachother and create copies if necessary. This is necessary if the same component model is referenced in multiple places in the Network but you want to dynamicially asign metadata, such as initialization information to specific instances.
  • verbose=false: Show additional information during construction.
source
Network(nw::Network; g, vertexm, edgem, kwargs...)

Rebuild the Network with same graph and vertex/edge models but possibly different kwargs.

source
NetworkDynamics.dimMethod
dim(nw::Network)

Returns the number of dynamic states in the network, corresponts to the length of the flat state vector.

source
NetworkDynamics.pdimMethod
pdim(nw::Network)

Returns the number of parameters in the network, corresponts to the length of the flat parameter vector.

source

Component Models

NetworkDynamics.VertexModelMethod
VertexModel(; kwargs...)

Build a VertexModel according to the keyword arguments.

Main Arguments:

  • f=nothing: Dynamic function of the component. Can be nothing if dim is 0.
  • g: Output function of the component. Usefull helpers: StateMask
  • sym/dim: Symbolic names of the states. If dim is provided, sym is set automaticially.
  • outsym/outdim: Symbolic names of the outputs. If outdim is provided, outsym is set automaticially. Can be infered automaticially if g isa StateMask.
  • psym/pdim=0: Symbolic names of the parameters. Ifpdimis provided,psym` is set automaticially.
  • mass_matrix=I: Mass matrix of component. Can be a vector v and is then interpreted as Diagonal(v).
  • name=dim>0 ? :VertexM : :StaticVertexM: Name of the component.

Optional Arguments:

  • insym/indim: Symbolic names of the inputs. If indim is provided, insym is set automaticially.
  • vidx: Index of the vertex in the graph, enables graphless constructor.
  • ff: FeedForwardType of component. Will be typically infered from g automaticially.
  • obssym/obsf: Define additional "observable" states.
  • symmetadata/metadata: Provide prefilled metadata dictionaries.
  • extin=nothing: Define "external" inputs for the model with Network indices, i.e. extin=[VIndex(7,:x), ..]. Those inputs will be provided as another input vector f(x, in, extin, p, t) and g(y, x, in, extin, p, t).

All Symbol arguments can be used to set default values, i.e. psym=[:K=>1, :p].

source
NetworkDynamics.EdgeModelMethod
EdgeModel(; kwargs...)

Build a EdgeModel according to the keyword arguments.

Main Arguments:

  • f=nothing: Dynamic function of the component. Can be nothing if dim is 0.
  • g: Output function of the component. Usefull helpers: AntiSymmetric, Symmetric, Fiducial, Directed and StateMask.
  • sym/dim: Symbolic names of the states. If dim is provided, sym is set automaticially.
  • outsym/outdim: Symbolic names of the outputs. If outdim is provided, outsym is set automaticially. In general, outsym for edges isa named tuple (; src, dst). However, depending on the g function, it might be enough to provide a single vector or even nothing (e.g. AntiSymmetric(StateMask(1:2))). See Building EdgeModels for examples.
  • psym/pdim=0: Symbolic names of the parameters. Ifpdimis provided,psym` is set automaticially.
  • mass_matrix=I: Mass matrix of component. Can be a vector v and is then interpreted as Diagonal(v).
  • name=dim>0 ? :EdgeM : :StaticEdgeM: Name of the component.

Optional Arguments:

  • insym/indim: Symbolic names of the inputs. If indim is provided, insym is set automaticially. For edges, insym is a named tuple (; src, dst). If give as vector tuple is created automaticially.
  • src/dst: Index or name of the vertices at src and dst end. Enables graphless constructor.
  • ff: FeedForwardType of component. Will be typically infered from g automaticially.
  • obssym/obsf: Define additional "observable" states.
  • symmetadata/metadata: Provide prefilled metadata dictionaries.
  • extin=nothing: Define "external" inputs for the model with Network indices, i.e. extin=[VIndex(7,:x), ..]. Those inputs will be provided as another input vector f(x, insrc, indst, extin, p, t) and g(ysrc, ydst, x, insrc, indst, extin, p, t).

All Symbol arguments can be used to set default values, i.e. psym=[:K=>1, :p].

source

Component Models with MTK

NetworkDynamics.VertexModelMethod
VertexModel(sys::ODESystem, inputs, outputs;
            verbose=false, name=getname(sys), extin=nothing, ff_to_constraint=true, kwargs...)

Create a VertexModel object from a given ODESystem created with ModelingToolkit. You need to provide 2 lists of symbolic names (Symbol or Vector{Symbols}):

  • inputs: names of variables in you equation representing the aggregated edge states
  • outputs: names of variables in you equation representing the node output

Additional kw arguments:

  • name: Set name of the component model. Will be lifted from the ODESystem name.
  • extin=nothing: Provide external inputs as pairs, i.e. extin=[:extvar => VIndex(1, :a)] will bound the variable extvar(t) in the equations to the state a of the first vertex.
  • ff_to_constraint=true: Controlls, whether output transformations g which depend on inputs should be transformed into constraints. Defaults to true since ND.jl does not handle vertices with FF yet.
source
NetworkDynamics.EdgeModelMethod
EdgeModel(sys::ODESystem, srcin, dstin, srcout, dstout;
          verbose=false, name=getname(sys), extin=nothing, ff_to_constraint=false, kwargs...)

Create a EdgeModel object from a given ODESystem created with ModelingToolkit. You need to provide 4 lists of symbolic names (Symbol or Vector{Symbols}):

  • srcin: names of variables in you equation representing the node state at the source
  • dstin: names of variables in you equation representing the node state at the destination
  • srcout: names of variables in you equation representing the output at the source
  • dstout: names of variables in you equation representing the output at the destination

Additional kw arguments:

  • name: Set name of the component model. Will be lifted from the ODESystem name.
  • extin=nothing: Provide external inputs as pairs, i.e. extin=[:extvar => VIndex(1, :a)] will bound the variable extvar(t) in the equations to the state a of the first vertex.
  • ff_to_constraint=false: Controlls, whether output transformations g which depend on inputs should be transformed into constraints.
source
NetworkDynamics.EdgeModelMethod
EdgeModel(sys::ODESystem, srcin, dstin, AntiSymmetric(dstout); kwargs...)

Create a EdgeModel object from a given ODESystem created with ModelingToolkit for single sided models.

Here you only need to provide one list of output symbols: dstout. To make it clear how to handle the single-sided output definiton, you musst wrap the symbol vector in

  • AntiSymmetric(dstout),
  • Symmetric(dstout), or
  • Directed(dstout).

Additional kwargs are the same as for the double-sided EdgeModel MTK constructor.

source

Output Function Helpers/Wrappers

NetworkDynamics.StateMaskType
StateMask(i::AbstractArray)
StateMaks(i::Number)

A StateMask is a predefined output function. It can be used to define the output of a component model by picking from the internal state.

I.e. g=StateMask(2:3) in a vertex function will output the internal states 2 and 3. In many contexts, StateMasks can be constructed implicitly by just providing the indices, e.g. g=1:2.

For EdgeModel this needs to be combined with a Directed, Symmetric, AntiSymmetric or Fiducial coupling, e.g. g=Fiducial(1:2, 3:4) forwards states 1:2 to dst and states 3:4 to src.

source

Accessors for Component Properties

NetworkDynamics.outdimFunction
outdim(c::VertexModel)::Int
outdim(c::EdgeModel)::@NamedTuple(src::Int, dst::Int)

Retrieve the output dimension of the component

source
NetworkDynamics.outsymFunction

outsym(c::VertexModel)::Vector{Symbol} outsym(c::EdgeModel)::@NamedTuple{src::Vector{Symbol}, dst::Vector{Symbol}}

Retrieve the output symbols of the component.

source
NetworkDynamics.insymFunction
insym(c::VertexModel)::Vector{Symbol}
insym(c::EdgeModel)::@NamedTuple{src::Vector{Symbol}, dst::Vector{Symbol}}

Musst be called after hasinsym/hasindim returned true. Gives the insym vector(s). For vertex model just a single vector, for edges it returns a named tuple (; src, dst) with two symbol vectors.

source

FeedForwardType-Traits

Symbolic Indexing API

Network Parameter Object

NetworkDynamics.NWParameterType
NWParameter(nw_or_nw_wraper, pflat)

Indexable wrapper for flat parameter array pflat. Needs Network or wrapper of Network, e.g. ODEProblem.

p = NWParameter(nw)
p.v[idx, :sym] # get parameter :sym of vertex idx
p.e[idx, :sym] # get parameter :sym of edge idx
p[s::Union{VPIndex, EPIndex}] # get parameter for specific index

Get flat array representation using pflat. The order of parameters in the flat representation corresponds to the order given by parameter_symbols.

source
NetworkDynamics.NWParameterMethod
NWParameter(nw_or_nw_wraper;
            ptype=Vector{Float64}, pfill=filltype(ptype), default=true)

Creates "empty" NWParameter object for the Network/Wrapper nw with flat type ptype. The array will be prefilled with pfill (defaults to NaN).

If default=true the default parameter values attached to the network components will be loaded.

source
NetworkDynamics.pflatFunction
pflat(p::NWParameter)
pflat(s::NWState)

Retrieve the wrapped flat array representation of the parameters. The order of parameters in this flat representation corresponds exactly to the order given by parameter_symbols.

source

Network State Object

NetworkDynamics.NWStateType
NWState(nw_or_nw_wrapper, uflat, [pflat], [t])

Indexable wrapper for flat state & parameter array. Needs Network or wrapper of Network, e.g. ODEProblem.

s = NWState(nw)
s.v[idx, :sym] # get state :sym of vertex idx
s.e[idx, :sym] # get state :sym of edge idx
s.p.v[idx, :sym] # get parameter :sym of vertex idx
s.p.e[idx, :sym] # get parameter :sym of edge idx
s[s::Union{VIndex, EIndex, EPIndex, VPIndex}] # get parameter for specific index

Get flat array representation using uflat and pflat. The order of states in the flat representation corresponds to the order given by variable_symbols, and the order of parameters corresponds to parameter_symbols.

source
NetworkDynamics.NWStateMethod
NWState(nw_or_nw_wrapper;
        utype=Vector{Float64}, ufill=filltype(utype),
        ptype=Vector{Float64}, pfill=filltype(ptype), default=true)

Creates "empty" NWState object for the Network/Wrapper nw with flat types utype & ptype. The arrays will be prefilled with ufill and pfill respectively (defaults to NaN).

If default=true the default state & parameter values attached to the network components will be loaded.

source
NetworkDynamics.NWStateMethod
NWState(p::NWState; utype=typeof(uflat(s)), ptype=typeof(pflat(s)))

Create NWState based on other state object, just convert types.

source
NetworkDynamics.NWStateMethod
NWState(p::NWParameter; utype=Vector{Float64}, ufill=filltype(utype), default=true)

Create NWState based on existing NWParameter object.

source
NetworkDynamics.uflatFunction
uflat(s::NWState)

Retrieve the wrapped flat array representation of the state. The order of states in this flat representation corresponds exactly to the order given by variable_symbols.

source

Symbolic Indices

NetworkDynamics.VIndexType
VIndex{C,S} <: SymbolicStateIndex{C,S}
idx = VIndex(comp, sub)

A symbolic index for a vertex state variable.

  • comp: the component index, either int, symbol or a collection
  • sub: the subindex, either int, symbol or a collection of those.
VIndex(1, :P)      # vertex 1, variable :P
VIndex(1:5, 1)     # first state of vertices 1 to 5
VIndex(7, (:x,:y)) # states :x and :y of vertex 7
VIndex(2)          # references the second vertex model
VIndex(:a)         # references vertex with unique name :a

Can be used to index into objects supporting the SymbolicIndexingInterface, e.g. NWState, NWParameter or ODESolution.

See also: EIndex, VPIndex, EPIndex

source
NetworkDynamics.EIndexType
EIndex{C,S} <: SymbolicStateIndex{C,S}
idx = EIndex(comp, sub)

A symbolic index for an edge state variable.

  • comp: the component index, either int, symbol, pair or a collection
  • sub: the subindex, either int, symbol or a collection of those.
EIndex(1, :P)      # edge 1, variable :P
EIndex(1:5, 1)     # first state of edges 1 to 5
EIndex(7, (:x,:y)) # states :x and :y of edge 7
EIndex(2)          # references the second edge model
EIndex(1=>2)       # references edge from v1 to v2
EIndex(:a=>:b)     # references edge from (uniquely named) vertex :a to :b

Can be used to index into objects supporting the SymbolicIndexingInterface, e.g. NWState, NWParameter or ODESolution.

See also: VIndex, VPIndex, EPIndex

source
NetworkDynamics.VPIndexType
VPIndex{C,S} <: SymbolicStateIndex{C,S}
idx = VPIndex(comp, sub)

A symbolic index into the parameter a vertex:

  • comp: the component index, either int, symbol or a collection
  • sub: the subindex, either int, symbol or a collection of those.

Can be used to index into objects supporting the SymbolicIndexingInterface, e.g. NWParameter or ODEProblem.

See also: EPIndex, VIndex, EIndex

source
NetworkDynamics.EPIndexType
EPIndex{C,S} <: SymbolicStateIndex{C,S}
idx = VEIndex(comp, sub)

A symbolic index into the parameter of an edge:

  • comp: the component index, either int, symbol, pair or a collection
  • sub: the subindex, either int, symbol or a collection of those.

Can be used to index into objects supporting the SymbolicIndexingInterface, e.g. NWParameter or ODEProblem.

See also: VPIndex, VIndex, EIndex

source
NetworkDynamics.@obsexMacro
@obsex([name =] expression)

Define observable expressions, which are simple combinations of knonw states/parameters/observables. @obsex(...) returns an ObservableExpression which can be used as an symbolic index. This is mainly intended for quick plotting or export of common "derived" variables, such as the argument of a 2-component complex state. For example:

sol(t; idxs=@obsex(arg = atan(VIndex(1,:u_i), VIndex(1,:u_r))]
sol(t; idxs=@obsex(δrel = VIndex(1,:δ) - VIndex(2,:δ)))
source

Index generators

NetworkDynamics.vidxsFunction
vidxs([inpr], components=:, variables=:) :: Vector{VIndex}

Generate vector of symbolic indexes for vertices.

  • inpr: Only needed for name matching or : access. Can be Network, sol, prob, ...
  • components: Number/Vector, :, Symbol (name matches), String/Regex (name contains)
  • variables: Symbol/Number/Vector, :, String/Regex (all sym containing)

Examples:

vidxs(nw)                 # all vertex state indices
vidxs(1:2, :u)            # [VIndex(1, :u), VIndex(2, :u)]
vidxs(nw, :, [:u, :v])    # [VIndex(i, :u), VIndex(i, :v) for i in 1:nv(nw)]
vidxs(nw, "ODEVertex", :) # all symbols of all vertices with name containing "ODEVertex"
source
NetworkDynamics.eidxsFunction
vidxs([inpr], components=:, variables=:) :: Vector{EIndex}

Generate vector of symbolic indexes for edges.

  • inpr: Only needed for name matching or : access. Can be Network, sol, prob, ...
  • components: Number/Vector, :, Symbol (name matches), String/Regex (name contains)
  • variables: Symbol/Number/Vector, :, String/Regex (all sym containing)

Examples:

eidxs(nw)                # all edge state indices
eidxs(1:2, :u)           # [EIndex(1, :u), EIndex(2, :u)]
eidxs(nw, :, [:u, :v])   # [EIndex(i, :u), EIndex(i, :v) for i in 1:ne(nw)]
eidxs(nw, "FlowEdge", :) # all symbols of all edges with name containing "FlowEdge"
source
NetworkDynamics.vpidxsFunction
vpidxs([inpr], components=:, variables=:) :: Vector{VPIndex}

Generate vector of symbolic indexes for parameters. See vidxs for more information.

source
NetworkDynamics.epidxsFunction
epidxs([inpr], components=:, variables=:) :: Vector{EPIndex}

Generate vector of symbolic indexes for parameters. See eidxs for more information.

source

Metadata API

Component Metadata API

NetworkDynamics.has_metadataMethod
has_metadata(c::ComponentModel, key::Symbol)
has_metadata(nw::Network, idx::Union{VIndex,EIndex}, key::Symbol)

Checks if metadata key is present for the component.

source
NetworkDynamics.get_metadataMethod
get_metadata(c::ComponentModel, key::Symbol)
get_metadata(nw::Network, idx::Union{VIndex,EIndex}, key::Symbol)

Retrieves the metadata key for the component.

source
NetworkDynamics.set_metadata!Method
set_metadata!(c::ComponentModel, key::Symbol, value)
set_metadata!(nw::Network, idx::Union{VIndex,EIndex}, key::Symbol, value)

Sets the metadata key for the component to value.

source
NetworkDynamics.delete_metadata!Method
delete_metadata!(c::ComponentModel, key::Symbol)
delete_metadata!(nw::Network, idx::Union{VIndex,EIndex}, key::Symbol)

Removes the component-wide metadata key from the component model, or from a component referenced by idx in a network. Returns true if the metadata existed and was removed, false otherwise.

source
NetworkDynamics.has_graphelementFunction
has_graphelement(c::ComponentModel)
has_graphelement(nw::Network, idx::Union{VIndex,EIndex})

Checks if the edge or vertex function has the graphelement metadata.

source
NetworkDynamics.get_graphelementFunction
get_graphelement(c::EdgeModel)::@NamedTuple{src::T, dst::T}
get_graphelement(c::VertexModel)::Int
get_graphelement(nw::Network, idx::Union{VIndex,EIndex})

Retrieves the graphelement metadata for the component model. For edges this returns a named tuple (;src, dst) where both are either integers (vertex index) or symbols (vertex name).

source
NetworkDynamics.set_graphelement!Function
set_graphelement!(c::EdgeModel, nt::@NamedTuple{src::T, dst::T})
set_graphelement!(c::EdgeModel, p::Pair)
set_graphelement!(c::VertexModel, vidx::Int)
set_graphelement!(nw::Network, idx::Union{VIndex,EIndex}, value)

Sets the graphelement metadata for the component. For edges this takes a named tuple (;src, dst) where both are either integer (vertex index) or symbol (vertex name). For vertices it takes a single integer vidx.

source

Per-Symbol Metadata API

NetworkDynamics.get_metadataMethod
get_metadata(c::ComponentModel, sym::Symbol, key::Symbol)
get_metadata(nw::Network, sni::SymbolicIndex, key::Symbol)

Retrieves the metadata key for symbol sym in a component model, or for a symbol referenced by sni in a network. Throws an error if the symbol does not exist in the component model.

source
NetworkDynamics.has_metadataMethod
has_metadata(c::ComponentModel, sym::Symbol, key::Symbol)
has_metadata(nw::Network, sni::SymbolicIndex, key::Symbol)

Checks if symbol metadata key is present for symbol sym in a component model, or for a symbol referenced by sni in a network. Throws an error if the symbol does not exist in the component model.

source
NetworkDynamics.set_metadata!Method
set_metadata!(c::ComponentModel, sym::Symbol, key::Symbol, value)
set_metadata!(nw::Network, sni::SymbolicIndex, key::Symbol, value)
set_metadata!(c::ComponentModel, sym::Symbol, pair::Pair)
set_metadata!(nw::Network, sni::SymbolicIndex, pair::Pair)

Sets the metadata key for symbol sym to value in a component model, or for a symbol referenced by sni in a network. Throws an error if the symbol does not exist in the component model.

source
NetworkDynamics.delete_metadata!Method
delete_metadata!(c::ComponentModel, sym::Symbol, key::Symbol)
delete_metadata!(nw::Network, sni::SymbolicIndex, key::Symbol)

Removes the metadata key for symbol sym in a component model, or for a symbol referenced by sni in a network. Returns true if the metadata existed and was removed, false otherwise. Throws an error if the symbol does not exist in the component model.

source
NetworkDynamics.has_defaultFunction
has_default(c::ComponentModel, sym::Symbol)
has_default(nw::Network, sni::SymbolicIndex)

Checks if a default value is present for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also get_default, set_default!.

source
NetworkDynamics.set_default!Function
set_default!(c::ComponentModel, sym::Symbol, value)
set_default!(nw::Network, sni::SymbolicIndex, value)

Sets the default value for symbol sym to value in a component model, or for a symbol referenced by sni in a network.

See also has_default, get_default.

source
NetworkDynamics.has_guessFunction
has_guess(c::ComponentModel, sym::Symbol)
has_guess(nw::Network, sni::SymbolicIndex)

Checks if a guess value is present for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also get_guess, set_guess!.

source
NetworkDynamics.get_guessFunction
get_guess(c::ComponentModel, sym::Symbol)
get_guess(nw::Network, sni::SymbolicIndex)

Returns the guess value for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also has_guess, set_guess!.

source
NetworkDynamics.set_guess!Function
set_guess!(c::ComponentModel, sym::Symbol, value)
set_guess!(nw::Network, sni::SymbolicIndex, value)

Sets the guess value for symbol sym to value in a component model, or for a symbol referenced by sni in a network.

See also has_guess, get_guess.

source
NetworkDynamics.delete_guess!Function
delete_guess!(c::ComponentModel, sym::Symbol)
delete_guess!(nw::Network, sni::SymbolicIndex)

Removes the guess value for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also has_guess, set_guess!.

source
NetworkDynamics.has_initFunction
has_init(c::ComponentModel, sym::Symbol)
has_init(nw::Network, sni::SymbolicIndex)

Checks if a init value is present for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also get_init, set_init!.

source
NetworkDynamics.get_initFunction
get_init(c::ComponentModel, sym::Symbol)
get_init(nw::Network, sni::SymbolicIndex)

Returns the init value for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also has_init, set_init!.

source
NetworkDynamics.set_init!Function
set_init!(c::ComponentModel, sym::Symbol, value)
set_init!(nw::Network, sni::SymbolicIndex, value)

Sets the init value for symbol sym to value in a component model, or for a symbol referenced by sni in a network.

See also has_init, get_init.

source
NetworkDynamics.delete_init!Function
delete_init!(c::ComponentModel, sym::Symbol)
delete_init!(nw::Network, sni::SymbolicIndex)

Removes the init value for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also has_init, set_init!.

source
NetworkDynamics.has_boundsFunction
has_bounds(c::ComponentModel, sym::Symbol)
has_bounds(nw::Network, sni::SymbolicIndex)

Checks if a bounds value is present for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also get_bounds, set_bounds!.

source
NetworkDynamics.get_boundsFunction
get_bounds(c::ComponentModel, sym::Symbol)
get_bounds(nw::Network, sni::SymbolicIndex)

Returns the bounds value for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also has_bounds, set_bounds!.

source
NetworkDynamics.set_bounds!Function
set_bounds!(c::ComponentModel, sym::Symbol, value)
set_bounds!(nw::Network, sni::SymbolicIndex, value)

Sets the bounds value for symbol sym to value in a component model, or for a symbol referenced by sni in a network.

See also has_bounds, get_bounds.

source
NetworkDynamics.delete_bounds!Function
delete_bounds!(c::ComponentModel, sym::Symbol)
delete_bounds!(nw::Network, sni::SymbolicIndex)

Removes the bounds value for symbol sym in a component model, or for a symbol referenced by sni in a network.

See also has_bounds, set_bounds!.

source
NetworkDynamics.set_defaults!Function
set_defaults!(nw::Network, s::NWState)

Set the default values of the network to the values of the given state. Can be used to "store" the found fixpoint in the network metadata.

Values of missing, nothing or NaN are ignored.

source
set_defaults!(nw::Network, p::NWParameter)

Set the parameter default values of the network to the values of the given parameter object.

Values of missing, nothing or NaN are ignored.

source
NetworkDynamics.set_interface_defaults!Function
set_interface_defaults!(nw::Network, s::NWState; verbose=false)

Sets the interface (i.e., node and edge inputs/outputs) defaults of a given network to the ones defined by the given state. Notably, while the graph topology and interface dimensions of the target network nw and the source network of s must be identical, the systems may differ in the dynamical components.

This is mainly intended for initialization purposes: solve the interface values with a simpler – possibly static – network and "transfer" the steady state interface values to the full network.

source

Metadata and Inspection Utils

NetworkDynamics.dump_stateFunction
dump_state([IO=stdout], sol, t, idx; sigdigits=5)

Takes a Network solution sol and prints the state at t as well as the initial state of the specified component model to IO (defaults to stdout).

idx musst a valid component index, i.e. VIndex or EIndex without symbol specification.

dump_state(sol, 1.0, VIndex(4))
dump_state(sol, 1.0, EIndex(2))

See also: dump_initial_state.

source
NetworkDynamics.dump_initial_stateFunction
dump_initial_state([IO=stdout], cf::ComponentModel,
                   [defaults=get_defaults_dict(cf)],
                   [inits=get_inits_dict(cf)],
                   [guesses=get_guesses_dict(cf)],
                   [bounds=get_bounds_dict(cf)];
                   sigdigits=5, p=true, obs=true)

Prints the initial state of the component model cf to IO (defaults to stdout). Optionally contains parameters and observed.

See also: get_initial_state and dump_state.

source
NetworkDynamics.get_initial_stateFunction
get_initial_state(c::ComponentModel, [state=get_defaults_or_inits_dict(c)], syms; missing_val=nothing)
get_initial_state(nw::Network, sni::SymbolicIndex; missing_val=nothing)

Returns the initial state for symbol sym (single symbol or vector) of the component model c. Returns missing_val if the symbol is not initialized. Also works for observed symbols.

See also: dump_initial_state.

source
NetworkDynamics.describe_verticesFunction
describe_vertices(nw::Network, extras...; parameters=true, states=true, batch=nothing)

Creates a DataFrame containing information about the vertices in a Network.

Arguments

  • nw::Network: The network to describe
  • extras...: Additional pairs of (key, function) to include as columns, where the function gets the VertexModel as its only parameter to extract a custom metadata field for example..
  • parameters=true: Whether to include parameter values
  • states=true: Whether to include state values
  • batch=nothing: Optionally filter by specific batches

Returns

A DataFrame with columns for vertex indices, names, batch numbers, and any parameter/state values.

source
NetworkDynamics.describe_edgesFunction
describe_edges(nw::Network, extras...; parameters=true, states=true, batch=nothing)

Creates a DataFrame containing information about the edges in a Network.

Arguments

  • nw::Network: The network to describe
  • extras...: Additional pairs of (key, function) to include as columns, where the function gets the EdgeModel as its only parameter to extract a custom metadata field for example..
  • parameters=true: Whether to include parameter values
  • states=true: Whether to include state values
  • batch=nothing: Optionally filter by specific batches

Returns

A DataFrame with columns for edge indices, source-destination pairs, names, batch numbers, and any parameter/state values.

source

Initialization

NetworkDynamics.find_fixpointFunction
find_fixpoint(nw::Network, [x0::NWState=NWState(nw)], [p::NWParameter=x0.p]; kwargs...)
find_fixpoint(nw::Network, x0::AbstractVector, p::AbstractVector; kwargs...)
find_fixpoint(nw::Network, x0::AbstractVector; kwargs...)

Convenience wrapper around SteadyStateProblem from SciML-ecosystem. Constructs and solves the steady state problem, returns found value wrapped as NWState.

source
NetworkDynamics.initialize_componentwiseFunction
initialize_componentwise[!](
    nw::Network;
    default_overrides=nothing,
    guess_overrides=nothing,
    bound_overrides=nothing,
    additional_initformula=nothing,
    additional_initconstraint=nothing,
    verbose=false,
    subverbose=false,
    tol=1e-10,
    nwtol=1e-10,
    t=NaN
) :: NWState

Initialize a network by solving initialization problems for each component individually, then verifying the combined solution works for the full network.

There are two versions of that function: a mutating one (!-at the end of name) and a non-mutating version. The mutating version uses initialize_component! internally, the non-mutating one initialize_component. When the mutating version is used, NWState(nw) after initialization will return the same initialized state again, as it is stored in the metadata.

Parameters

  • nw: The network to initialize
  • default_overrides: Dictionary mapping symbolic indices to values that should be used as defaults. Use nothing as a value for any key to remove that default.
  • guess_overrides: Dictionary mapping symbolic indices to values to use as initial guesses. Use nothing as a value for any key to remove that guess.
  • bound_overrides: Dictionary mapping symbolic indices to bounds for constrained variables. Use nothing as a value for any key to remove those bounds.
  • additional_initformula: Dictionary mapping component indices (VIndex/EIndex) to additional initialization formulas.
  • additional_initconstraint: Dictionary mapping component indices (VIndex/EIndex) to additional initialization constraints.
  • verbose: Whether to print information about each component initialization
  • subverbose: Whether to print detailed information within component initialization. Can be Vector [VIndex(1), EIndex(3), ...] for selective output
  • tol: Tolerance for individual component residuals
  • nwtol: Tolerance for the full network residual
  • t: Time at which to evaluate the system

Returns

  • NWState: A fully initialized network state that can be used for simulation

Example of two-step initialization

# First solve a static model
static_model = create_static_network(...)
static_state = find_fixpoint(static_model)

# Extract interface values and use them to initialize dynamic model
interface_vals = interface_values(static_state)
dynamic_model = create_dynamic_network(...)
dyn_state = initialize_componentwise(dynamic_model, default_overrides=interface_vals)

# Simulate the dynamic model from this initialized state
prob = ODEProblem(dynamic_model, uflat(dyn_state), tspan, pflat(dyn_state))
sol = solve(prob)

See also: initialize_component, interface_values, find_fixpoint

source
NetworkDynamics.initialize_componentwise!Function
initialize_componentwise[!](
    nw::Network;
    default_overrides=nothing,
    guess_overrides=nothing,
    bound_overrides=nothing,
    additional_initformula=nothing,
    additional_initconstraint=nothing,
    verbose=false,
    subverbose=false,
    tol=1e-10,
    nwtol=1e-10,
    t=NaN
) :: NWState

Initialize a network by solving initialization problems for each component individually, then verifying the combined solution works for the full network.

There are two versions of that function: a mutating one (!-at the end of name) and a non-mutating version. The mutating version uses initialize_component! internally, the non-mutating one initialize_component. When the mutating version is used, NWState(nw) after initialization will return the same initialized state again, as it is stored in the metadata.

Parameters

  • nw: The network to initialize
  • default_overrides: Dictionary mapping symbolic indices to values that should be used as defaults. Use nothing as a value for any key to remove that default.
  • guess_overrides: Dictionary mapping symbolic indices to values to use as initial guesses. Use nothing as a value for any key to remove that guess.
  • bound_overrides: Dictionary mapping symbolic indices to bounds for constrained variables. Use nothing as a value for any key to remove those bounds.
  • additional_initformula: Dictionary mapping component indices (VIndex/EIndex) to additional initialization formulas.
  • additional_initconstraint: Dictionary mapping component indices (VIndex/EIndex) to additional initialization constraints.
  • verbose: Whether to print information about each component initialization
  • subverbose: Whether to print detailed information within component initialization. Can be Vector [VIndex(1), EIndex(3), ...] for selective output
  • tol: Tolerance for individual component residuals
  • nwtol: Tolerance for the full network residual
  • t: Time at which to evaluate the system

Returns

  • NWState: A fully initialized network state that can be used for simulation

Example of two-step initialization

# First solve a static model
static_model = create_static_network(...)
static_state = find_fixpoint(static_model)

# Extract interface values and use them to initialize dynamic model
interface_vals = interface_values(static_state)
dynamic_model = create_dynamic_network(...)
dyn_state = initialize_componentwise(dynamic_model, default_overrides=interface_vals)

# Simulate the dynamic model from this initialized state
prob = ODEProblem(dynamic_model, uflat(dyn_state), tspan, pflat(dyn_state))
sol = solve(prob)

See also: initialize_component, interface_values, find_fixpoint

source
NetworkDynamics.initialize_componentFunction
initialize_component(cf;
                     defaults=get_defaults_dict(cf),
                     guesses=get_guesses_dict(cf),
                     bounds=get_bounds_dict(cf),
                     default_overrides=nothing,
                     guess_overrides=nothing,
                     bound_overrides=nothing,
                     additional_initformula=nothing,
                     additional_initconstraint=nothing,
                     verbose=true,
                     apply_bound_transformation=true,
                     t=NaN,
                     tol=1e-10,
                     residual=nothing,
                     kwargs...)

The function solves a nonlinear problem to find values for all free variables/parameters (those without defaults) that satisfy the component equations in steady state (i.e. RHS equals 0). The initial guess for each variable depends on the provided guesses parameter (defaults to the metadata guess values).

Parameters

  • cf: ComponentModel to initialize
  • defaults: Dictionary of default values (defaults to metadata defaults)
  • guesses: Dictionary of initial guesses (defaults to metadata guesses)
  • bounds: Dictionary of bounds (defaults to metadata bounds)
  • default/guess/bound_overrides: Dictionary to merge with defaults/guesses/bounds. You can use nothing as a value for any key to remove that entry from the respective dictionary.
  • additional_initformula: Additional initialization formulas to apply beyond those in component metadata
  • additional_initconstraint: Additional initialization constraints to apply beyond those in component metadata
  • verbose: Whether to print information during initialization
  • apply_bound_transformation: Whether to apply bound-conserving transformations
  • t: Time at which to solve for steady state. Only relevant for components with explicit time dependency.
  • tol: Tolerance for the residual of the initialized model (defaults to 1e-10). Init throws error if resid < tol.
  • residual: Optional Ref{Float64} which gets the final residual of the initialized model.
  • kwargs...: Additional arguments passed to the nonlinear solver

Returns

  • Dictionary mapping symbols to their values (complete state including defaults and initialized values)

Bounds of free variables

When encountering any bounds in the free variables, NetworkDynamics will try to conserve them by applying a coordinate transformation. This behavior can be suppressed by setting apply_bound_transformation=false. The following transformations are used:

  • (a, b) intervals where both a and b are positive are transformed to u^2/sqrt(u)
  • (a, b) intervals where both a and b are negative are transformed to -u^2/sqrt(-u)
source
NetworkDynamics.initialize_component!Function
initialize_component!(cf::ComponentModel;
                      defaults=nothing,
                      guesses=nothing,
                      bounds=nothing,
                      default_overrides=nothing,
                      guess_overrides=nothing,
                      bound_overrides=nothing,
                      additional_initformula=nothing,
                      additional_initconstraint=nothing,
                      verbose=true,
                      t=NaN,
                      kwargs...)

Mutating version of initialize_component. See this docstring for all details. In contrast to the non mutating version, this function reads in defaults and guesses from the symbolic metadata and writes the initialized values back in to the metadata.

Parameters

  • cf: ComponentModel to initialize
  • defaults: Optional dictionary to replace all metadata defaults
  • guesses: Optional dictionary to replace all metadata guesses
  • bounds: Optional dictionary to replace all metadata bounds
  • default/guess/bound_overrides: Dict of values that override existing default/guess/bound metadata. Use nothing as a value for any key to remove that metadata entry from the component model.
  • additional_initformula: Additional initialization formulas to apply beyond those in component metadata
  • additional_initconstraint: Additional initialization constraints to apply beyond those in component metadata
  • verbose: Whether to print information during initialization
  • t: Time at which to solve for steady state. Only relevant for components with explicit time dependency.
  • All other kwargs are passed to initialize_component

When defaults, guesses, or bounds are provided, they replace the corresponding metadata in the component model. Any keys in the original metadata that are not in the provided dictionaries will be removed, and new keys will be added.

source
NetworkDynamics.init_residualFunction
init_residual(cf::ComponentModel, [state=get_defaults_or_inits_dict(cf)]; t=NaN)

Calculates the residual |du| for the given component model using the values provided. If no state dictionary is provided, it uses the values from default/init Metadata.

See also initialize_component.

source
NetworkDynamics.InitConstraintType
struct InitConstraint{F}
InitConstraint(f, sym, dim)

A representation of an additional constraint that is applied during the initialization phase of a component. It contains a function f that defines the constraint, a vector of symbols sym that are involved in the constraint, and the dimension dim of the constraint.

InitConstraint([:x, :y], 2) do res, u
    res[1] = u[:x]^2 + u[:y]^2 - 1
end

See also @initconstraint for a macro to create such constraints.

source
NetworkDynamics.@initconstraintMacro

@initconstraint

Generate an InitConstraint from an expression using symbols.

@initconstraint begin
    :x + :y
    :z^2
end

is equal to

InitConstraint([:x, :y, :z], 2) do out, u
    out[1] = u[:x] + u[:y]
    out[2] = u[:z]^2
end
source
NetworkDynamics.delete_initconstraints!Function
delete_initconstraints!(c::ComponentModel)
delete_initconstraints!(nw::Network, idx::Union{VIndex,EIndex})

Removes the initialization constraint from the component model, or from a component referenced by idx in a network. Returns true if the constraint existed and was removed, false otherwise.

See also: set_initconstraint!.

source
NetworkDynamics.add_initconstraint!Function
add_initconstraint!(c::ComponentModel, constraint; check=true)
add_initconstraint!(nw::Network, idx::Union{VIndex,EIndex}, constraint; check=true)

Adds an initialization constraint to the component. Does not overwrite existing constraints. constraint should be a single InitConstraint object.

See also: set_initconstraint!, get_initconstraints.

source
NetworkDynamics.InitFormulaType
InitFormula(f, outsym, sym)

A representation of initialization formulas that are applied during the initialization phase of a component. InitFormulas act earlier in the initialization pipeline than InitConstraints - they essentially set additional defaults rather than adding equations to the nonlinear system.

It contains a function f that defines the formulas, a vector of output symbols outsym that will be set by the formulas, a vector of input symbols sym that are used in the formulas, and an optional pretty-print string.

InitFormula([:Vset], [:u_r, :u_i]) do out, u
    out[:Vset] = sqrt(u[:u_r]^2 + u[:u_i]^2)
end

See also @initformula for a macro to create such formulas.

source
NetworkDynamics.@initformulaMacro

@initformula

Generate an InitFormula from an expression using symbols.

@initformula begin
    :Vset = sqrt(:u_r^2 + :u_i^2)
    :Pset = :u_r * :i_r + :u_i * :i_i
end

is equal to

InitFormula([:Vset, :Pset], [:u_r, :u_i, :i_r, :i_i]) do out, u
    out[:Vset] = sqrt(u[:u_r]^2 + u[:u_i]^2)
    out[:Pset] = u[:u_r] * u[:i_r] + u[:u_i] * u[:i_i]
end
source
NetworkDynamics.add_initformula!Function
add_initformula!(c::ComponentModel, formula; check=true)
add_initformula!(nw::Network, idx::Union{VIndex,EIndex}, formula; check=true)

Adds an initialization formula to the component. Does not overwrite existing formulas. formula should be a single InitFormula object.

See also: set_initformula!, get_initformulas.

source
NetworkDynamics.delete_initformulas!Function
delete_initformulas!(c::ComponentModel)
delete_initformulas!(nw::Network, idx::Union{VIndex,EIndex})

Removes all initialization formulas from the component model, or from a component referenced by idx in a network. Returns true if formulas existed and were removed, false otherwise.

See also: set_initformula!, add_initformula!.

source
NetworkDynamics.interface_valuesFunction
interface_values(s::NWState) :: OrderedDict{SymbolicIndex, Float64}

Extract all interface values (inputs and outputs) from a network state and return them as a dictionary mapping symbolic indices to their values.

This function is particularly useful in two-step initialization workflows where you want to:

  1. Solve a simplified static model first (using find_fixpoint)
  2. Use the resulting interface values to initialize a more complex dynamic model componentwise.

In that scenario, use interface_values to for the default_overrides argument of initialize_componentwise.

See also: initialize_componentwise, find_fixpoint and initialize_component.

source

Linear Stability Analysis

NetworkDynamics.isfixpointFunction
isfixpoint(nw::Network, s0::NWState; tol=1e-10)

Check if the state s0 is a fixpoint of the network nw by calculating the the RHS and check that every entry is within the given tolerance tol.

source
NetworkDynamics.jacobian_eigenvalsFunction
jacobian_eigenvals(nw::Network, s0::NWState; eigvalf=LinearAlgebra.eigvals)

Compute the eigenvalues of the Jacobian matrix for linear stability analysis of the network dynamics at state s0.

For systems without algebraic constraints (identity mass matrix), this returns the eigenvalues of the full Jacobian matrix. For constrained systems (non-identity mass matrix), it computes the eigenvalues of the reduced Jacobian following the approach for differential-algebraic equations outlined in [1]

Arguments

  • nw::Network: The network dynamics object
  • s0::NWState: The state at which to compute the Jacobian eigenvalues
  • eigvalf: Function to compute eigenvalues (default: LinearAlgebra.eigvals)

Returns

  • Vector: Eigenvalues of the Jacobian (or reduced Jacobian for constrained systems)

Algorithm

For unconstrained systems (M = I):

  • Computes eigenvalues of the full Jacobian J

For constrained systems (M ≠ I, differential-algebraic equations):

  • The system has the form: M * dz/dt = f(z, t) where M is a diagonal mass matrix
  • Variables are partitioned into differential (Mii = 1) and algebraic (Mii = 0) components
  • Let z = [x; y] where x are differential and y are algebraic variables
  • The Jacobian J = ∂f/∂z is partitioned as:
    J = [f_x  f_y]  where f_x = ∂f_d/∂x, f_y = ∂f_d/∂y
        [g_x  g_y]        g_x = ∂g_a/∂x, g_y = ∂g_a/∂y
  • For the algebraic constraints 0 = ga(x, y), we have dy/dt = -gy^(-1) * g_x * dx/dt
  • Substituting into the differential equations gives the reduced system: dx/dt = (fx - fy * gy^(-1) * gx) * x = A_s * x
  • The eigenvalues of the reduced Jacobian A_s determine stability
  • This approach follows the theory of differential-algebraic equations [1]

References

[1] "Power System Modelling and Scripting", F. Milano, Chapter 7.2.

source
NetworkDynamics.is_linear_stableFunction
is_linear_stable(nw::Network, s0::NWState; kwargs...)

Check if the fixpoint s0 of the network nw is linearly stable by computing the eigenvalues of the Jacobian matrix (or reduced Jacobian for constrained systems).

A fixpoint is linearly stable if all eigenvalues of the Jacobian have negative real parts. For systems with algebraic constraints (non-identity mass matrix), the reduced Jacobian is used following the approach in [1]. See jacobian_eigenvals for more details.

Arguments

  • nw::Network: The network dynamics object
  • s0::NWState: The state to check for linear stability (must be a fixpoint)
  • kwargs...: Additional keyword arguments passed to jacobian_eigenvals

Returns

  • Bool: true if the fixpoint is linearly stable, false otherwise

References

[1] "Power System Modelling and Scripting", F. Milano, Chapter 7.2.

source

Callbacks API

Define Callbacks

NetworkDynamics.ComponentCallbackType
abstract type ComponentCallback end

Abstract type for a component based callback. A component callback bundles a ComponentCondition as well as a ComponentAffect which can be then tied to a component model using add_callback! or set_callback!.

On a Network level, you can automaticially create network wide CallbackSets using get_callbacks.

See ContinousComponentCallback and VectorContinousComponentCallback for concrete implemenations of this abstract type.

source
NetworkDynamics.VectorContinousComponentCallbackType
VectorContinousComponentCallback(condition, affect, len; kwargs...)

Connect a ComponentCondition and a [ComponentAffect)[@ref] to a continous callback which can be attached to a component model using add_callback! or set_callback!. This vector version allows for condions which have len output dimensions. The affect will be triggered with the additional event_idx argument to know in which dimension the zerocrossing was detected.

The kwargs will be forwarded to the VectorContinuousCallback when the component based callbacks are collected for the whole network using get_callbacks(::Network). DiffEq.jl docs for available options.

source
NetworkDynamics.DiscreteComponentCallbackType
DiscreteComponentCallback(condition, affect; kwargs...)

Connect a ComponentCondition and a [ComponentAffect)[@ref] to a discrete callback which can be attached to a component model using add_callback! or set_callback!.

Note that the condition function returns a boolean value, as the discrete callback perform no rootfinding.

The kwargs will be forwarded to the DiscreteCallback when the component based callbacks are collected for the whole network using get_callbacks(::Network). DiffEq.jl docs for available options.

source
NetworkDynamics.PresetTimeComponentCallbackType
PresetTimeComponentCallback(ts, affect; kwargs...)

Tirgger a ComponentAffect at given timesteps ts in discrete callback, which can be attached to a component model using add_callback! or set_callback!.

The kwargs will be forwarded to the PresetTimeCallback when the component based callbacks are collected for the whole network using get_callbacks(::Network).

The PresetTimeCallback will take care of adding the timesteps to the solver, ensuring to exactly trigger at the correct times.

source
NetworkDynamics.ComponentConditionType
ComponentCondition(f::Function, sym, psym)

Creates a callback condition for a [ComponentCallback].

  • f: The condition function. Must be a function of the form out=f(u, p, t) when used for ContinousComponentCallback or DiscreteComponentCallback and f!(out, u, p, t) when used for VectorContinousComponentCallback.
    • Arguments of f
      • u: The current value of the selecte sym states, provided as a SymbolicView object.
      • p: The current value of the selected psym parameters.
      • t: The current simulation time.
  • sym: A vector or tuple of symbols, which represent states (including inputs, outputs, observed) of the component model. Determines, which states will be available thorugh parameter u in the callback condition function f.
  • psym: A vector or tuple of symbols, which represetn parameters of the component mode. Determines, which parameters will be available in the condition function f

Example

Consider a component model with states [:u1, :u2], inputs [:i], outputs [:o] and parameters [:p1, :p2].

ComponentCondition([:u1, :o], [:p1]) do u, p, t
    # access states symbolicially or via int index
    u[:u1] == u[1]
    u[:o] == u[2]
    p[:p1] == p[1]
    # the states/prameters `:u2`, `:i` and `:p2` are not available as
    # they are not listed in the `sym` and `psym` arguments.
end
source
NetworkDynamics.ComponentAffectType
ComponentAffect(f::Function, sym, psym)

Creates a callback condition for a [ComponentCallback].

  • f: The affect function. Must be a function of the form f(u, p, [event_idx], ctx) where event_idx is only available in VectorContinousComponentCallback.
    • Arguments of f
      • u: The current (mutable) value of the selected sym states, provided as a SymbolicView object.
      • p: The current (mutalbe) value of the selected psym parameters.
      • event_idx: The current event index, i.e. which out element triggerd in case of VectorContinousComponentCallback.
      • ctx::NamedTuple a named tuple with context variables.
        • ctx.model: a referenc to the ocmponent model
        • ctx.vidx/ctx.eidx: The index of the vertex/edge model.
        • ctx.src/ctx.dst: src and dst indices (only for edge models).
        • ctx.integrator: The integrator object. Use extract_nw to obtain the network.
        • ctx.t=ctx.integrator.t: The current simulation time.
  • sym: A vector or tuple of symbols, which represent states (excluding inputs, outputs, observed) of the component model. Determines, which states will be available thorugh parameter u in the callback condition function f.
  • psym: A vector or tuple of symbols, which represetn parameters of the component mode. Determines, which parameters will be available in the condition function f

Example

Consider a component model with states [:u1, :u2], inputs [:i], outputs [:o] and parameters [:p1, :p2].

ComponentAffect([:u1, :o], [:p1]) do u, p, ctx
    u[:u1] = 0 # change the state
    p[:p1] = 1 # change the parameter
    @info "Changed :u1 and :p1 on vertex $(ctx.vidx)" # access context
end
source
NetworkDynamics.SymbolicViewType
SymbolicView{N,VT} <: AbstractVetor{VT}

Is a (smallish) fixed size vector type with named dimensions. Its main purpose is to allow named acces to variables in ComponentCondition and ComponentAffect functions.

I.e. when the ComponentAffect declared sym=[:x, :y], you can acces u[:x] and u[:y] inside the condition function.

source
NetworkDynamics.get_callbacksMethod
get_callbacks(nw::Network)::CallbackSet

Returns a CallbackSet composed of all the "component-based" callbacks in the metadata of the Network components.

source

Attach Callbacks to Edge/VertexModels

NetworkDynamics.has_callbackFunction
has_callback(c::ComponentModel)
has_callback(nw::Network, idx::Union{VIndex,EIndex})

Checks if the component has a callback function in metadata.

source
NetworkDynamics.get_callbacksMethod
get_callbacks(c::ComponentModel)
get_callbacks(nw::Network, idx::Union{VIndex,EIndex})

Gets all callback functions for the component. Wraps in tuple, even if there is only a single one.

source
NetworkDynamics.set_callback!Function
set_callback!(c::ComponentModel, cb; check=true)
set_callback!(nw::Network, idx::Union{VIndex,EIndex}, cb; check=true)

Sets the callback function for the component. Overwrites any existing callback. See also add_callback!.

source
NetworkDynamics.add_callback!Function
add_callback!(c::ComponentModel, cb; check=true)
add_callback!(nw::Network, idx::Union{VIndex,EIndex}, cb; check=true)

Adds a callback function to the component. Does not overwrite existing callbacks. See also set_callback!.

source

Sparsity Detection

NetworkDynamics.get_jac_prototypeFunction
get_jac_prototype(nw::Network; dense=false, remove_conditions=false)

Compute the sparsity pattern of the Jacobian matrix for a NetworkDynamics network.

This function uses SparseConnectivityTracer.jl to detect the sparsity pattern of the Jacobian matrix of the network's dynamics function. The resulting sparsity pattern can be used to improve the performance of ODE solvers by providing structural information about the system. The dense option is useful when certain components have complex sparsity patterns that are difficult to detect automatically. The remove_conditions option helps when conditional statements in component functions interfere with sparsity detection.

Arguments

  • nw::Network: The NetworkDynamics network for which to compute the Jacobian prototype
  • dense=false: Controls which components should be treated as dense during sparsity detection:
    • false: Use actual component functions (default)
    • true: Replace all components with dense equivalents
    • Vector{Union{VIndex, EIndex}}: Replace only the specified vertex/edge components with dense equivalents
  • remove_conditions=false: Controls removal of conditional statements from component functions: this is only applicable to components defined via MTK. It essentially scans the function expression for if/else statements, deleting the condition and replacing the block by truepath + falsepath, which can help with sparsity detection.
    • false: Keep conditional statements as-is (default)
    • true: Remove conditionals from all components by converting if-else to additive form
    • Vector{Union{VIndex, EIndex}}: Remove conditionals only from specified vertex/edge components
  • check=true: If true, the function checks the sparsity pattern against a forward-differentiated Jacobian as a sanity check.

Returns

  • A sparse matrix representing the sparsity pattern of the Jacobian matrix

Example Usage

nw = Network(...)
jac_prototype = get_jac_prototype(nw) # get the sparsity pattern

# manually set define ODEFunction
f_ode = ODEFunction(nw; jac_prototype=jac_prototype)
prob = ODEProblem(f_ode, x0, (0.0, 1.0), p0)
sol = solve(prob, Rodas5P())

# ALTERNATIVE: use set_jac_prototype!
set_jac_prototype!(nw; jac_prototype) # attach pattern to network
prob = ODEProblem(nw, x0, (0.0, 1.0), p0) # uses jac prototype from network
sol = solve(prob, Rodas5P())
source
NetworkDynamics.set_jac_prototype!Function
set_jac_prototype!(nw::Network, jac::SparseMatrixCSC{Bool,Int})

Set the Jacobian prototype for a NetworkDynamics network.

This function stores a pre-computed Jacobian sparsity pattern in the network object, which can be used by ODE solvers to improve performance during integration.

Arguments

  • nw::Network: The NetworkDynamics network to modify
  • jac::SparseMatrixCSC{Bool,Int}: A sparse matrix representing the Jacobian sparsity pattern
source
set_jac_prototype!(nw::Network; kwargs...)

Compute and set the Jacobian prototype for a NetworkDynamics network.

This is a convenience function that automatically computes the Jacobian sparsity pattern using get_jac_prototype and stores it in the network object. Needs SparseConnectivityTracer to be loaded!

Arguments

  • nw::Network: The NetworkDynamics network to modify
  • kwargs...: Keyword arguments passed to get_jac_prototype (e.g., dense, remove_conditions)

Example Usage

nw = Network(...)
set_jac_prototype!(nw) # computs sparsity pattern and stores in network
prob = ODEProblem(nw, x0, (0.0, 1.0), p0)
sol = solve(prob, Rodas5P())

See also: get_jac_prototype

source

Execution Types

NetworkDynamics.ExecutionStyleType
abstract type ExecutionStyle{buffered::Bool} end

Abstract type for execution style. The coreloop dispatches based on the Execution style stored in the network object.

  • buffered=true means that the edge input es explicitly gathered, i.e. the vertex outputs in the output buffer will be copied into a dedicated input buffer for the edges.
  • buffered=false means, that the edge inputs are not explicitly gathered, but the corloop will perform a redirected lookup into the output buffer.
source

Aggregators

NetworkDynamics.AggregatorType
abstract type Aggregator end

Abstract sypertype for aggregators. Aggregators operate on the output buffer of all components and fill the aggregation buffer with the aggregatated edge values per vertex.

All aggregators have the constructor

Aggegator(aggfun)

for example

SequentialAggreator(+)
source

Utils

NetworkDynamics.save_parameters!Function
save_parameters!(integrator::SciMLBase.DEIntegrator)

Save the current parameter values in the integrator. Call this function inside callbacks if the parameter values have changed. This will store a timeseries of said parameters in the solution object, thus alowing us to recosntruct observables which depend on time-dependet variables.

source
NetworkDynamics.ff_to_constraintFunction
ff_to_constraint(v::VertexModel)

Takes VertexModel v with feed forward and turns all algebraic output states into internal states by defining algebraic constraints contraints 0 = out - g(...). The new output function is just a StateMask into the extended internal state vector.

Returns the transformed VertexModel.

source
Base.copyMethod
copy(c::NetworkDynamics.ComponentModel)

Shallow copy of the component model. Creates a deepcopy of metadata and symmetadata but references the same objects everywhere else.

source
NetworkDynamics.extract_nwFunction
extract_nw(thing)

Try to extract the Network object from thing.

Thing can by many things, e.g. ODEProblem, ODESolution, Integrator, NWState, NWParameter, ...

source

NetworkDynamicsInspector API

NetworkDynamicsInspector.inspectFunction
inspect(sol; restart=false, reset=false, display=nothing)

Main entry point for gui. Starts the server and serves the app for solution sol.

  • restart: If true, the display will be restartet (i.e. new Electron window, new server or new Browser tab)
  • reset: If true, reset the appstate with the new solution sol.
  • display=CURRENT_DISPLAY[]: Can be BrowserDisp(), ServerDisp() or ElectronDisp(). Per default, the current display will be used (defaults toBrowserDisp()).
source