L idZddlmZddlZddlmZddlmZm Z ddl m Z ddl m Z ejej ZddZdd Zd Zd Zd Zd ZdZdZdZdZGdde ZdddddZdZdZdZ dZ! ddZ"y) zBoundary value problem solver.)warnN)pinv) coo_matrix csc_matrix)splu)OptimizeResultc|j\}}| ||||}|j}tj|||f|}tdzdtj |zz} t |D]I} |j} | | xx| | z cc<| | || z } ||| |} | |z | z |dd| ddf<K|jd}|dk(rd}||fStj|||f|}tdzdtj |zz} t |D]I} |j}|| xx| | z cc<|| || z } ||||} | |z | z |dd| ddf<K||fS)aEstimate derivatives of an ODE system rhs with forward differences. Returns ------- df_dy : ndarray, shape (n, n, m) Derivatives with respect to y. An element (i, j, q) corresponds to d f_i(x_q, y_q) / d (y_q)_j. df_dp : ndarray with shape (n, k, m) or None Derivatives with respect to p. An element (i, j, q) corresponds to d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned. Ndtype?r)shaper npemptyEPSabsrangecopy)funxypf0nmr df_dyhiy_newhif_newkdf_dpp_news Z/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/integrate/_bvp.pyestimate_fun_jacr&s 77DAq z Aq\ GGE HHaAYe ,E SAq M"A 1X+ aAaD 1X!_Aua "**aAg +  AAv %<!Q%0 HBFF1I &q /AFFHE !H! HqAaDB1e$E#bjB.E!Q'N  / %<c$|jd}|jd}| ||||}|j}tj|||zf|}tdzdtj |zz} t |D]B} |j} | | xx| | z cc<| | || z } || ||} | |z | z || <D|j}tdzdtj |zz} tj|||zf|}t |D]B} |j}|| xx| | z cc<|| || z } ||||} | |z | z || <D|j}|dk(rd}ntdzdtj |zz} tj|||zf|}t |D]B} |j}|| xx| | z cc<|| || z } ||||} | |z | z || <D|j}|||fS)a-Estimate derivatives of boundary conditions with forward differences. Returns ------- dbc_dya : ndarray, shape (n + k, n) Derivatives with respect to ya. An element (i, j) corresponds to d bc_i / d ya_j. dbc_dyb : ndarray, shape (n + k, n) Derivatives with respect to yb. An element (i, j) corresponds to d bc_i / d ya_j. dbc_dp : ndarray with shape (n + k, k) or None Derivatives with respect to p. An element (i, j) corresponds to d bc_i / d p_j. If `p` is empty, None is returned. rNr r r ) rr rrrrrrT)bcyaybrbc0rr"r dbc_dyarrya_newr bc_newdbc_dybyb_newdbc_dpr$s r%estimate_bc_jacr4:s.  A  A {Rm HHEhh1q5z/G SAr N#A 1X)q QqT AYA FB"slb( ) iiG SAr N#Ahh1q5z/G 1X)q QqT AYA B"slb( ) iiGAv HBFF1I &1a!e*E2q ,AFFHE !H! HqAaDBB&F#+F1I  ,  GV ##r'ctjtj|dz |z|}tjtj|||dz ztjtj|dz |z|dzz}tjtj|dz |z||z|z|}tjtj|||z}tjtj|dz |z|}tjtj||z||z|z|dz |z}tjtj|dz |z||z|z|} tjtj||z||z|z||z} tj|||||| f} tj|||z|||dz |zz|| f} | | fS)z{Compute indices for the collocation system Jacobian construction. See `construct_global_jac` for the explanation. r )rrepeatarangetilehstack) rrr"i_colj_coli_bcj_bci_p_colj_p_coli_p_bcj_p_bcrjs r%compute_jac_indicesrDus IIbiiQ! ,a 0E WWRYYq\1A; / YYryyQ'!+QT 23E 99RYYA{AEAI6 :D 77299Q<Q 'Dii 1q5A+.2GggbiiAq1uqy1AEQ;?G YYryy!a%1a!eai8! A 5%!)Q! +F$ %A a4Kr'cN|jddkDr}tj|jd|jd|jdf}t|jdD]!}tj||||||<#|Stj d||S)zStacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]). Empirical optimization. Use outer Python loop and BLAS for large matrices, otherwise use a single einsum call. r 2rr6z...ij,...jk->...ik)rrrrdoteinsum)aboutrs r%stacked_matmulrLs  wwqzBhh AGGAJ ;<qwwqz" (AVVAaD!A$'CF ( yy-q!44r'c htj|d}tj|d}|ddtjtjf}|j} tj|dz ||f| }tj | |dd||dz |ddd|zzzz}t ||dd}||dzdz |zz}tj|dz ||f| }tj ||dd||dz |ddd|zzzz}t ||dd}||dzdz |zz }tj|j|j| j| jf}|d kDrtj|d}tj| d} t ||dd|ddz }| d |z|zz } | dz |dd|ddzd | zzz}tj||j| jf}t|||ff}t|S) a/ Construct the Jacobian of the collocation system. There are n * m + k functions: m - 1 collocations residuals, each containing n components, followed by n + k boundary condition residuals. There are n * m + k variables: m vectors of y, each containing n components, followed by k values of vector p. For example, let m = 4, n = 2 and k = 1, then the Jacobian will have the following sparsity structure: 1 1 2 2 0 0 0 0 5 1 1 2 2 0 0 0 0 5 0 0 1 1 2 2 0 0 5 0 0 1 1 2 2 0 0 5 0 0 0 0 1 1 2 2 5 0 0 0 0 1 1 2 2 5 3 3 0 0 0 0 4 4 6 3 3 0 0 0 0 4 4 6 3 3 0 0 0 0 4 4 6 Zeros denote identically zero values, other values denote different kinds of blocks in the matrix (see below). The blank row indicates the separation of collocation residuals from boundary conditions. And the blank column indicates the separation of y values from p values. Refer to [1]_ (p. 306) for the formula of n x n blocks for derivatives of collocation residuals with respect to y. Parameters ---------- n : int Number of equations in the ODE system. m : int Number of nodes in the mesh. k : int Number of the unknown parameters. i_jac, j_jac : ndarray Row and column indices returned by `compute_jac_indices`. They represent different blocks in the Jacobian matrix in the following order (see the scheme above): * 1: m - 1 diagonal n x n blocks for the collocation residuals. * 2: m - 1 off-diagonal n x n blocks for the collocation residuals. * 3 : (n + k) x n block for the dependency of the boundary conditions on ya. * 4: (n + k) x n block for the dependency of the boundary conditions on yb. * 5: (m - 1) * n x k block for the dependency of the collocation residuals on p. * 6: (n + k) x k block for the dependency of the boundary conditions on p. df_dy : ndarray, shape (n, n, m) Jacobian of f with respect to y computed at the mesh nodes. df_dy_middle : ndarray, shape (n, n, m - 1) Jacobian of f with respect to y computed at the middle between the mesh nodes. df_dp : ndarray with shape (n, k, m) or None Jacobian of f with respect to p computed at the mesh nodes. df_dp_middle : ndarray with shape (n, k, m - 1) or None Jacobian of f with respect to p computed at the middle between the mesh nodes. dbc_dya, dbc_dyb : ndarray, shape (n, n) Jacobian of bc with respect to ya and yb. dbc_dp : ndarray with shape (n, k) or None Jacobian of bc with respect to p. Returns ------- J : csc_matrix, shape (n * m + k, n * m + k) Jacobian of the collocation system in a sparse form. References ---------- .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27, Number 3, pp. 299-316, 2001. )r6rr Nr r r6 r?) r transposenewaxisr ridentityrLr:ravelrr)rrr"i_jacj_jacrr df_dy_middler# df_dp_middler.r1r3r dPhi_dy_0r) dPhi_dy_1valuesdPhi_dpJs r%construct_global_jacr`s0d LL *E<< i8L !RZZ #$A KKE!a%Ae4IKKN?IaL Q%*q<'7788I|U3BZ0A AQI!a%Ae4I;;q>IaL Q%)a,&6677I|U12Y/A AQI YY )9??+ Aq! AqABx!AssF)+, Qq!"uX!SbS& 123H1Sb6C!G#Xq1H12h1crc6"QUa3B3i!AqrE(.B./(l/;&<.col_funBssAq!Q//r'c4 %t|||\}}t|||\}} n||\}}||\}} "t |dddf|dddf||\} } } n|dddf|dddf|\} } } t|||| | | | S)NrrO)r&r4r`)rrrdrcrer-rr#rYrZr.r1r3r*bc_jacrfun_jacrrWrXr"rrrx_middles r%sys_jaczprepare_sys..sys_jacEs ?+CAq!'6r1QT7AaeH78#(? $GWf(.a1gqBx'C $GWf#Aq!UE1e$0%w$+V5 5r')rD)rrr"rr*rnrmrrrkrprWrXros````````` @@@r% prepare_sysrq=sF"vaH&q!Q/LE5055& G r'c d|zdz| z} d} d} d}d}d}|||\}}}}||dddf|ddd f|}tj|jd |f}d}d }d }t| D]}|rE|||||||}|dz } t |}|j |}tj||}d||zj||fd }|||zd} d}!t|dzD]}"||!|zz }#|$tj||#dddf|#dddf<||!| zz }$||#|$\}}}}||#dddf|#ddd f|$}tj|jd |f}j |}%tj|%|%}&|&dd|!z|zz zkrn |"|ks|!|z}!#}$}|| k(rntjtj|| dtj|zzkr-tjtj|| krn|!dk(r%}&}d }d }|||fS#t $rd }YwxYw)a5 Solve the nonlinear collocation system by a Newton method. This is a simple Newton method with a backtracking line search. As advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2 is used, where J is the Jacobian matrix at the current iteration and r is the vector or collocation residuals (values of the system lhs). The method alters between full Newton iterations and the fixed-Jacobian iterations based There are other tricks proposed in [1]_, but they are not used as they don't seem to improve anything significantly, and even break the convergence on some test problems I tried. All important parameters of the algorithm are defined inside the function. Parameters ---------- n : int Number of equations in the ODE system. m : int Number of nodes in the mesh. h : ndarray, shape (m-1,) Mesh intervals. col_fun : callable Function computing collocation residuals. bc : callable Function computing boundary condition residuals. jac : callable Function computing the Jacobian of the whole system (including collocation and boundary condition residuals). It is supposed to return csc_matrix. y : ndarray, shape (n, m) Initial guess for the function values at the mesh nodes. p : ndarray, shape (k,) Initial guess for the unknown parameters. B : ndarray with shape (n, n) or None Matrix to force the S y(a) = 0 condition for a problems with the singular term. If None, the singular term is assumed to be absent. bvp_tol : float Tolerance to which we want to solve a BVP. bc_tol : float Tolerance to which we want to satisfy the boundary conditions. Returns ------- y : ndarray, shape (n, m) Final iterate for the function values at the mesh nodes. p : ndarray, shape (k,) Final iterate for the unknown parameters. singular : bool True, if the LU decomposition failed because Jacobian turned out to be singular. References ---------- .. [1] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of Boundary Value Problems for Ordinary Differential Equations", Philidelphia, PA: Society for Industrial and Applied Mathematics, 1995. gUUUUUU?g?rRg?r NrrOF)orderFTr r6) rr:rVrr RuntimeErrorsolverGreshapeallr)'rrrrkr*jacrrBbvp_tolbc_toltol_rmax_njevmax_itersigmataun_trialrfrdrcrebc_resresnjevsingular recompute_jac iterationr_LUstepcosty_stepp_stepalphatrialrr$step_newcost_news' r% solve_newtonr[sL !GdNW $E H H E CG%,Q]"GXq( !Q$1b51 %F ))W]]]-v6 7C DHM8_4! Aq(Ax8A AID !W 88C=D66$%Dfq1u%%q!fC%8a!ef7Q;' E&E} ffQad 4ad &E-4UE-B *GXq(ad U1b5\59F))W]]]5v>?Cxx}Hvvh1H1q5y500D88w ! $   8   FF266'?Ua"&&2B.B%CC Drvvf~./  A:DD!M Mi4!l a>a   s I I! I!c8tddddddddddy)N Iteration^15z Max residualzMax BC residualz Total nodesz Nodes addedprintrbr'r%print_iteration_headerrs4 [ nS12CC1H 3  c2 45r'c8t|d|d|d|d|dy)Nrz^15.2er)rresidual bc_residual total_nodes nodes_addeds r%print_iteration_progressrs2 YsOHV,[,@  k#. 01r'c eZdZy) BVPResultN)__name__ __module__ __qualname__rbr'r%rrsr'rz0The algorithm converged to the desired accuracy.z-The maximum number of mesh nodes is exceeded.zDA singular Jacobian encountered when solving the collocation system.zOThe solver was unable to satisfy boundary conditions tolerance on iteration 10.)rr r6c|ddd|zz}d|zdz}||z} ||z } || } || } || d} || d}|| | |}|| | |}| |z }||z }|dtj|zz}|dtj|zz}|dtj|zz}tjtj|tj|zd}tjtj|tj|zd}tjtj|tj|zd}dd|zd ||zzzzdzS) aEstimate rms values of collocation residuals using Lobatto quadrature. The residuals are defined as the difference between the derivatives of our solution and rhs of the ODE system. We use relative residuals, i.e., normalized by 1 + np.abs(f). RMS values are computed as sqrt from the normalized integrals of the squared relative residuals over each interval. Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the fact that residuals at the mesh nodes are identically zero. In [2] they don't normalize integrals by interval lengths, which gives a higher rate of convergence of the residuals by the factor of h**0.5. I chose to do such normalization for an ease of interpretation of return values as RMS estimates. Returns ------- rms_res : ndarray, shape (m - 1,) Estimated rms values of the relative residuals over each interval. References ---------- .. [1] http://mathworld.wolfram.com/LobattoQuadrature.html .. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27, Number 3, pp. 299-316, 2001. NrOr g*tj||Srjrasarray)rr_r rs r%fun_pzwrap_functions..fun_ps::c!Qi/ /r'c>tj||Srjr)r+r,rr*r s r% bc_wrappedz"wrap_functions..bc_wrappeds::bRj%0 0r'cBtj||dfSrjr)rrrr rns r% fun_jac_pz!wrap_functions..fun_jac_pszz'!Q-7==r'cv||\}}tj|tj|dfSrjr)r+r,rr.r1rmr s r%bc_jac_wrappedz&wrap_functions..bc_jac_wrappeds;#)"b>  7E2 7E2D::r'c@tj|||Srjr)rrrr rs r%rzwrap_functions..fun_ps::c!QlE2 2r'c@tj|||Srjr)rrrr*r s r%rz"wrap_functions..bc_wrappeds::bAqk51 1r'cv|||\}}tj|tj|fSrjr)rrrrr#r rns r%rz!wrap_functions..fun_jac_ps6&q!Q/ uzz%/E51IIIr'c|||\}}}tj|tj|tj|fSrjr)r+r,rr.r1r3rmr s r%rz&wrap_functions..bc_jac_wrappedsK+1"b!+<(& 7E2BJJw4N 65133r'c (|||}|dk(r_tj|dddf|dddf<|ddddfxxtj|ddddf|ddz z z cc<|S|tj||z z z }|SNrr rrG)rrrrcDSrIrs r% fun_wrappedz#wrap_functions..fun_wrappedsaAAtqy&&AadG,!Q$!QR%BFF1a12h/1QR519==HRVVAq\QU++Hr'c|||\}}|dk(rMtj|dddddf|dddddf<|ddddddfxx|ddz z z cc<||fS||z z z }||fSrr) rrrrr#rSrrIrs r%fun_jac_wrappedz'wrap_functions..fun_jac_wrappeds(Aq1 uQ419%'VVAuQ1W~%>E!Q'N!Q(OrQqrUQY'77Oe|#R1q5\)Ee|#r')rrT)rr*rnrmr"rIrrr rrrrrrrs```` ```` @@@r%wrap_functionsr~s ~Av 0 1   >   :  3 2   J   3  y   9'O1a#$B $  O^ CCr'c  tj|t}|jdk7r t dtj |} tj | dkr t d|d} tj|}tj|jtjrt}nt}|j|d}|jdk7r t d |jd|jdk7r,t d |jdd |jdd |tjg}ntj||}|jdk7r t d|dtzkr!tddtzdddtz}| dvr t d|jd}|jd}|tj||}|j||fk7rt d||fd|jtj |tj"t%||z }tj"||d d df|d d df<t%tj ||z }nd }d }| |} d}t'|||||| ||| \}}}}||||}|j|jk7r&t d|jd|jd ||d d df|d d df|}|j||zfk7r t d||zfd|jd d}d}| dk(r t) |jd}t+||||||||| \}}t-||| |||||||| \}}}|dz }t/||||| \} }!}}"||d d df|d d df|}tj0t3|}#d| z| z }$t5|||| }%t7||%|| ||$|"}&tj0|&}'|rd}ntj8|&|kD|&d|zkz\}(tj8|&d|zk\\})|(jdd|)jdzz}*||*z| kDrd}| dk(rd|*d}*t;||'|#||*nV| dk(rt;||'|#||*|*dkDr+t=||(|)}tj |} |%|}n|#| krd}n ||k\rd}n| dkDr|dk(r't?d|d |jdd!|'dd"|#dnS|dk(rt?d#|d!|'dd"|#dn7|dk(rt?d$|d!|'dd"|#dn|dk(rt?d%|d!|'dd"|#d|j@dk(rd }tC|%|||||&||tD||dk(& S)'a,Solve a boundary value problem for a system of ODEs. This function numerically solves a first order system of ODEs subject to two-point boundary conditions:: dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b bc(y(a), y(b), p) = 0 Here x is a 1-D independent variable, y(x) is an n-D vector-valued function and p is a k-D vector of unknown parameters which is to be found along with y(x). For the problem to be determined, there must be n + k boundary conditions, i.e., bc must be an (n + k)-D function. The last singular term on the right-hand side of the system is optional. It is defined by an n-by-n matrix S, such that the solution must satisfy S y(a) = 0. This condition will be forced during iterations, so it must not contradict boundary conditions. See [2]_ for the explanation how this term is handled when solving BVPs numerically. Problems in a complex domain can be solved as well. In this case, y and p are considered to be complex, and f and bc are assumed to be complex-valued functions, but x stays real. Note that f and bc must be complex differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you should rewrite your problem for real and imaginary parts separately. To solve a problem in a complex domain, pass an initial guess for y with a complex data type (see below). Parameters ---------- fun : callable Right-hand side of the system. The calling signature is ``fun(x, y)``, or ``fun(x, y, p)`` if parameters are present. All arguments are ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that ``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The return value must be an array with shape (n, m) and with the same layout as ``y``. bc : callable Function evaluating residuals of the boundary conditions. The calling signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,), and ``p`` with shape (k,). The return value must be an array with shape (n + k,). x : array_like, shape (m,) Initial mesh. Must be a strictly increasing sequence of real numbers with ``x[0]=a`` and ``x[-1]=b``. y : array_like, shape (n, m) Initial guess for the function values at the mesh nodes, ith column corresponds to ``x[i]``. For problems in a complex domain pass `y` with a complex data type (even if the initial guess is purely real). p : array_like with shape (k,) or None, optional Initial guess for the unknown parameters. If None (default), it is assumed that the problem doesn't depend on any parameters. S : array_like with shape (n, n) or None Matrix defining the singular term. If None (default), the problem is solved without the singular term. fun_jac : callable or None, optional Function computing derivatives of f with respect to y and p. The calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if parameters are present. The return must contain 1 or 2 elements in the following order: * df_dy : array_like with shape (n, n, m), where an element (i, j, q) equals to d f_i(x_q, y_q, p) / d (y_q)_j. * df_dp : array_like with shape (n, k, m), where an element (i, j, q) equals to d f_i(x_q, y_q, p) / d p_j. Here q numbers nodes at which x and y are defined, whereas i and j number vector components. If the problem is solved without unknown parameters, df_dp should not be returned. If `fun_jac` is None (default), the derivatives will be estimated by the forward finite differences. bc_jac : callable or None, optional Function computing derivatives of bc with respect to ya, yb, and p. The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)`` if parameters are present. The return must contain 2 or 3 elements in the following order: * dbc_dya : array_like with shape (n, n), where an element (i, j) equals to d bc_i(ya, yb, p) / d ya_j. * dbc_dyb : array_like with shape (n, n), where an element (i, j) equals to d bc_i(ya, yb, p) / d yb_j. * dbc_dp : array_like with shape (n, k), where an element (i, j) equals to d bc_i(ya, yb, p) / d p_j. If the problem is solved without unknown parameters, dbc_dp should not be returned. If `bc_jac` is None (default), the derivatives will be estimated by the forward finite differences. tol : float, optional Desired tolerance of the solution. If we define ``r = y' - f(x, y)``, where y is the found solution, then the solver tries to achieve on each mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is estimated in a root mean squared sense (using a numerical quadrature formula). Default is 1e-3. max_nodes : int, optional Maximum allowed number of the mesh nodes. If exceeded, the algorithm terminates. Default is 1000. verbose : {0, 1, 2}, optional Level of algorithm's verbosity: * 0 (default) : work silently. * 1 : display a termination report. * 2 : display progress during iterations. bc_tol : float, optional Desired absolute tolerance for the boundary condition residuals: `bc` value should satisfy ``abs(bc) < bc_tol`` component-wise. Equals to `tol` by default. Up to 10 iterations are allowed to achieve this tolerance. Returns ------- Bunch object with the following fields defined: sol : PPoly Found solution for y as `scipy.interpolate.PPoly` instance, a C1 continuous cubic spline. p : ndarray or None, shape (k,) Found parameters. None, if the parameters were not present in the problem. x : ndarray, shape (m,) Nodes of the final mesh. y : ndarray, shape (n, m) Solution values at the mesh nodes. yp : ndarray, shape (n, m) Solution derivatives at the mesh nodes. rms_residuals : ndarray, shape (m - 1,) RMS values of the relative residuals over each mesh interval (see the description of `tol` parameter). niter : int Number of completed iterations. status : int Reason for algorithm termination: * 0: The algorithm converged to the desired accuracy. * 1: The maximum number of mesh nodes is exceeded. * 2: A singular Jacobian encountered when solving the collocation system. message : string Verbal description of the termination reason. success : bool True if the algorithm converged to the desired accuracy (``status=0``). Notes ----- This function implements a 4th order collocation algorithm with the control of residuals similar to [1]_. A collocation system is solved by a damped Newton method with an affine-invariant criterion function as described in [3]_. Note that in [1]_ integral residuals are defined without normalization by interval lengths. So, their definition is different by a multiplier of h**0.5 (h is an interval length) from the definition used here. .. versionadded:: 0.18.0 References ---------- .. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27, Number 3, pp. 299-316, 2001. .. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP Solver", J. Numer. Anal., Ind. Appl. Math. (JNAIAM), Vol. 1, Number 2, pp. 201-217, 2006. .. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of Boundary Value Problems for Ordinary Differential Equations", Philidelphia, PA: Society for Industrial and Applied Mathematics, 1995. :doi:`10.1137/1.9781611971231` .. [4] `Cauchy-Riemann equations `_ on Wikipedia. Examples -------- In the first example, we solve Bratu's problem:: y'' + k * exp(y) = 0 y(0) = y(1) = 0 for k = 1. We rewrite the equation as a first-order system and implement its right-hand side evaluation:: y1' = y2 y2' = -exp(y1) >>> import numpy as np >>> def fun(x, y): ... return np.vstack((y[1], -np.exp(y[0]))) Implement evaluation of the boundary condition residuals: >>> def bc(ya, yb): ... return np.array([ya[0], yb[0]]) Define the initial mesh with 5 nodes: >>> x = np.linspace(0, 1, 5) This problem is known to have two solutions. To obtain both of them, we use two different initial guesses for y. We denote them by subscripts a and b. >>> y_a = np.zeros((2, x.size)) >>> y_b = np.zeros((2, x.size)) >>> y_b[0] = 3 Now we are ready to run the solver. >>> from scipy.integrate import solve_bvp >>> res_a = solve_bvp(fun, bc, x, y_a) >>> res_b = solve_bvp(fun, bc, x, y_b) Let's plot the two found solutions. We take an advantage of having the solution in a spline form to produce a smooth plot. >>> x_plot = np.linspace(0, 1, 100) >>> y_plot_a = res_a.sol(x_plot)[0] >>> y_plot_b = res_b.sol(x_plot)[0] >>> import matplotlib.pyplot as plt >>> plt.plot(x_plot, y_plot_a, label='y_a') >>> plt.plot(x_plot, y_plot_b, label='y_b') >>> plt.legend() >>> plt.xlabel("x") >>> plt.ylabel("y") >>> plt.show() We see that the two solutions have similar shape, but differ in scale significantly. In the second example, we solve a simple Sturm-Liouville problem:: y'' + k**2 * y = 0 y(0) = y(1) = 0 It is known that a non-trivial solution y = A * sin(k * x) is possible for k = pi * n, where n is an integer. To establish the normalization constant A = 1 we add a boundary condition:: y'(0) = k Again, we rewrite our equation as a first-order system and implement its right-hand side evaluation:: y1' = y2 y2' = -k**2 * y1 >>> def fun(x, y, p): ... k = p[0] ... return np.vstack((y[1], -k**2 * y[0])) Note that parameters p are passed as a vector (with one element in our case). Implement the boundary conditions: >>> def bc(ya, yb, p): ... k = p[0] ... return np.array([ya[0], yb[0], ya[1] - k]) Set up the initial mesh and guess for y. We aim to find the solution for k = 2 * pi, to achieve that we set values of y to approximately follow sin(2 * pi * x): >>> x = np.linspace(0, 1, 5) >>> y = np.zeros((2, x.size)) >>> y[0, 1] = 1 >>> y[0, 3] = -1 Run the solver with 6 as an initial guess for k. >>> sol = solve_bvp(fun, bc, x, y, p=[6]) We see that the found k is approximately correct: >>> sol.p[0] 6.28329460046 And, finally, plot the solution to see the anticipated sinusoid: >>> x_plot = np.linspace(0, 1, 100) >>> y_plot = sol.sol(x_plot)[0] >>> plt.plot(x_plot, y_plot) >>> plt.xlabel("x") >>> plt.ylabel("y") >>> plt.show() r r z`x` must be 1 dimensional.rz `x` must be strictly increasing.F)rr6z`y` must be 2 dimensional.z`y` is expected to have z columns, but actually has .Nz`p` must be 1 dimensional.dz`tol` is too low, setting to z.2e) stacklevel)rr r6z`verbose` must be in [0, 1, 2].z`S` is expected to have shape z, but actually has z'`fun` return is expected to have shape rOz&`bc` return is expected to have shape g?()rz Solved in z iterations, number of nodes z. Maximum relative residual: z Maximum boundary residual: z,Number of nodes is exceeded after iteration zOSingular Jacobian encountered when solving the collocation system on iteration zLThe solver was unable to satisfy boundary conditions tolerance on iteration ) rrrrr rms_residualsniterstatusmessagesuccess)#rrfloatndim ValueErrordiffany issubdtyper complexfloatingcomplexastyperarrayrrrUrGrrrrqrrgmaxrrrnonzerorrrsizerTERMINATION_MESSAGES)+rr*rrrrrnrmtol max_nodesverboser}rrIr rr"r{r max_iterationrrrrrcrrrrrkjac_sysrrfrdre max_bc_resrrrms_res max_rms_resrrrs+ r% solve_bvprsJ 1E"Avv{566  A vva1f~;<< !A 1 A }}QWWb001 U#Avv{566wwqzQWWQZ3AGGAJ<@ ! |1./ / y HHRL JJq &vv{566 S3Y ,S3YsO <KCii:;;  A  A} JJq & 77q!f =q!fXF112 ;< < KKNRVVDGQ/ /&&AadG$!Q$ Q!# $   ~M?M R&!Q1e@5 >FI!|  GGAJ&q!Q Z'61N%aAw G&'AsF<1hQ )8a9:Aq*B&1hAadGQq"uXq1VVCK( =1$Aq!Q'(c1a)18=ffWo F JJ# 'C#I2EFG JJw#)34 nnQ'!hnnQ.?*?? {?Y &F!| !+a0 (K)*K9  a< $Y Z%0 2 ?Ax2A AAA 6 !F  - 'F e h{ Q; Jyk)FqwwqzlS00;C/@A00:3/?A Bq[ @ L00;C/@A00:3/?A Bq[ ))2 400;C/@A00:3/?A Bq[ ,,5;700;C/@A00:3/?A B  vv{  Q!$V1&96Q; PPr'rj)NNNNgMbP?irN)#__doc__warningsrnumpyr numpy.linalgr scipy.sparserrscipy.sparse.linalgrscipy.optimizerfinforepsrr&r4rDrLr`rgrqrrrrrrrrrrrbr'r%rs$/$)bhhuo(V8$v4 5sl&*RAPr'