### Importing StockFlow.jl Library (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples/CausalLoopDiagrams/create_a_causalLoopDiagram.ipynb
Imports the StockFlow.jl package, making its functionalities available for use. This is the standard way to load a Julia package, allowing access to its types and functions.
```Julia
using StockFlow
```
--------------------------------
### Creating StockAndFlow0 Diagrams with @foot
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
This snippet demonstrates the `@foot` macro, used to create `StockAndFlow0` objects, which represent basic stock-sum relationships. It shows various use cases, including empty diagrams, diagrams with only stocks or sums, and diagrams with links between stocks and sums. The examples highlight how multiple occurrences of symbols are interpreted as the same instance and how duplicate links are preserved.
```Julia
(@foot () => ()) == StockAndFlow0([],[],[])
(@foot () => X) == StockAndFlow0([],[:X],[])
(@foot Y => ()) == StockAndFlow0([:Y],[],[])
(@foot Y => X) == StockAndFlow0([:Y],[:X],[:Y => :X])
(@foot Y => X, () => ()) == StockAndFlow0([:Y],[:X],[:Y => :X])
(@foot Y => X, Y => X) == StockAndFlow0([:Y],[:X],[:Y => :X, :Y => :X])
(@foot Y => X, A => X) == StockAndFlow0([:Y, :A],[:X],[:Y => :X, :A => :X])
(@foot Y => X, Y => Z) == StockAndFlow0([:Y],[:X, :Z],[:Y => :X, :Y => :Z])
```
--------------------------------
### Defining a Stock and Flow Model with @stock_and_flow
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
This example illustrates the usage of the `@stock_and_flow` macro to define a complex stock and flow model. It showcases the five main sections: `:stocks` for defining populations, `:parameters` for external constants, `:sums` for aggregate variables, `:dynamic_variables` for intermediate calculations, and `:flows` for defining rates of change between stocks or to/from the cloud. The snippet demonstrates various syntax capabilities for defining dynamic variables and flows, including splitting, arithmetic operations, and function calls.
```Julia
@stock_and_flow begin
# to specify stock names
:stocks
S
I
R
# to specify parameter names, which will be given values from outside
# the model when evaluated
:parameters
β
λ
δ
# to specify sum variables, which have at any given time have value
# equal to the sum of all their linked stocks
:sums
N = [S, I, R]
NI = [I]
None = [] # 0
# to specify how stocks, parameters, sums and other dynamic variables
# relate to each other. We use these to determine flow rates.
# If we specify a dynamic variable with multiple operators, it'll
# automatically be split into multiple.
:dynamic_variables
v₁ = S + I / N # this will be split into two dyvars
v₂ = *(β, I)
v₃ = v₂ + 1
v₄ = log(S)
# to specify the rate at which members of one population will
# leave to become members of another population.
# Use CLOUD or ☁ (\:cloud:) to indicate entering or leaving model.
# You can also use the dynamic variable format inside a flow to create
# a dynamic variable
:flows
CLOUD => f1(v1) => S
S => Deaths_S(δ * S) => CLOUD
S => infections(+λ) => I
I => recoveries(v₄ + v₃ / v₂) => R
end
```
--------------------------------
### Composing SIR and SVI Models (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
Shows how to compose two existing stockflows, `sir` and `svi`, by identifying shared stocks and sums. In this example, `S` and `I` from `sir` are composed with `N` from `svi`, indicating they represent the same underlying concept across the models.
```Julia
sirv = @compose sir svi begin
(sir, svi)
(sir, svi) ^ S => N, I => N
end
```
--------------------------------
### Generating Multiple Foot Diagrams with @feet
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
This snippet illustrates the `@feet` macro, which processes a block expression to produce an array of `StockAndFlow0` objects, each representing a foot diagram defined on a separate line within the block. It demonstrates how an empty block results in an empty array and provides examples of single and multiple foot diagrams, showcasing how complex relationships can be defined line by line.
```Julia
(@feet begin end) == Vector{StockAndFlow0}()
(@feet begin
() => ()
end) == [StockAndFlow0([],[],[])]
(@feet begin
A => B, AA => B
X => Y, X => B, Z => ()
end) == ([StockAndFlow0([:A, :AA],[:B],[:A => :B, :AA => :B]),
StockAndFlow0([:X, :Z],[:Y, :B],[:X => :Y, :X => :B])])
```
--------------------------------
### Defining Initial Conditions for Combined Model (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/literate/full_fledged_schema_examples_new/stratification/sir_linear_stratification.md
This snippet defines a `LVector` named `u0_weight` to set the initial population sizes for each stratified stock in the combined `aged_weight` model. These initial conditions specify the starting number of individuals in each weight and age category (e.g., `NormalWeightChild`, `OverWeightChild`, `ObeseChild`), which are essential for initiating simulations.
```Julia
u0_weight = LVector(
NormalWeightChild=95811.0*12.0/82.0, OverWeightChild=27709.0*12.0/82.0, ObeseChild=30770.0*12.0/82.0,
)
```
--------------------------------
### Defining a Causal Loop Diagram (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples/CausalLoopDiagrams/create_a_causalLoopDiagram.ipynb
Defines a Causal Loop Diagram (CLD) using the `CausalLoop` constructor. It takes a list of nodes (variables) and a list of directed edges (causal links) as input, representing the relationships within the system. This specific example models a simple SI (Susceptible-Infected) system.
```Julia
# test the causal loop diagram
si_causalLoop=CausalLoop(
[:S,:i,:I],
[:S=>:i,:i=>:S,:i=>:I,:I=>:i]
)
```
--------------------------------
### Rewriting SIRV Model Variables (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
Another example of `@rewrite` using `dyvar_swaps` and `removes`. It replaces `lambda` with `v_inf₂` and `rdeath_svi` with `rdeath` in dynamic variables, and subsequently removes the original `lambda` and `rdeath_svi` objects, demonstrating variable refactoring.
```Julia
sirv_rewritten = @rewrite sirv begin
:dyvar_swaps
lambda => v_inf₂
rdeath_svi => rdeath
:removes
lambda
rdeath_svi
end
```
--------------------------------
### Visualizing a Causal Loop Diagram (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples/CausalLoopDiagrams/create_a_causalLoopDiagram.ipynb
Visualizes the previously defined `si_causalLoop` diagram using the `GraphCL` function. This function typically generates a graphical representation of the CLD, allowing for visual inspection of the system's structure and causal relationships.
```Julia
GraphCL(si_causalLoop)
```
--------------------------------
### Initializing StockFlow and Dependencies in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SEIRVD/SEIRVD_model_hard.md
This snippet imports necessary Julia packages for building and simulating stock and flow models. It includes `StockFlow` for modeling, `Catlab` for categorical algebra, `LabelledArrays` for named arrays, `OrdinaryDiffEq` for ODE solving, and `Plots` for visualization. `Catlab.Graphics`, `Catlab.Programs`, and `Catlab.WiringDiagrams` are also imported for diagrammatic programming.
```Julia
using StockFlow
using Catlab
using Catlab.CategoricalAlgebra
using LabelledArrays
using OrdinaryDiffEq
using Plots
using Catlab.Graphics
using Catlab.Programs
using Catlab.WiringDiagrams
```
--------------------------------
### Importing StockFlow.jl Modules
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
This snippet demonstrates the necessary `using` statements to import the core StockFlow.jl library and its various syntax submodules, including `StockFlow.Syntax`, `StockFlow.Syntax.Stratification`, `StockFlow.Syntax.Composition`, `StockFlow.Syntax.Rewrite`, and `StockFlow.Syntax.Homomorphism`. These modules provide macros and functions for defining, manipulating, and analyzing stock and flow models.
```Julia
using StockFlow
using StockFlow.Syntax # stock_and_flow, foot, feet
using StockFlow.Syntax.Stratification # stratify, n_stratify
using StockFlow.Syntax.Composition # compose
using StockFlow.Syntax.Rewrite # rewrite
using StockFlow.Syntax.Homomorphism # hom
```
--------------------------------
### Creating Empty Stockflow with @compose (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
Demonstrates that composing with no arguments or an empty block results in an empty `StockAndFlow` object. This highlights the base case for composition, showing how to initialize an empty stockflow using `@compose`.
```Julia
(@compose begin
()
end) == (@compose begin end) == StockAndFlow()
```
--------------------------------
### Importing Core Julia Libraries for StockFlow and Catlab
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet imports a comprehensive set of Julia packages required for building and analyzing stock-and-flow models using StockFlow.jl, leveraging Catlab.jl for its categorical algebra, graph visualization, and wiring diagram capabilities, along with other essential scientific computing libraries.
```Julia
using StockFlow
using StockFlow.Syntax
using Catlab
using Catlab.CategoricalAlgebra
using LabelledArrays
using OrdinaryDiffEq
using Plots
using Catlab.Graphics
using Catlab.Programs
using Catlab.Theories
using Catlab.WiringDiagrams
using Catlab.Graphics.Graphviz: Html
using Catlab.Graphics.Graphviz
```
--------------------------------
### Importing StockFlow Modules (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/CausalLoopDiagrams/Causal_Loop_Operations.ipynb
Imports necessary modules from the `StockFlow.jl` library, including core functionalities, syntax extensions, and premade models, to enable the use of its features for system dynamics modeling.
```Julia
using StockFlow
using StockFlow.Syntax
using StockFlow.PremadeModels
```
--------------------------------
### Composing Typed Models via Pullback and Visualization in Python
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet demonstrates model composition by performing a `pullback` operation on the `typed_WeightModel` and `typed_ageWeightModel`. The `apex` function extracts the resulting combined model, which is then rebuilt and flattened using `rebuildStratifiedModelByFlattenSymbols`. Finally, `GraphF` visualizes this newly composed `aged_weight` model, showing the integration of both weight and age structures.
```Python
aged_weight = pullback(typed_WeightModel, typed_ageWeightModel) |> apex |> rebuildStratifiedModelByFlattenSymbols;
GraphF(aged_weight)
```
--------------------------------
### Creating Causal Loop Diagrams with @causal_loop
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
This snippet demonstrates the `@causal_loop` macro for defining causal loop diagrams, with or without polarities. It shows how to specify `:nodes` and `:edges`, including positive (`+Y`) and negative (`-Y`) polarities. Examples include a simple triangle without polarities, a balancing loop with polarities, a diagram with self-edges and multiple edges between nodes, and an empty causal loop. The macro defaults to a diagram with polarities if no edges are specified.
```Julia
# Triangle, without polarities.
@causal_loop begin
:nodes
A
B
C
:edges
A => B
B => C
C => A
end
# Triangle, with polarities, creating a balancing loop.
@causal_loop begin
:nodes
A
B
C
:edges
A => -B
B => +C
C => +A
end
# Causal loop with two nodes and three edges;
# A has a positive self edge, and A has two edges to B, one positive, one negative.
@causal_loop begin
:nodes
A
B
:edges
A => +A
A => +B
A => -B
end
# Empty causal loop, treated with polarities.
@causal_loop begin end
```
--------------------------------
### Loading Premade SEIR Model (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/json.md
Loads a pre-defined SEIR (Susceptible-Exposed-Infected-Recovered) model from the `StockFlow.PremadeModels` module. This showcases how to utilize existing model definitions provided by the library, simplifying the process of working with common epidemiological models.
```Julia
m = StockFlow.PremadeModels.seir_model
```
--------------------------------
### Constructing SEIR Stock and Flow Model in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples/CausalLoopDiagrams/convert_from_SEIR_stockFlowDiagram.ipynb
This snippet constructs the complete SEIR stock and flow model using the `StockAndFlow` constructor. It maps stocks to their inflows, outflows, associated variables, and sum variables, and defines the relationships between flows and variables, and variables and their corresponding functions.
```Julia
#(stock_name=>(inflows, outflows, variables, svariables))
## if a stock has no inflow or no outflow, use keyword ":F_NONE"
## if a stock has no variables connect to, use keyword ":V_NONE"
## if a stock has no sum_variables connect to, use keyword ":SV_NONE"
#(flow=>variable)
#(variable=>function)
#(svariable=>variable)
## if sum_variable contributes to no variables, use keywork ":SVV_NONE"
seir=StockAndFlow(
(:S=>(:birth,(:incid,:deathS),(:v_incid,:v_deathS),:N),
:E=>(:incid,(:inf,:deathE),(:v_inf,:v_deathE),:N),
:I=>(:inf,(:rec,:deathI),(:v_incid, :v_rec,:v_deathI),:N),
:R=>(:rec,:deathR,:v_deathR,:N)),
(:birth=>:v_birth,:incid=>:v_incid,:inf=>:v_inf,:rec=>:v_rec,:deathS=>:v_deathS,:deathE=>:v_deathE,:deathI=>:v_deathI,:deathR=>:v_deathR),
(:v_birth=>f_birth,:v_incid=>f_incid,:v_inf=>f_inf,:v_rec=>f_rec,:v_deathS=>f_deathS,:v_deathE=>f_deathE,:v_deathI=>f_deathI,:v_deathR=>f_deathR),
(:N=>(:v_birth,:v_inf))
)
```
--------------------------------
### Importing StockFlow.jl Modules in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/CausalLoopDiagrams/convert_from_SEIR_stockFlowDiagram.ipynb
This snippet imports the necessary modules from the StockFlow.jl library, including the main `StockFlow` module and its `Syntax` submodule, which provides macros like `@stock_and_flow` for defining models.
```Julia
using StockFlow
using StockFlow.Syntax
```
--------------------------------
### Placeholder for SEIR Stock and Flow Diagram Definition in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SEIRVD/SEIRVD_model_hard.md
This commented-out snippet indicates where the Stock and Flow diagram for the SEIR model would be defined using the `StockAndFlowp` constructor. It shows the general structure for linking flows to upstream and downstream stocks, which is a common pattern in StockFlow.jl.
```Julia
# StockAndFlowp(stocks,
# (flow=>function, upstream=>downstream) => stocks linked)
```
--------------------------------
### Solving Composed SEIRVD ODE Model in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SEIRVD/SEIRVD_model_hard.md
This snippet sets up and solves the ordinary differential equations (ODEs) generated from the composed SEIRVD stock and flow diagram. It uses `ODEProblem` to define the problem with the model's vector field, initial conditions `u0`, time span, and parameters `p`. The `solve` function from `OrdinaryDiffEq` then integrates the ODEs using the `Tsit5()` algorithm with a specified absolute tolerance, and `plot(sol)` visualizes the results.
```Julia
prob = ODEProblem(vectorfield(seirvd),u0,(0.0,100.0),p);
sol = solve(prob,Tsit5(),abstol=1e-8);
plot(sol)
```
--------------------------------
### Importing Core Julia Packages for StockFlow
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/literate/full_fledged_schema_examples_new/stratification/sir_linear_stratification.md
This snippet imports all the necessary Julia packages required for the StockFlow.jl project. It includes StockFlow itself, its Syntax module, Catlab for its categorical algebra and wiring diagram capabilities, LabelledArrays for structured data, OrdinaryDiffEq for solving differential equations, and Plots for data visualization. Catlab's Graphics and Graphviz modules are specifically imported for diagram rendering.
```Julia
using StockFlow
using StockFlow.Syntax
using Catlab
using Catlab.CategoricalAlgebra
using LabelledArrays
using OrdinaryDiffEq
using Plots
using Catlab.Graphics
using Catlab.Programs
using Catlab.Theories
using Catlab.WiringDiagrams
using Catlab.Graphics.Graphviz: Html
using Catlab.Graphics.Graphviz
```
--------------------------------
### Serializing Premade SEIR Model to Pretty JSON (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/json.md
Serializes the loaded premade `seir_model` (`m`) into a human-readable JSON format using `JSON3.pretty` and `generate_json_acset`. This confirms that premade models can also be easily serialized, consistent with custom-defined models.
```Julia
JSON3.pretty(generate_json_acset(m))
```
--------------------------------
### Importing StockFlow and JSON3 Libraries (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/json.md
Imports necessary modules and functions from `StockFlow`, `Catlab`, and `JSON3` to enable the creation, manipulation, and JSON serialization of Stock and Flow models. This sets up the environment for defining and working with the models.
```Julia
using StockFlow
using Catlab
using Catlab.CategoricalAlgebra
using JSON3
import StockFlow: StockAndFlowpUntyped, vectorify, state_dict, add_stocks!, add_flow!, add_links!
```
--------------------------------
### Importing StockFlow.jl Library
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples/CausalLoopDiagrams/convert_from_SEIR_stockFlowDiagram.ipynb
This snippet imports the StockFlow.jl library, which provides tools for defining and manipulating stock and flow diagrams and causal loop diagrams in Julia.
```Julia
using StockFlow
```
--------------------------------
### Visualizing SEIR Stock and Flow Diagram in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples/CausalLoopDiagrams/convert_from_SEIR_stockFlowDiagram.ipynb
This line generates a graphical representation of the defined `seir` stock and flow model, allowing for visual inspection of the model structure and connections.
```Julia
Graph(seir)
```
--------------------------------
### Defining Parameters and Initial Stock Values for SEIRVD Model in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SEIRVD/SEIRVD_model_hard.md
This snippet defines the constant parameters `p` and initial stock values `u0` for the SEIRVD model using `LVector` from `LabelledArrays`. These values are crucial for simulating the model and represent arbitrary settings for a toy model, which can be adjusted for different infectious diseases.
```Julia
p = LVector(
cβ=0.2, N=1000, rrec=0.083, rv=0.02, rlatent=0.2, rd=0.0001
)
# Define initial values for stocks
u0 = LVector(
S=990, E=0, I=10, R=0, V=0, D=0
)
```
--------------------------------
### Composing X, SIS_A, and SIS_Y Models (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
Illustrates a more complex composition involving three stockflows (`X`, `SIS_A`, `SIS_Y`). It specifies shared elements like `X` mapping to `N` across all three, and `A` and `Y` mapping to `NI` when composed, demonstrating multi-model integration.
```Julia
XAY_model = @compose X SIS_A SIS_Y begin
(X, A, Y)
(X, A, Y) ^ X => N
(A, Y) ^ () => NI
end
```
--------------------------------
### Solving ODE for Stratified Weight Model (Python)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This Python snippet sets up and solves an Ordinary Differential Equation (ODE) problem using the `ODEProblem` function. It utilizes `vectorfield(aged_weight)` to define the differential equations, `u0_weight` for initial conditions, `(0.0, 100.0)` as the time span, and `p_weight` for parameters. The `Tsit5()` algorithm is employed for numerical integration with an absolute tolerance of `1e-8`, and the resulting solution is then plotted.
```Python
prob_stratified_weight = ODEProblem(vectorfield(aged_weight),u0_weight,(0.0,100.0),p_weight);
sol_stratified_weight = solve(prob_stratified_weight,Tsit5(),abstol=1e-8);
plot(sol_stratified_weight)
```
--------------------------------
### Applying Composition Rule to Open Stock and Flow Diagrams in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SEIRVD/SEIRVD_model_hard.md
This snippet applies the previously defined UWD composition rule (`uwd_seirvd`) to a dictionary of open stock and flow diagrams using the `oapply` function. The `|> apex` pipes the result to extract the apex of the resulting diagram, which represents the composed SEIRVD model. The `Graph(seirvd)` then visualizes this composed model.
```Julia
seirvd=oapply(uwd_seirvd,Dict()) |> apex
Graph(seirvd)
```
--------------------------------
### Defining and Solving a SEIR Model in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/README.md
This snippet demonstrates how to define a SEIR (Susceptible-Exposed-Infected-Recovered) stock-flow model using StockFlow.jl's domain-specific language. It sets up stocks, parameters, flows, and sum variables, then defines parameter values and initial stock values. Finally, it creates an ODEProblem from the model's vector field and solves it using the Tsit5 algorithm, illustrating the simulation of the system's dynamics over time.
```Julia
seir = @stock_and_flow begin
:stocks
S
E
I
R
:parameters
μ
β
tlatent
trecovery
δ
:flows
☁ => fbirth(μ * N) => S # dynamic variables can be defined implicitly or with :dynamic_variables
S => fincid(β * S * I / N) => E
S => fdeathS(S * δ) => ☁
E => finf(E / tlatent) => I
E => fdeathE(E * δ) => ☁
I => frec(I / trecovery) => R
I => fdeathI(I * δ) => ☁
R => fdeathR(R * δ) => ☁
:sums
N = [S, E, I, R]
end
# define parameter values and initial values of stocks
# define constant parameters
p_measles = LVector(
β=49.598, μ=0.03/12, δ=0.03/12, tlatent=8.0/30, trecovery=5.0/30
)
# define initial values for stocks
u0_measles = LVector(
S=90000.0-930.0, E=0.0, I=930.0, R=773545.0
)
prob_measles = ODEProblem(vectorfield(seir),u0_measles,(0.0,120.0),p_measles);
sol_measles = solve(prob_measles,Tsit5(),abstol=1e-8);
plot(sol_measles)
```
--------------------------------
### Defining Parameters and Initial Values for SIRV Model - Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SIRV/SIRV_composition_model_simple.md
This snippet defines the constant parameters (`p_sirv`) and initial stock values (`u0_sirv`) for the SIRV model. `LVector` is used to create labelled vectors, making parameters and initial conditions easily accessible by name for the simulation.
```Julia
p_sirv = LVector(
cβ=0.2, N=1000, tr=12, rv=0.02, e=0.9
)
# Define initial values for stocks
u0_sirv = LVector(
S=990, I=10, R=0, V=0
)
```
--------------------------------
### N-ary Stratification of Stockflows with @n_stratify Macro (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
The `@n_stratify` macro extends stratification to multiple stockflows (A_1, ..., A_{n-1}, Z), creating a new stockflow representing their pullback. It uses an ordered list of tuples to indicate mappings from the i-th stockflow to Z, with support for single object mappings, empty tuples, wildcard (`_`), and substring (`~`) matches specific to each stockflow.
```Julia
@n_stratify WeightModel ageWeightModel l_type begin
# Once again, stocks header isn't necessary
:stocks
[_, _] => pop
:flows
[~Death, ~Death] => f_death
[~id, ~aging] => f_aging
[~Becoming, ~id] => f_fstOrder
[_, f_NB] => f_birth
:dynamic_variables
[v_NewBorn, v_NB] => v_birth
[~Death, ~Death] => v_death
[~id, (v_agingCA, v_agingAS)] => v_aging
[(v_BecomingOverWeight, v_BecomingObese), (v_idC, v_idA, v_idS)] => v_fstOrder
:parameters
[μ, μ] => μ
[(δw, δo), (δC, δA, δS)] => δ
[(rw, ro), r] => rFstOrder
[rage, (rageCA, rageAS)] => rage
# Nor is sums header necessary
:sums
[N,N] => N
end
```
--------------------------------
### Defining Initial Parameters and Conditions for Weight Model in Python
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet initializes a `LVector` named `p_weight` with specific numerical values for various parameters of the combined model, such as birth rates (μμ), death rates (δwδC, δoδC, etc.), aging rates (ragerageCA, ragerageAS), and transition rates (rwr, ror). It also begins the definition of `u0_weight`, which would typically hold initial stock values for simulation.
```Python
p_weight = LVector(
μμ=12.5/1000,δwδC=2.0/1000,δoδC=8.0/1000,δwδA=4.0/1000,δoδA=13.0/1000,δwδS=8.0/1000,δoδS=30.0/1000,
ragerageCA=1.0/(12.0*365.0),ragerageAS=1.0/(50.0*365.0),rwr=0.03,ror=0.06
)
u0_weight = LVector(
```
--------------------------------
### Typing Weight Model with ACSetTransformation in Python
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet creates a `typed_WeightModel` by applying an `ACSetTransformation` to the `WeightModel` using the `l_type` schema. It maps the elements of the `WeightModel` (stocks, flows, parameters, etc.) to corresponding typed elements extracted from `l_type`. The `@assert is_natural` confirms the validity of this transformation, and `GraphF_typed` visualizes the typed model.
```Python
typed_WeightModel=ACSetTransformation(WeightModel, l_type,
S = [s,s,s],
SV = [N],
LS = [lsn,lsn,lsn],
F = [f_birth, f_death, f_fstorder, f_death, f_fstorder, f_death, f_aging, f_aging, f_aging],
I = [i_birth, i_aging, i_fstorder, i_aging, i_fstorder, i_aging],
O = [o_death, o_fstorder, o_aging, o_death, o_fstorder, o_aging, o_death, o_aging],
V = [v_birth, v_death, v_fstorder, v_death, v_fstorder, v_death, v_aging, v_aging, v_aging],
LV = [lv_death1, lv_fstorder1, lv_death1, lv_fstorder1, lv_death1, lv_aging1, lv_aging1, lv_aging1],
LSV = [lsv_birth1],
P = [p_μ, p_δ, p_rfstOrder, p_rfstOrder, p_δ, p_rage],
LPV = [lpv_birth2, lpv_death2, lpv_fstorder2, lpv_death2, lpv_fstorder2, lpv_death2, lpv_aging2, lpv_aging2, lpv_aging2],
Name = name -> nothing, Op=op->nothing, Position=pos->nothing
);
@assert is_natural(typed_WeightModel)
GraphF_typed(typed_WeightModel, rd="TB")
```
--------------------------------
### Combining Models with Pullback and Visualizing (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/literate/full_fledged_schema_examples_new/stratification/sir_linear_stratification.md
This snippet demonstrates the categorical composition of models by performing a `pullback` operation on the `typed_WeightModel` and `typed_ageWeightModel`. The `apex` function extracts the resulting combined model, which is then rebuilt into a stratified model using `rebuildStratifiedModelByFlattenSymbols`. Finally, `GraphF` visualizes this newly combined, multi-dimensional model.
```Julia
aged_weight = pullback(typed_WeightModel, typed_ageWeightModel) |> apex |> rebuildStratifiedModelByFlattenSymbols;
GraphF(aged_weight)
```
--------------------------------
### Defining Weight Model with Stocks, Parameters, and Flows in Python
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet defines a `WeightModel` using the `@stock_and_flow` macro, specifying three stock variables (NormalWeight, OverWeight, Obese), various parameters (e.g., μ, δw), dynamic variables representing rates of change, and flows between stocks and/or an external 'CLOUD'. It also defines a sum `N` representing the total population across all weight categories.
```Python
WeightModel = @stock_and_flow begin
:stocks
NormalWeight
OverWeight
Obese
:parameters
μ
δw
rw
ro
δo
rage
:dynamic_variables
v_NewBorn = N * μ
v_DeathNormalWeight = NormalWeight * δw
v_BecomingOverWeight = NormalWeight * rw
v_DeathOverWeight = OverWeight * δw
v_BecomingObese = OverWeight * ro
v_DeathObese = Obese * δo
v_idNW = NormalWeight * rage
v_idOW = OverWeight * rage
v_idOb = Obese * rage
:flows
CLOUD => f_NewBorn(v_NewBorn) => NormalWeight
NormalWeight => f_DeathNormalWeight(v_DeathNormalWeight) => CLOUD
NormalWeight => f_BecomingOverWeight(v_BecomingOverWeight) => OverWeight
OverWeight => f_DeathOverWeight(v_DeathOverWeight) => CLOUD
OverWeight => f_BecomingObese(v_BecomingObese) => Obese
Obese => f_DeathObese(v_DeathObese) => CLOUD
NormalWeight => f_idNW(v_idNW) => NormalWeight
OverWeight => f_idOW(v_idOW) => OverWeight
Obese => f_idOb(v_idOb) => Obese
:sums
N = [NormalWeight, OverWeight, Obese]
end
```
--------------------------------
### Visualizing Stock and Flow Diagram in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/CausalLoopDiagrams/convert_from_SEIR_stockFlowDiagram.ipynb
This snippet generates a graphical representation of the defined `seir` stock and flow model. It uses the `GraphF` function from StockFlow.jl to visualize the model's structure, including stocks, flows, and auxiliary variables.
```Julia
GraphF(seir)
```
--------------------------------
### Visualizing Weight Model Graph in Python
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet generates a graphical representation of the `WeightModel` defined previously. The `GraphF` function is used to visualize the stock and flow diagram, with `rd="TB"` specifying a top-to-bottom rendering direction, aiding in the visual understanding of the model's structure and relationships.
```Python
GraphF(WeightModel, rd="TB")
```
--------------------------------
### Visualizing Age-Structured Model Graph in Python
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet generates a graphical representation of the `ageWeightModel` defined previously. The `GraphF` function is used to visualize the stock and flow diagram, providing a visual overview of the model's structure and the relationships between age cohorts.
```Python
GraphF(ageWeightModel)
```
--------------------------------
### Defining Parameter Node Attributes (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
Creates graph attributes for parameter nodes in a Petri net. It defines the label, shape (circle), and font color, with the color determined by the parameter's type via the `typed_StockFlow` transformation.
```Julia
def_parameter(typed_StockFlow::ACSetTransformation, colors) =
(p, pp) -> ("p$pp", Attributes(:label=>pname(p,pp) isa Tuple where T ? Html(replace(string(pname(p,pp)), ":"=>"", "," => "
", "("=>"", ")"=>"")) : "$(pname(p,pp))",
:shape=>"circle",
:color=>colors[typed_StockFlow[:P](pp)],
:fontcolor=>colors[typed_StockFlow[:P](pp)]))
```
--------------------------------
### Defining Stock-Flow Model Structure with Macro in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/literate/full_fledged_schema_examples_new/stratification/sir_linear_stratification.md
This snippet demonstrates the usage of the `@stock_and_flow` macro to concisely define the structure of a Stock-Flow model. It declares stocks, parameters, dynamic variables with their equations, and initiates the definition of flows, providing a domain-specific language for model specification.
```Julia
l_type = @stock_and_flow begin
:stocks
pop
:parameters
μ
δ
rFstOrder
rage
:dynamic_variables
v_aging = pop * rage
v_fstOrder = pop * rFstOrder
v_birth = N * μ
v_death = pop * δ
:flows
```
--------------------------------
### Applying UWD-Algebra for SIRV Model Composition - Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SIRV/SIRV_composition_model_simple.md
This snippet applies the defined uwd-algebra (`uwd_sirv`) to compose the SIRV model. It uses `oapply` with an empty dictionary for parameters, and then takes the `apex` to finalize the composition, resulting in the `sirv2` model.
```Julia
sirv2=oapply(uwd_sirv,Dict()) |> apex
```
--------------------------------
### Defining Graph Colors for Petri Net Elements (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
Defines color palettes used for different components of the Petri net graph, such as variable flows, stocks, sum variables, and parameters. These colors help visually distinguish element types in the generated graph.
```Julia
colors_vflow = ["antiquewhite4","antiquewhite", "gold", "saddlebrown", "slateblue", "blueviolet", "olive"]
colors_s = ["deeppink","darkorchid","darkred","coral"] # red series
colors_sv = ["cornflowerblue","cyan4","cyan","chartreuse"] # green and blue series
colors_p = ["gold","gold4","darkorange1","lightgoldenrod","goldenrod"] # yellow and orange
```
--------------------------------
### Composing Diabetes Models by Weight Categories (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
Demonstrates composing multiple diabetes models (`Model_Normoglycemic`, `Model_Hyperglycemic`, `Model_Norm_Hyper`) based on shared 'NormalWeight', 'OverWeight', and 'Obese' stocks, all mapping to `N`. This shows how to merge models based on common demographic or state categories.
```Julia
Diabetes_Model = @compose Model_Normoglycemic Model_Hyperglycemic Model_Norm_Hyper begin
(Normo, Hyper, NH)
(Normo, NH) ^ NormalWeight => N
(Normo, NH) ^ OverWeight => N
(Normo, NH) ^ Obese => N
(Hyper, NH) ^ Prediabetic_U => N
(Hyper, NH) ^ Prediabetic_D => N
end
```
--------------------------------
### Visualizing Causal Loop Diagram in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples/CausalLoopDiagrams/convert_from_SEIR_stockFlowDiagram.ipynb
This line generates a graphical representation of the converted causal loop diagram (`seir_causalLoop`), providing a visual aid for analyzing the system's feedback mechanisms.
```Julia
GraphCL(seir_causalLoop)
```
--------------------------------
### Generating Typed Petri Net Graph (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
The main function for generating a typed Petri net graph. It takes an `ACSetTransformation` representing the typed stock-flow model and various color palettes, then uses the previously defined `def_` functions to construct the graph.
```Julia
GraphF_typed(typed_StockFlow::ACSetTransformation, colors_vflow = colors_vflow, colors_s = colors_s, colors_p = colors_p, colors_sv = colors_sv; schema::String="C", type::String="SFVL", rd::String="LR") = GraphF(dom(typed_StockFlow),
make_stock = def_stock(typed_StockFlow, colors_s), make_auxiliaryV=def_auxiliaryVF(typed_StockFlow, colors_vflow), make_sumV=def_sumV(typed_StockFlow, colors_sv),
make_flow_V=def_flow_V(typed_StockFlow, colors_vflow), make_flow_noneV=def_flow_noneV(typed_StockFlow, colors_vflow),make_parameter=def_parameter(typed_StockFlow, colors_p),schema=schema, type=type, rd=rd
)
```
--------------------------------
### Defining Stock Node Attributes (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
Generates graph attributes for stock nodes in a Petri net. It sets the label, shape (square), color, style, and fill color based on the stock's name and its type as determined by the `typed_StockFlow` transformation.
```Julia
def_stock(typed_StockFlow::ACSetTransformation, colors) =
(p,s) -> ("s$s", Attributes(:label=>sname(p,s) isa Tuple where T ? Html(replace(string(sname(p,s)), ":"=>"", "," => "
", "("=>"", ")"=>"")) : "$(sname(p,s))",
:shape=>"square",
:color=>"black",
:style=>"filled",
:fillcolor=>colors[typed_StockFlow[:S](s)]))
```
--------------------------------
### Plotting SIR Model Stock and Flow Diagram - Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SIRV/SIRV_composition_model_simple.md
This snippet visualizes the previously defined SIR model's Stock and Flow Diagram using the `Graph` function from `Catlab.Graphics`. It takes the `sir` object as input to generate a graphical representation.
```Julia
Graph(sir)
```
--------------------------------
### Placeholder for SV Stock and Flow Diagram Definition in Julia
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/practices/SEIRVD/SEIRVD_model_hard.md
This commented-out snippet indicates where the Stock and Flow diagram for the SV model would be defined using the `StockAndFlowp` constructor. It serves as a template for defining the structure of the vaccination process within the model.
```Julia
# StockAndFlowp(stocks,
# (flow=>function, upstream=>downstream) => stocks linked)
```
--------------------------------
### Visualizing Age Model Graph (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/literate/full_fledged_schema_examples_new/stratification/sir_linear_stratification.md
This line generates a graphical representation of the `ageWeightModel` using the `GraphF` function, allowing for visual inspection of its structure and the relationships between its components.
```Julia
GraphF(ageWeightModel)
```
--------------------------------
### Defining Age-Structured Model with Stocks and Flows in Python
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet defines an `ageWeightModel` using the `@stock_and_flow` macro, focusing on age cohorts: Child, Adult, and Senior. It includes parameters for birth, death, and aging rates between cohorts, along with dynamic variables and flows representing transitions and mortality, and a sum `N` for the total population across age groups.
```Python
ageWeightModel = @stock_and_flow begin
:stocks
Child
Adult
Senior
:parameters
μ
δC
δA
δS
rageCA
rageAS
r
:dynamic_variables
v_NB = N * μ
v_DeathC = Child * δC
v_idC = Child * r
v_agingCA = Child * rageCA
v_DeathA = Adult * δA
v_idA = Adult * r
v_agingAS = Adult * rageAS
v_DeathS = Senior * δS
v_idS = Senior * r
:flows
CLOUD => f_NB(v_NB) => Child
Child => f_idC(v_idC) => Child
Child => f_DeathC(v_DeathC) => CLOUD
Child => f_agingCA(v_agingCA) => Adult
Adult => f_idA(v_idA) => Adult
Adult => f_DeathA(v_DeathA) => CLOUD
Adult => f_agingAS(v_agingAS) => Senior
Senior => f_idS(v_idS) => Senior
Senior => f_DeathS(v_DeathS) => CLOUD
:sums
N = [Child, Adult, Senior]
end
```
--------------------------------
### Defining Custom Symbolic Stock and Flow Constructor (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/json.md
Defines `NewStockAndFlowSymbolic`, a specialized constructor for `StockAndFlowpUntyped` models where flow formulas are represented as strings. It processes stock names and flow definitions, adding them to the model, and linking stocks to flows based on their symbolic names. This allows for serialization of the model's functional components.
```Julia
StockAndFlowSymbolic = StockAndFlowpUntyped{Symbol,String}
# This is our constructor specialized to String formulas.
NewStockAndFlowSymbolic(s,f) = begin
d = StockAndFlowSymbolic()
s = vectorify(s)
add_stocks!(d,length(s),sname=s)
s_idx = state_dict(s)
f = vectorify(f)
for (i, ((fattr,uds),ls)) in enumerate(f)
fn = first(fattr)
ff = last(fattr)
sui = s_idx[first(uds)]
sdi = s_idx[last(uds)]
ls = vectorify(ls)
add_flow!(d,sui,sdi,fname=fn,ϕf=ff)
add_links!(d,map(x->s_idx[x],ls),repeat([i], length(ls)), length(ls))
end
d
end
```
--------------------------------
### Composing Causal Loop Diagrams (Julia)
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/docs/src/DSLs.md
Shows composition applied to causal loop diagrams (`@cl`). It merges `ABC` and `BCD` by identifying the shared `B => C` link, demonstrating that `@compose` works with polarities and causal relationships, not just stocks and flows.
```Julia
ABC = (@cl A => B, B => C)
BCD = (@cl B => C, C => D)
ABCD = @compose ABC BCD begin
(ABC, BCD)
(ABC, BCD) ^ B => C
end
```
--------------------------------
### Typing Age-Structured Model with ACSetTransformation in Python
Source: https://github.com/algebraicjulia/stockflow.jl/blob/main/examples/full_fledged_schema_examples_new/stratification/sir_linear_stratification.ipynb
This snippet creates a `typed_ageWeightModel` by applying an `ACSetTransformation` to the `ageWeightModel` using the `l_type` schema. It maps the elements of the age-structured model to corresponding typed elements, similar to the `WeightModel` typing. The `@assert is_natural` verifies the transformation's validity, and `GraphF_typed` visualizes the typed model.
```Python
typed_ageWeightModel=ACSetTransformation(ageWeightModel, l_type,
S = [s,s,s],
SV = [N],
LS = [lsn,lsn,lsn],
F = [f_birth, f_fstorder, f_death, f_aging, f_fstorder, f_death, f_aging, f_fstorder, f_death],
I = [i_birth, i_fstorder, i_aging, i_fstorder, i_aging, i_fstorder],
O = [o_fstorder, o_death, o_aging, o_fstorder, o_death, o_aging, o_fstorder, o_death],
V = [v_birth, v_death, v_fstorder, v_aging, v_death, v_fstorder, v_aging, v_death, v_fstorder],
LV = [lv_death1, lv_fstorder1, lv_aging1, lv_death1, lv_fstorder1, lv_aging1, lv_death1, lv_fstorder1],
LSV = [lsv_birth1],
P = [p_μ, p_δ, p_δ, p_δ, p_rage, p_rage, p_rfstOrder],
LPV = [lpv_birth2, lpv_death2, lpv_fstorder2, lpv_aging2, lpv_death2, lpv_fstorder2, lpv_aging2, lpv_death2, lpv_fstorder2],
Name = name -> nothing, Op=op->nothing, Position=pos->nothing
);
@assert is_natural(typed_ageWeightModel)
GraphF_typed(typed_ageWeightModel)
```