API
The following functions are designed for public use.
Network Construction API
NetworkDynamics.Network — Type
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 definedgraphelement. Seevidxandsrc/dstkeywors forVertexModelandEdgeModelconstructors respectively.vertexm: A singleVertexModelor a vector ofVertexModelobjects. The order of the vertex models must mirror the order of thevertices(g)iterator.edgem: A singleEdgeModelor a vector ofEdgeModelobjects. The order of the edge models must mirror the order of theedges(g)iterator.
Optional keyword arguments:
execution=SequentialExecution{true}(): Execution model of the network. E.g.SequentialExecution,KAExecution,PolyesterExecutionorThreadedExecution.aggregator=execution isa SequentialExecution ? SequentialAggregator(+) : PolyesterAggregator(+): Aggregation function applied to the edge models. E.g.SequentialAggregator,PolyesterAggregator,ThreadedAggregator,SparseAggregator.check_graphelement=true: Check if thegraphelementmetadata is consistent with the graph.dealias=falseCheck 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.
Network(nw::Network; g, vertexm, edgem, kwargs...)Rebuild the Network with same graph and vertex/edge models but possibly different kwargs.
NetworkDynamics.get_graph — Function
get_graph(nw::Network)Extracts the underlying graph of the network.
NetworkDynamics.dim — Method
dim(nw::Network)Returns the number of dynamic states in the network, corresponts to the length of the flat state vector.
NetworkDynamics.pdim — Method
pdim(nw::Network)Returns the number of parameters in the network, corresponts to the length of the flat parameter vector.
Component Models
NetworkDynamics.VertexModel — Method
VertexModel(; kwargs...)Build a VertexModel according to the keyword arguments.
Main Arguments:
f=nothing: Dynamic function of the component. Can be nothing ifdimis 0.g: Output function of the component. Usefull helpers:StateMasksym/dim: Symbolic names of the states. Ifdimis provided,symis set automaticially.outsym/outdim: Symbolic names of the outputs. Ifoutdimis provided,outsymis set automaticially. Can be infered automaticially ifgisaStateMask.psym/pdim=0: Symbolic names of the parameters. Ifpdimis provided,psymis set automaticially.mass_matrix=I: Mass matrix of component. Can be a vectorvand is then interpreted asDiagonal(v).name=dim>0 ? :VertexM : :StaticVertexM: Name of the component.
Optional Arguments:
insym/indim: Symbolic names of the inputs. Ifindimis provided,insymis set automaticially.vidx: Index of the vertex in the graph, enables graphless constructor.ff:FeedForwardTypeof component. Will be typically infered fromgautomaticially.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 vectorf(x, in, extin, p, t)andg(y, x, in, extin, p, t).
All Symbol arguments can be used to set default values, i.e. psym=[:K=>1, :p].
NetworkDynamics.EdgeModel — Method
EdgeModel(; kwargs...)Build a EdgeModel according to the keyword arguments.
Main Arguments:
f=nothing: Dynamic function of the component. Can be nothing ifdimis 0.g: Output function of the component. Usefull helpers:AntiSymmetric,Symmetric,Fiducial,DirectedandStateMask.sym/dim: Symbolic names of the states. Ifdimis provided,symis set automaticially.outsym/outdim: Symbolic names of the outputs. Ifoutdimis provided,outsymis set automaticially. In general, outsym for edges isa named tuple(; src, dst). However, depending on thegfunction, it might be enough to provide a single vector or even nothing (e.g.AntiSymmetric(StateMask(1:2))). See BuildingEdgeModels for examples.psym/pdim=0: Symbolic names of the parameters. Ifpdimis provided,psymis set automaticially.mass_matrix=I: Mass matrix of component. Can be a vectorvand is then interpreted asDiagonal(v).name=dim>0 ? :EdgeM : :StaticEdgeM: Name of the component.
Optional Arguments:
insym/indim: Symbolic names of the inputs. Ifindimis provided,insymis set automaticially. For edges,insymis 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:FeedForwardTypeof component. Will be typically infered fromgautomaticially.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 vectorf(x, insrc, indst, extin, p, t)andg(ysrc, ydst, x, insrc, indst, extin, p, t).
All Symbol arguments can be used to set default values, i.e. psym=[:K=>1, :p].
Component Models with MTK
NetworkDynamics.VertexModel — Method
VertexModel(sys::System, inputs, outputs;
verbose=false, name=getname(sys), extin=nothing, ff_to_constraint=true, kwargs...)Create a VertexModel object from a given System 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 statesoutputs: 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 System name.extin=nothing: Provide external inputs as pairs, i.e.extin=[:extvar => VIndex(1, :a)]will bound the variableextvar(t)in the equations to the stateaof the first vertex.ff_to_constraint=true: Controls, whether output transformationsgwhich depend on inputs should be transformed into constraints. Defaults to true since ND.jl does not handle vertices with FF yet.
NetworkDynamics.EdgeModel — Method
EdgeModel(sys::System, srcin, dstin, srcout, dstout;
verbose=false, name=getname(sys), extin=nothing, ff_to_constraint=false, kwargs...)Create a EdgeModel object from a given System 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 sourcedstin: names of variables in you equation representing the node state at the destinationsrcout: names of variables in you equation representing the output at the sourcedstout: 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 System name.extin=nothing: Provide external inputs as pairs, i.e.extin=[:extvar => VIndex(1, :a)]will bound the variableextvar(t)in the equations to the stateaof the first vertex.ff_to_constraint=false: Controls, whether output transformationsgwhich depend on inputs should be transformed into constraints.
NetworkDynamics.EdgeModel — Method
EdgeModel(sys::System, srcin, dstin, AntiSymmetric(dstout); kwargs...)Create a EdgeModel object from a given System 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 definition, you must wrap the symbol vector in
AntiSymmetric(dstout),Symmetric(dstout), orDirected(dstout).
Additional kwargs are the same as for the double-sided EdgeModel MTK constructor.
NetworkDynamics.ComponentPostprocessing — Type
ComponentPostprocessingCustom MTK metadata type, you can add it to register a postprocessing function f for your model
function my_postproc(cm::Union{VertexModel, EdgeModel}, namespace)
# alter the cm as needed, for example add callbacks
end
@mtkmodel MyModel begin
...
@metadata begin
ComponentPostprocessing = my_postproc
end
...
endThe postprocessing function will be called at the end of the VertexModel/EdgeModel construction after the model compilation. You can use it to add custom callbacks or init functions/metadata to the generated component. The function gets both the component model to modify and the namespace (as string) of the model.
Output Function Helpers/Wrappers
NetworkDynamics.StateMask — Type
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.
NetworkDynamics.Symmetric — Type
Symmetric(g)Wraps a single-sided output function g turns it into a double sided output function which applies
y_dst = g(...)
y_src = y_dstg can be a Number/AbstractArray to impicitly wrap the corresponding StateMask.
See also AntiSymmetric, Directed, Fiducial and StateMask.
NetworkDynamics.AntiSymmetric — Type
AntiSymmetric(g_dst)Wraps a single-sided output function g_dst turns it into a double sided output function which applies
y_dst = g_dst(...)
y_src = -y_dstg_dst can be a Number/AbstractArray to impicitly wrap the corresponding StateMask.
NetworkDynamics.Directed — Type
Directed(g_dst)Wraps a single-sided output function g_dst turns it into a double sided output function which applies
y_dst = g_dst(...)With Directed there is no output for the src side. g_dst can be a Number/AbstractArray to impicitly wrap the corresponding StateMask.
See also AntiSymmetric, Symmetric, Fiducial and StateMask.
NetworkDynamics.Fiducial — Type
Fiducial(g_src, g_dst)Wraps two single-sided output function g_src and g_dst and turns them into a double sided output function which applies
y_dst = g_src(...)
y_src = g_dst(...)g can be a Number/AbstractArray to impicitly wrap the corresponding StateMask.
See also AntiSymmetric, Directed, Fiducial and StateMask.
Accessors for Component Properties
NetworkDynamics.fftype — Function
fftype(x)Retrieve the feed forward trait of x.
NetworkDynamics.dim — Method
dim(c::ComponentModel)::IntRetrieve the dimension of the component.
NetworkDynamics.sym — Function
sym(c::ComponentModel)::Vector{Symbol}Retrieve the symbols of the component.
NetworkDynamics.outdim — Function
outdim(c::VertexModel)::Int
outdim(c::EdgeModel)::@NamedTuple(src::Int, dst::Int)Retrieve the output dimension of the component
NetworkDynamics.outsym — Function
outsym(c::VertexModel)::Vector{Symbol} outsym(c::EdgeModel)::@NamedTuple{src::Vector{Symbol}, dst::Vector{Symbol}}
Retrieve the output symbols of the component.
NetworkDynamics.pdim — Method
pdim(c::ComponentModel)::IntRetrieve the parameter dimension of the component.
NetworkDynamics.psym — Function
psym(c::ComponentModel)::Vector{Symbol}Retrieve the parameter symbols of the component.
NetworkDynamics.obssym — Function
obssym(c::ComponentModel)::Vector{Symbol}Retrieve the observation symbols of the component.
NetworkDynamics.hasinsym — Function
hasinsym(c::ComponentModel)Checks if the optioan field insym is present in the component model.
NetworkDynamics.insym — Function
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.
NetworkDynamics.hasindim — Function
hasindim(c::ComponentModel)Checks if the optioan field insym is present in the component model.
NetworkDynamics.indim — Function
indim(c::VertexModel)::Int
indim(c::EdgeModel)::@NamedTuple{src::Int,dst::Int}Musst be called after hasinsym/hasindim returned true. Gives the input dimension(s).
FeedForwardType-Traits
NetworkDynamics.FeedForwardType — Type
abstract type FeedForwardType endAbstract supertype for the FeedForwardType traits.
NetworkDynamics.PureFeedForward — Type
PureFeedForward <: FeedForwardTypeTrait for component output functions g that have pure feed forward behavior (do not depend on x):
g!(outs..., ins..., p, t)See also FeedForward, NoFeedForward and PureStateMap.
NetworkDynamics.FeedForward — Type
FeedForward <: FeedForwardTypeTrait for component output functions g that have feed forward behavior. May depend on everything:
g!(outs..., x, ins..., p, t)See also PureFeedForward, NoFeedForward and PureStateMap.
NetworkDynamics.NoFeedForward — Type
NoFeedForward <: FeedForwardTypeTrait for component output functions g that have no feed forward behavior (do not depend on inputs):
g!(outs..., x, p, t)See also PureFeedForward, FeedForward and PureStateMap.
NetworkDynamics.PureStateMap — Type
PureStateMap <: FeedForwardTypeTrait for component output functions g that only depends on state:
g!(outs..., x)See also PureFeedForward, FeedForward and NoFeedForward.
Symbolic Indexing API
Network Parameter Object
NetworkDynamics.NWParameter — Type
NWParameter(nw_or_nw_wrapper, 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[VIndex(idx, :sym)] # get parameter using VIndex
p[VIndex(idx, ParamIdx(1))] # get first parameter by numeric indexUsing the special .v and .e properties, you get a FilteringProxy object which allows for interactive filtering, inspection and changing of parameters. See FilteringProxy for details.
Get flat array representation using pflat. The order of parameters in the flat representation corresponds to the order given by parameter_symbols.
See also: NWState, VIndex, EIndex, generate_indices, FilteringProxy
NetworkDynamics.NWParameter — Method
NWParameter(nw_or_nw_wrapper;
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.
NetworkDynamics.NWParameter — Method
NWParameter(p::NWParameter; ptype=typeof(p.pflat))Create NWParameter based on other parameter object, just convert type.
NetworkDynamics.NWParameter — Method
NWParameter(int::SciMLBase.DEIntegrator)Create NWParameter object from integrator.
NetworkDynamics.pflat — Function
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.
SymbolicIndexingInterface.parameter_symbols — Function
SymbolicIndexingInterface.parameter_symbols(nw::Network)Returns a vector of all symbolic network indices which in the same order as the flat parameter vector.
See also: NWParameter, NWState, pflat.
Network State Object
NetworkDynamics.NWState — Type
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[VIndex(idx, :sym)] # get state using VIndex
s[VIndex(idx, StateIdx(1))] # get first state by numeric index
s[VIndex(idx, ParamIdx(1))] # get first parameter by numeric indexUsing the special .v and .e properties, you get a FilteringProxy object which allows for interactive filtering, inspection and changing of states. See FilteringProxy for details.
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.
See also: NWParameter, VIndex, EIndex, generate_indices, FilteringProxy
NetworkDynamics.NWState — Method
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.
NetworkDynamics.NWState — Method
NWState(s::NWState; utype=typeof(uflat(s)), ptype=typeof(pflat(s)))Create NWState based on other state object, just convert types.
NetworkDynamics.NWState — Method
NWState(p::NWParameter; utype=Vector{Float64}, ufill=filltype(utype), default=true)Create NWState based on existing NWParameter object.
NetworkDynamics.NWState — Method
NWState(int::SciMLBase.DEIntegrator)Create NWState object from integrator.
NetworkDynamics.uflat — Function
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.
SymbolicIndexingInterface.variable_symbols — Function
SymbolicIndexingInterface.variable_symbols(nw::Network)Returns a vector of all symbolic network indices which in the same order as the flat state vector.
Symbolic Indices
NetworkDynamics.VIndex — Type
VIndex{C,S} <: SymbolicIndex{C,S}
idx = VIndex(comp, sub)A symbolic index for a vertex variable.
comp: the component index, either int, symbol or a collectionsub: the subindex, either int, symbol or a collection of those.
Symbolic indices are rather flexible and can potentially point to states, parameters, inputs, outputs, or observables.
The most basic form is VIndex(1, :P) which points to the variable with the name :P in the first vertex model. The component can be also given by unique name, so VIndex(:a, :P) would point to the vertex with unique name :a.
It is also possible to have "collections" of indices, such as
VIndex(1:5, 1) # first state of vertices 1 to 5
VIndex(7, (:x,:y)) # states :x and :y of vertex 7They can be used to index into objects supporting the SymbolicIndexingInterface, e.g. NWState, NWParameter or ODESolution.
It is also possible to construct vertices without a sub index, in which case they point to a component rather than a specific variable:
VIndex(2) # references the second vertex model
VIndex(:a) # references vertex with unique name :aFor example nw[VIndex(2)] would return the 2nd VertexModel in the Network.
See also: EIndex, StateIdx, ParamIdx, generate_indices, NWState, NWParameter
NetworkDynamics.EIndex — Type
EIndex{C,S} <: SymbolicIndex{C,S}
idx = EIndex(comp, sub)A symbolic index for an edge variable.
comp: the component index, either int, symbol, pair or a collectionsub: the subindex, either int, symbol or a collection of those.
Symbolic indices are rather flexible and can potentially point to states, parameters, inputs, outputs, or observables.
The most basic form is EIndex(1, :P) which points to the variable with the name :P in the first edge model. The component can be also given by unique name, so EIndex(:a, :P) would point to the edge with unique name :a. For edges, the component can also be specified as a source-destination pair:
EIndex(1=>2, :P) # variable :P in edge from vertex 1 to vertex 2
EIndex(:a=>:b, :P) # variable :P in edge from vertex :a to vertex :bIt is also possible to have "collections" of indices, such as
EIndex(1:5, 1) # first state of edges 1 to 5
EIndex(7, (:x,:y)) # states :x and :y of edge 7They can be used to index into objects supporting the SymbolicIndexingInterface, e.g. NWState, NWParameter or ODESolution.
It is also possible to construct edges without a sub index, in which case they point to a component rather than a specific variable:
EIndex(2) # references the second edge model
EIndex(1=>2) # references edge from v1 to v2
EIndex(:a=>:b) # references edge from vertex :a to vertex :bFor example nw[EIndex(2)] would return the 2nd EdgeModel in the Network.
See also: VIndex, StateIdx, ParamIdx, generate_indices, NWState, NWParameter
NetworkDynamics.ParamIdx — Type
ParamIdx{T} <: NumericSubIndex{T}Wrapper type for indexing into parameters by index rather than symbol. VPIndex(:name, 1) is equivalent to VIndex(:name, ParamIdx(1)) and tells NetworkDynamics that you mean the first parameter of the component in contrast to the first state of the component. Similarly, ParamIdx(:), ParamIdx(1:3) or ParamIdx([1,2,3]) can be used to access multiple parameters by numeric index at once.
NetworkDynamics.StateIdx — Type
StateIdx{T} <: NumericSubIndex{T}Wrapper type for indexing into states by index rather than symbol. VIndex(:name, 1) is equivalent to VIndex(:name, StateIdx(1)) and tells NetworkDynamics that you mean the first state of the component in contrast to the first parameter of the component. Similarly, StateIdx(:), StateIdx(1:3) or StateIdx([1,2,3]) can be used to access multiple states by numeric index at once.
NetworkDynamics.@obsex — Macro
@obsex([name =] expression)Define observable expressions, which are simple combinations of known 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,:δ)))Retained for backward compatibility:
NetworkDynamics.VPIndex — Function
VPIndex(c, s)Backward compatibility constructor for vertex parameter indices. Wraps integer-like subindices in ParamIdx, leaves other types unchanged. Equivalent to VIndex(c, ParamIdx(s)) when s is integer-like, otherwise VIndex(c, s).
NetworkDynamics.EPIndex — Function
EPIndex(c, s)Backward compatibility constructor for edge parameter indices. Wraps integer-like subindices in ParamIdx, leaves other types unchanged. Equivalent to EIndex(c, ParamIdx(s)) when s is integer-like, otherwise EIndex(c, s).
Index generators
NetworkDynamics.generate_indices — Function
generate_indices(inpr, compfilter=nothing, varfilter=nothing;
s=true, p=true, out=true, obs=true, in=true, just_count=false)Generate collections of valid symbolic indices with flexible filtering criteria.
Arguments
inpr: Index provider - Network or Network wrapper likeNWState,NWParameter,sol, etc.compfilternothing- matches all components (default)VIndex(1)- matches component by numberVIndex(:name)- matches by exact component nameVIndex("pattern")orVIndex(r"pattern")- matches bycontains(name, pattern)- Vector-like:
VIndex(1:10)matches vertices 1-10,[VIndex(:), EIndex(:)]matches all vertices and edges EIndex(src=>dst)- matches edges where src and dst vertices match (can be Int, Symbol, Regex, ...)
varfilternothing- matches all variables (default):name- matches variable:nameexactly"namepart"orr"namepart"- matches bycontains(variable_name, pattern)StateIdx(1)orParamIdx(1)- matches by numeric position- Vector-like:
[:foo, StateIdx(1), r"part"]matches any of the filters
Keyword Arguments
s=true- include statesp=true- include parametersout=true- include outputsobs=false- include observablesin=false- include inputsjust_count=false- return count instead of indices
Examples
# All vertex states and parameters
generate_indices(nw, VIndex(:))
# Parameters of vertex with name :generator
generate_indices(nw, VIndex(:generator); s=false, p=true, out=false)
# All variables containing "voltage" in vertices 1-5
generate_indices(nw, VIndex(1:5), "voltage")
# First parameter of all vertices using numeric indexing
generate_indices(nw, VIndex(:), ParamIdx(1); s=false, out=false)See also: FilteringProxy, vidxs, eidxs, vpidxs, epidxs
NetworkDynamics.vidxs — Function
vidxs(nw, cf=:, vf=nothing; kwargs...)Generate vertex indices for states, parameters, inputs, outputs, and observables. Equivalent to generate_indices(nw, VIndex(cf), vf; s=true, p=true, in=true, out=true, obs=true, kwargs...).
See also: generate_indices
NetworkDynamics.eidxs — Function
eidxs(nw, cf=:, vf=nothing; kwargs...)Generate edge indices for states, parameters, inputs, outputs, and observables. Equivalent to generate_indices(nw, EIndex(cf), vf; s=true, p=true, in=true, out=true, obs=true, kwargs...).
See also: generate_indices
NetworkDynamics.vpidxs — Function
vpidxs(nw, cf=:, vf=nothing; kwargs...)Generate vertex parameter indices. Equivalent to generate_indices(nw, VIndex(cf), vf; s=false, p=true, in=false, out=false, obs=false, kwargs...).
See also: generate_indices
NetworkDynamics.epidxs — Function
epidxs(nw, cf=:, vf=nothing; kwargs...)Generate edge parameter indices. Equivalent to generate_indices(nw, EIndex(cf), vf; s=false, p=true, in=false, out=false, obs=false, kwargs...).
See also: generate_indices
NetworkDynamics.FilteringProxy — Type
FilteringProxy{S,CF,VF} <: IndexingProxy{S}
FilteringProxy(s::NWState)
FilteringProxy(p::NWParameter)
(s::NWState).v # creates a FilteringProxyInteractive filtering proxy for exploring and accessing states/parameters in NetworkDynamics objects.
FilteringProxy provides a flexible, interactive way to filter and access network variables through a progressive refinement system. It acts as a "proxy" that changes indexing rules while operating on the same underlying data, allowing both exploration and modification of network states/parameters.
Core Concept
The proxy uses a filter refinement approach where each indexing operation either:
- Returns a more refined
FilteringProxy(if the filter needs more specificity) - Returns the actual values (if the filter is fully specified)
All filtering operations translate to equivalent generate_indices calls under the hood.
Stage 1: Component Filtering
Access vertices and edges using .v and .e properties:
s = NWState(nw)
s.v # FilteringProxy for all vertices
s.e # FilteringProxy for all edges
s.v[1] # Refine to vertex 1
s.v[:gen] # Refine to vertices named :gen
s.v[r"load"] # Refine to vertices matching pattern
FilteringProxy(s)[[VIndex(1), EIndex(2)]] # filter down to the first vertex and second edgeStage 2: Variable Filtering
Once the component filter is set, the next indexing operation will refine the variable filter.
s.v[1][:voltage] # value of Vertex(1) + variable called :voltage
s.v[:][r"δ"] # value of all variables containing "δ" of all vertices
s.e[1=>2].s[StateIdx(1)] # First state of edge from vertex 1 to 2Variable Type Filtering
Use type switches to select specific variable categories:
s.v.p # Parameters only
s.v.s # States only
s.v.out # Outputs only
s.v.obs # Observables only
s.v.in # Inputs only
s.v.all # All variable types
s.v(; p=true, s=true) # fine grade filter update using function call syntaxFunction Call Syntax
Use function call syntax proxy(args...) to refine without collapsing to values:
proxy = s.v(1)(:voltage) # Build filter without accessing values
value = proxy[] # Access value when readyThe function call syntax can also be used to refine any other properties. The properties match the argument names of generate_indices
s.v[1](; p=true) # equivalent to s.v[1].p
s.v(; compfilter=EIndex(:)) # resets the compfilter and now matches all edgesUtility Methods
keys(proxy)- Get matching symbolic indices viagenerate_indicesvalues(proxy) / proxy[]- Get actual values for all matching indices
See also: generate_indices, NWState, NWParameter, VIndex, EIndex
Metadata API
Component Metadata API
NetworkDynamics.metadata — Function
NetworkDynamics.has_metadata — Method
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.
NetworkDynamics.get_metadata — Method
get_metadata(c::ComponentModel, key::Symbol)
get_metadata(nw::Network, idx::Union{VIndex,EIndex}, key::Symbol)Retrieves the metadata key for the component.
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.
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.
NetworkDynamics.has_graphelement — Function
has_graphelement(c::ComponentModel)
has_graphelement(nw::Network, idx::Union{VIndex,EIndex})Checks if the edge or vertex function has the graphelement metadata.
NetworkDynamics.get_graphelement — Function
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).
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.
NetworkDynamics.has_position — Function
has_position(v::VertexModel)
has_position(nw::Network, vidx::VIndex)Checks if vertex v has position metadata.
See also: get_position, set_position!.
NetworkDynamics.get_position — Function
get_position(v::VertexModel)
get_position(nw::Network, vidx::VIndex)Returns the position metadata of vertex v. Might error if not present.
See also: has_position, set_position!.
NetworkDynamics.set_position! — Function
set_position!(v::VertexModel, val)
set_position!(nw::Network, vidx::VIndex, val)Sets the position metadata of vertex v to val.
See also: has_position, get_position.
NetworkDynamics.has_marker — Function
has_marker(v::VertexModel)
has_marker(nw::Network, vidx::VIndex)Checks if vertex v has marker metadata.
See also: get_marker, set_marker!.
NetworkDynamics.get_marker — Function
get_marker(v::VertexModel)
get_marker(nw::Network, vidx::VIndex)Returns the marker metadata of vertex v. Might error if not present.
See also: has_marker, set_marker!.
NetworkDynamics.set_marker! — Function
set_marker!(v::VertexModel, val)
set_marker!(nw::Network, vidx::VIndex, val)Sets the marker metadata of vertex v to val.
See also: has_marker, get_marker.
Per-Symbol Metadata API
NetworkDynamics.symmetadata — Function
symmetadata(c::ComponentModel)::Dict{Symbol,Dict{Symbol,Any}}Retrieve the metadata dictionary for the symbols. Keys are the names of the symbols as they appear in sym, psym, obssym and insym.
See also symmetadata
NetworkDynamics.get_metadata — Method
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.
sym can also be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
Throws an error if the symbol does not exist in the component model.
NetworkDynamics.has_metadata — Method
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.
sym can also be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
Throws an error if the symbol does not exist in the component model.
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.
For component models, you can also use a String or Regex pattern to match symbol names:
- String patterns use substring matching (e.g.,
"δ"matchesmachine₊δ) - Regex patterns use full regex matching (e.g.,
r"P$"matches symbols ending with "P")
This will error if there are none or multiple matches.
If the pattern matches multiple symbols, an error is thrown. Use a more specific pattern. Throws an error if the symbol does not exist in the component model.
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.
sym can also be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
Returns true if the metadata existed and was removed, false otherwise. Throws an error if the symbol does not exist in the component model.
NetworkDynamics.strip_metadata! — Function
strip_metadata!(c::ComponentModel, key::Symbol)Remove all metadata of type key from the component.
NetworkDynamics.has_default — Function
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also get_default, set_default!.
NetworkDynamics.get_default — Function
get_default(c::ComponentModel, sym::Symbol)
get_default(nw::Network, sni::SymbolicIndex)Returns the default value for symbol sym in a component model, or for a symbol referenced by sni in a network.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also has_default, set_default!.
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.
If value is nothing or missing, the metadata is removed.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also has_default, get_default.
NetworkDynamics.delete_default! — Function
delete_default!(c::ComponentModel, sym::Symbol)
delete_default!(nw::Network, sni::SymbolicIndex)Removes the default value for symbol sym in a component model, or for a symbol referenced by sni in a network.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also has_default, set_default!.
NetworkDynamics.strip_defaults! — Function
strip_default!(c::ComponentModel)
strip_default!(nw::Network, idx::Union{VIndex,EIndex})Removes all default values from a component model, or from a component referenced by idx in a network.
See also delete_default!, set_default!.
NetworkDynamics.has_guess — Function
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also get_guess, set_guess!.
NetworkDynamics.get_guess — Function
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also has_guess, set_guess!.
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.
If value is nothing or missing, the metadata is removed.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also has_guess, set_guess!.
NetworkDynamics.strip_guesses! — Function
strip_guess!(c::ComponentModel)
strip_guess!(nw::Network, idx::Union{VIndex,EIndex})Removes all guess values from a component model, or from a component referenced by idx in a network.
See also delete_guess!, set_guess!.
NetworkDynamics.has_init — Function
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
NetworkDynamics.get_init — Function
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
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.
If value is nothing or missing, the metadata is removed.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
NetworkDynamics.strip_inits! — Function
strip_init!(c::ComponentModel)
strip_init!(nw::Network, idx::Union{VIndex,EIndex})Removes all init values from a component model, or from a component referenced by idx in a network.
See also delete_init!, set_init!.
NetworkDynamics.has_bounds — Function
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also get_bounds, set_bounds!.
NetworkDynamics.get_bounds — Function
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also has_bounds, set_bounds!.
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.
If value is nothing or missing, the metadata is removed.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also has_bounds, get_bounds.
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.
sym can be a String or Regex, to address the only symbol containing the pattern, see set_metadata! for details.
See also has_bounds, set_bounds!.
NetworkDynamics.strip_bounds! — Function
strip_bounds!(c::ComponentModel)
strip_bounds!(nw::Network, idx::Union{VIndex,EIndex})Removes all bounds values from a component model, or from a component referenced by idx in a network.
See also delete_bounds!, set_bounds!.
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.
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.
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.
NetworkDynamics.get_defaults_dict — Function
get_defaults_dict(c::ComponentModel)Returns a dictionary mapping symbols to their default values. Only includes symbols that have default values set.
See also: get_guesses_dict, get_inits_dict
NetworkDynamics.get_guesses_dict — Function
get_guesses_dict(c::ComponentModel)Returns a dictionary mapping symbols to their guess values. Only includes symbols that have guess values set.
See also: get_defaults_dict, get_inits_dict
NetworkDynamics.get_bounds_dict — Function
get_bounds_dict(c::ComponentModel)Returns a dictionary mapping symbols to their bounds values. Only includes symbols that have bounds values set.
See also: get_defaults_dict, get_guesses_dict, get_inits_dict
NetworkDynamics.get_inits_dict — Function
get_inits_dict(c::ComponentModel)Returns a dictionary mapping symbols to their initialization values. Only includes symbols that have initialization values set.
See also: get_defaults_dict, get_guesses_dict
NetworkDynamics.free_u — Function
free_u(nw::Network)
free_u(cf::ComponentModel)Returns the "free" variables/states (variables without default values) for the given system.
Returns
- Vector of variable/state symbols that do not have default values set
See also: free_p, has_default, set_default!
NetworkDynamics.free_p — Function
free_p(cf::ComponentModel)
free_p(nw::Network)Returns the "free" parameters (parameters without default values) for the given system.
Returns
- Vector of parameter symbols that do not have default values set
See also: free_u, has_default, set_default!
Metadata and Inspection Utils
NetworkDynamics.dump_state — Function
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.
NetworkDynamics.dump_initial_state — Function
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.
NetworkDynamics.get_initial_state — Function
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.
NetworkDynamics.describe_vertices — Function
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 describeextras...: Additional pairs of (key, function) to include as columns, where the function gets theVertexModelas its only parameter to extract a custom metadata field for example..parameters=true: Whether to include parameter valuesstates=true: Whether to include state valuesbatch=nothing: Optionally filter by specific batches
Returns
A DataFrame with columns for vertex indices, names, batch numbers, and any parameter/state values.
NetworkDynamics.describe_edges — Function
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 describeextras...: Additional pairs of (key, function) to include as columns, where the function gets theEdgeModelas its only parameter to extract a custom metadata field for example..parameters=true: Whether to include parameter valuesstates=true: Whether to include state valuesbatch=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.
Initialization
NetworkDynamics.find_fixpoint — Function
find_fixpoint(nw::Network, [x0::NWState=NWState(nw)], [p::NWParameter=x0.p]; kwargs...)
find_fixpoint(nw::Network, x0::AbstractVector, p::AbstractVector; kwargs...)Find a steady-state (fixed-point) solution of the network dynamics by solving the nonlinear equation f(u, p, t) = 0, where f represents the network's right-hand side function.
This is a convenience wrapper around SteadyStateProblem from the SciML ecosystem that constructs and solves the steady state problem, returning the solution as an NWState.
Arguments
nw::Network: The network dynamics to find a fixed point forx0: Initial guess for the state variables. Can be:NWState: Complete network state (default:NWState(nw; ufill=0))AbstractVector: Flat state vector
p: Network parameters. Can be:NWParameter: Complete parameter object (default: extracted fromx0orNWParameter(nw))AbstractVector: Flat parameter vector
Keyword Arguments
alg=SSRootfind(): Steady state solver algorithm from NonlinearSolve.jlt=NaN: Time at which to evaluate the system (for time-dependent networks)- Additional
kwargsare passed to the SciMLsolvefunction
Returns
NWState: Network state at the found fixed point
See also: NWState, NWParameter, initialize_componentwise
NetworkDynamics.initialize_componentwise — Function
initialize_componentwise[!](
nw::Network;
default_overrides=nothing,
guess_overrides=nothing,
bound_overrides=nothing,
additional_initformula=nothing,
additional_guessformula=nothing,
additional_initconstraint=nothing,
verbose=false,
subverbose=false,
tol=1e-10,
nwtol=1e-10,
t=NaN,
subalg=nothing,
subsolve_kwargs=nothing,
parallel=false,
vset=[VIndex(i) for i in 1:nv(nw)],
eset=[EIndex(i) for i in 1:ne(nw)],
) :: NWStateInitialize 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 initializedefault_overrides: Dictionary mapping symbolic indices to values that should be used as defaults. Usenothingas a value for any key to remove that default.guess_overrides: Dictionary mapping symbolic indices to values to use as initial guesses. Usenothingas a value for any key to remove that guess.bound_overrides: Dictionary mapping symbolic indices to bounds for constrained variables. Usenothingas a value for any key to remove those bounds.additional_initformula: Dictionary mapping component indices (VIndex/EIndex) to additional initialization formulas. InitFormulas compute and set default values, reducing the number of free variables.additional_guessformula: Dictionary mapping component indices (VIndex/EIndex) to additional guess formulas. GuessFormulas compute improved initial guesses for free variables, improving solver convergence.additional_initconstraint: Dictionary mapping component indices (VIndex/EIndex) to additional initialization constraints.verbose: Whether to print information about each component initializationsubverbose: Whether to print detailed information within component initialization. Can be Vector [VIndex(1), EIndex(3), ...] for selective outputtol: Tolerance for individual component residualsnwtol: Tolerance for the full network residualt: Time at which to evaluate the systemsubalg: Nonlinear solver algorithm to use for component initialization (defaults to NonlinearSolve.jl default). Can be passed as single value or dict mapping VIndex/EIndex to alg (non-existent keys use default).subsolve_kwargs: Additional keyword arguments passed to the SciMLsolvefunction for component initialization. Can be passed as single value or dict mapping VIndex/EIndex to kwargs (non-existent keys use empty kwargs(;)).parallel=false: (Experimental) Whether to initialize components in parallel using multithreading.vset: Vector of VIndex values specifying which vertices to initialize (defaults to all vertices).eset: Vector of EIndex values specifying which edges to initialize (defaults to all edges).
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
NetworkDynamics.initialize_componentwise! — Function
initialize_componentwise[!](
nw::Network;
default_overrides=nothing,
guess_overrides=nothing,
bound_overrides=nothing,
additional_initformula=nothing,
additional_guessformula=nothing,
additional_initconstraint=nothing,
verbose=false,
subverbose=false,
tol=1e-10,
nwtol=1e-10,
t=NaN,
subalg=nothing,
subsolve_kwargs=nothing,
parallel=false,
vset=[VIndex(i) for i in 1:nv(nw)],
eset=[EIndex(i) for i in 1:ne(nw)],
) :: NWStateInitialize 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 initializedefault_overrides: Dictionary mapping symbolic indices to values that should be used as defaults. Usenothingas a value for any key to remove that default.guess_overrides: Dictionary mapping symbolic indices to values to use as initial guesses. Usenothingas a value for any key to remove that guess.bound_overrides: Dictionary mapping symbolic indices to bounds for constrained variables. Usenothingas a value for any key to remove those bounds.additional_initformula: Dictionary mapping component indices (VIndex/EIndex) to additional initialization formulas. InitFormulas compute and set default values, reducing the number of free variables.additional_guessformula: Dictionary mapping component indices (VIndex/EIndex) to additional guess formulas. GuessFormulas compute improved initial guesses for free variables, improving solver convergence.additional_initconstraint: Dictionary mapping component indices (VIndex/EIndex) to additional initialization constraints.verbose: Whether to print information about each component initializationsubverbose: Whether to print detailed information within component initialization. Can be Vector [VIndex(1), EIndex(3), ...] for selective outputtol: Tolerance for individual component residualsnwtol: Tolerance for the full network residualt: Time at which to evaluate the systemsubalg: Nonlinear solver algorithm to use for component initialization (defaults to NonlinearSolve.jl default). Can be passed as single value or dict mapping VIndex/EIndex to alg (non-existent keys use default).subsolve_kwargs: Additional keyword arguments passed to the SciMLsolvefunction for component initialization. Can be passed as single value or dict mapping VIndex/EIndex to kwargs (non-existent keys use empty kwargs(;)).parallel=false: (Experimental) Whether to initialize components in parallel using multithreading.vset: Vector of VIndex values specifying which vertices to initialize (defaults to all vertices).eset: Vector of EIndex values specifying which edges to initialize (defaults to all edges).
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
NetworkDynamics.initialize_component — Function
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_guessformula=nothing,
additional_initconstraint=nothing,
verbose=true,
apply_bound_transformation=true,
t=NaN,
tol=1e-10,
residual=nothing,
alg=nothing, # defaults to FastShortcutNLLSPolyalg(linsolve=QRFactorization())
solve_kwargs=(;),
io=stdout,
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 initializedefaults: 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 withdefaults/guesses/bounds. You can usenothingas 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. InitFormulas compute and set default values, reducing the number of free variables.additional_guessformula: Additional guess formulas to apply beyond those in component metadata. GuessFormulas compute improved initial guesses for free variables, improving solver convergence.additional_initconstraint: Additional initialization constraints to apply beyond those in component metadataverbose: Whether to print information during initializationapply_bound_transformation: Whether to apply bound-conserving transformationst: 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 to1e-10). Init throws error if resid ≥ tol.residual: OptionalRef{Float64}which gets the final residual of the initialized model.alg=nothing: Nonlinear solver algorithm (defaults to NonlinearSolve.jl default with QR factorization, since init problems tend to be ill-conditioned.)solve_kwargs=(;): Additional keyword arguments passed to the SciMLsolvefunctionio=stdout: IO stream for printing information
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)
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_guessformula=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 initializedefaults: Optional dictionary to replace all metadata defaultsguesses: Optional dictionary to replace all metadata guessesbounds: Optional dictionary to replace all metadata boundsdefault/guess/bound_overrides: Dict of values that override existing default/guess/bound metadata. Usenothingas 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. InitFormulas compute and set default values, reducing the number of free variables.additional_guessformula: Additional guess formulas to apply beyond those in component metadata. GuessFormulas compute improved initial guesses for free variables, improving solver convergence.additional_initconstraint: Additional initialization constraints to apply beyond those in component metadataverbose: Whether to print information during initializationt: Time at which to solve for steady state. Only relevant for components with explicit time dependency.- All other
kwargsare passed toinitialize_component, see its docstring for details!
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.
NetworkDynamics.init_residual — Function
init_residual(cf::ComponentModel, [state=get_defaults_or_inits_dict(cf)]; t=NaN, verbose=false)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.
If verbose=true prints the residual of every single state.
See also initialize_component.
NetworkDynamics.interface_values — Function
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:
- Solve a simplified static model first (using
find_fixpoint) - 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.
Init-Constraints
NetworkDynamics.InitConstraint — Type
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
endSee also @initconstraint for a macro to create such constraints.
NetworkDynamics.@initconstraint — Macro
@initconstraint
Generate an InitConstraint from an expression using symbols.
@initconstraint begin
:x + :y
:z^2
endis equal to
InitConstraint([:x, :y, :z], 2) do out, u
out[1] = u[:x] + u[:y]
out[2] = u[:z]^2
endNetworkDynamics.set_initconstraint! — Function
set_initconstraint!(c::ComponentModel, constraint; check=true)
set_initconstraint!(nw::Network, idx::Union{VIndex,EIndex}, constraint; check=true)Sets the initialization constraint(s) for the component. Overwrites any existing constraints. constraint can be a single InitConstraint or a tuple of InitConstraint objects.
See also: add_initconstraint!, get_initconstraints, delete_initconstraints!.
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!.
NetworkDynamics.has_initconstraint — Function
has_initconstraint(c::ComponentModel)
has_initconstraint(nw::Network, idx::Union{VIndex,EIndex})Checks if the component has an initialization constraint in metadata.
See also: get_initconstraints, set_initconstraint!.
NetworkDynamics.get_initconstraints — Function
get_initconstraints(c::ComponentModel)
get_initconstraints(nw::Network, idx::Union{VIndex,EIndex})Gets all initialization constraints for the component. Returns a tuple, even if there is only a single constraint.
See also: has_initconstraint, set_initconstraint!, add_initconstraint!.
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.
Init-Formulas
NetworkDynamics.InitFormula — Type
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)
endSee also @initformula for a macro to create such formulas.
NetworkDynamics.@initformula — Macro
@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
endis 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]
endNetworkDynamics.has_initformula — Function
has_initformula(c::ComponentModel)
has_initformula(nw::Network, idx::Union{VIndex,EIndex})Checks if the component has initialization formulas in metadata.
See also: get_initformulas, set_initformula!, add_initformula!.
NetworkDynamics.get_initformulas — Function
get_initformulas(c::ComponentModel)
get_initformulas(nw::Network, idx::Union{VIndex,EIndex})Gets all initialization formulas for the component. Returns a tuple, even if there is only a single formula.
See also: has_initformula, set_initformula!, add_initformula!.
NetworkDynamics.set_initformula! — Function
set_initformula!(c::ComponentModel, formula; check=true)
set_initformula!(nw::Network, idx::Union{VIndex,EIndex}, formula; check=true)Sets the initialization formula(s) for the component. Overwrites any existing formulas. formula can be a single InitFormula or a tuple of InitFormula objects.
See also: add_initformula!, get_initformulas, delete_initformulas!.
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.
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!.
Guess-Formulas
NetworkDynamics.GuessFormula — Type
GuessFormula(f, outsym, sym)A representation of guess formulas that improve initial guesses during component initialization. GuessFormulas are applied after InitFormulas in the pipeline, reading from both defaults and guesses to compute improved guess values for free variables.
Unlike InitFormulas which set defaults (reducing free variables), GuessFormulas only update the guesses dictionary to improve solver convergence without changing the problem dimension.
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.
Input Lookup Behavior
When evaluating a GuessFormula, input symbols are looked up with this priority:
- First check
defaultsdict (fixed/known values take precedence) - Then check
guessesdict (free variable current guesses) - Error if symbol not found in either
Examples
GuessFormula([:V, :theta], [:u_r, :u_i]) do out, u
out[:V] = sqrt(u[:u_r]^2 + u[:u_i]^2)
out[:theta] = atan(u[:u_i], u[:u_r])
endSee also @guessformula for a macro to create such formulas.
NetworkDynamics.@guessformula — Macro
@guessformula
Generate a GuessFormula from an expression using symbols.
This macro provides convenient syntax for creating guess formulas using assignment expressions with quoted symbols. Each assignment computes a guess value for a free variable.
Syntax
@guessformula begin
:output1 = expression_with(:input_symbols)
:output2 = other_expression(:more_inputs)
endInput Symbol Lookup
Input symbols (on RHS) are looked up with this priority:
- First from
defaultsdict (fixed values) - Then from
guessesdict (current guesses) - Error if not found in either
Output Symbol Target
Output symbols (on LHS) must be:
- Valid component symbols (states, parameters, inputs, outputs)
- NOT observables (observables are computed, not guessed)
See also: GuessFormula, @initformula, initialize_component
NetworkDynamics.has_guessformula — Function
has_guessformula(c::ComponentModel)
has_guessformula(nw::Network, idx::Union{VIndex,EIndex})Checks if the component has guess formulas in metadata.
See also: get_guessformulas, set_guessformula!, add_guessformula!.
NetworkDynamics.get_guessformulas — Function
get_guessformulas(c::ComponentModel)
get_guessformulas(nw::Network, idx::Union{VIndex,EIndex})Gets all guess formulas for the component. Returns a tuple, even if there is only a single formula.
See also: has_guessformula, set_guessformula!, add_guessformula!.
NetworkDynamics.set_guessformula! — Function
set_guessformula!(c::ComponentModel, formula; check=true)
set_guessformula!(nw::Network, idx::Union{VIndex,EIndex}, formula; check=true)Sets the guess formula(s) for the component. Overwrites any existing formulas. formula can be a single GuessFormula or a tuple of GuessFormula objects.
See also: add_guessformula!, get_guessformulas, delete_guessformulas!.
NetworkDynamics.add_guessformula! — Function
add_guessformula!(c::ComponentModel, formula; check=true)
add_guessformula!(nw::Network, idx::Union{VIndex,EIndex}, formula; check=true)Adds a guess formula to the component. Does not overwrite existing formulas. formula should be a single GuessFormula object.
See also: set_guessformula!, get_guessformulas.
NetworkDynamics.delete_guessformulas! — Function
delete_guessformulas!(c::ComponentModel)
delete_guessformulas!(nw::Network, idx::Union{VIndex,EIndex})Removes all guess 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_guessformula!, add_guessformula!.
Linear Stability Analysis
NetworkDynamics.isfixpoint — Function
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.
NetworkDynamics.jacobian_eigenvals — Function
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 objects0::NWState: The state at which to compute the Jacobian eigenvalueseigvalf: 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.
NetworkDynamics.is_linear_stable — Function
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 objects0::NWState: The state to check for linear stability (must be a fixpoint)kwargs...: Additional keyword arguments passed tojacobian_eigenvals
Returns
Bool:trueif the fixpoint is linearly stable,falseotherwise
References
[1] "Power System Modelling and Scripting", F. Milano, Chapter 7.2.
Callbacks API
Define Callbacks
NetworkDynamics.ComponentCallback — Type
abstract type ComponentCallback endAbstract 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 automatically create network wide CallbackSets using get_callbacks.
See ContinuousComponentCallback and VectorContinuousComponentCallback for concrete implementations of this abstract type.
NetworkDynamics.ContinuousComponentCallback — Type
ContinuousComponentCallback(condition, affect; affect_neg! = affect, kwargs...)Connect a ComponentCondition and a ComponentAffect to a continuous callback which can be attached to a component model using add_callback! or set_callback!.
The affect_neg! is also a ComponentAffect but will be triggered on downcrossing. It defaults to the same affect as on upcrossing.
The kwargs will be forwarded to the VectorContinuousCallback when the component based callbacks are collected for the whole network using get_callbacks. DiffEq.jl docs for available options.
NetworkDynamics.VectorContinuousComponentCallback — Type
VectorContinuousComponentCallback(condition, affect, len; affect_neg! = affect, kwargs...)Connect a ComponentCondition and a ComponentAffect to a continuous callback which can be attached to a component model using add_callback! or set_callback!. This vector version allows for conditions 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 affect_neg! is also a ComponentAffect but will be triggered on downcrossing. It defaults to the same affect as on upcrossing.
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.
NetworkDynamics.DiscreteComponentCallback — Type
DiscreteComponentCallback(condition, affect; kwargs...)Connect a ComponentCondition and a ComponentAffect 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.
NetworkDynamics.PresetTimeComponentCallback — Type
PresetTimeComponentCallback(ts, affect; kwargs...)Trigger 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.
NetworkDynamics.ComponentCondition — Type
ComponentCondition(f::Function, sym, psym)Creates a callback condition for a [ComponentCallback].
f: The condition function. Must be a function of the formout=f(u, p, t)when used forContinuousComponentCallbackorDiscreteComponentCallbackandf!(out, u, p, t)when used forVectorContinuousComponentCallback.- Arguments of
fu: The current value of the selectedsymstates, provided as aSymbolicViewobject.p: The current value of the selectedpsymparameters.t: The current simulation time.
- Arguments of
sym: A vector or tuple of symbols, which represent states (including inputs, outputs, observed) of the component model. Determines, which states will be available through parameteruin the callback condition functionf.psym: A vector or tuple of symbols, which represent parameters of the component mode. Determines, which parameters will be available in the condition functionf
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 symbolically 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.
endNetworkDynamics.ComponentAffect — Type
ComponentAffect(f::Function, sym, psym)Creates a callback condition for a [ComponentCallback].
f: The affect function. Must be a function of the formf(u, p, [event_idx], ctx)whereevent_idxis only available inVectorContinuousComponentCallback.- Arguments of
fu: The current (mutable) value of the selectedsymstates, provided as aSymbolicViewobject.p: The current (mutable) value of the selectedpsymparameters.event_idx: The current event index, i.e. whichoutelement triggered in case ofVectorContinuousComponentCallback.ctx::NamedTuplea named tuple with context variables.ctx.model: a reference to the component modelctx.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. Useextract_nwto obtain the network.ctx.t=ctx.integrator.t: The current simulation time.
- Arguments of
sym: A vector or tuple of symbols, which represent states (excluding inputs, outputs, observed) of the component model. Determines, which states will be available through parameteruin the callback condition functionf.psym: A vector or tuple of symbols, which represent parameters of the component mode. Determines, which parameters will be available in the condition functionf
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
endNetworkDynamics.SymbolicView — Type
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.
NetworkDynamics.get_callbacks — Method
get_callbacks(nw::Network, additional_callbacks=Dict())::CallbackSetReturns a CallbackSet composed of all the "component-based" callbacks in the metadata of the Network components.
You can inject additional callbacks at that stage by passing
get_callbacks(nw, VIndex(7) => cb)
get_callbacks(nw, Dict(VIndex(1)=>cb1, EIndex(2)=>cb2))which won't be stored in the metadata of the component.
Attach Callbacks to Edge/VertexModels
NetworkDynamics.has_callback — Function
has_callback(c::ComponentModel)
has_callback(nw::Network, idx::Union{VIndex,EIndex})Checks if the component has a callback function in metadata.
NetworkDynamics.get_callbacks — Method
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.
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!.
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!.
NetworkDynamics.delete_callbacks! — Function
delete_callbacks!(c::ComponentModel)
delete_callbacks!(nw::Network, idx::Union{VIndex,EIndex})Removes all callback functions from the component model, or from a component referenced by idx in a network. Returns true if callbacks existed and were removed, false otherwise.
See also: set_callback!, add_callback!.
Sparsity Detection
NetworkDynamics.get_jac_prototype — Function
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 prototypedense=false: Controls which components should be treated as dense during sparsity detection:false: Use actual component functions (default)true: Replace all components with dense equivalentsVector{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 bytruepath + falsepath, which can help with sparsity detection.false: Keep conditional statements as-is (default)true: Remove conditionals from all components by convertingif-elseto additive formVector{Union{VIndex, EIndex}}: Remove conditionals only from specified vertex/edge components
check=true: Iftrue, 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())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 modifyjac::SparseMatrixCSC{Bool,Int}: A sparse matrix representing the Jacobian sparsity pattern
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 modifykwargs...: Keyword arguments passed toget_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
Execution Types
NetworkDynamics.ExecutionStyle — Type
abstract type ExecutionStyle{buffered::Bool} endAbstract type for execution style. The coreloop dispatches based on the Execution style stored in the network object.
buffered=truemeans 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=falsemeans, that the edge inputs are not explicitly gathered, but the corloop will perform a redirected lookup into the output buffer.
NetworkDynamics.SequentialExecution — Type
struct SequentialExecution{buffered::Bool}Sequential execution, no parallelism. For buffered see ExecutionStyle.
NetworkDynamics.PolyesterExecution — Type
struct PolyesterExecution{buffered}Parallel execution using Polyester.jl. For buffered see ExecutionStyle.
NetworkDynamics.ThreadedExecution — Type
struct ThreadedExecution{buffered}Parallel execution using Julia threads. For buffered see ExecutionStyle.
NetworkDynamics.KAExecution — Type
struct KAExecution{buffered}Parallel execution using KernelAbstractions.jl. Works with GPU and CPU arrays. For buffered see ExecutionStyle.
Aggregators
NetworkDynamics.Aggregator — Type
abstract type Aggregator endAbstract 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(+)NetworkDynamics.SequentialAggregator — Type
SequentialAggregator(aggfun)Sequential aggregation.
NetworkDynamics.SparseAggregator — Type
SparseAggregator(+)Only works with additive aggregation +. Aggregates via sparse inplace matrix multiplication. Works with GPU Arrays.
NetworkDynamics.ThreadedAggregator — Type
ThreadedAggregator(aggfun)Parallel aggregation using Julia threads.
NetworkDynamics.PolyesterAggregator — Type
PolyesterAggregator(aggfun)Parallel aggregation using Polyester.jl.
NetworkDynamics.KAAggregator — Type
KAAggregator(aggfun)Parallel aggregation using KernelAbstractions.jl. Works with both GPU and CPU arrays.
Utils
SciMLBase.ODEProblem — Method
SciMLBase.ODEProblem(nw::Network, args...;
add_comp_cb=Dict(),
add_nw_cb=nothing,
override_cb=nothing,
kwargs...
)Custom cosntructor for creating ODEProblem base of a Network-Object. Its main purpose is to automaticially handle callback construction from the component level callbacks.
Callback Keywords
The callback system supports three keyword arguments that control how callbacks are managed:
add_comp_cb: Additional component callbacks: ADictmapping component indices (e.g.,VIndex(1)orEIndex(2)) to component callbacks. These are forwarded toget_callbacksand combined with callbacks stored in the network's component metadata. Use this to inject temporary component callbacks without modifying the network structure.add_nw_cb: Additional network/system callbacks: A network-level callback orCallbackSet(e.g.,PeriodicCallback,PresetTimeCallback) that is combined with the network's component callbacks. Use this for callbacks that don't fit the component-based pattern, such as periodic saving or global termination conditions.override_cb: A callback orCallbackSetthat completely replaces all network callbacks. When set, bothadd_comp_cbandadd_nw_cbmust be empty/nothing (enforced by ArgumentError). Use this for complete control over the callback system.
SciMLBase.ODEProblem(nw::Network, s0::NWState, tspan; kwargs...)
SciMLBase.ODEProblem(nw::Network, s0::NWState, tspan, p0::NWParameter; kwargs...)This is a simple wrapper which:
- extracts the flat state and parameter vectors from
s0(andp0if provided) - makes a copy of the parameter vector to avoid side effects due to callbacks
- constructs the callbacks from the network and combines them with any additional callbacks
Callback Keywords
The callback system supports three keyword arguments that control how callbacks are managed:
add_comp_cb: Additional component callbacks: ADictmapping component indices (e.g.,VIndex(1)orEIndex(2)) to component callbacks. These are forwarded toget_callbacksand combined with callbacks stored in the network's component metadata. Use this to inject temporary component callbacks without modifying the network structure.add_nw_cb: Additional network/system callbacks: A network-level callback orCallbackSet(e.g.,PeriodicCallback,PresetTimeCallback) that is combined with the network's component callbacks. Use this for callbacks that don't fit the component-based pattern, such as periodic saving or global termination conditions.override_cb: A callback orCallbackSetthat completely replaces all network callbacks. When set, bothadd_comp_cbandadd_nw_cbmust be empty/nothing (enforced by ArgumentError). Use this for complete control over the callback system.
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.
NetworkDynamics.ff_to_constraint — Function
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.
NetworkDynamics.extract_nw — Function
extract_nw(thing)Try to extract the Network object from thing.
Thing can by many things, e.g. ODEProblem, ODESolution, Integrator, NWState, NWParameter, ...
NetworkDynamics.implicit_output — Function
implicit_output(x) = 0
ModelingToolkit.@register_symbolic implicit_output(x)This is a helper function to define MTK models with fully implicit outputs. It is sort of a barrier for Symbolics to not descent in to the equation. When added to an equation, it does nothing (defined as 0), but it tricks MTK/Symbolics into believing the equation depends on x. This can be necessary to define a model with fully implicit outputs.
@mtkmodel ImplicitForcing begin
@variables begin
u(t), [description = "Input Variable", input=true]
y(t), [description = "fully implicit output", output=true]
end
@equations begin
# 0 ~ u # WRONG!
0 ~ u + implicit_output(y) # CORRECT!
end
end
VertexModel(ImplicitForcing(name=:implicit), [:u], [:y])For more information see the NetworkDynamics docs on fully implicit outputs.
NetworkDynamics.pretty_f — Function
NetworkDynamics.pretty_f(v::VertexModel)For debugging vertex models based off MTK, this function pretty prints the underlying generated function f(du, u, in, p, t) in a more readable way.
NetworkDynamicsInspector API
NetworkDynamicsInspector.inspect — Function
inspect(sol; restart=false, reset=false, display=nothing)Main entry point for gui. Starts the server and serves the app for solution sol.
restart: Iftrue, the display will be restartet (i.e. new Electron window, new server or new Browser tab)reset: Iftrue, reset the appstate with the new solutionsol.display=CURRENT_DISPLAY[]: Can beBrowserDisp(),ServerDisp()orElectronDisp(). Per default, the current display will be used (defaults toBrowserDisp()).
NetworkDynamicsInspector.dump_app_state — Function
dump_app_state()Generate a list of set_sol!, set_state!, set_graphplot! and define_timeseries! commands to recreate the current appstate. The intended usecase is to quickly recreate "starting points" for interactive exploration.
NetworkDynamicsInspector.set_sol! — Function
set_sol!(sol)Set the solution of the current appstate to sol.
NetworkDynamicsInspector.set_state! — Function
set_state!(; sol, t, tmin, tmax)Set the solution, current time and time limits of the current appstate.
To automaticially create commands see dump_app_state().
NetworkDynamicsInspector.set_graphplot! — Function
set_graphplot!(; nstate, estate, nstate_rel, estate_rel, ncolorrange, ecolorrange)Set the properties of the graphplot of the current appstate.
To automaticially create commands see dump_app_state().
NetworkDynamicsInspector.set_timeseries! — Function
set_timeseries!(key; selcomp, states, rel)Set properties of the timeseries plot with key key. See also define_timeseries!.
To automaticially create commands see dump_app_state().
NetworkDynamicsInspector.define_timeseries! — Function
define_timeseries!(tsarray)Defines timeseries, where tsarray is an array of timeseries keyword arguments (see set_timeseries!).
To automaticially create commands see dump_app_state().