Skip to content

Add HomotopySweep: natural-parameter continuation solver for HomotopyProblem - #962

Merged
ChrisRackauckas merged 15 commits into
SciML:masterfrom
BatchZero:feature/homotopy-sweep
Jun 11, 2026
Merged

ChrisRackauckas merged 15 commits into
SciML:masterfrom
BatchZero:feature/homotopy-sweep

Conversation

@BatchZero

@BatchZero BatchZero commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds HomotopySweep, a natural-parameter continuation solver for SciMLBase.HomotopyProblem. Given a homotopy family 0 = H(u, p, λ), it sweeps λ across the problem's λspan (default 0 → 1), warm-starting an inner nonlinear solve at each step from the previous step's solution, with step-size bisection on a non-converging step. This robustly solves systems whose target form (λ=1) is hard to solve cold but whose λ=0 form is easy.

It is MTK-independent — any user with a hand-built HomotopyProblem can solve(prob, HomotopySweep()). It is unrelated to the polynomial HomotopyContinuationJL (which tracks complex polynomial paths via HomotopyContinuation.jl); HomotopySweep is a real-arithmetic embedding-homotopy continuation for general nonlinear systems.

API

HomotopySweep(; inner = nothing, nsteps = 10, adaptive = true, min_dλ = 1.0e-3)
  • inner — inner nonlinear algorithm used at each λ-step; nothing selects the default polyalgorithm (not a hardcoded Newton).
  • nsteps — number of λ steps across λspan.
  • adaptive / min_dλ — on a non-converging inner solve, halve the λ increment and retry, down to min_dλ; otherwise surface the inner solver's failure retcode.

A HomotopyProblem solved with no algorithm (solve(prob, nothing)) defaults to HomotopySweep().

The algorithm lives in NonlinearSolveBase (beside the sibling meta-algorithm NonlinearSolvePolyAlgorithm) and is re-exported by NonlinearSolve.

Tests

test/Core/homotopy_sweep_tests__item*.jl (Core group): construction/defaults; monotone-sweep convergence; an out-of-basin rescue acceptance test (a guess from which a cold Newton diverges — atan(x-3) saturation — rescued to the actual root by continuation); failure retcode when the family has no real root past a fold; composable inner solver (default polyalg / NewtonRaphson / SimpleNewtonRaphson); integer-eltype p; and the nothing-algorithm default route.

Depends on

SciML/SciMLBase.jl#1375 — adds HomotopyProblem, which this solver dispatches on. This PR should merge after that one releases; the [compat] SciMLBase lower bound will be bumped to the release carrying HomotopyProblem.

Part of a series

Second of three coordinated PRs for the Modelica homotopy() operator:
SciMLBase HomotopyProblem (SciML/SciMLBase.jl#1375) → (this PR) NonlinearSolve HomotopySweep → ModelingToolkit lowering (to follow).

BatchZero added 10 commits June 5, 2026 12:11
Adds `HomotopySweep <: AbstractNonlinearSolveAlgorithm`, a natural-parameter
continuation solver stub for `SciMLBase.HomotopyProblem`. Wires include/export
in the main module and adds a construction test (9 assertions, all passing).
Add _lambda_setter helpers (integer-index and symbolic-SII variants) and
CommonSolve.solve(::HomotopyProblem, ::HomotopySweep) that sweeps λ from
λspan[1] to λspan[2] in nsteps steps, warm-starting each inner
NonlinearProblem solve from the previous step's solution. Also imports
HomotopyProblem from SciMLBase into the NonlinearSolve module. Happy-path
test (oop, λ in p by index) converges u → √c = 2.0 for c = 4.0.
last_sol = solve(inner_prob, alg.inner, args...; kwargs...)

if SciMLBase.successful_retcode(last_sol)
u = last_sol.u

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 is a pointer assignment, so won't it just alias and start overwriting?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Correct — the comment's claim was false under pointer assignment, and the sharper version of the problem is on the copy-in side: with alias = NonlinearAliasSpecifier(alias_u0 = true) forwarded to the inner solves, a failed attempt iterates directly in its u0 buffer and leaves diverged garbage there, corrupting the warm start for the bisected retry. Fixed in both directions: each inner problem now receives copy(u), and on success we take u = copy(last_sol.u) (defensive, in case an inner solver returns a view into persistent workspace). A regression test runs an aliased sweep against a non-aliased reference and requires exactly identical u (the step sequences are deterministic).

# conservative: step size is not restored after a bisection
dλ = dλ / 2 # bisect; retry from the same λ (do not advance)
else
# on failure: u is the last CONVERGED iterate (λ<λ1); resid is from the failed step (advisory)

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 is not true if pointer assignment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed together with the pointer-assignment thread above — with copy-in (copy(u) per attempt) and copy-out (copy(last_sol.u) on success) in place, the "last converged iterate" claim is now actually guaranteed, and a regression test covers it.

end

function HomotopySweep(; inner = nothing, nsteps = 10, adaptive = true, min_dλ = 1.0e-3)
nsteps >= 1 || throw(ArgumentError("HomotopySweep `nsteps` must be ≥ 1, got $nsteps"))

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.

nsteps magic number?

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.

I'm not sure about having a magic number here. initial_step_factor = 0.1, nsteps= nothing, adaptive = true. If adaptive = false, nsteps must be set. initial_step_factor is a default initial step, but not necessarily a default number of steps, which IMO would be dangerous.

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.

min_dλ = 1.0e-3 this is not floating point dependent. I would make it nothing, and in the algorithm instead use a value of sqrt(eps(lambda))

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.

That way if you change precision, the minimum changes with it. 1e-3 is more for Float32 than Float64.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adopted as prescribed: nsteps = nothing, adaptive = true, initial_step_factor = 0.1, min_dλ = nothing; adaptive = false without an explicit nsteps throws an ArgumentError, and min_dλ = nothing resolves to sqrt(eps(typeof(λ))) at solve time so the floor scales with precision (min_dλ <= 0 also throws — it would bisect forever). One judgment call to confirm: when nsteps is given together with adaptive = true, it sets the initial step to span/nsteps and bisection stays active; initial_step_factor only applies when nsteps === nothing. A second one: the eps floor is absolute, not scaled by the span width — on large-magnitude spans (e.g. λspan = (1e9, 2e9)) bisection can push dλ below eps(λ) before the floor bites, making λ + dλ == λ, so there is now a stall guard returning ReturnCode.Stalled instead of looping forever, with a test locking it. A span-scaled floor (sqrt(eps(λT)) * abs(λ1 - λ0)) would largely keep the sweep out of that regime — preference?

Comment on lines +70 to +72
elseif alg.adaptive && abs(dλ) / 2 >= alg.min_dλ
# conservative: step size is not restored after a bisection
dλ = dλ / 2 # bisect; retry from the same λ (do not advance)

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 is a bit simple, but can be improved in a future PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed; keeping bisection-only here, with step regrowth and/or a predictor-corrector as the natural follow-up. One scoping question: with no regrowth, a single hard region that collapses dλ to the floor commits the sweep to up to span/min_dλ further inner solves. An outer maxsteps cap (or regrowth itself) would bound that — left out to keep this PR minimal.

@ChrisRackauckas

Copy link
Copy Markdown
Member

Close but there's still a bit to do for a first merge. But main thing, the homotopy parameter should definitely be separated from the full parameter vector.

Review feedback (SciML#962):
- λ is a separate scalar argument now: each step wraps f with FixLambda (a named
  callable, so the inner solver compiles once) and hands the inner solver a plain
  NonlinearProblem with the user's p untouched; _lambda_setter machinery removed
- copy(last_sol.u): sol.u may alias solver-internal storage that the next inner
  solve can mutate (kwargs incl. alias_u0 are forwarded), which would corrupt the
  last-converged-iterate guarantee of the failure path
- step-size kwargs per review: nsteps = nothing + initial_step_factor = 0.1
  defaults; adaptive = false requires explicit nsteps
- min_dλ = nothing resolves to sqrt(eps(typeof(λ))) so the floor scales with the
  working precision instead of a fixed 1e-3
@BatchZero

Copy link
Copy Markdown
Contributor Author

λ is now fully separated from the parameter vector across both PRs; SciML/SciMLBase.jl#1375 is updated with the f(u, p, λ) residual convention. The sweep no longer touches the user's p: each step wraps the residual in a FixLambda callable fixing λ as the trailing argument, so the inner solver sees a plain (u, p) / (du, u, p) problem of the same concrete function type every step and compiles once.

A few additional hardening changes landed alongside, so the diff holds no surprises: problem-level prob.kwargs are now forwarded to inner solves (per the documented SciMLBase contract), zero-arg solve(prob) routes to HomotopySweep() (previously a MethodError), a stall guard returns ReturnCode.Stalled when dλ underflows eps(λ) (details in the step-size thread), and failure returns carry original = last_sol for diagnostics, with the failure semantics documented in the docstring.

@ChrisRackauckas

Copy link
Copy Markdown
Member

Bump the SciMLBase minimum to 3.19

Comment thread test/homotopy_sweep_tests.jl Outdated
@@ -0,0 +1,188 @@
@testitem "HomotopySweep construction + defaults" tags = [:core] begin

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.

Update to the new test format.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Converted following the #961 layout — each @testitem is now a standalone test/Core/homotopy_sweep_tests__itemN.jl included via @safetestset from the Core group in test/runtests.jl.

@ChrisRackauckas

Copy link
Copy Markdown
Member

Follow the post-SciML#961 canonical structure: each former @testitem in
test/homotopy_sweep_tests.jl becomes a standalone
test/Core/homotopy_sweep_tests__itemN.jl, registered via @safetestset in
the Core group block of test/runtests.jl. Test bodies are unchanged
(14 items, 45 assertions).
…earSolve 4.20.0

HomotopyProblem ships in SciMLBase 3.19.0, so the minimum moves to 3.19
in the root and NonlinearSolveBase Project.tomls (as requested in
review). NonlinearSolveBase gains HomotopySweep (feature -> 2.31.0); the
root re-exports it and its Core test group references it, so the root
NonlinearSolveBase floor rises to 2.31 (-> 4.20.0). The lts grids and
the root Downgrade job resolve NonlinearSolveBase from the registry and
stay red until 2.31.0 is registered, then heal automatically.
The HomotopySweep default-algorithm entry points
solve(::HomotopyProblem, ::Nothing, ...) and solve(::HomotopyProblem; ...)
are all-foreign signatures, so Aqua.test_piracies flags them. Add
HomotopyProblem to treat_as_own, matching the existing NonlinearProblem
entry (Aqua matches treat_as_own exactly and does not expand subtypes,
so the AbstractNonlinearProblem entry does not cover it).
@BatchZero

Copy link
Copy Markdown
Contributor Author

Done — SciMLBase = "3.19" in the root Project.toml and in lib/NonlinearSolveBase, master merged, and the tests are converted to the new layout (14 files under test/Core/homotopy_sweep_tests__item*.jl, registered in the Core group). All 14 pass locally against SciMLBase v3.19.0.

Three release-chain items came out of checking the CI semantics:

  • NonlinearSolveBase's Aqua piracy check now treats SciMLBase.HomotopyProblem as own — the solve(::HomotopyProblem, ...) default-algorithm methods are all-foreign signatures, same pattern as the existing NonlinearProblem entry.
  • Versions bumped: NonlinearSolveBase 2.31.0, NonlinearSolve 4.20.0, with the root NonlinearSolveBase floor raised to 2.31 since the root Core group now references HomotopySweep.
  • Until a NonlinearSolveBase with HomotopySweep is registered, the lts grids (Pkg 1.10 ignores [sources], so NonlinearSolveBase resolves from the registry) and the root Downgrade job will stay red; with the 2.31 floor they heal automatically once it's registered.

Comment thread lib/NonlinearSolveBase/test/qa/qa.jl Resolved
@ChrisRackauckas

Copy link
Copy Markdown
Member

There are still a lot of things I want to do to improve the solver here, but this is a baseline that I think is good to start with.

@ChrisRackauckas
ChrisRackauckas merged commit 633d93a into SciML:master Jun 11, 2026
47 of 95 checks passed
local last_sol

while true
next_λ = abs(λend - λ) <= abs(dλ) ? λend : λ + dλ

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 isn't evaluated at 0, so the initial is never found 😅

BatchZero added a commit to BatchZero/NonlinearSolve.jl that referenced this pull request Jun 16, 2026
The sweep initialized λ = λspan[1] but the first inner solve ran at λspan[1] + dλ
warm-started from u0, so the system at λspan[1] -- the `simplified` system for the
canonical (0, 1) span -- was never solved. Adaptive bisection only fires on
inner-solve failure, so a poor u0 that converges onto the wrong branch at
λspan[1] + dλ is tracked to a wrong root with a success retcode (e.g.
H = (1-λ)(u-4) + λ(u^2-4) from u0 = -10 returns -2 instead of +2).

Solve at λ = λspan[1] from u0 before stepping; continue from that iterate. The
zero-width-span, adaptive-bisection, and failure contracts are preserved -- a
failed anchor fails fast with the inner retcode and leaves u at u0.

Tests: item15 (wrong-branch regression -> +2), item16 (anchor-failure contract),
item17 (zero-width span); item10 rewritten to keep a solvable λspan[1] anchor so
it still exercises the mid-sweep stall guard.

Follow-up to SciML#962.
ChrisRackauckas pushed a commit that referenced this pull request Jun 30, 2026
…on) (#972)

The sweep initialized λ = λspan[1] but the first inner solve ran at λspan[1] + dλ
warm-started from u0, so the system at λspan[1] -- the `simplified` system for the
canonical (0, 1) span -- was never solved. Adaptive bisection only fires on
inner-solve failure, so a poor u0 that converges onto the wrong branch at
λspan[1] + dλ is tracked to a wrong root with a success retcode (e.g.
H = (1-λ)(u-4) + λ(u^2-4) from u0 = -10 returns -2 instead of +2).

Solve at λ = λspan[1] from u0 before stepping; continue from that iterate. The
zero-width-span, adaptive-bisection, and failure contracts are preserved -- a
failed anchor fails fast with the inner retcode and leaves u at u0.

Tests: item15 (wrong-branch regression -> +2), item16 (anchor-failure contract),
item17 (zero-width span); item10 rewritten to keep a solvable λspan[1] anchor so
it still exercises the mid-sweep stall guard.

Follow-up to #962.
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.

2 participants