|
| 1 | +# Sparsity Detection |
| 2 | + |
| 3 | +NetworkDynamics.jl can automatically detect and exploit the sparsity structure of the Jacobian matrix to significantly improve the performance of ODE solvers. This feature uses [SparseConnectivityTracer.jl](https://github.com/adrhill/SparseConnectivityTracer.jl) to analyze the network's dynamics and create a sparse Jacobian prototype that modern solvers can use for more efficient linear algebra operations. |
| 4 | + |
| 5 | +The sparsity detection is particularly beneficial for: |
| 6 | +- Large networks where the Jacobian matrix is sparse |
| 7 | +- Stiff systems that require implicit solvers |
| 8 | +- Networks with complex component interactions |
| 9 | +- Components with conditional statements that complicate automatic differentiation |
| 10 | + |
| 11 | +## Core Function |
| 12 | + |
| 13 | +The main interface is the [`get_jac_prototype`](@ref) function, which take the a `Network` object as an argument and returns a sparse boolean matrix containing the sparsity pattern. |
| 14 | + |
| 15 | +The sparsity pattern can be passed to ODE solvers to improve performance: |
| 16 | + |
| 17 | +```julia |
| 18 | +f_ode = ODEFunction(nw; jac_prototype=get_jac_prototype(nw)) |
| 19 | +prob = ODEProblem(f_ode, x0, (0.0, 1.0), p0) |
| 20 | +sol = solve(prob, Rodas5P()) |
| 21 | +``` |
| 22 | + |
| 23 | +Alternatively, you can store the sparsity pattern directly in the network: |
| 24 | + |
| 25 | +```julia |
| 26 | +set_jac_prototype!(nw; kwargs_for_get_jac_prototype...) |
| 27 | +prob = ODEProblem(nw, x0, (0.0, 1.0), p0) # automatically uses stored prototype |
| 28 | +``` |
| 29 | + |
| 30 | +## Example: Handling Conditional Statements |
| 31 | + |
| 32 | +A key feature of NetworkDynamics.jl's sparsity detection is the ability to handle conditional statements in component functions. This is particularly useful for ModelingToolkit-based components that use `ifelse` statements. |
| 33 | + |
| 34 | +The conditional statements will be resolved in favor of a "global" sparsity pattern by |
| 35 | +replacing them temporarily with `trueblock + falseblock` which is then inferable by |
| 36 | +SparseConnectivityTracer.jl. |
| 37 | + |
| 38 | +!!! details "Setup code" |
| 39 | + ```@example sparsity |
| 40 | + using NetworkDynamics, ModelingToolkit, Graphs |
| 41 | + using SparseArrays, OrdinaryDiffEqRosenbrock, OrdinaryDiffEqNonlinearSolve |
| 42 | + using ModelingToolkit: D_nounits as Dt, t_nounits as t |
| 43 | + nothing #hide |
| 44 | + ``` |
| 45 | + |
| 46 | +```@example sparsity |
| 47 | +# Define a component with conditional logic |
| 48 | +@mtkmodel ValveModel begin |
| 49 | + @variables begin |
| 50 | + p_src(t), [description="source pressure"] |
| 51 | + p_dst(t), [description="destination pressure"] |
| 52 | + q(t), [description="flow through valve"] |
| 53 | + end |
| 54 | + @parameters begin |
| 55 | + K=1, [description="conductance"] |
| 56 | + active=1, [description="valve state"] |
| 57 | + end |
| 58 | + @equations begin |
| 59 | + q ~ ifelse(active > 0, K * (p_src - p_dst), 0) |
| 60 | + end |
| 61 | +end |
| 62 | +
|
| 63 | +@mtkmodel NodeModel begin |
| 64 | + @variables begin |
| 65 | + p(t)=1, [description="pressure"] |
| 66 | + q_nw(t), [description="network flow"] |
| 67 | + end |
| 68 | + @parameters begin |
| 69 | + C=1, [description="capacitance"] |
| 70 | + q_ext, [description="external flow"] |
| 71 | + end |
| 72 | + @equations begin |
| 73 | + C*Dt(p) ~ q_ext + q_nw |
| 74 | + end |
| 75 | +end |
| 76 | +nothing # hide |
| 77 | +``` |
| 78 | + |
| 79 | +```@example sparsity |
| 80 | +# Create network |
| 81 | +@named valve = ValveModel() |
| 82 | +@named node = NodeModel() |
| 83 | +
|
| 84 | +g = wheel_graph(10) |
| 85 | +v = VertexModel(node, [:q_nw], [:p]) |
| 86 | +e = EdgeModel(valve, [:p_src], [:p_dst], AntiSymmetric([:q])) |
| 87 | +
|
| 88 | +nw = Network(g, v, e) |
| 89 | +``` |
| 90 | + |
| 91 | +```@example sparsity |
| 92 | +# This will fail due to conditional statements |
| 93 | +try |
| 94 | + get_jac_prototype(nw) |
| 95 | +catch |
| 96 | + println("Error: Sparsity detection failed due to conditional statements") |
| 97 | +end |
| 98 | +``` |
| 99 | + |
| 100 | +```@example sparsity |
| 101 | +# This works by removing conditionals |
| 102 | +jac_prototype = get_jac_prototype(nw; remove_conditions=true) |
| 103 | +
|
| 104 | +# Store the prototype directly in the network |
| 105 | +set_jac_prototype!(nw, jac_prototype) |
| 106 | +``` |
| 107 | + |
| 108 | +## Performance Benefits |
| 109 | + |
| 110 | +Using sparsity detection can significantly improve solver performance, especially for large networks and stiff systems: |
| 111 | + |
| 112 | +```@example sparsity |
| 113 | +using OrdinaryDiffEqRosenbrock, Chairmarks |
| 114 | +
|
| 115 | +# Create a large sparse network for benchmarking |
| 116 | +g_large = grid([20, 20]) # 400 nodes in a 2D grid (very sparse) |
| 117 | +nw_large = Network(g_large, v, e) |
| 118 | +
|
| 119 | +# Setup initial conditions and parameters |
| 120 | +using Random # hide |
| 121 | +Random.seed!(42) # hide |
| 122 | +s0 = NWState(nw_large) |
| 123 | +s0.v[:, :p] .= randn(400) # random initial pressures |
| 124 | +
|
| 125 | +p0 = NWParameter(nw_large) |
| 126 | +p0.v[:, :q_ext] .= randn(400) # small external flow |
| 127 | +
|
| 128 | +nothing #hide |
| 129 | +``` |
| 130 | + |
| 131 | +The network is now ready for benchmarking. Let's first time the solution without sparsity detection: |
| 132 | + |
| 133 | +```@example sparsity |
| 134 | +# Without sparsity detection (dense Jacobian) |
| 135 | +prob_dense = ODEProblem(nw_large, uflat(s0), (0.0, 1.0), pflat(p0)) |
| 136 | +@b solve($prob_dense, Rodas5P()) seconds=1 |
| 137 | +``` |
| 138 | + |
| 139 | +Now let's enable sparsity detection: |
| 140 | +```@example sparsity |
| 141 | +jac = get_jac_prototype(nw_large; remove_conditions=true) |
| 142 | +``` |
| 143 | +The pattern already shows that the Jacobian is really sparse due to the sparse network connections. |
| 144 | + |
| 145 | +```@example sparsity |
| 146 | +set_jac_prototype!(nw_large, jac) |
| 147 | +``` |
| 148 | + |
| 149 | +Now we can benchmark the sparse version: |
| 150 | +```@example sparsity |
| 151 | +# Solve with sparsity detection |
| 152 | +prob_sparse = ODEProblem(nw_large, uflat(s0), (0.0, 1.0), pflat(p0)) |
| 153 | +@b solve($prob_sparse, Rodas5P()) seconds=1 |
| 154 | +``` |
| 155 | + |
| 156 | +For this network, we see a substantial speedup due to the sparse solver! |
| 157 | + |
| 158 | +## Troubleshooting |
| 159 | + |
| 160 | +**Sparsity detection fails with conditional statements:** |
| 161 | +- Use `remove_conditions=true` to handle `ifelse` statements in MTK components |
| 162 | +- For specific problematic components, pass a vector of indices: `remove_conditions=[EIndex(1), VIndex(2)]` |
| 163 | + |
| 164 | +**Detection fails for complex components:** |
| 165 | +- Use `dense=true` to treat all components as dense (fallback option) |
| 166 | +- For specific components, use `dense=[EIndex(1)]` to treat only those components as dense |
| 167 | + |
| 168 | +**Performance doesn't improve:** |
| 169 | +- Sparsity detection is most beneficial for large networks (>50 nodes) with sparse connectivity |
| 170 | +- Dense networks or small systems may not see significant speedup |
| 171 | +- Ensure you're using a solver that can exploit sparsity (e.g., `Rodas5P`, `FBDF`) |
| 172 | + |
| 173 | +The sparsity detection feature requires the `SparseConnectivityTracer.jl` package, which needs to be loaded manually! |
0 commit comments