You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用solve_ivp传入Jacobian矩阵遇警告:jac参数无效求助

Fixing the jac Warning and Jacobian Issues in solve_ivp

Hey there! Let's work through the problems you're seeing with your solve_ivp code. You've got two key issues to address:

1. The jac parameter doesn't work with the RK45 solver

The warning you're getting is straightforward: the RK45 solver (which you're using) is an explicit Runge-Kutta method, and it doesn't use a Jacobian matrix at all. The jac argument only applies to implicit solvers in solve_ivp that benefit from Jacobian information, like:

  • Radau
  • BDF
  • LSODA

If you want to leverage your Jacobian matrix to improve solver performance or stability, switch to one of these implicit methods. If you're fine sticking with RK45, just remove the jac=jacfunc argument from your solve_ivp call—you won't get the warning anymore.

2. Your Jacobian function isn't returning anything!

Looking at your Richardsmatrix function, the last line is just return with no value. That means when jacfunc calls it, it gets None instead of the actual Jacobian matrix. Even if you switch to a solver that supports jac, this will break things.

Fix this by returning the sparse matrix you created (or the dense matrix, depending on what you need):

def Richardsmatrix(hw, t, wPar, sPar, RPar, dzIN, dzN):
    # ... all your existing code to build a, b, c, B, sB ...
    return sB  # or return B if you want a dense matrix instead of sparse

Modified Code Example

Here's how your corrected solve_ivp call might look if you switch to the Radau solver (and fix the Jacobian return):

def MyIntFun(t,y): 
    return DivWatFlux(y,t,wPar, sPar, RPar,dzIN, dzN) 

def jacfunc(t,y): 
    jac = Richardsmatrix(y, t, wPar, sPar, RPar, dzIN, dzN) 
    return jac 

mt.tic()
hwODE = spi.solve_ivp(
    MyIntFun, 
    [tout[0], tout[-1]], 
    hw0, 
    method='Radau',  # Switched to a solver that supports jac
    vectorized=True,
    rtol=1e-4, 
    jac=jacfunc
)
mt.toc()

Just a quick note: if your Jacobian is sparse, make sure the solver knows that—returning a sparse matrix (like your sB) should work automatically with most implicit solvers, but you can also set the jac_sparsity argument if you need more control.

内容的提问来源于stack exchange,提问作者J.S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:09:05