Skip to content

Instantly share code, notes, and snippets.

@j-fu
Created October 21, 2025 21:36
Show Gist options
  • Select an option

  • Save j-fu/9ee3a3d8aa33f2a0ae5e1d96c43ad33c to your computer and use it in GitHub Desktop.

Select an option

Save j-fu/9ee3a3d8aa33f2a0ae5e1d96c43ad33c to your computer and use it in GitHub Desktop.
MWE for issue with SCT+Nonlinear solve
module MWE_DI
using DifferentiationInterface
using NonlinearSolve
using SparseConnectivityTracer
using SparseMatrixColorings
struct System{Tprep}
X::Vector{Float64}
jac_prep::Tprep
end
function unknowns(sys::System, value = 0.0)
u = copy(sys.X)
u .= value
return u
end
function operator!(f, u, sys)
(; X) = sys
n = length(X)
f .= zero(eltype(f))
for i in 1:(n - 1)
du = (u[i + 1] - u[i]) / (X[i + 1] - X[i])
f[i] += du
f[i + 1] -= du
end
for i in 1:n
f[i] += 0.1 * u[i] - 1
end
return f
end
function SystemSCT(X)
X = collect(X)
protosys = System(X, nothing)
input = unknowns(protosys, 1)
output = unknowns(protosys)
backend = AutoSparse(
AutoForwardDiff();
sparsity_detector = TracerSparsityDetector(),
coloring_algorithm = GreedyColoringAlgorithm()
)
jac_prep = prepare_jacobian(
(f, u) -> operator!(f, u, protosys),
output,
backend,
input;
strict = Val(false)
)
return System(X, jac_prep)
end
function SystemADT(X)
X = collect(X)
protosys = System(X, nothing)
input = unknowns(protosys, 1)
output = unknowns(protosys)
sparsity = ADTypes.jacobian_sparsity(
(f, u) -> operator!(f, u, protosys),
output,
input,
TracerSparsityDetector()
)
return System(X, sparsity)
end
function testSCT(; withprototype = false)
sys = SystemSCT(range(0, 1, length = 11))
if withprototype
nlfunc = NonlinearFunction(operator!, jac_prototype = sys.jac_prep.sparsity)
else
nlfunc = NonlinearFunction(operator!)
end
prob = NonlinearProblem(nlfunc, unknowns(sys, 0.5), sys)
return solve(prob, NewtonRaphson())
end
function testADT(; withprototype = false)
sys = SystemADT(range(0, 1, length = 11))
if withprototype
nlfunc = NonlinearFunction(operator!, jac_prototype = sys.jac_prep)
else
nlfunc = NonlinearFunction(operator!)
end
prob = NonlinearProblem(nlfunc, unknowns(sys, 0.5), sys)
return solve(prob, NewtonRaphson())
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment