Skip to content

Route DAE/ODE initialization through the homotopy continuation solver - #4766

Merged
ChrisRackauckas merged 3 commits into
SciML:masterfrom
ChrisRackauckas-Claude:init-homotopy-routing
Jul 22, 2026
Merged

ChrisRackauckas merged 3 commits into
SciML:masterfrom
ChrisRackauckas-Claude:init-homotopy-routing

Conversation

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

Draft — please ignore until reviewed by @ChrisRackauckas.

Summary

Makes DAE/ODE initialization automatically use the Modelica homotopy(actual, simplified) operator. When the (square) initialization system contains homotopy nodes, InitializationProblem now builds a SciMLBase.HomotopyProblem (solved by NonlinearSolve continuation from the simplified form) instead of a plain NonlinearProblem, selected with the same dispatch as AbstractNonlinearProblem(isys, op) (get_nonlinear_problem_type). This robustly initializes systems whose target form is hard to solve from a cold start — singular Jacobian at the natural guess, multiple roots, folds — which is exactly what the operator exists for (Modelica spec 3.7.4.2; Sielemann, Casella & Otter 2011).

Systems without homotopy nodes take a byte-identical path (get_nonlinear_problem_type returns NonlinearProblem).

What changed

  • initializationproblem.jl — get_initialization_problem_type's square-system branch now returns isys isa System ? get_nonlinear_problem_type(isys) : NonlinearProblem (was always NonlinearProblem). The InitializationProblem constructor builds a HomotopyProblem on that selection, threading the caller's resolved _iip.
  • homotopyproblem.jl — adds a SciMLBase.HomotopyProblem{iip}(sys::System, op) constructor form. The bare HomotopyProblem(sys, op) derives in-place-ness from op, but an init op is a varmap (never a StaticArray), so it always reads as in-place; the init path must pass the resolved iip explicitly, exactly like the sibling NonlinearProblem{iip} path. Without this an out-of-place / StaticArray initialization is silently built in-place and hard-errors at solve.

Companion change (separate PR)

End-to-end solve(odeprob) also needs a one-method solver-side fallback so the OverrideInit path routes a HomotopyProblem init to the continuation polyalgorithm. Since HomotopyProblem <: AbstractNonlinearProblem, default_nlsolve currently hands it a Newton polyalg that has no HomotopyProblem method. The companion PR (SciML/NonlinearSolve.jl) adds solve(::HomotopyProblem, ::AbstractNonlinearSolveAlgorithm) in NonlinearSolveBase, which fixes every init caller at once without any per-integrator glue.

Tests

Adds test/homotopy_initialization.jl (registered in runtests.jl): routing selection, in-place-ness is honored both ways (regression guard for the {iip} fix), non-homotopy systems unaffected, and end-to-end solving of the stored init problem. Local run (Julia 1.12): homotopy_initialization 17/17, and the existing homotopy_lowering (43), homotopy_problem (29), homotopy_omc_parity (13) all still pass.

Notes / known limitations

  • Non-square (over/under-determined) homotopy init systems fall through to NonlinearLeastSquaresProblem, which loses continuation (HomotopyProblem requires a square system). Currently silent; a warning could be added.
  • The homotopy branch does not forward unknowns' bounds metadata (the continuation solvers don't consume lb/ub).

Process

Implemented and demonstrated against canonical Modelica homotopy examples (turbulent PressureDrop resistor and coupled flow network at the singular zero-flow guess, atan saturation, squared-flow branch selection, an S-fold) where a plain Newton init stalls / picks the wrong branch but the auto-homotopy init succeeds. An adversarial multi-agent review of the diff surfaced the {iip} bug (fixed here) and the default_nlsolve ambiguity (addressed by choosing the NonlinearSolveBase-side companion). Runic-formatted.

🤖 Generated with Claude Code

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Companion (solver-side) PR: SciML/NonlinearSolve.jl#1085 — adds the solve(::HomotopyProblem, ::AbstractNonlinearSolveAlgorithm) fallback that lets solve(odeprob) initialize a homotopy init system by continuation. Both are drafts; please ignore until reviewed by @ChrisRackauckas.

@oscardssmith

Copy link
Copy Markdown
Member

how do benchmarks compare?

@AayushSabharwal AayushSabharwal left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also doesn't hit the MTK method of get_initialization_problem_type which builds SCCNonlinearProblem. Or is the intention that individual SCCs do the homotopy init?

# the initialization path, which has already resolved `iip` from the calling problem and
# must not re-derive it (an out-of-place system's `op` is still a plain varmap, so the
# `Both` derivation would wrongly pick in-place).
function SciMLBase.HomotopyProblem(sys::System, op; kwargs...)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why doesn't this use @fallback_iip_specialize?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to it in b014ca5. I had hand-written the {iip} form following the SCCNonlinearProblem{iip}(sys, op) pattern, but the macro is the better fit: its problem-default of Both reproduces the previous zero-argument behaviour exactly (resolve_iip(Both, op)), and it supplies HomotopyProblem{iip} for free — which is what let me collapse the duplicated branch you spotted below.

Comment on lines 159 to 175
if TProb === SciMLBase.HomotopyProblem
# The init system contains Modelica `homotopy` nodes: build a `HomotopyProblem`
# so the initialization is solved by continuation from the `simplified` form.
# Pass the resolved `_iip` explicitly (like the sibling `TProb{_iip}` branch): the
# bare `HomotopyProblem(sys, op)` would re-derive in-place-ness from `op`, which is
# a varmap and so always reads as in-place — wrong for an out-of-place system.
SciMLBase.HomotopyProblem{_iip}(
isys, op; kwargs..., check_length_kw...,
build_initializeprob = false, is_initializeprob = true
)
else
TProb{_iip}(
isys, op; kwargs..., check_length_kw...,
build_initializeprob = false, is_initializeprob = true
)
end
end

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both branches do the same thing?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes — leftover, good catch. That branch dates from when HomotopyProblem had no {iip} constructor form, so the homotopy side had to be built unparametrized. Once I added one (and now that it comes from @fallback_iip_specialize) both sides were character-for-character the same. Collapsed back to the single TProb{_iip}(...) call in b014ca5.

# the `LinearInitializationProblem` branch above instead — there is nothing to
# continue. `get_nonlinear_problem_type` is only defined for `System`; other
# `AbstractSystem`s keep the previous `NonlinearProblem` behavior.)
isys isa System ? get_nonlinear_problem_type(isys) : NonlinearProblem

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When is isys not a System?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Never, as far as I can tell — generate_initializesystem + mtkcompile return a System, and your override in src/initialization.jl types it isys::System outright. That guard was unnecessary defensiveness on my part; removed in b014ca5, so it just calls get_nonlinear_problem_type(isys).

@ChrisRackauckas

Copy link
Copy Markdown
Member

how do benchmarks compare?

That's not a great way to look at it. Homotopy is like 5x slower than Newton methods (the gap may be closer to 2x-3x now, I've been optimizing), but if you're adding homotopy operators then Newton methods probably don't converge anyways. So the general benchmark is, yes there are lots of problems where no nonlinear solver except the homotopy solver converges to the solution, so if the user opts into homotopy methods by using a homotopy operator then we should use the homotopy solver.

ChrisRackauckas and others added 2 commits July 20, 2026 06:04
When the (square) initialization system contains Modelica
`homotopy(actual, simplified)` operator nodes, `InitializationProblem` now
builds a `SciMLBase.HomotopyProblem` instead of a plain `NonlinearProblem`,
selected with the same dispatch as `AbstractNonlinearProblem(isys, op)`
(`get_nonlinear_problem_type`). The initialization is then solved by
natural-parameter / pseudo-arclength continuation from the `simplified`
form, robustly initializing systems whose target form is hard to solve from
a cold start (singular Jacobian at the natural guess, multiple roots, folds).

Systems without `homotopy` nodes are unaffected — they take a byte-identical
path (`get_nonlinear_problem_type` returns `NonlinearProblem`).

The init branch threads the caller's resolved `_iip` through a new
`SciMLBase.HomotopyProblem{iip}(sys, op)` constructor form: the bare
`HomotopyProblem(sys, op)` derives in-place-ness from `op`, but the init `op`
is a varmap (never a `StaticArray`) so it would always read as in-place and
silently break out-of-place / StaticArray initialization at solve time.

Adds `test/homotopy_initialization.jl` (routing, in-place-ness, regression,
and end-to-end solve of the stored init problem) and registers it in
`runtests.jl`.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01GSXiS4u4BaR2RvGFWGEQeH
- `src/initialization.jl`: the full-MTK `get_initialization_problem_type` selects
  `SCCNonlinearProblem` for a fully determined split init system, so it bypassed the
  homotopy routing entirely. It now returns `HomotopyProblem` for a `homotopy`-carrying
  square init system, ahead of the SCC branch. Modelica's `homotopy` shares a single λ
  across the whole model (spec 3.7.4.2), so the init system is solved as one continuation
  rather than torn into blocks that would each sweep their own λ with per-block Newton.

- `homotopyproblem.jl`: use `@fallback_iip_specialize` instead of the hand-written
  `{iip}` forms. Its `Both` problem-default reproduces the previous zero-argument
  behaviour (`resolve_iip(Both, op)`) and supplies `HomotopyProblem{iip}` for free.

- `initializationproblem.jl`: with `HomotopyProblem{iip}` available, the two construction
  branches were identical — collapsed back to the single `TProb{_iip}(...)` call. Also
  dropped the `isys isa System` guard: `isys` is always a `System` here.

Adds `test/homotopy_initialization_scc.jl` (registered in `group_initialization.jl`): the
fixture is a three-block `a -> b -> c` chain, since a single-equation init system degrades
to a plain `NonlinearProblem` inside the `SCCNonlinearProblem` constructor and would not
exercise the SCC path at all.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01GSXiS4u4BaR2RvGFWGEQeH
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Good catch — you were right, and it was a real gap: the full-MTK path never reached the routing at all. There are two get_initialization_problem_type methods, and my change only touched the MTKBase one; src/initialization.jl's override is what actually runs, and it returns SCCNonlinearProblem. (My original end-to-end test only passed because it went through ModelingToolkitBase directly.) Fixed in b014ca5 — the override now returns HomotopyProblem for a homotopy-carrying square init system, ahead of the SCC branch.

On the design question — I went with the whole init system as one HomotopyProblem, not per-SCC, because Modelica's homotopy shares a single continuation parameter λ across the whole model (spec 3.7.4.2), and that is what lower_homotopy implements: every node gets the one HOMOTOPY_LAMBDA. SCC blocks are solved sequentially, so per-block homotopy would sweep a separate λ per block — defensible, but different semantics from what the operator declares. It's also the case that the operator is an explicit signal that the system isn't solvable from a cold start, which is exactly what the per-block Newton solves inside SCCNonlinearProblem would attempt.

That said, per-SCC is very doable and would be faster when only one block is actually hard — continuation on the whole system costs the 2-5x Chris mentions above, and here it drags the easy blocks along with it. With the companion NonlinearSolve PR (SciML/NonlinearSolve.jl#1085) a HomotopyProblem block routes to continuation automatically, so it's mostly a matter of building per-block problems in sccnonlinearproblem.jl for blocks whose equations contain homotopy nodes. Happy to switch — your call, since it's a semantics decision as much as a performance one.

One thing worth flagging that I hit while testing: a single-equation init system degrades to a plain NonlinearProblem inside the SCCNonlinearProblem constructor, so it never exercises this path. The new test therefore uses a three-block a -> b -> c chain, which genuinely tears into three SCCs (verified: without homotopy it builds an SCCNonlinearProblem, with it a HomotopyProblem).

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

@oscardssmith — Chris's framing above is the right one, but here is the concrete data I collected while building this, since it makes the "Newton probably doesn't converge anyway" claim measurable.

On canonical Modelica homotopy patterns, solved from the natural initial guesses, continuation vs. the default Newton polyalgorithm on the identical residual:

example (natural guess) continuation plain Newton polyalg
turbulent PressureDrop resistor, m = 0 (singular Jacobian: d(m·|m|)/dm = 0) ✅ ❌ Stalled
coupled two-resistor flow network, m = 0 (2×2, structurally singular in m) ✅ ❌ Stalled
atan saturation, y = 12 ✅ ✅
squared-flow branch selection, m = -3 ✅ +1 ❌ converges to the unphysical root -1

So 3 of 4 are cases where Newton either cannot move or silently lands on the wrong branch — the wrong-root one is the nastiest, since it succeeds with a clean retcode. The atan row is the honest counterexample: a modern trust-region polyalgorithm handles plenty of "hard-looking" scalar problems fine, and there homotopy buys nothing but cost.

I did not measure a head-to-head wall-clock ratio against Newton on a problem both solve, so I can't add a number to Chris's 2-5x. Within the continuation solvers themselves (which is what this PR selects), on a fold-free scalar problem: HomotopySweep 0.126 ms, ArcLengthContinuation 0.187 ms, and HomotopyPolyAlgorithm 0.124 ms — the polyalgorithm costs about the sweep because the sweep succeeds first and the arclength stage never runs. It only pays the fallback cost on problems with a fold, where the sweep cannot reach λ = 1 at all.

Per review: an initialization system that tears into SCC blocks now keeps its
`SCCNonlinearProblem`, and only the blocks whose equations carry Modelica
`homotopy(actual, simplified)` nodes are built as `SciMLBase.HomotopyProblem`s and
solved by continuation. The other blocks keep their plain Newton solves, so the
cost of continuation is paid only where the model asks for it.

- `SCCNonlinearFunction`: a homotopy-carrying block compiles the λ-swept residual
  `f(u, p, λ)` via `lower_homotopy` + `generate_homotopy_residual`. `λ` is a
  trailing argument, so the block's cache buffers — which `generate_rhs` appends to
  the parameter list — are unaffected.
- block construction: such a block becomes `HomotopyProblem(f, _u0, p; λspan)`.
- `src/initialization.jl`: no longer diverts homotopy systems away from SCC. The
  non-SCC fallbacks (`split = false`, and `use_scc = false` / `neqs == 0`) now
  return `get_nonlinear_problem_type(isys)`, so an init system that cannot be torn
  is still swept as a whole.

No `SCCNonlinearSolve` change is needed: its block loop calls
`SciMLBase.solve(prob, alg.nlalg)`, which routes a `HomotopyProblem` block to the
continuation polyalgorithm — via `solve(::HomotopyProblem, ::Nothing)`, or via the
`AbstractNonlinearSolveAlgorithm` fallback in SciML/NonlinearSolve.jl#1085 when a
concrete algorithm is passed.

Also updates the `homotopy` docstring: `λ` is shared within a lowered system or
block, but separate blocks sweep their own `λ` in dependency order.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01GSXiS4u4BaR2RvGFWGEQeH
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Switched to per-SCC in 8ab5274, as you suggested.

An init system that tears into SCC blocks now keeps its SCCNonlinearProblem, and only the blocks whose equations carry homotopy nodes are built as SciMLBase.HomotopyProblems and solved by continuation — the rest keep their plain Newton solves, so the 2-5x is paid only on the block that asked for it.

It needs no SCCNonlinearSolve change. Its block loop is sol = SciMLBase.solve(prob, alg.nlalg; kwargs...), so a HomotopyProblem block routes to the continuation polyalgorithm on its own — via the existing solve(::HomotopyProblem, ::Nothing) when the SCC alg carries no inner algorithm, and via the AbstractNonlinearSolveAlgorithm fallback in SciML/NonlinearSolve.jl#1085 when the init path passes a concrete one (which is what default_nlsolve does). That companion PR turns out to be load-bearing for exactly this. (probvec has no HomotopyProblem method, but it's dead code — never called — so it isn't a gap.)

Two things I checked before writing it, since both could have sunk the approach:

  • λ composes with the block cache buffers. generate_rhs does append!(p, cachesyms) — caches ride in the parameter list — and args = (args..., extra_args...) puts λ last with p_end marking where the parameters stop. So a block residual is exactly f(u, p, λ), the HomotopyProblem convention, with the caches untouched.
  • Block subsystems are already complete (subset_system builds them with complete = true), which lower_homotopy requires.

The changes: SCCNonlinearFunction compiles the λ-swept residual for a homotopy-carrying block (after the islin early return, so linear blocks are untouched); that block becomes HomotopyProblem(f, _u0, p; λspan); and src/initialization.jl no longer diverts homotopy systems away from SCC — its non-SCC fallbacks (split = false, use_scc = false, neqs == 0) now return get_nonlinear_problem_type(isys) so a system that can't be torn is still swept as a whole.

One semantics note worth flagging. This does change what the homotopy docstring advertised: it claimed all homotopy calls "share the single λ, per the Modelica spec's recommendation of (conceptually) one homotopy iteration over the whole model". With per-SCC, λ is shared within a block but separate blocks sweep their own λ sequentially (in dependency order, each reaching λ = 1 before the next starts). I updated the docstring to describe that rather than leave the docs contradicting the code — happy to word it differently if you'd rather frame the divergence another way.

Tests (Julia 1.12): the new test/homotopy_initialization_scc.jl is 14/14 — init is still an SCCNonlinearProblem, exactly one block is a HomotopyProblem, that block's residual genuinely depends on λ, and the solve lands the exact roots (a=√2, b=√a, c=√b); plus a guard that non-homotopy systems have no HomotopyProblem blocks, and that use_scc = false still falls back to whole-system continuation. The MTKBase homotopy suite is 102/102. The fixture is a three-block a -> b -> c chain on purpose — a single-equation init system degrades to a plain NonlinearProblem inside the SCCNonlinearProblem constructor and never exercises this path.

@oscardssmith

Copy link
Copy Markdown
Member

Given that homotopy is slower but more robust, should it be integrated into the polyalg rather than a pure opt in?

@ChrisRackauckas

Copy link
Copy Markdown
Member

I don't think that matters on the MTK side. You can just solve a HomotopyNonlinearProblem with a non-homotopy nonlinear solver, that would be the nice interface for that. I don't think the user has to care what internal structures are used.

@ChrisRackauckas
ChrisRackauckas marked this pull request as ready for review July 22, 2026 20:48
@ChrisRackauckas
ChrisRackauckas merged commit 8cb1d72 into SciML:master Jul 22, 2026
83 of 92 checks passed
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member Author

Follow-ups after reworking the NonlinearSolve companion per your note there:

  • Single-block regression fixed (37648c4): the per-SCC change I pushed earlier had a latent bug — the SCCNonlinearProblem constructor solves a single nonlinear block directly and returned a plain NonlinearProblem for it, so a one-equation homotopy init lost the sweep (my 3-block test didn't cover the degrade path). Now routed through get_nonlinear_problem_type, so a single-block homotopy init degrades to a HomotopyProblem. Added single-block tests; homotopy_initialization_scc.jl is 20/20 locally.

Companion PRs (the init now opts into continuation via the default path, not by hijacking a concrete algorithm):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants