Type unstable in NonlinearSolve.jl

I am using NonlinearSolve.jl to solve a system of nonlinear equations. The @code_warntype macro gives Any type when I use NonlinearProblem, see code below. When I wrapped this code into a larger outer function, the type instability propagated. How can I solve this instability?
Thanks for your time.

using StaticArrays
using NonlinearSolve

x1 = SVector(5.410765991201068, -1.955858432452871, 1.236281448472692)
x2 = SVector(9.190671981350006, -0.858583463255322, 0.250942726005373)
x3 = SVector(8.86055136300633, 1.989613825349654, -0.69411438796056)
x4 = SVector(4.978916963046636, 1.770025873857406, 0.0)
x5 = SVector(6.56268038475586, -0.632855678126095, 4.82114644313298)
x6 = SVector(9.791606329419208, 0.304474410427785, 3.979436153631626)
x7 = SVector(9.446657214279373, 3.280608222903378, 2.991928566693289)
x8 = SVector(6.13083135660143, 3.093028628184183, 3.584864994660288)
xp = SVector(6.07558940271011, -1.08983308562881, 2.09667267469191)
x0 = SVector{3,Float64}((0, 0, 0))
targetfun(x, p) = @. (p.C + p.D * x[1]) * x[2] + (p.E + p.F * x[1]) * x[3] + (p.G + p.H * x[1]) * x[2] * x[3] - (p.A + p.B * x[1])
p = (A=xp - x6,
       B=x6 - x5,
       C=x7 - x6,
       D=x6 - x5 + x8 - x7,
       E=x2 - x6,
       F=x6 - x5 + x1 - x2,
       G=x3 - x2 + x6 - x7,
       H=x2 - x1 + x5 - x6 + x7 - x8 + x4 - x3)
prob = NonlinearProblem(targetfun, x0, p)
solve(prob, SimpleNewtonRaphson())
@code_warntype NonlinearProblem(targetfun, x0, p)       # type unstable
@code_warntype solve(prob, SimpleNewtonRaphson())       # type stable

function ttt(x0, p)
       prob = NonlinearProblem(targetfun, x0, p)
       return solve(prob, SimpleNewtonRaphson())
end
@code_warntype ttt(x0, p)          # the wrapping function become unstable

Just guessing, but these XYProblem types are pretty big such that the type might not be reasonable inferable beforehand.

You could consider passing the problem instance and using remake if you need to solve similar nonlinear problems repeatedly. If you only need to solve one, then the type instability might be irrelevant anyway.

1 Like

NonlinearProblem{false}(targetfun, x0, p) setting the inplaceness directly can be required.

1 Like

Thanks to @SteffenPL and @ChrisRackauckas . Both solutions work. However, the second does not need an initial instance.