diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..039234777d35a1aebce2b93b943261e4f013a6b5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/__init__.py @@ -0,0 +1,110 @@ +""" +============================================= +Integration and ODEs (:mod:`scipy.integrate`) +============================================= + +.. currentmodule:: scipy.integrate + +Integrating functions, given function object +============================================ + +.. autosummary:: + :toctree: generated/ + + quad -- General purpose integration + quad_vec -- General purpose integration of vector-valued functions + dblquad -- General purpose double integration + tplquad -- General purpose triple integration + nquad -- General purpose N-D integration + fixed_quad -- Integrate func(x) using Gaussian quadrature of order n + quadrature -- Integrate with given tolerance using Gaussian quadrature + romberg -- Integrate func using Romberg integration + newton_cotes -- Weights and error coefficient for Newton-Cotes integration + qmc_quad -- N-D integration using Quasi-Monte Carlo quadrature + IntegrationWarning -- Warning on issues during integration + AccuracyWarning -- Warning on issues during quadrature integration + +Integrating functions, given fixed samples +========================================== + +.. autosummary:: + :toctree: generated/ + + trapezoid -- Use trapezoidal rule to compute integral. + cumulative_trapezoid -- Use trapezoidal rule to cumulatively compute integral. + simpson -- Use Simpson's rule to compute integral from samples. + cumulative_simpson -- Use Simpson's rule to cumulatively compute integral from samples. + romb -- Use Romberg Integration to compute integral from + -- (2**k + 1) evenly-spaced samples. + +.. seealso:: + + :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian + quadrature roots and weights for other weighting factors and regions. + +Solving initial value problems for ODE systems +============================================== + +The solvers are implemented as individual classes, which can be used directly +(low-level usage) or through a convenience function. + +.. autosummary:: + :toctree: generated/ + + solve_ivp -- Convenient function for ODE integration. + RK23 -- Explicit Runge-Kutta solver of order 3(2). + RK45 -- Explicit Runge-Kutta solver of order 5(4). + DOP853 -- Explicit Runge-Kutta solver of order 8. + Radau -- Implicit Runge-Kutta solver of order 5. + BDF -- Implicit multi-step variable order (1 to 5) solver. + LSODA -- LSODA solver from ODEPACK Fortran package. + OdeSolver -- Base class for ODE solvers. + DenseOutput -- Local interpolant for computing a dense output. + OdeSolution -- Class which represents a continuous ODE solution. + + +Old API +------- + +These are the routines developed earlier for SciPy. They wrap older solvers +implemented in Fortran (mostly ODEPACK). While the interface to them is not +particularly convenient and certain features are missing compared to the new +API, the solvers themselves are of good quality and work fast as compiled +Fortran code. In some cases, it might be worth using this old API. + +.. autosummary:: + :toctree: generated/ + + odeint -- General integration of ordinary differential equations. + ode -- Integrate ODE using VODE and ZVODE routines. + complex_ode -- Convert a complex-valued ODE to real-valued and integrate. + ODEintWarning -- Warning raised during the execution of `odeint`. + + +Solving boundary value problems for ODE systems +=============================================== + +.. autosummary:: + :toctree: generated/ + + solve_bvp -- Solve a boundary value problem for a system of ODEs. +""" # noqa: E501 + + +from ._quadrature import * +from ._odepack_py import * +from ._quadpack_py import * +from ._ode import * +from ._bvp import solve_bvp +from ._ivp import (solve_ivp, OdeSolution, DenseOutput, + OdeSolver, RK23, RK45, DOP853, Radau, BDF, LSODA) +from ._quad_vec import quad_vec + +# Deprecated namespaces, to be removed in v2.0.0 +from . import dop, lsoda, vode, odepack, quadpack + +__all__ = [s for s in dir() if not s.startswith('_')] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_bvp.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_bvp.py new file mode 100644 index 0000000000000000000000000000000000000000..f988fdd6e0527d3adc4f4edfa955cc33d9eb85f8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_bvp.py @@ -0,0 +1,1155 @@ +"""Boundary value problem solver.""" +from warnings import warn + +import numpy as np +from numpy.linalg import pinv + +from scipy.sparse import coo_matrix, csc_matrix +from scipy.sparse.linalg import splu +from scipy.optimize import OptimizeResult + + +EPS = np.finfo(float).eps + + +def estimate_fun_jac(fun, x, y, p, f0=None): + """Estimate 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. + """ + n, m = y.shape + if f0 is None: + f0 = fun(x, y, p) + + dtype = y.dtype + + df_dy = np.empty((n, n, m), dtype=dtype) + h = EPS**0.5 * (1 + np.abs(y)) + for i in range(n): + y_new = y.copy() + y_new[i] += h[i] + hi = y_new[i] - y[i] + f_new = fun(x, y_new, p) + df_dy[:, i, :] = (f_new - f0) / hi + + k = p.shape[0] + if k == 0: + df_dp = None + else: + df_dp = np.empty((n, k, m), dtype=dtype) + h = EPS**0.5 * (1 + np.abs(p)) + for i in range(k): + p_new = p.copy() + p_new[i] += h[i] + hi = p_new[i] - p[i] + f_new = fun(x, y, p_new) + df_dp[:, i, :] = (f_new - f0) / hi + + return df_dy, df_dp + + +def estimate_bc_jac(bc, ya, yb, p, bc0=None): + """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. + """ + n = ya.shape[0] + k = p.shape[0] + + if bc0 is None: + bc0 = bc(ya, yb, p) + + dtype = ya.dtype + + dbc_dya = np.empty((n, n + k), dtype=dtype) + h = EPS**0.5 * (1 + np.abs(ya)) + for i in range(n): + ya_new = ya.copy() + ya_new[i] += h[i] + hi = ya_new[i] - ya[i] + bc_new = bc(ya_new, yb, p) + dbc_dya[i] = (bc_new - bc0) / hi + dbc_dya = dbc_dya.T + + h = EPS**0.5 * (1 + np.abs(yb)) + dbc_dyb = np.empty((n, n + k), dtype=dtype) + for i in range(n): + yb_new = yb.copy() + yb_new[i] += h[i] + hi = yb_new[i] - yb[i] + bc_new = bc(ya, yb_new, p) + dbc_dyb[i] = (bc_new - bc0) / hi + dbc_dyb = dbc_dyb.T + + if k == 0: + dbc_dp = None + else: + h = EPS**0.5 * (1 + np.abs(p)) + dbc_dp = np.empty((k, n + k), dtype=dtype) + for i in range(k): + p_new = p.copy() + p_new[i] += h[i] + hi = p_new[i] - p[i] + bc_new = bc(ya, yb, p_new) + dbc_dp[i] = (bc_new - bc0) / hi + dbc_dp = dbc_dp.T + + return dbc_dya, dbc_dyb, dbc_dp + + +def compute_jac_indices(n, m, k): + """Compute indices for the collocation system Jacobian construction. + + See `construct_global_jac` for the explanation. + """ + i_col = np.repeat(np.arange((m - 1) * n), n) + j_col = (np.tile(np.arange(n), n * (m - 1)) + + np.repeat(np.arange(m - 1) * n, n**2)) + + i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n) + j_bc = np.tile(np.arange(n), n + k) + + i_p_col = np.repeat(np.arange((m - 1) * n), k) + j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n) + + i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k) + j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k) + + i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc)) + j = np.hstack((j_col, j_col + n, + j_bc, j_bc + (m - 1) * n, + j_p_col, j_p_bc)) + + return i, j + + +def stacked_matmul(a, b): + """Stacked 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. + """ + if a.shape[1] > 50: + out = np.empty((a.shape[0], a.shape[1], b.shape[2])) + for i in range(a.shape[0]): + out[i] = np.dot(a[i], b[i]) + return out + else: + return np.einsum('...ij,...jk->...ik', a, b) + + +def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp, + df_dp_middle, dbc_dya, dbc_dyb, dbc_dp): + """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. + """ + df_dy = np.transpose(df_dy, (2, 0, 1)) + df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1)) + + h = h[:, np.newaxis, np.newaxis] + + dtype = df_dy.dtype + + # Computing diagonal n x n blocks. + dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype) + dPhi_dy_0[:] = -np.identity(n) + dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle) + T = stacked_matmul(df_dy_middle, df_dy[:-1]) + dPhi_dy_0 -= h**2 / 12 * T + + # Computing off-diagonal n x n blocks. + dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype) + dPhi_dy_1[:] = np.identity(n) + dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle) + T = stacked_matmul(df_dy_middle, df_dy[1:]) + dPhi_dy_1 += h**2 / 12 * T + + values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(), + dbc_dyb.ravel())) + + if k > 0: + df_dp = np.transpose(df_dp, (2, 0, 1)) + df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1)) + T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:]) + df_dp_middle += 0.125 * h * T + dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle) + values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel())) + + J = coo_matrix((values, (i_jac, j_jac))) + return csc_matrix(J) + + +def collocation_fun(fun, y, p, x, h): + """Evaluate collocation residuals. + + This function lies in the core of the method. The solution is sought + as a cubic C1 continuous spline with derivatives matching the ODE rhs + at given nodes `x`. Collocation conditions are formed from the equality + of the spline derivatives and rhs of the ODE system in the middle points + between nodes. + + Such method is classified to Lobbato IIIA family in ODE literature. + Refer to [1]_ for the formula and some discussion. + + Returns + ------- + col_res : ndarray, shape (n, m - 1) + Collocation residuals at the middle points of the mesh intervals. + y_middle : ndarray, shape (n, m - 1) + Values of the cubic spline evaluated at the middle points of the mesh + intervals. + f : ndarray, shape (n, m) + RHS of the ODE system evaluated at the mesh nodes. + f_middle : ndarray, shape (n, m - 1) + RHS of the ODE system evaluated at the middle points of the mesh + intervals (and using `y_middle`). + + 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. + """ + f = fun(x, y, p) + y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) - + 0.125 * h * (f[:, 1:] - f[:, :-1])) + f_middle = fun(x[:-1] + 0.5 * h, y_middle, p) + col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] + + 4 * f_middle) + + return col_res, y_middle, f, f_middle + + +def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h): + """Create the function and the Jacobian for the collocation system.""" + x_middle = x[:-1] + 0.5 * h + i_jac, j_jac = compute_jac_indices(n, m, k) + + def col_fun(y, p): + return collocation_fun(fun, y, p, x, h) + + def sys_jac(y, p, y_middle, f, f_middle, bc0): + if fun_jac is None: + df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f) + df_dy_middle, df_dp_middle = estimate_fun_jac( + fun, x_middle, y_middle, p, f_middle) + else: + df_dy, df_dp = fun_jac(x, y, p) + df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p) + + if bc_jac is None: + dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1], + p, bc0) + else: + dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p) + + return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, + df_dy_middle, df_dp, df_dp_middle, dbc_dya, + dbc_dyb, dbc_dp) + + return col_fun, sys_jac + + +def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol): + """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" + """ + # We know that the solution residuals at the middle points of the mesh + # are connected with collocation residuals r_middle = 1.5 * col_res / h. + # As our BVP solver tries to decrease relative residuals below a certain + # tolerance, it seems reasonable to terminated Newton iterations by + # comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold, + # which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite + # the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r + # should be computed as follows: + tol_r = 2/3 * h * 5e-2 * bvp_tol + + # Maximum allowed number of Jacobian evaluation and factorization, in + # other words, the maximum number of full Newton iterations. A small value + # is recommended in the literature. + max_njev = 4 + + # Maximum number of iterations, considering that some of them can be + # performed with the fixed Jacobian. In theory, such iterations are cheap, + # but it's not that simple in Python. + max_iter = 8 + + # Minimum relative improvement of the criterion function to accept the + # step (Armijo constant). + sigma = 0.2 + + # Step size decrease factor for backtracking. + tau = 0.5 + + # Maximum number of backtracking steps, the minimum step is then + # tau ** n_trial. + n_trial = 4 + + col_res, y_middle, f, f_middle = col_fun(y, p) + bc_res = bc(y[:, 0], y[:, -1], p) + res = np.hstack((col_res.ravel(order='F'), bc_res)) + + njev = 0 + singular = False + recompute_jac = True + for iteration in range(max_iter): + if recompute_jac: + J = jac(y, p, y_middle, f, f_middle, bc_res) + njev += 1 + try: + LU = splu(J) + except RuntimeError: + singular = True + break + + step = LU.solve(res) + cost = np.dot(step, step) + + y_step = step[:m * n].reshape((n, m), order='F') + p_step = step[m * n:] + + alpha = 1 + for trial in range(n_trial + 1): + y_new = y - alpha * y_step + if B is not None: + y_new[:, 0] = np.dot(B, y_new[:, 0]) + p_new = p - alpha * p_step + + col_res, y_middle, f, f_middle = col_fun(y_new, p_new) + bc_res = bc(y_new[:, 0], y_new[:, -1], p_new) + res = np.hstack((col_res.ravel(order='F'), bc_res)) + + step_new = LU.solve(res) + cost_new = np.dot(step_new, step_new) + if cost_new < (1 - 2 * alpha * sigma) * cost: + break + + if trial < n_trial: + alpha *= tau + + y = y_new + p = p_new + + if njev == max_njev: + break + + if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and + np.all(np.abs(bc_res) < bc_tol)): + break + + # If the full step was taken, then we are going to continue with + # the same Jacobian. This is the approach of BVP_SOLVER. + if alpha == 1: + step = step_new + cost = cost_new + recompute_jac = False + else: + recompute_jac = True + + return y, p, singular + + +def print_iteration_header(): + print("{:^15}{:^15}{:^15}{:^15}{:^15}".format( + "Iteration", "Max residual", "Max BC residual", "Total nodes", + "Nodes added")) + + +def print_iteration_progress(iteration, residual, bc_residual, total_nodes, + nodes_added): + print("{:^15}{:^15.2e}{:^15.2e}{:^15}{:^15}".format( + iteration, residual, bc_residual, total_nodes, nodes_added)) + + +class BVPResult(OptimizeResult): + pass + + +TERMINATION_MESSAGES = { + 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.", + 3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10." +} + + +def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle): + """Estimate 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. + """ + x_middle = x[:-1] + 0.5 * h + s = 0.5 * h * (3/7)**0.5 + x1 = x_middle + s + x2 = x_middle - s + y1 = sol(x1) + y2 = sol(x2) + y1_prime = sol(x1, 1) + y2_prime = sol(x2, 1) + f1 = fun(x1, y1, p) + f2 = fun(x2, y2, p) + r1 = y1_prime - f1 + r2 = y2_prime - f2 + + r_middle /= 1 + np.abs(f_middle) + r1 /= 1 + np.abs(f1) + r2 /= 1 + np.abs(f2) + + r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0) + r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0) + r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0) + + return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5 + + +def create_spline(y, yp, x, h): + """Create a cubic spline given values and derivatives. + + Formulas for the coefficients are taken from interpolate.CubicSpline. + + Returns + ------- + sol : PPoly + Constructed spline as a PPoly instance. + """ + from scipy.interpolate import PPoly + + n, m = y.shape + c = np.empty((4, n, m - 1), dtype=y.dtype) + slope = (y[:, 1:] - y[:, :-1]) / h + t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h + c[0] = t / h + c[1] = (slope - yp[:, :-1]) / h - t + c[2] = yp[:, :-1] + c[3] = y[:, :-1] + c = np.moveaxis(c, 1, 0) + + return PPoly(c, x, extrapolate=True, axis=1) + + +def modify_mesh(x, insert_1, insert_2): + """Insert nodes into a mesh. + + Nodes removal logic is not established, its impact on the solver is + presumably negligible. So, only insertion is done in this function. + + Parameters + ---------- + x : ndarray, shape (m,) + Mesh nodes. + insert_1 : ndarray + Intervals to each insert 1 new node in the middle. + insert_2 : ndarray + Intervals to each insert 2 new nodes, such that divide an interval + into 3 equal parts. + + Returns + ------- + x_new : ndarray + New mesh nodes. + + Notes + ----- + `insert_1` and `insert_2` should not have common values. + """ + # Because np.insert implementation apparently varies with a version of + # NumPy, we use a simple and reliable approach with sorting. + return np.sort(np.hstack(( + x, + 0.5 * (x[insert_1] + x[insert_1 + 1]), + (2 * x[insert_2] + x[insert_2 + 1]) / 3, + (x[insert_2] + 2 * x[insert_2 + 1]) / 3 + ))) + + +def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype): + """Wrap functions for unified usage in the solver.""" + if fun_jac is None: + fun_jac_wrapped = None + + if bc_jac is None: + bc_jac_wrapped = None + + if k == 0: + def fun_p(x, y, _): + return np.asarray(fun(x, y), dtype) + + def bc_wrapped(ya, yb, _): + return np.asarray(bc(ya, yb), dtype) + + if fun_jac is not None: + def fun_jac_p(x, y, _): + return np.asarray(fun_jac(x, y), dtype), None + + if bc_jac is not None: + def bc_jac_wrapped(ya, yb, _): + dbc_dya, dbc_dyb = bc_jac(ya, yb) + return (np.asarray(dbc_dya, dtype), + np.asarray(dbc_dyb, dtype), None) + else: + def fun_p(x, y, p): + return np.asarray(fun(x, y, p), dtype) + + def bc_wrapped(x, y, p): + return np.asarray(bc(x, y, p), dtype) + + if fun_jac is not None: + def fun_jac_p(x, y, p): + df_dy, df_dp = fun_jac(x, y, p) + return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype) + + if bc_jac is not None: + def bc_jac_wrapped(ya, yb, p): + dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p) + return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype), + np.asarray(dbc_dp, dtype)) + + if S is None: + fun_wrapped = fun_p + else: + def fun_wrapped(x, y, p): + f = fun_p(x, y, p) + if x[0] == a: + f[:, 0] = np.dot(D, f[:, 0]) + f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a) + else: + f += np.dot(S, y) / (x - a) + return f + + if fun_jac is not None: + if S is None: + fun_jac_wrapped = fun_jac_p + else: + Sr = S[:, :, np.newaxis] + + def fun_jac_wrapped(x, y, p): + df_dy, df_dp = fun_jac_p(x, y, p) + if x[0] == a: + df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0]) + df_dy[:, :, 1:] += Sr / (x[1:] - a) + else: + df_dy += Sr / (x - a) + + return df_dy, df_dp + + return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped + + +def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None, + tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None): + """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". + .. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of + Boundary Value Problems for Ordinary Differential Equations". + .. [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() + """ + x = np.asarray(x, dtype=float) + if x.ndim != 1: + raise ValueError("`x` must be 1 dimensional.") + h = np.diff(x) + if np.any(h <= 0): + raise ValueError("`x` must be strictly increasing.") + a = x[0] + + y = np.asarray(y) + if np.issubdtype(y.dtype, np.complexfloating): + dtype = complex + else: + dtype = float + y = y.astype(dtype, copy=False) + + if y.ndim != 2: + raise ValueError("`y` must be 2 dimensional.") + if y.shape[1] != x.shape[0]: + raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually " + f"has {y.shape[1]}.") + + if p is None: + p = np.array([]) + else: + p = np.asarray(p, dtype=dtype) + if p.ndim != 1: + raise ValueError("`p` must be 1 dimensional.") + + if tol < 100 * EPS: + warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2) + tol = 100 * EPS + + if verbose not in [0, 1, 2]: + raise ValueError("`verbose` must be in [0, 1, 2].") + + n = y.shape[0] + k = p.shape[0] + + if S is not None: + S = np.asarray(S, dtype=dtype) + if S.shape != (n, n): + raise ValueError(f"`S` is expected to have shape {(n, n)}, " + f"but actually has {S.shape}") + + # Compute I - S^+ S to impose necessary boundary conditions. + B = np.identity(n) - np.dot(pinv(S), S) + + y[:, 0] = np.dot(B, y[:, 0]) + + # Compute (I - S)^+ to correct derivatives at x=a. + D = pinv(np.identity(n) - S) + else: + B = None + D = None + + if bc_tol is None: + bc_tol = tol + + # Maximum number of iterations + max_iteration = 10 + + fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions( + fun, bc, fun_jac, bc_jac, k, a, S, D, dtype) + + f = fun_wrapped(x, y, p) + if f.shape != y.shape: + raise ValueError(f"`fun` return is expected to have shape {y.shape}, " + f"but actually has {f.shape}.") + + bc_res = bc_wrapped(y[:, 0], y[:, -1], p) + if bc_res.shape != (n + k,): + raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, " + f"but actually has {bc_res.shape}.") + + status = 0 + iteration = 0 + if verbose == 2: + print_iteration_header() + + while True: + m = x.shape[0] + + col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped, + fun_jac_wrapped, bc_jac_wrapped, x, h) + y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys, + y, p, B, tol, bc_tol) + iteration += 1 + + col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y, + p, x, h) + bc_res = bc_wrapped(y[:, 0], y[:, -1], p) + max_bc_res = np.max(abs(bc_res)) + + # This relation is not trivial, but can be verified. + r_middle = 1.5 * col_res / h + sol = create_spline(y, f, x, h) + rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p, + r_middle, f_middle) + max_rms_res = np.max(rms_res) + + if singular: + status = 2 + break + + insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol)) + insert_2, = np.nonzero(rms_res >= 100 * tol) + nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0] + + if m + nodes_added > max_nodes: + status = 1 + if verbose == 2: + nodes_added = f"({nodes_added})" + print_iteration_progress(iteration, max_rms_res, max_bc_res, + m, nodes_added) + break + + if verbose == 2: + print_iteration_progress(iteration, max_rms_res, max_bc_res, m, + nodes_added) + + if nodes_added > 0: + x = modify_mesh(x, insert_1, insert_2) + h = np.diff(x) + y = sol(x) + elif max_bc_res <= bc_tol: + status = 0 + break + elif iteration >= max_iteration: + status = 3 + break + + if verbose > 0: + if status == 0: + print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n" + f"Maximum relative residual: {max_rms_res:.2e} \n" + f"Maximum boundary residual: {max_bc_res:.2e}") + elif status == 1: + print(f"Number of nodes is exceeded after iteration {iteration}. \n" + f"Maximum relative residual: {max_rms_res:.2e} \n" + f"Maximum boundary residual: {max_bc_res:.2e}") + elif status == 2: + print("Singular Jacobian encountered when solving the collocation " + f"system on iteration {iteration}. \n" + f"Maximum relative residual: {max_rms_res:.2e} \n" + f"Maximum boundary residual: {max_bc_res:.2e}") + elif status == 3: + print("The solver was unable to satisfy boundary conditions " + f"tolerance on iteration {iteration}. \n" + f"Maximum relative residual: {max_rms_res:.2e} \n" + f"Maximum boundary residual: {max_bc_res:.2e}") + + if p.size == 0: + p = None + + return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res, + niter=iteration, status=status, + message=TERMINATION_MESSAGES[status], success=status == 0) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..63dd7dda2db1359067285d9f64c8896a30127569 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c8aaa36588651ae5e48b58fbb1d443bc71fc77 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py @@ -0,0 +1,8 @@ +"""Suite of ODE solvers implemented in Python.""" +from .ivp import solve_ivp +from .rk import RK23, RK45, DOP853 +from .radau import Radau +from .bdf import BDF +from .lsoda import LSODA +from .common import OdeSolution +from .base import DenseOutput, OdeSolver diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py new file mode 100644 index 0000000000000000000000000000000000000000..46db9a69dfb3e7aee5c150ac6795234cd455dfe5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py @@ -0,0 +1,290 @@ +import numpy as np + + +def check_arguments(fun, y0, support_complex): + """Helper function for checking arguments common to all solvers.""" + y0 = np.asarray(y0) + if np.issubdtype(y0.dtype, np.complexfloating): + if not support_complex: + raise ValueError("`y0` is complex, but the chosen solver does " + "not support integration in a complex domain.") + dtype = complex + else: + dtype = float + y0 = y0.astype(dtype, copy=False) + + if y0.ndim != 1: + raise ValueError("`y0` must be 1-dimensional.") + + if not np.isfinite(y0).all(): + raise ValueError("All components of the initial state `y0` must be finite.") + + def fun_wrapped(t, y): + return np.asarray(fun(t, y), dtype=dtype) + + return fun_wrapped, y0 + + +class OdeSolver: + """Base class for ODE solvers. + + In order to implement a new solver you need to follow the guidelines: + + 1. A constructor must accept parameters presented in the base class + (listed below) along with any other parameters specific to a solver. + 2. A constructor must accept arbitrary extraneous arguments + ``**extraneous``, but warn that these arguments are irrelevant + using `common.warn_extraneous` function. Do not pass these + arguments to the base class. + 3. A solver must implement a private method `_step_impl(self)` which + propagates a solver one step further. It must return tuple + ``(success, message)``, where ``success`` is a boolean indicating + whether a step was successful, and ``message`` is a string + containing description of a failure if a step failed or None + otherwise. + 4. A solver must implement a private method `_dense_output_impl(self)`, + which returns a `DenseOutput` object covering the last successful + step. + 5. A solver must have attributes listed below in Attributes section. + Note that ``t_old`` and ``step_size`` are updated automatically. + 6. Use `fun(self, t, y)` method for the system rhs evaluation, this + way the number of function evaluations (`nfev`) will be tracked + automatically. + 7. For convenience, a base class provides `fun_single(self, t, y)` and + `fun_vectorized(self, t, y)` for evaluating the rhs in + non-vectorized and vectorized fashions respectively (regardless of + how `fun` from the constructor is implemented). These calls don't + increment `nfev`. + 8. If a solver uses a Jacobian matrix and LU decompositions, it should + track the number of Jacobian evaluations (`njev`) and the number of + LU decompositions (`nlu`). + 9. By convention, the function evaluations used to compute a finite + difference approximation of the Jacobian should not be counted in + `nfev`, thus use `fun_single(self, t, y)` or + `fun_vectorized(self, t, y)` when computing a finite difference + approximation of the Jacobian. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time --- the integration won't continue beyond it. It also + determines the direction of the integration. + vectorized : bool + Whether `fun` can be called in a vectorized fashion. Default is False. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by methods 'Radau' and 'BDF', but + will result in slower execution for other methods. It can also + result in slower overall execution for 'Radau' and 'BDF' in some + circumstances (e.g. small ``len(y0)``). + support_complex : bool, optional + Whether integration in a complex domain should be supported. + Generally determined by a derived solver class capabilities. + Default is False. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number of the system's rhs evaluations. + njev : int + Number of the Jacobian evaluations. + nlu : int + Number of LU decompositions. + """ + TOO_SMALL_STEP = "Required step size is less than spacing between numbers." + + def __init__(self, fun, t0, y0, t_bound, vectorized, + support_complex=False): + self.t_old = None + self.t = t0 + self._fun, self.y = check_arguments(fun, y0, support_complex) + self.t_bound = t_bound + self.vectorized = vectorized + + if vectorized: + def fun_single(t, y): + return self._fun(t, y[:, None]).ravel() + fun_vectorized = self._fun + else: + fun_single = self._fun + + def fun_vectorized(t, y): + f = np.empty_like(y) + for i, yi in enumerate(y.T): + f[:, i] = self._fun(t, yi) + return f + + def fun(t, y): + self.nfev += 1 + return self.fun_single(t, y) + + self.fun = fun + self.fun_single = fun_single + self.fun_vectorized = fun_vectorized + + self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1 + self.n = self.y.size + self.status = 'running' + + self.nfev = 0 + self.njev = 0 + self.nlu = 0 + + @property + def step_size(self): + if self.t_old is None: + return None + else: + return np.abs(self.t - self.t_old) + + def step(self): + """Perform one integration step. + + Returns + ------- + message : string or None + Report from the solver. Typically a reason for a failure if + `self.status` is 'failed' after the step was taken or None + otherwise. + """ + if self.status != 'running': + raise RuntimeError("Attempt to step on a failed or finished " + "solver.") + + if self.n == 0 or self.t == self.t_bound: + # Handle corner cases of empty solver or no integration. + self.t_old = self.t + self.t = self.t_bound + message = None + self.status = 'finished' + else: + t = self.t + success, message = self._step_impl() + + if not success: + self.status = 'failed' + else: + self.t_old = t + if self.direction * (self.t - self.t_bound) >= 0: + self.status = 'finished' + + return message + + def dense_output(self): + """Compute a local interpolant over the last successful step. + + Returns + ------- + sol : `DenseOutput` + Local interpolant over the last successful step. + """ + if self.t_old is None: + raise RuntimeError("Dense output is available after a successful " + "step was made.") + + if self.n == 0 or self.t == self.t_old: + # Handle corner cases of empty solver and no integration. + return ConstantDenseOutput(self.t_old, self.t, self.y) + else: + return self._dense_output_impl() + + def _step_impl(self): + raise NotImplementedError + + def _dense_output_impl(self): + raise NotImplementedError + + +class DenseOutput: + """Base class for local interpolant over step made by an ODE solver. + + It interpolates between `t_min` and `t_max` (see Attributes below). + Evaluation outside this interval is not forbidden, but the accuracy is not + guaranteed. + + Attributes + ---------- + t_min, t_max : float + Time range of the interpolation. + """ + def __init__(self, t_old, t): + self.t_old = t_old + self.t = t + self.t_min = min(t, t_old) + self.t_max = max(t, t_old) + + def __call__(self, t): + """Evaluate the interpolant. + + Parameters + ---------- + t : float or array_like with shape (n_points,) + Points to evaluate the solution at. + + Returns + ------- + y : ndarray, shape (n,) or (n, n_points) + Computed values. Shape depends on whether `t` was a scalar or a + 1-D array. + """ + t = np.asarray(t) + if t.ndim > 1: + raise ValueError("`t` must be a float or a 1-D array.") + return self._call_impl(t) + + def _call_impl(self, t): + raise NotImplementedError + + +class ConstantDenseOutput(DenseOutput): + """Constant value interpolator. + + This class used for degenerate integration cases: equal integration limits + or a system with 0 equations. + """ + def __init__(self, t_old, t, value): + super().__init__(t_old, t) + self.value = value + + def _call_impl(self, t): + if t.ndim == 0: + return self.value + else: + ret = np.empty((self.value.shape[0], t.shape[0])) + ret[:] = self.value[:, None] + return ret diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py new file mode 100644 index 0000000000000000000000000000000000000000..5b78060cc3a2cef61fd491e0163d1c13f9997dbe --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py @@ -0,0 +1,479 @@ +import numpy as np +from scipy.linalg import lu_factor, lu_solve +from scipy.sparse import issparse, csc_matrix, eye +from scipy.sparse.linalg import splu +from scipy.optimize._numdiff import group_columns +from .common import (validate_max_step, validate_tol, select_initial_step, + norm, EPS, num_jac, validate_first_step, + warn_extraneous) +from .base import OdeSolver, DenseOutput + + +MAX_ORDER = 5 +NEWTON_MAXITER = 4 +MIN_FACTOR = 0.2 +MAX_FACTOR = 10 + + +def compute_R(order, factor): + """Compute the matrix for changing the differences array.""" + I = np.arange(1, order + 1)[:, None] + J = np.arange(1, order + 1) + M = np.zeros((order + 1, order + 1)) + M[1:, 1:] = (I - 1 - factor * J) / I + M[0] = 1 + return np.cumprod(M, axis=0) + + +def change_D(D, order, factor): + """Change differences array in-place when step size is changed.""" + R = compute_R(order, factor) + U = compute_R(order, 1) + RU = R.dot(U) + D[:order + 1] = np.dot(RU.T, D[:order + 1]) + + +def solve_bdf_system(fun, t_new, y_predict, c, psi, LU, solve_lu, scale, tol): + """Solve the algebraic system resulting from BDF method.""" + d = 0 + y = y_predict.copy() + dy_norm_old = None + converged = False + for k in range(NEWTON_MAXITER): + f = fun(t_new, y) + if not np.all(np.isfinite(f)): + break + + dy = solve_lu(LU, c * f - psi - d) + dy_norm = norm(dy / scale) + + if dy_norm_old is None: + rate = None + else: + rate = dy_norm / dy_norm_old + + if (rate is not None and (rate >= 1 or + rate ** (NEWTON_MAXITER - k) / (1 - rate) * dy_norm > tol)): + break + + y += dy + d += dy + + if (dy_norm == 0 or + rate is not None and rate / (1 - rate) * dy_norm < tol): + converged = True + break + + dy_norm_old = dy_norm + + return converged, k + 1, y, d + + +class BDF(OdeSolver): + """Implicit method based on backward-differentiation formulas. + + This is a variable order method with the order varying automatically from + 1 to 5. The general framework of the BDF algorithm is described in [1]_. + This class implements a quasi-constant step size as explained in [2]_. + The error estimation strategy for the constant-step BDF is derived in [3]_. + An accuracy enhancement using modified formulas (NDF) [2]_ is also implemented. + + Can be applied in the complex domain. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + jac : {None, array_like, sparse_matrix, callable}, optional + Jacobian matrix of the right-hand side of the system with respect to y, + required by this method. The Jacobian matrix has shape (n, n) and its + element (i, j) is equal to ``d f_i / d y_j``. + There are three ways to define the Jacobian: + + * If array_like or sparse_matrix, the Jacobian is assumed to + be constant. + * If callable, the Jacobian is assumed to depend on both + t and y; it will be called as ``jac(t, y)`` as necessary. + For the 'Radau' and 'BDF' methods, the return value might be a + sparse matrix. + * If None (default), the Jacobian will be approximated by + finite differences. + + It is generally recommended to provide the Jacobian rather than + relying on a finite-difference approximation. + jac_sparsity : {None, array_like, sparse matrix}, optional + Defines a sparsity structure of the Jacobian matrix for a + finite-difference approximation. Its shape must be (n, n). This argument + is ignored if `jac` is not `None`. If the Jacobian has only few non-zero + elements in *each* row, providing the sparsity structure will greatly + speed up the computations [4]_. A zero entry means that a corresponding + element in the Jacobian is always zero. If None (default), the Jacobian + is assumed to be dense. + vectorized : bool, optional + Whether `fun` can be called in a vectorized fashion. Default is False. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by this method, but may result in slower + execution overall in some circumstances (e.g. small ``len(y0)``). + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number of evaluations of the right-hand side. + njev : int + Number of evaluations of the Jacobian. + nlu : int + Number of LU decompositions. + + References + ---------- + .. [1] G. D. Byrne, A. C. Hindmarsh, "A Polyalgorithm for the Numerical + Solution of Ordinary Differential Equations", ACM Transactions on + Mathematical Software, Vol. 1, No. 1, pp. 71-96, March 1975. + .. [2] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI. + COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997. + .. [3] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations I: + Nonstiff Problems", Sec. III.2. + .. [4] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of Mathematics + and its Applications, 13, pp. 117-120, 1974. + """ + def __init__(self, fun, t0, y0, t_bound, max_step=np.inf, + rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None, + vectorized=False, first_step=None, **extraneous): + warn_extraneous(extraneous) + super().__init__(fun, t0, y0, t_bound, vectorized, + support_complex=True) + self.max_step = validate_max_step(max_step) + self.rtol, self.atol = validate_tol(rtol, atol, self.n) + f = self.fun(self.t, self.y) + if first_step is None: + self.h_abs = select_initial_step(self.fun, self.t, self.y, f, + self.direction, 1, + self.rtol, self.atol) + else: + self.h_abs = validate_first_step(first_step, t0, t_bound) + self.h_abs_old = None + self.error_norm_old = None + + self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5)) + + self.jac_factor = None + self.jac, self.J = self._validate_jac(jac, jac_sparsity) + if issparse(self.J): + def lu(A): + self.nlu += 1 + return splu(A) + + def solve_lu(LU, b): + return LU.solve(b) + + I = eye(self.n, format='csc', dtype=self.y.dtype) + else: + def lu(A): + self.nlu += 1 + return lu_factor(A, overwrite_a=True) + + def solve_lu(LU, b): + return lu_solve(LU, b, overwrite_b=True) + + I = np.identity(self.n, dtype=self.y.dtype) + + self.lu = lu + self.solve_lu = solve_lu + self.I = I + + kappa = np.array([0, -0.1850, -1/9, -0.0823, -0.0415, 0]) + self.gamma = np.hstack((0, np.cumsum(1 / np.arange(1, MAX_ORDER + 1)))) + self.alpha = (1 - kappa) * self.gamma + self.error_const = kappa * self.gamma + 1 / np.arange(1, MAX_ORDER + 2) + + D = np.empty((MAX_ORDER + 3, self.n), dtype=self.y.dtype) + D[0] = self.y + D[1] = f * self.h_abs * self.direction + self.D = D + + self.order = 1 + self.n_equal_steps = 0 + self.LU = None + + def _validate_jac(self, jac, sparsity): + t0 = self.t + y0 = self.y + + if jac is None: + if sparsity is not None: + if issparse(sparsity): + sparsity = csc_matrix(sparsity) + groups = group_columns(sparsity) + sparsity = (sparsity, groups) + + def jac_wrapped(t, y): + self.njev += 1 + f = self.fun_single(t, y) + J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f, + self.atol, self.jac_factor, + sparsity) + return J + J = jac_wrapped(t0, y0) + elif callable(jac): + J = jac(t0, y0) + self.njev += 1 + if issparse(J): + J = csc_matrix(J, dtype=y0.dtype) + + def jac_wrapped(t, y): + self.njev += 1 + return csc_matrix(jac(t, y), dtype=y0.dtype) + else: + J = np.asarray(J, dtype=y0.dtype) + + def jac_wrapped(t, y): + self.njev += 1 + return np.asarray(jac(t, y), dtype=y0.dtype) + + if J.shape != (self.n, self.n): + raise ValueError("`jac` is expected to have shape {}, but " + "actually has {}." + .format((self.n, self.n), J.shape)) + else: + if issparse(jac): + J = csc_matrix(jac, dtype=y0.dtype) + else: + J = np.asarray(jac, dtype=y0.dtype) + + if J.shape != (self.n, self.n): + raise ValueError("`jac` is expected to have shape {}, but " + "actually has {}." + .format((self.n, self.n), J.shape)) + jac_wrapped = None + + return jac_wrapped, J + + def _step_impl(self): + t = self.t + D = self.D + + max_step = self.max_step + min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t) + if self.h_abs > max_step: + h_abs = max_step + change_D(D, self.order, max_step / self.h_abs) + self.n_equal_steps = 0 + elif self.h_abs < min_step: + h_abs = min_step + change_D(D, self.order, min_step / self.h_abs) + self.n_equal_steps = 0 + else: + h_abs = self.h_abs + + atol = self.atol + rtol = self.rtol + order = self.order + + alpha = self.alpha + gamma = self.gamma + error_const = self.error_const + + J = self.J + LU = self.LU + current_jac = self.jac is None + + step_accepted = False + while not step_accepted: + if h_abs < min_step: + return False, self.TOO_SMALL_STEP + + h = h_abs * self.direction + t_new = t + h + + if self.direction * (t_new - self.t_bound) > 0: + t_new = self.t_bound + change_D(D, order, np.abs(t_new - t) / h_abs) + self.n_equal_steps = 0 + LU = None + + h = t_new - t + h_abs = np.abs(h) + + y_predict = np.sum(D[:order + 1], axis=0) + + scale = atol + rtol * np.abs(y_predict) + psi = np.dot(D[1: order + 1].T, gamma[1: order + 1]) / alpha[order] + + converged = False + c = h / alpha[order] + while not converged: + if LU is None: + LU = self.lu(self.I - c * J) + + converged, n_iter, y_new, d = solve_bdf_system( + self.fun, t_new, y_predict, c, psi, LU, self.solve_lu, + scale, self.newton_tol) + + if not converged: + if current_jac: + break + J = self.jac(t_new, y_predict) + LU = None + current_jac = True + + if not converged: + factor = 0.5 + h_abs *= factor + change_D(D, order, factor) + self.n_equal_steps = 0 + LU = None + continue + + safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER + + n_iter) + + scale = atol + rtol * np.abs(y_new) + error = error_const[order] * d + error_norm = norm(error / scale) + + if error_norm > 1: + factor = max(MIN_FACTOR, + safety * error_norm ** (-1 / (order + 1))) + h_abs *= factor + change_D(D, order, factor) + self.n_equal_steps = 0 + # As we didn't have problems with convergence, we don't + # reset LU here. + else: + step_accepted = True + + self.n_equal_steps += 1 + + self.t = t_new + self.y = y_new + + self.h_abs = h_abs + self.J = J + self.LU = LU + + # Update differences. The principal relation here is + # D^{j + 1} y_n = D^{j} y_n - D^{j} y_{n - 1}. Keep in mind that D + # contained difference for previous interpolating polynomial and + # d = D^{k + 1} y_n. Thus this elegant code follows. + D[order + 2] = d - D[order + 1] + D[order + 1] = d + for i in reversed(range(order + 1)): + D[i] += D[i + 1] + + if self.n_equal_steps < order + 1: + return True, None + + if order > 1: + error_m = error_const[order - 1] * D[order] + error_m_norm = norm(error_m / scale) + else: + error_m_norm = np.inf + + if order < MAX_ORDER: + error_p = error_const[order + 1] * D[order + 2] + error_p_norm = norm(error_p / scale) + else: + error_p_norm = np.inf + + error_norms = np.array([error_m_norm, error_norm, error_p_norm]) + with np.errstate(divide='ignore'): + factors = error_norms ** (-1 / np.arange(order, order + 3)) + + delta_order = np.argmax(factors) - 1 + order += delta_order + self.order = order + + factor = min(MAX_FACTOR, safety * np.max(factors)) + self.h_abs *= factor + change_D(D, order, factor) + self.n_equal_steps = 0 + self.LU = None + + return True, None + + def _dense_output_impl(self): + return BdfDenseOutput(self.t_old, self.t, self.h_abs * self.direction, + self.order, self.D[:self.order + 1].copy()) + + +class BdfDenseOutput(DenseOutput): + def __init__(self, t_old, t, h, order, D): + super().__init__(t_old, t) + self.order = order + self.t_shift = self.t - h * np.arange(self.order) + self.denom = h * (1 + np.arange(self.order)) + self.D = D + + def _call_impl(self, t): + if t.ndim == 0: + x = (t - self.t_shift) / self.denom + p = np.cumprod(x) + else: + x = (t - self.t_shift[:, None]) / self.denom[:, None] + p = np.cumprod(x, axis=0) + + y = np.dot(self.D[1:].T, p) + if y.ndim == 1: + y += self.D[0] + else: + y += self.D[0, :, None] + + return y diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py new file mode 100644 index 0000000000000000000000000000000000000000..eccf91f9d5efb15c440f1162164ab327af2f0f95 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py @@ -0,0 +1,440 @@ +from itertools import groupby +from warnings import warn +import numpy as np +from scipy.sparse import find, coo_matrix + + +EPS = np.finfo(float).eps + + +def validate_first_step(first_step, t0, t_bound): + """Assert that first_step is valid and return it.""" + if first_step <= 0: + raise ValueError("`first_step` must be positive.") + if first_step > np.abs(t_bound - t0): + raise ValueError("`first_step` exceeds bounds.") + return first_step + + +def validate_max_step(max_step): + """Assert that max_Step is valid and return it.""" + if max_step <= 0: + raise ValueError("`max_step` must be positive.") + return max_step + + +def warn_extraneous(extraneous): + """Display a warning for extraneous keyword arguments. + + The initializer of each solver class is expected to collect keyword + arguments that it doesn't understand and warn about them. This function + prints a warning for each key in the supplied dictionary. + + Parameters + ---------- + extraneous : dict + Extraneous keyword arguments + """ + if extraneous: + warn("The following arguments have no effect for a chosen solver: {}." + .format(", ".join(f"`{x}`" for x in extraneous)), + stacklevel=3) + + +def validate_tol(rtol, atol, n): + """Validate tolerance values.""" + + if np.any(rtol < 100 * EPS): + warn("At least one element of `rtol` is too small. " + f"Setting `rtol = np.maximum(rtol, {100 * EPS})`.", + stacklevel=3) + rtol = np.maximum(rtol, 100 * EPS) + + atol = np.asarray(atol) + if atol.ndim > 0 and atol.shape != (n,): + raise ValueError("`atol` has wrong shape.") + + if np.any(atol < 0): + raise ValueError("`atol` must be positive.") + + return rtol, atol + + +def norm(x): + """Compute RMS norm.""" + return np.linalg.norm(x) / x.size ** 0.5 + + +def select_initial_step(fun, t0, y0, f0, direction, order, rtol, atol): + """Empirically select a good initial step. + + The algorithm is described in [1]_. + + Parameters + ---------- + fun : callable + Right-hand side of the system. + t0 : float + Initial value of the independent variable. + y0 : ndarray, shape (n,) + Initial value of the dependent variable. + f0 : ndarray, shape (n,) + Initial value of the derivative, i.e., ``fun(t0, y0)``. + direction : float + Integration direction. + order : float + Error estimator order. It means that the error controlled by the + algorithm is proportional to ``step_size ** (order + 1)`. + rtol : float + Desired relative tolerance. + atol : float + Desired absolute tolerance. + + Returns + ------- + h_abs : float + Absolute value of the suggested initial step. + + References + ---------- + .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations I: Nonstiff Problems", Sec. II.4. + """ + if y0.size == 0: + return np.inf + + scale = atol + np.abs(y0) * rtol + d0 = norm(y0 / scale) + d1 = norm(f0 / scale) + if d0 < 1e-5 or d1 < 1e-5: + h0 = 1e-6 + else: + h0 = 0.01 * d0 / d1 + + y1 = y0 + h0 * direction * f0 + f1 = fun(t0 + h0 * direction, y1) + d2 = norm((f1 - f0) / scale) / h0 + + if d1 <= 1e-15 and d2 <= 1e-15: + h1 = max(1e-6, h0 * 1e-3) + else: + h1 = (0.01 / max(d1, d2)) ** (1 / (order + 1)) + + return min(100 * h0, h1) + + +class OdeSolution: + """Continuous ODE solution. + + It is organized as a collection of `DenseOutput` objects which represent + local interpolants. It provides an algorithm to select a right interpolant + for each given point. + + The interpolants cover the range between `t_min` and `t_max` (see + Attributes below). Evaluation outside this interval is not forbidden, but + the accuracy is not guaranteed. + + When evaluating at a breakpoint (one of the values in `ts`) a segment with + the lower index is selected. + + Parameters + ---------- + ts : array_like, shape (n_segments + 1,) + Time instants between which local interpolants are defined. Must + be strictly increasing or decreasing (zero segment with two points is + also allowed). + interpolants : list of DenseOutput with n_segments elements + Local interpolants. An i-th interpolant is assumed to be defined + between ``ts[i]`` and ``ts[i + 1]``. + alt_segment : boolean + Requests the alternative interpolant segment selection scheme. At each + solver integration point, two interpolant segments are available. The + default (False) and alternative (True) behaviours select the segment + for which the requested time corresponded to ``t`` and ``t_old``, + respectively. This functionality is only relevant for testing the + interpolants' accuracy: different integrators use different + construction strategies. + + Attributes + ---------- + t_min, t_max : float + Time range of the interpolation. + """ + def __init__(self, ts, interpolants, alt_segment=False): + ts = np.asarray(ts) + d = np.diff(ts) + # The first case covers integration on zero segment. + if not ((ts.size == 2 and ts[0] == ts[-1]) + or np.all(d > 0) or np.all(d < 0)): + raise ValueError("`ts` must be strictly increasing or decreasing.") + + self.n_segments = len(interpolants) + if ts.shape != (self.n_segments + 1,): + raise ValueError("Numbers of time stamps and interpolants " + "don't match.") + + self.ts = ts + self.interpolants = interpolants + if ts[-1] >= ts[0]: + self.t_min = ts[0] + self.t_max = ts[-1] + self.ascending = True + self.side = "right" if alt_segment else "left" + self.ts_sorted = ts + else: + self.t_min = ts[-1] + self.t_max = ts[0] + self.ascending = False + self.side = "left" if alt_segment else "right" + self.ts_sorted = ts[::-1] + + def _call_single(self, t): + # Here we preserve a certain symmetry that when t is in self.ts, + # if alt_segment=False, then we prioritize a segment with a lower + # index. + ind = np.searchsorted(self.ts_sorted, t, side=self.side) + + segment = min(max(ind - 1, 0), self.n_segments - 1) + if not self.ascending: + segment = self.n_segments - 1 - segment + + return self.interpolants[segment](t) + + def __call__(self, t): + """Evaluate the solution. + + Parameters + ---------- + t : float or array_like with shape (n_points,) + Points to evaluate at. + + Returns + ------- + y : ndarray, shape (n_states,) or (n_states, n_points) + Computed values. Shape depends on whether `t` is a scalar or a + 1-D array. + """ + t = np.asarray(t) + + if t.ndim == 0: + return self._call_single(t) + + order = np.argsort(t) + reverse = np.empty_like(order) + reverse[order] = np.arange(order.shape[0]) + t_sorted = t[order] + + # See comment in self._call_single. + segments = np.searchsorted(self.ts_sorted, t_sorted, side=self.side) + segments -= 1 + segments[segments < 0] = 0 + segments[segments > self.n_segments - 1] = self.n_segments - 1 + if not self.ascending: + segments = self.n_segments - 1 - segments + + ys = [] + group_start = 0 + for segment, group in groupby(segments): + group_end = group_start + len(list(group)) + y = self.interpolants[segment](t_sorted[group_start:group_end]) + ys.append(y) + group_start = group_end + + ys = np.hstack(ys) + ys = ys[:, reverse] + + return ys + + +NUM_JAC_DIFF_REJECT = EPS ** 0.875 +NUM_JAC_DIFF_SMALL = EPS ** 0.75 +NUM_JAC_DIFF_BIG = EPS ** 0.25 +NUM_JAC_MIN_FACTOR = 1e3 * EPS +NUM_JAC_FACTOR_INCREASE = 10 +NUM_JAC_FACTOR_DECREASE = 0.1 + + +def num_jac(fun, t, y, f, threshold, factor, sparsity=None): + """Finite differences Jacobian approximation tailored for ODE solvers. + + This function computes finite difference approximation to the Jacobian + matrix of `fun` with respect to `y` using forward differences. + The Jacobian matrix has shape (n, n) and its element (i, j) is equal to + ``d f_i / d y_j``. + + A special feature of this function is the ability to correct the step + size from iteration to iteration. The main idea is to keep the finite + difference significantly separated from its round-off error which + approximately equals ``EPS * np.abs(f)``. It reduces a possibility of a + huge error and assures that the estimated derivative are reasonably close + to the true values (i.e., the finite difference approximation is at least + qualitatively reflects the structure of the true Jacobian). + + Parameters + ---------- + fun : callable + Right-hand side of the system implemented in a vectorized fashion. + t : float + Current time. + y : ndarray, shape (n,) + Current state. + f : ndarray, shape (n,) + Value of the right hand side at (t, y). + threshold : float + Threshold for `y` value used for computing the step size as + ``factor * np.maximum(np.abs(y), threshold)``. Typically, the value of + absolute tolerance (atol) for a solver should be passed as `threshold`. + factor : ndarray with shape (n,) or None + Factor to use for computing the step size. Pass None for the very + evaluation, then use the value returned from this function. + sparsity : tuple (structure, groups) or None + Sparsity structure of the Jacobian, `structure` must be csc_matrix. + + Returns + ------- + J : ndarray or csc_matrix, shape (n, n) + Jacobian matrix. + factor : ndarray, shape (n,) + Suggested `factor` for the next evaluation. + """ + y = np.asarray(y) + n = y.shape[0] + if n == 0: + return np.empty((0, 0)), factor + + if factor is None: + factor = np.full(n, EPS ** 0.5) + else: + factor = factor.copy() + + # Direct the step as ODE dictates, hoping that such a step won't lead to + # a problematic region. For complex ODEs it makes sense to use the real + # part of f as we use steps along real axis. + f_sign = 2 * (np.real(f) >= 0).astype(float) - 1 + y_scale = f_sign * np.maximum(threshold, np.abs(y)) + h = (y + factor * y_scale) - y + + # Make sure that the step is not 0 to start with. Not likely it will be + # executed often. + for i in np.nonzero(h == 0)[0]: + while h[i] == 0: + factor[i] *= 10 + h[i] = (y[i] + factor[i] * y_scale[i]) - y[i] + + if sparsity is None: + return _dense_num_jac(fun, t, y, f, h, factor, y_scale) + else: + structure, groups = sparsity + return _sparse_num_jac(fun, t, y, f, h, factor, y_scale, + structure, groups) + + +def _dense_num_jac(fun, t, y, f, h, factor, y_scale): + n = y.shape[0] + h_vecs = np.diag(h) + f_new = fun(t, y[:, None] + h_vecs) + diff = f_new - f[:, None] + max_ind = np.argmax(np.abs(diff), axis=0) + r = np.arange(n) + max_diff = np.abs(diff[max_ind, r]) + scale = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r])) + + diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale + if np.any(diff_too_small): + ind, = np.nonzero(diff_too_small) + new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind] + h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind] + h_vecs[ind, ind] = h_new + f_new = fun(t, y[:, None] + h_vecs[:, ind]) + diff_new = f_new - f[:, None] + max_ind = np.argmax(np.abs(diff_new), axis=0) + r = np.arange(ind.shape[0]) + max_diff_new = np.abs(diff_new[max_ind, r]) + scale_new = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r])) + + update = max_diff[ind] * scale_new < max_diff_new * scale[ind] + if np.any(update): + update, = np.nonzero(update) + update_ind = ind[update] + factor[update_ind] = new_factor[update] + h[update_ind] = h_new[update] + diff[:, update_ind] = diff_new[:, update] + scale[update_ind] = scale_new[update] + max_diff[update_ind] = max_diff_new[update] + + diff /= h + + factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE + factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE + factor = np.maximum(factor, NUM_JAC_MIN_FACTOR) + + return diff, factor + + +def _sparse_num_jac(fun, t, y, f, h, factor, y_scale, structure, groups): + n = y.shape[0] + n_groups = np.max(groups) + 1 + h_vecs = np.empty((n_groups, n)) + for group in range(n_groups): + e = np.equal(group, groups) + h_vecs[group] = h * e + h_vecs = h_vecs.T + + f_new = fun(t, y[:, None] + h_vecs) + df = f_new - f[:, None] + + i, j, _ = find(structure) + diff = coo_matrix((df[i, groups[j]], (i, j)), shape=(n, n)).tocsc() + max_ind = np.array(abs(diff).argmax(axis=0)).ravel() + r = np.arange(n) + max_diff = np.asarray(np.abs(diff[max_ind, r])).ravel() + scale = np.maximum(np.abs(f[max_ind]), + np.abs(f_new[max_ind, groups[r]])) + + diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale + if np.any(diff_too_small): + ind, = np.nonzero(diff_too_small) + new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind] + h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind] + h_new_all = np.zeros(n) + h_new_all[ind] = h_new + + groups_unique = np.unique(groups[ind]) + groups_map = np.empty(n_groups, dtype=int) + h_vecs = np.empty((groups_unique.shape[0], n)) + for k, group in enumerate(groups_unique): + e = np.equal(group, groups) + h_vecs[k] = h_new_all * e + groups_map[group] = k + h_vecs = h_vecs.T + + f_new = fun(t, y[:, None] + h_vecs) + df = f_new - f[:, None] + i, j, _ = find(structure[:, ind]) + diff_new = coo_matrix((df[i, groups_map[groups[ind[j]]]], + (i, j)), shape=(n, ind.shape[0])).tocsc() + + max_ind_new = np.array(abs(diff_new).argmax(axis=0)).ravel() + r = np.arange(ind.shape[0]) + max_diff_new = np.asarray(np.abs(diff_new[max_ind_new, r])).ravel() + scale_new = np.maximum( + np.abs(f[max_ind_new]), + np.abs(f_new[max_ind_new, groups_map[groups[ind]]])) + + update = max_diff[ind] * scale_new < max_diff_new * scale[ind] + if np.any(update): + update, = np.nonzero(update) + update_ind = ind[update] + factor[update_ind] = new_factor[update] + h[update_ind] = h_new[update] + diff[:, update_ind] = diff_new[:, update] + scale[update_ind] = scale_new[update] + max_diff[update_ind] = max_diff_new[update] + + diff.data /= np.repeat(h, np.diff(diff.indptr)) + + factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE + factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE + factor = np.maximum(factor, NUM_JAC_MIN_FACTOR) + + return diff, factor diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py new file mode 100644 index 0000000000000000000000000000000000000000..f39f2f3650d321e2c475d4e220f9769139118a5e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py @@ -0,0 +1,193 @@ +import numpy as np + +N_STAGES = 12 +N_STAGES_EXTENDED = 16 +INTERPOLATOR_POWER = 7 + +C = np.array([0.0, + 0.526001519587677318785587544488e-01, + 0.789002279381515978178381316732e-01, + 0.118350341907227396726757197510, + 0.281649658092772603273242802490, + 0.333333333333333333333333333333, + 0.25, + 0.307692307692307692307692307692, + 0.651282051282051282051282051282, + 0.6, + 0.857142857142857142857142857142, + 1.0, + 1.0, + 0.1, + 0.2, + 0.777777777777777777777777777778]) + +A = np.zeros((N_STAGES_EXTENDED, N_STAGES_EXTENDED)) +A[1, 0] = 5.26001519587677318785587544488e-2 + +A[2, 0] = 1.97250569845378994544595329183e-2 +A[2, 1] = 5.91751709536136983633785987549e-2 + +A[3, 0] = 2.95875854768068491816892993775e-2 +A[3, 2] = 8.87627564304205475450678981324e-2 + +A[4, 0] = 2.41365134159266685502369798665e-1 +A[4, 2] = -8.84549479328286085344864962717e-1 +A[4, 3] = 9.24834003261792003115737966543e-1 + +A[5, 0] = 3.7037037037037037037037037037e-2 +A[5, 3] = 1.70828608729473871279604482173e-1 +A[5, 4] = 1.25467687566822425016691814123e-1 + +A[6, 0] = 3.7109375e-2 +A[6, 3] = 1.70252211019544039314978060272e-1 +A[6, 4] = 6.02165389804559606850219397283e-2 +A[6, 5] = -1.7578125e-2 + +A[7, 0] = 3.70920001185047927108779319836e-2 +A[7, 3] = 1.70383925712239993810214054705e-1 +A[7, 4] = 1.07262030446373284651809199168e-1 +A[7, 5] = -1.53194377486244017527936158236e-2 +A[7, 6] = 8.27378916381402288758473766002e-3 + +A[8, 0] = 6.24110958716075717114429577812e-1 +A[8, 3] = -3.36089262944694129406857109825 +A[8, 4] = -8.68219346841726006818189891453e-1 +A[8, 5] = 2.75920996994467083049415600797e1 +A[8, 6] = 2.01540675504778934086186788979e1 +A[8, 7] = -4.34898841810699588477366255144e1 + +A[9, 0] = 4.77662536438264365890433908527e-1 +A[9, 3] = -2.48811461997166764192642586468 +A[9, 4] = -5.90290826836842996371446475743e-1 +A[9, 5] = 2.12300514481811942347288949897e1 +A[9, 6] = 1.52792336328824235832596922938e1 +A[9, 7] = -3.32882109689848629194453265587e1 +A[9, 8] = -2.03312017085086261358222928593e-2 + +A[10, 0] = -9.3714243008598732571704021658e-1 +A[10, 3] = 5.18637242884406370830023853209 +A[10, 4] = 1.09143734899672957818500254654 +A[10, 5] = -8.14978701074692612513997267357 +A[10, 6] = -1.85200656599969598641566180701e1 +A[10, 7] = 2.27394870993505042818970056734e1 +A[10, 8] = 2.49360555267965238987089396762 +A[10, 9] = -3.0467644718982195003823669022 + +A[11, 0] = 2.27331014751653820792359768449 +A[11, 3] = -1.05344954667372501984066689879e1 +A[11, 4] = -2.00087205822486249909675718444 +A[11, 5] = -1.79589318631187989172765950534e1 +A[11, 6] = 2.79488845294199600508499808837e1 +A[11, 7] = -2.85899827713502369474065508674 +A[11, 8] = -8.87285693353062954433549289258 +A[11, 9] = 1.23605671757943030647266201528e1 +A[11, 10] = 6.43392746015763530355970484046e-1 + +A[12, 0] = 5.42937341165687622380535766363e-2 +A[12, 5] = 4.45031289275240888144113950566 +A[12, 6] = 1.89151789931450038304281599044 +A[12, 7] = -5.8012039600105847814672114227 +A[12, 8] = 3.1116436695781989440891606237e-1 +A[12, 9] = -1.52160949662516078556178806805e-1 +A[12, 10] = 2.01365400804030348374776537501e-1 +A[12, 11] = 4.47106157277725905176885569043e-2 + +A[13, 0] = 5.61675022830479523392909219681e-2 +A[13, 6] = 2.53500210216624811088794765333e-1 +A[13, 7] = -2.46239037470802489917441475441e-1 +A[13, 8] = -1.24191423263816360469010140626e-1 +A[13, 9] = 1.5329179827876569731206322685e-1 +A[13, 10] = 8.20105229563468988491666602057e-3 +A[13, 11] = 7.56789766054569976138603589584e-3 +A[13, 12] = -8.298e-3 + +A[14, 0] = 3.18346481635021405060768473261e-2 +A[14, 5] = 2.83009096723667755288322961402e-2 +A[14, 6] = 5.35419883074385676223797384372e-2 +A[14, 7] = -5.49237485713909884646569340306e-2 +A[14, 10] = -1.08347328697249322858509316994e-4 +A[14, 11] = 3.82571090835658412954920192323e-4 +A[14, 12] = -3.40465008687404560802977114492e-4 +A[14, 13] = 1.41312443674632500278074618366e-1 + +A[15, 0] = -4.28896301583791923408573538692e-1 +A[15, 5] = -4.69762141536116384314449447206 +A[15, 6] = 7.68342119606259904184240953878 +A[15, 7] = 4.06898981839711007970213554331 +A[15, 8] = 3.56727187455281109270669543021e-1 +A[15, 12] = -1.39902416515901462129418009734e-3 +A[15, 13] = 2.9475147891527723389556272149 +A[15, 14] = -9.15095847217987001081870187138 + + +B = A[N_STAGES, :N_STAGES] + +E3 = np.zeros(N_STAGES + 1) +E3[:-1] = B.copy() +E3[0] -= 0.244094488188976377952755905512 +E3[8] -= 0.733846688281611857341361741547 +E3[11] -= 0.220588235294117647058823529412e-1 + +E5 = np.zeros(N_STAGES + 1) +E5[0] = 0.1312004499419488073250102996e-1 +E5[5] = -0.1225156446376204440720569753e+1 +E5[6] = -0.4957589496572501915214079952 +E5[7] = 0.1664377182454986536961530415e+1 +E5[8] = -0.3503288487499736816886487290 +E5[9] = 0.3341791187130174790297318841 +E5[10] = 0.8192320648511571246570742613e-1 +E5[11] = -0.2235530786388629525884427845e-1 + +# First 3 coefficients are computed separately. +D = np.zeros((INTERPOLATOR_POWER - 3, N_STAGES_EXTENDED)) +D[0, 0] = -0.84289382761090128651353491142e+1 +D[0, 5] = 0.56671495351937776962531783590 +D[0, 6] = -0.30689499459498916912797304727e+1 +D[0, 7] = 0.23846676565120698287728149680e+1 +D[0, 8] = 0.21170345824450282767155149946e+1 +D[0, 9] = -0.87139158377797299206789907490 +D[0, 10] = 0.22404374302607882758541771650e+1 +D[0, 11] = 0.63157877876946881815570249290 +D[0, 12] = -0.88990336451333310820698117400e-1 +D[0, 13] = 0.18148505520854727256656404962e+2 +D[0, 14] = -0.91946323924783554000451984436e+1 +D[0, 15] = -0.44360363875948939664310572000e+1 + +D[1, 0] = 0.10427508642579134603413151009e+2 +D[1, 5] = 0.24228349177525818288430175319e+3 +D[1, 6] = 0.16520045171727028198505394887e+3 +D[1, 7] = -0.37454675472269020279518312152e+3 +D[1, 8] = -0.22113666853125306036270938578e+2 +D[1, 9] = 0.77334326684722638389603898808e+1 +D[1, 10] = -0.30674084731089398182061213626e+2 +D[1, 11] = -0.93321305264302278729567221706e+1 +D[1, 12] = 0.15697238121770843886131091075e+2 +D[1, 13] = -0.31139403219565177677282850411e+2 +D[1, 14] = -0.93529243588444783865713862664e+1 +D[1, 15] = 0.35816841486394083752465898540e+2 + +D[2, 0] = 0.19985053242002433820987653617e+2 +D[2, 5] = -0.38703730874935176555105901742e+3 +D[2, 6] = -0.18917813819516756882830838328e+3 +D[2, 7] = 0.52780815920542364900561016686e+3 +D[2, 8] = -0.11573902539959630126141871134e+2 +D[2, 9] = 0.68812326946963000169666922661e+1 +D[2, 10] = -0.10006050966910838403183860980e+1 +D[2, 11] = 0.77771377980534432092869265740 +D[2, 12] = -0.27782057523535084065932004339e+1 +D[2, 13] = -0.60196695231264120758267380846e+2 +D[2, 14] = 0.84320405506677161018159903784e+2 +D[2, 15] = 0.11992291136182789328035130030e+2 + +D[3, 0] = -0.25693933462703749003312586129e+2 +D[3, 5] = -0.15418974869023643374053993627e+3 +D[3, 6] = -0.23152937917604549567536039109e+3 +D[3, 7] = 0.35763911791061412378285349910e+3 +D[3, 8] = 0.93405324183624310003907691704e+2 +D[3, 9] = -0.37458323136451633156875139351e+2 +D[3, 10] = 0.10409964950896230045147246184e+3 +D[3, 11] = 0.29840293426660503123344363579e+2 +D[3, 12] = -0.43533456590011143754432175058e+2 +D[3, 13] = 0.96324553959188282948394950600e+2 +D[3, 14] = -0.39177261675615439165231486172e+2 +D[3, 15] = -0.14972683625798562581422125276e+3 diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py new file mode 100644 index 0000000000000000000000000000000000000000..13d4732bd644832857d31fde5cf33e2b169051e6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py @@ -0,0 +1,748 @@ +import inspect +import numpy as np +from .bdf import BDF +from .radau import Radau +from .rk import RK23, RK45, DOP853 +from .lsoda import LSODA +from scipy.optimize import OptimizeResult +from .common import EPS, OdeSolution +from .base import OdeSolver + + +METHODS = {'RK23': RK23, + 'RK45': RK45, + 'DOP853': DOP853, + 'Radau': Radau, + 'BDF': BDF, + 'LSODA': LSODA} + + +MESSAGES = {0: "The solver successfully reached the end of the integration interval.", + 1: "A termination event occurred."} + + +class OdeResult(OptimizeResult): + pass + + +def prepare_events(events): + """Standardize event functions and extract attributes.""" + if callable(events): + events = (events,) + + max_events = np.empty(len(events)) + direction = np.empty(len(events)) + for i, event in enumerate(events): + terminal = getattr(event, 'terminal', None) + direction[i] = getattr(event, 'direction', 0) + + message = ('The `terminal` attribute of each event ' + 'must be a boolean or positive integer.') + if terminal is None or terminal == 0: + max_events[i] = np.inf + elif int(terminal) == terminal and terminal > 0: + max_events[i] = terminal + else: + raise ValueError(message) + + return events, max_events, direction + + +def solve_event_equation(event, sol, t_old, t): + """Solve an equation corresponding to an ODE event. + + The equation is ``event(t, y(t)) = 0``, here ``y(t)`` is known from an + ODE solver using some sort of interpolation. It is solved by + `scipy.optimize.brentq` with xtol=atol=4*EPS. + + Parameters + ---------- + event : callable + Function ``event(t, y)``. + sol : callable + Function ``sol(t)`` which evaluates an ODE solution between `t_old` + and `t`. + t_old, t : float + Previous and new values of time. They will be used as a bracketing + interval. + + Returns + ------- + root : float + Found solution. + """ + from scipy.optimize import brentq + return brentq(lambda t: event(t, sol(t)), t_old, t, + xtol=4 * EPS, rtol=4 * EPS) + + +def handle_events(sol, events, active_events, event_count, max_events, + t_old, t): + """Helper function to handle events. + + Parameters + ---------- + sol : DenseOutput + Function ``sol(t)`` which evaluates an ODE solution between `t_old` + and `t`. + events : list of callables, length n_events + Event functions with signatures ``event(t, y)``. + active_events : ndarray + Indices of events which occurred. + event_count : ndarray + Current number of occurrences for each event. + max_events : ndarray, shape (n_events,) + Number of occurrences allowed for each event before integration + termination is issued. + t_old, t : float + Previous and new values of time. + + Returns + ------- + root_indices : ndarray + Indices of events which take zero between `t_old` and `t` and before + a possible termination. + roots : ndarray + Values of t at which events occurred. + terminate : bool + Whether a terminal event occurred. + """ + roots = [solve_event_equation(events[event_index], sol, t_old, t) + for event_index in active_events] + + roots = np.asarray(roots) + + if np.any(event_count[active_events] >= max_events[active_events]): + if t > t_old: + order = np.argsort(roots) + else: + order = np.argsort(-roots) + active_events = active_events[order] + roots = roots[order] + t = np.nonzero(event_count[active_events] + >= max_events[active_events])[0][0] + active_events = active_events[:t + 1] + roots = roots[:t + 1] + terminate = True + else: + terminate = False + + return active_events, roots, terminate + + +def find_active_events(g, g_new, direction): + """Find which event occurred during an integration step. + + Parameters + ---------- + g, g_new : array_like, shape (n_events,) + Values of event functions at a current and next points. + direction : ndarray, shape (n_events,) + Event "direction" according to the definition in `solve_ivp`. + + Returns + ------- + active_events : ndarray + Indices of events which occurred during the step. + """ + g, g_new = np.asarray(g), np.asarray(g_new) + up = (g <= 0) & (g_new >= 0) + down = (g >= 0) & (g_new <= 0) + either = up | down + mask = (up & (direction > 0) | + down & (direction < 0) | + either & (direction == 0)) + + return np.nonzero(mask)[0] + + +def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False, + events=None, vectorized=False, args=None, **options): + """Solve an initial value problem for a system of ODEs. + + This function numerically integrates a system of ordinary differential + equations given an initial value:: + + dy / dt = f(t, y) + y(t0) = y0 + + Here t is a 1-D independent variable (time), y(t) is an + N-D vector-valued function (state), and an N-D + vector-valued function f(t, y) determines the differential equations. + The goal is to find y(t) approximately satisfying the differential + equations, given an initial value y(t0)=y0. + + Some of the solvers support integration in the complex domain, but note + that for stiff ODE solvers, the right-hand side must be + complex-differentiable (satisfy Cauchy-Riemann equations [11]_). + To solve a problem in the complex domain, pass y0 with a complex data type. + Another option always available is to rewrite your problem for real and + imaginary parts separately. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. Additional + arguments need to be passed if ``args`` is used (see documentation of + ``args`` argument). ``fun`` must return an array of the same shape as + ``y``. See `vectorized` for more information. + t_span : 2-member sequence + Interval of integration (t0, tf). The solver starts with t=t0 and + integrates until it reaches t=tf. Both t0 and tf must be floats + or values interpretable by the float conversion function. + y0 : array_like, shape (n,) + Initial state. For problems in the complex domain, pass `y0` with a + complex data type (even if the initial value is purely real). + method : string or `OdeSolver`, optional + Integration method to use: + + * 'RK45' (default): Explicit Runge-Kutta method of order 5(4) [1]_. + The error is controlled assuming accuracy of the fourth-order + method, but steps are taken using the fifth-order accurate + formula (local extrapolation is done). A quartic interpolation + polynomial is used for the dense output [2]_. Can be applied in + the complex domain. + * 'RK23': Explicit Runge-Kutta method of order 3(2) [3]_. The error + is controlled assuming accuracy of the second-order method, but + steps are taken using the third-order accurate formula (local + extrapolation is done). A cubic Hermite polynomial is used for the + dense output. Can be applied in the complex domain. + * 'DOP853': Explicit Runge-Kutta method of order 8 [13]_. + Python implementation of the "DOP853" algorithm originally + written in Fortran [14]_. A 7-th order interpolation polynomial + accurate to 7-th order is used for the dense output. + Can be applied in the complex domain. + * 'Radau': Implicit Runge-Kutta method of the Radau IIA family of + order 5 [4]_. The error is controlled with a third-order accurate + embedded formula. A cubic polynomial which satisfies the + collocation conditions is used for the dense output. + * 'BDF': Implicit multi-step variable-order (1 to 5) method based + on a backward differentiation formula for the derivative + approximation [5]_. The implementation follows the one described + in [6]_. A quasi-constant step scheme is used and accuracy is + enhanced using the NDF modification. Can be applied in the + complex domain. + * 'LSODA': Adams/BDF method with automatic stiffness detection and + switching [7]_, [8]_. This is a wrapper of the Fortran solver + from ODEPACK. + + Explicit Runge-Kutta methods ('RK23', 'RK45', 'DOP853') should be used + for non-stiff problems and implicit methods ('Radau', 'BDF') for + stiff problems [9]_. Among Runge-Kutta methods, 'DOP853' is recommended + for solving with high precision (low values of `rtol` and `atol`). + + If not sure, first try to run 'RK45'. If it makes unusually many + iterations, diverges, or fails, your problem is likely to be stiff and + you should use 'Radau' or 'BDF'. 'LSODA' can also be a good universal + choice, but it might be somewhat less convenient to work with as it + wraps old Fortran code. + + You can also pass an arbitrary class derived from `OdeSolver` which + implements the solver. + t_eval : array_like or None, optional + Times at which to store the computed solution, must be sorted and lie + within `t_span`. If None (default), use points selected by the solver. + dense_output : bool, optional + Whether to compute a continuous solution. Default is False. + events : callable, or list of callables, optional + Events to track. If None (default), no events will be tracked. + Each event occurs at the zeros of a continuous function of time and + state. Each function must have the signature ``event(t, y)`` where + additional argument have to be passed if ``args`` is used (see + documentation of ``args`` argument). Each function must return a + float. The solver will find an accurate value of `t` at which + ``event(t, y(t)) = 0`` using a root-finding algorithm. By default, + all zeros will be found. The solver looks for a sign change over + each step, so if multiple zero crossings occur within one step, + events may be missed. Additionally each `event` function might + have the following attributes: + + terminal: bool or int, optional + When boolean, whether to terminate integration if this event occurs. + When integral, termination occurs after the specified the number of + occurences of this event. + Implicitly False if not assigned. + direction: float, optional + Direction of a zero crossing. If `direction` is positive, + `event` will only trigger when going from negative to positive, + and vice versa if `direction` is negative. If 0, then either + direction will trigger event. Implicitly 0 if not assigned. + + You can assign attributes like ``event.terminal = True`` to any + function in Python. + vectorized : bool, optional + Whether `fun` can be called in a vectorized fashion. Default is False. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by methods 'Radau' and 'BDF', but + will result in slower execution for other methods and for 'Radau' and + 'BDF' in some circumstances (e.g. small ``len(y0)``). + args : tuple, optional + Additional arguments to pass to the user-defined functions. If given, + the additional arguments are passed to all user-defined functions. + So if, for example, `fun` has the signature ``fun(t, y, a, b, c)``, + then `jac` (if given) and any event functions must have the same + signature, and `args` must be a tuple of length 3. + **options + Options passed to a chosen solver. All options available for already + implemented solvers are listed below. + first_step : float or None, optional + Initial step size. Default is `None` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float or array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + jac : array_like, sparse_matrix, callable or None, optional + Jacobian matrix of the right-hand side of the system with respect + to y, required by the 'Radau', 'BDF' and 'LSODA' method. The + Jacobian matrix has shape (n, n) and its element (i, j) is equal to + ``d f_i / d y_j``. There are three ways to define the Jacobian: + + * If array_like or sparse_matrix, the Jacobian is assumed to + be constant. Not supported by 'LSODA'. + * If callable, the Jacobian is assumed to depend on both + t and y; it will be called as ``jac(t, y)``, as necessary. + Additional arguments have to be passed if ``args`` is + used (see documentation of ``args`` argument). + For 'Radau' and 'BDF' methods, the return value might be a + sparse matrix. + * If None (default), the Jacobian will be approximated by + finite differences. + + It is generally recommended to provide the Jacobian rather than + relying on a finite-difference approximation. + jac_sparsity : array_like, sparse matrix or None, optional + Defines a sparsity structure of the Jacobian matrix for a finite- + difference approximation. Its shape must be (n, n). This argument + is ignored if `jac` is not `None`. If the Jacobian has only few + non-zero elements in *each* row, providing the sparsity structure + will greatly speed up the computations [10]_. A zero entry means that + a corresponding element in the Jacobian is always zero. If None + (default), the Jacobian is assumed to be dense. + Not supported by 'LSODA', see `lband` and `uband` instead. + lband, uband : int or None, optional + Parameters defining the bandwidth of the Jacobian for the 'LSODA' + method, i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. + Default is None. Setting these requires your jac routine to return the + Jacobian in the packed format: the returned array must have ``n`` + columns and ``uband + lband + 1`` rows in which Jacobian diagonals are + written. Specifically ``jac_packed[uband + i - j , j] = jac[i, j]``. + The same format is used in `scipy.linalg.solve_banded` (check for an + illustration). These parameters can be also used with ``jac=None`` to + reduce the number of Jacobian elements estimated by finite differences. + min_step : float, optional + The minimum allowed step size for 'LSODA' method. + By default `min_step` is zero. + + Returns + ------- + Bunch object with the following fields defined: + t : ndarray, shape (n_points,) + Time points. + y : ndarray, shape (n, n_points) + Values of the solution at `t`. + sol : `OdeSolution` or None + Found solution as `OdeSolution` instance; None if `dense_output` was + set to False. + t_events : list of ndarray or None + Contains for each event type a list of arrays at which an event of + that type event was detected. None if `events` was None. + y_events : list of ndarray or None + For each value of `t_events`, the corresponding value of the solution. + None if `events` was None. + nfev : int + Number of evaluations of the right-hand side. + njev : int + Number of evaluations of the Jacobian. + nlu : int + Number of LU decompositions. + status : int + Reason for algorithm termination: + + * -1: Integration step failed. + * 0: The solver successfully reached the end of `tspan`. + * 1: A termination event occurred. + + message : string + Human-readable description of the termination reason. + success : bool + True if the solver reached the interval end or a termination event + occurred (``status >= 0``). + + References + ---------- + .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta + formulae", Journal of Computational and Applied Mathematics, Vol. 6, + No. 1, pp. 19-26, 1980. + .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics + of Computation,, Vol. 46, No. 173, pp. 135-150, 1986. + .. [3] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas", + Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989. + .. [4] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II: + Stiff and Differential-Algebraic Problems", Sec. IV.8. + .. [5] `Backward Differentiation Formula + `_ + on Wikipedia. + .. [6] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI. + COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997. + .. [7] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE + Solvers," IMACS Transactions on Scientific Computation, Vol 1., + pp. 55-64, 1983. + .. [8] L. Petzold, "Automatic selection of methods for solving stiff and + nonstiff systems of ordinary differential equations", SIAM Journal + on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148, + 1983. + .. [9] `Stiff equation `_ on + Wikipedia. + .. [10] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of Mathematics + and its Applications, 13, pp. 117-120, 1974. + .. [11] `Cauchy-Riemann equations + `_ on + Wikipedia. + .. [12] `Lotka-Volterra equations + `_ + on Wikipedia. + .. [13] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations I: Nonstiff Problems", Sec. II. + .. [14] `Page with original Fortran code of DOP853 + `_. + + Examples + -------- + Basic exponential decay showing automatically chosen time points. + + >>> import numpy as np + >>> from scipy.integrate import solve_ivp + >>> def exponential_decay(t, y): return -0.5 * y + >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8]) + >>> print(sol.t) + [ 0. 0.11487653 1.26364188 3.06061781 4.81611105 6.57445806 + 8.33328988 10. ] + >>> print(sol.y) + [[2. 1.88836035 1.06327177 0.43319312 0.18017253 0.07483045 + 0.03107158 0.01350781] + [4. 3.7767207 2.12654355 0.86638624 0.36034507 0.14966091 + 0.06214316 0.02701561] + [8. 7.5534414 4.25308709 1.73277247 0.72069014 0.29932181 + 0.12428631 0.05403123]] + + Specifying points where the solution is desired. + + >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8], + ... t_eval=[0, 1, 2, 4, 10]) + >>> print(sol.t) + [ 0 1 2 4 10] + >>> print(sol.y) + [[2. 1.21305369 0.73534021 0.27066736 0.01350938] + [4. 2.42610739 1.47068043 0.54133472 0.02701876] + [8. 4.85221478 2.94136085 1.08266944 0.05403753]] + + Cannon fired upward with terminal event upon impact. The ``terminal`` and + ``direction`` fields of an event are applied by monkey patching a function. + Here ``y[0]`` is position and ``y[1]`` is velocity. The projectile starts + at position 0 with velocity +10. Note that the integration never reaches + t=100 because the event is terminal. + + >>> def upward_cannon(t, y): return [y[1], -0.5] + >>> def hit_ground(t, y): return y[0] + >>> hit_ground.terminal = True + >>> hit_ground.direction = -1 + >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], events=hit_ground) + >>> print(sol.t_events) + [array([40.])] + >>> print(sol.t) + [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02 + 1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01] + + Use `dense_output` and `events` to find position, which is 100, at the apex + of the cannonball's trajectory. Apex is not defined as terminal, so both + apex and hit_ground are found. There is no information at t=20, so the sol + attribute is used to evaluate the solution. The sol attribute is returned + by setting ``dense_output=True``. Alternatively, the `y_events` attribute + can be used to access the solution at the time of the event. + + >>> def apex(t, y): return y[1] + >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], + ... events=(hit_ground, apex), dense_output=True) + >>> print(sol.t_events) + [array([40.]), array([20.])] + >>> print(sol.t) + [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02 + 1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01] + >>> print(sol.sol(sol.t_events[1][0])) + [100. 0.] + >>> print(sol.y_events) + [array([[-5.68434189e-14, -1.00000000e+01]]), + array([[1.00000000e+02, 1.77635684e-15]])] + + As an example of a system with additional parameters, we'll implement + the Lotka-Volterra equations [12]_. + + >>> def lotkavolterra(t, z, a, b, c, d): + ... x, y = z + ... return [a*x - b*x*y, -c*y + d*x*y] + ... + + We pass in the parameter values a=1.5, b=1, c=3 and d=1 with the `args` + argument. + + >>> sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1), + ... dense_output=True) + + Compute a dense solution and plot it. + + >>> t = np.linspace(0, 15, 300) + >>> z = sol.sol(t) + >>> import matplotlib.pyplot as plt + >>> plt.plot(t, z.T) + >>> plt.xlabel('t') + >>> plt.legend(['x', 'y'], shadow=True) + >>> plt.title('Lotka-Volterra System') + >>> plt.show() + + A couple examples of using solve_ivp to solve the differential + equation ``y' = Ay`` with complex matrix ``A``. + + >>> A = np.array([[-0.25 + 0.14j, 0, 0.33 + 0.44j], + ... [0.25 + 0.58j, -0.2 + 0.14j, 0], + ... [0, 0.2 + 0.4j, -0.1 + 0.97j]]) + + Solving an IVP with ``A`` from above and ``y`` as 3x1 vector: + + >>> def deriv_vec(t, y): + ... return A @ y + >>> result = solve_ivp(deriv_vec, [0, 25], + ... np.array([10 + 0j, 20 + 0j, 30 + 0j]), + ... t_eval=np.linspace(0, 25, 101)) + >>> print(result.y[:, 0]) + [10.+0.j 20.+0.j 30.+0.j] + >>> print(result.y[:, -1]) + [18.46291039+45.25653651j 10.01569306+36.23293216j + -4.98662741+80.07360388j] + + Solving an IVP with ``A`` from above with ``y`` as 3x3 matrix : + + >>> def deriv_mat(t, y): + ... return (A @ y.reshape(3, 3)).flatten() + >>> y0 = np.array([[2 + 0j, 3 + 0j, 4 + 0j], + ... [5 + 0j, 6 + 0j, 7 + 0j], + ... [9 + 0j, 34 + 0j, 78 + 0j]]) + + >>> result = solve_ivp(deriv_mat, [0, 25], y0.flatten(), + ... t_eval=np.linspace(0, 25, 101)) + >>> print(result.y[:, 0].reshape(3, 3)) + [[ 2.+0.j 3.+0.j 4.+0.j] + [ 5.+0.j 6.+0.j 7.+0.j] + [ 9.+0.j 34.+0.j 78.+0.j]] + >>> print(result.y[:, -1].reshape(3, 3)) + [[ 5.67451179 +12.07938445j 17.2888073 +31.03278837j + 37.83405768 +63.25138759j] + [ 3.39949503 +11.82123994j 21.32530996 +44.88668871j + 53.17531184+103.80400411j] + [ -2.26105874 +22.19277664j -15.1255713 +70.19616341j + -38.34616845+153.29039931j]] + + + """ + if method not in METHODS and not ( + inspect.isclass(method) and issubclass(method, OdeSolver)): + raise ValueError(f"`method` must be one of {METHODS} or OdeSolver class.") + + t0, tf = map(float, t_span) + + if args is not None: + # Wrap the user's fun (and jac, if given) in lambdas to hide the + # additional parameters. Pass in the original fun as a keyword + # argument to keep it in the scope of the lambda. + try: + _ = [*(args)] + except TypeError as exp: + suggestion_tuple = ( + "Supplied 'args' cannot be unpacked. Please supply `args`" + f" as a tuple (e.g. `args=({args},)`)" + ) + raise TypeError(suggestion_tuple) from exp + + def fun(t, x, fun=fun): + return fun(t, x, *args) + jac = options.get('jac') + if callable(jac): + options['jac'] = lambda t, x: jac(t, x, *args) + + if t_eval is not None: + t_eval = np.asarray(t_eval) + if t_eval.ndim != 1: + raise ValueError("`t_eval` must be 1-dimensional.") + + if np.any(t_eval < min(t0, tf)) or np.any(t_eval > max(t0, tf)): + raise ValueError("Values in `t_eval` are not within `t_span`.") + + d = np.diff(t_eval) + if tf > t0 and np.any(d <= 0) or tf < t0 and np.any(d >= 0): + raise ValueError("Values in `t_eval` are not properly sorted.") + + if tf > t0: + t_eval_i = 0 + else: + # Make order of t_eval decreasing to use np.searchsorted. + t_eval = t_eval[::-1] + # This will be an upper bound for slices. + t_eval_i = t_eval.shape[0] + + if method in METHODS: + method = METHODS[method] + + solver = method(fun, t0, y0, tf, vectorized=vectorized, **options) + + if t_eval is None: + ts = [t0] + ys = [y0] + elif t_eval is not None and dense_output: + ts = [] + ti = [t0] + ys = [] + else: + ts = [] + ys = [] + + interpolants = [] + + if events is not None: + events, max_events, event_dir = prepare_events(events) + event_count = np.zeros(len(events)) + if args is not None: + # Wrap user functions in lambdas to hide the additional parameters. + # The original event function is passed as a keyword argument to the + # lambda to keep the original function in scope (i.e., avoid the + # late binding closure "gotcha"). + events = [lambda t, x, event=event: event(t, x, *args) + for event in events] + g = [event(t0, y0) for event in events] + t_events = [[] for _ in range(len(events))] + y_events = [[] for _ in range(len(events))] + else: + t_events = None + y_events = None + + status = None + while status is None: + message = solver.step() + + if solver.status == 'finished': + status = 0 + elif solver.status == 'failed': + status = -1 + break + + t_old = solver.t_old + t = solver.t + y = solver.y + + if dense_output: + sol = solver.dense_output() + interpolants.append(sol) + else: + sol = None + + if events is not None: + g_new = [event(t, y) for event in events] + active_events = find_active_events(g, g_new, event_dir) + if active_events.size > 0: + if sol is None: + sol = solver.dense_output() + + event_count[active_events] += 1 + root_indices, roots, terminate = handle_events( + sol, events, active_events, event_count, max_events, + t_old, t) + + for e, te in zip(root_indices, roots): + t_events[e].append(te) + y_events[e].append(sol(te)) + + if terminate: + status = 1 + t = roots[-1] + y = sol(t) + + g = g_new + + if t_eval is None: + ts.append(t) + ys.append(y) + else: + # The value in t_eval equal to t will be included. + if solver.direction > 0: + t_eval_i_new = np.searchsorted(t_eval, t, side='right') + t_eval_step = t_eval[t_eval_i:t_eval_i_new] + else: + t_eval_i_new = np.searchsorted(t_eval, t, side='left') + # It has to be done with two slice operations, because + # you can't slice to 0th element inclusive using backward + # slicing. + t_eval_step = t_eval[t_eval_i_new:t_eval_i][::-1] + + if t_eval_step.size > 0: + if sol is None: + sol = solver.dense_output() + ts.append(t_eval_step) + ys.append(sol(t_eval_step)) + t_eval_i = t_eval_i_new + + if t_eval is not None and dense_output: + ti.append(t) + + message = MESSAGES.get(status, message) + + if t_events is not None: + t_events = [np.asarray(te) for te in t_events] + y_events = [np.asarray(ye) for ye in y_events] + + if t_eval is None: + ts = np.array(ts) + ys = np.vstack(ys).T + elif ts: + ts = np.hstack(ts) + ys = np.hstack(ys) + + if dense_output: + if t_eval is None: + sol = OdeSolution( + ts, interpolants, alt_segment=True if method in [BDF, LSODA] else False + ) + else: + sol = OdeSolution( + ti, interpolants, alt_segment=True if method in [BDF, LSODA] else False + ) + else: + sol = None + + return OdeResult(t=ts, y=ys, sol=sol, t_events=t_events, y_events=y_events, + nfev=solver.nfev, njev=solver.njev, nlu=solver.nlu, + status=status, message=message, success=status >= 0) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py new file mode 100644 index 0000000000000000000000000000000000000000..2a5a7c530c04eddc9beff44e2d4f6df439d5ef01 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py @@ -0,0 +1,224 @@ +import numpy as np +from scipy.integrate import ode +from .common import validate_tol, validate_first_step, warn_extraneous +from .base import OdeSolver, DenseOutput + + +class LSODA(OdeSolver): + """Adams/BDF method with automatic stiffness detection and switching. + + This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches + automatically between the nonstiff Adams method and the stiff BDF method. + The method was originally detailed in [2]_. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + min_step : float, optional + Minimum allowed step size. Default is 0.0, i.e., the step size is not + bounded and determined solely by the solver. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + jac : None or callable, optional + Jacobian matrix of the right-hand side of the system with respect to + ``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is + equal to ``d f_i / d y_j``. The function will be called as + ``jac(t, y)``. If None (default), the Jacobian will be + approximated by finite differences. It is generally recommended to + provide the Jacobian rather than relying on a finite-difference + approximation. + lband, uband : int or None + Parameters defining the bandwidth of the Jacobian, + i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting + these requires your jac routine to return the Jacobian in the packed format: + the returned array must have ``n`` columns and ``uband + lband + 1`` + rows in which Jacobian diagonals are written. Specifically + ``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used + in `scipy.linalg.solve_banded` (check for an illustration). + These parameters can be also used with ``jac=None`` to reduce the + number of Jacobian elements estimated by finite differences. + vectorized : bool, optional + Whether `fun` may be called in a vectorized fashion. False (default) + is recommended for this solver. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by methods 'Radau' and 'BDF', but + will result in slower execution for this solver. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + nfev : int + Number of evaluations of the right-hand side. + njev : int + Number of evaluations of the Jacobian. + + References + ---------- + .. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE + Solvers," IMACS Transactions on Scientific Computation, Vol 1., + pp. 55-64, 1983. + .. [2] L. Petzold, "Automatic selection of methods for solving stiff and + nonstiff systems of ordinary differential equations", SIAM Journal + on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148, + 1983. + """ + def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0, + max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None, + uband=None, vectorized=False, **extraneous): + warn_extraneous(extraneous) + super().__init__(fun, t0, y0, t_bound, vectorized) + + if first_step is None: + first_step = 0 # LSODA value for automatic selection. + else: + first_step = validate_first_step(first_step, t0, t_bound) + + first_step *= self.direction + + if max_step == np.inf: + max_step = 0 # LSODA value for infinity. + elif max_step <= 0: + raise ValueError("`max_step` must be positive.") + + if min_step < 0: + raise ValueError("`min_step` must be nonnegative.") + + rtol, atol = validate_tol(rtol, atol, self.n) + + solver = ode(self.fun, jac) + solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step, + min_step=min_step, first_step=first_step, + lband=lband, uband=uband) + solver.set_initial_value(y0, t0) + + # Inject t_bound into rwork array as needed for itask=5. + solver._integrator.rwork[0] = self.t_bound + solver._integrator.call_args[4] = solver._integrator.rwork + + self._lsoda_solver = solver + + def _step_impl(self): + solver = self._lsoda_solver + integrator = solver._integrator + + # From lsoda.step and lsoda.integrate itask=5 means take a single + # step and do not go past t_bound. + itask = integrator.call_args[2] + integrator.call_args[2] = 5 + solver._y, solver.t = integrator.run( + solver.f, solver.jac or (lambda: None), solver._y, solver.t, + self.t_bound, solver.f_params, solver.jac_params) + integrator.call_args[2] = itask + + if solver.successful(): + self.t = solver.t + self.y = solver._y + # From LSODA Fortran source njev is equal to nlu. + self.njev = integrator.iwork[12] + self.nlu = integrator.iwork[12] + return True, None + else: + return False, 'Unexpected istate in LSODA.' + + def _dense_output_impl(self): + iwork = self._lsoda_solver._integrator.iwork + rwork = self._lsoda_solver._integrator.rwork + + # We want to produce the Nordsieck history array, yh, up to the order + # used in the last successful iteration. The step size is unimportant + # because it will be scaled out in LsodaDenseOutput. Some additional + # work may be required because ODEPACK's LSODA implementation produces + # the Nordsieck history in the state needed for the next iteration. + + # iwork[13] contains order from last successful iteration, while + # iwork[14] contains order to be attempted next. + order = iwork[13] + + # rwork[11] contains the step size to be attempted next, while + # rwork[10] contains step size from last successful iteration. + h = rwork[11] + + # rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the + # Nordsieck array in state needed for next iteration. We want + # the entries up to order for the last successful step so use the + # following. + yh = np.reshape(rwork[20:20 + (order + 1) * self.n], + (self.n, order + 1), order='F').copy() + if iwork[14] < order: + # If the order is set to decrease then the final column of yh + # has not been updated within ODEPACK's LSODA + # implementation because this column will not be used in the + # next iteration. We must rescale this column to make the + # associated step size consistent with the other columns. + yh[:, -1] *= (h / rwork[10]) ** order + + return LsodaDenseOutput(self.t_old, self.t, h, order, yh) + + +class LsodaDenseOutput(DenseOutput): + def __init__(self, t_old, t, h, order, yh): + super().__init__(t_old, t) + self.h = h + self.yh = yh + self.p = np.arange(order + 1) + + def _call_impl(self, t): + if t.ndim == 0: + x = ((t - self.t) / self.h) ** self.p + else: + x = ((t - self.t) / self.h) ** self.p[:, None] + + return np.dot(self.yh, x) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py new file mode 100644 index 0000000000000000000000000000000000000000..0d9109e3564ebaf26ba3d2174ee95d34fde355ac --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py @@ -0,0 +1,574 @@ +import numpy as np +from scipy.linalg import lu_factor, lu_solve +from scipy.sparse import csc_matrix, issparse, eye +from scipy.sparse.linalg import splu +from scipy.optimize._numdiff import group_columns +from .common import (validate_max_step, validate_tol, select_initial_step, + norm, num_jac, EPS, warn_extraneous, + validate_first_step) +from .base import OdeSolver, DenseOutput + +S6 = 6 ** 0.5 + +# Butcher tableau. A is not used directly, see below. +C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1]) +E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3 + +# Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue +# and a complex conjugate pair. They are written below. +MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3) +MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3)) + - 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6))) + +# These are transformation matrices. +T = np.array([ + [0.09443876248897524, -0.14125529502095421, 0.03002919410514742], + [0.25021312296533332, 0.20412935229379994, -0.38294211275726192], + [1, 1, 0]]) +TI = np.array([ + [4.17871859155190428, 0.32768282076106237, 0.52337644549944951], + [-4.17871859155190428, -0.32768282076106237, 0.47662355450055044], + [0.50287263494578682, -2.57192694985560522, 0.59603920482822492]]) +# These linear combinations are used in the algorithm. +TI_REAL = TI[0] +TI_COMPLEX = TI[1] + 1j * TI[2] + +# Interpolator coefficients. +P = np.array([ + [13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6], + [13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6], + [1/3, -8/3, 10/3]]) + + +NEWTON_MAXITER = 6 # Maximum number of Newton iterations. +MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size. +MAX_FACTOR = 10 # Maximum allowed increase in a step size. + + +def solve_collocation_system(fun, t, y, h, Z0, scale, tol, + LU_real, LU_complex, solve_lu): + """Solve the collocation system. + + Parameters + ---------- + fun : callable + Right-hand side of the system. + t : float + Current time. + y : ndarray, shape (n,) + Current state. + h : float + Step to try. + Z0 : ndarray, shape (3, n) + Initial guess for the solution. It determines new values of `y` at + ``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants. + scale : ndarray, shape (n) + Problem tolerance scale, i.e. ``rtol * abs(y) + atol``. + tol : float + Tolerance to which solve the system. This value is compared with + the normalized by `scale` error. + LU_real, LU_complex + LU decompositions of the system Jacobians. + solve_lu : callable + Callable which solves a linear system given a LU decomposition. The + signature is ``solve_lu(LU, b)``. + + Returns + ------- + converged : bool + Whether iterations converged. + n_iter : int + Number of completed iterations. + Z : ndarray, shape (3, n) + Found solution. + rate : float + The rate of convergence. + """ + n = y.shape[0] + M_real = MU_REAL / h + M_complex = MU_COMPLEX / h + + W = TI.dot(Z0) + Z = Z0 + + F = np.empty((3, n)) + ch = h * C + + dW_norm_old = None + dW = np.empty_like(W) + converged = False + rate = None + for k in range(NEWTON_MAXITER): + for i in range(3): + F[i] = fun(t + ch[i], y + Z[i]) + + if not np.all(np.isfinite(F)): + break + + f_real = F.T.dot(TI_REAL) - M_real * W[0] + f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2]) + + dW_real = solve_lu(LU_real, f_real) + dW_complex = solve_lu(LU_complex, f_complex) + + dW[0] = dW_real + dW[1] = dW_complex.real + dW[2] = dW_complex.imag + + dW_norm = norm(dW / scale) + if dW_norm_old is not None: + rate = dW_norm / dW_norm_old + + if (rate is not None and (rate >= 1 or + rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)): + break + + W += dW + Z = T.dot(W) + + if (dW_norm == 0 or + rate is not None and rate / (1 - rate) * dW_norm < tol): + converged = True + break + + dW_norm_old = dW_norm + + return converged, k + 1, Z, rate + + +def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old): + """Predict by which factor to increase/decrease the step size. + + The algorithm is described in [1]_. + + Parameters + ---------- + h_abs, h_abs_old : float + Current and previous values of the step size, `h_abs_old` can be None + (see Notes). + error_norm, error_norm_old : float + Current and previous values of the error norm, `error_norm_old` can + be None (see Notes). + + Returns + ------- + factor : float + Predicted factor. + + Notes + ----- + If `h_abs_old` and `error_norm_old` are both not None then a two-step + algorithm is used, otherwise a one-step algorithm is used. + + References + ---------- + .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8. + """ + if error_norm_old is None or h_abs_old is None or error_norm == 0: + multiplier = 1 + else: + multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25 + + with np.errstate(divide='ignore'): + factor = min(1, multiplier) * error_norm ** -0.25 + + return factor + + +class Radau(OdeSolver): + """Implicit Runge-Kutta method of Radau IIA family of order 5. + + The implementation follows [1]_. The error is controlled with a + third-order accurate embedded formula. A cubic polynomial which satisfies + the collocation conditions is used for the dense output. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + jac : {None, array_like, sparse_matrix, callable}, optional + Jacobian matrix of the right-hand side of the system with respect to + y, required by this method. The Jacobian matrix has shape (n, n) and + its element (i, j) is equal to ``d f_i / d y_j``. + There are three ways to define the Jacobian: + + * If array_like or sparse_matrix, the Jacobian is assumed to + be constant. + * If callable, the Jacobian is assumed to depend on both + t and y; it will be called as ``jac(t, y)`` as necessary. + For the 'Radau' and 'BDF' methods, the return value might be a + sparse matrix. + * If None (default), the Jacobian will be approximated by + finite differences. + + It is generally recommended to provide the Jacobian rather than + relying on a finite-difference approximation. + jac_sparsity : {None, array_like, sparse matrix}, optional + Defines a sparsity structure of the Jacobian matrix for a + finite-difference approximation. Its shape must be (n, n). This argument + is ignored if `jac` is not `None`. If the Jacobian has only few non-zero + elements in *each* row, providing the sparsity structure will greatly + speed up the computations [2]_. A zero entry means that a corresponding + element in the Jacobian is always zero. If None (default), the Jacobian + is assumed to be dense. + vectorized : bool, optional + Whether `fun` can be called in a vectorized fashion. Default is False. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by this method, but may result in slower + execution overall in some circumstances (e.g. small ``len(y0)``). + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number of evaluations of the right-hand side. + njev : int + Number of evaluations of the Jacobian. + nlu : int + Number of LU decompositions. + + References + ---------- + .. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II: + Stiff and Differential-Algebraic Problems", Sec. IV.8. + .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of + sparse Jacobian matrices", Journal of the Institute of Mathematics + and its Applications, 13, pp. 117-120, 1974. + """ + def __init__(self, fun, t0, y0, t_bound, max_step=np.inf, + rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None, + vectorized=False, first_step=None, **extraneous): + warn_extraneous(extraneous) + super().__init__(fun, t0, y0, t_bound, vectorized) + self.y_old = None + self.max_step = validate_max_step(max_step) + self.rtol, self.atol = validate_tol(rtol, atol, self.n) + self.f = self.fun(self.t, self.y) + # Select initial step assuming the same order which is used to control + # the error. + if first_step is None: + self.h_abs = select_initial_step( + self.fun, self.t, self.y, self.f, self.direction, + 3, self.rtol, self.atol) + else: + self.h_abs = validate_first_step(first_step, t0, t_bound) + self.h_abs_old = None + self.error_norm_old = None + + self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5)) + self.sol = None + + self.jac_factor = None + self.jac, self.J = self._validate_jac(jac, jac_sparsity) + if issparse(self.J): + def lu(A): + self.nlu += 1 + return splu(A) + + def solve_lu(LU, b): + return LU.solve(b) + + I = eye(self.n, format='csc') + else: + def lu(A): + self.nlu += 1 + return lu_factor(A, overwrite_a=True) + + def solve_lu(LU, b): + return lu_solve(LU, b, overwrite_b=True) + + I = np.identity(self.n) + + self.lu = lu + self.solve_lu = solve_lu + self.I = I + + self.current_jac = True + self.LU_real = None + self.LU_complex = None + self.Z = None + + def _validate_jac(self, jac, sparsity): + t0 = self.t + y0 = self.y + + if jac is None: + if sparsity is not None: + if issparse(sparsity): + sparsity = csc_matrix(sparsity) + groups = group_columns(sparsity) + sparsity = (sparsity, groups) + + def jac_wrapped(t, y, f): + self.njev += 1 + J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f, + self.atol, self.jac_factor, + sparsity) + return J + J = jac_wrapped(t0, y0, self.f) + elif callable(jac): + J = jac(t0, y0) + self.njev = 1 + if issparse(J): + J = csc_matrix(J) + + def jac_wrapped(t, y, _=None): + self.njev += 1 + return csc_matrix(jac(t, y), dtype=float) + + else: + J = np.asarray(J, dtype=float) + + def jac_wrapped(t, y, _=None): + self.njev += 1 + return np.asarray(jac(t, y), dtype=float) + + if J.shape != (self.n, self.n): + raise ValueError("`jac` is expected to have shape {}, but " + "actually has {}." + .format((self.n, self.n), J.shape)) + else: + if issparse(jac): + J = csc_matrix(jac) + else: + J = np.asarray(jac, dtype=float) + + if J.shape != (self.n, self.n): + raise ValueError("`jac` is expected to have shape {}, but " + "actually has {}." + .format((self.n, self.n), J.shape)) + jac_wrapped = None + + return jac_wrapped, J + + def _step_impl(self): + t = self.t + y = self.y + f = self.f + + max_step = self.max_step + atol = self.atol + rtol = self.rtol + + min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t) + if self.h_abs > max_step: + h_abs = max_step + h_abs_old = None + error_norm_old = None + elif self.h_abs < min_step: + h_abs = min_step + h_abs_old = None + error_norm_old = None + else: + h_abs = self.h_abs + h_abs_old = self.h_abs_old + error_norm_old = self.error_norm_old + + J = self.J + LU_real = self.LU_real + LU_complex = self.LU_complex + + current_jac = self.current_jac + jac = self.jac + + rejected = False + step_accepted = False + message = None + while not step_accepted: + if h_abs < min_step: + return False, self.TOO_SMALL_STEP + + h = h_abs * self.direction + t_new = t + h + + if self.direction * (t_new - self.t_bound) > 0: + t_new = self.t_bound + + h = t_new - t + h_abs = np.abs(h) + + if self.sol is None: + Z0 = np.zeros((3, y.shape[0])) + else: + Z0 = self.sol(t + h * C).T - y + + scale = atol + np.abs(y) * rtol + + converged = False + while not converged: + if LU_real is None or LU_complex is None: + LU_real = self.lu(MU_REAL / h * self.I - J) + LU_complex = self.lu(MU_COMPLEX / h * self.I - J) + + converged, n_iter, Z, rate = solve_collocation_system( + self.fun, t, y, h, Z0, scale, self.newton_tol, + LU_real, LU_complex, self.solve_lu) + + if not converged: + if current_jac: + break + + J = self.jac(t, y, f) + current_jac = True + LU_real = None + LU_complex = None + + if not converged: + h_abs *= 0.5 + LU_real = None + LU_complex = None + continue + + y_new = y + Z[-1] + ZE = Z.T.dot(E) / h + error = self.solve_lu(LU_real, f + ZE) + scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol + error_norm = norm(error / scale) + safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER + + n_iter) + + if rejected and error_norm > 1: + error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE) + error_norm = norm(error / scale) + + if error_norm > 1: + factor = predict_factor(h_abs, h_abs_old, + error_norm, error_norm_old) + h_abs *= max(MIN_FACTOR, safety * factor) + + LU_real = None + LU_complex = None + rejected = True + else: + step_accepted = True + + recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3 + + factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old) + factor = min(MAX_FACTOR, safety * factor) + + if not recompute_jac and factor < 1.2: + factor = 1 + else: + LU_real = None + LU_complex = None + + f_new = self.fun(t_new, y_new) + if recompute_jac: + J = jac(t_new, y_new, f_new) + current_jac = True + elif jac is not None: + current_jac = False + + self.h_abs_old = self.h_abs + self.error_norm_old = error_norm + + self.h_abs = h_abs * factor + + self.y_old = y + + self.t = t_new + self.y = y_new + self.f = f_new + + self.Z = Z + + self.LU_real = LU_real + self.LU_complex = LU_complex + self.current_jac = current_jac + self.J = J + + self.t_old = t + self.sol = self._compute_dense_output() + + return step_accepted, message + + def _compute_dense_output(self): + Q = np.dot(self.Z.T, P) + return RadauDenseOutput(self.t_old, self.t, self.y_old, Q) + + def _dense_output_impl(self): + return self.sol + + +class RadauDenseOutput(DenseOutput): + def __init__(self, t_old, t, y_old, Q): + super().__init__(t_old, t) + self.h = t - t_old + self.Q = Q + self.order = Q.shape[1] - 1 + self.y_old = y_old + + def _call_impl(self, t): + x = (t - self.t_old) / self.h + if t.ndim == 0: + p = np.tile(x, self.order + 1) + p = np.cumprod(p) + else: + p = np.tile(x, (self.order + 1, 1)) + p = np.cumprod(p, axis=0) + # Here we don't multiply by h, not a mistake. + y = np.dot(self.Q, p) + if y.ndim == 2: + y += self.y_old[:, None] + else: + y += self.y_old + + return y diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py new file mode 100644 index 0000000000000000000000000000000000000000..b6076f950156fede284f398407327051558e7c7b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py @@ -0,0 +1,601 @@ +import numpy as np +from .base import OdeSolver, DenseOutput +from .common import (validate_max_step, validate_tol, select_initial_step, + norm, warn_extraneous, validate_first_step) +from . import dop853_coefficients + +# Multiply steps computed from asymptotic behaviour of errors by this. +SAFETY = 0.9 + +MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size. +MAX_FACTOR = 10 # Maximum allowed increase in a step size. + + +def rk_step(fun, t, y, f, h, A, B, C, K): + """Perform a single Runge-Kutta step. + + This function computes a prediction of an explicit Runge-Kutta method and + also estimates the error of a less accurate method. + + Notation for Butcher tableau is as in [1]_. + + Parameters + ---------- + fun : callable + Right-hand side of the system. + t : float + Current time. + y : ndarray, shape (n,) + Current state. + f : ndarray, shape (n,) + Current value of the derivative, i.e., ``fun(x, y)``. + h : float + Step to use. + A : ndarray, shape (n_stages, n_stages) + Coefficients for combining previous RK stages to compute the next + stage. For explicit methods the coefficients at and above the main + diagonal are zeros. + B : ndarray, shape (n_stages,) + Coefficients for combining RK stages for computing the final + prediction. + C : ndarray, shape (n_stages,) + Coefficients for incrementing time for consecutive RK stages. + The value for the first stage is always zero. + K : ndarray, shape (n_stages + 1, n) + Storage array for putting RK stages here. Stages are stored in rows. + The last row is a linear combination of the previous rows with + coefficients + + Returns + ------- + y_new : ndarray, shape (n,) + Solution at t + h computed with a higher accuracy. + f_new : ndarray, shape (n,) + Derivative ``fun(t + h, y_new)``. + + References + ---------- + .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations I: Nonstiff Problems", Sec. II.4. + """ + K[0] = f + for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1): + dy = np.dot(K[:s].T, a[:s]) * h + K[s] = fun(t + c * h, y + dy) + + y_new = y + h * np.dot(K[:-1].T, B) + f_new = fun(t + h, y_new) + + K[-1] = f_new + + return y_new, f_new + + +class RungeKutta(OdeSolver): + """Base class for explicit Runge-Kutta methods.""" + C: np.ndarray = NotImplemented + A: np.ndarray = NotImplemented + B: np.ndarray = NotImplemented + E: np.ndarray = NotImplemented + P: np.ndarray = NotImplemented + order: int = NotImplemented + error_estimator_order: int = NotImplemented + n_stages: int = NotImplemented + + def __init__(self, fun, t0, y0, t_bound, max_step=np.inf, + rtol=1e-3, atol=1e-6, vectorized=False, + first_step=None, **extraneous): + warn_extraneous(extraneous) + super().__init__(fun, t0, y0, t_bound, vectorized, + support_complex=True) + self.y_old = None + self.max_step = validate_max_step(max_step) + self.rtol, self.atol = validate_tol(rtol, atol, self.n) + self.f = self.fun(self.t, self.y) + if first_step is None: + self.h_abs = select_initial_step( + self.fun, self.t, self.y, self.f, self.direction, + self.error_estimator_order, self.rtol, self.atol) + else: + self.h_abs = validate_first_step(first_step, t0, t_bound) + self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype) + self.error_exponent = -1 / (self.error_estimator_order + 1) + self.h_previous = None + + def _estimate_error(self, K, h): + return np.dot(K.T, self.E) * h + + def _estimate_error_norm(self, K, h, scale): + return norm(self._estimate_error(K, h) / scale) + + def _step_impl(self): + t = self.t + y = self.y + + max_step = self.max_step + rtol = self.rtol + atol = self.atol + + min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t) + + if self.h_abs > max_step: + h_abs = max_step + elif self.h_abs < min_step: + h_abs = min_step + else: + h_abs = self.h_abs + + step_accepted = False + step_rejected = False + + while not step_accepted: + if h_abs < min_step: + return False, self.TOO_SMALL_STEP + + h = h_abs * self.direction + t_new = t + h + + if self.direction * (t_new - self.t_bound) > 0: + t_new = self.t_bound + + h = t_new - t + h_abs = np.abs(h) + + y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A, + self.B, self.C, self.K) + scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol + error_norm = self._estimate_error_norm(self.K, h, scale) + + if error_norm < 1: + if error_norm == 0: + factor = MAX_FACTOR + else: + factor = min(MAX_FACTOR, + SAFETY * error_norm ** self.error_exponent) + + if step_rejected: + factor = min(1, factor) + + h_abs *= factor + + step_accepted = True + else: + h_abs *= max(MIN_FACTOR, + SAFETY * error_norm ** self.error_exponent) + step_rejected = True + + self.h_previous = h + self.y_old = y + + self.t = t_new + self.y = y_new + + self.h_abs = h_abs + self.f = f_new + + return True, None + + def _dense_output_impl(self): + Q = self.K.T.dot(self.P) + return RkDenseOutput(self.t_old, self.t, self.y_old, Q) + + +class RK23(RungeKutta): + """Explicit Runge-Kutta method of order 3(2). + + This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled + assuming accuracy of the second-order method, but steps are taken using the + third-order accurate formula (local extrapolation is done). A cubic Hermite + polynomial is used for the dense output. + + Can be applied in the complex domain. + + Parameters + ---------- + fun : callable + Right-hand side of the system: the time derivative of the state ``y`` + at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a + scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must + return an array of the same shape as ``y``. See `vectorized` for more + information. + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + vectorized : bool, optional + Whether `fun` may be called in a vectorized fashion. False (default) + is recommended for this solver. + + If ``vectorized`` is False, `fun` will always be called with ``y`` of + shape ``(n,)``, where ``n = len(y0)``. + + If ``vectorized`` is True, `fun` may be called with ``y`` of shape + ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave + such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of + the returned array is the time derivative of the state corresponding + with a column of ``y``). + + Setting ``vectorized=True`` allows for faster finite difference + approximation of the Jacobian by methods 'Radau' and 'BDF', but + will result in slower execution for this solver. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number evaluations of the system's right-hand side. + njev : int + Number of evaluations of the Jacobian. + Is always 0 for this solver as it does not use the Jacobian. + nlu : int + Number of LU decompositions. Is always 0 for this solver. + + References + ---------- + .. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas", + Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989. + """ + order = 3 + error_estimator_order = 2 + n_stages = 3 + C = np.array([0, 1/2, 3/4]) + A = np.array([ + [0, 0, 0], + [1/2, 0, 0], + [0, 3/4, 0] + ]) + B = np.array([2/9, 1/3, 4/9]) + E = np.array([5/72, -1/12, -1/9, 1/8]) + P = np.array([[1, -4 / 3, 5 / 9], + [0, 1, -2/3], + [0, 4/3, -8/9], + [0, -1, 1]]) + + +class RK45(RungeKutta): + """Explicit Runge-Kutta method of order 5(4). + + This uses the Dormand-Prince pair of formulas [1]_. The error is controlled + assuming accuracy of the fourth-order method accuracy, but steps are taken + using the fifth-order accurate formula (local extrapolation is done). + A quartic interpolation polynomial is used for the dense output [2]_. + + Can be applied in the complex domain. + + Parameters + ---------- + fun : callable + Right-hand side of the system. The calling signature is ``fun(t, y)``. + Here ``t`` is a scalar, and there are two options for the ndarray ``y``: + It can either have shape (n,); then ``fun`` must return array_like with + shape (n,). Alternatively it can have shape (n, k); then ``fun`` + must return an array_like with shape (n, k), i.e., each column + corresponds to a single column in ``y``. The choice between the two + options is determined by `vectorized` argument (see below). + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e., the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + vectorized : bool, optional + Whether `fun` is implemented in a vectorized fashion. Default is False. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number evaluations of the system's right-hand side. + njev : int + Number of evaluations of the Jacobian. + Is always 0 for this solver as it does not use the Jacobian. + nlu : int + Number of LU decompositions. Is always 0 for this solver. + + References + ---------- + .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta + formulae", Journal of Computational and Applied Mathematics, Vol. 6, + No. 1, pp. 19-26, 1980. + .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics + of Computation,, Vol. 46, No. 173, pp. 135-150, 1986. + """ + order = 5 + error_estimator_order = 4 + n_stages = 6 + C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1]) + A = np.array([ + [0, 0, 0, 0, 0], + [1/5, 0, 0, 0, 0], + [3/40, 9/40, 0, 0, 0], + [44/45, -56/15, 32/9, 0, 0], + [19372/6561, -25360/2187, 64448/6561, -212/729, 0], + [9017/3168, -355/33, 46732/5247, 49/176, -5103/18656] + ]) + B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84]) + E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525, + 1/40]) + # Corresponds to the optimum value of c_6 from [2]_. + P = np.array([ + [1, -8048581381/2820520608, 8663915743/2820520608, + -12715105075/11282082432], + [0, 0, 0, 0], + [0, 131558114200/32700410799, -68118460800/10900136933, + 87487479700/32700410799], + [0, -1754552775/470086768, 14199869525/1410260304, + -10690763975/1880347072], + [0, 127303824393/49829197408, -318862633887/49829197408, + 701980252875 / 199316789632], + [0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844], + [0, 40617522/29380423, -110615467/29380423, 69997945/29380423]]) + + +class DOP853(RungeKutta): + """Explicit Runge-Kutta method of order 8. + + This is a Python implementation of "DOP853" algorithm originally written + in Fortran [1]_, [2]_. Note that this is not a literal translation, but + the algorithmic core and coefficients are the same. + + Can be applied in the complex domain. + + Parameters + ---------- + fun : callable + Right-hand side of the system. The calling signature is ``fun(t, y)``. + Here, ``t`` is a scalar, and there are two options for the ndarray ``y``: + It can either have shape (n,); then ``fun`` must return array_like with + shape (n,). Alternatively it can have shape (n, k); then ``fun`` + must return an array_like with shape (n, k), i.e. each column + corresponds to a single column in ``y``. The choice between the two + options is determined by `vectorized` argument (see below). + t0 : float + Initial time. + y0 : array_like, shape (n,) + Initial state. + t_bound : float + Boundary time - the integration won't continue beyond it. It also + determines the direction of the integration. + first_step : float or None, optional + Initial step size. Default is ``None`` which means that the algorithm + should choose. + max_step : float, optional + Maximum allowed step size. Default is np.inf, i.e. the step size is not + bounded and determined solely by the solver. + rtol, atol : float and array_like, optional + Relative and absolute tolerances. The solver keeps the local error + estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a + relative accuracy (number of correct digits), while `atol` controls + absolute accuracy (number of correct decimal places). To achieve the + desired `rtol`, set `atol` to be smaller than the smallest value that + can be expected from ``rtol * abs(y)`` so that `rtol` dominates the + allowable error. If `atol` is larger than ``rtol * abs(y)`` the + number of correct digits is not guaranteed. Conversely, to achieve the + desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller + than `atol`. If components of y have different scales, it might be + beneficial to set different `atol` values for different components by + passing array_like with shape (n,) for `atol`. Default values are + 1e-3 for `rtol` and 1e-6 for `atol`. + vectorized : bool, optional + Whether `fun` is implemented in a vectorized fashion. Default is False. + + Attributes + ---------- + n : int + Number of equations. + status : string + Current status of the solver: 'running', 'finished' or 'failed'. + t_bound : float + Boundary time. + direction : float + Integration direction: +1 or -1. + t : float + Current time. + y : ndarray + Current state. + t_old : float + Previous time. None if no steps were made yet. + step_size : float + Size of the last successful step. None if no steps were made yet. + nfev : int + Number evaluations of the system's right-hand side. + njev : int + Number of evaluations of the Jacobian. Is always 0 for this solver + as it does not use the Jacobian. + nlu : int + Number of LU decompositions. Is always 0 for this solver. + + References + ---------- + .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential + Equations I: Nonstiff Problems", Sec. II. + .. [2] `Page with original Fortran code of DOP853 + `_. + """ + n_stages = dop853_coefficients.N_STAGES + order = 8 + error_estimator_order = 7 + A = dop853_coefficients.A[:n_stages, :n_stages] + B = dop853_coefficients.B + C = dop853_coefficients.C[:n_stages] + E3 = dop853_coefficients.E3 + E5 = dop853_coefficients.E5 + D = dop853_coefficients.D + + A_EXTRA = dop853_coefficients.A[n_stages + 1:] + C_EXTRA = dop853_coefficients.C[n_stages + 1:] + + def __init__(self, fun, t0, y0, t_bound, max_step=np.inf, + rtol=1e-3, atol=1e-6, vectorized=False, + first_step=None, **extraneous): + super().__init__(fun, t0, y0, t_bound, max_step, rtol, atol, + vectorized, first_step, **extraneous) + self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED, + self.n), dtype=self.y.dtype) + self.K = self.K_extended[:self.n_stages + 1] + + def _estimate_error(self, K, h): # Left for testing purposes. + err5 = np.dot(K.T, self.E5) + err3 = np.dot(K.T, self.E3) + denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3)) + correction_factor = np.ones_like(err5) + mask = denom > 0 + correction_factor[mask] = np.abs(err5[mask]) / denom[mask] + return h * err5 * correction_factor + + def _estimate_error_norm(self, K, h, scale): + err5 = np.dot(K.T, self.E5) / scale + err3 = np.dot(K.T, self.E3) / scale + err5_norm_2 = np.linalg.norm(err5)**2 + err3_norm_2 = np.linalg.norm(err3)**2 + if err5_norm_2 == 0 and err3_norm_2 == 0: + return 0.0 + denom = err5_norm_2 + 0.01 * err3_norm_2 + return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale)) + + def _dense_output_impl(self): + K = self.K_extended + h = self.h_previous + for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA), + start=self.n_stages + 1): + dy = np.dot(K[:s].T, a[:s]) * h + K[s] = self.fun(self.t_old + c * h, self.y_old + dy) + + F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n), + dtype=self.y_old.dtype) + + f_old = K[0] + delta_y = self.y - self.y_old + + F[0] = delta_y + F[1] = h * f_old - delta_y + F[2] = 2 * delta_y - h * (self.f + f_old) + F[3:] = h * np.dot(self.D, K) + + return Dop853DenseOutput(self.t_old, self.t, self.y_old, F) + + +class RkDenseOutput(DenseOutput): + def __init__(self, t_old, t, y_old, Q): + super().__init__(t_old, t) + self.h = t - t_old + self.Q = Q + self.order = Q.shape[1] - 1 + self.y_old = y_old + + def _call_impl(self, t): + x = (t - self.t_old) / self.h + if t.ndim == 0: + p = np.tile(x, self.order + 1) + p = np.cumprod(p) + else: + p = np.tile(x, (self.order + 1, 1)) + p = np.cumprod(p, axis=0) + y = self.h * np.dot(self.Q, p) + if y.ndim == 2: + y += self.y_old[:, None] + else: + y += self.y_old + + return y + + +class Dop853DenseOutput(DenseOutput): + def __init__(self, t_old, t, y_old, F): + super().__init__(t_old, t) + self.h = t - t_old + self.F = F + self.y_old = y_old + + def _call_impl(self, t): + x = (t - self.t_old) / self.h + + if t.ndim == 0: + y = np.zeros_like(self.y_old) + else: + x = x[:, None] + y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype) + + for i, f in enumerate(reversed(self.F)): + y += f + if i % 2 == 0: + y *= x + else: + y *= 1 - x + y += self.y_old + + return y.T diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py new file mode 100644 index 0000000000000000000000000000000000000000..1c542c5380eb2f5f7e827a5b15743a68cd0f3f39 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py @@ -0,0 +1,1135 @@ +from itertools import product +from numpy.testing import (assert_, assert_allclose, assert_array_less, + assert_equal, assert_no_warnings, suppress_warnings) +import pytest +from pytest import raises as assert_raises +import numpy as np +from scipy.optimize._numdiff import group_columns +from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA +from scipy.integrate import OdeSolution +from scipy.integrate._ivp.common import num_jac +from scipy.integrate._ivp.base import ConstantDenseOutput +from scipy.sparse import coo_matrix, csc_matrix + + +def fun_zero(t, y): + return np.zeros_like(y) + + +def fun_linear(t, y): + return np.array([-y[0] - 5 * y[1], y[0] + y[1]]) + + +def jac_linear(): + return np.array([[-1, -5], [1, 1]]) + + +def sol_linear(t): + return np.vstack((-5 * np.sin(2 * t), + 2 * np.cos(2 * t) + np.sin(2 * t))) + + +def fun_rational(t, y): + return np.array([y[1] / t, + y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))]) + + +def fun_rational_vectorized(t, y): + return np.vstack((y[1] / t, + y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1)))) + + +def jac_rational(t, y): + return np.array([ + [0, 1 / t], + [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2), + (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))] + ]) + + +def jac_rational_sparse(t, y): + return csc_matrix([ + [0, 1 / t], + [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2), + (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))] + ]) + + +def sol_rational(t): + return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2)) + + +def fun_medazko(t, y): + n = y.shape[0] // 2 + k = 100 + c = 4 + + phi = 2 if t <= 5 else 0 + y = np.hstack((phi, 0, y, y[-2])) + + d = 1 / n + j = np.arange(n) + 1 + alpha = 2 * (j * d - 1) ** 3 / c ** 2 + beta = (j * d - 1) ** 4 / c ** 2 + + j_2_p1 = 2 * j + 2 + j_2_m3 = 2 * j - 2 + j_2_m1 = 2 * j + j_2 = 2 * j + 1 + + f = np.empty(2 * n) + f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) + + beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 - + k * y[j_2_m1] * y[j_2]) + f[1::2] = -k * y[j_2] * y[j_2_m1] + + return f + + +def medazko_sparsity(n): + cols = [] + rows = [] + + i = np.arange(n) * 2 + + cols.append(i[1:]) + rows.append(i[1:] - 2) + + cols.append(i) + rows.append(i) + + cols.append(i) + rows.append(i + 1) + + cols.append(i[:-1]) + rows.append(i[:-1] + 2) + + i = np.arange(n) * 2 + 1 + + cols.append(i) + rows.append(i) + + cols.append(i) + rows.append(i - 1) + + cols = np.hstack(cols) + rows = np.hstack(rows) + + return coo_matrix((np.ones_like(cols), (cols, rows))) + + +def fun_complex(t, y): + return -y + + +def jac_complex(t, y): + return -np.eye(y.shape[0]) + + +def jac_complex_sparse(t, y): + return csc_matrix(jac_complex(t, y)) + + +def sol_complex(t): + y = (0.5 + 1j) * np.exp(-t) + return y.reshape((1, -1)) + + +def fun_event_dense_output_LSODA(t, y): + return y * (t - 2) + + +def jac_event_dense_output_LSODA(t, y): + return t - 2 + + +def sol_event_dense_output_LSODA(t): + return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6) + + +def compute_error(y, y_true, rtol, atol): + e = (y - y_true) / (atol + rtol * np.abs(y_true)) + return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0]) + + +def test_integration(): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + + for vectorized, method, t_span, jac in product( + [False, True], + ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'], + [[5, 9], [5, 1]], + [None, jac_rational, jac_rational_sparse]): + + if vectorized: + fun = fun_rational_vectorized + else: + fun = fun_rational + + with suppress_warnings() as sup: + sup.filter(UserWarning, + "The following arguments have no effect for a chosen " + "solver: `jac`") + res = solve_ivp(fun, t_span, y0, rtol=rtol, + atol=atol, method=method, dense_output=True, + jac=jac, vectorized=vectorized) + assert_equal(res.t[0], t_span[0]) + assert_(res.t_events is None) + assert_(res.y_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + if method == 'DOP853': + # DOP853 spends more functions evaluation because it doesn't + # have enough time to develop big enough step size. + assert_(res.nfev < 50) + else: + assert_(res.nfev < 40) + + if method in ['RK23', 'RK45', 'DOP853', 'LSODA']: + assert_equal(res.njev, 0) + assert_equal(res.nlu, 0) + else: + assert_(0 < res.njev < 3) + assert_(0 < res.nlu < 10) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + tc = np.linspace(*t_span) + yc_true = sol_rational(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 5)) + + tc = (t_span[0] + t_span[-1]) / 2 + yc_true = sol_rational(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 5)) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15) + + +def test_integration_complex(): + rtol = 1e-3 + atol = 1e-6 + y0 = [0.5 + 1j] + t_span = [0, 1] + tc = np.linspace(t_span[0], t_span[1]) + for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'], + [None, jac_complex, jac_complex_sparse]): + with suppress_warnings() as sup: + sup.filter(UserWarning, + "The following arguments have no effect for a chosen " + "solver: `jac`") + res = solve_ivp(fun_complex, t_span, y0, method=method, + dense_output=True, rtol=rtol, atol=atol, jac=jac) + + assert_equal(res.t[0], t_span[0]) + assert_(res.t_events is None) + assert_(res.y_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + if method == 'DOP853': + assert res.nfev < 35 + else: + assert res.nfev < 25 + + if method == 'BDF': + assert_equal(res.njev, 1) + assert res.nlu < 6 + else: + assert res.njev == 0 + assert res.nlu == 0 + + y_true = sol_complex(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert np.all(e < 5) + + yc_true = sol_complex(tc) + yc = res.sol(tc) + e = compute_error(yc, yc_true, rtol, atol) + + assert np.all(e < 5) + + +def test_integration_sparse_difference(): + n = 200 + t_span = [0, 20] + y0 = np.zeros(2 * n) + y0[1::2] = 1 + sparsity = medazko_sparsity(n) + + for method in ['BDF', 'Radau']: + res = solve_ivp(fun_medazko, t_span, y0, method=method, + jac_sparsity=sparsity) + + assert_equal(res.t[0], t_span[0]) + assert_(res.t_events is None) + assert_(res.y_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2) + assert_allclose(res.y[79, -1], 0, atol=1e-3) + assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2) + assert_allclose(res.y[149, -1], 0, atol=1e-3) + assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2) + assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3) + assert_allclose(res.y[238, -1], 0, atol=1e-3) + assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2) + + +def test_integration_const_jac(): + rtol = 1e-3 + atol = 1e-6 + y0 = [0, 2] + t_span = [0, 2] + J = jac_linear() + J_sparse = csc_matrix(J) + + for method, jac in product(['Radau', 'BDF'], [J, J_sparse]): + res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol, + method=method, dense_output=True, jac=jac) + assert_equal(res.t[0], t_span[0]) + assert_(res.t_events is None) + assert_(res.y_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + assert_(res.nfev < 100) + assert_equal(res.njev, 0) + assert_(0 < res.nlu < 15) + + y_true = sol_linear(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 10)) + + tc = np.linspace(*t_span) + yc_true = sol_linear(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 15)) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14) + + +@pytest.mark.slow +@pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA']) +def test_integration_stiff(method): + rtol = 1e-6 + atol = 1e-6 + y0 = [1e4, 0, 0] + tspan = [0, 1e8] + + def fun_robertson(t, state): + x, y, z = state + return [ + -0.04 * x + 1e4 * y * z, + 0.04 * x - 1e4 * y * z - 3e7 * y * y, + 3e7 * y * y, + ] + + res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol, + atol=atol, method=method) + + # If the stiff mode is not activated correctly, these numbers will be much bigger + assert res.nfev < 5000 + assert res.njev < 200 + + +def test_events(): + def event_rational_1(t, y): + return y[0] - y[1] ** 0.7 + + def event_rational_2(t, y): + return y[1] ** 0.6 - y[0] + + def event_rational_3(t, y): + return t - 7.4 + + event_rational_3.terminal = True + + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 1) + assert_(5.3 < res.t_events[0][0] < 5.7) + assert_(7.3 < res.t_events[1][0] < 7.7) + + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + + event_rational_1.direction = 1 + event_rational_2.direction = 1 + res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 0) + assert_(5.3 < res.t_events[0][0] < 5.7) + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (0,)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + + event_rational_1.direction = -1 + event_rational_2.direction = -1 + res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 0) + assert_equal(res.t_events[1].size, 1) + assert_(7.3 < res.t_events[1][0] < 7.7) + assert_equal(res.y_events[0].shape, (0,)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + + event_rational_1.direction = 0 + event_rational_2.direction = 0 + + res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method, + events=(event_rational_1, event_rational_2, + event_rational_3), dense_output=True) + assert_equal(res.status, 1) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 0) + assert_equal(res.t_events[2].size, 1) + assert_(5.3 < res.t_events[0][0] < 5.7) + assert_(7.3 < res.t_events[2][0] < 7.5) + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (0,)) + assert_equal(res.y_events[2].shape, (1, 2)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + assert np.isclose( + event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0) + + res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method, + events=event_rational_1, dense_output=True) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_(5.3 < res.t_events[0][0] < 5.7) + + assert_equal(res.y_events[0].shape, (1, 2)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + + # Also test that termination by event doesn't break interpolants. + tc = np.linspace(res.t[0], res.t[-1]) + yc_true = sol_rational(tc) + yc = res.sol(tc) + e = compute_error(yc, yc_true, 1e-3, 1e-6) + assert_(np.all(e < 5)) + + # Test that the y_event matches solution + assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0], + rtol=1e-3, atol=1e-6) + + # Test in backward direction. + event_rational_1.direction = 0 + event_rational_2.direction = 0 + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 1) + assert_(5.3 < res.t_events[0][0] < 5.7) + assert_(7.3 < res.t_events[1][0] < 7.7) + + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + + event_rational_1.direction = -1 + event_rational_2.direction = -1 + res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 1) + assert_equal(res.t_events[1].size, 0) + assert_(5.3 < res.t_events[0][0] < 5.7) + + assert_equal(res.y_events[0].shape, (1, 2)) + assert_equal(res.y_events[1].shape, (0,)) + assert np.isclose( + event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0) + + event_rational_1.direction = 1 + event_rational_2.direction = 1 + res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method, + events=(event_rational_1, event_rational_2)) + assert_equal(res.status, 0) + assert_equal(res.t_events[0].size, 0) + assert_equal(res.t_events[1].size, 1) + assert_(7.3 < res.t_events[1][0] < 7.7) + + assert_equal(res.y_events[0].shape, (0,)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + + event_rational_1.direction = 0 + event_rational_2.direction = 0 + + res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method, + events=(event_rational_1, event_rational_2, + event_rational_3), dense_output=True) + assert_equal(res.status, 1) + assert_equal(res.t_events[0].size, 0) + assert_equal(res.t_events[1].size, 1) + assert_equal(res.t_events[2].size, 1) + assert_(7.3 < res.t_events[1][0] < 7.7) + assert_(7.3 < res.t_events[2][0] < 7.5) + + assert_equal(res.y_events[0].shape, (0,)) + assert_equal(res.y_events[1].shape, (1, 2)) + assert_equal(res.y_events[2].shape, (1, 2)) + assert np.isclose( + event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0) + assert np.isclose( + event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0) + + # Also test that termination by event doesn't break interpolants. + tc = np.linspace(res.t[-1], res.t[0]) + yc_true = sol_rational(tc) + yc = res.sol(tc) + e = compute_error(yc, yc_true, 1e-3, 1e-6) + assert_(np.all(e < 5)) + + assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0], + rtol=1e-3, atol=1e-6) + assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0], + rtol=1e-3, atol=1e-6) + + +def _get_harmonic_oscillator(): + def f(t, y): + return [y[1], -y[0]] + + def event(t, y): + return y[0] + + return f, event + + +@pytest.mark.parametrize('n_events', [3, 4]) +def test_event_terminal_integer(n_events): + f, event = _get_harmonic_oscillator() + event.terminal = n_events + res = solve_ivp(f, (0, 100), [1, 0], events=event) + assert len(res.t_events[0]) == n_events + assert len(res.y_events[0]) == n_events + assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14) + + +def test_event_terminal_iv(): + f, event = _get_harmonic_oscillator() + args = (f, (0, 100), [1, 0]) + + event.terminal = None + res = solve_ivp(*args, events=event) + event.terminal = 0 + ref = solve_ivp(*args, events=event) + assert_allclose(res.t_events, ref.t_events) + + message = "The `terminal` attribute..." + event.terminal = -1 + with pytest.raises(ValueError, match=message): + solve_ivp(*args, events=event) + event.terminal = 3.5 + with pytest.raises(ValueError, match=message): + solve_ivp(*args, events=event) + + +def test_max_step(): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]: + for t_span in ([5, 9], [5, 1]): + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, + max_step=0.5, atol=atol, method=method, + dense_output=True) + assert_equal(res.t[0], t_span[0]) + assert_equal(res.t[-1], t_span[-1]) + assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15)) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + tc = np.linspace(*t_span) + yc_true = sol_rational(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 5)) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15) + + assert_raises(ValueError, method, fun_rational, t_span[0], y0, + t_span[1], max_step=-1) + + if method is not LSODA: + solver = method(fun_rational, t_span[0], y0, t_span[1], + rtol=rtol, atol=atol, max_step=1e-20) + message = solver.step() + + assert_equal(solver.status, 'failed') + assert_("step size is less" in message) + assert_raises(RuntimeError, solver.step) + + +def test_first_step(): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + first_step = 0.1 + for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]: + for t_span in ([5, 9], [5, 1]): + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, + max_step=0.5, atol=atol, method=method, + dense_output=True, first_step=first_step) + + assert_equal(res.t[0], t_span[0]) + assert_equal(res.t[-1], t_span[-1]) + assert_allclose(first_step, np.abs(res.t[1] - 5)) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + tc = np.linspace(*t_span) + yc_true = sol_rational(tc) + yc = res.sol(tc) + + e = compute_error(yc, yc_true, rtol, atol) + assert_(np.all(e < 5)) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15) + + assert_raises(ValueError, method, fun_rational, t_span[0], y0, + t_span[1], first_step=-1) + assert_raises(ValueError, method, fun_rational, t_span[0], y0, + t_span[1], first_step=5) + + +def test_t_eval(): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + for t_span in ([5, 9], [5, 1]): + t_eval = np.linspace(t_span[0], t_span[1], 10) + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + t_eval = [5, 5.01, 7, 8, 8.01, 9] + res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1] + res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + t_eval = [5.01, 7, 8, 8.01] + res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + t_eval = [4.99, 3, 1.5, 1.1, 1.01] + res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol, + t_eval=t_eval) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + t_eval = [4, 6] + assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0, + rtol=rtol, atol=atol, t_eval=t_eval) + + +def test_t_eval_dense_output(): + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + t_span = [5, 9] + t_eval = np.linspace(t_span[0], t_span[1], 10) + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol, + t_eval=t_eval) + res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol, + t_eval=t_eval, dense_output=True) + assert_equal(res.t, t_eval) + assert_(res.t_events is None) + assert_(res.success) + assert_equal(res.status, 0) + + assert_equal(res.t, res_d.t) + assert_equal(res.y, res_d.y) + assert_(res_d.t_events is None) + assert_(res_d.success) + assert_equal(res_d.status, 0) + + # if t and y are equal only test values for one case + y_true = sol_rational(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_(np.all(e < 5)) + + +def test_t_eval_early_event(): + def early_event(t, y): + return t - 7 + + early_event.terminal = True + + rtol = 1e-3 + atol = 1e-6 + y0 = [1/3, 2/9] + t_span = [5, 9] + t_eval = np.linspace(7.5, 9, 16) + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + with suppress_warnings() as sup: + sup.filter(UserWarning, + "The following arguments have no effect for a chosen " + "solver: `jac`") + res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol, + method=method, t_eval=t_eval, events=early_event, + jac=jac_rational) + assert res.success + assert res.message == 'A termination event occurred.' + assert res.status == 1 + assert not res.t and not res.y + assert len(res.t_events) == 1 + assert res.t_events[0].size == 1 + assert res.t_events[0][0] == 7 + + +def test_event_dense_output_LSODA(): + def event_lsoda(t, y): + return y[0] - 2.02e-5 + + rtol = 1e-3 + atol = 1e-6 + y0 = [0.05] + t_span = [-2, 2] + first_step = 1e-3 + res = solve_ivp( + fun_event_dense_output_LSODA, + t_span, + y0, + method="LSODA", + dense_output=True, + events=event_lsoda, + first_step=first_step, + max_step=1, + rtol=rtol, + atol=atol, + jac=jac_event_dense_output_LSODA, + ) + + assert_equal(res.t[0], t_span[0]) + assert_equal(res.t[-1], t_span[-1]) + assert_allclose(first_step, np.abs(res.t[1] - t_span[0])) + assert res.success + assert_equal(res.status, 0) + + y_true = sol_event_dense_output_LSODA(res.t) + e = compute_error(res.y, y_true, rtol, atol) + assert_array_less(e, 5) + + tc = np.linspace(*t_span) + yc_true = sol_event_dense_output_LSODA(tc) + yc = res.sol(tc) + e = compute_error(yc, yc_true, rtol, atol) + assert_array_less(e, 5) + + assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15) + + +def test_no_integration(): + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3], + method=method, dense_output=True) + assert_equal(sol.sol(4), [2, 3]) + assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]]) + + +def test_no_integration_class(): + for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]: + solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0) + solver.step() + assert_equal(solver.status, 'finished') + sol = solver.dense_output() + assert_equal(sol(0.0), [10.0, 0.0]) + assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]]) + + solver = method(lambda t, y: -y, 0.0, [], np.inf) + solver.step() + assert_equal(solver.status, 'finished') + sol = solver.dense_output() + assert_equal(sol(100.0), []) + assert_equal(sol([0, 1, 2]), np.empty((0, 3))) + + +def test_empty(): + def fun(t, y): + return np.zeros((0,)) + + y0 = np.zeros((0,)) + + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0, + method=method, dense_output=True) + assert_equal(sol.sol(10), np.zeros((0,))) + assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3))) + + for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']: + sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0, + method=method, dense_output=True) + assert_equal(sol.sol(10), np.zeros((0,))) + assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3))) + + +def test_ConstantDenseOutput(): + sol = ConstantDenseOutput(0, 1, np.array([1, 2])) + assert_allclose(sol(1.5), [1, 2]) + assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]]) + + sol = ConstantDenseOutput(0, 1, np.array([])) + assert_allclose(sol(1.5), np.empty(0)) + assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3))) + + +def test_classes(): + y0 = [1 / 3, 2 / 9] + for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]: + solver = cls(fun_rational, 5, y0, np.inf) + assert_equal(solver.n, 2) + assert_equal(solver.status, 'running') + assert_equal(solver.t_bound, np.inf) + assert_equal(solver.direction, 1) + assert_equal(solver.t, 5) + assert_equal(solver.y, y0) + assert_(solver.step_size is None) + if cls is not LSODA: + assert_(solver.nfev > 0) + assert_(solver.njev >= 0) + assert_equal(solver.nlu, 0) + else: + assert_equal(solver.nfev, 0) + assert_equal(solver.njev, 0) + assert_equal(solver.nlu, 0) + + assert_raises(RuntimeError, solver.dense_output) + + message = solver.step() + assert_equal(solver.status, 'running') + assert_equal(message, None) + assert_equal(solver.n, 2) + assert_equal(solver.t_bound, np.inf) + assert_equal(solver.direction, 1) + assert_(solver.t > 5) + assert_(not np.all(np.equal(solver.y, y0))) + assert_(solver.step_size > 0) + assert_(solver.nfev > 0) + assert_(solver.njev >= 0) + assert_(solver.nlu >= 0) + sol = solver.dense_output() + assert_allclose(sol(5), y0, rtol=1e-15, atol=0) + + +def test_OdeSolution(): + ts = np.array([0, 2, 5], dtype=float) + s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1])) + s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1])) + + sol = OdeSolution(ts, [s1, s2]) + + assert_equal(sol(-1), [-1]) + assert_equal(sol(1), [-1]) + assert_equal(sol(2), [-1]) + assert_equal(sol(3), [1]) + assert_equal(sol(5), [1]) + assert_equal(sol(6), [1]) + + assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]), + np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]])) + + ts = np.array([10, 4, -3]) + s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1])) + s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1])) + + sol = OdeSolution(ts, [s1, s2]) + assert_equal(sol(11), [-1]) + assert_equal(sol(10), [-1]) + assert_equal(sol(5), [-1]) + assert_equal(sol(4), [-1]) + assert_equal(sol(0), [1]) + assert_equal(sol(-3), [1]) + assert_equal(sol(-4), [1]) + + assert_equal(sol([12, -5, 10, -3, 6, 1, 4]), + np.array([[-1, 1, -1, 1, -1, 1, -1]])) + + ts = np.array([1, 1]) + s = ConstantDenseOutput(1, 1, np.array([10])) + sol = OdeSolution(ts, [s]) + assert_equal(sol(0), [10]) + assert_equal(sol(1), [10]) + assert_equal(sol(2), [10]) + + assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]])) + + +def test_num_jac(): + def fun(t, y): + return np.vstack([ + -0.04 * y[0] + 1e4 * y[1] * y[2], + 0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2, + 3e7 * y[1] ** 2 + ]) + + def jac(t, y): + return np.array([ + [-0.04, 1e4 * y[2], 1e4 * y[1]], + [0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]], + [0, 6e7 * y[1], 0] + ]) + + t = 1 + y = np.array([1, 0, 0]) + J_true = jac(t, y) + threshold = 1e-5 + f = fun(t, y).ravel() + + J_num, factor = num_jac(fun, t, y, f, threshold, None) + assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5) + + J_num, factor = num_jac(fun, t, y, f, threshold, factor) + assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5) + + +def test_num_jac_sparse(): + def fun(t, y): + e = y[1:]**3 - y[:-1]**2 + z = np.zeros(y.shape[1]) + return np.vstack((z, 3 * e)) + np.vstack((2 * e, z)) + + def structure(n): + A = np.zeros((n, n), dtype=int) + A[0, 0] = 1 + A[0, 1] = 1 + for i in range(1, n - 1): + A[i, i - 1: i + 2] = 1 + A[-1, -1] = 1 + A[-1, -2] = 1 + + return A + + np.random.seed(0) + n = 20 + y = np.random.randn(n) + A = structure(n) + groups = group_columns(A) + + f = fun(0, y[:, None]).ravel() + + # Compare dense and sparse results, assuming that dense implementation + # is correct (as it is straightforward). + J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None, + sparsity=(A, groups)) + J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None) + assert_allclose(J_num_dense, J_num_sparse.toarray(), + rtol=1e-12, atol=1e-14) + assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14) + + # Take small factors to trigger their recomputing inside. + factor = np.random.uniform(0, 1e-12, size=n) + J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor, + sparsity=(A, groups)) + J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor) + + assert_allclose(J_num_dense, J_num_sparse.toarray(), + rtol=1e-12, atol=1e-14) + assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14) + + +def test_args(): + + # sys3 is actually two decoupled systems. (x, y) form a + # linear oscillator, while z is a nonlinear first order + # system with equilibria at z=0 and z=1. If k > 0, z=1 + # is stable and z=0 is unstable. + + def sys3(t, w, omega, k, zfinal): + x, y, z = w + return [-omega*y, omega*x, k*z*(1 - z)] + + def sys3_jac(t, w, omega, k, zfinal): + x, y, z = w + J = np.array([[0, -omega, 0], + [omega, 0, 0], + [0, 0, k*(1 - 2*z)]]) + return J + + def sys3_x0decreasing(t, w, omega, k, zfinal): + x, y, z = w + return x + + def sys3_y0increasing(t, w, omega, k, zfinal): + x, y, z = w + return y + + def sys3_zfinal(t, w, omega, k, zfinal): + x, y, z = w + return z - zfinal + + # Set the event flags for the event functions. + sys3_x0decreasing.direction = -1 + sys3_y0increasing.direction = 1 + sys3_zfinal.terminal = True + + omega = 2 + k = 4 + + tfinal = 5 + zfinal = 0.99 + # Find z0 such that when z(0) = z0, z(tfinal) = zfinal. + # The condition z(tfinal) = zfinal is the terminal event. + z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal)) + + w0 = [0, -1, z0] + + # Provide the jac argument and use the Radau method to ensure that the use + # of the Jacobian function is exercised. + # If event handling is working, the solution will stop at tfinal, not tend. + tend = 2*tfinal + sol = solve_ivp(sys3, [0, tend], w0, + events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal], + dense_output=True, args=(omega, k, zfinal), + method='Radau', jac=sys3_jac, + rtol=1e-10, atol=1e-13) + + # Check that we got the expected events at the expected times. + x0events_t = sol.t_events[0] + y0events_t = sol.t_events[1] + zfinalevents_t = sol.t_events[2] + assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi]) + assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi]) + assert_allclose(zfinalevents_t, [tfinal]) + + # Check that the solution agrees with the known exact solution. + t = np.linspace(0, zfinalevents_t[0], 250) + w = sol.sol(t) + assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12) + assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12) + assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1), + rtol=1e-9, atol=1e-12) + + # Check that the state variables have the expected values at the events. + x0events = sol.sol(x0events_t) + y0events = sol.sol(y0events_t) + zfinalevents = sol.sol(zfinalevents_t) + assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14) + assert_allclose(x0events[1], np.ones_like(x0events[1])) + assert_allclose(y0events[0], np.ones_like(y0events[0])) + assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14) + assert_allclose(zfinalevents[2], [zfinal]) + + +def test_array_rtol(): + # solve_ivp had a bug with array_like `rtol`; see gh-15482 + # check that it's fixed + def f(t, y): + return y[0], y[1] + + # no warning (or error) when `rtol` is array_like + sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1]) + err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1))) + + # warning when an element of `rtol` is too small + with pytest.warns(UserWarning, match="At least one element..."): + sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16]) + err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1))) + + # tighter rtol improves the error + assert err2 < err1 + +@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']) +def test_integration_zero_rhs(method): + result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method) + assert_(result.success) + assert_equal(result.status, 0) + assert_allclose(result.y, 1.0, rtol=1e-15) + + +def test_args_single_value(): + def fun_with_arg(t, y, a): + return a*y + + message = "Supplied 'args' cannot be unpacked." + with pytest.raises(TypeError, match=message): + solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1) + + sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,)) + assert_allclose(sol.y[0, -1], np.exp(-0.1)) + +@pytest.mark.parametrize("f0_fill", [np.nan, np.inf]) +def test_initial_state_finiteness(f0_fill): + # regression test for gh-17846 + msg = "All components of the initial state `y0` must be finite." + with pytest.raises(ValueError, match=msg): + solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill)) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py new file mode 100644 index 0000000000000000000000000000000000000000..33cb27d0323d037c0937ab94b4de8f63b46be3d7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py @@ -0,0 +1,37 @@ +import pytest +from numpy.testing import assert_allclose, assert_ +import numpy as np +from scipy.integrate import RK23, RK45, DOP853 +from scipy.integrate._ivp import dop853_coefficients + + +@pytest.mark.parametrize("solver", [RK23, RK45, DOP853]) +def test_coefficient_properties(solver): + assert_allclose(np.sum(solver.B), 1, rtol=1e-15) + assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14) + + +def test_coefficient_properties_dop853(): + assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15) + assert_allclose(np.sum(dop853_coefficients.A, axis=1), + dop853_coefficients.C, + rtol=1e-14) + + +@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853]) +def test_error_estimation(solver_class): + step = 0.2 + solver = solver_class(lambda t, y: y, 0, [1], 1, first_step=step) + solver.step() + error_estimate = solver._estimate_error(solver.K, step) + error = solver.y - np.exp([step]) + assert_(np.abs(error) < np.abs(error_estimate)) + + +@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853]) +def test_error_estimation_complex(solver_class): + h = 0.2 + solver = solver_class(lambda t, y: 1j * y, 0, [1j], 1, first_step=h) + solver.step() + err_norm = solver._estimate_error_norm(solver.K, h, scale=[1]) + assert np.isrealobj(err_norm) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_lsoda.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_lsoda.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a8fbd7d95563e4e75a66137410fac5a26c1617a8 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_lsoda.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ode.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ode.py new file mode 100644 index 0000000000000000000000000000000000000000..eb03d194a353473311247cf9ad3ab98afdd42cb7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_ode.py @@ -0,0 +1,1376 @@ +# Authors: Pearu Peterson, Pauli Virtanen, John Travers +""" +First-order ODE integrators. + +User-friendly interface to various numerical integrators for solving a +system of first order ODEs with prescribed initial conditions:: + + d y(t)[i] + --------- = f(t,y(t))[i], + d t + + y(t=0)[i] = y0[i], + +where:: + + i = 0, ..., len(y0) - 1 + +class ode +--------- + +A generic interface class to numeric integrators. It has the following +methods:: + + integrator = ode(f, jac=None) + integrator = integrator.set_integrator(name, **params) + integrator = integrator.set_initial_value(y0, t0=0.0) + integrator = integrator.set_f_params(*args) + integrator = integrator.set_jac_params(*args) + y1 = integrator.integrate(t1, step=False, relax=False) + flag = integrator.successful() + +class complex_ode +----------------- + +This class has the same generic interface as ode, except it can handle complex +f, y and Jacobians by transparently translating them into the equivalent +real-valued system. It supports the real-valued solvers (i.e., not zvode) and is +an alternative to ode with the zvode solver, sometimes performing better. +""" +# XXX: Integrators must have: +# =========================== +# cvode - C version of vode and vodpk with many improvements. +# Get it from http://www.netlib.org/ode/cvode.tar.gz. +# To wrap cvode to Python, one must write the extension module by +# hand. Its interface is too much 'advanced C' that using f2py +# would be too complicated (or impossible). +# +# How to define a new integrator: +# =============================== +# +# class myodeint(IntegratorBase): +# +# runner = or None +# +# def __init__(self,...): # required +# +# +# def reset(self,n,has_jac): # optional +# # n - the size of the problem (number of equations) +# # has_jac - whether user has supplied its own routine for Jacobian +# +# +# def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required +# # this method is called to integrate from t=t0 to t=t1 +# # with initial condition y0. f and jac are user-supplied functions +# # that define the problem. f_params,jac_params are additional +# # arguments +# # to these functions. +# +# if : +# self.success = 0 +# return t1,y1 +# +# # In addition, one can define step() and run_relax() methods (they +# # take the same arguments as run()) if the integrator can support +# # these features (see IntegratorBase doc strings). +# +# if myodeint.runner: +# IntegratorBase.integrator_classes.append(myodeint) + +__all__ = ['ode', 'complex_ode'] + +import re +import warnings + +from numpy import asarray, array, zeros, isscalar, real, imag, vstack + +from . import _vode +from . import _dop +from . import _lsoda + + +_dop_int_dtype = _dop.types.intvar.dtype +_vode_int_dtype = _vode.types.intvar.dtype +_lsoda_int_dtype = _lsoda.types.intvar.dtype + + +# ------------------------------------------------------------------------------ +# User interface +# ------------------------------------------------------------------------------ + + +class ode: + """ + A generic interface class to numeric integrators. + + Solve an equation system :math:`y'(t) = f(t,y)` with (optional) ``jac = df/dy``. + + *Note*: The first two arguments of ``f(t, y, ...)`` are in the + opposite order of the arguments in the system definition function used + by `scipy.integrate.odeint`. + + Parameters + ---------- + f : callable ``f(t, y, *f_args)`` + Right-hand side of the differential equation. t is a scalar, + ``y.shape == (n,)``. + ``f_args`` is set by calling ``set_f_params(*args)``. + `f` should return a scalar, array or list (not a tuple). + jac : callable ``jac(t, y, *jac_args)``, optional + Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``. + ``jac_args`` is set by calling ``set_jac_params(*args)``. + + Attributes + ---------- + t : float + Current time. + y : ndarray + Current variable values. + + See also + -------- + odeint : an integrator with a simpler interface based on lsoda from ODEPACK + quad : for finding the area under a curve + + Notes + ----- + Available integrators are listed below. They can be selected using + the `set_integrator` method. + + "vode" + + Real-valued Variable-coefficient Ordinary Differential Equation + solver, with fixed-leading-coefficient implementation. It provides + implicit Adams method (for non-stiff problems) and a method based on + backward differentiation formulas (BDF) (for stiff problems). + + Source: http://www.netlib.org/ode/vode.f + + .. warning:: + + This integrator is not re-entrant. You cannot have two `ode` + instances using the "vode" integrator at the same time. + + This integrator accepts the following parameters in `set_integrator` + method of the `ode` class: + + - atol : float or sequence + absolute tolerance for solution + - rtol : float or sequence + relative tolerance for solution + - lband : None or int + - uband : None or int + Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband. + Setting these requires your jac routine to return the jacobian + in packed format, jac_packed[i-j+uband, j] = jac[i,j]. The + dimension of the matrix must be (lband+uband+1, len(y)). + - method: 'adams' or 'bdf' + Which solver to use, Adams (non-stiff) or BDF (stiff) + - with_jacobian : bool + This option is only considered when the user has not supplied a + Jacobian function and has not indicated (by setting either band) + that the Jacobian is banded. In this case, `with_jacobian` specifies + whether the iteration method of the ODE solver's correction step is + chord iteration with an internally generated full Jacobian or + functional iteration with no Jacobian. + - nsteps : int + Maximum number of (internally defined) steps allowed during one + call to the solver. + - first_step : float + - min_step : float + - max_step : float + Limits for the step sizes used by the integrator. + - order : int + Maximum order used by the integrator, + order <= 12 for Adams, <= 5 for BDF. + + "zvode" + + Complex-valued Variable-coefficient Ordinary Differential Equation + solver, with fixed-leading-coefficient implementation. It provides + implicit Adams method (for non-stiff problems) and a method based on + backward differentiation formulas (BDF) (for stiff problems). + + Source: http://www.netlib.org/ode/zvode.f + + .. warning:: + + This integrator is not re-entrant. You cannot have two `ode` + instances using the "zvode" integrator at the same time. + + This integrator accepts the same parameters in `set_integrator` + as the "vode" solver. + + .. note:: + + When using ZVODE for a stiff system, it should only be used for + the case in which the function f is analytic, that is, when each f(i) + is an analytic function of each y(j). Analyticity means that the + partial derivative df(i)/dy(j) is a unique complex number, and this + fact is critical in the way ZVODE solves the dense or banded linear + systems that arise in the stiff case. For a complex stiff ODE system + in which f is not analytic, ZVODE is likely to have convergence + failures, and for this problem one should instead use DVODE on the + equivalent real system (in the real and imaginary parts of y). + + "lsoda" + + Real-valued Variable-coefficient Ordinary Differential Equation + solver, with fixed-leading-coefficient implementation. It provides + automatic method switching between implicit Adams method (for non-stiff + problems) and a method based on backward differentiation formulas (BDF) + (for stiff problems). + + Source: http://www.netlib.org/odepack + + .. warning:: + + This integrator is not re-entrant. You cannot have two `ode` + instances using the "lsoda" integrator at the same time. + + This integrator accepts the following parameters in `set_integrator` + method of the `ode` class: + + - atol : float or sequence + absolute tolerance for solution + - rtol : float or sequence + relative tolerance for solution + - lband : None or int + - uband : None or int + Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband. + Setting these requires your jac routine to return the jacobian + in packed format, jac_packed[i-j+uband, j] = jac[i,j]. + - with_jacobian : bool + *Not used.* + - nsteps : int + Maximum number of (internally defined) steps allowed during one + call to the solver. + - first_step : float + - min_step : float + - max_step : float + Limits for the step sizes used by the integrator. + - max_order_ns : int + Maximum order used in the nonstiff case (default 12). + - max_order_s : int + Maximum order used in the stiff case (default 5). + - max_hnil : int + Maximum number of messages reporting too small step size (t + h = t) + (default 0) + - ixpr : int + Whether to generate extra printing at method switches (default False). + + "dopri5" + + This is an explicit runge-kutta method of order (4)5 due to Dormand & + Prince (with stepsize control and dense output). + + Authors: + + E. Hairer and G. Wanner + Universite de Geneve, Dept. de Mathematiques + CH-1211 Geneve 24, Switzerland + e-mail: ernst.hairer@math.unige.ch, gerhard.wanner@math.unige.ch + + This code is described in [HNW93]_. + + This integrator accepts the following parameters in set_integrator() + method of the ode class: + + - atol : float or sequence + absolute tolerance for solution + - rtol : float or sequence + relative tolerance for solution + - nsteps : int + Maximum number of (internally defined) steps allowed during one + call to the solver. + - first_step : float + - max_step : float + - safety : float + Safety factor on new step selection (default 0.9) + - ifactor : float + - dfactor : float + Maximum factor to increase/decrease step size by in one step + - beta : float + Beta parameter for stabilised step size control. + - verbosity : int + Switch for printing messages (< 0 for no messages). + + "dop853" + + This is an explicit runge-kutta method of order 8(5,3) due to Dormand + & Prince (with stepsize control and dense output). + + Options and references the same as "dopri5". + + Examples + -------- + + A problem to integrate and the corresponding jacobian: + + >>> from scipy.integrate import ode + >>> + >>> y0, t0 = [1.0j, 2.0], 0 + >>> + >>> def f(t, y, arg1): + ... return [1j*arg1*y[0] + y[1], -arg1*y[1]**2] + >>> def jac(t, y, arg1): + ... return [[1j*arg1, 1], [0, -arg1*2*y[1]]] + + The integration: + + >>> r = ode(f, jac).set_integrator('zvode', method='bdf') + >>> r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0) + >>> t1 = 10 + >>> dt = 1 + >>> while r.successful() and r.t < t1: + ... print(r.t+dt, r.integrate(r.t+dt)) + 1 [-0.71038232+0.23749653j 0.40000271+0.j ] + 2.0 [0.19098503-0.52359246j 0.22222356+0.j ] + 3.0 [0.47153208+0.52701229j 0.15384681+0.j ] + 4.0 [-0.61905937+0.30726255j 0.11764744+0.j ] + 5.0 [0.02340997-0.61418799j 0.09523835+0.j ] + 6.0 [0.58643071+0.339819j 0.08000018+0.j ] + 7.0 [-0.52070105+0.44525141j 0.06896565+0.j ] + 8.0 [-0.15986733-0.61234476j 0.06060616+0.j ] + 9.0 [0.64850462+0.15048982j 0.05405414+0.j ] + 10.0 [-0.38404699+0.56382299j 0.04878055+0.j ] + + References + ---------- + .. [HNW93] E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary + Differential Equations i. Nonstiff Problems. 2nd edition. + Springer Series in Computational Mathematics, + Springer-Verlag (1993) + + """ + + def __init__(self, f, jac=None): + self.stiff = 0 + self.f = f + self.jac = jac + self.f_params = () + self.jac_params = () + self._y = [] + + @property + def y(self): + return self._y + + def set_initial_value(self, y, t=0.0): + """Set initial conditions y(t) = y.""" + if isscalar(y): + y = [y] + n_prev = len(self._y) + if not n_prev: + self.set_integrator('') # find first available integrator + self._y = asarray(y, self._integrator.scalar) + self.t = t + self._integrator.reset(len(self._y), self.jac is not None) + return self + + def set_integrator(self, name, **integrator_params): + """ + Set integrator by name. + + Parameters + ---------- + name : str + Name of the integrator. + **integrator_params + Additional parameters for the integrator. + """ + integrator = find_integrator(name) + if integrator is None: + # FIXME: this really should be raise an exception. Will that break + # any code? + message = f'No integrator name match with {name!r} or is not available.' + warnings.warn(message, stacklevel=2) + else: + self._integrator = integrator(**integrator_params) + if not len(self._y): + self.t = 0.0 + self._y = array([0.0], self._integrator.scalar) + self._integrator.reset(len(self._y), self.jac is not None) + return self + + def integrate(self, t, step=False, relax=False): + """Find y=y(t), set y as an initial condition, and return y. + + Parameters + ---------- + t : float + The endpoint of the integration step. + step : bool + If True, and if the integrator supports the step method, + then perform a single integration step and return. + This parameter is provided in order to expose internals of + the implementation, and should not be changed from its default + value in most cases. + relax : bool + If True and if the integrator supports the run_relax method, + then integrate until t_1 >= t and return. ``relax`` is not + referenced if ``step=True``. + This parameter is provided in order to expose internals of + the implementation, and should not be changed from its default + value in most cases. + + Returns + ------- + y : float + The integrated value at t + """ + if step and self._integrator.supports_step: + mth = self._integrator.step + elif relax and self._integrator.supports_run_relax: + mth = self._integrator.run_relax + else: + mth = self._integrator.run + + try: + self._y, self.t = mth(self.f, self.jac or (lambda: None), + self._y, self.t, t, + self.f_params, self.jac_params) + except SystemError as e: + # f2py issue with tuple returns, see ticket 1187. + raise ValueError( + 'Function to integrate must not return a tuple.' + ) from e + + return self._y + + def successful(self): + """Check if integration was successful.""" + try: + self._integrator + except AttributeError: + self.set_integrator('') + return self._integrator.success == 1 + + def get_return_code(self): + """Extracts the return code for the integration to enable better control + if the integration fails. + + In general, a return code > 0 implies success, while a return code < 0 + implies failure. + + Notes + ----- + This section describes possible return codes and their meaning, for available + integrators that can be selected by `set_integrator` method. + + "vode" + + =========== ======= + Return Code Message + =========== ======= + 2 Integration successful. + -1 Excess work done on this call. (Perhaps wrong MF.) + -2 Excess accuracy requested. (Tolerances too small.) + -3 Illegal input detected. (See printed message.) + -4 Repeated error test failures. (Check all input.) + -5 Repeated convergence failures. (Perhaps bad Jacobian + supplied or wrong choice of MF or tolerances.) + -6 Error weight became zero during problem. (Solution + component i vanished, and ATOL or ATOL(i) = 0.) + =========== ======= + + "zvode" + + =========== ======= + Return Code Message + =========== ======= + 2 Integration successful. + -1 Excess work done on this call. (Perhaps wrong MF.) + -2 Excess accuracy requested. (Tolerances too small.) + -3 Illegal input detected. (See printed message.) + -4 Repeated error test failures. (Check all input.) + -5 Repeated convergence failures. (Perhaps bad Jacobian + supplied or wrong choice of MF or tolerances.) + -6 Error weight became zero during problem. (Solution + component i vanished, and ATOL or ATOL(i) = 0.) + =========== ======= + + "dopri5" + + =========== ======= + Return Code Message + =========== ======= + 1 Integration successful. + 2 Integration successful (interrupted by solout). + -1 Input is not consistent. + -2 Larger nsteps is needed. + -3 Step size becomes too small. + -4 Problem is probably stiff (interrupted). + =========== ======= + + "dop853" + + =========== ======= + Return Code Message + =========== ======= + 1 Integration successful. + 2 Integration successful (interrupted by solout). + -1 Input is not consistent. + -2 Larger nsteps is needed. + -3 Step size becomes too small. + -4 Problem is probably stiff (interrupted). + =========== ======= + + "lsoda" + + =========== ======= + Return Code Message + =========== ======= + 2 Integration successful. + -1 Excess work done on this call (perhaps wrong Dfun type). + -2 Excess accuracy requested (tolerances too small). + -3 Illegal input detected (internal error). + -4 Repeated error test failures (internal error). + -5 Repeated convergence failures (perhaps bad Jacobian or tolerances). + -6 Error weight became zero during problem. + -7 Internal workspace insufficient to finish (internal error). + =========== ======= + """ + try: + self._integrator + except AttributeError: + self.set_integrator('') + return self._integrator.istate + + def set_f_params(self, *args): + """Set extra parameters for user-supplied function f.""" + self.f_params = args + return self + + def set_jac_params(self, *args): + """Set extra parameters for user-supplied function jac.""" + self.jac_params = args + return self + + def set_solout(self, solout): + """ + Set callable to be called at every successful integration step. + + Parameters + ---------- + solout : callable + ``solout(t, y)`` is called at each internal integrator step, + t is a scalar providing the current independent position + y is the current solution ``y.shape == (n,)`` + solout should return -1 to stop integration + otherwise it should return None or 0 + + """ + if self._integrator.supports_solout: + self._integrator.set_solout(solout) + if self._y is not None: + self._integrator.reset(len(self._y), self.jac is not None) + else: + raise ValueError("selected integrator does not support solout," + " choose another one") + + +def _transform_banded_jac(bjac): + """ + Convert a real matrix of the form (for example) + + [0 0 A B] [0 0 0 B] + [0 0 C D] [0 0 A D] + [E F G H] to [0 F C H] + [I J K L] [E J G L] + [I 0 K 0] + + That is, every other column is shifted up one. + """ + # Shift every other column. + newjac = zeros((bjac.shape[0] + 1, bjac.shape[1])) + newjac[1:, ::2] = bjac[:, ::2] + newjac[:-1, 1::2] = bjac[:, 1::2] + return newjac + + +class complex_ode(ode): + """ + A wrapper of ode for complex systems. + + This functions similarly as `ode`, but re-maps a complex-valued + equation system to a real-valued one before using the integrators. + + Parameters + ---------- + f : callable ``f(t, y, *f_args)`` + Rhs of the equation. t is a scalar, ``y.shape == (n,)``. + ``f_args`` is set by calling ``set_f_params(*args)``. + jac : callable ``jac(t, y, *jac_args)`` + Jacobian of the rhs, ``jac[i,j] = d f[i] / d y[j]``. + ``jac_args`` is set by calling ``set_f_params(*args)``. + + Attributes + ---------- + t : float + Current time. + y : ndarray + Current variable values. + + Examples + -------- + For usage examples, see `ode`. + + """ + + def __init__(self, f, jac=None): + self.cf = f + self.cjac = jac + if jac is None: + ode.__init__(self, self._wrap, None) + else: + ode.__init__(self, self._wrap, self._wrap_jac) + + def _wrap(self, t, y, *f_args): + f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args)) + # self.tmp is a real-valued array containing the interleaved + # real and imaginary parts of f. + self.tmp[::2] = real(f) + self.tmp[1::2] = imag(f) + return self.tmp + + def _wrap_jac(self, t, y, *jac_args): + # jac is the complex Jacobian computed by the user-defined function. + jac = self.cjac(*((t, y[::2] + 1j * y[1::2]) + jac_args)) + + # jac_tmp is the real version of the complex Jacobian. Each complex + # entry in jac, say 2+3j, becomes a 2x2 block of the form + # [2 -3] + # [3 2] + jac_tmp = zeros((2 * jac.shape[0], 2 * jac.shape[1])) + jac_tmp[1::2, 1::2] = jac_tmp[::2, ::2] = real(jac) + jac_tmp[1::2, ::2] = imag(jac) + jac_tmp[::2, 1::2] = -jac_tmp[1::2, ::2] + + ml = getattr(self._integrator, 'ml', None) + mu = getattr(self._integrator, 'mu', None) + if ml is not None or mu is not None: + # Jacobian is banded. The user's Jacobian function has computed + # the complex Jacobian in packed format. The corresponding + # real-valued version has every other column shifted up. + jac_tmp = _transform_banded_jac(jac_tmp) + + return jac_tmp + + @property + def y(self): + return self._y[::2] + 1j * self._y[1::2] + + def set_integrator(self, name, **integrator_params): + """ + Set integrator by name. + + Parameters + ---------- + name : str + Name of the integrator + **integrator_params + Additional parameters for the integrator. + """ + if name == 'zvode': + raise ValueError("zvode must be used with ode, not complex_ode") + + lband = integrator_params.get('lband') + uband = integrator_params.get('uband') + if lband is not None or uband is not None: + # The Jacobian is banded. Override the user-supplied bandwidths + # (which are for the complex Jacobian) with the bandwidths of + # the corresponding real-valued Jacobian wrapper of the complex + # Jacobian. + integrator_params['lband'] = 2 * (lband or 0) + 1 + integrator_params['uband'] = 2 * (uband or 0) + 1 + + return ode.set_integrator(self, name, **integrator_params) + + def set_initial_value(self, y, t=0.0): + """Set initial conditions y(t) = y.""" + y = asarray(y) + self.tmp = zeros(y.size * 2, 'float') + self.tmp[::2] = real(y) + self.tmp[1::2] = imag(y) + return ode.set_initial_value(self, self.tmp, t) + + def integrate(self, t, step=False, relax=False): + """Find y=y(t), set y as an initial condition, and return y. + + Parameters + ---------- + t : float + The endpoint of the integration step. + step : bool + If True, and if the integrator supports the step method, + then perform a single integration step and return. + This parameter is provided in order to expose internals of + the implementation, and should not be changed from its default + value in most cases. + relax : bool + If True and if the integrator supports the run_relax method, + then integrate until t_1 >= t and return. ``relax`` is not + referenced if ``step=True``. + This parameter is provided in order to expose internals of + the implementation, and should not be changed from its default + value in most cases. + + Returns + ------- + y : float + The integrated value at t + """ + y = ode.integrate(self, t, step, relax) + return y[::2] + 1j * y[1::2] + + def set_solout(self, solout): + """ + Set callable to be called at every successful integration step. + + Parameters + ---------- + solout : callable + ``solout(t, y)`` is called at each internal integrator step, + t is a scalar providing the current independent position + y is the current solution ``y.shape == (n,)`` + solout should return -1 to stop integration + otherwise it should return None or 0 + + """ + if self._integrator.supports_solout: + self._integrator.set_solout(solout, complex=True) + else: + raise TypeError("selected integrator does not support solouta," + + "choose another one") + + +# ------------------------------------------------------------------------------ +# ODE integrators +# ------------------------------------------------------------------------------ + +def find_integrator(name): + for cl in IntegratorBase.integrator_classes: + if re.match(name, cl.__name__, re.I): + return cl + return None + + +class IntegratorConcurrencyError(RuntimeError): + """ + Failure due to concurrent usage of an integrator that can be used + only for a single problem at a time. + + """ + + def __init__(self, name): + msg = ("Integrator `%s` can be used to solve only a single problem " + "at a time. If you want to integrate multiple problems, " + "consider using a different integrator " + "(see `ode.set_integrator`)") % name + RuntimeError.__init__(self, msg) + + +class IntegratorBase: + runner = None # runner is None => integrator is not available + success = None # success==1 if integrator was called successfully + istate = None # istate > 0 means success, istate < 0 means failure + supports_run_relax = None + supports_step = None + supports_solout = False + integrator_classes = [] + scalar = float + + def acquire_new_handle(self): + # Some of the integrators have internal state (ancient + # Fortran...), and so only one instance can use them at a time. + # We keep track of this, and fail when concurrent usage is tried. + self.__class__.active_global_handle += 1 + self.handle = self.__class__.active_global_handle + + def check_handle(self): + if self.handle is not self.__class__.active_global_handle: + raise IntegratorConcurrencyError(self.__class__.__name__) + + def reset(self, n, has_jac): + """Prepare integrator for call: allocate memory, set flags, etc. + n - number of equations. + has_jac - if user has supplied function for evaluating Jacobian. + """ + + def run(self, f, jac, y0, t0, t1, f_params, jac_params): + """Integrate from t=t0 to t=t1 using y0 as an initial condition. + Return 2-tuple (y1,t1) where y1 is the result and t=t1 + defines the stoppage coordinate of the result. + """ + raise NotImplementedError('all integrators must define ' + 'run(f, jac, t0, t1, y0, f_params, jac_params)') + + def step(self, f, jac, y0, t0, t1, f_params, jac_params): + """Make one integration step and return (y1,t1).""" + raise NotImplementedError('%s does not support step() method' % + self.__class__.__name__) + + def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params): + """Integrate from t=t0 to t>=t1 and return (y1,t).""" + raise NotImplementedError('%s does not support run_relax() method' % + self.__class__.__name__) + + # XXX: __str__ method for getting visual state of the integrator + + +def _vode_banded_jac_wrapper(jacfunc, ml, jac_params): + """ + Wrap a banded Jacobian function with a function that pads + the Jacobian with `ml` rows of zeros. + """ + + def jac_wrapper(t, y): + jac = asarray(jacfunc(t, y, *jac_params)) + padded_jac = vstack((jac, zeros((ml, jac.shape[1])))) + return padded_jac + + return jac_wrapper + + +class vode(IntegratorBase): + runner = getattr(_vode, 'dvode', None) + + messages = {-1: 'Excess work done on this call. (Perhaps wrong MF.)', + -2: 'Excess accuracy requested. (Tolerances too small.)', + -3: 'Illegal input detected. (See printed message.)', + -4: 'Repeated error test failures. (Check all input.)', + -5: 'Repeated convergence failures. (Perhaps bad' + ' Jacobian supplied or wrong choice of MF or tolerances.)', + -6: 'Error weight became zero during problem. (Solution' + ' component i vanished, and ATOL or ATOL(i) = 0.)' + } + supports_run_relax = 1 + supports_step = 1 + active_global_handle = 0 + + def __init__(self, + method='adams', + with_jacobian=False, + rtol=1e-6, atol=1e-12, + lband=None, uband=None, + order=12, + nsteps=500, + max_step=0.0, # corresponds to infinite + min_step=0.0, + first_step=0.0, # determined by solver + ): + + if re.match(method, r'adams', re.I): + self.meth = 1 + elif re.match(method, r'bdf', re.I): + self.meth = 2 + else: + raise ValueError('Unknown integration method %s' % method) + self.with_jacobian = with_jacobian + self.rtol = rtol + self.atol = atol + self.mu = uband + self.ml = lband + + self.order = order + self.nsteps = nsteps + self.max_step = max_step + self.min_step = min_step + self.first_step = first_step + self.success = 1 + + self.initialized = False + + def _determine_mf_and_set_bands(self, has_jac): + """ + Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`. + + In the Fortran code, the legal values of `MF` are: + 10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, + -11, -12, -14, -15, -21, -22, -24, -25 + but this Python wrapper does not use negative values. + + Returns + + mf = 10*self.meth + miter + + self.meth is the linear multistep method: + self.meth == 1: method="adams" + self.meth == 2: method="bdf" + + miter is the correction iteration method: + miter == 0: Functional iteration; no Jacobian involved. + miter == 1: Chord iteration with user-supplied full Jacobian. + miter == 2: Chord iteration with internally computed full Jacobian. + miter == 3: Chord iteration with internally computed diagonal Jacobian. + miter == 4: Chord iteration with user-supplied banded Jacobian. + miter == 5: Chord iteration with internally computed banded Jacobian. + + Side effects: If either self.mu or self.ml is not None and the other is None, + then the one that is None is set to 0. + """ + + jac_is_banded = self.mu is not None or self.ml is not None + if jac_is_banded: + if self.mu is None: + self.mu = 0 + if self.ml is None: + self.ml = 0 + + # has_jac is True if the user provided a Jacobian function. + if has_jac: + if jac_is_banded: + miter = 4 + else: + miter = 1 + else: + if jac_is_banded: + if self.ml == self.mu == 0: + miter = 3 # Chord iteration with internal diagonal Jacobian. + else: + miter = 5 # Chord iteration with internal banded Jacobian. + else: + # self.with_jacobian is set by the user in + # the call to ode.set_integrator. + if self.with_jacobian: + miter = 2 # Chord iteration with internal full Jacobian. + else: + miter = 0 # Functional iteration; no Jacobian involved. + + mf = 10 * self.meth + miter + return mf + + def reset(self, n, has_jac): + mf = self._determine_mf_and_set_bands(has_jac) + + if mf == 10: + lrw = 20 + 16 * n + elif mf in [11, 12]: + lrw = 22 + 16 * n + 2 * n * n + elif mf == 13: + lrw = 22 + 17 * n + elif mf in [14, 15]: + lrw = 22 + 18 * n + (3 * self.ml + 2 * self.mu) * n + elif mf == 20: + lrw = 20 + 9 * n + elif mf in [21, 22]: + lrw = 22 + 9 * n + 2 * n * n + elif mf == 23: + lrw = 22 + 10 * n + elif mf in [24, 25]: + lrw = 22 + 11 * n + (3 * self.ml + 2 * self.mu) * n + else: + raise ValueError('Unexpected mf=%s' % mf) + + if mf % 10 in [0, 3]: + liw = 30 + else: + liw = 30 + n + + rwork = zeros((lrw,), float) + rwork[4] = self.first_step + rwork[5] = self.max_step + rwork[6] = self.min_step + self.rwork = rwork + + iwork = zeros((liw,), _vode_int_dtype) + if self.ml is not None: + iwork[0] = self.ml + if self.mu is not None: + iwork[1] = self.mu + iwork[4] = self.order + iwork[5] = self.nsteps + iwork[6] = 2 # mxhnil + self.iwork = iwork + + self.call_args = [self.rtol, self.atol, 1, 1, + self.rwork, self.iwork, mf] + self.success = 1 + self.initialized = False + + def run(self, f, jac, y0, t0, t1, f_params, jac_params): + if self.initialized: + self.check_handle() + else: + self.initialized = True + self.acquire_new_handle() + + if self.ml is not None and self.ml > 0: + # Banded Jacobian. Wrap the user-provided function with one + # that pads the Jacobian array with the extra `self.ml` rows + # required by the f2py-generated wrapper. + jac = _vode_banded_jac_wrapper(jac, self.ml, jac_params) + + args = ((f, jac, y0, t0, t1) + tuple(self.call_args) + + (f_params, jac_params)) + y1, t, istate = self.runner(*args) + self.istate = istate + if istate < 0: + unexpected_istate_msg = f'Unexpected istate={istate:d}' + warnings.warn('{:s}: {:s}'.format(self.__class__.__name__, + self.messages.get(istate, unexpected_istate_msg)), + stacklevel=2) + self.success = 0 + else: + self.call_args[3] = 2 # upgrade istate from 1 to 2 + self.istate = 2 + return y1, t + + def step(self, *args): + itask = self.call_args[2] + self.call_args[2] = 2 + r = self.run(*args) + self.call_args[2] = itask + return r + + def run_relax(self, *args): + itask = self.call_args[2] + self.call_args[2] = 3 + r = self.run(*args) + self.call_args[2] = itask + return r + + +if vode.runner is not None: + IntegratorBase.integrator_classes.append(vode) + + +class zvode(vode): + runner = getattr(_vode, 'zvode', None) + + supports_run_relax = 1 + supports_step = 1 + scalar = complex + active_global_handle = 0 + + def reset(self, n, has_jac): + mf = self._determine_mf_and_set_bands(has_jac) + + if mf in (10,): + lzw = 15 * n + elif mf in (11, 12): + lzw = 15 * n + 2 * n ** 2 + elif mf in (-11, -12): + lzw = 15 * n + n ** 2 + elif mf in (13,): + lzw = 16 * n + elif mf in (14, 15): + lzw = 17 * n + (3 * self.ml + 2 * self.mu) * n + elif mf in (-14, -15): + lzw = 16 * n + (2 * self.ml + self.mu) * n + elif mf in (20,): + lzw = 8 * n + elif mf in (21, 22): + lzw = 8 * n + 2 * n ** 2 + elif mf in (-21, -22): + lzw = 8 * n + n ** 2 + elif mf in (23,): + lzw = 9 * n + elif mf in (24, 25): + lzw = 10 * n + (3 * self.ml + 2 * self.mu) * n + elif mf in (-24, -25): + lzw = 9 * n + (2 * self.ml + self.mu) * n + + lrw = 20 + n + + if mf % 10 in (0, 3): + liw = 30 + else: + liw = 30 + n + + zwork = zeros((lzw,), complex) + self.zwork = zwork + + rwork = zeros((lrw,), float) + rwork[4] = self.first_step + rwork[5] = self.max_step + rwork[6] = self.min_step + self.rwork = rwork + + iwork = zeros((liw,), _vode_int_dtype) + if self.ml is not None: + iwork[0] = self.ml + if self.mu is not None: + iwork[1] = self.mu + iwork[4] = self.order + iwork[5] = self.nsteps + iwork[6] = 2 # mxhnil + self.iwork = iwork + + self.call_args = [self.rtol, self.atol, 1, 1, + self.zwork, self.rwork, self.iwork, mf] + self.success = 1 + self.initialized = False + + +if zvode.runner is not None: + IntegratorBase.integrator_classes.append(zvode) + + +class dopri5(IntegratorBase): + runner = getattr(_dop, 'dopri5', None) + name = 'dopri5' + supports_solout = True + + messages = {1: 'computation successful', + 2: 'computation successful (interrupted by solout)', + -1: 'input is not consistent', + -2: 'larger nsteps is needed', + -3: 'step size becomes too small', + -4: 'problem is probably stiff (interrupted)', + } + + def __init__(self, + rtol=1e-6, atol=1e-12, + nsteps=500, + max_step=0.0, + first_step=0.0, # determined by solver + safety=0.9, + ifactor=10.0, + dfactor=0.2, + beta=0.0, + method=None, + verbosity=-1, # no messages if negative + ): + self.rtol = rtol + self.atol = atol + self.nsteps = nsteps + self.max_step = max_step + self.first_step = first_step + self.safety = safety + self.ifactor = ifactor + self.dfactor = dfactor + self.beta = beta + self.verbosity = verbosity + self.success = 1 + self.set_solout(None) + + def set_solout(self, solout, complex=False): + self.solout = solout + self.solout_cmplx = complex + if solout is None: + self.iout = 0 + else: + self.iout = 1 + + def reset(self, n, has_jac): + work = zeros((8 * n + 21,), float) + work[1] = self.safety + work[2] = self.dfactor + work[3] = self.ifactor + work[4] = self.beta + work[5] = self.max_step + work[6] = self.first_step + self.work = work + iwork = zeros((21,), _dop_int_dtype) + iwork[0] = self.nsteps + iwork[2] = self.verbosity + self.iwork = iwork + self.call_args = [self.rtol, self.atol, self._solout, + self.iout, self.work, self.iwork] + self.success = 1 + + def run(self, f, jac, y0, t0, t1, f_params, jac_params): + x, y, iwork, istate = self.runner(*((f, t0, y0, t1) + + tuple(self.call_args) + (f_params,))) + self.istate = istate + if istate < 0: + unexpected_istate_msg = f'Unexpected istate={istate:d}' + warnings.warn('{:s}: {:s}'.format(self.__class__.__name__, + self.messages.get(istate, unexpected_istate_msg)), + stacklevel=2) + self.success = 0 + return y, x + + def _solout(self, nr, xold, x, y, nd, icomp, con): + if self.solout is not None: + if self.solout_cmplx: + y = y[::2] + 1j * y[1::2] + return self.solout(x, y) + else: + return 1 + + +if dopri5.runner is not None: + IntegratorBase.integrator_classes.append(dopri5) + + +class dop853(dopri5): + runner = getattr(_dop, 'dop853', None) + name = 'dop853' + + def __init__(self, + rtol=1e-6, atol=1e-12, + nsteps=500, + max_step=0.0, + first_step=0.0, # determined by solver + safety=0.9, + ifactor=6.0, + dfactor=0.3, + beta=0.0, + method=None, + verbosity=-1, # no messages if negative + ): + super().__init__(rtol, atol, nsteps, max_step, first_step, safety, + ifactor, dfactor, beta, method, verbosity) + + def reset(self, n, has_jac): + work = zeros((11 * n + 21,), float) + work[1] = self.safety + work[2] = self.dfactor + work[3] = self.ifactor + work[4] = self.beta + work[5] = self.max_step + work[6] = self.first_step + self.work = work + iwork = zeros((21,), _dop_int_dtype) + iwork[0] = self.nsteps + iwork[2] = self.verbosity + self.iwork = iwork + self.call_args = [self.rtol, self.atol, self._solout, + self.iout, self.work, self.iwork] + self.success = 1 + + +if dop853.runner is not None: + IntegratorBase.integrator_classes.append(dop853) + + +class lsoda(IntegratorBase): + runner = getattr(_lsoda, 'lsoda', None) + active_global_handle = 0 + + messages = { + 2: "Integration successful.", + -1: "Excess work done on this call (perhaps wrong Dfun type).", + -2: "Excess accuracy requested (tolerances too small).", + -3: "Illegal input detected (internal error).", + -4: "Repeated error test failures (internal error).", + -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).", + -6: "Error weight became zero during problem.", + -7: "Internal workspace insufficient to finish (internal error)." + } + + def __init__(self, + with_jacobian=False, + rtol=1e-6, atol=1e-12, + lband=None, uband=None, + nsteps=500, + max_step=0.0, # corresponds to infinite + min_step=0.0, + first_step=0.0, # determined by solver + ixpr=0, + max_hnil=0, + max_order_ns=12, + max_order_s=5, + method=None + ): + + self.with_jacobian = with_jacobian + self.rtol = rtol + self.atol = atol + self.mu = uband + self.ml = lband + + self.max_order_ns = max_order_ns + self.max_order_s = max_order_s + self.nsteps = nsteps + self.max_step = max_step + self.min_step = min_step + self.first_step = first_step + self.ixpr = ixpr + self.max_hnil = max_hnil + self.success = 1 + + self.initialized = False + + def reset(self, n, has_jac): + # Calculate parameters for Fortran subroutine dvode. + if has_jac: + if self.mu is None and self.ml is None: + jt = 1 + else: + if self.mu is None: + self.mu = 0 + if self.ml is None: + self.ml = 0 + jt = 4 + else: + if self.mu is None and self.ml is None: + jt = 2 + else: + if self.mu is None: + self.mu = 0 + if self.ml is None: + self.ml = 0 + jt = 5 + lrn = 20 + (self.max_order_ns + 4) * n + if jt in [1, 2]: + lrs = 22 + (self.max_order_s + 4) * n + n * n + elif jt in [4, 5]: + lrs = 22 + (self.max_order_s + 5 + 2 * self.ml + self.mu) * n + else: + raise ValueError('Unexpected jt=%s' % jt) + lrw = max(lrn, lrs) + liw = 20 + n + rwork = zeros((lrw,), float) + rwork[4] = self.first_step + rwork[5] = self.max_step + rwork[6] = self.min_step + self.rwork = rwork + iwork = zeros((liw,), _lsoda_int_dtype) + if self.ml is not None: + iwork[0] = self.ml + if self.mu is not None: + iwork[1] = self.mu + iwork[4] = self.ixpr + iwork[5] = self.nsteps + iwork[6] = self.max_hnil + iwork[7] = self.max_order_ns + iwork[8] = self.max_order_s + self.iwork = iwork + self.call_args = [self.rtol, self.atol, 1, 1, + self.rwork, self.iwork, jt] + self.success = 1 + self.initialized = False + + def run(self, f, jac, y0, t0, t1, f_params, jac_params): + if self.initialized: + self.check_handle() + else: + self.initialized = True + self.acquire_new_handle() + args = [f, y0, t0, t1] + self.call_args[:-1] + \ + [jac, self.call_args[-1], f_params, 0, jac_params] + y1, t, istate = self.runner(*args) + self.istate = istate + if istate < 0: + unexpected_istate_msg = f'Unexpected istate={istate:d}' + warnings.warn('{:s}: {:s}'.format(self.__class__.__name__, + self.messages.get(istate, unexpected_istate_msg)), + stacklevel=2) + self.success = 0 + else: + self.call_args[3] = 2 # upgrade istate from 1 to 2 + self.istate = 2 + return y1, t + + def step(self, *args): + itask = self.call_args[2] + self.call_args[2] = 2 + r = self.run(*args) + self.call_args[2] = itask + return r + + def run_relax(self, *args): + itask = self.call_args[2] + self.call_args[2] = 3 + r = self.run(*args) + self.call_args[2] = itask + return r + + +if lsoda.runner: + IntegratorBase.integrator_classes.append(lsoda) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bf1769caef3028f1662ec9b463367f53673e10dd Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py new file mode 100644 index 0000000000000000000000000000000000000000..b868c0ced8c21adfc237e1577c024d6db12657c3 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py @@ -0,0 +1,262 @@ +# Author: Travis Oliphant + +__all__ = ['odeint', 'ODEintWarning'] + +import numpy as np +from . import _odepack +from copy import copy +import warnings + + +class ODEintWarning(Warning): + """Warning raised during the execution of `odeint`.""" + pass + + +_msgs = {2: "Integration successful.", + 1: "Nothing was done; the integration time was 0.", + -1: "Excess work done on this call (perhaps wrong Dfun type).", + -2: "Excess accuracy requested (tolerances too small).", + -3: "Illegal input detected (internal error).", + -4: "Repeated error test failures (internal error).", + -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).", + -6: "Error weight became zero during problem.", + -7: "Internal workspace insufficient to finish (internal error).", + -8: "Run terminated (internal error)." + } + + +def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, + ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, + hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, + mxords=5, printmessg=0, tfirst=False): + """ + Integrate a system of ordinary differential equations. + + .. note:: For new code, use `scipy.integrate.solve_ivp` to solve a + differential equation. + + Solve a system of ordinary differential equations using lsoda from the + FORTRAN library odepack. + + Solves the initial value problem for stiff or non-stiff systems + of first order ode-s:: + + dy/dt = func(y, t, ...) [or func(t, y, ...)] + + where y can be a vector. + + .. note:: By default, the required order of the first two arguments of + `func` are in the opposite order of the arguments in the system + definition function used by the `scipy.integrate.ode` class and + the function `scipy.integrate.solve_ivp`. To use a function with + the signature ``func(t, y, ...)``, the argument `tfirst` must be + set to ``True``. + + Parameters + ---------- + func : callable(y, t, ...) or callable(t, y, ...) + Computes the derivative of y at t. + If the signature is ``callable(t, y, ...)``, then the argument + `tfirst` must be set ``True``. + y0 : array + Initial condition on y (can be a vector). + t : array + A sequence of time points for which to solve for y. The initial + value point should be the first element of this sequence. + This sequence must be monotonically increasing or monotonically + decreasing; repeated values are allowed. + args : tuple, optional + Extra arguments to pass to function. + Dfun : callable(y, t, ...) or callable(t, y, ...) + Gradient (Jacobian) of `func`. + If the signature is ``callable(t, y, ...)``, then the argument + `tfirst` must be set ``True``. + col_deriv : bool, optional + True if `Dfun` defines derivatives down columns (faster), + otherwise `Dfun` should define derivatives across rows. + full_output : bool, optional + True if to return a dictionary of optional outputs as the second output + printmessg : bool, optional + Whether to print the convergence message + tfirst : bool, optional + If True, the first two arguments of `func` (and `Dfun`, if given) + must ``t, y`` instead of the default ``y, t``. + + .. versionadded:: 1.1.0 + + Returns + ------- + y : array, shape (len(t), len(y0)) + Array containing the value of y for each desired time in t, + with the initial value `y0` in the first row. + infodict : dict, only returned if full_output == True + Dictionary containing additional output information + + ======= ============================================================ + key meaning + ======= ============================================================ + 'hu' vector of step sizes successfully used for each time step + 'tcur' vector with the value of t reached for each time step + (will always be at least as large as the input times) + 'tolsf' vector of tolerance scale factors, greater than 1.0, + computed when a request for too much accuracy was detected + 'tsw' value of t at the time of the last method switch + (given for each time step) + 'nst' cumulative number of time steps + 'nfe' cumulative number of function evaluations for each time step + 'nje' cumulative number of jacobian evaluations for each time step + 'nqu' a vector of method orders for each successful step + 'imxer' index of the component of largest magnitude in the + weighted local error vector (e / ewt) on an error return, -1 + otherwise + 'lenrw' the length of the double work array required + 'leniw' the length of integer work array required + 'mused' a vector of method indicators for each successful time step: + 1: adams (nonstiff), 2: bdf (stiff) + ======= ============================================================ + + Other Parameters + ---------------- + ml, mu : int, optional + If either of these are not None or non-negative, then the + Jacobian is assumed to be banded. These give the number of + lower and upper non-zero diagonals in this banded matrix. + For the banded case, `Dfun` should return a matrix whose + rows contain the non-zero bands (starting with the lowest diagonal). + Thus, the return matrix `jac` from `Dfun` should have shape + ``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``. + The data in `jac` must be stored such that ``jac[i - j + mu, j]`` + holds the derivative of the ``i``\\ th equation with respect to the + ``j``\\ th state variable. If `col_deriv` is True, the transpose of + this `jac` must be returned. + rtol, atol : float, optional + The input parameters `rtol` and `atol` determine the error + control performed by the solver. The solver will control the + vector, e, of estimated local errors in y, according to an + inequality of the form ``max-norm of (e / ewt) <= 1``, + where ewt is a vector of positive error weights computed as + ``ewt = rtol * abs(y) + atol``. + rtol and atol can be either vectors the same length as y or scalars. + Defaults to 1.49012e-8. + tcrit : ndarray, optional + Vector of critical points (e.g., singularities) where integration + care should be taken. + h0 : float, (0: solver-determined), optional + The step size to be attempted on the first step. + hmax : float, (0: solver-determined), optional + The maximum absolute step size allowed. + hmin : float, (0: solver-determined), optional + The minimum absolute step size allowed. + ixpr : bool, optional + Whether to generate extra printing at method switches. + mxstep : int, (0: solver-determined), optional + Maximum number of (internally defined) steps allowed for each + integration point in t. + mxhnil : int, (0: solver-determined), optional + Maximum number of messages printed. + mxordn : int, (0: solver-determined), optional + Maximum order to be allowed for the non-stiff (Adams) method. + mxords : int, (0: solver-determined), optional + Maximum order to be allowed for the stiff (BDF) method. + + See Also + -------- + solve_ivp : solve an initial value problem for a system of ODEs + ode : a more object-oriented integrator based on VODE + quad : for finding the area under a curve + + Examples + -------- + The second order differential equation for the angle `theta` of a + pendulum acted on by gravity with friction can be written:: + + theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0 + + where `b` and `c` are positive constants, and a prime (') denotes a + derivative. To solve this equation with `odeint`, we must first convert + it to a system of first order equations. By defining the angular + velocity ``omega(t) = theta'(t)``, we obtain the system:: + + theta'(t) = omega(t) + omega'(t) = -b*omega(t) - c*sin(theta(t)) + + Let `y` be the vector [`theta`, `omega`]. We implement this system + in Python as: + + >>> import numpy as np + >>> def pend(y, t, b, c): + ... theta, omega = y + ... dydt = [omega, -b*omega - c*np.sin(theta)] + ... return dydt + ... + + We assume the constants are `b` = 0.25 and `c` = 5.0: + + >>> b = 0.25 + >>> c = 5.0 + + For initial conditions, we assume the pendulum is nearly vertical + with `theta(0)` = `pi` - 0.1, and is initially at rest, so + `omega(0)` = 0. Then the vector of initial conditions is + + >>> y0 = [np.pi - 0.1, 0.0] + + We will generate a solution at 101 evenly spaced samples in the interval + 0 <= `t` <= 10. So our array of times is: + + >>> t = np.linspace(0, 10, 101) + + Call `odeint` to generate the solution. To pass the parameters + `b` and `c` to `pend`, we give them to `odeint` using the `args` + argument. + + >>> from scipy.integrate import odeint + >>> sol = odeint(pend, y0, t, args=(b, c)) + + The solution is an array with shape (101, 2). The first column + is `theta(t)`, and the second is `omega(t)`. The following code + plots both components. + + >>> import matplotlib.pyplot as plt + >>> plt.plot(t, sol[:, 0], 'b', label='theta(t)') + >>> plt.plot(t, sol[:, 1], 'g', label='omega(t)') + >>> plt.legend(loc='best') + >>> plt.xlabel('t') + >>> plt.grid() + >>> plt.show() + """ + + if ml is None: + ml = -1 # changed to zero inside function call + if mu is None: + mu = -1 # changed to zero inside function call + + dt = np.diff(t) + if not ((dt >= 0).all() or (dt <= 0).all()): + raise ValueError("The values in t must be monotonically increasing " + "or monotonically decreasing; repeated values are " + "allowed.") + + t = copy(t) + y0 = copy(y0) + output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu, + full_output, rtol, atol, tcrit, h0, hmax, hmin, + ixpr, mxstep, mxhnil, mxordn, mxords, + int(bool(tfirst))) + if output[-1] < 0: + warning_msg = (f"{_msgs[output[-1]]} Run with full_output = 1 to " + f"get quantitative information.") + warnings.warn(warning_msg, ODEintWarning, stacklevel=2) + elif printmessg: + warning_msg = _msgs[output[-1]] + warnings.warn(warning_msg, ODEintWarning, stacklevel=2) + + if full_output: + output[1]['message'] = _msgs[output[-1]] + + output = output[:-1] + if len(output) == 1: + return output[0] + else: + return output diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py new file mode 100644 index 0000000000000000000000000000000000000000..7b3382baad7844919c74b2dfd3e56ae74d81325f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py @@ -0,0 +1,656 @@ +import sys +import copy +import heapq +import collections +import functools + +import numpy as np + +from scipy._lib._util import MapWrapper, _FunctionWrapper + + +class LRUDict(collections.OrderedDict): + def __init__(self, max_size): + self.__max_size = max_size + + def __setitem__(self, key, value): + existing_key = (key in self) + super().__setitem__(key, value) + if existing_key: + self.move_to_end(key) + elif len(self) > self.__max_size: + self.popitem(last=False) + + def update(self, other): + # Not needed below + raise NotImplementedError() + + +class SemiInfiniteFunc: + """ + Argument transform from (start, +-oo) to (0, 1) + """ + def __init__(self, func, start, infty): + self._func = func + self._start = start + self._sgn = -1 if infty < 0 else 1 + + # Overflow threshold for the 1/t**2 factor + self._tmin = sys.float_info.min**0.5 + + def get_t(self, x): + z = self._sgn * (x - self._start) + 1 + if z == 0: + # Can happen only if point not in range + return np.inf + return 1 / z + + def __call__(self, t): + if t < self._tmin: + return 0.0 + else: + x = self._start + self._sgn * (1 - t) / t + f = self._func(x) + return self._sgn * (f / t) / t + + +class DoubleInfiniteFunc: + """ + Argument transform from (-oo, oo) to (-1, 1) + """ + def __init__(self, func): + self._func = func + + # Overflow threshold for the 1/t**2 factor + self._tmin = sys.float_info.min**0.5 + + def get_t(self, x): + s = -1 if x < 0 else 1 + return s / (abs(x) + 1) + + def __call__(self, t): + if abs(t) < self._tmin: + return 0.0 + else: + x = (1 - abs(t)) / t + f = self._func(x) + return (f / t) / t + + +def _max_norm(x): + return np.amax(abs(x)) + + +def _get_sizeof(obj): + try: + return sys.getsizeof(obj) + except TypeError: + # occurs on pypy + if hasattr(obj, '__sizeof__'): + return int(obj.__sizeof__()) + return 64 + + +class _Bunch: + def __init__(self, **kwargs): + self.__keys = kwargs.keys() + self.__dict__.update(**kwargs) + + def __repr__(self): + return "_Bunch({})".format(", ".join(f"{k}={repr(self.__dict__[k])}" + for k in self.__keys)) + + +def quad_vec(f, a, b, epsabs=1e-200, epsrel=1e-8, norm='2', cache_size=100e6, + limit=10000, workers=1, points=None, quadrature=None, full_output=False, + *, args=()): + r"""Adaptive integration of a vector-valued function. + + Parameters + ---------- + f : callable + Vector-valued function f(x) to integrate. + a : float + Initial point. + b : float + Final point. + epsabs : float, optional + Absolute tolerance. + epsrel : float, optional + Relative tolerance. + norm : {'max', '2'}, optional + Vector norm to use for error estimation. + cache_size : int, optional + Number of bytes to use for memoization. + limit : float or int, optional + An upper bound on the number of subintervals used in the adaptive + algorithm. + workers : int or map-like callable, optional + If `workers` is an integer, part of the computation is done in + parallel subdivided to this many tasks (using + :class:`python:multiprocessing.pool.Pool`). + Supply `-1` to use all cores available to the Process. + Alternatively, supply a map-like callable, such as + :meth:`python:multiprocessing.pool.Pool.map` for evaluating the + population in parallel. + This evaluation is carried out as ``workers(func, iterable)``. + points : list, optional + List of additional breakpoints. + quadrature : {'gk21', 'gk15', 'trapezoid'}, optional + Quadrature rule to use on subintervals. + Options: 'gk21' (Gauss-Kronrod 21-point rule), + 'gk15' (Gauss-Kronrod 15-point rule), + 'trapezoid' (composite trapezoid rule). + Default: 'gk21' for finite intervals and 'gk15' for (semi-)infinite + full_output : bool, optional + Return an additional ``info`` dictionary. + args : tuple, optional + Extra arguments to pass to function, if any. + + .. versionadded:: 1.8.0 + + Returns + ------- + res : {float, array-like} + Estimate for the result + err : float + Error estimate for the result in the given norm + info : dict + Returned only when ``full_output=True``. + Info dictionary. Is an object with the attributes: + + success : bool + Whether integration reached target precision. + status : int + Indicator for convergence, success (0), + failure (1), and failure due to rounding error (2). + neval : int + Number of function evaluations. + intervals : ndarray, shape (num_intervals, 2) + Start and end points of subdivision intervals. + integrals : ndarray, shape (num_intervals, ...) + Integral for each interval. + Note that at most ``cache_size`` values are recorded, + and the array may contains *nan* for missing items. + errors : ndarray, shape (num_intervals,) + Estimated integration error for each interval. + + Notes + ----- + The algorithm mainly follows the implementation of QUADPACK's + DQAG* algorithms, implementing global error control and adaptive + subdivision. + + The algorithm here has some differences to the QUADPACK approach: + + Instead of subdividing one interval at a time, the algorithm + subdivides N intervals with largest errors at once. This enables + (partial) parallelization of the integration. + + The logic of subdividing "next largest" intervals first is then + not implemented, and we rely on the above extension to avoid + concentrating on "small" intervals only. + + The Wynn epsilon table extrapolation is not used (QUADPACK uses it + for infinite intervals). This is because the algorithm here is + supposed to work on vector-valued functions, in an user-specified + norm, and the extension of the epsilon algorithm to this case does + not appear to be widely agreed. For max-norm, using elementwise + Wynn epsilon could be possible, but we do not do this here with + the hope that the epsilon extrapolation is mainly useful in + special cases. + + References + ---------- + [1] R. Piessens, E. de Doncker, QUADPACK (1983). + + Examples + -------- + We can compute integrations of a vector-valued function: + + >>> from scipy.integrate import quad_vec + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> alpha = np.linspace(0.0, 2.0, num=30) + >>> f = lambda x: x**alpha + >>> x0, x1 = 0, 2 + >>> y, err = quad_vec(f, x0, x1) + >>> plt.plot(alpha, y) + >>> plt.xlabel(r"$\alpha$") + >>> plt.ylabel(r"$\int_{0}^{2} x^\alpha dx$") + >>> plt.show() + + """ + a = float(a) + b = float(b) + + if args: + if not isinstance(args, tuple): + args = (args,) + + # create a wrapped function to allow the use of map and Pool.map + f = _FunctionWrapper(f, args) + + # Use simple transformations to deal with integrals over infinite + # intervals. + kwargs = dict(epsabs=epsabs, + epsrel=epsrel, + norm=norm, + cache_size=cache_size, + limit=limit, + workers=workers, + points=points, + quadrature='gk15' if quadrature is None else quadrature, + full_output=full_output) + if np.isfinite(a) and np.isinf(b): + f2 = SemiInfiniteFunc(f, start=a, infty=b) + if points is not None: + kwargs['points'] = tuple(f2.get_t(xp) for xp in points) + return quad_vec(f2, 0, 1, **kwargs) + elif np.isfinite(b) and np.isinf(a): + f2 = SemiInfiniteFunc(f, start=b, infty=a) + if points is not None: + kwargs['points'] = tuple(f2.get_t(xp) for xp in points) + res = quad_vec(f2, 0, 1, **kwargs) + return (-res[0],) + res[1:] + elif np.isinf(a) and np.isinf(b): + sgn = -1 if b < a else 1 + + # NB. explicitly split integral at t=0, which separates + # the positive and negative sides + f2 = DoubleInfiniteFunc(f) + if points is not None: + kwargs['points'] = (0,) + tuple(f2.get_t(xp) for xp in points) + else: + kwargs['points'] = (0,) + + if a != b: + res = quad_vec(f2, -1, 1, **kwargs) + else: + res = quad_vec(f2, 1, 1, **kwargs) + + return (res[0]*sgn,) + res[1:] + elif not (np.isfinite(a) and np.isfinite(b)): + raise ValueError(f"invalid integration bounds a={a}, b={b}") + + norm_funcs = { + None: _max_norm, + 'max': _max_norm, + '2': np.linalg.norm + } + if callable(norm): + norm_func = norm + else: + norm_func = norm_funcs[norm] + + parallel_count = 128 + min_intervals = 2 + + try: + _quadrature = {None: _quadrature_gk21, + 'gk21': _quadrature_gk21, + 'gk15': _quadrature_gk15, + 'trapz': _quadrature_trapezoid, # alias for backcompat + 'trapezoid': _quadrature_trapezoid}[quadrature] + except KeyError as e: + raise ValueError(f"unknown quadrature {quadrature!r}") from e + + # Initial interval set + if points is None: + initial_intervals = [(a, b)] + else: + prev = a + initial_intervals = [] + for p in sorted(points): + p = float(p) + if not (a < p < b) or p == prev: + continue + initial_intervals.append((prev, p)) + prev = p + initial_intervals.append((prev, b)) + + global_integral = None + global_error = None + rounding_error = None + interval_cache = None + intervals = [] + neval = 0 + + for x1, x2 in initial_intervals: + ig, err, rnd = _quadrature(x1, x2, f, norm_func) + neval += _quadrature.num_eval + + if global_integral is None: + if isinstance(ig, (float, complex)): + # Specialize for scalars + if norm_func in (_max_norm, np.linalg.norm): + norm_func = abs + + global_integral = ig + global_error = float(err) + rounding_error = float(rnd) + + cache_count = cache_size // _get_sizeof(ig) + interval_cache = LRUDict(cache_count) + else: + global_integral += ig + global_error += err + rounding_error += rnd + + interval_cache[(x1, x2)] = copy.copy(ig) + intervals.append((-err, x1, x2)) + + heapq.heapify(intervals) + + CONVERGED = 0 + NOT_CONVERGED = 1 + ROUNDING_ERROR = 2 + NOT_A_NUMBER = 3 + + status_msg = { + CONVERGED: "Target precision reached.", + NOT_CONVERGED: "Target precision not reached.", + ROUNDING_ERROR: "Target precision could not be reached due to rounding error.", + NOT_A_NUMBER: "Non-finite values encountered." + } + + # Process intervals + with MapWrapper(workers) as mapwrapper: + ier = NOT_CONVERGED + + while intervals and len(intervals) < limit: + # Select intervals with largest errors for subdivision + tol = max(epsabs, epsrel*norm_func(global_integral)) + + to_process = [] + err_sum = 0 + + for j in range(parallel_count): + if not intervals: + break + + if j > 0 and err_sum > global_error - tol/8: + # avoid unnecessary parallel splitting + break + + interval = heapq.heappop(intervals) + + neg_old_err, a, b = interval + old_int = interval_cache.pop((a, b), None) + to_process.append( + ((-neg_old_err, a, b, old_int), f, norm_func, _quadrature) + ) + err_sum += -neg_old_err + + # Subdivide intervals + for parts in mapwrapper(_subdivide_interval, to_process): + dint, derr, dround_err, subint, dneval = parts + neval += dneval + global_integral += dint + global_error += derr + rounding_error += dround_err + for x in subint: + x1, x2, ig, err = x + interval_cache[(x1, x2)] = ig + heapq.heappush(intervals, (-err, x1, x2)) + + # Termination check + if len(intervals) >= min_intervals: + tol = max(epsabs, epsrel*norm_func(global_integral)) + if global_error < tol/8: + ier = CONVERGED + break + if global_error < rounding_error: + ier = ROUNDING_ERROR + break + + if not (np.isfinite(global_error) and np.isfinite(rounding_error)): + ier = NOT_A_NUMBER + break + + res = global_integral + err = global_error + rounding_error + + if full_output: + res_arr = np.asarray(res) + dummy = np.full(res_arr.shape, np.nan, dtype=res_arr.dtype) + integrals = np.array([interval_cache.get((z[1], z[2]), dummy) + for z in intervals], dtype=res_arr.dtype) + errors = np.array([-z[0] for z in intervals]) + intervals = np.array([[z[1], z[2]] for z in intervals]) + + info = _Bunch(neval=neval, + success=(ier == CONVERGED), + status=ier, + message=status_msg[ier], + intervals=intervals, + integrals=integrals, + errors=errors) + return (res, err, info) + else: + return (res, err) + + +def _subdivide_interval(args): + interval, f, norm_func, _quadrature = args + old_err, a, b, old_int = interval + + c = 0.5 * (a + b) + + # Left-hand side + if getattr(_quadrature, 'cache_size', 0) > 0: + f = functools.lru_cache(_quadrature.cache_size)(f) + + s1, err1, round1 = _quadrature(a, c, f, norm_func) + dneval = _quadrature.num_eval + s2, err2, round2 = _quadrature(c, b, f, norm_func) + dneval += _quadrature.num_eval + if old_int is None: + old_int, _, _ = _quadrature(a, b, f, norm_func) + dneval += _quadrature.num_eval + + if getattr(_quadrature, 'cache_size', 0) > 0: + dneval = f.cache_info().misses + + dint = s1 + s2 - old_int + derr = err1 + err2 - old_err + dround_err = round1 + round2 + + subintervals = ((a, c, s1, err1), (c, b, s2, err2)) + return dint, derr, dround_err, subintervals, dneval + + +def _quadrature_trapezoid(x1, x2, f, norm_func): + """ + Composite trapezoid quadrature + """ + x3 = 0.5*(x1 + x2) + f1 = f(x1) + f2 = f(x2) + f3 = f(x3) + + s2 = 0.25 * (x2 - x1) * (f1 + 2*f3 + f2) + + round_err = 0.25 * abs(x2 - x1) * (float(norm_func(f1)) + + 2*float(norm_func(f3)) + + float(norm_func(f2))) * 2e-16 + + s1 = 0.5 * (x2 - x1) * (f1 + f2) + err = 1/3 * float(norm_func(s1 - s2)) + return s2, err, round_err + + +_quadrature_trapezoid.cache_size = 3 * 3 +_quadrature_trapezoid.num_eval = 3 + + +def _quadrature_gk(a, b, f, norm_func, x, w, v): + """ + Generic Gauss-Kronrod quadrature + """ + + fv = [0.0]*len(x) + + c = 0.5 * (a + b) + h = 0.5 * (b - a) + + # Gauss-Kronrod + s_k = 0.0 + s_k_abs = 0.0 + for i in range(len(x)): + ff = f(c + h*x[i]) + fv[i] = ff + + vv = v[i] + + # \int f(x) + s_k += vv * ff + # \int |f(x)| + s_k_abs += vv * abs(ff) + + # Gauss + s_g = 0.0 + for i in range(len(w)): + s_g += w[i] * fv[2*i + 1] + + # Quadrature of abs-deviation from average + s_k_dabs = 0.0 + y0 = s_k / 2.0 + for i in range(len(x)): + # \int |f(x) - y0| + s_k_dabs += v[i] * abs(fv[i] - y0) + + # Use similar error estimation as quadpack + err = float(norm_func((s_k - s_g) * h)) + dabs = float(norm_func(s_k_dabs * h)) + if dabs != 0 and err != 0: + err = dabs * min(1.0, (200 * err / dabs)**1.5) + + eps = sys.float_info.epsilon + round_err = float(norm_func(50 * eps * h * s_k_abs)) + + if round_err > sys.float_info.min: + err = max(err, round_err) + + return h * s_k, err, round_err + + +def _quadrature_gk21(a, b, f, norm_func): + """ + Gauss-Kronrod 21 quadrature with error estimate + """ + # Gauss-Kronrod points + x = (0.995657163025808080735527280689003, + 0.973906528517171720077964012084452, + 0.930157491355708226001207180059508, + 0.865063366688984510732096688423493, + 0.780817726586416897063717578345042, + 0.679409568299024406234327365114874, + 0.562757134668604683339000099272694, + 0.433395394129247190799265943165784, + 0.294392862701460198131126603103866, + 0.148874338981631210884826001129720, + 0, + -0.148874338981631210884826001129720, + -0.294392862701460198131126603103866, + -0.433395394129247190799265943165784, + -0.562757134668604683339000099272694, + -0.679409568299024406234327365114874, + -0.780817726586416897063717578345042, + -0.865063366688984510732096688423493, + -0.930157491355708226001207180059508, + -0.973906528517171720077964012084452, + -0.995657163025808080735527280689003) + + # 10-point weights + w = (0.066671344308688137593568809893332, + 0.149451349150580593145776339657697, + 0.219086362515982043995534934228163, + 0.269266719309996355091226921569469, + 0.295524224714752870173892994651338, + 0.295524224714752870173892994651338, + 0.269266719309996355091226921569469, + 0.219086362515982043995534934228163, + 0.149451349150580593145776339657697, + 0.066671344308688137593568809893332) + + # 21-point weights + v = (0.011694638867371874278064396062192, + 0.032558162307964727478818972459390, + 0.054755896574351996031381300244580, + 0.075039674810919952767043140916190, + 0.093125454583697605535065465083366, + 0.109387158802297641899210590325805, + 0.123491976262065851077958109831074, + 0.134709217311473325928054001771707, + 0.142775938577060080797094273138717, + 0.147739104901338491374841515972068, + 0.149445554002916905664936468389821, + 0.147739104901338491374841515972068, + 0.142775938577060080797094273138717, + 0.134709217311473325928054001771707, + 0.123491976262065851077958109831074, + 0.109387158802297641899210590325805, + 0.093125454583697605535065465083366, + 0.075039674810919952767043140916190, + 0.054755896574351996031381300244580, + 0.032558162307964727478818972459390, + 0.011694638867371874278064396062192) + + return _quadrature_gk(a, b, f, norm_func, x, w, v) + + +_quadrature_gk21.num_eval = 21 + + +def _quadrature_gk15(a, b, f, norm_func): + """ + Gauss-Kronrod 15 quadrature with error estimate + """ + # Gauss-Kronrod points + x = (0.991455371120812639206854697526329, + 0.949107912342758524526189684047851, + 0.864864423359769072789712788640926, + 0.741531185599394439863864773280788, + 0.586087235467691130294144838258730, + 0.405845151377397166906606412076961, + 0.207784955007898467600689403773245, + 0.000000000000000000000000000000000, + -0.207784955007898467600689403773245, + -0.405845151377397166906606412076961, + -0.586087235467691130294144838258730, + -0.741531185599394439863864773280788, + -0.864864423359769072789712788640926, + -0.949107912342758524526189684047851, + -0.991455371120812639206854697526329) + + # 7-point weights + w = (0.129484966168869693270611432679082, + 0.279705391489276667901467771423780, + 0.381830050505118944950369775488975, + 0.417959183673469387755102040816327, + 0.381830050505118944950369775488975, + 0.279705391489276667901467771423780, + 0.129484966168869693270611432679082) + + # 15-point weights + v = (0.022935322010529224963732008058970, + 0.063092092629978553290700663189204, + 0.104790010322250183839876322541518, + 0.140653259715525918745189590510238, + 0.169004726639267902826583426598550, + 0.190350578064785409913256402421014, + 0.204432940075298892414161999234649, + 0.209482141084727828012999174891714, + 0.204432940075298892414161999234649, + 0.190350578064785409913256402421014, + 0.169004726639267902826583426598550, + 0.140653259715525918745189590510238, + 0.104790010322250183839876322541518, + 0.063092092629978553290700663189204, + 0.022935322010529224963732008058970) + + return _quadrature_gk(a, b, f, norm_func, x, w, v) + + +_quadrature_gk15.num_eval = 15 diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadpack.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadpack.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b7e9dd2988a04bc5b8e8d016a77b9ec90fdaab30 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadpack.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d200e6ddca8356a793e7fd2381c93f7c9dd6e5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py @@ -0,0 +1,1291 @@ +# Author: Travis Oliphant 2001 +# Author: Nathan Woods 2013 (nquad &c) +import sys +import warnings +from functools import partial + +from . import _quadpack +import numpy as np + +__all__ = ["quad", "dblquad", "tplquad", "nquad", "IntegrationWarning"] + + +error = _quadpack.error + +class IntegrationWarning(UserWarning): + """ + Warning on issues during integration. + """ + pass + + +def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8, + limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50, + limlst=50, complex_func=False): + """ + Compute a definite integral. + + Integrate func from `a` to `b` (possibly infinite interval) using a + technique from the Fortran library QUADPACK. + + Parameters + ---------- + func : {function, scipy.LowLevelCallable} + A Python function or method to integrate. If `func` takes many + arguments, it is integrated along the axis corresponding to the + first argument. + + If the user desires improved integration performance, then `f` may + be a `scipy.LowLevelCallable` with one of the signatures:: + + double func(double x) + double func(double x, void *user_data) + double func(int n, double *xx) + double func(int n, double *xx, void *user_data) + + The ``user_data`` is the data contained in the `scipy.LowLevelCallable`. + In the call forms with ``xx``, ``n`` is the length of the ``xx`` + array which contains ``xx[0] == x`` and the rest of the items are + numbers contained in the ``args`` argument of quad. + + In addition, certain ctypes call signatures are supported for + backward compatibility, but those should not be used in new code. + a : float + Lower limit of integration (use -numpy.inf for -infinity). + b : float + Upper limit of integration (use numpy.inf for +infinity). + args : tuple, optional + Extra arguments to pass to `func`. + full_output : int, optional + Non-zero to return a dictionary of integration information. + If non-zero, warning messages are also suppressed and the + message is appended to the output tuple. + complex_func : bool, optional + Indicate if the function's (`func`) return type is real + (``complex_func=False``: default) or complex (``complex_func=True``). + In both cases, the function's argument is real. + If full_output is also non-zero, the `infodict`, `message`, and + `explain` for the real and complex components are returned in + a dictionary with keys "real output" and "imag output". + + Returns + ------- + y : float + The integral of func from `a` to `b`. + abserr : float + An estimate of the absolute error in the result. + infodict : dict + A dictionary containing additional information. + message + A convergence message. + explain + Appended only with 'cos' or 'sin' weighting and infinite + integration limits, it contains an explanation of the codes in + infodict['ierlst'] + + Other Parameters + ---------------- + epsabs : float or int, optional + Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain + an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))`` + where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the + numerical approximation. See `epsrel` below. + epsrel : float or int, optional + Relative error tolerance. Default is 1.49e-8. + If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29 + and ``50 * (machine epsilon)``. See `epsabs` above. + limit : float or int, optional + An upper bound on the number of subintervals used in the adaptive + algorithm. + points : (sequence of floats,ints), optional + A sequence of break points in the bounded integration interval + where local difficulties of the integrand may occur (e.g., + singularities, discontinuities). The sequence does not have + to be sorted. Note that this option cannot be used in conjunction + with ``weight``. + weight : float or int, optional + String indicating weighting function. Full explanation for this + and the remaining arguments can be found below. + wvar : optional + Variables for use with weighting functions. + wopts : optional + Optional input for reusing Chebyshev moments. + maxp1 : float or int, optional + An upper bound on the number of Chebyshev moments. + limlst : int, optional + Upper bound on the number of cycles (>=3) for use with a sinusoidal + weighting and an infinite end-point. + + See Also + -------- + dblquad : double integral + tplquad : triple integral + nquad : n-dimensional integrals (uses `quad` recursively) + fixed_quad : fixed-order Gaussian quadrature + quadrature : adaptive Gaussian quadrature + odeint : ODE integrator + ode : ODE integrator + simpson : integrator for sampled data + romb : integrator for sampled data + scipy.special : for coefficients and roots of orthogonal polynomials + + Notes + ----- + For valid results, the integral must converge; behavior for divergent + integrals is not guaranteed. + + **Extra information for quad() inputs and outputs** + + If full_output is non-zero, then the third output argument + (infodict) is a dictionary with entries as tabulated below. For + infinite limits, the range is transformed to (0,1) and the + optional outputs are given with respect to this transformed range. + Let M be the input argument limit and let K be infodict['last']. + The entries are: + + 'neval' + The number of function evaluations. + 'last' + The number, K, of subintervals produced in the subdivision process. + 'alist' + A rank-1 array of length M, the first K elements of which are the + left end points of the subintervals in the partition of the + integration range. + 'blist' + A rank-1 array of length M, the first K elements of which are the + right end points of the subintervals. + 'rlist' + A rank-1 array of length M, the first K elements of which are the + integral approximations on the subintervals. + 'elist' + A rank-1 array of length M, the first K elements of which are the + moduli of the absolute error estimates on the subintervals. + 'iord' + A rank-1 integer array of length M, the first L elements of + which are pointers to the error estimates over the subintervals + with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the + sequence ``infodict['iord']`` and let E be the sequence + ``infodict['elist']``. Then ``E[I[1]], ..., E[I[L]]`` forms a + decreasing sequence. + + If the input argument points is provided (i.e., it is not None), + the following additional outputs are placed in the output + dictionary. Assume the points sequence is of length P. + + 'pts' + A rank-1 array of length P+2 containing the integration limits + and the break points of the intervals in ascending order. + This is an array giving the subintervals over which integration + will occur. + 'level' + A rank-1 integer array of length M (=limit), containing the + subdivision levels of the subintervals, i.e., if (aa,bb) is a + subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]`` + are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l + if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``. + 'ndin' + A rank-1 integer array of length P+2. After the first integration + over the intervals (pts[1], pts[2]), the error estimates over some + of the intervals may have been increased artificially in order to + put their subdivision forward. This array has ones in slots + corresponding to the subintervals for which this happens. + + **Weighting the integrand** + + The input variables, *weight* and *wvar*, are used to weight the + integrand by a select list of functions. Different integration + methods are used to compute the integral with these weighting + functions, and these do not support specifying break points. The + possible values of weight and the corresponding weighting functions are. + + ========== =================================== ===================== + ``weight`` Weight function used ``wvar`` + ========== =================================== ===================== + 'cos' cos(w*x) wvar = w + 'sin' sin(w*x) wvar = w + 'alg' g(x) = ((x-a)**alpha)*((b-x)**beta) wvar = (alpha, beta) + 'alg-loga' g(x)*log(x-a) wvar = (alpha, beta) + 'alg-logb' g(x)*log(b-x) wvar = (alpha, beta) + 'alg-log' g(x)*log(x-a)*log(b-x) wvar = (alpha, beta) + 'cauchy' 1/(x-c) wvar = c + ========== =================================== ===================== + + wvar holds the parameter w, (alpha, beta), or c depending on the weight + selected. In these expressions, a and b are the integration limits. + + For the 'cos' and 'sin' weighting, additional inputs and outputs are + available. + + For finite integration limits, the integration is performed using a + Clenshaw-Curtis method which uses Chebyshev moments. For repeated + calculations, these moments are saved in the output dictionary: + + 'momcom' + The maximum level of Chebyshev moments that have been computed, + i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been + computed for intervals of length ``|b-a| * 2**(-l)``, + ``l=0,1,...,M_c``. + 'nnlog' + A rank-1 integer array of length M(=limit), containing the + subdivision levels of the subintervals, i.e., an element of this + array is equal to l if the corresponding subinterval is + ``|b-a|* 2**(-l)``. + 'chebmo' + A rank-2 array of shape (25, maxp1) containing the computed + Chebyshev moments. These can be passed on to an integration + over the same interval by passing this array as the second + element of the sequence wopts and passing infodict['momcom'] as + the first element. + + If one of the integration limits is infinite, then a Fourier integral is + computed (assuming w neq 0). If full_output is 1 and a numerical error + is encountered, besides the error message attached to the output tuple, + a dictionary is also appended to the output tuple which translates the + error codes in the array ``info['ierlst']`` to English messages. The + output information dictionary contains the following entries instead of + 'last', 'alist', 'blist', 'rlist', and 'elist': + + 'lst' + The number of subintervals needed for the integration (call it ``K_f``). + 'rslst' + A rank-1 array of length M_f=limlst, whose first ``K_f`` elements + contain the integral contribution over the interval + ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|`` + and ``k=1,2,...,K_f``. + 'erlst' + A rank-1 array of length ``M_f`` containing the error estimate + corresponding to the interval in the same position in + ``infodict['rslist']``. + 'ierlst' + A rank-1 integer array of length ``M_f`` containing an error flag + corresponding to the interval in the same position in + ``infodict['rslist']``. See the explanation dictionary (last entry + in the output tuple) for the meaning of the codes. + + + **Details of QUADPACK level routines** + + `quad` calls routines from the FORTRAN library QUADPACK. This section + provides details on the conditions for each routine to be called and a + short description of each routine. The routine called depends on + `weight`, `points` and the integration limits `a` and `b`. + + ================ ============== ========== ===================== + QUADPACK routine `weight` `points` infinite bounds + ================ ============== ========== ===================== + qagse None No No + qagie None No Yes + qagpe None Yes No + qawoe 'sin', 'cos' No No + qawfe 'sin', 'cos' No either `a` or `b` + qawse 'alg*' No No + qawce 'cauchy' No No + ================ ============== ========== ===================== + + The following provides a short description from [1]_ for each + routine. + + qagse + is an integrator based on globally adaptive interval + subdivision in connection with extrapolation, which will + eliminate the effects of integrand singularities of + several types. + qagie + handles integration over infinite intervals. The infinite range is + mapped onto a finite interval and subsequently the same strategy as + in ``QAGS`` is applied. + qagpe + serves the same purposes as QAGS, but also allows the + user to provide explicit information about the location + and type of trouble-spots i.e. the abscissae of internal + singularities, discontinuities and other difficulties of + the integrand function. + qawoe + is an integrator for the evaluation of + :math:`\\int^b_a \\cos(\\omega x)f(x)dx` or + :math:`\\int^b_a \\sin(\\omega x)f(x)dx` + over a finite interval [a,b], where :math:`\\omega` and :math:`f` + are specified by the user. The rule evaluation component is based + on the modified Clenshaw-Curtis technique + + An adaptive subdivision scheme is used in connection + with an extrapolation procedure, which is a modification + of that in ``QAGS`` and allows the algorithm to deal with + singularities in :math:`f(x)`. + qawfe + calculates the Fourier transform + :math:`\\int^\\infty_a \\cos(\\omega x)f(x)dx` or + :math:`\\int^\\infty_a \\sin(\\omega x)f(x)dx` + for user-provided :math:`\\omega` and :math:`f`. The procedure of + ``QAWO`` is applied on successive finite intervals, and convergence + acceleration by means of the :math:`\\varepsilon`-algorithm is applied + to the series of integral approximations. + qawse + approximate :math:`\\int^b_a w(x)f(x)dx`, with :math:`a < b` where + :math:`w(x) = (x-a)^{\\alpha}(b-x)^{\\beta}v(x)` with + :math:`\\alpha,\\beta > -1`, where :math:`v(x)` may be one of the + following functions: :math:`1`, :math:`\\log(x-a)`, :math:`\\log(b-x)`, + :math:`\\log(x-a)\\log(b-x)`. + + The user specifies :math:`\\alpha`, :math:`\\beta` and the type of the + function :math:`v`. A globally adaptive subdivision strategy is + applied, with modified Clenshaw-Curtis integration on those + subintervals which contain `a` or `b`. + qawce + compute :math:`\\int^b_a f(x) / (x-c)dx` where the integral must be + interpreted as a Cauchy principal value integral, for user specified + :math:`c` and :math:`f`. The strategy is globally adaptive. Modified + Clenshaw-Curtis integration is used on those intervals containing the + point :math:`x = c`. + + **Integration of Complex Function of a Real Variable** + + A complex valued function, :math:`f`, of a real variable can be written as + :math:`f = g + ih`. Similarly, the integral of :math:`f` can be + written as + + .. math:: + \\int_a^b f(x) dx = \\int_a^b g(x) dx + i\\int_a^b h(x) dx + + assuming that the integrals of :math:`g` and :math:`h` exist + over the interval :math:`[a,b]` [2]_. Therefore, ``quad`` integrates + complex-valued functions by integrating the real and imaginary components + separately. + + + References + ---------- + + .. [1] Piessens, Robert; de Doncker-Kapenga, Elise; + Überhuber, Christoph W.; Kahaner, David (1983). + QUADPACK: A subroutine package for automatic integration. + Springer-Verlag. + ISBN 978-3-540-12553-2. + + .. [2] McCullough, Thomas; Phillips, Keith (1973). + Foundations of Analysis in the Complex Plane. + Holt Rinehart Winston. + ISBN 0-03-086370-8 + + Examples + -------- + Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result + + >>> from scipy import integrate + >>> import numpy as np + >>> x2 = lambda x: x**2 + >>> integrate.quad(x2, 0, 4) + (21.333333333333332, 2.3684757858670003e-13) + >>> print(4**3 / 3.) # analytical result + 21.3333333333 + + Calculate :math:`\\int^\\infty_0 e^{-x} dx` + + >>> invexp = lambda x: np.exp(-x) + >>> integrate.quad(invexp, 0, np.inf) + (1.0, 5.842605999138044e-11) + + Calculate :math:`\\int^1_0 a x \\,dx` for :math:`a = 1, 3` + + >>> f = lambda x, a: a*x + >>> y, err = integrate.quad(f, 0, 1, args=(1,)) + >>> y + 0.5 + >>> y, err = integrate.quad(f, 0, 1, args=(3,)) + >>> y + 1.5 + + Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding + y parameter as 1:: + + testlib.c => + double func(int n, double args[n]){ + return args[0]*args[0] + args[1]*args[1];} + compile to library testlib.* + + :: + + from scipy import integrate + import ctypes + lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path + lib.func.restype = ctypes.c_double + lib.func.argtypes = (ctypes.c_int,ctypes.c_double) + integrate.quad(lib.func,0,1,(1)) + #(1.3333333333333333, 1.4802973661668752e-14) + print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result + # 1.3333333333333333 + + Be aware that pulse shapes and other sharp features as compared to the + size of the integration interval may not be integrated correctly using + this method. A simplified example of this limitation is integrating a + y-axis reflected step function with many zero values within the integrals + bounds. + + >>> y = lambda x: 1 if x<=0 else 0 + >>> integrate.quad(y, -1, 1) + (1.0, 1.1102230246251565e-14) + >>> integrate.quad(y, -1, 100) + (1.0000000002199108, 1.0189464580163188e-08) + >>> integrate.quad(y, -1, 10000) + (0.0, 0.0) + + """ + if not isinstance(args, tuple): + args = (args,) + + # check the limits of integration: \int_a^b, expect a < b + flip, a, b = b < a, min(a, b), max(a, b) + + if complex_func: + def imfunc(x, *args): + return func(x, *args).imag + + def refunc(x, *args): + return func(x, *args).real + + re_retval = quad(refunc, a, b, args, full_output, epsabs, + epsrel, limit, points, weight, wvar, wopts, + maxp1, limlst, complex_func=False) + im_retval = quad(imfunc, a, b, args, full_output, epsabs, + epsrel, limit, points, weight, wvar, wopts, + maxp1, limlst, complex_func=False) + integral = re_retval[0] + 1j*im_retval[0] + error_estimate = re_retval[1] + 1j*im_retval[1] + retval = integral, error_estimate + if full_output: + msgexp = {} + msgexp["real"] = re_retval[2:] + msgexp["imag"] = im_retval[2:] + retval = retval + (msgexp,) + + return retval + + if weight is None: + retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit, + points) + else: + if points is not None: + msg = ("Break points cannot be specified when using weighted integrand.\n" + "Continuing, ignoring specified points.") + warnings.warn(msg, IntegrationWarning, stacklevel=2) + retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel, + limlst, limit, maxp1, weight, wvar, wopts) + + if flip: + retval = (-retval[0],) + retval[1:] + + ier = retval[-1] + if ier == 0: + return retval[:-1] + + msgs = {80: "A Python error occurred possibly while calling the function.", + 1: f"The maximum number of subdivisions ({limit}) has been achieved.\n " + f"If increasing the limit yields no improvement it is advised to " + f"analyze \n the integrand in order to determine the difficulties. " + f"If the position of a \n local difficulty can be determined " + f"(singularity, discontinuity) one will \n probably gain from " + f"splitting up the interval and calling the integrator \n on the " + f"subranges. Perhaps a special-purpose integrator should be used.", + 2: "The occurrence of roundoff error is detected, which prevents \n " + "the requested tolerance from being achieved. " + "The error may be \n underestimated.", + 3: "Extremely bad integrand behavior occurs at some points of the\n " + "integration interval.", + 4: "The algorithm does not converge. Roundoff error is detected\n " + "in the extrapolation table. It is assumed that the requested " + "tolerance\n cannot be achieved, and that the returned result " + "(if full_output = 1) is \n the best which can be obtained.", + 5: "The integral is probably divergent, or slowly convergent.", + 6: "The input is invalid.", + 7: "Abnormal termination of the routine. The estimates for result\n " + "and error are less reliable. It is assumed that the requested " + "accuracy\n has not been achieved.", + 'unknown': "Unknown error."} + + if weight in ['cos','sin'] and (b == np.inf or a == -np.inf): + msgs[1] = ( + "The maximum number of cycles allowed has been achieved., e.e.\n of " + "subintervals (a+(k-1)c, a+kc) where c = (2*int(abs(omega)+1))\n " + "*pi/abs(omega), for k = 1, 2, ..., lst. " + "One can allow more cycles by increasing the value of limlst. " + "Look at info['ierlst'] with full_output=1." + ) + msgs[4] = ( + "The extrapolation table constructed for convergence acceleration\n of " + "the series formed by the integral contributions over the cycles, \n does " + "not converge to within the requested accuracy. " + "Look at \n info['ierlst'] with full_output=1." + ) + msgs[7] = ( + "Bad integrand behavior occurs within one or more of the cycles.\n " + "Location and type of the difficulty involved can be determined from \n " + "the vector info['ierlist'] obtained with full_output=1." + ) + explain = {1: "The maximum number of subdivisions (= limit) has been \n " + "achieved on this cycle.", + 2: "The occurrence of roundoff error is detected and prevents\n " + "the tolerance imposed on this cycle from being achieved.", + 3: "Extremely bad integrand behavior occurs at some points of\n " + "this cycle.", + 4: "The integral over this cycle does not converge (to within the " + "required accuracy) due to roundoff in the extrapolation " + "procedure invoked on this cycle. It is assumed that the result " + "on this interval is the best which can be obtained.", + 5: "The integral over this cycle is probably divergent or " + "slowly convergent."} + + try: + msg = msgs[ier] + except KeyError: + msg = msgs['unknown'] + + if ier in [1,2,3,4,5,7]: + if full_output: + if weight in ['cos', 'sin'] and (b == np.inf or a == -np.inf): + return retval[:-1] + (msg, explain) + else: + return retval[:-1] + (msg,) + else: + warnings.warn(msg, IntegrationWarning, stacklevel=2) + return retval[:-1] + + elif ier == 6: # Forensic decision tree when QUADPACK throws ier=6 + if epsabs <= 0: # Small error tolerance - applies to all methods + if epsrel < max(50 * sys.float_info.epsilon, 5e-29): + msg = ("If 'epsabs'<=0, 'epsrel' must be greater than both" + " 5e-29 and 50*(machine epsilon).") + elif weight in ['sin', 'cos'] and (abs(a) + abs(b) == np.inf): + msg = ("Sine or cosine weighted integrals with infinite domain" + " must have 'epsabs'>0.") + + elif weight is None: + if points is None: # QAGSE/QAGIE + msg = ("Invalid 'limit' argument. There must be" + " at least one subinterval") + else: # QAGPE + if not (min(a, b) <= min(points) <= max(points) <= max(a, b)): + msg = ("All break points in 'points' must lie within the" + " integration limits.") + elif len(points) >= limit: + msg = (f"Number of break points ({len(points):d}) " + f"must be less than subinterval limit ({limit:d})") + + else: + if maxp1 < 1: + msg = "Chebyshev moment limit maxp1 must be >=1." + + elif weight in ('cos', 'sin') and abs(a+b) == np.inf: # QAWFE + msg = "Cycle limit limlst must be >=3." + + elif weight.startswith('alg'): # QAWSE + if min(wvar) < -1: + msg = "wvar parameters (alpha, beta) must both be >= -1." + if b < a: + msg = "Integration limits a, b must satistfy a>> import numpy as np + >>> from scipy import integrate + >>> f = lambda y, x: x*y**2 + >>> integrate.dblquad(f, 0, 2, 0, 1) + (0.6666666666666667, 7.401486830834377e-15) + + Calculate :math:`\\int^{x=\\pi/4}_{x=0} \\int^{y=\\cos(x)}_{y=\\sin(x)} 1 + \\,dy \\,dx`. + + >>> f = lambda y, x: 1 + >>> integrate.dblquad(f, 0, np.pi/4, np.sin, np.cos) + (0.41421356237309503, 1.1083280054755938e-14) + + Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=2-x}_{y=x} a x y \\,dy \\,dx` + for :math:`a=1, 3`. + + >>> f = lambda y, x, a: a*x*y + >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(1,)) + (0.33333333333333337, 5.551115123125783e-15) + >>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(3,)) + (0.9999999999999999, 1.6653345369377348e-14) + + Compute the two-dimensional Gaussian Integral, which is the integral of the + Gaussian function :math:`f(x,y) = e^{-(x^{2} + y^{2})}`, over + :math:`(-\\infty,+\\infty)`. That is, compute the integral + :math:`\\iint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2})} \\,dy\\,dx`. + + >>> f = lambda x, y: np.exp(-(x ** 2 + y ** 2)) + >>> integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf) + (3.141592653589777, 2.5173086737433208e-08) + + """ + + def temp_ranges(*args): + return [gfun(args[0]) if callable(gfun) else gfun, + hfun(args[0]) if callable(hfun) else hfun] + + return nquad(func, [temp_ranges, [a, b]], args=args, + opts={"epsabs": epsabs, "epsrel": epsrel}) + + +def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-8, + epsrel=1.49e-8): + """ + Compute a triple (definite) integral. + + Return the triple integral of ``func(z, y, x)`` from ``x = a..b``, + ``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``. + + Parameters + ---------- + func : function + A Python function or method of at least three variables in the + order (z, y, x). + a, b : float + The limits of integration in x: `a` < `b` + gfun : function or float + The lower boundary curve in y which is a function taking a single + floating point argument (x) and returning a floating point result + or a float indicating a constant boundary curve. + hfun : function or float + The upper boundary curve in y (same requirements as `gfun`). + qfun : function or float + The lower boundary surface in z. It must be a function that takes + two floats in the order (x, y) and returns a float or a float + indicating a constant boundary surface. + rfun : function or float + The upper boundary surface in z. (Same requirements as `qfun`.) + args : tuple, optional + Extra arguments to pass to `func`. + epsabs : float, optional + Absolute tolerance passed directly to the innermost 1-D quadrature + integration. Default is 1.49e-8. + epsrel : float, optional + Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8. + + Returns + ------- + y : float + The resultant integral. + abserr : float + An estimate of the error. + + See Also + -------- + quad : Adaptive quadrature using QUADPACK + quadrature : Adaptive Gaussian quadrature + fixed_quad : Fixed-order Gaussian quadrature + dblquad : Double integrals + nquad : N-dimensional integrals + romb : Integrators for sampled data + simpson : Integrators for sampled data + ode : ODE integrators + odeint : ODE integrators + scipy.special : For coefficients and roots of orthogonal polynomials + + Notes + ----- + For valid results, the integral must converge; behavior for divergent + integrals is not guaranteed. + + **Details of QUADPACK level routines** + + `quad` calls routines from the FORTRAN library QUADPACK. This section + provides details on the conditions for each routine to be called and a + short description of each routine. For each level of integration, ``qagse`` + is used for finite limits or ``qagie`` is used, if either limit (or both!) + are infinite. The following provides a short description from [1]_ for each + routine. + + qagse + is an integrator based on globally adaptive interval + subdivision in connection with extrapolation, which will + eliminate the effects of integrand singularities of + several types. + qagie + handles integration over infinite intervals. The infinite range is + mapped onto a finite interval and subsequently the same strategy as + in ``QAGS`` is applied. + + References + ---------- + + .. [1] Piessens, Robert; de Doncker-Kapenga, Elise; + Überhuber, Christoph W.; Kahaner, David (1983). + QUADPACK: A subroutine package for automatic integration. + Springer-Verlag. + ISBN 978-3-540-12553-2. + + Examples + -------- + Compute the triple integral of ``x * y * z``, over ``x`` ranging + from 1 to 2, ``y`` ranging from 2 to 3, ``z`` ranging from 0 to 1. + That is, :math:`\\int^{x=2}_{x=1} \\int^{y=3}_{y=2} \\int^{z=1}_{z=0} x y z + \\,dz \\,dy \\,dx`. + + >>> import numpy as np + >>> from scipy import integrate + >>> f = lambda z, y, x: x*y*z + >>> integrate.tplquad(f, 1, 2, 2, 3, 0, 1) + (1.8749999999999998, 3.3246447942574074e-14) + + Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1-2x}_{y=0} + \\int^{z=1-x-2y}_{z=0} x y z \\,dz \\,dy \\,dx`. + Note: `qfun`/`rfun` takes arguments in the order (x, y), even though ``f`` + takes arguments in the order (z, y, x). + + >>> f = lambda z, y, x: x*y*z + >>> integrate.tplquad(f, 0, 1, 0, lambda x: 1-2*x, 0, lambda x, y: 1-x-2*y) + (0.05416666666666668, 2.1774196738157757e-14) + + Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1}_{y=0} \\int^{z=1}_{z=0} + a x y z \\,dz \\,dy \\,dx` for :math:`a=1, 3`. + + >>> f = lambda z, y, x, a: a*x*y*z + >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(1,)) + (0.125, 5.527033708952211e-15) + >>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(3,)) + (0.375, 1.6581101126856635e-14) + + Compute the three-dimensional Gaussian Integral, which is the integral of + the Gaussian function :math:`f(x,y,z) = e^{-(x^{2} + y^{2} + z^{2})}`, over + :math:`(-\\infty,+\\infty)`. That is, compute the integral + :math:`\\iiint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2} + z^{2})} \\,dz + \\,dy\\,dx`. + + >>> f = lambda x, y, z: np.exp(-(x ** 2 + y ** 2 + z ** 2)) + >>> integrate.tplquad(f, -np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf) + (5.568327996830833, 4.4619078828029765e-08) + + """ + # f(z, y, x) + # qfun/rfun(x, y) + # gfun/hfun(x) + # nquad will hand (y, x, t0, ...) to ranges0 + # nquad will hand (x, t0, ...) to ranges1 + # Only qfun / rfun is different API... + + def ranges0(*args): + return [qfun(args[1], args[0]) if callable(qfun) else qfun, + rfun(args[1], args[0]) if callable(rfun) else rfun] + + def ranges1(*args): + return [gfun(args[0]) if callable(gfun) else gfun, + hfun(args[0]) if callable(hfun) else hfun] + + ranges = [ranges0, ranges1, [a, b]] + return nquad(func, ranges, args=args, + opts={"epsabs": epsabs, "epsrel": epsrel}) + + +def nquad(func, ranges, args=None, opts=None, full_output=False): + r""" + Integration over multiple variables. + + Wraps `quad` to enable integration over multiple variables. + Various options allow improved integration of discontinuous functions, as + well as the use of weighted integration, and generally finer control of the + integration process. + + Parameters + ---------- + func : {callable, scipy.LowLevelCallable} + The function to be integrated. Has arguments of ``x0, ... xn``, + ``t0, ... tm``, where integration is carried out over ``x0, ... xn``, + which must be floats. Where ``t0, ... tm`` are extra arguments + passed in args. + Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``. + Integration is carried out in order. That is, integration over ``x0`` + is the innermost integral, and ``xn`` is the outermost. + + If the user desires improved integration performance, then `f` may + be a `scipy.LowLevelCallable` with one of the signatures:: + + double func(int n, double *xx) + double func(int n, double *xx, void *user_data) + + where ``n`` is the number of variables and args. The ``xx`` array + contains the coordinates and extra arguments. ``user_data`` is the data + contained in the `scipy.LowLevelCallable`. + ranges : iterable object + Each element of ranges may be either a sequence of 2 numbers, or else + a callable that returns such a sequence. ``ranges[0]`` corresponds to + integration over x0, and so on. If an element of ranges is a callable, + then it will be called with all of the integration arguments available, + as well as any parametric arguments. e.g., if + ``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as + either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``. + args : iterable object, optional + Additional arguments ``t0, ... tn``, required by ``func``, ``ranges``, + and ``opts``. + opts : iterable object or dict, optional + Options to be passed to `quad`. May be empty, a dict, or + a sequence of dicts or functions that return a dict. If empty, the + default options from scipy.integrate.quad are used. If a dict, the same + options are used for all levels of integraion. If a sequence, then each + element of the sequence corresponds to a particular integration. e.g., + ``opts[0]`` corresponds to integration over ``x0``, and so on. If a + callable, the signature must be the same as for ``ranges``. The + available options together with their default values are: + + - epsabs = 1.49e-08 + - epsrel = 1.49e-08 + - limit = 50 + - points = None + - weight = None + - wvar = None + - wopts = None + + For more information on these options, see `quad`. + + full_output : bool, optional + Partial implementation of ``full_output`` from scipy.integrate.quad. + The number of integrand function evaluations ``neval`` can be obtained + by setting ``full_output=True`` when calling nquad. + + Returns + ------- + result : float + The result of the integration. + abserr : float + The maximum of the estimates of the absolute error in the various + integration results. + out_dict : dict, optional + A dict containing additional information on the integration. + + See Also + -------- + quad : 1-D numerical integration + dblquad, tplquad : double and triple integrals + fixed_quad : fixed-order Gaussian quadrature + quadrature : adaptive Gaussian quadrature + + Notes + ----- + For valid results, the integral must converge; behavior for divergent + integrals is not guaranteed. + + **Details of QUADPACK level routines** + + `nquad` calls routines from the FORTRAN library QUADPACK. This section + provides details on the conditions for each routine to be called and a + short description of each routine. The routine called depends on + `weight`, `points` and the integration limits `a` and `b`. + + ================ ============== ========== ===================== + QUADPACK routine `weight` `points` infinite bounds + ================ ============== ========== ===================== + qagse None No No + qagie None No Yes + qagpe None Yes No + qawoe 'sin', 'cos' No No + qawfe 'sin', 'cos' No either `a` or `b` + qawse 'alg*' No No + qawce 'cauchy' No No + ================ ============== ========== ===================== + + The following provides a short description from [1]_ for each + routine. + + qagse + is an integrator based on globally adaptive interval + subdivision in connection with extrapolation, which will + eliminate the effects of integrand singularities of + several types. + qagie + handles integration over infinite intervals. The infinite range is + mapped onto a finite interval and subsequently the same strategy as + in ``QAGS`` is applied. + qagpe + serves the same purposes as QAGS, but also allows the + user to provide explicit information about the location + and type of trouble-spots i.e. the abscissae of internal + singularities, discontinuities and other difficulties of + the integrand function. + qawoe + is an integrator for the evaluation of + :math:`\int^b_a \cos(\omega x)f(x)dx` or + :math:`\int^b_a \sin(\omega x)f(x)dx` + over a finite interval [a,b], where :math:`\omega` and :math:`f` + are specified by the user. The rule evaluation component is based + on the modified Clenshaw-Curtis technique + + An adaptive subdivision scheme is used in connection + with an extrapolation procedure, which is a modification + of that in ``QAGS`` and allows the algorithm to deal with + singularities in :math:`f(x)`. + qawfe + calculates the Fourier transform + :math:`\int^\infty_a \cos(\omega x)f(x)dx` or + :math:`\int^\infty_a \sin(\omega x)f(x)dx` + for user-provided :math:`\omega` and :math:`f`. The procedure of + ``QAWO`` is applied on successive finite intervals, and convergence + acceleration by means of the :math:`\varepsilon`-algorithm is applied + to the series of integral approximations. + qawse + approximate :math:`\int^b_a w(x)f(x)dx`, with :math:`a < b` where + :math:`w(x) = (x-a)^{\alpha}(b-x)^{\beta}v(x)` with + :math:`\alpha,\beta > -1`, where :math:`v(x)` may be one of the + following functions: :math:`1`, :math:`\log(x-a)`, :math:`\log(b-x)`, + :math:`\log(x-a)\log(b-x)`. + + The user specifies :math:`\alpha`, :math:`\beta` and the type of the + function :math:`v`. A globally adaptive subdivision strategy is + applied, with modified Clenshaw-Curtis integration on those + subintervals which contain `a` or `b`. + qawce + compute :math:`\int^b_a f(x) / (x-c)dx` where the integral must be + interpreted as a Cauchy principal value integral, for user specified + :math:`c` and :math:`f`. The strategy is globally adaptive. Modified + Clenshaw-Curtis integration is used on those intervals containing the + point :math:`x = c`. + + References + ---------- + + .. [1] Piessens, Robert; de Doncker-Kapenga, Elise; + Überhuber, Christoph W.; Kahaner, David (1983). + QUADPACK: A subroutine package for automatic integration. + Springer-Verlag. + ISBN 978-3-540-12553-2. + + Examples + -------- + Calculate + + .. math:: + + \int^{1}_{-0.15} \int^{0.8}_{0.13} \int^{1}_{-1} \int^{1}_{0} + f(x_0, x_1, x_2, x_3) \,dx_0 \,dx_1 \,dx_2 \,dx_3 , + + where + + .. math:: + + f(x_0, x_1, x_2, x_3) = \begin{cases} + x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+1 & (x_0-0.2 x_3-0.5-0.25 x_1 > 0) \\ + x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+0 & (x_0-0.2 x_3-0.5-0.25 x_1 \leq 0) + \end{cases} . + + >>> import numpy as np + >>> from scipy import integrate + >>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + ( + ... 1 if (x0-.2*x3-.5-.25*x1>0) else 0) + >>> def opts0(*args, **kwargs): + ... return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]} + >>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]], + ... opts=[opts0,{},{},{}], full_output=True) + (1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962}) + + Calculate + + .. math:: + + \int^{t_0+t_1+1}_{t_0+t_1-1} + \int^{x_2+t_0^2 t_1^3+1}_{x_2+t_0^2 t_1^3-1} + \int^{t_0 x_1+t_1 x_2+1}_{t_0 x_1+t_1 x_2-1} + f(x_0,x_1, x_2,t_0,t_1) + \,dx_0 \,dx_1 \,dx_2, + + where + + .. math:: + + f(x_0, x_1, x_2, t_0, t_1) = \begin{cases} + x_0 x_2^2 + \sin{x_1}+2 & (x_0+t_1 x_1-t_0 > 0) \\ + x_0 x_2^2 +\sin{x_1}+1 & (x_0+t_1 x_1-t_0 \leq 0) + \end{cases} + + and :math:`(t_0, t_1) = (0, 1)` . + + >>> def func2(x0, x1, x2, t0, t1): + ... return x0*x2**2 + np.sin(x1) + 1 + (1 if x0+t1*x1-t0>0 else 0) + >>> def lim0(x1, x2, t0, t1): + ... return [t0*x1 + t1*x2 - 1, t0*x1 + t1*x2 + 1] + >>> def lim1(x2, t0, t1): + ... return [x2 + t0**2*t1**3 - 1, x2 + t0**2*t1**3 + 1] + >>> def lim2(t0, t1): + ... return [t0 + t1 - 1, t0 + t1 + 1] + >>> def opts0(x1, x2, t0, t1): + ... return {'points' : [t0 - t1*x1]} + >>> def opts1(x2, t0, t1): + ... return {} + >>> def opts2(t0, t1): + ... return {} + >>> integrate.nquad(func2, [lim0, lim1, lim2], args=(0,1), + ... opts=[opts0, opts1, opts2]) + (36.099919226771625, 1.8546948553373528e-07) + + """ + depth = len(ranges) + ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges] + if args is None: + args = () + if opts is None: + opts = [dict([])] * depth + + if isinstance(opts, dict): + opts = [_OptFunc(opts)] * depth + else: + opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts] + return _NQuad(func, ranges, opts, full_output).integrate(*args) + + +class _RangeFunc: + def __init__(self, range_): + self.range_ = range_ + + def __call__(self, *args): + """Return stored value. + + *args needed because range_ can be float or func, and is called with + variable number of parameters. + """ + return self.range_ + + +class _OptFunc: + def __init__(self, opt): + self.opt = opt + + def __call__(self, *args): + """Return stored dict.""" + return self.opt + + +class _NQuad: + def __init__(self, func, ranges, opts, full_output): + self.abserr = 0 + self.func = func + self.ranges = ranges + self.opts = opts + self.maxdepth = len(ranges) + self.full_output = full_output + if self.full_output: + self.out_dict = {'neval': 0} + + def integrate(self, *args, **kwargs): + depth = kwargs.pop('depth', 0) + if kwargs: + raise ValueError('unexpected kwargs') + + # Get the integration range and options for this depth. + ind = -(depth + 1) + fn_range = self.ranges[ind] + low, high = fn_range(*args) + fn_opt = self.opts[ind] + opt = dict(fn_opt(*args)) + + if 'points' in opt: + opt['points'] = [x for x in opt['points'] if low <= x <= high] + if depth + 1 == self.maxdepth: + f = self.func + else: + f = partial(self.integrate, depth=depth+1) + quad_r = quad(f, low, high, args=args, full_output=self.full_output, + **opt) + value = quad_r[0] + abserr = quad_r[1] + if self.full_output: + infodict = quad_r[2] + # The 'neval' parameter in full_output returns the total + # number of times the integrand function was evaluated. + # Therefore, only the innermost integration loop counts. + if depth + 1 == self.maxdepth: + self.out_dict['neval'] += infodict['neval'] + self.abserr = max(self.abserr, abserr) + if depth > 0: + return value + else: + # Final result of N-D integration with error + if self.full_output: + return value, self.abserr, self.out_dict + else: + return value, self.abserr diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadrature.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadrature.py new file mode 100644 index 0000000000000000000000000000000000000000..a80040c47f4df2e7bff9430960d64c9a62f00b01 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_quadrature.py @@ -0,0 +1,1830 @@ +from __future__ import annotations +from typing import TYPE_CHECKING, Callable, Any, cast +import numpy as np +import numpy.typing as npt +import math +import warnings +from collections import namedtuple + +from scipy.special import roots_legendre +from scipy.special import gammaln, logsumexp +from scipy._lib._util import _rng_spawn +from scipy._lib.deprecation import (_NoValue, _deprecate_positional_args, + _deprecated) + + +__all__ = ['fixed_quad', 'quadrature', 'romberg', 'romb', + 'trapezoid', 'trapz', 'simps', 'simpson', + 'cumulative_trapezoid', 'cumtrapz', 'newton_cotes', + 'qmc_quad', 'AccuracyWarning', 'cumulative_simpson'] + + +def trapezoid(y, x=None, dx=1.0, axis=-1): + r""" + Integrate along the given axis using the composite trapezoidal rule. + + If `x` is provided, the integration happens in sequence along its + elements - they are not sorted. + + Integrate `y` (`x`) along each 1d slice on the given axis, compute + :math:`\int y(x) dx`. + When `x` is specified, this integrates along the parametric curve, + computing :math:`\int_t y(t) dt = + \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`. + + Parameters + ---------- + y : array_like + Input array to integrate. + x : array_like, optional + The sample points corresponding to the `y` values. If `x` is None, + the sample points are assumed to be evenly spaced `dx` apart. The + default is None. + dx : scalar, optional + The spacing between sample points when `x` is None. The default is 1. + axis : int, optional + The axis along which to integrate. + + Returns + ------- + trapezoid : float or ndarray + Definite integral of `y` = n-dimensional array as approximated along + a single axis by the trapezoidal rule. If `y` is a 1-dimensional array, + then the result is a float. If `n` is greater than 1, then the result + is an `n`-1 dimensional array. + + See Also + -------- + cumulative_trapezoid, simpson, romb + + Notes + ----- + Image [2]_ illustrates trapezoidal rule -- y-axis locations of points + will be taken from `y` array, by default x-axis distances between + points will be 1.0, alternatively they can be provided with `x` array + or with `dx` scalar. Return value will be equal to combined area under + the red lines. + + References + ---------- + .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule + + .. [2] Illustration image: + https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png + + Examples + -------- + Use the trapezoidal rule on evenly spaced points: + + >>> import numpy as np + >>> from scipy import integrate + >>> integrate.trapezoid([1, 2, 3]) + 4.0 + + The spacing between sample points can be selected by either the + ``x`` or ``dx`` arguments: + + >>> integrate.trapezoid([1, 2, 3], x=[4, 6, 8]) + 8.0 + >>> integrate.trapezoid([1, 2, 3], dx=2) + 8.0 + + Using a decreasing ``x`` corresponds to integrating in reverse: + + >>> integrate.trapezoid([1, 2, 3], x=[8, 6, 4]) + -8.0 + + More generally ``x`` is used to integrate along a parametric curve. We can + estimate the integral :math:`\int_0^1 x^2 = 1/3` using: + + >>> x = np.linspace(0, 1, num=50) + >>> y = x**2 + >>> integrate.trapezoid(y, x) + 0.33340274885464394 + + Or estimate the area of a circle, noting we repeat the sample which closes + the curve: + + >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True) + >>> integrate.trapezoid(np.cos(theta), x=np.sin(theta)) + 3.141571941375841 + + ``trapezoid`` can be applied along a specified axis to do multiple + computations in one call: + + >>> a = np.arange(6).reshape(2, 3) + >>> a + array([[0, 1, 2], + [3, 4, 5]]) + >>> integrate.trapezoid(a, axis=0) + array([1.5, 2.5, 3.5]) + >>> integrate.trapezoid(a, axis=1) + array([2., 8.]) + """ + y = np.asanyarray(y) + if x is None: + d = dx + else: + x = np.asanyarray(x) + if x.ndim == 1: + d = np.diff(x) + # reshape to correct shape + shape = [1]*y.ndim + shape[axis] = d.shape[0] + d = d.reshape(shape) + else: + d = np.diff(x, axis=axis) + nd = y.ndim + slice1 = [slice(None)]*nd + slice2 = [slice(None)]*nd + slice1[axis] = slice(1, None) + slice2[axis] = slice(None, -1) + try: + ret = (d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0).sum(axis) + except ValueError: + # Operations didn't work, cast to ndarray + d = np.asarray(d) + y = np.asarray(y) + ret = np.add.reduce(d * (y[tuple(slice1)]+y[tuple(slice2)])/2.0, axis) + return ret + + +# Note: alias kept for backwards compatibility. Rename was done +# because trapz is a slur in colloquial English (see gh-12924). +def trapz(y, x=None, dx=1.0, axis=-1): + """An alias of `trapezoid`. + + `trapz` is kept for backwards compatibility. For new code, prefer + `trapezoid` instead. + """ + msg = ("'scipy.integrate.trapz' is deprecated in favour of " + "'scipy.integrate.trapezoid' and will be removed in SciPy 1.14.0") + warnings.warn(msg, DeprecationWarning, stacklevel=2) + return trapezoid(y, x=x, dx=dx, axis=axis) + + +class AccuracyWarning(Warning): + pass + + +if TYPE_CHECKING: + # workaround for mypy function attributes see: + # https://github.com/python/mypy/issues/2087#issuecomment-462726600 + from typing import Protocol + + class CacheAttributes(Protocol): + cache: dict[int, tuple[Any, Any]] +else: + CacheAttributes = Callable + + +def cache_decorator(func: Callable) -> CacheAttributes: + return cast(CacheAttributes, func) + + +@cache_decorator +def _cached_roots_legendre(n): + """ + Cache roots_legendre results to speed up calls of the fixed_quad + function. + """ + if n in _cached_roots_legendre.cache: + return _cached_roots_legendre.cache[n] + + _cached_roots_legendre.cache[n] = roots_legendre(n) + return _cached_roots_legendre.cache[n] + + +_cached_roots_legendre.cache = dict() + + +def fixed_quad(func, a, b, args=(), n=5): + """ + Compute a definite integral using fixed-order Gaussian quadrature. + + Integrate `func` from `a` to `b` using Gaussian quadrature of + order `n`. + + Parameters + ---------- + func : callable + A Python function or method to integrate (must accept vector inputs). + If integrating a vector-valued function, the returned array must have + shape ``(..., len(x))``. + a : float + Lower limit of integration. + b : float + Upper limit of integration. + args : tuple, optional + Extra arguments to pass to function, if any. + n : int, optional + Order of quadrature integration. Default is 5. + + Returns + ------- + val : float + Gaussian quadrature approximation to the integral + none : None + Statically returned value of None + + See Also + -------- + quad : adaptive quadrature using QUADPACK + dblquad : double integrals + tplquad : triple integrals + romberg : adaptive Romberg quadrature + quadrature : adaptive Gaussian quadrature + romb : integrators for sampled data + simpson : integrators for sampled data + cumulative_trapezoid : cumulative integration for sampled data + ode : ODE integrator + odeint : ODE integrator + + Examples + -------- + >>> from scipy import integrate + >>> import numpy as np + >>> f = lambda x: x**8 + >>> integrate.fixed_quad(f, 0.0, 1.0, n=4) + (0.1110884353741496, None) + >>> integrate.fixed_quad(f, 0.0, 1.0, n=5) + (0.11111111111111102, None) + >>> print(1/9.0) # analytical result + 0.1111111111111111 + + >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=4) + (0.9999999771971152, None) + >>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=5) + (1.000000000039565, None) + >>> np.sin(np.pi/2)-np.sin(0) # analytical result + 1.0 + + """ + x, w = _cached_roots_legendre(n) + x = np.real(x) + if np.isinf(a) or np.isinf(b): + raise ValueError("Gaussian quadrature is only available for " + "finite limits.") + y = (b-a)*(x+1)/2.0 + a + return (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1), None + + +def vectorize1(func, args=(), vec_func=False): + """Vectorize the call to a function. + + This is an internal utility function used by `romberg` and + `quadrature` to create a vectorized version of a function. + + If `vec_func` is True, the function `func` is assumed to take vector + arguments. + + Parameters + ---------- + func : callable + User defined function. + args : tuple, optional + Extra arguments for the function. + vec_func : bool, optional + True if the function func takes vector arguments. + + Returns + ------- + vfunc : callable + A function that will take a vector argument and return the + result. + + """ + if vec_func: + def vfunc(x): + return func(x, *args) + else: + def vfunc(x): + if np.isscalar(x): + return func(x, *args) + x = np.asarray(x) + # call with first point to get output type + y0 = func(x[0], *args) + n = len(x) + dtype = getattr(y0, 'dtype', type(y0)) + output = np.empty((n,), dtype=dtype) + output[0] = y0 + for i in range(1, n): + output[i] = func(x[i], *args) + return output + return vfunc + + +@_deprecated("`scipy.integrate.quadrature` is deprecated as of SciPy 1.12.0" + "and will be removed in SciPy 1.15.0. Please use" + "`scipy.integrate.quad` instead.") +def quadrature(func, a, b, args=(), tol=1.49e-8, rtol=1.49e-8, maxiter=50, + vec_func=True, miniter=1): + """ + Compute a definite integral using fixed-tolerance Gaussian quadrature. + + .. deprecated:: 1.12.0 + + This function is deprecated as of SciPy 1.12.0 and will be removed + in SciPy 1.15.0. Please use `scipy.integrate.quad` instead. + + Integrate `func` from `a` to `b` using Gaussian quadrature + with absolute tolerance `tol`. + + Parameters + ---------- + func : function + A Python function or method to integrate. + a : float + Lower limit of integration. + b : float + Upper limit of integration. + args : tuple, optional + Extra arguments to pass to function. + tol, rtol : float, optional + Iteration stops when error between last two iterates is less than + `tol` OR the relative change is less than `rtol`. + maxiter : int, optional + Maximum order of Gaussian quadrature. + vec_func : bool, optional + True or False if func handles arrays as arguments (is + a "vector" function). Default is True. + miniter : int, optional + Minimum order of Gaussian quadrature. + + Returns + ------- + val : float + Gaussian quadrature approximation (within tolerance) to integral. + err : float + Difference between last two estimates of the integral. + + See Also + -------- + romberg : adaptive Romberg quadrature + fixed_quad : fixed-order Gaussian quadrature + quad : adaptive quadrature using QUADPACK + dblquad : double integrals + tplquad : triple integrals + romb : integrator for sampled data + simpson : integrator for sampled data + cumulative_trapezoid : cumulative integration for sampled data + ode : ODE integrator + odeint : ODE integrator + + Examples + -------- + >>> from scipy import integrate + >>> import numpy as np + >>> f = lambda x: x**8 + >>> integrate.quadrature(f, 0.0, 1.0) + (0.11111111111111106, 4.163336342344337e-17) + >>> print(1/9.0) # analytical result + 0.1111111111111111 + + >>> integrate.quadrature(np.cos, 0.0, np.pi/2) + (0.9999999999999536, 3.9611425250996035e-11) + >>> np.sin(np.pi/2)-np.sin(0) # analytical result + 1.0 + + """ + if not isinstance(args, tuple): + args = (args,) + vfunc = vectorize1(func, args, vec_func=vec_func) + val = np.inf + err = np.inf + maxiter = max(miniter+1, maxiter) + for n in range(miniter, maxiter+1): + newval = fixed_quad(vfunc, a, b, (), n)[0] + err = abs(newval-val) + val = newval + + if err < tol or err < rtol*abs(val): + break + else: + warnings.warn( + "maxiter (%d) exceeded. Latest difference = %e" % (maxiter, err), + AccuracyWarning, stacklevel=2 + ) + return val, err + + +def tupleset(t, i, value): + l = list(t) + l[i] = value + return tuple(l) + + +# Note: alias kept for backwards compatibility. Rename was done +# because cumtrapz is a slur in colloquial English (see gh-12924). +def cumtrapz(y, x=None, dx=1.0, axis=-1, initial=None): + """An alias of `cumulative_trapezoid`. + + `cumtrapz` is kept for backwards compatibility. For new code, prefer + `cumulative_trapezoid` instead. + """ + msg = ("'scipy.integrate.cumtrapz' is deprecated in favour of " + "'scipy.integrate.cumulative_trapezoid' and will be removed " + "in SciPy 1.14.0") + warnings.warn(msg, DeprecationWarning, stacklevel=2) + return cumulative_trapezoid(y, x=x, dx=dx, axis=axis, initial=initial) + + +def cumulative_trapezoid(y, x=None, dx=1.0, axis=-1, initial=None): + """ + Cumulatively integrate y(x) using the composite trapezoidal rule. + + Parameters + ---------- + y : array_like + Values to integrate. + x : array_like, optional + The coordinate to integrate along. If None (default), use spacing `dx` + between consecutive elements in `y`. + dx : float, optional + Spacing between elements of `y`. Only used if `x` is None. + axis : int, optional + Specifies the axis to cumulate. Default is -1 (last axis). + initial : scalar, optional + If given, insert this value at the beginning of the returned result. + 0 or None are the only values accepted. Default is None, which means + `res` has one element less than `y` along the axis of integration. + + .. deprecated:: 1.12.0 + The option for non-zero inputs for `initial` will be deprecated in + SciPy 1.15.0. After this time, a ValueError will be raised if + `initial` is not None or 0. + + Returns + ------- + res : ndarray + The result of cumulative integration of `y` along `axis`. + If `initial` is None, the shape is such that the axis of integration + has one less value than `y`. If `initial` is given, the shape is equal + to that of `y`. + + See Also + -------- + numpy.cumsum, numpy.cumprod + cumulative_simpson : cumulative integration using Simpson's 1/3 rule + quad : adaptive quadrature using QUADPACK + romberg : adaptive Romberg quadrature + quadrature : adaptive Gaussian quadrature + fixed_quad : fixed-order Gaussian quadrature + dblquad : double integrals + tplquad : triple integrals + romb : integrators for sampled data + ode : ODE integrators + odeint : ODE integrators + + Examples + -------- + >>> from scipy import integrate + >>> import numpy as np + >>> import matplotlib.pyplot as plt + + >>> x = np.linspace(-2, 2, num=20) + >>> y = x + >>> y_int = integrate.cumulative_trapezoid(y, x, initial=0) + >>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-') + >>> plt.show() + + """ + y = np.asarray(y) + if y.shape[axis] == 0: + raise ValueError("At least one point is required along `axis`.") + if x is None: + d = dx + else: + x = np.asarray(x) + if x.ndim == 1: + d = np.diff(x) + # reshape to correct shape + shape = [1] * y.ndim + shape[axis] = -1 + d = d.reshape(shape) + elif len(x.shape) != len(y.shape): + raise ValueError("If given, shape of x must be 1-D or the " + "same as y.") + else: + d = np.diff(x, axis=axis) + + if d.shape[axis] != y.shape[axis] - 1: + raise ValueError("If given, length of x along axis must be the " + "same as y.") + + nd = len(y.shape) + slice1 = tupleset((slice(None),)*nd, axis, slice(1, None)) + slice2 = tupleset((slice(None),)*nd, axis, slice(None, -1)) + res = np.cumsum(d * (y[slice1] + y[slice2]) / 2.0, axis=axis) + + if initial is not None: + if initial != 0: + warnings.warn( + "The option for values for `initial` other than None or 0 is " + "deprecated as of SciPy 1.12.0 and will raise a value error in" + " SciPy 1.15.0.", + DeprecationWarning, stacklevel=2 + ) + if not np.isscalar(initial): + raise ValueError("`initial` parameter should be a scalar.") + + shape = list(res.shape) + shape[axis] = 1 + res = np.concatenate([np.full(shape, initial, dtype=res.dtype), res], + axis=axis) + + return res + + +def _basic_simpson(y, start, stop, x, dx, axis): + nd = len(y.shape) + if start is None: + start = 0 + step = 2 + slice_all = (slice(None),)*nd + slice0 = tupleset(slice_all, axis, slice(start, stop, step)) + slice1 = tupleset(slice_all, axis, slice(start+1, stop+1, step)) + slice2 = tupleset(slice_all, axis, slice(start+2, stop+2, step)) + + if x is None: # Even-spaced Simpson's rule. + result = np.sum(y[slice0] + 4.0*y[slice1] + y[slice2], axis=axis) + result *= dx / 3.0 + else: + # Account for possibly different spacings. + # Simpson's rule changes a bit. + h = np.diff(x, axis=axis) + sl0 = tupleset(slice_all, axis, slice(start, stop, step)) + sl1 = tupleset(slice_all, axis, slice(start+1, stop+1, step)) + h0 = h[sl0].astype(float, copy=False) + h1 = h[sl1].astype(float, copy=False) + hsum = h0 + h1 + hprod = h0 * h1 + h0divh1 = np.true_divide(h0, h1, out=np.zeros_like(h0), where=h1 != 0) + tmp = hsum/6.0 * (y[slice0] * + (2.0 - np.true_divide(1.0, h0divh1, + out=np.zeros_like(h0divh1), + where=h0divh1 != 0)) + + y[slice1] * (hsum * + np.true_divide(hsum, hprod, + out=np.zeros_like(hsum), + where=hprod != 0)) + + y[slice2] * (2.0 - h0divh1)) + result = np.sum(tmp, axis=axis) + return result + + +# Note: alias kept for backwards compatibility. simps was renamed to simpson +# because the former is a slur in colloquial English (see gh-12924). +def simps(y, x=None, dx=1.0, axis=-1, even=_NoValue): + """An alias of `simpson`. + + `simps` is kept for backwards compatibility. For new code, prefer + `simpson` instead. + """ + msg = ("'scipy.integrate.simps' is deprecated in favour of " + "'scipy.integrate.simpson' and will be removed in SciPy 1.14.0") + warnings.warn(msg, DeprecationWarning, stacklevel=2) + # we don't deprecate positional use as the wrapper is going away completely + return simpson(y, x=x, dx=dx, axis=axis, even=even) + + +@_deprecate_positional_args(version="1.14") +def simpson(y, *, x=None, dx=1.0, axis=-1, even=_NoValue): + """ + Integrate y(x) using samples along the given axis and the composite + Simpson's rule. If x is None, spacing of dx is assumed. + + If there are an even number of samples, N, then there are an odd + number of intervals (N-1), but Simpson's rule requires an even number + of intervals. The parameter 'even' controls how this is handled. + + Parameters + ---------- + y : array_like + Array to be integrated. + x : array_like, optional + If given, the points at which `y` is sampled. + dx : float, optional + Spacing of integration points along axis of `x`. Only used when + `x` is None. Default is 1. + axis : int, optional + Axis along which to integrate. Default is the last axis. + even : {None, 'simpson', 'avg', 'first', 'last'}, optional + 'avg' : Average two results: + 1) use the first N-2 intervals with + a trapezoidal rule on the last interval and + 2) use the last + N-2 intervals with a trapezoidal rule on the first interval. + + 'first' : Use Simpson's rule for the first N-2 intervals with + a trapezoidal rule on the last interval. + + 'last' : Use Simpson's rule for the last N-2 intervals with a + trapezoidal rule on the first interval. + + None : equivalent to 'simpson' (default) + + 'simpson' : Use Simpson's rule for the first N-2 intervals with the + addition of a 3-point parabolic segment for the last + interval using equations outlined by Cartwright [1]_. + If the axis to be integrated over only has two points then + the integration falls back to a trapezoidal integration. + + .. versionadded:: 1.11.0 + + .. versionchanged:: 1.11.0 + The newly added 'simpson' option is now the default as it is more + accurate in most situations. + + .. deprecated:: 1.11.0 + Parameter `even` is deprecated and will be removed in SciPy + 1.14.0. After this time the behaviour for an even number of + points will follow that of `even='simpson'`. + + Returns + ------- + float + The estimated integral computed with the composite Simpson's rule. + + See Also + -------- + quad : adaptive quadrature using QUADPACK + romberg : adaptive Romberg quadrature + quadrature : adaptive Gaussian quadrature + fixed_quad : fixed-order Gaussian quadrature + dblquad : double integrals + tplquad : triple integrals + romb : integrators for sampled data + cumulative_trapezoid : cumulative integration for sampled data + cumulative_simpson : cumulative integration using Simpson's 1/3 rule + ode : ODE integrators + odeint : ODE integrators + + Notes + ----- + For an odd number of samples that are equally spaced the result is + exact if the function is a polynomial of order 3 or less. If + the samples are not equally spaced, then the result is exact only + if the function is a polynomial of order 2 or less. + + References + ---------- + .. [1] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with + MS Excel and Irregularly-spaced Data. Journal of Mathematical + Sciences and Mathematics Education. 12 (2): 1-9 + + Examples + -------- + >>> from scipy import integrate + >>> import numpy as np + >>> x = np.arange(0, 10) + >>> y = np.arange(0, 10) + + >>> integrate.simpson(y, x=x) + 40.5 + + >>> y = np.power(x, 3) + >>> integrate.simpson(y, x=x) + 1640.5 + >>> integrate.quad(lambda x: x**3, 0, 9)[0] + 1640.25 + + >>> integrate.simpson(y, x=x, even='first') + 1644.5 + + """ + y = np.asarray(y) + nd = len(y.shape) + N = y.shape[axis] + last_dx = dx + first_dx = dx + returnshape = 0 + if x is not None: + x = np.asarray(x) + if len(x.shape) == 1: + shapex = [1] * nd + shapex[axis] = x.shape[0] + saveshape = x.shape + returnshape = 1 + x = x.reshape(tuple(shapex)) + elif len(x.shape) != len(y.shape): + raise ValueError("If given, shape of x must be 1-D or the " + "same as y.") + if x.shape[axis] != N: + raise ValueError("If given, length of x along axis must be the " + "same as y.") + + # even keyword parameter is deprecated + if even is not _NoValue: + warnings.warn( + "The 'even' keyword is deprecated as of SciPy 1.11.0 and will be " + "removed in SciPy 1.14.0", + DeprecationWarning, stacklevel=2 + ) + + if N % 2 == 0: + val = 0.0 + result = 0.0 + slice_all = (slice(None),) * nd + + # default is 'simpson' + even = even if even not in (_NoValue, None) else "simpson" + + if even not in ['avg', 'last', 'first', 'simpson']: + raise ValueError( + "Parameter 'even' must be 'simpson', " + "'avg', 'last', or 'first'." + ) + + if N == 2: + # need at least 3 points in integration axis to form parabolic + # segment. If there are two points then any of 'avg', 'first', + # 'last' should give the same result. + slice1 = tupleset(slice_all, axis, -1) + slice2 = tupleset(slice_all, axis, -2) + if x is not None: + last_dx = x[slice1] - x[slice2] + val += 0.5 * last_dx * (y[slice1] + y[slice2]) + + # calculation is finished. Set `even` to None to skip other + # scenarios + even = None + + if even == 'simpson': + # use Simpson's rule on first intervals + result = _basic_simpson(y, 0, N-3, x, dx, axis) + + slice1 = tupleset(slice_all, axis, -1) + slice2 = tupleset(slice_all, axis, -2) + slice3 = tupleset(slice_all, axis, -3) + + h = np.asarray([dx, dx], dtype=np.float64) + if x is not None: + # grab the last two spacings from the appropriate axis + hm2 = tupleset(slice_all, axis, slice(-2, -1, 1)) + hm1 = tupleset(slice_all, axis, slice(-1, None, 1)) + + diffs = np.float64(np.diff(x, axis=axis)) + h = [np.squeeze(diffs[hm2], axis=axis), + np.squeeze(diffs[hm1], axis=axis)] + + # This is the correction for the last interval according to + # Cartwright. + # However, I used the equations given at + # https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule_for_irregularly_spaced_data + # A footnote on Wikipedia says: + # Cartwright 2017, Equation 8. The equation in Cartwright is + # calculating the first interval whereas the equations in the + # Wikipedia article are adjusting for the last integral. If the + # proper algebraic substitutions are made, the equation results in + # the values shown. + num = 2 * h[1] ** 2 + 3 * h[0] * h[1] + den = 6 * (h[1] + h[0]) + alpha = np.true_divide( + num, + den, + out=np.zeros_like(den), + where=den != 0 + ) + + num = h[1] ** 2 + 3.0 * h[0] * h[1] + den = 6 * h[0] + beta = np.true_divide( + num, + den, + out=np.zeros_like(den), + where=den != 0 + ) + + num = 1 * h[1] ** 3 + den = 6 * h[0] * (h[0] + h[1]) + eta = np.true_divide( + num, + den, + out=np.zeros_like(den), + where=den != 0 + ) + + result += alpha*y[slice1] + beta*y[slice2] - eta*y[slice3] + + # The following code (down to result=result+val) can be removed + # once the 'even' keyword is removed. + + # Compute using Simpson's rule on first intervals + if even in ['avg', 'first']: + slice1 = tupleset(slice_all, axis, -1) + slice2 = tupleset(slice_all, axis, -2) + if x is not None: + last_dx = x[slice1] - x[slice2] + val += 0.5*last_dx*(y[slice1]+y[slice2]) + result = _basic_simpson(y, 0, N-3, x, dx, axis) + # Compute using Simpson's rule on last set of intervals + if even in ['avg', 'last']: + slice1 = tupleset(slice_all, axis, 0) + slice2 = tupleset(slice_all, axis, 1) + if x is not None: + first_dx = x[tuple(slice2)] - x[tuple(slice1)] + val += 0.5*first_dx*(y[slice2]+y[slice1]) + result += _basic_simpson(y, 1, N-2, x, dx, axis) + if even == 'avg': + val /= 2.0 + result /= 2.0 + result = result + val + else: + result = _basic_simpson(y, 0, N-2, x, dx, axis) + if returnshape: + x = x.reshape(saveshape) + return result + + +def _cumulatively_sum_simpson_integrals( + y: np.ndarray, + dx: np.ndarray, + integration_func: Callable[[np.ndarray, np.ndarray], np.ndarray], +) -> np.ndarray: + """Calculate cumulative sum of Simpson integrals. + Takes as input the integration function to be used. + The integration_func is assumed to return the cumulative sum using + composite Simpson's rule. Assumes the axis of summation is -1. + """ + sub_integrals_h1 = integration_func(y, dx) + sub_integrals_h2 = integration_func(y[..., ::-1], dx[..., ::-1])[..., ::-1] + + shape = list(sub_integrals_h1.shape) + shape[-1] += 1 + sub_integrals = np.empty(shape) + sub_integrals[..., :-1:2] = sub_integrals_h1[..., ::2] + sub_integrals[..., 1::2] = sub_integrals_h2[..., ::2] + # Integral over last subinterval can only be calculated from + # formula for h2 + sub_integrals[..., -1] = sub_integrals_h2[..., -1] + res = np.cumsum(sub_integrals, axis=-1) + return res + + +def _cumulative_simpson_equal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray: + """Calculate the Simpson integrals for all h1 intervals assuming equal interval + widths. The function can also be used to calculate the integral for all + h2 intervals by reversing the inputs, `y` and `dx`. + """ + d = dx[..., :-1] + f1 = y[..., :-2] + f2 = y[..., 1:-1] + f3 = y[..., 2:] + + # Calculate integral over the subintervals (eqn (10) of Reference [2]) + return d / 3 * (5 * f1 / 4 + 2 * f2 - f3 / 4) + + +def _cumulative_simpson_unequal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray: + """Calculate the Simpson integrals for all h1 intervals assuming unequal interval + widths. The function can also be used to calculate the integral for all + h2 intervals by reversing the inputs, `y` and `dx`. + """ + x21 = dx[..., :-1] + x32 = dx[..., 1:] + f1 = y[..., :-2] + f2 = y[..., 1:-1] + f3 = y[..., 2:] + + x31 = x21 + x32 + x21_x31 = x21/x31 + x21_x32 = x21/x32 + x21x21_x31x32 = x21_x31 * x21_x32 + + # Calculate integral over the subintervals (eqn (8) of Reference [2]) + coeff1 = 3 - x21_x31 + coeff2 = 3 + x21x21_x31x32 + x21_x31 + coeff3 = -x21x21_x31x32 + + return x21/6 * (coeff1*f1 + coeff2*f2 + coeff3*f3) + + +def _ensure_float_array(arr: npt.ArrayLike) -> np.ndarray: + arr = np.asarray(arr) + if np.issubdtype(arr.dtype, np.integer): + arr = arr.astype(float, copy=False) + return arr + + +def cumulative_simpson(y, *, x=None, dx=1.0, axis=-1, initial=None): + r""" + Cumulatively integrate y(x) using the composite Simpson's 1/3 rule. + The integral of the samples at every point is calculated by assuming a + quadratic relationship between each point and the two adjacent points. + + Parameters + ---------- + y : array_like + Values to integrate. Requires at least one point along `axis`. If two or fewer + points are provided along `axis`, Simpson's integration is not possible and the + result is calculated with `cumulative_trapezoid`. + x : array_like, optional + The coordinate to integrate along. Must have the same shape as `y` or + must be 1D with the same length as `y` along `axis`. `x` must also be + strictly increasing along `axis`. + If `x` is None (default), integration is performed using spacing `dx` + between consecutive elements in `y`. + dx : scalar or array_like, optional + Spacing between elements of `y`. Only used if `x` is None. Can either + be a float, or an array with the same shape as `y`, but of length one along + `axis`. Default is 1.0. + axis : int, optional + Specifies the axis to integrate along. Default is -1 (last axis). + initial : scalar or array_like, optional + If given, insert this value at the beginning of the returned result, + and add it to the rest of the result. Default is None, which means no + value at ``x[0]`` is returned and `res` has one element less than `y` + along the axis of integration. Can either be a float, or an array with + the same shape as `y`, but of length one along `axis`. + + Returns + ------- + res : ndarray + The result of cumulative integration of `y` along `axis`. + If `initial` is None, the shape is such that the axis of integration + has one less value than `y`. If `initial` is given, the shape is equal + to that of `y`. + + See Also + -------- + numpy.cumsum + cumulative_trapezoid : cumulative integration using the composite + trapezoidal rule + simpson : integrator for sampled data using the Composite Simpson's Rule + + Notes + ----- + + .. versionadded:: 1.12.0 + + The composite Simpson's 1/3 method can be used to approximate the definite + integral of a sampled input function :math:`y(x)` [1]_. The method assumes + a quadratic relationship over the interval containing any three consecutive + sampled points. + + Consider three consecutive points: + :math:`(x_1, y_1), (x_2, y_2), (x_3, y_3)`. + + Assuming a quadratic relationship over the three points, the integral over + the subinterval between :math:`x_1` and :math:`x_2` is given by formula + (8) of [2]_: + + .. math:: + \int_{x_1}^{x_2} y(x) dx\ &= \frac{x_2-x_1}{6}\left[\ + \left\{3-\frac{x_2-x_1}{x_3-x_1}\right\} y_1 + \ + \left\{3 + \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} + \ + \frac{x_2-x_1}{x_3-x_1}\right\} y_2\\ + - \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} y_3\right] + + The integral between :math:`x_2` and :math:`x_3` is given by swapping + appearances of :math:`x_1` and :math:`x_3`. The integral is estimated + separately for each subinterval and then cumulatively summed to obtain + the final result. + + For samples that are equally spaced, the result is exact if the function + is a polynomial of order three or less [1]_ and the number of subintervals + is even. Otherwise, the integral is exact for polynomials of order two or + less. + + References + ---------- + .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Simpson's_rule + .. [2] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with + MS Excel and Irregularly-spaced Data. Journal of Mathematical + Sciences and Mathematics Education. 12 (2): 1-9 + + Examples + -------- + >>> from scipy import integrate + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> x = np.linspace(-2, 2, num=20) + >>> y = x**2 + >>> y_int = integrate.cumulative_simpson(y, x=x, initial=0) + >>> fig, ax = plt.subplots() + >>> ax.plot(x, y_int, 'ro', x, x**3/3 - (x[0])**3/3, 'b-') + >>> ax.grid() + >>> plt.show() + + The output of `cumulative_simpson` is similar to that of iteratively + calling `simpson` with successively higher upper limits of integration, but + not identical. + + >>> def cumulative_simpson_reference(y, x): + ... return np.asarray([integrate.simpson(y[:i], x=x[:i]) + ... for i in range(2, len(y) + 1)]) + >>> + >>> rng = np.random.default_rng(354673834679465) + >>> x, y = rng.random(size=(2, 10)) + >>> x.sort() + >>> + >>> res = integrate.cumulative_simpson(y, x=x) + >>> ref = cumulative_simpson_reference(y, x) + >>> equal = np.abs(res - ref) < 1e-15 + >>> equal # not equal when `simpson` has even number of subintervals + array([False, True, False, True, False, True, False, True, True]) + + This is expected: because `cumulative_simpson` has access to more + information than `simpson`, it can typically produce more accurate + estimates of the underlying integral over subintervals. + + """ + y = _ensure_float_array(y) + + # validate `axis` and standardize to work along the last axis + original_y = y + original_shape = y.shape + try: + y = np.swapaxes(y, axis, -1) + except IndexError as e: + message = f"`axis={axis}` is not valid for `y` with `y.ndim={y.ndim}`." + raise ValueError(message) from e + if y.shape[-1] < 3: + res = cumulative_trapezoid(original_y, x, dx=dx, axis=axis, initial=None) + res = np.swapaxes(res, axis, -1) + + elif x is not None: + x = _ensure_float_array(x) + message = ("If given, shape of `x` must be the same as `y` or 1-D with " + "the same length as `y` along `axis`.") + if not (x.shape == original_shape + or (x.ndim == 1 and len(x) == original_shape[axis])): + raise ValueError(message) + + x = np.broadcast_to(x, y.shape) if x.ndim == 1 else np.swapaxes(x, axis, -1) + dx = np.diff(x, axis=-1) + if np.any(dx <= 0): + raise ValueError("Input x must be strictly increasing.") + res = _cumulatively_sum_simpson_integrals( + y, dx, _cumulative_simpson_unequal_intervals + ) + + else: + dx = _ensure_float_array(dx) + final_dx_shape = tupleset(original_shape, axis, original_shape[axis] - 1) + alt_input_dx_shape = tupleset(original_shape, axis, 1) + message = ("If provided, `dx` must either be a scalar or have the same " + "shape as `y` but with only 1 point along `axis`.") + if not (dx.ndim == 0 or dx.shape == alt_input_dx_shape): + raise ValueError(message) + dx = np.broadcast_to(dx, final_dx_shape) + dx = np.swapaxes(dx, axis, -1) + res = _cumulatively_sum_simpson_integrals( + y, dx, _cumulative_simpson_equal_intervals + ) + + if initial is not None: + initial = _ensure_float_array(initial) + alt_initial_input_shape = tupleset(original_shape, axis, 1) + message = ("If provided, `initial` must either be a scalar or have the " + "same shape as `y` but with only 1 point along `axis`.") + if not (initial.ndim == 0 or initial.shape == alt_initial_input_shape): + raise ValueError(message) + initial = np.broadcast_to(initial, alt_initial_input_shape) + initial = np.swapaxes(initial, axis, -1) + + res += initial + res = np.concatenate((initial, res), axis=-1) + + res = np.swapaxes(res, -1, axis) + return res + + +def romb(y, dx=1.0, axis=-1, show=False): + """ + Romberg integration using samples of a function. + + Parameters + ---------- + y : array_like + A vector of ``2**k + 1`` equally-spaced samples of a function. + dx : float, optional + The sample spacing. Default is 1. + axis : int, optional + The axis along which to integrate. Default is -1 (last axis). + show : bool, optional + When `y` is a single 1-D array, then if this argument is True + print the table showing Richardson extrapolation from the + samples. Default is False. + + Returns + ------- + romb : ndarray + The integrated result for `axis`. + + See Also + -------- + quad : adaptive quadrature using QUADPACK + romberg : adaptive Romberg quadrature + quadrature : adaptive Gaussian quadrature + fixed_quad : fixed-order Gaussian quadrature + dblquad : double integrals + tplquad : triple integrals + simpson : integrators for sampled data + cumulative_trapezoid : cumulative integration for sampled data + ode : ODE integrators + odeint : ODE integrators + + Examples + -------- + >>> from scipy import integrate + >>> import numpy as np + >>> x = np.arange(10, 14.25, 0.25) + >>> y = np.arange(3, 12) + + >>> integrate.romb(y) + 56.0 + + >>> y = np.sin(np.power(x, 2.5)) + >>> integrate.romb(y) + -0.742561336672229 + + >>> integrate.romb(y, show=True) + Richardson Extrapolation Table for Romberg Integration + ====================================================== + -0.81576 + 4.63862 6.45674 + -1.10581 -3.02062 -3.65245 + -2.57379 -3.06311 -3.06595 -3.05664 + -1.34093 -0.92997 -0.78776 -0.75160 -0.74256 + ====================================================== + -0.742561336672229 # may vary + + """ + y = np.asarray(y) + nd = len(y.shape) + Nsamps = y.shape[axis] + Ninterv = Nsamps-1 + n = 1 + k = 0 + while n < Ninterv: + n <<= 1 + k += 1 + if n != Ninterv: + raise ValueError("Number of samples must be one plus a " + "non-negative power of 2.") + + R = {} + slice_all = (slice(None),) * nd + slice0 = tupleset(slice_all, axis, 0) + slicem1 = tupleset(slice_all, axis, -1) + h = Ninterv * np.asarray(dx, dtype=float) + R[(0, 0)] = (y[slice0] + y[slicem1])/2.0*h + slice_R = slice_all + start = stop = step = Ninterv + for i in range(1, k+1): + start >>= 1 + slice_R = tupleset(slice_R, axis, slice(start, stop, step)) + step >>= 1 + R[(i, 0)] = 0.5*(R[(i-1, 0)] + h*y[slice_R].sum(axis=axis)) + for j in range(1, i+1): + prev = R[(i, j-1)] + R[(i, j)] = prev + (prev-R[(i-1, j-1)]) / ((1 << (2*j))-1) + h /= 2.0 + + if show: + if not np.isscalar(R[(0, 0)]): + print("*** Printing table only supported for integrals" + + " of a single data set.") + else: + try: + precis = show[0] + except (TypeError, IndexError): + precis = 5 + try: + width = show[1] + except (TypeError, IndexError): + width = 8 + formstr = "%%%d.%df" % (width, precis) + + title = "Richardson Extrapolation Table for Romberg Integration" + print(title, "=" * len(title), sep="\n", end="\n") + for i in range(k+1): + for j in range(i+1): + print(formstr % R[(i, j)], end=" ") + print() + print("=" * len(title)) + + return R[(k, k)] + +# Romberg quadratures for numeric integration. +# +# Written by Scott M. Ransom +# last revision: 14 Nov 98 +# +# Cosmetic changes by Konrad Hinsen +# last revision: 1999-7-21 +# +# Adapted to SciPy by Travis Oliphant +# last revision: Dec 2001 + + +def _difftrap(function, interval, numtraps): + """ + Perform part of the trapezoidal rule to integrate a function. + Assume that we had called difftrap with all lower powers-of-2 + starting with 1. Calling difftrap only returns the summation + of the new ordinates. It does _not_ multiply by the width + of the trapezoids. This must be performed by the caller. + 'function' is the function to evaluate (must accept vector arguments). + 'interval' is a sequence with lower and upper limits + of integration. + 'numtraps' is the number of trapezoids to use (must be a + power-of-2). + """ + if numtraps <= 0: + raise ValueError("numtraps must be > 0 in difftrap().") + elif numtraps == 1: + return 0.5*(function(interval[0])+function(interval[1])) + else: + numtosum = numtraps/2 + h = float(interval[1]-interval[0])/numtosum + lox = interval[0] + 0.5 * h + points = lox + h * np.arange(numtosum) + s = np.sum(function(points), axis=0) + return s + + +def _romberg_diff(b, c, k): + """ + Compute the differences for the Romberg quadrature corrections. + See Forman Acton's "Real Computing Made Real," p 143. + """ + tmp = 4.0**k + return (tmp * c - b)/(tmp - 1.0) + + +def _printresmat(function, interval, resmat): + # Print the Romberg result matrix. + i = j = 0 + print('Romberg integration of', repr(function), end=' ') + print('from', interval) + print('') + print('%6s %9s %9s' % ('Steps', 'StepSize', 'Results')) + for i in range(len(resmat)): + print('%6d %9f' % (2**i, (interval[1]-interval[0])/(2.**i)), end=' ') + for j in range(i+1): + print('%9f' % (resmat[i][j]), end=' ') + print('') + print('') + print('The final result is', resmat[i][j], end=' ') + print('after', 2**(len(resmat)-1)+1, 'function evaluations.') + + +@_deprecated("`scipy.integrate.romberg` is deprecated as of SciPy 1.12.0" + "and will be removed in SciPy 1.15.0. Please use" + "`scipy.integrate.quad` instead.") +def romberg(function, a, b, args=(), tol=1.48e-8, rtol=1.48e-8, show=False, + divmax=10, vec_func=False): + """ + Romberg integration of a callable function or method. + + .. deprecated:: 1.12.0 + + This function is deprecated as of SciPy 1.12.0 and will be removed + in SciPy 1.15.0. Please use `scipy.integrate.quad` instead. + + Returns the integral of `function` (a function of one variable) + over the interval (`a`, `b`). + + If `show` is 1, the triangular array of the intermediate results + will be printed. If `vec_func` is True (default is False), then + `function` is assumed to support vector arguments. + + Parameters + ---------- + function : callable + Function to be integrated. + a : float + Lower limit of integration. + b : float + Upper limit of integration. + + Returns + ------- + results : float + Result of the integration. + + Other Parameters + ---------------- + args : tuple, optional + Extra arguments to pass to function. Each element of `args` will + be passed as a single argument to `func`. Default is to pass no + extra arguments. + tol, rtol : float, optional + The desired absolute and relative tolerances. Defaults are 1.48e-8. + show : bool, optional + Whether to print the results. Default is False. + divmax : int, optional + Maximum order of extrapolation. Default is 10. + vec_func : bool, optional + Whether `func` handles arrays as arguments (i.e., whether it is a + "vector" function). Default is False. + + See Also + -------- + fixed_quad : Fixed-order Gaussian quadrature. + quad : Adaptive quadrature using QUADPACK. + dblquad : Double integrals. + tplquad : Triple integrals. + romb : Integrators for sampled data. + simpson : Integrators for sampled data. + cumulative_trapezoid : Cumulative integration for sampled data. + ode : ODE integrator. + odeint : ODE integrator. + + References + ---------- + .. [1] 'Romberg's method' https://en.wikipedia.org/wiki/Romberg%27s_method + + Examples + -------- + Integrate a gaussian from 0 to 1 and compare to the error function. + + >>> from scipy import integrate + >>> from scipy.special import erf + >>> import numpy as np + >>> gaussian = lambda x: 1/np.sqrt(np.pi) * np.exp(-x**2) + >>> result = integrate.romberg(gaussian, 0, 1, show=True) + Romberg integration of from [0, 1] + + :: + + Steps StepSize Results + 1 1.000000 0.385872 + 2 0.500000 0.412631 0.421551 + 4 0.250000 0.419184 0.421368 0.421356 + 8 0.125000 0.420810 0.421352 0.421350 0.421350 + 16 0.062500 0.421215 0.421350 0.421350 0.421350 0.421350 + 32 0.031250 0.421317 0.421350 0.421350 0.421350 0.421350 0.421350 + + The final result is 0.421350396475 after 33 function evaluations. + + >>> print("%g %g" % (2*result, erf(1))) + 0.842701 0.842701 + + """ + if np.isinf(a) or np.isinf(b): + raise ValueError("Romberg integration only available " + "for finite limits.") + vfunc = vectorize1(function, args, vec_func=vec_func) + n = 1 + interval = [a, b] + intrange = b - a + ordsum = _difftrap(vfunc, interval, n) + result = intrange * ordsum + resmat = [[result]] + err = np.inf + last_row = resmat[0] + for i in range(1, divmax+1): + n *= 2 + ordsum += _difftrap(vfunc, interval, n) + row = [intrange * ordsum / n] + for k in range(i): + row.append(_romberg_diff(last_row[k], row[k], k+1)) + result = row[i] + lastresult = last_row[i-1] + if show: + resmat.append(row) + err = abs(result - lastresult) + if err < tol or err < rtol * abs(result): + break + last_row = row + else: + warnings.warn( + "divmax (%d) exceeded. Latest difference = %e" % (divmax, err), + AccuracyWarning, stacklevel=2) + + if show: + _printresmat(vfunc, interval, resmat) + return result + + +# Coefficients for Newton-Cotes quadrature +# +# These are the points being used +# to construct the local interpolating polynomial +# a are the weights for Newton-Cotes integration +# B is the error coefficient. +# error in these coefficients grows as N gets larger. +# or as samples are closer and closer together + +# You can use maxima to find these rational coefficients +# for equally spaced data using the commands +# a(i,N) := (integrate(product(r-j,j,0,i-1) * product(r-j,j,i+1,N),r,0,N) +# / ((N-i)! * i!) * (-1)^(N-i)); +# Be(N) := N^(N+2)/(N+2)! * (N/(N+3) - sum((i/N)^(N+2)*a(i,N),i,0,N)); +# Bo(N) := N^(N+1)/(N+1)! * (N/(N+2) - sum((i/N)^(N+1)*a(i,N),i,0,N)); +# B(N) := (if (mod(N,2)=0) then Be(N) else Bo(N)); +# +# pre-computed for equally-spaced weights +# +# num_a, den_a, int_a, num_B, den_B = _builtincoeffs[N] +# +# a = num_a*array(int_a)/den_a +# B = num_B*1.0 / den_B +# +# integrate(f(x),x,x_0,x_N) = dx*sum(a*f(x_i)) + B*(dx)^(2k+3) f^(2k+2)(x*) +# where k = N // 2 +# +_builtincoeffs = { + 1: (1,2,[1,1],-1,12), + 2: (1,3,[1,4,1],-1,90), + 3: (3,8,[1,3,3,1],-3,80), + 4: (2,45,[7,32,12,32,7],-8,945), + 5: (5,288,[19,75,50,50,75,19],-275,12096), + 6: (1,140,[41,216,27,272,27,216,41],-9,1400), + 7: (7,17280,[751,3577,1323,2989,2989,1323,3577,751],-8183,518400), + 8: (4,14175,[989,5888,-928,10496,-4540,10496,-928,5888,989], + -2368,467775), + 9: (9,89600,[2857,15741,1080,19344,5778,5778,19344,1080, + 15741,2857], -4671, 394240), + 10: (5,299376,[16067,106300,-48525,272400,-260550,427368, + -260550,272400,-48525,106300,16067], + -673175, 163459296), + 11: (11,87091200,[2171465,13486539,-3237113, 25226685,-9595542, + 15493566,15493566,-9595542,25226685,-3237113, + 13486539,2171465], -2224234463, 237758976000), + 12: (1, 5255250, [1364651,9903168,-7587864,35725120,-51491295, + 87516288,-87797136,87516288,-51491295,35725120, + -7587864,9903168,1364651], -3012, 875875), + 13: (13, 402361344000,[8181904909, 56280729661, -31268252574, + 156074417954,-151659573325,206683437987, + -43111992612,-43111992612,206683437987, + -151659573325,156074417954,-31268252574, + 56280729661,8181904909], -2639651053, + 344881152000), + 14: (7, 2501928000, [90241897,710986864,-770720657,3501442784, + -6625093363,12630121616,-16802270373,19534438464, + -16802270373,12630121616,-6625093363,3501442784, + -770720657,710986864,90241897], -3740727473, + 1275983280000) + } + + +def newton_cotes(rn, equal=0): + r""" + Return weights and error coefficient for Newton-Cotes integration. + + Suppose we have (N+1) samples of f at the positions + x_0, x_1, ..., x_N. Then an N-point Newton-Cotes formula for the + integral between x_0 and x_N is: + + :math:`\int_{x_0}^{x_N} f(x)dx = \Delta x \sum_{i=0}^{N} a_i f(x_i) + + B_N (\Delta x)^{N+2} f^{N+1} (\xi)` + + where :math:`\xi \in [x_0,x_N]` + and :math:`\Delta x = \frac{x_N-x_0}{N}` is the average samples spacing. + + If the samples are equally-spaced and N is even, then the error + term is :math:`B_N (\Delta x)^{N+3} f^{N+2}(\xi)`. + + Parameters + ---------- + rn : int + The integer order for equally-spaced data or the relative positions of + the samples with the first sample at 0 and the last at N, where N+1 is + the length of `rn`. N is the order of the Newton-Cotes integration. + equal : int, optional + Set to 1 to enforce equally spaced data. + + Returns + ------- + an : ndarray + 1-D array of weights to apply to the function at the provided sample + positions. + B : float + Error coefficient. + + Notes + ----- + Normally, the Newton-Cotes rules are used on smaller integration + regions and a composite rule is used to return the total integral. + + Examples + -------- + Compute the integral of sin(x) in [0, :math:`\pi`]: + + >>> from scipy.integrate import newton_cotes + >>> import numpy as np + >>> def f(x): + ... return np.sin(x) + >>> a = 0 + >>> b = np.pi + >>> exact = 2 + >>> for N in [2, 4, 6, 8, 10]: + ... x = np.linspace(a, b, N + 1) + ... an, B = newton_cotes(N, 1) + ... dx = (b - a) / N + ... quad = dx * np.sum(an * f(x)) + ... error = abs(quad - exact) + ... print('{:2d} {:10.9f} {:.5e}'.format(N, quad, error)) + ... + 2 2.094395102 9.43951e-02 + 4 1.998570732 1.42927e-03 + 6 2.000017814 1.78136e-05 + 8 1.999999835 1.64725e-07 + 10 2.000000001 1.14677e-09 + + """ + try: + N = len(rn)-1 + if equal: + rn = np.arange(N+1) + elif np.all(np.diff(rn) == 1): + equal = 1 + except Exception: + N = rn + rn = np.arange(N+1) + equal = 1 + + if equal and N in _builtincoeffs: + na, da, vi, nb, db = _builtincoeffs[N] + an = na * np.array(vi, dtype=float) / da + return an, float(nb)/db + + if (rn[0] != 0) or (rn[-1] != N): + raise ValueError("The sample positions must start at 0" + " and end at N") + yi = rn / float(N) + ti = 2 * yi - 1 + nvec = np.arange(N+1) + C = ti ** nvec[:, np.newaxis] + Cinv = np.linalg.inv(C) + # improve precision of result + for i in range(2): + Cinv = 2*Cinv - Cinv.dot(C).dot(Cinv) + vec = 2.0 / (nvec[::2]+1) + ai = Cinv[:, ::2].dot(vec) * (N / 2.) + + if (N % 2 == 0) and equal: + BN = N/(N+3.) + power = N+2 + else: + BN = N/(N+2.) + power = N+1 + + BN = BN - np.dot(yi**power, ai) + p1 = power+1 + fac = power*math.log(N) - gammaln(p1) + fac = math.exp(fac) + return ai, BN*fac + + +def _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log): + + # lazy import to avoid issues with partially-initialized submodule + if not hasattr(qmc_quad, 'qmc'): + from scipy import stats + qmc_quad.stats = stats + else: + stats = qmc_quad.stats + + if not callable(func): + message = "`func` must be callable." + raise TypeError(message) + + # a, b will be modified, so copy. Oh well if it's copied twice. + a = np.atleast_1d(a).copy() + b = np.atleast_1d(b).copy() + a, b = np.broadcast_arrays(a, b) + dim = a.shape[0] + + try: + func((a + b) / 2) + except Exception as e: + message = ("`func` must evaluate the integrand at points within " + "the integration range; e.g. `func( (a + b) / 2)` " + "must return the integrand at the centroid of the " + "integration volume.") + raise ValueError(message) from e + + try: + func(np.array([a, b]).T) + vfunc = func + except Exception as e: + message = ("Exception encountered when attempting vectorized call to " + f"`func`: {e}. For better performance, `func` should " + "accept two-dimensional array `x` with shape `(len(a), " + "n_points)` and return an array of the integrand value at " + "each of the `n_points.") + warnings.warn(message, stacklevel=3) + + def vfunc(x): + return np.apply_along_axis(func, axis=-1, arr=x) + + n_points_int = np.int64(n_points) + if n_points != n_points_int: + message = "`n_points` must be an integer." + raise TypeError(message) + + n_estimates_int = np.int64(n_estimates) + if n_estimates != n_estimates_int: + message = "`n_estimates` must be an integer." + raise TypeError(message) + + if qrng is None: + qrng = stats.qmc.Halton(dim) + elif not isinstance(qrng, stats.qmc.QMCEngine): + message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine." + raise TypeError(message) + + if qrng.d != a.shape[0]: + message = ("`qrng` must be initialized with dimensionality equal to " + "the number of variables in `a`, i.e., " + "`qrng.random().shape[-1]` must equal `a.shape[0]`.") + raise ValueError(message) + + rng_seed = getattr(qrng, 'rng_seed', None) + rng = stats._qmc.check_random_state(rng_seed) + + if log not in {True, False}: + message = "`log` must be boolean (`True` or `False`)." + raise TypeError(message) + + return (vfunc, a, b, n_points_int, n_estimates_int, qrng, rng, log, stats) + + +QMCQuadResult = namedtuple('QMCQuadResult', ['integral', 'standard_error']) + + +def qmc_quad(func, a, b, *, n_estimates=8, n_points=1024, qrng=None, + log=False): + """ + Compute an integral in N-dimensions using Quasi-Monte Carlo quadrature. + + Parameters + ---------- + func : callable + The integrand. Must accept a single argument ``x``, an array which + specifies the point(s) at which to evaluate the scalar-valued + integrand, and return the value(s) of the integrand. + For efficiency, the function should be vectorized to accept an array of + shape ``(d, n_points)``, where ``d`` is the number of variables (i.e. + the dimensionality of the function domain) and `n_points` is the number + of quadrature points, and return an array of shape ``(n_points,)``, + the integrand at each quadrature point. + a, b : array-like + One-dimensional arrays specifying the lower and upper integration + limits, respectively, of each of the ``d`` variables. + n_estimates, n_points : int, optional + `n_estimates` (default: 8) statistically independent QMC samples, each + of `n_points` (default: 1024) points, will be generated by `qrng`. + The total number of points at which the integrand `func` will be + evaluated is ``n_points * n_estimates``. See Notes for details. + qrng : `~scipy.stats.qmc.QMCEngine`, optional + An instance of the QMCEngine from which to sample QMC points. + The QMCEngine must be initialized to a number of dimensions ``d`` + corresponding with the number of variables ``x1, ..., xd`` passed to + `func`. + The provided QMCEngine is used to produce the first integral estimate. + If `n_estimates` is greater than one, additional QMCEngines are + spawned from the first (with scrambling enabled, if it is an option.) + If a QMCEngine is not provided, the default `scipy.stats.qmc.Halton` + will be initialized with the number of dimensions determine from + the length of `a`. + log : boolean, default: False + When set to True, `func` returns the log of the integrand, and + the result object contains the log of the integral. + + Returns + ------- + result : object + A result object with attributes: + + integral : float + The estimate of the integral. + standard_error : + The error estimate. See Notes for interpretation. + + Notes + ----- + Values of the integrand at each of the `n_points` points of a QMC sample + are used to produce an estimate of the integral. This estimate is drawn + from a population of possible estimates of the integral, the value of + which we obtain depends on the particular points at which the integral + was evaluated. We perform this process `n_estimates` times, each time + evaluating the integrand at different scrambled QMC points, effectively + drawing i.i.d. random samples from the population of integral estimates. + The sample mean :math:`m` of these integral estimates is an + unbiased estimator of the true value of the integral, and the standard + error of the mean :math:`s` of these estimates may be used to generate + confidence intervals using the t distribution with ``n_estimates - 1`` + degrees of freedom. Perhaps counter-intuitively, increasing `n_points` + while keeping the total number of function evaluation points + ``n_points * n_estimates`` fixed tends to reduce the actual error, whereas + increasing `n_estimates` tends to decrease the error estimate. + + Examples + -------- + QMC quadrature is particularly useful for computing integrals in higher + dimensions. An example integrand is the probability density function + of a multivariate normal distribution. + + >>> import numpy as np + >>> from scipy import stats + >>> dim = 8 + >>> mean = np.zeros(dim) + >>> cov = np.eye(dim) + >>> def func(x): + ... # `multivariate_normal` expects the _last_ axis to correspond with + ... # the dimensionality of the space, so `x` must be transposed + ... return stats.multivariate_normal.pdf(x.T, mean, cov) + + To compute the integral over the unit hypercube: + + >>> from scipy.integrate import qmc_quad + >>> a = np.zeros(dim) + >>> b = np.ones(dim) + >>> rng = np.random.default_rng() + >>> qrng = stats.qmc.Halton(d=dim, seed=rng) + >>> n_estimates = 8 + >>> res = qmc_quad(func, a, b, n_estimates=n_estimates, qrng=qrng) + >>> res.integral, res.standard_error + (0.00018429555666024108, 1.0389431116001344e-07) + + A two-sided, 99% confidence interval for the integral may be estimated + as: + + >>> t = stats.t(df=n_estimates-1, loc=res.integral, + ... scale=res.standard_error) + >>> t.interval(0.99) + (0.0001839319802536469, 0.00018465913306683527) + + Indeed, the value reported by `scipy.stats.multivariate_normal` is + within this range. + + >>> stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a) + 0.00018430867675187443 + + """ + args = _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log) + func, a, b, n_points, n_estimates, qrng, rng, log, stats = args + + def sum_product(integrands, dA, log=False): + if log: + return logsumexp(integrands) + np.log(dA) + else: + return np.sum(integrands * dA) + + def mean(estimates, log=False): + if log: + return logsumexp(estimates) - np.log(n_estimates) + else: + return np.mean(estimates) + + def std(estimates, m=None, ddof=0, log=False): + m = m or mean(estimates, log) + if log: + estimates, m = np.broadcast_arrays(estimates, m) + temp = np.vstack((estimates, m + np.pi * 1j)) + diff = logsumexp(temp, axis=0) + return np.real(0.5 * (logsumexp(2 * diff) + - np.log(n_estimates - ddof))) + else: + return np.std(estimates, ddof=ddof) + + def sem(estimates, m=None, s=None, log=False): + m = m or mean(estimates, log) + s = s or std(estimates, m, ddof=1, log=log) + if log: + return s - 0.5*np.log(n_estimates) + else: + return s / np.sqrt(n_estimates) + + # The sign of the integral depends on the order of the limits. Fix this by + # ensuring that lower bounds are indeed lower and setting sign of resulting + # integral manually + if np.any(a == b): + message = ("A lower limit was equal to an upper limit, so the value " + "of the integral is zero by definition.") + warnings.warn(message, stacklevel=2) + return QMCQuadResult(-np.inf if log else 0, 0) + + i_swap = b < a + sign = (-1)**(i_swap.sum(axis=-1)) # odd # of swaps -> negative + a[i_swap], b[i_swap] = b[i_swap], a[i_swap] + + A = np.prod(b - a) + dA = A / n_points + + estimates = np.zeros(n_estimates) + rngs = _rng_spawn(qrng.rng, n_estimates) + for i in range(n_estimates): + # Generate integral estimate + sample = qrng.random(n_points) + # The rationale for transposing is that this allows users to easily + # unpack `x` into separate variables, if desired. This is consistent + # with the `xx` array passed into the `scipy.integrate.nquad` `func`. + x = stats.qmc.scale(sample, a, b).T # (n_dim, n_points) + integrands = func(x) + estimates[i] = sum_product(integrands, dA, log) + + # Get a new, independently-scrambled QRNG for next time + qrng = type(qrng)(seed=rngs[i], **qrng._init_quad) + + integral = mean(estimates, log) + standard_error = sem(estimates, m=integral, log=log) + integral = integral + np.pi*1j if (log and sign < 0) else integral*sign + return QMCQuadResult(integral, standard_error) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py new file mode 100644 index 0000000000000000000000000000000000000000..213b7de4b3c36ce595dbacf3eeeaf92f154fcd26 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py @@ -0,0 +1,1231 @@ +# mypy: disable-error-code="attr-defined" +import numpy as np +from scipy import special +import scipy._lib._elementwise_iterative_method as eim +from scipy._lib._util import _RichResult + +# todo: +# figure out warning situation +# address https://github.com/scipy/scipy/pull/18650#discussion_r1233032521 +# without `minweight`, we are also suppressing infinities within the interval. +# Is that OK? If so, we can probably get rid of `status=3`. +# Add heuristic to stop when improvement is too slow / antithrashing +# support singularities? interval subdivision? this feature will be added +# eventually, but do we adjust the interface now? +# When doing log-integration, should the tolerances control the error of the +# log-integral or the error of the integral? The trouble is that `log` +# inherently looses some precision so it may not be possible to refine +# the integral further. Example: 7th moment of stats.f(15, 20) +# respect function evaluation limit? +# make public? + + +def _tanhsinh(f, a, b, *, args=(), log=False, maxfun=None, maxlevel=None, + minlevel=2, atol=None, rtol=None, preserve_shape=False, + callback=None): + """Evaluate a convergent integral numerically using tanh-sinh quadrature. + + In practice, tanh-sinh quadrature achieves quadratic convergence for + many integrands: the number of accurate *digits* scales roughly linearly + with the number of function evaluations [1]_. + + Either or both of the limits of integration may be infinite, and + singularities at the endpoints are acceptable. Divergent integrals and + integrands with non-finite derivatives or singularities within an interval + are out of scope, but the latter may be evaluated be calling `_tanhsinh` on + each sub-interval separately. + + Parameters + ---------- + f : callable + The function to be integrated. The signature must be:: + func(x: ndarray, *fargs) -> ndarray + where each element of ``x`` is a finite real and ``fargs`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with `x`. ``func`` must be an elementwise-scalar function; see + documentation of parameter `preserve_shape` for details. + If ``func`` returns a value with complex dtype when evaluated at + either endpoint, subsequent arguments ``x`` will have complex dtype + (but zero imaginary part). + a, b : array_like + Real lower and upper limits of integration. Must be broadcastable. + Elements may be infinite. + args : tuple, optional + Additional positional arguments to be passed to `func`. Must be arrays + broadcastable with `a` and `b`. If the callable to be integrated + requires arguments that are not broadcastable with `a` and `b`, wrap + that callable with `f`. See Examples. + log : bool, default: False + Setting to True indicates that `f` returns the log of the integrand + and that `atol` and `rtol` are expressed as the logs of the absolute + and relative errors. In this case, the result object will contain the + log of the integral and error. This is useful for integrands for which + numerical underflow or overflow would lead to inaccuracies. + When ``log=True``, the integrand (the exponential of `f`) must be real, + but it may be negative, in which case the log of the integrand is a + complex number with an imaginary part that is an odd multiple of π. + maxlevel : int, default: 10 + The maximum refinement level of the algorithm. + + At the zeroth level, `f` is called once, performing 16 function + evaluations. At each subsequent level, `f` is called once more, + approximately doubling the number of function evaluations that have + been performed. Accordingly, for many integrands, each successive level + will double the number of accurate digits in the result (up to the + limits of floating point precision). + + The algorithm will terminate after completing level `maxlevel` or after + another termination condition is satisfied, whichever comes first. + minlevel : int, default: 2 + The level at which to begin iteration (default: 2). This does not + change the total number of function evaluations or the abscissae at + which the function is evaluated; it changes only the *number of times* + `f` is called. If ``minlevel=k``, then the integrand is evaluated at + all abscissae from levels ``0`` through ``k`` in a single call. + Note that if `minlevel` exceeds `maxlevel`, the provided `minlevel` is + ignored, and `minlevel` is set equal to `maxlevel`. + atol, rtol : float, optional + Absolute termination tolerance (default: 0) and relative termination + tolerance (default: ``eps**0.75``, where ``eps`` is the precision of + the result dtype), respectively. The error estimate is as + described in [1]_ Section 5. While not theoretically rigorous or + conservative, it is said to work well in practice. Must be non-negative + and finite if `log` is False, and must be expressed as the log of a + non-negative and finite number if `log` is True. + preserve_shape : bool, default: False + In the following, "arguments of `f`" refers to the array ``x`` and + any arrays within ``fargs``. Let ``shape`` be the broadcasted shape + of `a`, `b`, and all elements of `args` (which is conceptually + distinct from ``fargs`` passed into `f`). + + - When ``preserve_shape=False`` (default), `f` must accept arguments + of *any* broadcastable shapes. + + - When ``preserve_shape=True``, `f` must accept arguments of shape + ``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of + abscissae at which the function is being evaluated. + + In either case, for each scalar element ``xi`` within `x`, the array + returned by `f` must include the scalar ``f(xi)`` at the same index. + Consequently, the shape of the output is always the shape of the input + ``x``. + + See Examples. + + callback : callable, optional + An optional user-supplied function to be called before the first + iteration and after each iteration. + Called as ``callback(res)``, where ``res`` is a ``_RichResult`` + similar to that returned by `_differentiate` (but containing the + current iterate's values of all variables). If `callback` raises a + ``StopIteration``, the algorithm will terminate immediately and + `_tanhsinh` will return a result object. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. (The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + arrays of the same shape.) + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + status : int + An integer representing the exit status of the algorithm. + ``0`` : The algorithm converged to the specified tolerances. + ``-1`` : (unused) + ``-2`` : The maximum number of iterations was reached. + ``-3`` : A non-finite value was encountered. + ``-4`` : Iteration was terminated by `callback`. + ``1`` : The algorithm is proceeding normally (in `callback` only). + integral : float + An estimate of the integral + error : float + An estimate of the error. Only available if level two or higher + has been completed; otherwise NaN. + maxlevel : int + The maximum refinement level used. + nfev : int + The number of points at which `func` was evaluated. + + See Also + -------- + quad, quadrature + + Notes + ----- + Implements the algorithm as described in [1]_ with minor adaptations for + finite-precision arithmetic, including some described by [2]_ and [3]_. The + tanh-sinh scheme was originally introduced in [4]_. + + Due to floating-point error in the abscissae, the function may be evaluated + at the endpoints of the interval during iterations. The values returned by + the function at the endpoints will be ignored. + + References + ---------- + [1] Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. "A comparison of + three high-precision quadrature schemes." Experimental Mathematics 14.3 + (2005): 317-329. + [2] Vanherck, Joren, Bart Sorée, and Wim Magnus. "Tanh-sinh quadrature for + single and multiple integration using floating-point arithmetic." + arXiv preprint arXiv:2007.15057 (2020). + [3] van Engelen, Robert A. "Improving the Double Exponential Quadrature + Tanh-Sinh, Sinh-Sinh and Exp-Sinh Formulas." + https://www.genivia.com/files/qthsh.pdf + [4] Takahasi, Hidetosi, and Masatake Mori. "Double exponential formulas for + numerical integration." Publications of the Research Institute for + Mathematical Sciences 9.3 (1974): 721-741. + + Example + ------- + Evaluate the Gaussian integral: + + >>> import numpy as np + >>> from scipy.integrate._tanhsinh import _tanhsinh + >>> def f(x): + ... return np.exp(-x**2) + >>> res = _tanhsinh(f, -np.inf, np.inf) + >>> res.integral # true value is np.sqrt(np.pi), 1.7724538509055159 + 1.7724538509055159 + >>> res.error # actual error is 0 + 4.0007963937534104e-16 + + The value of the Gaussian function (bell curve) is nearly zero for + arguments sufficiently far from zero, so the value of the integral + over a finite interval is nearly the same. + + >>> _tanhsinh(f, -20, 20).integral + 1.772453850905518 + + However, with unfavorable integration limits, the integration scheme + may not be able to find the important region. + + >>> _tanhsinh(f, -np.inf, 1000).integral + 4.500490856620352 + + In such cases, or when there are singularities within the interval, + break the integral into parts with endpoints at the important points. + + >>> _tanhsinh(f, -np.inf, 0).integral + _tanhsinh(f, 0, 1000).integral + 1.772453850905404 + + For integration involving very large or very small magnitudes, use + log-integration. (For illustrative purposes, the following example shows a + case in which both regular and log-integration work, but for more extreme + limits of integration, log-integration would avoid the underflow + experienced when evaluating the integral normally.) + + >>> res = _tanhsinh(f, 20, 30, rtol=1e-10) + >>> res.integral, res.error + 4.7819613911309014e-176, 4.670364401645202e-187 + >>> def log_f(x): + ... return -x**2 + >>> np.exp(res.integral), np.exp(res.error) + 4.7819613911306924e-176, 4.670364401645093e-187 + + The limits of integration and elements of `args` may be broadcastable + arrays, and integration is performed elementwise. + + >>> from scipy import stats + >>> dist = stats.gausshyper(13.8, 3.12, 2.51, 5.18) + >>> a, b = dist.support() + >>> x = np.linspace(a, b, 100) + >>> res = _tanhsinh(dist.pdf, a, x) + >>> ref = dist.cdf(x) + >>> np.allclose(res.integral, ref) + + By default, `preserve_shape` is False, and therefore the callable + `f` may be called with arrays of any broadcastable shapes. + For example: + + >>> shapes = [] + >>> def f(x, c): + ... shape = np.broadcast_shapes(x.shape, c.shape) + ... shapes.append(shape) + ... return np.sin(c*x) + >>> + >>> c = [1, 10, 30, 100] + >>> res = _tanhsinh(f, 0, 1, args=(c,), minlevel=1) + >>> shapes + [(4,), (4, 66), (3, 64), (2, 128), (1, 256)] + + To understand where these shapes are coming from - and to better + understand how `_tanhsinh` computes accurate results - note that + higher values of ``c`` correspond with higher frequency sinusoids. + The higher frequency sinusoids make the integrand more complicated, + so more function evaluations are required to achieve the target + accuracy: + + >>> res.nfev + array([ 67, 131, 259, 515]) + + The initial ``shape``, ``(4,)``, corresponds with evaluating the + integrand at a single abscissa and all four frequencies; this is used + for input validation and to determine the size and dtype of the arrays + that store results. The next shape corresponds with evaluating the + integrand at an initial grid of abscissae and all four frequencies. + Successive calls to the function double the total number of abscissae at + which the function has been evaluated. However, in later function + evaluations, the integrand is evaluated at fewer frequencies because + the corresponding integral has already converged to the required + tolerance. This saves function evaluations to improve performance, but + it requires the function to accept arguments of any shape. + + "Vector-valued" integrands, such as those written for use with + `scipy.integrate.quad_vec`, are unlikely to satisfy this requirement. + For example, consider + + >>> def f(x): + ... return [x, np.sin(10*x), np.cos(30*x), x*np.sin(100*x)**2] + + This integrand is not compatible with `_tanhsinh` as written; for instance, + the shape of the output will not be the same as the shape of ``x``. Such a + function *could* be converted to a compatible form with the introduction of + additional parameters, but this would be inconvenient. In such cases, + a simpler solution would be to use `preserve_shape`. + + >>> shapes = [] + >>> def f(x): + ... shapes.append(x.shape) + ... x0, x1, x2, x3 = x + ... return [x0, np.sin(10*x1), np.cos(30*x2), x3*np.sin(100*x3)] + >>> + >>> a = np.zeros(4) + >>> res = _tanhsinh(f, a, 1, preserve_shape=True) + >>> shapes + [(4,), (4, 66), (4, 64), (4, 128), (4, 256)] + + Here, the broadcasted shape of `a` and `b` is ``(4,)``. With + ``preserve_shape=True``, the function may be called with argument + ``x`` of shape ``(4,)`` or ``(4, n)``, and this is what we observe. + + """ + (f, a, b, log, maxfun, maxlevel, minlevel, + atol, rtol, args, preserve_shape, callback) = _tanhsinh_iv( + f, a, b, log, maxfun, maxlevel, minlevel, atol, + rtol, args, preserve_shape, callback) + + # Initialization + # `eim._initialize` does several important jobs, including + # ensuring that limits, each of the `args`, and the output of `f` + # broadcast correctly and are of consistent types. To save a function + # evaluation, I pass the midpoint of the integration interval. This comes + # at a cost of some gymnastics to ensure that the midpoint has the right + # shape and dtype. Did you know that 0d and >0d arrays follow different + # type promotion rules? + with np.errstate(over='ignore', invalid='ignore', divide='ignore'): + c = ((a.ravel() + b.ravel())/2).reshape(a.shape) + inf_a, inf_b = np.isinf(a), np.isinf(b) + c[inf_a] = b[inf_a] - 1 # takes care of infinite a + c[inf_b] = a[inf_b] + 1 # takes care of infinite b + c[inf_a & inf_b] = 0 # takes care of infinite a and b + temp = eim._initialize(f, (c,), args, complex_ok=True, + preserve_shape=preserve_shape) + f, xs, fs, args, shape, dtype = temp + a = np.broadcast_to(a, shape).astype(dtype).ravel() + b = np.broadcast_to(b, shape).astype(dtype).ravel() + + # Transform improper integrals + a, b, a0, negative, abinf, ainf, binf = _transform_integrals(a, b) + + # Define variables we'll need + nit, nfev = 0, 1 # one function evaluation performed above + zero = -np.inf if log else 0 + pi = dtype.type(np.pi) + maxiter = maxlevel - minlevel + 1 + eps = np.finfo(dtype).eps + if rtol is None: + rtol = 0.75*np.log(eps) if log else eps**0.75 + + Sn = np.full(shape, zero, dtype=dtype).ravel() # latest integral estimate + Sn[np.isnan(a) | np.isnan(b) | np.isnan(fs[0])] = np.nan + Sk = np.empty_like(Sn).reshape(-1, 1)[:, 0:0] # all integral estimates + aerr = np.full(shape, np.nan, dtype=dtype).ravel() # absolute error + status = np.full(shape, eim._EINPROGRESS, dtype=int).ravel() + h0 = np.real(_get_base_step(dtype=dtype)) # base step + + # For term `d4` of error estimate ([1] Section 5), we need to keep the + # most extreme abscissae and corresponding `fj`s, `wj`s in Euler-Maclaurin + # sum. Here, we initialize these variables. + xr0 = np.full(shape, -np.inf, dtype=dtype).ravel() + fr0 = np.full(shape, np.nan, dtype=dtype).ravel() + wr0 = np.zeros(shape, dtype=dtype).ravel() + xl0 = np.full(shape, np.inf, dtype=dtype).ravel() + fl0 = np.full(shape, np.nan, dtype=dtype).ravel() + wl0 = np.zeros(shape, dtype=dtype).ravel() + d4 = np.zeros(shape, dtype=dtype).ravel() + + work = _RichResult( + Sn=Sn, Sk=Sk, aerr=aerr, h=h0, log=log, dtype=dtype, pi=pi, eps=eps, + a=a.reshape(-1, 1), b=b.reshape(-1, 1), # integration limits + n=minlevel, nit=nit, nfev=nfev, status=status, # iter/eval counts + xr0=xr0, fr0=fr0, wr0=wr0, xl0=xl0, fl0=fl0, wl0=wl0, d4=d4, # err est + ainf=ainf, binf=binf, abinf=abinf, a0=a0.reshape(-1, 1)) # transforms + # Constant scalars don't need to be put in `work` unless they need to be + # passed outside `tanhsinh`. Examples: atol, rtol, h0, minlevel. + + # Correspondence between terms in the `work` object and the result + res_work_pairs = [('status', 'status'), ('integral', 'Sn'), + ('error', 'aerr'), ('nit', 'nit'), ('nfev', 'nfev')] + + def pre_func_eval(work): + # Determine abscissae at which to evaluate `f` + work.h = h0 / 2**work.n + xjc, wj = _get_pairs(work.n, h0, dtype=work.dtype, + inclusive=(work.n == minlevel)) + work.xj, work.wj = _transform_to_limits(xjc, wj, work.a, work.b) + + # Perform abscissae substitutions for infinite limits of integration + xj = work.xj.copy() + xj[work.abinf] = xj[work.abinf] / (1 - xj[work.abinf]**2) + xj[work.binf] = 1/xj[work.binf] - 1 + work.a0[work.binf] + xj[work.ainf] *= -1 + return xj + + def post_func_eval(x, fj, work): + # Weight integrand as required by substitutions for infinite limits + if work.log: + fj[work.abinf] += (np.log(1 + work.xj[work.abinf] ** 2) + - 2*np.log(1 - work.xj[work.abinf] ** 2)) + fj[work.binf] -= 2 * np.log(work.xj[work.binf]) + else: + fj[work.abinf] *= ((1 + work.xj[work.abinf]**2) / + (1 - work.xj[work.abinf]**2)**2) + fj[work.binf] *= work.xj[work.binf]**-2. + + # Estimate integral with Euler-Maclaurin Sum + fjwj, Sn = _euler_maclaurin_sum(fj, work) + if work.Sk.shape[-1]: + Snm1 = work.Sk[:, -1] + Sn = (special.logsumexp([Snm1 - np.log(2), Sn], axis=0) if log + else Snm1 / 2 + Sn) + + work.fjwj = fjwj + work.Sn = Sn + + def check_termination(work): + """Terminate due to convergence or encountering non-finite values""" + stop = np.zeros(work.Sn.shape, dtype=bool) + + # Terminate before first iteration if integration limits are equal + if work.nit == 0: + i = (work.a == work.b).ravel() # ravel singleton dimension + zero = -np.inf if log else 0 + work.Sn[i] = zero + work.aerr[i] = zero + work.status[i] = eim._ECONVERGED + stop[i] = True + else: + # Terminate if convergence criterion is met + work.rerr, work.aerr = _estimate_error(work) + i = ((work.rerr < rtol) | (work.rerr + np.real(work.Sn) < atol) if log + else (work.rerr < rtol) | (work.rerr * abs(work.Sn) < atol)) + work.status[i] = eim._ECONVERGED + stop[i] = True + + # Terminate if integral estimate becomes invalid + if log: + i = (np.isposinf(np.real(work.Sn)) | np.isnan(work.Sn)) & ~stop + else: + i = ~np.isfinite(work.Sn) & ~stop + work.status[i] = eim._EVALUEERR + stop[i] = True + + return stop + + def post_termination_check(work): + work.n += 1 + work.Sk = np.concatenate((work.Sk, work.Sn[:, np.newaxis]), axis=-1) + return + + def customize_result(res, shape): + # If the integration limits were such that b < a, we reversed them + # to perform the calculation, and the final result needs to be negated. + if log and np.any(negative): + pi = res['integral'].dtype.type(np.pi) + j = np.complex64(1j) # minimum complex type + res['integral'] = res['integral'] + negative*pi*j + else: + res['integral'][negative] *= -1 + + # For this algorithm, it seems more appropriate to report the maximum + # level rather than the number of iterations in which it was performed. + res['maxlevel'] = minlevel + res['nit'] - 1 + res['maxlevel'][res['nit'] == 0] = -1 + del res['nit'] + return shape + + # Suppress all warnings initially, since there are many places in the code + # for which this is expected behavior. + with np.errstate(over='ignore', invalid='ignore', divide='ignore'): + res = eim._loop(work, callback, shape, maxiter, f, args, dtype, pre_func_eval, + post_func_eval, check_termination, post_termination_check, + customize_result, res_work_pairs, preserve_shape) + return res + + +def _get_base_step(dtype=np.float64): + # Compute the base step length for the provided dtype. Theoretically, the + # Euler-Maclaurin sum is infinite, but it gets cut off when either the + # weights underflow or the abscissae cannot be distinguished from the + # limits of integration. The latter happens to occur first for float32 and + # float64, and it occurs when `xjc` (the abscissa complement) + # in `_compute_pair` underflows. We can solve for the argument `tmax` at + # which it will underflow using [2] Eq. 13. + fmin = 4*np.finfo(dtype).tiny # stay a little away from the limit + tmax = np.arcsinh(np.log(2/fmin - 1) / np.pi) + + # Based on this, we can choose a base step size `h` for level 0. + # The number of function evaluations will be `2 + m*2^(k+1)`, where `k` is + # the level and `m` is an integer we get to choose. I choose + # m = _N_BASE_STEPS = `8` somewhat arbitrarily, but a rationale is that a + # power of 2 makes floating point arithmetic more predictable. It also + # results in a base step size close to `1`, which is what [1] uses (and I + # used here until I found [2] and these ideas settled). + h0 = tmax / _N_BASE_STEPS + return h0.astype(dtype) + + +_N_BASE_STEPS = 8 + + +def _compute_pair(k, h0): + # Compute the abscissa-weight pairs for each level k. See [1] page 9. + + # For now, we compute and store in 64-bit precision. If higher-precision + # data types become better supported, it would be good to compute these + # using the highest precision available. Or, once there is an Array API- + # compatible arbitrary precision array, we can compute at the required + # precision. + + # "....each level k of abscissa-weight pairs uses h = 2 **-k" + # We adapt to floating point arithmetic using ideas of [2]. + h = h0 / 2**k + max = _N_BASE_STEPS * 2**k + + # For iterations after the first, "....the integrand function needs to be + # evaluated only at the odd-indexed abscissas at each level." + j = np.arange(max+1) if k == 0 else np.arange(1, max+1, 2) + jh = j * h + + # "In this case... the weights wj = u1/cosh(u2)^2, where..." + pi_2 = np.pi / 2 + u1 = pi_2*np.cosh(jh) + u2 = pi_2*np.sinh(jh) + # Denominators get big here. Overflow then underflow doesn't need warning. + # with np.errstate(under='ignore', over='ignore'): + wj = u1 / np.cosh(u2)**2 + # "We actually store 1-xj = 1/(...)." + xjc = 1 / (np.exp(u2) * np.cosh(u2)) # complement of xj = np.tanh(u2) + + # When level k == 0, the zeroth xj corresponds with xj = 0. To simplify + # code, the function will be evaluated there twice; each gets half weight. + wj[0] = wj[0] / 2 if k == 0 else wj[0] + + return xjc, wj # store at full precision + + +def _pair_cache(k, h0): + # Cache the abscissa-weight pairs up to a specified level. + # Abscissae and weights of consecutive levels are concatenated. + # `index` records the indices that correspond with each level: + # `xjc[index[k]:index[k+1]` extracts the level `k` abscissae. + if h0 != _pair_cache.h0: + _pair_cache.xjc = np.empty(0) + _pair_cache.wj = np.empty(0) + _pair_cache.indices = [0] + + xjcs = [_pair_cache.xjc] + wjs = [_pair_cache.wj] + + for i in range(len(_pair_cache.indices)-1, k + 1): + xjc, wj = _compute_pair(i, h0) + xjcs.append(xjc) + wjs.append(wj) + _pair_cache.indices.append(_pair_cache.indices[-1] + len(xjc)) + + _pair_cache.xjc = np.concatenate(xjcs) + _pair_cache.wj = np.concatenate(wjs) + _pair_cache.h0 = h0 + +_pair_cache.xjc = np.empty(0) +_pair_cache.wj = np.empty(0) +_pair_cache.indices = [0] +_pair_cache.h0 = None + + +def _get_pairs(k, h0, inclusive=False, dtype=np.float64): + # Retrieve the specified abscissa-weight pairs from the cache + # If `inclusive`, return all up to and including the specified level + if len(_pair_cache.indices) <= k+2 or h0 != _pair_cache.h0: + _pair_cache(k, h0) + + xjc = _pair_cache.xjc + wj = _pair_cache.wj + indices = _pair_cache.indices + + start = 0 if inclusive else indices[k] + end = indices[k+1] + + return xjc[start:end].astype(dtype), wj[start:end].astype(dtype) + + +def _transform_to_limits(xjc, wj, a, b): + # Transform integral according to user-specified limits. This is just + # math that follows from the fact that the standard limits are (-1, 1). + # Note: If we had stored xj instead of xjc, we would have + # xj = alpha * xj + beta, where beta = (a + b)/2 + alpha = (b - a) / 2 + xj = np.concatenate((-alpha * xjc + b, alpha * xjc + a), axis=-1) + wj = wj*alpha # arguments get broadcasted, so we can't use *= + wj = np.concatenate((wj, wj), axis=-1) + + # Points at the boundaries can be generated due to finite precision + # arithmetic, but these function values aren't supposed to be included in + # the Euler-Maclaurin sum. Ideally we wouldn't evaluate the function at + # these points; however, we can't easily filter out points since this + # function is vectorized. Instead, zero the weights. + invalid = (xj <= a) | (xj >= b) + wj[invalid] = 0 + return xj, wj + + +def _euler_maclaurin_sum(fj, work): + # Perform the Euler-Maclaurin Sum, [1] Section 4 + + # The error estimate needs to know the magnitude of the last term + # omitted from the Euler-Maclaurin sum. This is a bit involved because + # it may have been computed at a previous level. I sure hope it's worth + # all the trouble. + xr0, fr0, wr0 = work.xr0, work.fr0, work.wr0 + xl0, fl0, wl0 = work.xl0, work.fl0, work.wl0 + + # It is much more convenient to work with the transposes of our work + # variables here. + xj, fj, wj = work.xj.T, fj.T, work.wj.T + n_x, n_active = xj.shape # number of abscissae, number of active elements + + # We'll work with the left and right sides separately + xr, xl = xj.reshape(2, n_x // 2, n_active).copy() # this gets modified + fr, fl = fj.reshape(2, n_x // 2, n_active) + wr, wl = wj.reshape(2, n_x // 2, n_active) + + invalid_r = ~np.isfinite(fr) | (wr == 0) + invalid_l = ~np.isfinite(fl) | (wl == 0) + + # integer index of the maximum abscissa at this level + xr[invalid_r] = -np.inf + ir = np.argmax(xr, axis=0, keepdims=True) + # abscissa, function value, and weight at this index + xr_max = np.take_along_axis(xr, ir, axis=0)[0] + fr_max = np.take_along_axis(fr, ir, axis=0)[0] + wr_max = np.take_along_axis(wr, ir, axis=0)[0] + # boolean indices at which maximum abscissa at this level exceeds + # the incumbent maximum abscissa (from all previous levels) + j = xr_max > xr0 + # Update record of the incumbent abscissa, function value, and weight + xr0[j] = xr_max[j] + fr0[j] = fr_max[j] + wr0[j] = wr_max[j] + + # integer index of the minimum abscissa at this level + xl[invalid_l] = np.inf + il = np.argmin(xl, axis=0, keepdims=True) + # abscissa, function value, and weight at this index + xl_min = np.take_along_axis(xl, il, axis=0)[0] + fl_min = np.take_along_axis(fl, il, axis=0)[0] + wl_min = np.take_along_axis(wl, il, axis=0)[0] + # boolean indices at which minimum abscissa at this level is less than + # the incumbent minimum abscissa (from all previous levels) + j = xl_min < xl0 + # Update record of the incumbent abscissa, function value, and weight + xl0[j] = xl_min[j] + fl0[j] = fl_min[j] + wl0[j] = wl_min[j] + fj = fj.T + + # Compute the error estimate `d4` - the magnitude of the leftmost or + # rightmost term, whichever is greater. + flwl0 = fl0 + np.log(wl0) if work.log else fl0 * wl0 # leftmost term + frwr0 = fr0 + np.log(wr0) if work.log else fr0 * wr0 # rightmost term + magnitude = np.real if work.log else np.abs + work.d4 = np.maximum(magnitude(flwl0), magnitude(frwr0)) + + # There are two approaches to dealing with function values that are + # numerically infinite due to approaching a singularity - zero them, or + # replace them with the function value at the nearest non-infinite point. + # [3] pg. 22 suggests the latter, so let's do that given that we have the + # information. + fr0b = np.broadcast_to(fr0[np.newaxis, :], fr.shape) + fl0b = np.broadcast_to(fl0[np.newaxis, :], fl.shape) + fr[invalid_r] = fr0b[invalid_r] + fl[invalid_l] = fl0b[invalid_l] + + # When wj is zero, log emits a warning + # with np.errstate(divide='ignore'): + fjwj = fj + np.log(work.wj) if work.log else fj * work.wj + + # update integral estimate + Sn = (special.logsumexp(fjwj + np.log(work.h), axis=-1) if work.log + else np.sum(fjwj, axis=-1) * work.h) + + work.xr0, work.fr0, work.wr0 = xr0, fr0, wr0 + work.xl0, work.fl0, work.wl0 = xl0, fl0, wl0 + + return fjwj, Sn + + +def _estimate_error(work): + # Estimate the error according to [1] Section 5 + + if work.n == 0 or work.nit == 0: + # The paper says to use "one" as the error before it can be calculated. + # NaN seems to be more appropriate. + nan = np.full_like(work.Sn, np.nan) + return nan, nan + + indices = _pair_cache.indices + + n_active = len(work.Sn) # number of active elements + axis_kwargs = dict(axis=-1, keepdims=True) + + # With a jump start (starting at level higher than 0), we haven't + # explicitly calculated the integral estimate at lower levels. But we have + # all the function value-weight products, so we can compute the + # lower-level estimates. + if work.Sk.shape[-1] == 0: + h = 2 * work.h # step size at this level + n_x = indices[work.n] # number of abscissa up to this level + # The right and left fjwj terms from all levels are concatenated along + # the last axis. Get out only the terms up to this level. + fjwj_rl = work.fjwj.reshape(n_active, 2, -1) + fjwj = fjwj_rl[:, :, :n_x].reshape(n_active, 2*n_x) + # Compute the Euler-Maclaurin sum at this level + Snm1 = (special.logsumexp(fjwj, **axis_kwargs) + np.log(h) if work.log + else np.sum(fjwj, **axis_kwargs) * h) + work.Sk = np.concatenate((Snm1, work.Sk), axis=-1) + + if work.n == 1: + nan = np.full_like(work.Sn, np.nan) + return nan, nan + + # The paper says not to calculate the error for n<=2, but it's not clear + # about whether it starts at level 0 or level 1. We start at level 0, so + # why not compute the error beginning in level 2? + if work.Sk.shape[-1] < 2: + h = 4 * work.h # step size at this level + n_x = indices[work.n-1] # number of abscissa up to this level + # The right and left fjwj terms from all levels are concatenated along + # the last axis. Get out only the terms up to this level. + fjwj_rl = work.fjwj.reshape(len(work.Sn), 2, -1) + fjwj = fjwj_rl[..., :n_x].reshape(n_active, 2*n_x) + # Compute the Euler-Maclaurin sum at this level + Snm2 = (special.logsumexp(fjwj, **axis_kwargs) + np.log(h) if work.log + else np.sum(fjwj, **axis_kwargs) * h) + work.Sk = np.concatenate((Snm2, work.Sk), axis=-1) + + Snm2 = work.Sk[..., -2] + Snm1 = work.Sk[..., -1] + + e1 = work.eps + + if work.log: + log_e1 = np.log(e1) + # Currently, only real integrals are supported in log-scale. All + # complex values have imaginary part in increments of pi*j, which just + # carries sign information of the original integral, so use of + # `np.real` here is equivalent to absolute value in real scale. + d1 = np.real(special.logsumexp([work.Sn, Snm1 + work.pi*1j], axis=0)) + d2 = np.real(special.logsumexp([work.Sn, Snm2 + work.pi*1j], axis=0)) + d3 = log_e1 + np.max(np.real(work.fjwj), axis=-1) + d4 = work.d4 + aerr = np.max([d1 ** 2 / d2, 2 * d1, d3, d4], axis=0) + rerr = np.maximum(log_e1, aerr - np.real(work.Sn)) + else: + # Note: explicit computation of log10 of each of these is unnecessary. + d1 = np.abs(work.Sn - Snm1) + d2 = np.abs(work.Sn - Snm2) + d3 = e1 * np.max(np.abs(work.fjwj), axis=-1) + d4 = work.d4 + # If `d1` is 0, no need to warn. This does the right thing. + # with np.errstate(divide='ignore'): + aerr = np.max([d1**(np.log(d1)/np.log(d2)), d1**2, d3, d4], axis=0) + rerr = np.maximum(e1, aerr/np.abs(work.Sn)) + return rerr, aerr.reshape(work.Sn.shape) + + +def _transform_integrals(a, b): + # Transform integrals to a form with finite a < b + # For b < a, we reverse the limits and will multiply the final result by -1 + # For infinite limit on the right, we use the substitution x = 1/t - 1 + a + # For infinite limit on the left, we substitute x = -x and treat as above + # For infinite limits, we substitute x = t / (1-t**2) + + negative = b < a + a[negative], b[negative] = b[negative], a[negative] + + abinf = np.isinf(a) & np.isinf(b) + a[abinf], b[abinf] = -1, 1 + + ainf = np.isinf(a) + a[ainf], b[ainf] = -b[ainf], -a[ainf] + + binf = np.isinf(b) + a0 = a.copy() + a[binf], b[binf] = 0, 1 + + return a, b, a0, negative, abinf, ainf, binf + + +def _tanhsinh_iv(f, a, b, log, maxfun, maxlevel, minlevel, + atol, rtol, args, preserve_shape, callback): + # Input validation and standardization + + message = '`f` must be callable.' + if not callable(f): + raise ValueError(message) + + message = 'All elements of `a` and `b` must be real numbers.' + a, b = np.broadcast_arrays(a, b) + if np.any(np.iscomplex(a)) or np.any(np.iscomplex(b)): + raise ValueError(message) + + message = '`log` must be True or False.' + if log not in {True, False}: + raise ValueError(message) + log = bool(log) + + if atol is None: + atol = -np.inf if log else 0 + + rtol_temp = rtol if rtol is not None else 0. + + params = np.asarray([atol, rtol_temp, 0.]) + message = "`atol` and `rtol` must be real numbers." + if not np.issubdtype(params.dtype, np.floating): + raise ValueError(message) + + if log: + message = '`atol` and `rtol` may not be positive infinity.' + if np.any(np.isposinf(params)): + raise ValueError(message) + else: + message = '`atol` and `rtol` must be non-negative and finite.' + if np.any(params < 0) or np.any(np.isinf(params)): + raise ValueError(message) + atol = params[0] + rtol = rtol if rtol is None else params[1] + + BIGINT = float(2**62) + if maxfun is None and maxlevel is None: + maxlevel = 10 + + maxfun = BIGINT if maxfun is None else maxfun + maxlevel = BIGINT if maxlevel is None else maxlevel + + message = '`maxfun`, `maxlevel`, and `minlevel` must be integers.' + params = np.asarray([maxfun, maxlevel, minlevel]) + if not (np.issubdtype(params.dtype, np.number) + and np.all(np.isreal(params)) + and np.all(params.astype(np.int64) == params)): + raise ValueError(message) + message = '`maxfun`, `maxlevel`, and `minlevel` must be non-negative.' + if np.any(params < 0): + raise ValueError(message) + maxfun, maxlevel, minlevel = params.astype(np.int64) + minlevel = min(minlevel, maxlevel) + + if not np.iterable(args): + args = (args,) + + message = '`preserve_shape` must be True or False.' + if preserve_shape not in {True, False}: + raise ValueError(message) + + if callback is not None and not callable(callback): + raise ValueError('`callback` must be callable.') + + return (f, a, b, log, maxfun, maxlevel, minlevel, + atol, rtol, args, preserve_shape, callback) + + +def _logsumexp(x, axis=0): + # logsumexp raises with empty array + x = np.asarray(x) + shape = list(x.shape) + if shape[axis] == 0: + shape.pop(axis) + return np.full(shape, fill_value=-np.inf, dtype=x.dtype) + else: + return special.logsumexp(x, axis=axis) + + +def _nsum_iv(f, a, b, step, args, log, maxterms, atol, rtol): + # Input validation and standardization + + message = '`f` must be callable.' + if not callable(f): + raise ValueError(message) + + message = 'All elements of `a`, `b`, and `step` must be real numbers.' + a, b, step = np.broadcast_arrays(a, b, step) + dtype = np.result_type(a.dtype, b.dtype, step.dtype) + if not np.issubdtype(dtype, np.number) or np.issubdtype(dtype, np.complexfloating): + raise ValueError(message) + + valid_a = np.isfinite(a) + valid_b = b >= a # NaNs will be False + valid_step = np.isfinite(step) & (step > 0) + valid_abstep = valid_a & valid_b & valid_step + + message = '`log` must be True or False.' + if log not in {True, False}: + raise ValueError(message) + + if atol is None: + atol = -np.inf if log else 0 + + rtol_temp = rtol if rtol is not None else 0. + + params = np.asarray([atol, rtol_temp, 0.]) + message = "`atol` and `rtol` must be real numbers." + if not np.issubdtype(params.dtype, np.floating): + raise ValueError(message) + + if log: + message = '`atol`, `rtol` may not be positive infinity or NaN.' + if np.any(np.isposinf(params) | np.isnan(params)): + raise ValueError(message) + else: + message = '`atol`, and `rtol` must be non-negative and finite.' + if np.any((params < 0) | (~np.isfinite(params))): + raise ValueError(message) + atol = params[0] + rtol = rtol if rtol is None else params[1] + + maxterms_int = int(maxterms) + if maxterms_int != maxterms or maxterms < 0: + message = "`maxterms` must be a non-negative integer." + raise ValueError(message) + + if not np.iterable(args): + args = (args,) + + return f, a, b, step, valid_abstep, args, log, maxterms_int, atol, rtol + + +def _nsum(f, a, b, step=1, args=(), log=False, maxterms=int(2**20), atol=None, + rtol=None): + r"""Evaluate a convergent sum. + + For finite `b`, this evaluates:: + + f(a + np.arange(n)*step).sum() + + where ``n = int((b - a) / step) + 1``. If `f` is smooth, positive, and + monotone decreasing, `b` may be infinite, in which case the infinite sum + is approximated using integration. + + Parameters + ---------- + f : callable + The function that evaluates terms to be summed. The signature must be:: + + f(x: ndarray, *args) -> ndarray + + where each element of ``x`` is a finite real and ``args`` is a tuple, + which may contain an arbitrary number of arrays that are broadcastable + with `x`. `f` must represent a smooth, positive, and monotone decreasing + function of `x`; `_nsum` performs no checks to verify that these conditions + are met and may return erroneous results if they are violated. + a, b : array_like + Real lower and upper limits of summed terms. Must be broadcastable. + Each element of `a` must be finite and less than the corresponding + element in `b`, but elements of `b` may be infinite. + step : array_like + Finite, positive, real step between summed terms. Must be broadcastable + with `a` and `b`. + args : tuple, optional + Additional positional arguments to be passed to `f`. Must be arrays + broadcastable with `a`, `b`, and `step`. If the callable to be summed + requires arguments that are not broadcastable with `a`, `b`, and `step`, + wrap that callable with `f`. See Examples. + log : bool, default: False + Setting to True indicates that `f` returns the log of the terms + and that `atol` and `rtol` are expressed as the logs of the absolute + and relative errors. In this case, the result object will contain the + log of the sum and error. This is useful for summands for which + numerical underflow or overflow would lead to inaccuracies. + maxterms : int, default: 2**32 + The maximum number of terms to evaluate when summing directly. + Additional function evaluations may be performed for input + validation and integral evaluation. + atol, rtol : float, optional + Absolute termination tolerance (default: 0) and relative termination + tolerance (default: ``eps**0.5``, where ``eps`` is the precision of + the result dtype), respectively. Must be non-negative + and finite if `log` is False, and must be expressed as the log of a + non-negative and finite number if `log` is True. + + Returns + ------- + res : _RichResult + An instance of `scipy._lib._util._RichResult` with the following + attributes. (The descriptions are written as though the values will be + scalars; however, if `func` returns an array, the outputs will be + + arrays of the same shape.) + success : bool + ``True`` when the algorithm terminated successfully (status ``0``). + status : int + An integer representing the exit status of the algorithm. + ``0`` : The algorithm converged to the specified tolerances. + ``-1`` : Element(s) of `a`, `b`, or `step` are invalid + ``-2`` : Numerical integration reached its iteration limit; the sum may be divergent. + ``-3`` : A non-finite value was encountered. + sum : float + An estimate of the sum. + error : float + An estimate of the absolute error, assuming all terms are non-negative. + nfev : int + The number of points at which `func` was evaluated. + + See Also + -------- + tanhsinh + + Notes + ----- + The method implemented for infinite summation is related to the integral + test for convergence of an infinite series: assuming `step` size 1 for + simplicity of exposition, the sum of a monotone decreasing function is bounded by + + .. math:: + + \int_u^\infty f(x) dx \leq \sum_{k=u}^\infty f(k) \leq \int_u^\infty f(x) dx + f(u) + + Let :math:`a` represent `a`, :math:`n` represent `maxterms`, :math:`\epsilon_a` + represent `atol`, and :math:`\epsilon_r` represent `rtol`. + The implementation first evaluates the integral :math:`S_l=\int_a^\infty f(x) dx` + as a lower bound of the infinite sum. Then, it seeks a value :math:`c > a` such + that :math:`f(c) < \epsilon_a + S_l \epsilon_r`, if it exists; otherwise, + let :math:`c = a + n`. Then the infinite sum is approximated as + + .. math:: + + \sum_{k=a}^{c-1} f(k) + \int_c^\infty f(x) dx + f(c)/2 + + and the reported error is :math:`f(c)/2` plus the error estimate of + numerical integration. The approach described above is generalized for non-unit + `step` and finite `b` that is too large for direct evaluation of the sum, + i.e. ``b - a + 1 > maxterms``. + + References + ---------- + [1] Wikipedia. "Integral test for convergence." + https://en.wikipedia.org/wiki/Integral_test_for_convergence + + Examples + -------- + Compute the infinite sum of the reciprocals of squared integers. + + >>> import numpy as np + >>> from scipy.integrate._tanhsinh import _nsum + >>> res = _nsum(lambda k: 1/k**2, 1, np.inf, maxterms=1e3) + >>> ref = np.pi**2/6 # true value + >>> res.error # estimated error + 4.990014980029223e-07 + >>> (res.sum - ref)/ref # true error + -1.0101760641302586e-10 + >>> res.nfev # number of points at which callable was evaluated + 1142 + + Compute the infinite sums of the reciprocals of integers raised to powers ``p``. + + >>> from scipy import special + >>> p = np.arange(2, 10) + >>> res = _nsum(lambda k, p: 1/k**p, 1, np.inf, maxterms=1e3, args=(p,)) + >>> ref = special.zeta(p, 1) + >>> np.allclose(res.sum, ref) + True + + """ # noqa: E501 + # Potential future work: + # - more careful testing of when `b` is slightly less than `a` plus an + # integer multiple of step (needed before this is public) + # - improve error estimate of `_direct` sum + # - add other methods for convergence acceleration (Richardson, epsilon) + # - support infinite lower limit? + # - support negative monotone increasing functions? + # - b < a / negative step? + # - complex-valued function? + # - check for violations of monotonicity? + + # Function-specific input validation / standardization + tmp = _nsum_iv(f, a, b, step, args, log, maxterms, atol, rtol) + f, a, b, step, valid_abstep, args, log, maxterms, atol, rtol = tmp + + # Additional elementwise algorithm input validation / standardization + tmp = eim._initialize(f, (a,), args, complex_ok=False) + f, xs, fs, args, shape, dtype = tmp + + # Finish preparing `a`, `b`, and `step` arrays + a = xs[0] + b = np.broadcast_to(b, shape).ravel().astype(dtype) + step = np.broadcast_to(step, shape).ravel().astype(dtype) + valid_abstep = np.broadcast_to(valid_abstep, shape).ravel() + nterms = np.floor((b - a) / step) + b = a + nterms*step + + # Define constants + eps = np.finfo(dtype).eps + zero = np.asarray(-np.inf if log else 0, dtype=dtype)[()] + if rtol is None: + rtol = 0.5*np.log(eps) if log else eps**0.5 + constants = (dtype, log, eps, zero, rtol, atol, maxterms) + + # Prepare result arrays + S = np.empty_like(a) + E = np.empty_like(a) + status = np.zeros(len(a), dtype=int) + nfev = np.ones(len(a), dtype=int) # one function evaluation above + + # Branch for direct sum evaluation / integral approximation / invalid input + i1 = (nterms + 1 <= maxterms) & valid_abstep + i2 = (nterms + 1 > maxterms) & valid_abstep + i3 = ~valid_abstep + + if np.any(i1): + args_direct = [arg[i1] for arg in args] + tmp = _direct(f, a[i1], b[i1], step[i1], args_direct, constants) + S[i1], E[i1] = tmp[:-1] + nfev[i1] += tmp[-1] + status[i1] = -3 * (~np.isfinite(S[i1])) + + if np.any(i2): + args_indirect = [arg[i2] for arg in args] + tmp = _integral_bound(f, a[i2], b[i2], step[i2], args_indirect, constants) + S[i2], E[i2], status[i2] = tmp[:-1] + nfev[i2] += tmp[-1] + + if np.any(i3): + S[i3], E[i3] = np.nan, np.nan + status[i3] = -1 + + # Return results + S, E = S.reshape(shape)[()], E.reshape(shape)[()] + status, nfev = status.reshape(shape)[()], nfev.reshape(shape)[()] + return _RichResult(sum=S, error=E, status=status, success=status == 0, + nfev=nfev) + + +def _direct(f, a, b, step, args, constants, inclusive=True): + # Directly evaluate the sum. + + # When used in the context of distributions, `args` would contain the + # distribution parameters. We have broadcasted for simplicity, but we could + # reduce function evaluations when distribution parameters are the same but + # sum limits differ. Roughly: + # - compute the function at all points between min(a) and max(b), + # - compute the cumulative sum, + # - take the difference between elements of the cumulative sum + # corresponding with b and a. + # This is left to future enhancement + + dtype, log, eps, zero, _, _, _ = constants + + # To allow computation in a single vectorized call, find the maximum number + # of points (over all slices) at which the function needs to be evaluated. + # Note: if `inclusive` is `True`, then we want `1` more term in the sum. + # I didn't think it was great style to use `True` as `1` in Python, so I + # explicitly converted it to an `int` before using it. + inclusive_adjustment = int(inclusive) + steps = np.round((b - a) / step) + inclusive_adjustment + # Equivalently, steps = np.round((b - a) / step) + inclusive + max_steps = int(np.max(steps)) + + # In each slice, the function will be evaluated at the same number of points, + # but excessive points (those beyond the right sum limit `b`) are replaced + # with NaN to (potentially) reduce the time of these unnecessary calculations. + # Use a new last axis for these calculations for consistency with other + # elementwise algorithms. + a2, b2, step2 = a[:, np.newaxis], b[:, np.newaxis], step[:, np.newaxis] + args2 = [arg[:, np.newaxis] for arg in args] + ks = a2 + np.arange(max_steps, dtype=dtype) * step2 + i_nan = ks >= (b2 + inclusive_adjustment*step2/2) + ks[i_nan] = np.nan + fs = f(ks, *args2) + + # The function evaluated at NaN is NaN, and NaNs are zeroed in the sum. + # In some cases it may be faster to loop over slices than to vectorize + # like this. This is an optimization that can be added later. + fs[i_nan] = zero + nfev = max_steps - i_nan.sum(axis=-1) + S = _logsumexp(fs, axis=-1) if log else np.sum(fs, axis=-1) + # Rough, non-conservative error estimate. See gh-19667 for improvement ideas. + E = np.real(S) + np.log(eps) if log else eps * abs(S) + return S, E, nfev + + +def _integral_bound(f, a, b, step, args, constants): + # Estimate the sum with integral approximation + dtype, log, _, _, rtol, atol, maxterms = constants + log2 = np.log(2, dtype=dtype) + + # Get a lower bound on the sum and compute effective absolute tolerance + lb = _tanhsinh(f, a, b, args=args, atol=atol, rtol=rtol, log=log) + tol = np.broadcast_to(atol, lb.integral.shape) + tol = _logsumexp((tol, rtol + lb.integral)) if log else tol + rtol*lb.integral + i_skip = lb.status < 0 # avoid unnecessary f_evals if integral is divergent + tol[i_skip] = np.nan + status = lb.status + + # As in `_direct`, we'll need a temporary new axis for points + # at which to evaluate the function. Append axis at the end for + # consistency with other elementwise algorithms. + a2 = a[..., np.newaxis] + step2 = step[..., np.newaxis] + args2 = [arg[..., np.newaxis] for arg in args] + + # Find the location of a term that is less than the tolerance (if possible) + log2maxterms = np.floor(np.log2(maxterms)) if maxterms else 0 + n_steps = np.concatenate([2**np.arange(0, log2maxterms), [maxterms]], dtype=dtype) + nfev = len(n_steps) + ks = a2 + n_steps * step2 + fks = f(ks, *args2) + nt = np.minimum(np.sum(fks > tol[:, np.newaxis], axis=-1), n_steps.shape[-1]-1) + n_steps = n_steps[nt] + + # Directly evaluate the sum up to this term + k = a + n_steps * step + left, left_error, left_nfev = _direct(f, a, k, step, args, + constants, inclusive=False) + i_skip |= np.isposinf(left) # if sum is not finite, no sense in continuing + status[np.isposinf(left)] = -3 + k[i_skip] = np.nan + + # Use integration to estimate the remaining sum + # Possible optimization for future work: if there were no terms less than + # the tolerance, there is no need to compute the integral to better accuracy. + # Something like: + # atol = np.maximum(atol, np.minimum(fk/2 - fb/2)) + # rtol = np.maximum(rtol, np.minimum((fk/2 - fb/2)/left)) + # where `fk`/`fb` are currently calculated below. + right = _tanhsinh(f, k, b, args=args, atol=atol, rtol=rtol, log=log) + + # Calculate the full estimate and error from the pieces + fk = fks[np.arange(len(fks)), nt] + fb = f(b, *args) + nfev += 1 + if log: + log_step = np.log(step) + S_terms = (left, right.integral - log_step, fk - log2, fb - log2) + S = _logsumexp(S_terms, axis=0) + E_terms = (left_error, right.error - log_step, fk-log2, fb-log2+np.pi*1j) + E = _logsumexp(E_terms, axis=0).real + else: + S = left + right.integral/step + fk/2 + fb/2 + E = left_error + right.error/step + fk/2 - fb/2 + status[~i_skip] = right.status[~i_skip] + return S, E, status, left_nfev + right.nfev + nfev + lb.nfev diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..fbe799fa8bfe4c5f1b2d2ed5edc07fe91db628ef Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_test_odeint_banded.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_test_odeint_banded.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..95cd375e0490bec6640cdf39fbcbfb9c34a82424 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_test_odeint_banded.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_vode.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_vode.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8af33ad79ddfd8a7555d13cfe21c427dc9740b4f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/_vode.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/dop.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/dop.py new file mode 100644 index 0000000000000000000000000000000000000000..5e61e475220e0826a1338a7af327aa3581281728 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/dop.py @@ -0,0 +1,18 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'dopri5', + 'dop853' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="integrate", module="dop", + private_modules=["_dop"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/lsoda.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/lsoda.py new file mode 100644 index 0000000000000000000000000000000000000000..1bc1f1da3c4f0aefad9da73b6405b957ce9335b4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/lsoda.py @@ -0,0 +1,15 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = ['lsoda'] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="integrate", module="lsoda", + private_modules=["_lsoda"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/odepack.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/odepack.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb4c1a8c9be375df855abe6e1b30ca9711f2607 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/odepack.py @@ -0,0 +1,17 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.integrate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = ['odeint', 'ODEintWarning'] # noqa: F822 + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="integrate", module="odepack", + private_modules=["_odepack_py"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/quadpack.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/quadpack.py new file mode 100644 index 0000000000000000000000000000000000000000..9de6e498e38252c08933f221dfdc630c2a31023e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/quadpack.py @@ -0,0 +1,24 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.integrate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + "quad", + "dblquad", + "tplquad", + "nquad", + "IntegrationWarning", + "error", +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="integrate", module="quadpack", + private_modules=["_quadpack_py"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/integrate/vode.py b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/vode.py new file mode 100644 index 0000000000000000000000000000000000000000..dc58782b99ceb9eb6cc9d89b0e99ed595eef4ae3 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/integrate/vode.py @@ -0,0 +1,18 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'dvode', + 'zvode' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="integrate", module="vode", + private_modules=["_vode"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/__pycache__/mmio.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/io/__pycache__/mmio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cae319a3a4ffb7b8a258378afe1f368f366a101 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/io/__pycache__/mmio.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..094479a593ce925ef640b954d0c41f58a2d1bb9e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/__init__.py @@ -0,0 +1,17 @@ +from .hb import (MalformedHeader, hb_read, hb_write, HBInfo, + HBFile, HBMatrixType) +from ._fortran_format_parser import (FortranFormatParser, IntFormat, + ExpFormat, BadFortranFormat) + +# Deprecated namespaces, to be removed in v2.0.0 +from . import hb + +__all__ = [ + 'MalformedHeader', 'hb_read', 'hb_write', 'HBInfo', + 'HBFile', 'HBMatrixType', 'FortranFormatParser', 'IntFormat', + 'ExpFormat', 'BadFortranFormat', 'hb' +] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/_fortran_format_parser.py b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/_fortran_format_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ab77c1bfbf8a75b8362b72d3d5f4676593e062 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/_fortran_format_parser.py @@ -0,0 +1,309 @@ +""" +Preliminary module to handle Fortran formats for IO. Does not use this outside +scipy.sparse io for now, until the API is deemed reasonable. + +The *Format classes handle conversion between Fortran and Python format, and +FortranFormatParser can create *Format instances from raw Fortran format +strings (e.g. '(3I4)', '(10I3)', etc...) +""" +import re + +import numpy as np + + +__all__ = ["BadFortranFormat", "FortranFormatParser", "IntFormat", "ExpFormat"] + + +TOKENS = { + "LPAR": r"\(", + "RPAR": r"\)", + "INT_ID": r"I", + "EXP_ID": r"E", + "INT": r"\d+", + "DOT": r"\.", +} + + +class BadFortranFormat(SyntaxError): + pass + + +def number_digits(n): + return int(np.floor(np.log10(np.abs(n))) + 1) + + +class IntFormat: + @classmethod + def from_number(cls, n, min=None): + """Given an integer, returns a "reasonable" IntFormat instance to represent + any number between 0 and n if n > 0, -n and n if n < 0 + + Parameters + ---------- + n : int + max number one wants to be able to represent + min : int + minimum number of characters to use for the format + + Returns + ------- + res : IntFormat + IntFormat instance with reasonable (see Notes) computed width + + Notes + ----- + Reasonable should be understood as the minimal string length necessary + without losing precision. For example, IntFormat.from_number(1) will + return an IntFormat instance of width 2, so that any 0 and 1 may be + represented as 1-character strings without loss of information. + """ + width = number_digits(n) + 1 + if n < 0: + width += 1 + repeat = 80 // width + return cls(width, min, repeat=repeat) + + def __init__(self, width, min=None, repeat=None): + self.width = width + self.repeat = repeat + self.min = min + + def __repr__(self): + r = "IntFormat(" + if self.repeat: + r += "%d" % self.repeat + r += "I%d" % self.width + if self.min: + r += ".%d" % self.min + return r + ")" + + @property + def fortran_format(self): + r = "(" + if self.repeat: + r += "%d" % self.repeat + r += "I%d" % self.width + if self.min: + r += ".%d" % self.min + return r + ")" + + @property + def python_format(self): + return "%" + str(self.width) + "d" + + +class ExpFormat: + @classmethod + def from_number(cls, n, min=None): + """Given a float number, returns a "reasonable" ExpFormat instance to + represent any number between -n and n. + + Parameters + ---------- + n : float + max number one wants to be able to represent + min : int + minimum number of characters to use for the format + + Returns + ------- + res : ExpFormat + ExpFormat instance with reasonable (see Notes) computed width + + Notes + ----- + Reasonable should be understood as the minimal string length necessary + to avoid losing precision. + """ + # len of one number in exp format: sign + 1|0 + "." + + # number of digit for fractional part + 'E' + sign of exponent + + # len of exponent + finfo = np.finfo(n.dtype) + # Number of digits for fractional part + n_prec = finfo.precision + 1 + # Number of digits for exponential part + n_exp = number_digits(np.max(np.abs([finfo.maxexp, finfo.minexp]))) + width = 1 + 1 + n_prec + 1 + n_exp + 1 + if n < 0: + width += 1 + repeat = int(np.floor(80 / width)) + return cls(width, n_prec, min, repeat=repeat) + + def __init__(self, width, significand, min=None, repeat=None): + """\ + Parameters + ---------- + width : int + number of characters taken by the string (includes space). + """ + self.width = width + self.significand = significand + self.repeat = repeat + self.min = min + + def __repr__(self): + r = "ExpFormat(" + if self.repeat: + r += "%d" % self.repeat + r += "E%d.%d" % (self.width, self.significand) + if self.min: + r += "E%d" % self.min + return r + ")" + + @property + def fortran_format(self): + r = "(" + if self.repeat: + r += "%d" % self.repeat + r += "E%d.%d" % (self.width, self.significand) + if self.min: + r += "E%d" % self.min + return r + ")" + + @property + def python_format(self): + return "%" + str(self.width-1) + "." + str(self.significand) + "E" + + +class Token: + def __init__(self, type, value, pos): + self.type = type + self.value = value + self.pos = pos + + def __str__(self): + return f"""Token('{self.type}', "{self.value}")""" + + def __repr__(self): + return self.__str__() + + +class Tokenizer: + def __init__(self): + self.tokens = list(TOKENS.keys()) + self.res = [re.compile(TOKENS[i]) for i in self.tokens] + + def input(self, s): + self.data = s + self.curpos = 0 + self.len = len(s) + + def next_token(self): + curpos = self.curpos + + while curpos < self.len: + for i, r in enumerate(self.res): + m = r.match(self.data, curpos) + if m is None: + continue + else: + self.curpos = m.end() + return Token(self.tokens[i], m.group(), self.curpos) + raise SyntaxError("Unknown character at position %d (%s)" + % (self.curpos, self.data[curpos])) + + +# Grammar for fortran format: +# format : LPAR format_string RPAR +# format_string : repeated | simple +# repeated : repeat simple +# simple : int_fmt | exp_fmt +# int_fmt : INT_ID width +# exp_fmt : simple_exp_fmt +# simple_exp_fmt : EXP_ID width DOT significand +# extended_exp_fmt : EXP_ID width DOT significand EXP_ID ndigits +# repeat : INT +# width : INT +# significand : INT +# ndigits : INT + +# Naive fortran formatter - parser is hand-made +class FortranFormatParser: + """Parser for Fortran format strings. The parse method returns a *Format + instance. + + Notes + ----- + Only ExpFormat (exponential format for floating values) and IntFormat + (integer format) for now. + """ + def __init__(self): + self.tokenizer = Tokenizer() + + def parse(self, s): + self.tokenizer.input(s) + + tokens = [] + + try: + while True: + t = self.tokenizer.next_token() + if t is None: + break + else: + tokens.append(t) + return self._parse_format(tokens) + except SyntaxError as e: + raise BadFortranFormat(str(e)) from e + + def _get_min(self, tokens): + next = tokens.pop(0) + if not next.type == "DOT": + raise SyntaxError() + next = tokens.pop(0) + return next.value + + def _expect(self, token, tp): + if not token.type == tp: + raise SyntaxError() + + def _parse_format(self, tokens): + if not tokens[0].type == "LPAR": + raise SyntaxError("Expected left parenthesis at position " + "%d (got '%s')" % (0, tokens[0].value)) + elif not tokens[-1].type == "RPAR": + raise SyntaxError("Expected right parenthesis at position " + "%d (got '%s')" % (len(tokens), tokens[-1].value)) + + tokens = tokens[1:-1] + types = [t.type for t in tokens] + if types[0] == "INT": + repeat = int(tokens.pop(0).value) + else: + repeat = None + + next = tokens.pop(0) + if next.type == "INT_ID": + next = self._next(tokens, "INT") + width = int(next.value) + if tokens: + min = int(self._get_min(tokens)) + else: + min = None + return IntFormat(width, min, repeat) + elif next.type == "EXP_ID": + next = self._next(tokens, "INT") + width = int(next.value) + + next = self._next(tokens, "DOT") + + next = self._next(tokens, "INT") + significand = int(next.value) + + if tokens: + next = self._next(tokens, "EXP_ID") + + next = self._next(tokens, "INT") + min = int(next.value) + else: + min = None + return ExpFormat(width, significand, min, repeat) + else: + raise SyntaxError("Invalid formatter type %s" % next.value) + + def _next(self, tokens, tp): + if not len(tokens) > 0: + raise SyntaxError() + next = tokens.pop(0) + self._expect(next, tp) + return next diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.py b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.py new file mode 100644 index 0000000000000000000000000000000000000000..210982bee2ffa3f84816d6660e8fa9ee933eb6e5 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/hb.py @@ -0,0 +1,571 @@ +""" +Implementation of Harwell-Boeing read/write. + +At the moment not the full Harwell-Boeing format is supported. Supported +features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + +""" +# TODO: +# - Add more support (symmetric/complex matrices, non-assembled matrices ?) + +# XXX: reading is reasonably efficient (>= 85 % is in numpy.fromstring), but +# takes a lot of memory. Being faster would require compiled code. +# write is not efficient. Although not a terribly exciting task, +# having reusable facilities to efficiently read/write fortran-formatted files +# would be useful outside this module. + +import warnings + +import numpy as np +from scipy.sparse import csc_matrix +from ._fortran_format_parser import FortranFormatParser, IntFormat, ExpFormat + +__all__ = ["MalformedHeader", "hb_read", "hb_write", "HBInfo", "HBFile", + "HBMatrixType"] + + +class MalformedHeader(Exception): + pass + + +class LineOverflow(Warning): + pass + + +def _nbytes_full(fmt, nlines): + """Return the number of bytes to read to get every full lines for the + given parsed fortran format.""" + return (fmt.repeat * fmt.width + 1) * (nlines - 1) + + +class HBInfo: + @classmethod + def from_data(cls, m, title="Default title", key="0", mxtype=None, fmt=None): + """Create a HBInfo instance from an existing sparse matrix. + + Parameters + ---------- + m : sparse matrix + the HBInfo instance will derive its parameters from m + title : str + Title to put in the HB header + key : str + Key + mxtype : HBMatrixType + type of the input matrix + fmt : dict + not implemented + + Returns + ------- + hb_info : HBInfo instance + """ + m = m.tocsc(copy=False) + + pointer = m.indptr + indices = m.indices + values = m.data + + nrows, ncols = m.shape + nnon_zeros = m.nnz + + if fmt is None: + # +1 because HB use one-based indexing (Fortran), and we will write + # the indices /pointer as such + pointer_fmt = IntFormat.from_number(np.max(pointer+1)) + indices_fmt = IntFormat.from_number(np.max(indices+1)) + + if values.dtype.kind in np.typecodes["AllFloat"]: + values_fmt = ExpFormat.from_number(-np.max(np.abs(values))) + elif values.dtype.kind in np.typecodes["AllInteger"]: + values_fmt = IntFormat.from_number(-np.max(np.abs(values))) + else: + message = f"type {values.dtype.kind} not implemented yet" + raise NotImplementedError(message) + else: + raise NotImplementedError("fmt argument not supported yet.") + + if mxtype is None: + if not np.isrealobj(values): + raise ValueError("Complex values not supported yet") + if values.dtype.kind in np.typecodes["AllInteger"]: + tp = "integer" + elif values.dtype.kind in np.typecodes["AllFloat"]: + tp = "real" + else: + raise NotImplementedError("type %s for values not implemented" + % values.dtype) + mxtype = HBMatrixType(tp, "unsymmetric", "assembled") + else: + raise ValueError("mxtype argument not handled yet.") + + def _nlines(fmt, size): + nlines = size // fmt.repeat + if nlines * fmt.repeat != size: + nlines += 1 + return nlines + + pointer_nlines = _nlines(pointer_fmt, pointer.size) + indices_nlines = _nlines(indices_fmt, indices.size) + values_nlines = _nlines(values_fmt, values.size) + + total_nlines = pointer_nlines + indices_nlines + values_nlines + + return cls(title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + pointer_fmt.fortran_format, indices_fmt.fortran_format, + values_fmt.fortran_format) + + @classmethod + def from_file(cls, fid): + """Create a HBInfo instance from a file object containing a matrix in the + HB format. + + Parameters + ---------- + fid : file-like matrix + File or file-like object containing a matrix in the HB format. + + Returns + ------- + hb_info : HBInfo instance + """ + # First line + line = fid.readline().strip("\n") + if not len(line) > 72: + raise ValueError("Expected at least 72 characters for first line, " + "got: \n%s" % line) + title = line[:72] + key = line[72:] + + # Second line + line = fid.readline().strip("\n") + if not len(line.rstrip()) >= 56: + raise ValueError("Expected at least 56 characters for second line, " + "got: \n%s" % line) + total_nlines = _expect_int(line[:14]) + pointer_nlines = _expect_int(line[14:28]) + indices_nlines = _expect_int(line[28:42]) + values_nlines = _expect_int(line[42:56]) + + rhs_nlines = line[56:72].strip() + if rhs_nlines == '': + rhs_nlines = 0 + else: + rhs_nlines = _expect_int(rhs_nlines) + if not rhs_nlines == 0: + raise ValueError("Only files without right hand side supported for " + "now.") + + # Third line + line = fid.readline().strip("\n") + if not len(line) >= 70: + raise ValueError("Expected at least 72 character for third line, got:\n" + "%s" % line) + + mxtype_s = line[:3].upper() + if not len(mxtype_s) == 3: + raise ValueError("mxtype expected to be 3 characters long") + + mxtype = HBMatrixType.from_fortran(mxtype_s) + if mxtype.value_type not in ["real", "integer"]: + raise ValueError("Only real or integer matrices supported for " + "now (detected %s)" % mxtype) + if not mxtype.structure == "unsymmetric": + raise ValueError("Only unsymmetric matrices supported for " + "now (detected %s)" % mxtype) + if not mxtype.storage == "assembled": + raise ValueError("Only assembled matrices supported for now") + + if not line[3:14] == " " * 11: + raise ValueError("Malformed data for third line: %s" % line) + + nrows = _expect_int(line[14:28]) + ncols = _expect_int(line[28:42]) + nnon_zeros = _expect_int(line[42:56]) + nelementals = _expect_int(line[56:70]) + if not nelementals == 0: + raise ValueError("Unexpected value %d for nltvl (last entry of line 3)" + % nelementals) + + # Fourth line + line = fid.readline().strip("\n") + + ct = line.split() + if not len(ct) == 3: + raise ValueError("Expected 3 formats, got %s" % ct) + + return cls(title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + ct[0], ct[1], ct[2], + rhs_nlines, nelementals) + + def __init__(self, title, key, + total_nlines, pointer_nlines, indices_nlines, values_nlines, + mxtype, nrows, ncols, nnon_zeros, + pointer_format_str, indices_format_str, values_format_str, + right_hand_sides_nlines=0, nelementals=0): + """Do not use this directly, but the class ctrs (from_* functions).""" + self.title = title + self.key = key + if title is None: + title = "No Title" + if len(title) > 72: + raise ValueError("title cannot be > 72 characters") + + if key is None: + key = "|No Key" + if len(key) > 8: + warnings.warn("key is > 8 characters (key is %s)" % key, + LineOverflow, stacklevel=3) + + self.total_nlines = total_nlines + self.pointer_nlines = pointer_nlines + self.indices_nlines = indices_nlines + self.values_nlines = values_nlines + + parser = FortranFormatParser() + pointer_format = parser.parse(pointer_format_str) + if not isinstance(pointer_format, IntFormat): + raise ValueError("Expected int format for pointer format, got %s" + % pointer_format) + + indices_format = parser.parse(indices_format_str) + if not isinstance(indices_format, IntFormat): + raise ValueError("Expected int format for indices format, got %s" % + indices_format) + + values_format = parser.parse(values_format_str) + if isinstance(values_format, ExpFormat): + if mxtype.value_type not in ["real", "complex"]: + raise ValueError(f"Inconsistency between matrix type {mxtype} and " + f"value type {values_format}") + values_dtype = np.float64 + elif isinstance(values_format, IntFormat): + if mxtype.value_type not in ["integer"]: + raise ValueError(f"Inconsistency between matrix type {mxtype} and " + f"value type {values_format}") + # XXX: fortran int -> dtype association ? + values_dtype = int + else: + raise ValueError(f"Unsupported format for values {values_format!r}") + + self.pointer_format = pointer_format + self.indices_format = indices_format + self.values_format = values_format + + self.pointer_dtype = np.int32 + self.indices_dtype = np.int32 + self.values_dtype = values_dtype + + self.pointer_nlines = pointer_nlines + self.pointer_nbytes_full = _nbytes_full(pointer_format, pointer_nlines) + + self.indices_nlines = indices_nlines + self.indices_nbytes_full = _nbytes_full(indices_format, indices_nlines) + + self.values_nlines = values_nlines + self.values_nbytes_full = _nbytes_full(values_format, values_nlines) + + self.nrows = nrows + self.ncols = ncols + self.nnon_zeros = nnon_zeros + self.nelementals = nelementals + self.mxtype = mxtype + + def dump(self): + """Gives the header corresponding to this instance as a string.""" + header = [self.title.ljust(72) + self.key.ljust(8)] + + header.append("%14d%14d%14d%14d" % + (self.total_nlines, self.pointer_nlines, + self.indices_nlines, self.values_nlines)) + header.append("%14s%14d%14d%14d%14d" % + (self.mxtype.fortran_format.ljust(14), self.nrows, + self.ncols, self.nnon_zeros, 0)) + + pffmt = self.pointer_format.fortran_format + iffmt = self.indices_format.fortran_format + vffmt = self.values_format.fortran_format + header.append("%16s%16s%20s" % + (pffmt.ljust(16), iffmt.ljust(16), vffmt.ljust(20))) + return "\n".join(header) + + +def _expect_int(value, msg=None): + try: + return int(value) + except ValueError as e: + if msg is None: + msg = "Expected an int, got %s" + raise ValueError(msg % value) from e + + +def _read_hb_data(content, header): + # XXX: look at a way to reduce memory here (big string creation) + ptr_string = "".join([content.read(header.pointer_nbytes_full), + content.readline()]) + ptr = np.fromstring(ptr_string, + dtype=int, sep=' ') + + ind_string = "".join([content.read(header.indices_nbytes_full), + content.readline()]) + ind = np.fromstring(ind_string, + dtype=int, sep=' ') + + val_string = "".join([content.read(header.values_nbytes_full), + content.readline()]) + val = np.fromstring(val_string, + dtype=header.values_dtype, sep=' ') + + try: + return csc_matrix((val, ind-1, ptr-1), + shape=(header.nrows, header.ncols)) + except ValueError as e: + raise e + + +def _write_data(m, fid, header): + m = m.tocsc(copy=False) + + def write_array(f, ar, nlines, fmt): + # ar_nlines is the number of full lines, n is the number of items per + # line, ffmt the fortran format + pyfmt = fmt.python_format + pyfmt_full = pyfmt * fmt.repeat + + # for each array to write, we first write the full lines, and special + # case for partial line + full = ar[:(nlines - 1) * fmt.repeat] + for row in full.reshape((nlines-1, fmt.repeat)): + f.write(pyfmt_full % tuple(row) + "\n") + nremain = ar.size - full.size + if nremain > 0: + f.write((pyfmt * nremain) % tuple(ar[ar.size - nremain:]) + "\n") + + fid.write(header.dump()) + fid.write("\n") + # +1 is for Fortran one-based indexing + write_array(fid, m.indptr+1, header.pointer_nlines, + header.pointer_format) + write_array(fid, m.indices+1, header.indices_nlines, + header.indices_format) + write_array(fid, m.data, header.values_nlines, + header.values_format) + + +class HBMatrixType: + """Class to hold the matrix type.""" + # q2f* translates qualified names to Fortran character + _q2f_type = { + "real": "R", + "complex": "C", + "pattern": "P", + "integer": "I", + } + _q2f_structure = { + "symmetric": "S", + "unsymmetric": "U", + "hermitian": "H", + "skewsymmetric": "Z", + "rectangular": "R" + } + _q2f_storage = { + "assembled": "A", + "elemental": "E", + } + + _f2q_type = {j: i for i, j in _q2f_type.items()} + _f2q_structure = {j: i for i, j in _q2f_structure.items()} + _f2q_storage = {j: i for i, j in _q2f_storage.items()} + + @classmethod + def from_fortran(cls, fmt): + if not len(fmt) == 3: + raise ValueError("Fortran format for matrix type should be 3 " + "characters long") + try: + value_type = cls._f2q_type[fmt[0]] + structure = cls._f2q_structure[fmt[1]] + storage = cls._f2q_storage[fmt[2]] + return cls(value_type, structure, storage) + except KeyError as e: + raise ValueError("Unrecognized format %s" % fmt) from e + + def __init__(self, value_type, structure, storage="assembled"): + self.value_type = value_type + self.structure = structure + self.storage = storage + + if value_type not in self._q2f_type: + raise ValueError("Unrecognized type %s" % value_type) + if structure not in self._q2f_structure: + raise ValueError("Unrecognized structure %s" % structure) + if storage not in self._q2f_storage: + raise ValueError("Unrecognized storage %s" % storage) + + @property + def fortran_format(self): + return self._q2f_type[self.value_type] + \ + self._q2f_structure[self.structure] + \ + self._q2f_storage[self.storage] + + def __repr__(self): + return f"HBMatrixType({self.value_type}, {self.structure}, {self.storage})" + + +class HBFile: + def __init__(self, file, hb_info=None): + """Create a HBFile instance. + + Parameters + ---------- + file : file-object + StringIO work as well + hb_info : HBInfo, optional + Should be given as an argument for writing, in which case the file + should be writable. + """ + self._fid = file + if hb_info is None: + self._hb_info = HBInfo.from_file(file) + else: + #raise OSError("file %s is not writable, and hb_info " + # "was given." % file) + self._hb_info = hb_info + + @property + def title(self): + return self._hb_info.title + + @property + def key(self): + return self._hb_info.key + + @property + def type(self): + return self._hb_info.mxtype.value_type + + @property + def structure(self): + return self._hb_info.mxtype.structure + + @property + def storage(self): + return self._hb_info.mxtype.storage + + def read_matrix(self): + return _read_hb_data(self._fid, self._hb_info) + + def write_matrix(self, m): + return _write_data(m, self._fid, self._hb_info) + + +def hb_read(path_or_open_file): + """Read HB-format file. + + Parameters + ---------- + path_or_open_file : path-like or file-like + If a file-like object, it is used as-is. Otherwise, it is opened + before reading. + + Returns + ------- + data : scipy.sparse.csc_matrix instance + The data read from the HB file as a sparse matrix. + + Notes + ----- + At the moment not the full Harwell-Boeing format is supported. Supported + features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + + Examples + -------- + We can read and write a harwell-boeing format file: + + >>> from scipy.io import hb_read, hb_write + >>> from scipy.sparse import csr_matrix, eye + >>> data = csr_matrix(eye(3)) # create a sparse matrix + >>> hb_write("data.hb", data) # write a hb file + >>> print(hb_read("data.hb")) # read a hb file + (0, 0) 1.0 + (1, 1) 1.0 + (2, 2) 1.0 + + """ + def _get_matrix(fid): + hb = HBFile(fid) + return hb.read_matrix() + + if hasattr(path_or_open_file, 'read'): + return _get_matrix(path_or_open_file) + else: + with open(path_or_open_file) as f: + return _get_matrix(f) + + +def hb_write(path_or_open_file, m, hb_info=None): + """Write HB-format file. + + Parameters + ---------- + path_or_open_file : path-like or file-like + If a file-like object, it is used as-is. Otherwise, it is opened + before writing. + m : sparse-matrix + the sparse matrix to write + hb_info : HBInfo + contains the meta-data for write + + Returns + ------- + None + + Notes + ----- + At the moment not the full Harwell-Boeing format is supported. Supported + features are: + + - assembled, non-symmetric, real matrices + - integer for pointer/indices + - exponential format for float values, and int format + + Examples + -------- + We can read and write a harwell-boeing format file: + + >>> from scipy.io import hb_read, hb_write + >>> from scipy.sparse import csr_matrix, eye + >>> data = csr_matrix(eye(3)) # create a sparse matrix + >>> hb_write("data.hb", data) # write a hb file + >>> print(hb_read("data.hb")) # read a hb file + (0, 0) 1.0 + (1, 1) 1.0 + (2, 2) 1.0 + + """ + m = m.tocsc(copy=False) + + if hb_info is None: + hb_info = HBInfo.from_data(m) + + def _set_matrix(fid): + hb = HBFile(fid, hb_info) + return hb.write_matrix(m) + + if hasattr(path_or_open_file, 'write'): + return _set_matrix(path_or_open_file) + else: + with open(path_or_open_file, 'w') as f: + return _set_matrix(f) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..849b74026456c5fed1f7e6a925b778c13ef9f7c0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1512975f6c458eb10c67728b3cf4fd51b1dac439 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_fortran_format.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d2d31408d16e7d014dd92c34b22b67262a32e0d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/__pycache__/test_hb.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py new file mode 100644 index 0000000000000000000000000000000000000000..53384ca06d16c2b4ef2d6b19d985d8402439207b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_fortran_format.py @@ -0,0 +1,74 @@ +import numpy as np + +from numpy.testing import assert_equal +from pytest import raises as assert_raises + +from scipy.io._harwell_boeing import ( + FortranFormatParser, IntFormat, ExpFormat, BadFortranFormat) + + +class TestFortranFormatParser: + def setup_method(self): + self.parser = FortranFormatParser() + + def _test_equal(self, format, ref): + ret = self.parser.parse(format) + assert_equal(ret.__dict__, ref.__dict__) + + def test_simple_int(self): + self._test_equal("(I4)", IntFormat(4)) + + def test_simple_repeated_int(self): + self._test_equal("(3I4)", IntFormat(4, repeat=3)) + + def test_simple_exp(self): + self._test_equal("(E4.3)", ExpFormat(4, 3)) + + def test_exp_exp(self): + self._test_equal("(E8.3E3)", ExpFormat(8, 3, 3)) + + def test_repeat_exp(self): + self._test_equal("(2E4.3)", ExpFormat(4, 3, repeat=2)) + + def test_repeat_exp_exp(self): + self._test_equal("(2E8.3E3)", ExpFormat(8, 3, 3, repeat=2)) + + def test_wrong_formats(self): + def _test_invalid(bad_format): + assert_raises(BadFortranFormat, lambda: self.parser.parse(bad_format)) + _test_invalid("I4") + _test_invalid("(E4)") + _test_invalid("(E4.)") + _test_invalid("(E4.E3)") + + +class TestIntFormat: + def test_to_fortran(self): + f = [IntFormat(10), IntFormat(12, 10), IntFormat(12, 10, 3)] + res = ["(I10)", "(I12.10)", "(3I12.10)"] + + for i, j in zip(f, res): + assert_equal(i.fortran_format, j) + + def test_from_number(self): + f = [10, -12, 123456789] + r_f = [IntFormat(3, repeat=26), IntFormat(4, repeat=20), + IntFormat(10, repeat=8)] + for i, j in zip(f, r_f): + assert_equal(IntFormat.from_number(i).__dict__, j.__dict__) + + +class TestExpFormat: + def test_to_fortran(self): + f = [ExpFormat(10, 5), ExpFormat(12, 10), ExpFormat(12, 10, min=3), + ExpFormat(10, 5, repeat=3)] + res = ["(E10.5)", "(E12.10)", "(E12.10E3)", "(3E10.5)"] + + for i, j in zip(f, res): + assert_equal(i.fortran_format, j) + + def test_from_number(self): + f = np.array([1.0, -1.2]) + r_f = [ExpFormat(24, 16, repeat=3), ExpFormat(25, 16, repeat=3)] + for i, j in zip(f, r_f): + assert_equal(ExpFormat.from_number(i).__dict__, j.__dict__) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py new file mode 100644 index 0000000000000000000000000000000000000000..a4cf88230a09d8ae01a66427bc4f6f860737e80a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/io/_harwell_boeing/tests/test_hb.py @@ -0,0 +1,65 @@ +from io import StringIO +import tempfile + +import numpy as np + +from numpy.testing import assert_equal, \ + assert_array_almost_equal_nulp + +from scipy.sparse import coo_matrix, csc_matrix, rand + +from scipy.io import hb_read, hb_write + + +SIMPLE = """\ +No Title |No Key + 9 4 1 4 +RUA 100 100 10 0 +(26I3) (26I3) (3E23.15) +1 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 +3 3 3 3 3 3 3 4 4 4 6 6 6 6 6 6 6 6 6 6 6 8 9 9 9 9 +9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 11 +37 71 89 18 30 45 70 19 25 52 +2.971243799687726e-01 3.662366682877375e-01 4.786962174699534e-01 +6.490068647991184e-01 6.617490424831662e-02 8.870370343191623e-01 +4.196478590163001e-01 5.649603072111251e-01 9.934423887087086e-01 +6.912334991524289e-01 +""" + +SIMPLE_MATRIX = coo_matrix( + ((0.297124379969, 0.366236668288, 0.47869621747, 0.649006864799, + 0.0661749042483, 0.887037034319, 0.419647859016, + 0.564960307211, 0.993442388709, 0.691233499152,), + (np.array([[36, 70, 88, 17, 29, 44, 69, 18, 24, 51], + [0, 4, 58, 61, 61, 72, 72, 73, 99, 99]])))) + + +def assert_csc_almost_equal(r, l): + r = csc_matrix(r) + l = csc_matrix(l) + assert_equal(r.indptr, l.indptr) + assert_equal(r.indices, l.indices) + assert_array_almost_equal_nulp(r.data, l.data, 10000) + + +class TestHBReader: + def test_simple(self): + m = hb_read(StringIO(SIMPLE)) + assert_csc_almost_equal(m, SIMPLE_MATRIX) + + +class TestHBReadWrite: + + def check_save_load(self, value): + with tempfile.NamedTemporaryFile(mode='w+t') as file: + hb_write(file, value) + file.file.seek(0) + value_loaded = hb_read(file) + assert_csc_almost_equal(value, value_loaded) + + def test_simple(self): + random_matrix = rand(10, 100, 0.1) + for matrix_format in ('coo', 'csc', 'csr', 'bsr', 'dia', 'dok', 'lil'): + matrix = random_matrix.asformat(matrix_format, copy=False) + self.check_save_load(matrix) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f619dded6615a284392c4273559f226a1c8c72c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__init__.py @@ -0,0 +1,169 @@ +""" +========================================================= +Multidimensional image processing (:mod:`scipy.ndimage`) +========================================================= + +.. currentmodule:: scipy.ndimage + +This package contains various functions for multidimensional image +processing. + + +Filters +======= + +.. autosummary:: + :toctree: generated/ + + convolve - Multidimensional convolution + convolve1d - 1-D convolution along the given axis + correlate - Multidimensional correlation + correlate1d - 1-D correlation along the given axis + gaussian_filter + gaussian_filter1d + gaussian_gradient_magnitude + gaussian_laplace + generic_filter - Multidimensional filter using a given function + generic_filter1d - 1-D generic filter along the given axis + generic_gradient_magnitude + generic_laplace + laplace - N-D Laplace filter based on approximate second derivatives + maximum_filter + maximum_filter1d + median_filter - Calculates a multidimensional median filter + minimum_filter + minimum_filter1d + percentile_filter - Calculates a multidimensional percentile filter + prewitt + rank_filter - Calculates a multidimensional rank filter + sobel + uniform_filter - Multidimensional uniform filter + uniform_filter1d - 1-D uniform filter along the given axis + +Fourier filters +=============== + +.. autosummary:: + :toctree: generated/ + + fourier_ellipsoid + fourier_gaussian + fourier_shift + fourier_uniform + +Interpolation +============= + +.. autosummary:: + :toctree: generated/ + + affine_transform - Apply an affine transformation + geometric_transform - Apply an arbitrary geometric transform + map_coordinates - Map input array to new coordinates by interpolation + rotate - Rotate an array + shift - Shift an array + spline_filter + spline_filter1d + zoom - Zoom an array + +Measurements +============ + +.. autosummary:: + :toctree: generated/ + + center_of_mass - The center of mass of the values of an array at labels + extrema - Min's and max's of an array at labels, with their positions + find_objects - Find objects in a labeled array + histogram - Histogram of the values of an array, optionally at labels + label - Label features in an array + labeled_comprehension + maximum + maximum_position + mean - Mean of the values of an array at labels + median + minimum + minimum_position + standard_deviation - Standard deviation of an N-D image array + sum_labels - Sum of the values of the array + value_indices - Find indices of each distinct value in given array + variance - Variance of the values of an N-D image array + watershed_ift + +Morphology +========== + +.. autosummary:: + :toctree: generated/ + + binary_closing + binary_dilation + binary_erosion + binary_fill_holes + binary_hit_or_miss + binary_opening + binary_propagation + black_tophat + distance_transform_bf + distance_transform_cdt + distance_transform_edt + generate_binary_structure + grey_closing + grey_dilation + grey_erosion + grey_opening + iterate_structure + morphological_gradient + morphological_laplace + white_tophat + +""" + +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from ._filters import * +from ._fourier import * +from ._interpolation import * +from ._measurements import * +from ._morphology import * + +# Deprecated namespaces, to be removed in v2.0.0 +from . import filters +from . import fourier +from . import interpolation +from . import measurements +from . import morphology + +__all__ = [s for s in dir() if not s.startswith('_')] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..802542d0dc4ebe2fe26da6fadabfbe8037d4ebf0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1adacbcadfde91b53037e5d71de57e1497800e72 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_filters.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66a37210fc3dc2688d433339c32e8776860f7626 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_fourier.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a46eb0d8a6ef79035f852c90ce616c8b5efaa62e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_interpolation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e676917a85028c8dcbf9b21a480bb25aa012139 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_measurements.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74199ce6a52b661cc565ca91735db9b8d8de47ab Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56d5699ddee1ccb522d507d329e3d5b130872872 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_docstrings.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4aae3ecbb95c55394091f188081f04ece3cf0e75 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/_ni_support.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..192979784220757bab009feace98c200309c7cdc Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/filters.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60b8ce5a166f6a04d16de8dde98fd781188158a6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/fourier.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0eb604ede1640df7d67203208d91692f4b1c1ad9 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/interpolation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..531106ee50d1e332e0296e84cbf92f17b3ace3c7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/measurements.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df3b24b831ff4471621073bb61431af584920c8c Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/__pycache__/morphology.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0d05e123ba1f7f45c1f37795e7ba5cd0257018b4 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..af816c8e2ce5740bd2b524a4bca51b4d0ccdac20 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_cytest.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_filters.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..a2907614d5acffcd8dcfaf054d84d69b438e7923 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_filters.py @@ -0,0 +1,1852 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from collections.abc import Iterable +import numbers +import warnings +import numpy +import operator + +from scipy._lib._util import normalize_axis_index +from . import _ni_support +from . import _nd_image +from . import _ni_docstrings + +__all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter', + 'prewitt', 'sobel', 'generic_laplace', 'laplace', + 'gaussian_laplace', 'generic_gradient_magnitude', + 'gaussian_gradient_magnitude', 'correlate', 'convolve', + 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', + 'maximum_filter1d', 'minimum_filter', 'maximum_filter', + 'rank_filter', 'median_filter', 'percentile_filter', + 'generic_filter1d', 'generic_filter'] + + +def _invalid_origin(origin, lenw): + return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2) + + +def _complex_via_real_components(func, input, weights, output, cval, **kwargs): + """Complex convolution via a linear combination of real convolutions.""" + complex_input = input.dtype.kind == 'c' + complex_weights = weights.dtype.kind == 'c' + if complex_input and complex_weights: + # real component of the output + func(input.real, weights.real, output=output.real, + cval=numpy.real(cval), **kwargs) + output.real -= func(input.imag, weights.imag, output=None, + cval=numpy.imag(cval), **kwargs) + # imaginary component of the output + func(input.real, weights.imag, output=output.imag, + cval=numpy.real(cval), **kwargs) + output.imag += func(input.imag, weights.real, output=None, + cval=numpy.imag(cval), **kwargs) + elif complex_input: + func(input.real, weights, output=output.real, cval=numpy.real(cval), + **kwargs) + func(input.imag, weights, output=output.imag, cval=numpy.imag(cval), + **kwargs) + else: + if numpy.iscomplexobj(cval): + raise ValueError("Cannot provide a complex-valued cval when the " + "input is real.") + func(input, weights.real, output=output.real, cval=cval, **kwargs) + func(input, weights.imag, output=output.imag, cval=cval, **kwargs) + return output + + +@_ni_docstrings.docfiller +def correlate1d(input, weights, axis=-1, output=None, mode="reflect", + cval=0.0, origin=0): + """Calculate a 1-D correlation along the given axis. + + The lines of the array along the given axis are correlated with the + given weights. + + Parameters + ---------- + %(input)s + weights : array + 1-D sequence of numbers. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + result : ndarray + Correlation result. Has the same shape as `input`. + + Examples + -------- + >>> from scipy.ndimage import correlate1d + >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3]) + array([ 8, 26, 8, 12, 7, 28, 36, 9]) + """ + input = numpy.asarray(input) + weights = numpy.asarray(weights) + complex_input = input.dtype.kind == 'c' + complex_weights = weights.dtype.kind == 'c' + if complex_input or complex_weights: + if complex_weights: + weights = weights.conj() + weights = weights.astype(numpy.complex128, copy=False) + kwargs = dict(axis=axis, mode=mode, origin=origin) + output = _ni_support._get_output(output, input, complex_output=True) + return _complex_via_real_components(correlate1d, input, weights, + output, cval, **kwargs) + + output = _ni_support._get_output(output, input) + weights = numpy.asarray(weights, dtype=numpy.float64) + if weights.ndim != 1 or weights.shape[0] < 1: + raise RuntimeError('no filter weights given') + if not weights.flags.contiguous: + weights = weights.copy() + axis = normalize_axis_index(axis, input.ndim) + if _invalid_origin(origin, len(weights)): + raise ValueError('Invalid origin; origin must satisfy ' + '-(len(weights) // 2) <= origin <= ' + '(len(weights)-1) // 2') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.correlate1d(input, weights, axis, output, mode, cval, + origin) + return output + + +@_ni_docstrings.docfiller +def convolve1d(input, weights, axis=-1, output=None, mode="reflect", + cval=0.0, origin=0): + """Calculate a 1-D convolution along the given axis. + + The lines of the array along the given axis are convolved with the + given weights. + + Parameters + ---------- + %(input)s + weights : ndarray + 1-D sequence of numbers. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + convolve1d : ndarray + Convolved array with same shape as input + + Examples + -------- + >>> from scipy.ndimage import convolve1d + >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3]) + array([14, 24, 4, 13, 12, 36, 27, 0]) + """ + weights = weights[::-1] + origin = -origin + if not len(weights) & 1: + origin -= 1 + weights = numpy.asarray(weights) + if weights.dtype.kind == 'c': + # pre-conjugate here to counteract the conjugation in correlate1d + weights = weights.conj() + return correlate1d(input, weights, axis, output, mode, cval, origin) + + +def _gaussian_kernel1d(sigma, order, radius): + """ + Computes a 1-D Gaussian convolution kernel. + """ + if order < 0: + raise ValueError('order must be non-negative') + exponent_range = numpy.arange(order + 1) + sigma2 = sigma * sigma + x = numpy.arange(-radius, radius+1) + phi_x = numpy.exp(-0.5 / sigma2 * x ** 2) + phi_x = phi_x / phi_x.sum() + + if order == 0: + return phi_x + else: + # f(x) = q(x) * phi(x) = q(x) * exp(p(x)) + # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x) + # p'(x) = -1 / sigma ** 2 + # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the + # coefficients of q(x) + q = numpy.zeros(order + 1) + q[0] = 1 + D = numpy.diag(exponent_range[1:], 1) # D @ q(x) = q'(x) + P = numpy.diag(numpy.ones(order)/-sigma2, -1) # P @ q(x) = q(x) * p'(x) + Q_deriv = D + P + for _ in range(order): + q = Q_deriv.dot(q) + q = (x[:, None] ** exponent_range).dot(q) + return q * phi_x + + +@_ni_docstrings.docfiller +def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None, + mode="reflect", cval=0.0, truncate=4.0, *, radius=None): + """1-D Gaussian filter. + + Parameters + ---------- + %(input)s + sigma : scalar + standard deviation for Gaussian kernel + %(axis)s + order : int, optional + An order of 0 corresponds to convolution with a Gaussian + kernel. A positive order corresponds to convolution with + that derivative of a Gaussian. + %(output)s + %(mode_reflect)s + %(cval)s + truncate : float, optional + Truncate the filter at this many standard deviations. + Default is 4.0. + radius : None or int, optional + Radius of the Gaussian kernel. If specified, the size of + the kernel will be ``2*radius + 1``, and `truncate` is ignored. + Default is None. + + Returns + ------- + gaussian_filter1d : ndarray + + Notes + ----- + The Gaussian kernel will have size ``2*radius + 1`` along each axis. If + `radius` is None, a default ``radius = round(truncate * sigma)`` will be + used. + + Examples + -------- + >>> from scipy.ndimage import gaussian_filter1d + >>> import numpy as np + >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1) + array([ 1.42704095, 2.06782203, 3. , 3.93217797, 4.57295905]) + >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4) + array([ 2.91948343, 2.95023502, 3. , 3.04976498, 3.08051657]) + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> x = rng.standard_normal(101).cumsum() + >>> y3 = gaussian_filter1d(x, 3) + >>> y6 = gaussian_filter1d(x, 6) + >>> plt.plot(x, 'k', label='original data') + >>> plt.plot(y3, '--', label='filtered, sigma=3') + >>> plt.plot(y6, ':', label='filtered, sigma=6') + >>> plt.legend() + >>> plt.grid() + >>> plt.show() + + """ + sd = float(sigma) + # make the radius of the filter equal to truncate standard deviations + lw = int(truncate * sd + 0.5) + if radius is not None: + lw = radius + if not isinstance(lw, numbers.Integral) or lw < 0: + raise ValueError('Radius must be a nonnegative integer.') + # Since we are calling correlate, not convolve, revert the kernel + weights = _gaussian_kernel1d(sigma, order, lw)[::-1] + return correlate1d(input, weights, axis, output, mode, cval, 0) + + +@_ni_docstrings.docfiller +def gaussian_filter(input, sigma, order=0, output=None, + mode="reflect", cval=0.0, truncate=4.0, *, radius=None, + axes=None): + """Multidimensional Gaussian filter. + + Parameters + ---------- + %(input)s + sigma : scalar or sequence of scalars + Standard deviation for Gaussian kernel. The standard + deviations of the Gaussian filter are given for each axis as a + sequence, or as a single number, in which case it is equal for + all axes. + order : int or sequence of ints, optional + The order of the filter along each axis is given as a sequence + of integers, or as a single number. An order of 0 corresponds + to convolution with a Gaussian kernel. A positive order + corresponds to convolution with that derivative of a Gaussian. + %(output)s + %(mode_multiple)s + %(cval)s + truncate : float, optional + Truncate the filter at this many standard deviations. + Default is 4.0. + radius : None or int or sequence of ints, optional + Radius of the Gaussian kernel. The radius are given for each axis + as a sequence, or as a single number, in which case it is equal + for all axes. If specified, the size of the kernel along each axis + will be ``2*radius + 1``, and `truncate` is ignored. + Default is None. + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `sigma`, `order`, `mode` and/or `radius` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + gaussian_filter : ndarray + Returned array of same shape as `input`. + + Notes + ----- + The multidimensional filter is implemented as a sequence of + 1-D convolution filters. The intermediate arrays are + stored in the same data type as the output. Therefore, for output + types with a limited precision, the results may be imprecise + because intermediate results may be stored with insufficient + precision. + + The Gaussian kernel will have size ``2*radius + 1`` along each axis. If + `radius` is None, the default ``radius = round(truncate * sigma)`` will be + used. + + Examples + -------- + >>> from scipy.ndimage import gaussian_filter + >>> import numpy as np + >>> a = np.arange(50, step=2).reshape((5,5)) + >>> a + array([[ 0, 2, 4, 6, 8], + [10, 12, 14, 16, 18], + [20, 22, 24, 26, 28], + [30, 32, 34, 36, 38], + [40, 42, 44, 46, 48]]) + >>> gaussian_filter(a, sigma=1) + array([[ 4, 6, 8, 9, 11], + [10, 12, 14, 15, 17], + [20, 22, 24, 25, 27], + [29, 31, 33, 34, 36], + [35, 37, 39, 40, 42]]) + + >>> from scipy import datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = gaussian_filter(ascent, sigma=5) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = numpy.asarray(input) + output = _ni_support._get_output(output, input) + + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + orders = _ni_support._normalize_sequence(order, num_axes) + sigmas = _ni_support._normalize_sequence(sigma, num_axes) + modes = _ni_support._normalize_sequence(mode, num_axes) + radiuses = _ni_support._normalize_sequence(radius, num_axes) + axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii], radiuses[ii]) + for ii in range(num_axes) if sigmas[ii] > 1e-15] + if len(axes) > 0: + for axis, sigma, order, mode, radius in axes: + gaussian_filter1d(input, sigma, axis, order, output, + mode, cval, truncate, radius=radius) + input = output + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0): + """Calculate a Prewitt filter. + + Parameters + ---------- + %(input)s + %(axis)s + %(output)s + %(mode_multiple)s + %(cval)s + + Returns + ------- + prewitt : ndarray + Filtered array. Has the same shape as `input`. + + See Also + -------- + sobel: Sobel filter + + Notes + ----- + This function computes the one-dimensional Prewitt filter. + Horizontal edges are emphasised with the horizontal transform (axis=0), + vertical edges with the vertical transform (axis=1), and so on for higher + dimensions. These can be combined to give the magnitude. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> ascent = datasets.ascent() + >>> prewitt_h = ndimage.prewitt(ascent, axis=0) + >>> prewitt_v = ndimage.prewitt(ascent, axis=1) + >>> magnitude = np.sqrt(prewitt_h ** 2 + prewitt_v ** 2) + >>> magnitude *= 255 / np.max(magnitude) # Normalization + >>> fig, axes = plt.subplots(2, 2, figsize = (8, 8)) + >>> plt.gray() + >>> axes[0, 0].imshow(ascent) + >>> axes[0, 1].imshow(prewitt_h) + >>> axes[1, 0].imshow(prewitt_v) + >>> axes[1, 1].imshow(magnitude) + >>> titles = ["original", "horizontal", "vertical", "magnitude"] + >>> for i, ax in enumerate(axes.ravel()): + ... ax.set_title(titles[i]) + ... ax.axis("off") + >>> plt.show() + + """ + input = numpy.asarray(input) + axis = normalize_axis_index(axis, input.ndim) + output = _ni_support._get_output(output, input) + modes = _ni_support._normalize_sequence(mode, input.ndim) + correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0) + axes = [ii for ii in range(input.ndim) if ii != axis] + for ii in axes: + correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,) + return output + + +@_ni_docstrings.docfiller +def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0): + """Calculate a Sobel filter. + + Parameters + ---------- + %(input)s + %(axis)s + %(output)s + %(mode_multiple)s + %(cval)s + + Returns + ------- + sobel : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + This function computes the axis-specific Sobel gradient. + The horizontal edges can be emphasised with the horizontal transform (axis=0), + the vertical edges with the vertical transform (axis=1) and so on for higher + dimensions. These can be combined to give the magnitude. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> ascent = datasets.ascent().astype('int32') + >>> sobel_h = ndimage.sobel(ascent, 0) # horizontal gradient + >>> sobel_v = ndimage.sobel(ascent, 1) # vertical gradient + >>> magnitude = np.sqrt(sobel_h**2 + sobel_v**2) + >>> magnitude *= 255.0 / np.max(magnitude) # normalization + >>> fig, axs = plt.subplots(2, 2, figsize=(8, 8)) + >>> plt.gray() # show the filtered result in grayscale + >>> axs[0, 0].imshow(ascent) + >>> axs[0, 1].imshow(sobel_h) + >>> axs[1, 0].imshow(sobel_v) + >>> axs[1, 1].imshow(magnitude) + >>> titles = ["original", "horizontal", "vertical", "magnitude"] + >>> for i, ax in enumerate(axs.ravel()): + ... ax.set_title(titles[i]) + ... ax.axis("off") + >>> plt.show() + + """ + input = numpy.asarray(input) + axis = normalize_axis_index(axis, input.ndim) + output = _ni_support._get_output(output, input) + modes = _ni_support._normalize_sequence(mode, input.ndim) + correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0) + axes = [ii for ii in range(input.ndim) if ii != axis] + for ii in axes: + correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0) + return output + + +@_ni_docstrings.docfiller +def generic_laplace(input, derivative2, output=None, mode="reflect", + cval=0.0, + extra_arguments=(), + extra_keywords=None): + """ + N-D Laplace filter using a provided second derivative function. + + Parameters + ---------- + %(input)s + derivative2 : callable + Callable with the following signature:: + + derivative2(input, axis, output, mode, cval, + *extra_arguments, **extra_keywords) + + See `extra_arguments`, `extra_keywords` below. + %(output)s + %(mode_multiple)s + %(cval)s + %(extra_keywords)s + %(extra_arguments)s + + Returns + ------- + generic_laplace : ndarray + Filtered array. Has the same shape as `input`. + + """ + if extra_keywords is None: + extra_keywords = {} + input = numpy.asarray(input) + output = _ni_support._get_output(output, input) + axes = list(range(input.ndim)) + if len(axes) > 0: + modes = _ni_support._normalize_sequence(mode, len(axes)) + derivative2(input, axes[0], output, modes[0], cval, + *extra_arguments, **extra_keywords) + for ii in range(1, len(axes)): + tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval, + *extra_arguments, **extra_keywords) + output += tmp + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def laplace(input, output=None, mode="reflect", cval=0.0): + """N-D Laplace filter based on approximate second derivatives. + + Parameters + ---------- + %(input)s + %(output)s + %(mode_multiple)s + %(cval)s + + Returns + ------- + laplace : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.laplace(ascent) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + def derivative2(input, axis, output, mode, cval): + return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0) + return generic_laplace(input, derivative2, output, mode, cval) + + +@_ni_docstrings.docfiller +def gaussian_laplace(input, sigma, output=None, mode="reflect", + cval=0.0, **kwargs): + """Multidimensional Laplace filter using Gaussian second derivatives. + + Parameters + ---------- + %(input)s + sigma : scalar or sequence of scalars + The standard deviations of the Gaussian filter are given for + each axis as a sequence, or as a single number, in which case + it is equal for all axes. + %(output)s + %(mode_multiple)s + %(cval)s + Extra keyword arguments will be passed to gaussian_filter(). + + Returns + ------- + gaussian_laplace : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> ascent = datasets.ascent() + + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + + >>> result = ndimage.gaussian_laplace(ascent, sigma=1) + >>> ax1.imshow(result) + + >>> result = ndimage.gaussian_laplace(ascent, sigma=3) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = numpy.asarray(input) + + def derivative2(input, axis, output, mode, cval, sigma, **kwargs): + order = [0] * input.ndim + order[axis] = 2 + return gaussian_filter(input, sigma, order, output, mode, cval, + **kwargs) + + return generic_laplace(input, derivative2, output, mode, cval, + extra_arguments=(sigma,), + extra_keywords=kwargs) + + +@_ni_docstrings.docfiller +def generic_gradient_magnitude(input, derivative, output=None, + mode="reflect", cval=0.0, + extra_arguments=(), extra_keywords=None): + """Gradient magnitude using a provided gradient function. + + Parameters + ---------- + %(input)s + derivative : callable + Callable with the following signature:: + + derivative(input, axis, output, mode, cval, + *extra_arguments, **extra_keywords) + + See `extra_arguments`, `extra_keywords` below. + `derivative` can assume that `input` and `output` are ndarrays. + Note that the output from `derivative` is modified inplace; + be careful to copy important inputs before returning them. + %(output)s + %(mode_multiple)s + %(cval)s + %(extra_keywords)s + %(extra_arguments)s + + Returns + ------- + generic_gradient_matnitude : ndarray + Filtered array. Has the same shape as `input`. + + """ + if extra_keywords is None: + extra_keywords = {} + input = numpy.asarray(input) + output = _ni_support._get_output(output, input) + axes = list(range(input.ndim)) + if len(axes) > 0: + modes = _ni_support._normalize_sequence(mode, len(axes)) + derivative(input, axes[0], output, modes[0], cval, + *extra_arguments, **extra_keywords) + numpy.multiply(output, output, output) + for ii in range(1, len(axes)): + tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval, + *extra_arguments, **extra_keywords) + numpy.multiply(tmp, tmp, tmp) + output += tmp + # This allows the sqrt to work with a different default casting + numpy.sqrt(output, output, casting='unsafe') + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def gaussian_gradient_magnitude(input, sigma, output=None, + mode="reflect", cval=0.0, **kwargs): + """Multidimensional gradient magnitude using Gaussian derivatives. + + Parameters + ---------- + %(input)s + sigma : scalar or sequence of scalars + The standard deviations of the Gaussian filter are given for + each axis as a sequence, or as a single number, in which case + it is equal for all axes. + %(output)s + %(mode_multiple)s + %(cval)s + Extra keyword arguments will be passed to gaussian_filter(). + + Returns + ------- + gaussian_gradient_magnitude : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = numpy.asarray(input) + + def derivative(input, axis, output, mode, cval, sigma, **kwargs): + order = [0] * input.ndim + order[axis] = 1 + return gaussian_filter(input, sigma, order, output, mode, + cval, **kwargs) + + return generic_gradient_magnitude(input, derivative, output, mode, + cval, extra_arguments=(sigma,), + extra_keywords=kwargs) + + +def _correlate_or_convolve(input, weights, output, mode, cval, origin, + convolution): + input = numpy.asarray(input) + weights = numpy.asarray(weights) + complex_input = input.dtype.kind == 'c' + complex_weights = weights.dtype.kind == 'c' + if complex_input or complex_weights: + if complex_weights and not convolution: + # As for numpy.correlate, conjugate weights rather than input. + weights = weights.conj() + kwargs = dict( + mode=mode, origin=origin, convolution=convolution + ) + output = _ni_support._get_output(output, input, complex_output=True) + + return _complex_via_real_components(_correlate_or_convolve, input, + weights, output, cval, **kwargs) + + origins = _ni_support._normalize_sequence(origin, input.ndim) + weights = numpy.asarray(weights, dtype=numpy.float64) + wshape = [ii for ii in weights.shape if ii > 0] + if len(wshape) != input.ndim: + raise RuntimeError('filter weights array has incorrect shape.') + if convolution: + weights = weights[tuple([slice(None, None, -1)] * weights.ndim)] + for ii in range(len(origins)): + origins[ii] = -origins[ii] + if not weights.shape[ii] & 1: + origins[ii] -= 1 + for origin, lenw in zip(origins, wshape): + if _invalid_origin(origin, lenw): + raise ValueError('Invalid origin; origin must satisfy ' + '-(weights.shape[k] // 2) <= origin[k] <= ' + '(weights.shape[k]-1) // 2') + + if not weights.flags.contiguous: + weights = weights.copy() + output = _ni_support._get_output(output, input) + temp_needed = numpy.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + if not isinstance(mode, str) and isinstance(mode, Iterable): + raise RuntimeError("A sequence of modes is not supported") + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.correlate(input, weights, output, mode, cval, origins) + if temp_needed: + temp[...] = output + output = temp + return output + + +@_ni_docstrings.docfiller +def correlate(input, weights, output=None, mode='reflect', cval=0.0, + origin=0): + """ + Multidimensional correlation. + + The array is correlated with the given kernel. + + Parameters + ---------- + %(input)s + weights : ndarray + array of weights, same number of dimensions as input + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + + Returns + ------- + result : ndarray + The result of correlation of `input` with `weights`. + + See Also + -------- + convolve : Convolve an image with a kernel. + + Examples + -------- + Correlation is the process of moving a filter mask often referred to + as kernel over the image and computing the sum of products at each location. + + >>> from scipy.ndimage import correlate + >>> import numpy as np + >>> input_img = np.arange(25).reshape(5,5) + >>> print(input_img) + [[ 0 1 2 3 4] + [ 5 6 7 8 9] + [10 11 12 13 14] + [15 16 17 18 19] + [20 21 22 23 24]] + + Define a kernel (weights) for correlation. In this example, it is for sum of + center and up, down, left and right next elements. + + >>> weights = [[0, 1, 0], + ... [1, 1, 1], + ... [0, 1, 0]] + + We can calculate a correlation result: + For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``. + + >>> correlate(input_img, weights) + array([[ 6, 10, 15, 20, 24], + [ 26, 30, 35, 40, 44], + [ 51, 55, 60, 65, 69], + [ 76, 80, 85, 90, 94], + [ 96, 100, 105, 110, 114]]) + + """ + return _correlate_or_convolve(input, weights, output, mode, cval, + origin, False) + + +@_ni_docstrings.docfiller +def convolve(input, weights, output=None, mode='reflect', cval=0.0, + origin=0): + """ + Multidimensional convolution. + + The array is convolved with the given kernel. + + Parameters + ---------- + %(input)s + weights : array_like + Array of weights, same number of dimensions as input + %(output)s + %(mode_reflect)s + cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0 + origin : int, optional + Controls the origin of the input signal, which is where the + filter is centered to produce the first element of the output. + Positive values shift the filter to the right, and negative values + shift the filter to the left. Default is 0. + + Returns + ------- + result : ndarray + The result of convolution of `input` with `weights`. + + See Also + -------- + correlate : Correlate an image with a kernel. + + Notes + ----- + Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where + W is the `weights` kernel, + j is the N-D spatial index over :math:`W`, + I is the `input` and k is the coordinate of the center of + W, specified by `origin` in the input parameters. + + Examples + -------- + Perhaps the simplest case to understand is ``mode='constant', cval=0.0``, + because in this case borders (i.e., where the `weights` kernel, centered + on any one value, extends beyond an edge of `input`) are treated as zeros. + + >>> import numpy as np + >>> a = np.array([[1, 2, 0, 0], + ... [5, 3, 0, 4], + ... [0, 0, 0, 7], + ... [9, 3, 0, 0]]) + >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]]) + >>> from scipy import ndimage + >>> ndimage.convolve(a, k, mode='constant', cval=0.0) + array([[11, 10, 7, 4], + [10, 3, 11, 11], + [15, 12, 14, 7], + [12, 3, 7, 0]]) + + Setting ``cval=1.0`` is equivalent to padding the outer edge of `input` + with 1.0's (and then extracting only the original region of the result). + + >>> ndimage.convolve(a, k, mode='constant', cval=1.0) + array([[13, 11, 8, 7], + [11, 3, 11, 14], + [16, 12, 14, 10], + [15, 6, 10, 5]]) + + With ``mode='reflect'`` (the default), outer values are reflected at the + edge of `input` to fill in missing values. + + >>> b = np.array([[2, 0, 0], + ... [1, 0, 0], + ... [0, 0, 0]]) + >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]]) + >>> ndimage.convolve(b, k, mode='reflect') + array([[5, 0, 0], + [3, 0, 0], + [1, 0, 0]]) + + This includes diagonally at the corners. + + >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]]) + >>> ndimage.convolve(b, k) + array([[4, 2, 0], + [3, 2, 0], + [1, 1, 0]]) + + With ``mode='nearest'``, the single nearest value in to an edge in + `input` is repeated as many times as needed to match the overlapping + `weights`. + + >>> c = np.array([[2, 0, 1], + ... [1, 0, 0], + ... [0, 0, 0]]) + >>> k = np.array([[0, 1, 0], + ... [0, 1, 0], + ... [0, 1, 0], + ... [0, 1, 0], + ... [0, 1, 0]]) + >>> ndimage.convolve(c, k, mode='nearest') + array([[7, 0, 3], + [5, 0, 2], + [3, 0, 1]]) + + """ + return _correlate_or_convolve(input, weights, output, mode, cval, + origin, True) + + +@_ni_docstrings.docfiller +def uniform_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D uniform filter along the given axis. + + The lines of the array along the given axis are filtered with a + uniform filter of given size. + + Parameters + ---------- + %(input)s + size : int + length of uniform filter + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + result : ndarray + Filtered array. Has same shape as `input`. + + Examples + -------- + >>> from scipy.ndimage import uniform_filter1d + >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([4, 3, 4, 1, 4, 6, 6, 3]) + """ + input = numpy.asarray(input) + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + complex_output = input.dtype.kind == 'c' + output = _ni_support._get_output(output, input, + complex_output=complex_output) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + if not complex_output: + _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, + origin) + else: + _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode, + numpy.real(cval), origin) + _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode, + numpy.imag(cval), origin) + return output + + +@_ni_docstrings.docfiller +def uniform_filter(input, size=3, output=None, mode="reflect", + cval=0.0, origin=0, *, axes=None): + """Multidimensional uniform filter. + + Parameters + ---------- + %(input)s + size : int or sequence of ints, optional + The sizes of the uniform filter are given for each axis as a + sequence, or as a single number, in which case the size is + equal for all axes. + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + uniform_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + The multidimensional filter is implemented as a sequence of + 1-D uniform filters. The intermediate arrays are stored + in the same data type as the output. Therefore, for output types + with a limited precision, the results may be imprecise because + intermediate results may be stored with insufficient precision. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.uniform_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = numpy.asarray(input) + output = _ni_support._get_output(output, input, + complex_output=input.dtype.kind == 'c') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + sizes = _ni_support._normalize_sequence(size, num_axes) + origins = _ni_support._normalize_sequence(origin, num_axes) + modes = _ni_support._normalize_sequence(mode, num_axes) + axes = [(axes[ii], sizes[ii], origins[ii], modes[ii]) + for ii in range(num_axes) if sizes[ii] > 1] + if len(axes) > 0: + for axis, size, origin, mode in axes: + uniform_filter1d(input, int(size), axis, output, mode, + cval, origin) + input = output + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def minimum_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D minimum filter along the given axis. + + The lines of the array along the given axis are filtered with a + minimum filter of given size. + + Parameters + ---------- + %(input)s + size : int + length along which to calculate 1D minimum + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + result : ndarray. + Filtered image. Has the same shape as `input`. + + Notes + ----- + This function implements the MINLIST algorithm [1]_, as described by + Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being + the `input` length, regardless of filter size. + + References + ---------- + .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 + .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html + + + Examples + -------- + >>> from scipy.ndimage import minimum_filter1d + >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([2, 0, 0, 0, 1, 1, 0, 0]) + """ + input = numpy.asarray(input) + if numpy.iscomplexobj(input): + raise TypeError('Complex type not supported') + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + output = _ni_support._get_output(output, input) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, + origin, 1) + return output + + +@_ni_docstrings.docfiller +def maximum_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D maximum filter along the given axis. + + The lines of the array along the given axis are filtered with a + maximum filter of given size. + + Parameters + ---------- + %(input)s + size : int + Length along which to calculate the 1-D maximum. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + maximum1d : ndarray, None + Maximum-filtered array with same shape as input. + None if `output` is not None + + Notes + ----- + This function implements the MAXLIST algorithm [1]_, as described by + Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being + the `input` length, regardless of filter size. + + References + ---------- + .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 + .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html + + Examples + -------- + >>> from scipy.ndimage import maximum_filter1d + >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([8, 8, 8, 4, 9, 9, 9, 9]) + """ + input = numpy.asarray(input) + if numpy.iscomplexobj(input): + raise TypeError('Complex type not supported') + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + output = _ni_support._get_output(output, input) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, + origin, 0) + return output + + +def _min_or_max_filter(input, size, footprint, structure, output, mode, + cval, origin, minimum, axes=None): + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=3) + if structure is None: + if footprint is None: + if size is None: + raise RuntimeError("no footprint provided") + separable = True + else: + footprint = numpy.asarray(footprint, dtype=bool) + if not footprint.any(): + raise ValueError("All-zero footprint is not supported.") + if footprint.all(): + size = footprint.shape + footprint = None + separable = True + else: + separable = False + else: + structure = numpy.asarray(structure, dtype=numpy.float64) + separable = False + if footprint is None: + footprint = numpy.ones(structure.shape, bool) + else: + footprint = numpy.asarray(footprint, dtype=bool) + input = numpy.asarray(input) + if numpy.iscomplexobj(input): + raise TypeError('Complex type not supported') + output = _ni_support._get_output(output, input) + temp_needed = numpy.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if separable: + origins = _ni_support._normalize_sequence(origin, num_axes) + sizes = _ni_support._normalize_sequence(size, num_axes) + modes = _ni_support._normalize_sequence(mode, num_axes) + axes = [(axes[ii], sizes[ii], origins[ii], modes[ii]) + for ii in range(len(axes)) if sizes[ii] > 1] + if minimum: + filter_ = minimum_filter1d + else: + filter_ = maximum_filter1d + if len(axes) > 0: + for axis, size, origin, mode in axes: + filter_(input, int(size), axis, output, mode, cval, origin) + input = output + else: + output[...] = input[...] + else: + origins = _ni_support._normalize_sequence(origin, input.ndim) + if num_axes < input.ndim: + if footprint.ndim != num_axes: + raise RuntimeError("footprint array has incorrect shape") + footprint = numpy.expand_dims( + footprint, + tuple(ax for ax in range(input.ndim) if ax not in axes) + ) + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError('footprint array has incorrect shape.') + for origin, lenf in zip(origins, fshape): + if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): + raise ValueError('invalid origin') + if not footprint.flags.contiguous: + footprint = footprint.copy() + if structure is not None: + if len(structure.shape) != input.ndim: + raise RuntimeError('structure array has incorrect shape') + if num_axes != structure.ndim: + structure = numpy.expand_dims( + structure, + tuple(ax for ax in range(structure.ndim) if ax not in axes) + ) + if not structure.flags.contiguous: + structure = structure.copy() + if not isinstance(mode, str) and isinstance(mode, Iterable): + raise RuntimeError( + "A sequence of modes is not supported for non-separable " + "footprints") + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter(input, footprint, structure, output, + mode, cval, origins, minimum) + if temp_needed: + temp[...] = output + output = temp + return output + + +@_ni_docstrings.docfiller +def minimum_filter(input, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """Calculate a multidimensional minimum filter. + + Parameters + ---------- + %(input)s + %(size_foot)s + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + minimum_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + A sequence of modes (one per axis) is only supported when the footprint is + separable. Otherwise, a single mode string must be provided. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.minimum_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _min_or_max_filter(input, size, footprint, None, output, mode, + cval, origin, 1, axes) + + +@_ni_docstrings.docfiller +def maximum_filter(input, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """Calculate a multidimensional maximum filter. + + Parameters + ---------- + %(input)s + %(size_foot)s + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + maximum_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + A sequence of modes (one per axis) is only supported when the footprint is + separable. Otherwise, a single mode string must be provided. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.maximum_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _min_or_max_filter(input, size, footprint, None, output, mode, + cval, origin, 0, axes) + + +@_ni_docstrings.docfiller +def _rank_filter(input, rank, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, operation='rank', + axes=None): + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=3) + input = numpy.asarray(input) + if numpy.iscomplexobj(input): + raise TypeError('Complex type not supported') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + origins = _ni_support._normalize_sequence(origin, num_axes) + if footprint is None: + if size is None: + raise RuntimeError("no footprint or filter size provided") + sizes = _ni_support._normalize_sequence(size, num_axes) + footprint = numpy.ones(sizes, dtype=bool) + else: + footprint = numpy.asarray(footprint, dtype=bool) + if num_axes < input.ndim: + # set origin = 0 for any axes not being filtered + origins_temp = [0,] * input.ndim + for o, ax in zip(origins, axes): + origins_temp[ax] = o + origins = origins_temp + + if not isinstance(mode, str) and isinstance(mode, Iterable): + # set mode = 'constant' for any axes not being filtered + modes = _ni_support._normalize_sequence(mode, num_axes) + modes_temp = ['constant'] * input.ndim + for m, ax in zip(modes, axes): + modes_temp[ax] = m + mode = modes_temp + + # insert singleton dimension along any non-filtered axes + if footprint.ndim != num_axes: + raise RuntimeError("footprint array has incorrect shape") + footprint = numpy.expand_dims( + footprint, + tuple(ax for ax in range(input.ndim) if ax not in axes) + ) + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError('footprint array has incorrect shape.') + for origin, lenf in zip(origins, fshape): + if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): + raise ValueError('invalid origin') + if not footprint.flags.contiguous: + footprint = footprint.copy() + filter_size = numpy.where(footprint, 1, 0).sum() + if operation == 'median': + rank = filter_size // 2 + elif operation == 'percentile': + percentile = rank + if percentile < 0.0: + percentile += 100.0 + if percentile < 0 or percentile > 100: + raise RuntimeError('invalid percentile') + if percentile == 100.0: + rank = filter_size - 1 + else: + rank = int(float(filter_size) * percentile / 100.0) + if rank < 0: + rank += filter_size + if rank < 0 or rank >= filter_size: + raise RuntimeError('rank not within filter footprint size') + if rank == 0: + return minimum_filter(input, None, footprint, output, mode, cval, + origins, axes=None) + elif rank == filter_size - 1: + return maximum_filter(input, None, footprint, output, mode, cval, + origins, axes=None) + else: + output = _ni_support._get_output(output, input) + temp_needed = numpy.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + if not isinstance(mode, str) and isinstance(mode, Iterable): + raise RuntimeError( + "A sequence of modes is not supported by non-separable rank " + "filters") + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.rank_filter(input, rank, footprint, output, mode, cval, + origins) + if temp_needed: + temp[...] = output + output = temp + return output + + +@_ni_docstrings.docfiller +def rank_filter(input, rank, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """Calculate a multidimensional rank filter. + + Parameters + ---------- + %(input)s + rank : int + The rank parameter may be less than zero, i.e., rank = -1 + indicates the largest element. + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. + + Returns + ------- + rank_filter : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.rank_filter(ascent, rank=42, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + rank = operator.index(rank) + return _rank_filter(input, rank, size, footprint, output, mode, cval, + origin, 'rank', axes=axes) + + +@_ni_docstrings.docfiller +def median_filter(input, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """ + Calculate a multidimensional median filter. + + Parameters + ---------- + %(input)s + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. + + Returns + ------- + median_filter : ndarray + Filtered array. Has the same shape as `input`. + + See Also + -------- + scipy.signal.medfilt2d + + Notes + ----- + For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes + the specialised function `scipy.signal.medfilt2d` may be faster. It is + however limited to constant mode with ``cval=0``. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.median_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _rank_filter(input, 0, size, footprint, output, mode, cval, + origin, 'median', axes=axes) + + +@_ni_docstrings.docfiller +def percentile_filter(input, percentile, size=None, footprint=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """Calculate a multidimensional percentile filter. + + Parameters + ---------- + %(input)s + percentile : scalar + The percentile parameter may be less than zero, i.e., + percentile = -20 equals percentile = 80 + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. + + Returns + ------- + percentile_filter : ndarray + Filtered array. Has the same shape as `input`. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _rank_filter(input, percentile, size, footprint, output, mode, + cval, origin, 'percentile', axes=axes) + + +@_ni_docstrings.docfiller +def generic_filter1d(input, function, filter_size, axis=-1, + output=None, mode="reflect", cval=0.0, origin=0, + extra_arguments=(), extra_keywords=None): + """Calculate a 1-D filter along the given axis. + + `generic_filter1d` iterates over the lines of the array, calling the + given function at each line. The arguments of the line are the + input line, and the output line. The input and output lines are 1-D + double arrays. The input line is extended appropriately according + to the filter size and origin. The output line must be modified + in-place with the result. + + Parameters + ---------- + %(input)s + function : {callable, scipy.LowLevelCallable} + Function to apply along given axis. + filter_size : scalar + Length of the filter. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + %(extra_arguments)s + %(extra_keywords)s + + Returns + ------- + generic_filter1d : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + This function also accepts low-level callback functions with one of + the following signatures and wrapped in `scipy.LowLevelCallable`: + + .. code:: c + + int function(double *input_line, npy_intp input_length, + double *output_line, npy_intp output_length, + void *user_data) + int function(double *input_line, intptr_t input_length, + double *output_line, intptr_t output_length, + void *user_data) + + The calling function iterates over the lines of the input and output + arrays, calling the callback function at each line. The current line + is extended according to the border conditions set by the calling + function, and the result is copied into the array that is passed + through ``input_line``. The length of the input line (after extension) + is passed through ``input_length``. The callback function should apply + the filter and store the result in the array passed through + ``output_line``. The length of the output line is passed through + ``output_length``. ``user_data`` is the data pointer provided + to `scipy.LowLevelCallable` as-is. + + The callback function must return an integer error status that is zero + if something went wrong and one otherwise. If an error occurs, you should + normally set the python error status with an informative message + before returning, otherwise a default error message is set by the + calling function. + + In addition, some other low-level function pointer specifications + are accepted, but these are for backward compatibility only and should + not be used in new code. + + """ + if extra_keywords is None: + extra_keywords = {} + input = numpy.asarray(input) + if numpy.iscomplexobj(input): + raise TypeError('Complex type not supported') + output = _ni_support._get_output(output, input) + if filter_size < 1: + raise RuntimeError('invalid filter size') + axis = normalize_axis_index(axis, input.ndim) + if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >= + filter_size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.generic_filter1d(input, function, filter_size, axis, output, + mode, cval, origin, extra_arguments, + extra_keywords) + return output + + +@_ni_docstrings.docfiller +def generic_filter(input, function, size=None, footprint=None, + output=None, mode="reflect", cval=0.0, origin=0, + extra_arguments=(), extra_keywords=None): + """Calculate a multidimensional filter using the given function. + + At each element the provided function is called. The input values + within the filter footprint at that element are passed to the function + as a 1-D array of double values. + + Parameters + ---------- + %(input)s + function : {callable, scipy.LowLevelCallable} + Function to apply at each element. + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + %(extra_arguments)s + %(extra_keywords)s + + Returns + ------- + generic_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + This function also accepts low-level callback functions with one of + the following signatures and wrapped in `scipy.LowLevelCallable`: + + .. code:: c + + int callback(double *buffer, npy_intp filter_size, + double *return_value, void *user_data) + int callback(double *buffer, intptr_t filter_size, + double *return_value, void *user_data) + + The calling function iterates over the elements of the input and + output arrays, calling the callback function at each element. The + elements within the footprint of the filter at the current element are + passed through the ``buffer`` parameter, and the number of elements + within the footprint through ``filter_size``. The calculated value is + returned in ``return_value``. ``user_data`` is the data pointer provided + to `scipy.LowLevelCallable` as-is. + + The callback function must return an integer error status that is zero + if something went wrong and one otherwise. If an error occurs, you should + normally set the python error status with an informative message + before returning, otherwise a default error message is set by the + calling function. + + In addition, some other low-level function pointer specifications + are accepted, but these are for backward compatibility only and should + not be used in new code. + + Examples + -------- + Import the necessary modules and load the example image used for + filtering. + + >>> import numpy as np + >>> from scipy import datasets + >>> from scipy.ndimage import generic_filter + >>> import matplotlib.pyplot as plt + >>> ascent = datasets.ascent() + + Compute a maximum filter with kernel size 10 by passing a simple NumPy + aggregation function as argument to `function`. + + >>> maximum_filter_result = generic_filter(ascent, np.amax, [10, 10]) + + While a maximmum filter could also directly be obtained using + `maximum_filter`, `generic_filter` allows generic Python function or + `scipy.LowLevelCallable` to be used as a filter. Here, we compute the + range between maximum and minimum value as an example for a kernel size + of 5. + + >>> def custom_filter(image): + ... return np.amax(image) - np.amin(image) + >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5]) + + Plot the original and filtered images. + + >>> fig, axes = plt.subplots(3, 1, figsize=(4, 12)) + >>> plt.gray() # show the filtered result in grayscale + >>> top, middle, bottom = axes + >>> for ax in axes: + ... ax.set_axis_off() # remove coordinate system + >>> top.imshow(ascent) + >>> top.set_title("Original image") + >>> middle.imshow(maximum_filter_result) + >>> middle.set_title("Maximum filter, Kernel: 10x10") + >>> bottom.imshow(custom_filter_result) + >>> bottom.set_title("Custom filter, Kernel: 5x5") + >>> fig.tight_layout() + + """ + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=2) + if extra_keywords is None: + extra_keywords = {} + input = numpy.asarray(input) + if numpy.iscomplexobj(input): + raise TypeError('Complex type not supported') + origins = _ni_support._normalize_sequence(origin, input.ndim) + if footprint is None: + if size is None: + raise RuntimeError("no footprint or filter size provided") + sizes = _ni_support._normalize_sequence(size, input.ndim) + footprint = numpy.ones(sizes, dtype=bool) + else: + footprint = numpy.asarray(footprint, dtype=bool) + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError('filter footprint array has incorrect shape.') + for origin, lenf in zip(origins, fshape): + if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf): + raise ValueError('invalid origin') + if not footprint.flags.contiguous: + footprint = footprint.copy() + output = _ni_support._get_output(output, input) + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.generic_filter(input, function, footprint, output, mode, + cval, origins, extra_arguments, extra_keywords) + return output diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..e6469f2c75fcee1f74dfbbe049df8ca05b074505 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py @@ -0,0 +1,208 @@ +"""Docstring components common to several ndimage functions.""" +from scipy._lib import doccer + +__all__ = ['docfiller'] + + +_input_doc = ( +"""input : array_like + The input array.""") +_axis_doc = ( +"""axis : int, optional + The axis of `input` along which to calculate. Default is -1.""") +_output_doc = ( +"""output : array or dtype, optional + The array in which to place the output, or the dtype of the + returned array. By default an array of the same dtype as input + will be created.""") +_size_foot_doc = ( +"""size : scalar or tuple, optional + See footprint, below. Ignored if footprint is given. +footprint : array, optional + Either `size` or `footprint` must be defined. `size` gives + the shape that is taken from the input array, at every element + position, to define the input to the filter function. + `footprint` is a boolean array that specifies (implicitly) a + shape, but also which of the elements within this shape will get + passed to the filter function. Thus ``size=(n,m)`` is equivalent + to ``footprint=np.ones((n,m))``. We adjust `size` to the number + of dimensions of the input array, so that, if the input array is + shape (10,10,10), and `size` is 2, then the actual size used is + (2,2,2). When `footprint` is given, `size` is ignored.""") +_mode_reflect_doc = ( +"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the input array is extended + beyond its boundaries. Default is 'reflect'. Behavior for each valid + value is as follows: + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + For consistency with the interpolation functions, the following mode + names can also be used: + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'grid-constant' + This is a synonym for 'constant'. + + 'grid-wrap' + This is a synonym for 'wrap'.""") + +_mode_interp_constant_doc = ( +"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \ +'mirror', 'grid-wrap', 'wrap'}, optional + The `mode` parameter determines how the input array is extended + beyond its boundaries. Default is 'constant'. Behavior for each valid + value is as follows (see additional plots and details on + :ref:`boundary modes `): + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. No + interpolation is performed beyond the edges of the input. + + 'grid-constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. Interpolation + occurs for samples outside the input's extent as well. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'grid-wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + 'wrap' (`d b c d | a b c d | b c a b`) + The input is extended by wrapping around to the opposite edge, but in a + way such that the last point and initial point exactly overlap. In this + case it is not well defined which sample will be chosen at the point of + overlap.""") +_mode_interp_mirror_doc = ( + _mode_interp_constant_doc.replace("Default is 'constant'", + "Default is 'mirror'") +) +assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \ + 'Default not replaced' + +_mode_multiple_doc = ( +"""mode : str or sequence, optional + The `mode` parameter determines how the input array is extended + when the filter overlaps a border. By passing a sequence of modes + with length equal to the number of dimensions of the input array, + different modes can be specified along each axis. Default value is + 'reflect'. The valid values and their behavior is as follows: + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + For consistency with the interpolation functions, the following mode + names can also be used: + + 'grid-constant' + This is a synonym for 'constant'. + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'grid-wrap' + This is a synonym for 'wrap'.""") +_cval_doc = ( +"""cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0.""") +_origin_doc = ( +"""origin : int, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the left, and negative ones + to the right.""") +_origin_multiple_doc = ( +"""origin : int or sequence, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the left, and negative ones + to the right. By passing a sequence of origins with length equal to + the number of dimensions of the input array, different shifts can + be specified along each axis.""") +_extra_arguments_doc = ( +"""extra_arguments : sequence, optional + Sequence of extra positional arguments to pass to passed function.""") +_extra_keywords_doc = ( +"""extra_keywords : dict, optional + dict of extra keyword arguments to pass to passed function.""") +_prefilter_doc = ( +"""prefilter : bool, optional + Determines if the input array is prefiltered with `spline_filter` + before interpolation. The default is True, which will create a + temporary `float64` array of filtered values if `order > 1`. If + setting this to False, the output will be slightly blurred if + `order > 1`, unless the input is prefiltered, i.e. it is the result + of calling `spline_filter` on the original input.""") + +docdict = { + 'input': _input_doc, + 'axis': _axis_doc, + 'output': _output_doc, + 'size_foot': _size_foot_doc, + 'mode_interp_constant': _mode_interp_constant_doc, + 'mode_interp_mirror': _mode_interp_mirror_doc, + 'mode_reflect': _mode_reflect_doc, + 'mode_multiple': _mode_multiple_doc, + 'cval': _cval_doc, + 'origin': _origin_doc, + 'origin_multiple': _origin_multiple_doc, + 'extra_arguments': _extra_arguments_doc, + 'extra_keywords': _extra_keywords_doc, + 'prefilter': _prefilter_doc + } + +docfiller = doccer.filldoc(docdict) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/filters.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..e16d9d279a9585b2454c46ee09cf22143de833a6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/filters.py @@ -0,0 +1,27 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'correlate1d', 'convolve1d', 'gaussian_filter1d', + 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace', + 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude', + 'gaussian_gradient_magnitude', 'correlate', 'convolve', + 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', + 'maximum_filter1d', 'minimum_filter', 'maximum_filter', + 'rank_filter', 'median_filter', 'percentile_filter', + 'generic_filter1d', 'generic_filter' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='filters', + private_modules=['_filters'], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc6581276063ca8d0e90362e1d1eee743d4ed18 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py @@ -0,0 +1,13 @@ +from __future__ import annotations +import numpy + +# list of numarray data types +integer_types: list[type] = [ + numpy.int8, numpy.uint8, numpy.int16, numpy.uint16, + numpy.int32, numpy.uint32, numpy.int64, numpy.uint64] + +float_types: list[type] = [numpy.float32, numpy.float64] + +complex_types: list[type] = [numpy.complex64, numpy.complex128] + +types: list[type] = integer_types + float_types diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40cf87665cef9e7b27676b9215c3352feb90a992 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_c_api.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77469f5bc212161cd8c0a89e436b7c4a0c0176ab Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_datatypes.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d98b4be23c369bad847d8234014c277c5e1f0a9 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e70a919a4a40294a5de3354554d590d9bdce8bd Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_fourier.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2c51834362ed9d41cf8ccef64419ef36c1c7ae7 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3095bfa7db64776b7e0f3f7bab1ac5f8fa5d9f4f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ab81d1ad03345e727356ac0e99d3479dbe08a31 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_ni_support.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bae2096939fcba7342bc47413a450281ab897c05 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/__pycache__/test_splines.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py new file mode 100644 index 0000000000000000000000000000000000000000..cd9382a16ada38a6d3059d54ad765c2e0f74b7c1 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py @@ -0,0 +1,66 @@ +""" Testing data types for ndimage calls +""" +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_ +import pytest + +from scipy import ndimage + + +def test_map_coordinates_dts(): + # check that ndimage accepts different data types for interpolation + data = np.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + shifted_data = np.array([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + idx = np.indices(data.shape) + dts = (np.uint8, np.uint16, np.uint32, np.uint64, + np.int8, np.int16, np.int32, np.int64, + np.intp, np.uintp, np.float32, np.float64) + for order in range(0, 6): + for data_dt in dts: + these_data = data.astype(data_dt) + for coord_dt in dts: + # affine mapping + mat = np.eye(2, dtype=coord_dt) + off = np.zeros((2,), dtype=coord_dt) + out = ndimage.affine_transform(these_data, mat, off) + assert_array_almost_equal(these_data, out) + # map coordinates + coords_m1 = idx.astype(coord_dt) - 1 + coords_p10 = idx.astype(coord_dt) + 10 + out = ndimage.map_coordinates(these_data, coords_m1, order=order) + assert_array_almost_equal(out, shifted_data) + # check constant fill works + out = ndimage.map_coordinates(these_data, coords_p10, order=order) + assert_array_almost_equal(out, np.zeros((3,4))) + # check shift and zoom + out = ndimage.shift(these_data, 1) + assert_array_almost_equal(out, shifted_data) + out = ndimage.zoom(these_data, 1) + assert_array_almost_equal(these_data, out) + + +@pytest.mark.xfail(True, reason="Broken on many platforms") +def test_uint64_max(): + # Test interpolation respects uint64 max. Reported to fail at least on + # win32 (due to the 32 bit visual C compiler using signed int64 when + # converting between uint64 to double) and Debian on s390x. + # Interpolation is always done in double precision floating point, so + # we use the largest uint64 value for which int(float(big)) still fits + # in a uint64. + # This test was last enabled on macOS only, and there it started failing + # on arm64 as well (see gh-19117). + big = 2**64 - 1025 + arr = np.array([big, big, big], dtype=np.uint64) + # Tests geometric transform (map_coordinates, affine_transform) + inds = np.indices(arr.shape) - 0.1 + x = ndimage.map_coordinates(arr, inds) + assert_(x[1] == int(float(big))) + assert_(x[2] == int(float(big))) + # Tests zoom / shift + x = ndimage.shift(arr, 0.1) + assert_(x[1] == int(float(big))) + assert_(x[2] == int(float(big))) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..6401a69f8627fa6b95c71f3711dfd064e74264f2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py @@ -0,0 +1,2189 @@ +''' Some tests for filters ''' +import functools +import itertools +import math +import numpy + +from numpy.testing import (assert_equal, assert_allclose, + assert_array_almost_equal, + assert_array_equal, assert_almost_equal, + suppress_warnings, assert_) +import pytest +from pytest import raises as assert_raises + +from scipy import ndimage +from scipy.ndimage._filters import _gaussian_kernel1d + +from . import types, float_types, complex_types + + +def sumsq(a, b): + return math.sqrt(((a - b)**2).sum()) + + +def _complex_correlate(array, kernel, real_dtype, convolve=False, + mode="reflect", cval=0, ): + """Utility to perform a reference complex-valued convolutions. + + When convolve==False, correlation is performed instead + """ + array = numpy.asarray(array) + kernel = numpy.asarray(kernel) + complex_array = array.dtype.kind == 'c' + complex_kernel = kernel.dtype.kind == 'c' + if array.ndim == 1: + func = ndimage.convolve1d if convolve else ndimage.correlate1d + else: + func = ndimage.convolve if convolve else ndimage.correlate + if not convolve: + kernel = kernel.conj() + if complex_array and complex_kernel: + # use: real(cval) for array.real component + # imag(cval) for array.imag component + output = ( + func(array.real, kernel.real, output=real_dtype, + mode=mode, cval=numpy.real(cval)) - + func(array.imag, kernel.imag, output=real_dtype, + mode=mode, cval=numpy.imag(cval)) + + 1j * func(array.imag, kernel.real, output=real_dtype, + mode=mode, cval=numpy.imag(cval)) + + 1j * func(array.real, kernel.imag, output=real_dtype, + mode=mode, cval=numpy.real(cval)) + ) + elif complex_array: + output = ( + func(array.real, kernel, output=real_dtype, mode=mode, + cval=numpy.real(cval)) + + 1j * func(array.imag, kernel, output=real_dtype, mode=mode, + cval=numpy.imag(cval)) + ) + elif complex_kernel: + # real array so cval is real too + output = ( + func(array, kernel.real, output=real_dtype, mode=mode, cval=cval) + + 1j * func(array, kernel.imag, output=real_dtype, mode=mode, + cval=cval) + ) + return output + + +def _cases_axes_tuple_length_mismatch(): + # Generate combinations of filter function, valid kwargs, and + # keyword-value pairs for which the value will become with mismatched + # (invalid) size + filter_func = ndimage.gaussian_filter + kwargs = dict(radius=3, mode='constant', sigma=1.0, order=0) + for key, val in kwargs.items(): + yield filter_func, kwargs, key, val + + filter_funcs = [ndimage.uniform_filter, ndimage.minimum_filter, + ndimage.maximum_filter] + kwargs = dict(size=3, mode='constant', origin=0) + for filter_func in filter_funcs: + for key, val in kwargs.items(): + yield filter_func, kwargs, key, val + + +class TestNdimageFilters: + + def _validate_complex(self, array, kernel, type2, mode='reflect', cval=0): + # utility for validating complex-valued correlations + real_dtype = numpy.asarray([], dtype=type2).real.dtype + expected = _complex_correlate( + array, kernel, real_dtype, convolve=False, mode=mode, cval=cval + ) + + if array.ndim == 1: + correlate = functools.partial(ndimage.correlate1d, axis=-1, + mode=mode, cval=cval) + convolve = functools.partial(ndimage.convolve1d, axis=-1, + mode=mode, cval=cval) + else: + correlate = functools.partial(ndimage.correlate, mode=mode, + cval=cval) + convolve = functools.partial(ndimage.convolve, mode=mode, + cval=cval) + + # test correlate output dtype + output = correlate(array, kernel, output=type2) + assert_array_almost_equal(expected, output) + assert_equal(output.dtype.type, type2) + + # test correlate with pre-allocated output + output = numpy.zeros_like(array, dtype=type2) + correlate(array, kernel, output=output) + assert_array_almost_equal(expected, output) + + # test convolve output dtype + output = convolve(array, kernel, output=type2) + expected = _complex_correlate( + array, kernel, real_dtype, convolve=True, mode=mode, cval=cval, + ) + assert_array_almost_equal(expected, output) + assert_equal(output.dtype.type, type2) + + # convolve with pre-allocated output + convolve(array, kernel, output=output) + assert_array_almost_equal(expected, output) + assert_equal(output.dtype.type, type2) + + # warns if the output is not a complex dtype + with pytest.warns(UserWarning, + match="promoting specified output dtype to complex"): + correlate(array, kernel, output=real_dtype) + + with pytest.warns(UserWarning, + match="promoting specified output dtype to complex"): + convolve(array, kernel, output=real_dtype) + + # raises if output array is provided, but is not complex-valued + output_real = numpy.zeros_like(array, dtype=real_dtype) + with assert_raises(RuntimeError): + correlate(array, kernel, output=output_real) + + with assert_raises(RuntimeError): + convolve(array, kernel, output=output_real) + + def test_correlate01(self): + array = numpy.array([1, 2]) + weights = numpy.array([2]) + expected = [2, 4] + + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + def test_correlate01_overlap(self): + array = numpy.arange(256).reshape(16, 16) + weights = numpy.array([2]) + expected = 2 * array + + ndimage.correlate1d(array, weights, output=array) + assert_array_almost_equal(array, expected) + + def test_correlate02(self): + array = numpy.array([1, 2, 3]) + kernel = numpy.array([1]) + + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(array, output) + + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate03(self): + array = numpy.array([1]) + weights = numpy.array([1, 1]) + expected = [2] + + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + def test_correlate04(self): + array = numpy.array([1, 2]) + tcor = [2, 3] + tcov = [3, 4] + weights = numpy.array([1, 1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate05(self): + array = numpy.array([1, 2, 3]) + tcor = [2, 3, 5] + tcov = [3, 5, 6] + kernel = numpy.array([1, 1]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(tcov, output) + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(tcov, output) + + def test_correlate06(self): + array = numpy.array([1, 2, 3]) + tcor = [9, 14, 17] + tcov = [7, 10, 15] + weights = numpy.array([1, 2, 3]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate07(self): + array = numpy.array([1, 2, 3]) + expected = [5, 8, 11] + weights = numpy.array([1, 2, 1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, expected) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, expected) + + def test_correlate08(self): + array = numpy.array([1, 2, 3]) + tcor = [1, 2, 5] + tcov = [3, 6, 7] + weights = numpy.array([1, 2, -1]) + output = ndimage.correlate(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve(array, weights) + assert_array_almost_equal(output, tcov) + output = ndimage.correlate1d(array, weights) + assert_array_almost_equal(output, tcor) + output = ndimage.convolve1d(array, weights) + assert_array_almost_equal(output, tcov) + + def test_correlate09(self): + array = [] + kernel = numpy.array([1, 1]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.correlate1d(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve1d(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate10(self): + array = [[]] + kernel = numpy.array([[1, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal(array, output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal(array, output) + + def test_correlate11(self): + array = numpy.array([[1, 2, 3], + [4, 5, 6]]) + kernel = numpy.array([[1, 1], + [1, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal([[12, 16, 18], [18, 22, 24]], output) + + def test_correlate12(self): + array = numpy.array([[1, 2, 3], + [4, 5, 6]]) + kernel = numpy.array([[1, 0], + [0, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_kernel', types) + def test_correlate13(self, dtype_array, dtype_kernel): + kernel = numpy.array([[1, 0], + [0, 1]]) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, output=dtype_kernel) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + assert_equal(output.dtype.type, dtype_kernel) + + output = ndimage.convolve(array, kernel, + output=dtype_kernel) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + assert_equal(output.dtype.type, dtype_kernel) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate14(self, dtype_array, dtype_output): + kernel = numpy.array([[1, 0], + [0, 1]]) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = numpy.zeros(array.shape, dtype_output) + ndimage.correlate(array, kernel, output=output) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + assert_equal(output.dtype.type, dtype_output) + + ndimage.convolve(array, kernel, output=output) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + assert_equal(output.dtype.type, dtype_output) + + @pytest.mark.parametrize('dtype_array', types) + def test_correlate15(self, dtype_array): + kernel = numpy.array([[1, 0], + [0, 1]]) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, output=numpy.float32) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + assert_equal(output.dtype.type, numpy.float32) + + output = ndimage.convolve(array, kernel, output=numpy.float32) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + assert_equal(output.dtype.type, numpy.float32) + + @pytest.mark.parametrize('dtype_array', types) + def test_correlate16(self, dtype_array): + kernel = numpy.array([[0.5, 0], + [0, 0.5]]) + array = numpy.array([[1, 2, 3], [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, output=numpy.float32) + assert_array_almost_equal([[1, 1.5, 2.5], [2.5, 3, 4]], output) + assert_equal(output.dtype.type, numpy.float32) + + output = ndimage.convolve(array, kernel, output=numpy.float32) + assert_array_almost_equal([[3, 4, 4.5], [4.5, 5.5, 6]], output) + assert_equal(output.dtype.type, numpy.float32) + + def test_correlate17(self): + array = numpy.array([1, 2, 3]) + tcor = [3, 5, 6] + tcov = [2, 3, 5] + kernel = numpy.array([1, 1]) + output = ndimage.correlate(array, kernel, origin=-1) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve(array, kernel, origin=-1) + assert_array_almost_equal(tcov, output) + output = ndimage.correlate1d(array, kernel, origin=-1) + assert_array_almost_equal(tcor, output) + output = ndimage.convolve1d(array, kernel, origin=-1) + assert_array_almost_equal(tcov, output) + + @pytest.mark.parametrize('dtype_array', types) + def test_correlate18(self, dtype_array): + kernel = numpy.array([[1, 0], + [0, 1]]) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, + output=numpy.float32, + mode='nearest', origin=-1) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + assert_equal(output.dtype.type, numpy.float32) + + output = ndimage.convolve(array, kernel, + output=numpy.float32, + mode='nearest', origin=-1) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + assert_equal(output.dtype.type, numpy.float32) + + def test_correlate_mode_sequence(self): + kernel = numpy.ones((2, 2)) + array = numpy.ones((3, 3), float) + with assert_raises(RuntimeError): + ndimage.correlate(array, kernel, mode=['nearest', 'reflect']) + with assert_raises(RuntimeError): + ndimage.convolve(array, kernel, mode=['nearest', 'reflect']) + + @pytest.mark.parametrize('dtype_array', types) + def test_correlate19(self, dtype_array): + kernel = numpy.array([[1, 0], + [0, 1]]) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, + output=numpy.float32, + mode='nearest', origin=[-1, 0]) + assert_array_almost_equal([[5, 6, 8], [8, 9, 11]], output) + assert_equal(output.dtype.type, numpy.float32) + + output = ndimage.convolve(array, kernel, + output=numpy.float32, + mode='nearest', origin=[-1, 0]) + assert_array_almost_equal([[3, 5, 6], [6, 8, 9]], output) + assert_equal(output.dtype.type, numpy.float32) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate20(self, dtype_array, dtype_output): + weights = numpy.array([1, 2, 1]) + expected = [[5, 10, 15], [7, 14, 21]] + array = numpy.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = numpy.zeros((2, 3), dtype_output) + ndimage.correlate1d(array, weights, axis=0, output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, output=output) + assert_array_almost_equal(output, expected) + + def test_correlate21(self): + array = numpy.array([[1, 2, 3], + [2, 4, 6]]) + expected = [[5, 10, 15], [7, 14, 21]] + weights = numpy.array([1, 2, 1]) + output = ndimage.correlate1d(array, weights, axis=0) + assert_array_almost_equal(output, expected) + output = ndimage.convolve1d(array, weights, axis=0) + assert_array_almost_equal(output, expected) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate22(self, dtype_array, dtype_output): + weights = numpy.array([1, 2, 1]) + expected = [[6, 12, 18], [6, 12, 18]] + array = numpy.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = numpy.zeros((2, 3), dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='wrap', output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, + mode='wrap', output=output) + assert_array_almost_equal(output, expected) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate23(self, dtype_array, dtype_output): + weights = numpy.array([1, 2, 1]) + expected = [[5, 10, 15], [7, 14, 21]] + array = numpy.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = numpy.zeros((2, 3), dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output) + assert_array_almost_equal(output, expected) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output) + assert_array_almost_equal(output, expected) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate24(self, dtype_array, dtype_output): + weights = numpy.array([1, 2, 1]) + tcor = [[7, 14, 21], [8, 16, 24]] + tcov = [[4, 8, 12], [5, 10, 15]] + array = numpy.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = numpy.zeros((2, 3), dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output, origin=-1) + assert_array_almost_equal(output, tcor) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output, origin=-1) + assert_array_almost_equal(output, tcov) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate25(self, dtype_array, dtype_output): + weights = numpy.array([1, 2, 1]) + tcor = [[4, 8, 12], [5, 10, 15]] + tcov = [[7, 14, 21], [8, 16, 24]] + array = numpy.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = numpy.zeros((2, 3), dtype_output) + ndimage.correlate1d(array, weights, axis=0, + mode='nearest', output=output, origin=1) + assert_array_almost_equal(output, tcor) + ndimage.convolve1d(array, weights, axis=0, + mode='nearest', output=output, origin=1) + assert_array_almost_equal(output, tcov) + + def test_correlate26(self): + # test fix for gh-11661 (mirror extension of a length 1 signal) + y = ndimage.convolve1d(numpy.ones(1), numpy.ones(5), mode='mirror') + assert_array_equal(y, numpy.array(5.)) + + y = ndimage.correlate1d(numpy.ones(1), numpy.ones(5), mode='mirror') + assert_array_equal(y, numpy.array(5.)) + + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_kernel(self, dtype_input, dtype_kernel, + dtype_output): + kernel = numpy.array([[1, 0], + [0, 1 + 1j]], dtype_kernel) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype_input) + self._validate_complex(array, kernel, dtype_output) + + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + @pytest.mark.parametrize('mode', ['grid-constant', 'constant']) + def test_correlate_complex_kernel_cval(self, dtype_input, dtype_kernel, + dtype_output, mode): + # test use of non-zero cval with complex inputs + # also verifies that mode 'grid-constant' does not segfault + kernel = numpy.array([[1, 0], + [0, 1 + 1j]], dtype_kernel) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype_input) + self._validate_complex(array, kernel, dtype_output, mode=mode, + cval=5.0) + + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + def test_correlate_complex_kernel_invalid_cval(self, dtype_input, + dtype_kernel): + # cannot give complex cval with a real image + kernel = numpy.array([[1, 0], + [0, 1 + 1j]], dtype_kernel) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype_input) + for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d, + ndimage.correlate1d]: + with pytest.raises(ValueError): + func(array, kernel, mode='constant', cval=5.0 + 1.0j, + output=numpy.complex64) + + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_kernel(self, dtype_input, dtype_kernel, + dtype_output): + kernel = numpy.array([1, 1 + 1j], dtype_kernel) + array = numpy.array([1, 2, 3, 4, 5, 6], dtype_input) + self._validate_complex(array, kernel, dtype_output) + + @pytest.mark.parametrize('dtype_kernel', complex_types) + @pytest.mark.parametrize('dtype_input', types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_kernel_cval(self, dtype_input, dtype_kernel, + dtype_output): + kernel = numpy.array([1, 1 + 1j], dtype_kernel) + array = numpy.array([1, 2, 3, 4, 5, 6], dtype_input) + self._validate_complex(array, kernel, dtype_output, mode='constant', + cval=5.0) + + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input(self, dtype_input, dtype_kernel, + dtype_output): + kernel = numpy.array([[1, 0], + [0, 1]], dtype_kernel) + array = numpy.array([[1, 2j, 3], + [1 + 4j, 5, 6j]], dtype_input) + self._validate_complex(array, kernel, dtype_output) + + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input(self, dtype_input, dtype_kernel, + dtype_output): + kernel = numpy.array([1, 0, 1], dtype_kernel) + array = numpy.array([1, 2j, 3, 1 + 4j, 5, 6j], dtype_input) + self._validate_complex(array, kernel, dtype_output) + + @pytest.mark.parametrize('dtype_kernel', types) + @pytest.mark.parametrize('dtype_input', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_cval(self, dtype_input, dtype_kernel, + dtype_output): + kernel = numpy.array([1, 0, 1], dtype_kernel) + array = numpy.array([1, 2j, 3, 1 + 4j, 5, 6j], dtype_input) + self._validate_complex(array, kernel, dtype_output, mode='constant', + cval=5 - 3j) + + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input_and_kernel(self, dtype, dtype_output): + kernel = numpy.array([[1, 0], + [0, 1 + 1j]], dtype) + array = numpy.array([[1, 2j, 3], + [1 + 4j, 5, 6j]], dtype) + self._validate_complex(array, kernel, dtype_output) + + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input_and_kernel_cval(self, dtype, + dtype_output): + kernel = numpy.array([[1, 0], + [0, 1 + 1j]], dtype) + array = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype) + self._validate_complex(array, kernel, dtype_output, mode='constant', + cval=5.0 + 2.0j) + + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output): + kernel = numpy.array([1, 1 + 1j], dtype) + array = numpy.array([1, 2j, 3, 1 + 4j, 5, 6j], dtype) + self._validate_complex(array, kernel, dtype_output) + + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_and_kernel_cval(self, dtype, + dtype_output): + kernel = numpy.array([1, 1 + 1j], dtype) + array = numpy.array([1, 2j, 3, 1 + 4j, 5, 6j], dtype) + self._validate_complex(array, kernel, dtype_output, mode='constant', + cval=5.0 + 2.0j) + + def test_gauss01(self): + input = numpy.array([[1, 2, 3], + [2, 4, 6]], numpy.float32) + output = ndimage.gaussian_filter(input, 0) + assert_array_almost_equal(output, input) + + def test_gauss02(self): + input = numpy.array([[1, 2, 3], + [2, 4, 6]], numpy.float32) + output = ndimage.gaussian_filter(input, 1.0) + assert_equal(input.dtype, output.dtype) + assert_equal(input.shape, output.shape) + + def test_gauss03(self): + # single precision data + input = numpy.arange(100 * 100).astype(numpy.float32) + input.shape = (100, 100) + output = ndimage.gaussian_filter(input, [1.0, 1.0]) + + assert_equal(input.dtype, output.dtype) + assert_equal(input.shape, output.shape) + + # input.sum() is 49995000.0. With single precision floats, we can't + # expect more than 8 digits of accuracy, so use decimal=0 in this test. + assert_almost_equal(output.sum(dtype='d'), input.sum(dtype='d'), + decimal=0) + assert_(sumsq(input, output) > 1.0) + + def test_gauss04(self): + input = numpy.arange(100 * 100).astype(numpy.float32) + input.shape = (100, 100) + otype = numpy.float64 + output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) + assert_equal(output.dtype.type, numpy.float64) + assert_equal(input.shape, output.shape) + assert_(sumsq(input, output) > 1.0) + + def test_gauss05(self): + input = numpy.arange(100 * 100).astype(numpy.float32) + input.shape = (100, 100) + otype = numpy.float64 + output = ndimage.gaussian_filter(input, [1.0, 1.0], + order=1, output=otype) + assert_equal(output.dtype.type, numpy.float64) + assert_equal(input.shape, output.shape) + assert_(sumsq(input, output) > 1.0) + + def test_gauss06(self): + input = numpy.arange(100 * 100).astype(numpy.float32) + input.shape = (100, 100) + otype = numpy.float64 + output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) + output2 = ndimage.gaussian_filter(input, 1.0, output=otype) + assert_array_almost_equal(output1, output2) + + def test_gauss_memory_overlap(self): + input = numpy.arange(100 * 100).astype(numpy.float32) + input.shape = (100, 100) + output1 = ndimage.gaussian_filter(input, 1.0) + ndimage.gaussian_filter(input, 1.0, output=input) + assert_array_almost_equal(output1, input) + + @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'), + [(ndimage.gaussian_filter, (), 0, 1.0), + (ndimage.uniform_filter, (), 1, 3), + (ndimage.minimum_filter, (), 1, 3), + (ndimage.maximum_filter, (), 1, 3), + (ndimage.median_filter, (), 1, 3), + (ndimage.rank_filter, (1,), 1, 3), + (ndimage.percentile_filter, (40,), 1, 3)]) + @pytest.mark.parametrize( + 'axes', + tuple(itertools.combinations(range(-3, 3), 1)) + + tuple(itertools.combinations(range(-3, 3), 2)) + + ((0, 1, 2),)) + def test_filter_axes(self, filter_func, extra_args, size0, size, axes): + # Note: `size` is called `sigma` in `gaussian_filter` + array = numpy.arange(6 * 8 * 12, dtype=numpy.float64).reshape(6, 8, 12) + axes = numpy.array(axes) + + if len(set(axes % array.ndim)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError, match="axes must be unique"): + filter_func(array, *extra_args, size, axes=axes) + return + output = filter_func(array, *extra_args, size, axes=axes) + + # result should be equivalent to sigma=0.0/size=1 on unfiltered axes + all_sizes = (size if ax in (axes % array.ndim) else size0 + for ax in range(array.ndim)) + expected = filter_func(array, *extra_args, all_sizes) + assert_allclose(output, expected) + + kwargs_gauss = dict(radius=[4, 2, 3], order=[0, 1, 2], + mode=['reflect', 'nearest', 'constant']) + kwargs_other = dict(origin=(-1, 0, 1), + mode=['reflect', 'nearest', 'constant']) + kwargs_rank = dict(origin=(-1, 0, 1)) + + @pytest.mark.parametrize("filter_func, size0, size, kwargs", + [(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss), + (ndimage.uniform_filter, 1, 3, kwargs_other), + (ndimage.maximum_filter, 1, 3, kwargs_other), + (ndimage.minimum_filter, 1, 3, kwargs_other), + (ndimage.median_filter, 1, 3, kwargs_rank), + (ndimage.rank_filter, 1, 3, kwargs_rank), + (ndimage.percentile_filter, 1, 3, kwargs_rank)]) + @pytest.mark.parametrize('axes', itertools.combinations(range(-3, 3), 2)) + def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes): + array = numpy.arange(6 * 8 * 12, dtype=numpy.float64).reshape(6, 8, 12) + + kwargs = {key: numpy.array(val) for key, val in kwargs.items()} + axes = numpy.array(axes) + n_axes = axes.size + + if filter_func == ndimage.rank_filter: + args = (2,) # (rank,) + elif filter_func == ndimage.percentile_filter: + args = (30,) # (percentile,) + else: + args = () + + # form kwargs that specify only the axes in `axes` + reduced_kwargs = {key: val[axes] for key, val in kwargs.items()} + if len(set(axes % array.ndim)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError, match="axes must be unique"): + filter_func(array, *args, [size]*n_axes, axes=axes, + **reduced_kwargs) + return + + output = filter_func(array, *args, [size]*n_axes, axes=axes, + **reduced_kwargs) + + # result should be equivalent to sigma=0.0/size=1 on unfiltered axes + size_3d = numpy.full(array.ndim, fill_value=size0) + size_3d[axes] = size + if 'origin' in kwargs: + # origin should be zero on the axis that has size 0 + origin = numpy.array([0, 0, 0]) + origin[axes] = reduced_kwargs['origin'] + kwargs['origin'] = origin + expected = filter_func(array, *args, size_3d, **kwargs) + assert_allclose(output, expected) + + @pytest.mark.parametrize( + 'filter_func, args', + [(ndimage.gaussian_filter, (1.0,)), # args = (sigma,) + (ndimage.uniform_filter, (3,)), # args = (size,) + (ndimage.minimum_filter, (3,)), # args = (size,) + (ndimage.maximum_filter, (3,)), # args = (size,) + (ndimage.median_filter, (3,)), # args = (size,) + (ndimage.rank_filter, (2, 3)), # args = (rank, size) + (ndimage.percentile_filter, (30, 3))]) # args = (percentile, size) + @pytest.mark.parametrize( + 'axes', [(1.5,), (0, 1, 2, 3), (3,), (-4,)] + ) + def test_filter_invalid_axes(self, filter_func, args, axes): + array = numpy.arange(6 * 8 * 12, dtype=numpy.float64).reshape(6, 8, 12) + if any(isinstance(ax, float) for ax in axes): + error_class = TypeError + match = "cannot be interpreted as an integer" + else: + error_class = ValueError + match = "out of range" + with pytest.raises(error_class, match=match): + filter_func(array, *args, axes=axes) + + @pytest.mark.parametrize( + 'filter_func, kwargs', + [(ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, dict(rank=3)), + (ndimage.percentile_filter, dict(percentile=30))]) + @pytest.mark.parametrize( + 'axes', [(0, ), (1, 2), (0, 1, 2)] + ) + @pytest.mark.parametrize('separable_footprint', [False, True]) + def test_filter_invalid_footprint_ndim(self, filter_func, kwargs, axes, + separable_footprint): + array = numpy.arange(6 * 8 * 12, dtype=numpy.float64).reshape(6, 8, 12) + # create a footprint with one too many dimensions + footprint = numpy.ones((3,) * (len(axes) + 1)) + if not separable_footprint: + footprint[(0,) * footprint.ndim] = 0 + if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter] + and separable_footprint): + match = "sequence argument must have length equal to input rank" + else: + match = "footprint array has incorrect shape" + with pytest.raises(RuntimeError, match=match): + filter_func(array, **kwargs, footprint=footprint, axes=axes) + + @pytest.mark.parametrize('n_mismatch', [1, 3]) + @pytest.mark.parametrize('filter_func, kwargs, key, val', + _cases_axes_tuple_length_mismatch()) + def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func, + kwargs, key, val): + # Test for the intended RuntimeError when a kwargs has an invalid size + array = numpy.arange(6 * 8 * 12, dtype=numpy.float64).reshape(6, 8, 12) + kwargs = dict(**kwargs, axes=(0, 1)) + kwargs[key] = (val,) * n_mismatch + err_msg = "sequence argument must have length equal to input rank" + with pytest.raises(RuntimeError, match=err_msg): + filter_func(array, **kwargs) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt01(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) + t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 1) + output = ndimage.prewitt(array, 0) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt02(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) + t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 1) + output = numpy.zeros(array.shape, dtype) + ndimage.prewitt(array, 0, output) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt03(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 1) + t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 0) + output = ndimage.prewitt(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt04(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.prewitt(array, -1) + output = ndimage.prewitt(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel01(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) + t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 1) + output = ndimage.sobel(array, 0) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel02(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) + t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 1) + output = numpy.zeros(array.shape, dtype) + ndimage.sobel(array, 0, output) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel03(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 1) + t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 0) + output = numpy.zeros(array.shape, dtype) + output = ndimage.sobel(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel04(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.sobel(array, -1) + output = ndimage.sobel(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', + [numpy.int32, numpy.float32, numpy.float64, + numpy.complex64, numpy.complex128]) + def test_laplace01(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.correlate1d(array, [1, -2, 1], 0) + tmp2 = ndimage.correlate1d(array, [1, -2, 1], 1) + output = ndimage.laplace(array) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', + [numpy.int32, numpy.float32, numpy.float64, + numpy.complex64, numpy.complex128]) + def test_laplace02(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.correlate1d(array, [1, -2, 1], 0) + tmp2 = ndimage.correlate1d(array, [1, -2, 1], 1) + output = numpy.zeros(array.shape, dtype) + ndimage.laplace(array, output=output) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', + [numpy.int32, numpy.float32, numpy.float64, + numpy.complex64, numpy.complex128]) + def test_gaussian_laplace01(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) + output = ndimage.gaussian_laplace(array, 1.0) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', + [numpy.int32, numpy.float32, numpy.float64, + numpy.complex64, numpy.complex128]) + def test_gaussian_laplace02(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) + output = numpy.zeros(array.shape, dtype) + ndimage.gaussian_laplace(array, 1.0, output) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_generic_laplace01(self, dtype): + def derivative2(input, axis, output, mode, cval, a, b): + sigma = [a, b / 2.0] + input = numpy.asarray(input) + order = [0] * input.ndim + order[axis] = 2 + return ndimage.gaussian_filter(input, sigma, order, + output, mode, cval) + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = numpy.zeros(array.shape, dtype) + tmp = ndimage.generic_laplace(array, derivative2, + extra_arguments=(1.0,), + extra_keywords={'b': 2.0}) + ndimage.gaussian_laplace(array, 1.0, output) + assert_array_almost_equal(tmp, output) + + @pytest.mark.parametrize('dtype', + [numpy.int32, numpy.float32, numpy.float64, + numpy.complex64, numpy.complex128]) + def test_gaussian_gradient_magnitude01(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) + output = ndimage.gaussian_gradient_magnitude(array, 1.0) + expected = tmp1 * tmp1 + tmp2 * tmp2 + expected = numpy.sqrt(expected).astype(dtype) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', + [numpy.int32, numpy.float32, numpy.float64, + numpy.complex64, numpy.complex128]) + def test_gaussian_gradient_magnitude02(self, dtype): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) + output = numpy.zeros(array.shape, dtype) + ndimage.gaussian_gradient_magnitude(array, 1.0, output) + expected = tmp1 * tmp1 + tmp2 * tmp2 + expected = numpy.sqrt(expected).astype(dtype) + assert_array_almost_equal(expected, output) + + def test_generic_gradient_magnitude01(self): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], numpy.float64) + + def derivative(input, axis, output, mode, cval, a, b): + sigma = [a, b / 2.0] + input = numpy.asarray(input) + order = [0] * input.ndim + order[axis] = 1 + return ndimage.gaussian_filter(input, sigma, order, + output, mode, cval) + tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0) + tmp2 = ndimage.generic_gradient_magnitude( + array, derivative, extra_arguments=(1.0,), + extra_keywords={'b': 2.0}) + assert_array_almost_equal(tmp1, tmp2) + + def test_uniform01(self): + array = numpy.array([2, 4, 6]) + size = 2 + output = ndimage.uniform_filter1d(array, size, origin=-1) + assert_array_almost_equal([3, 5, 6], output) + + def test_uniform01_complex(self): + array = numpy.array([2 + 1j, 4 + 2j, 6 + 3j], dtype=numpy.complex128) + size = 2 + output = ndimage.uniform_filter1d(array, size, origin=-1) + assert_array_almost_equal([3, 5, 6], output.real) + assert_array_almost_equal([1.5, 2.5, 3], output.imag) + + def test_uniform02(self): + array = numpy.array([1, 2, 3]) + filter_shape = [0] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(array, output) + + def test_uniform03(self): + array = numpy.array([1, 2, 3]) + filter_shape = [1] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(array, output) + + def test_uniform04(self): + array = numpy.array([2, 4, 6]) + filter_shape = [2] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal([2, 3, 5], output) + + def test_uniform05(self): + array = [] + filter_shape = [1] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal([], output) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_uniform06(self, dtype_array, dtype_output): + filter_shape = [2, 2] + array = numpy.array([[4, 8, 12], + [16, 20, 24]], dtype_array) + output = ndimage.uniform_filter( + array, filter_shape, output=dtype_output) + assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output) + assert_equal(output.dtype.type, dtype_output) + + @pytest.mark.parametrize('dtype_array', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_uniform06_complex(self, dtype_array, dtype_output): + filter_shape = [2, 2] + array = numpy.array([[4, 8 + 5j, 12], + [16, 20, 24]], dtype_array) + output = ndimage.uniform_filter( + array, filter_shape, output=dtype_output) + assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output.real) + assert_equal(output.dtype.type, dtype_output) + + def test_minimum_filter01(self): + array = numpy.array([1, 2, 3, 4, 5]) + filter_shape = numpy.array([2]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([1, 1, 2, 3, 4], output) + + def test_minimum_filter02(self): + array = numpy.array([1, 2, 3, 4, 5]) + filter_shape = numpy.array([3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([1, 1, 2, 3, 4], output) + + def test_minimum_filter03(self): + array = numpy.array([3, 2, 5, 1, 4]) + filter_shape = numpy.array([2]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([3, 2, 2, 1, 1], output) + + def test_minimum_filter04(self): + array = numpy.array([3, 2, 5, 1, 4]) + filter_shape = numpy.array([3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([2, 2, 1, 1, 1], output) + + def test_minimum_filter05(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = numpy.array([2, 3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]], output) + + def test_minimum_filter05_overlap(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = numpy.array([2, 3]) + ndimage.minimum_filter(array, filter_shape, output=array) + assert_array_almost_equal([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]], array) + + def test_minimum_filter06(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 1, 1], [1, 1, 1]] + output = ndimage.minimum_filter(array, footprint=footprint) + assert_array_almost_equal([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]], output) + # separable footprint should allow mode sequence + output2 = ndimage.minimum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + assert_array_almost_equal(output2, output) + + def test_minimum_filter07(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.minimum_filter(array, footprint=footprint) + assert_array_almost_equal([[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]], output) + with assert_raises(RuntimeError): + ndimage.minimum_filter(array, footprint=footprint, + mode=['reflect', 'constant']) + + def test_minimum_filter08(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.minimum_filter(array, footprint=footprint, origin=-1) + assert_array_almost_equal([[3, 1, 3, 1, 1], + [5, 3, 3, 1, 1], + [3, 3, 1, 1, 1]], output) + + def test_minimum_filter09(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.minimum_filter(array, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal([[2, 3, 1, 3, 1], + [5, 5, 3, 3, 1], + [5, 3, 3, 1, 1]], output) + + def test_maximum_filter01(self): + array = numpy.array([1, 2, 3, 4, 5]) + filter_shape = numpy.array([2]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([1, 2, 3, 4, 5], output) + + def test_maximum_filter02(self): + array = numpy.array([1, 2, 3, 4, 5]) + filter_shape = numpy.array([3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([2, 3, 4, 5, 5], output) + + def test_maximum_filter03(self): + array = numpy.array([3, 2, 5, 1, 4]) + filter_shape = numpy.array([2]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([3, 3, 5, 5, 4], output) + + def test_maximum_filter04(self): + array = numpy.array([3, 2, 5, 1, 4]) + filter_shape = numpy.array([3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([3, 5, 5, 5, 4], output) + + def test_maximum_filter05(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = numpy.array([2, 3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([[3, 5, 5, 5, 4], + [7, 9, 9, 9, 5], + [8, 9, 9, 9, 7]], output) + + def test_maximum_filter06(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 1, 1], [1, 1, 1]] + output = ndimage.maximum_filter(array, footprint=footprint) + assert_array_almost_equal([[3, 5, 5, 5, 4], + [7, 9, 9, 9, 5], + [8, 9, 9, 9, 7]], output) + # separable footprint should allow mode sequence + output2 = ndimage.maximum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + assert_array_almost_equal(output2, output) + + def test_maximum_filter07(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.maximum_filter(array, footprint=footprint) + assert_array_almost_equal([[3, 5, 5, 5, 4], + [7, 7, 9, 9, 5], + [7, 9, 8, 9, 7]], output) + # non-separable footprint should not allow mode sequence + with assert_raises(RuntimeError): + ndimage.maximum_filter(array, footprint=footprint, + mode=['reflect', 'reflect']) + + def test_maximum_filter08(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.maximum_filter(array, footprint=footprint, origin=-1) + assert_array_almost_equal([[7, 9, 9, 5, 5], + [9, 8, 9, 7, 5], + [8, 8, 7, 7, 7]], output) + + def test_maximum_filter09(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.maximum_filter(array, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal([[7, 7, 9, 9, 5], + [7, 9, 8, 9, 7], + [8, 8, 8, 7, 7]], output) + + @pytest.mark.parametrize( + 'axes', tuple(itertools.combinations(range(-3, 3), 2)) + ) + @pytest.mark.parametrize( + 'filter_func, kwargs', + [(ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, dict(rank=3)), + (ndimage.percentile_filter, dict(percentile=60))] + ) + def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs): + array = numpy.arange(6 * 8 * 12, dtype=numpy.float32).reshape(6, 8, 12) + # use 2D triangular footprint because it is non-separable + footprint = numpy.tri(5) + axes = numpy.array(axes) + + if len(set(axes % array.ndim)) != len(axes): + # parametrized cases with duplicate axes raise an error + with pytest.raises(ValueError): + filter_func(array, footprint=footprint, axes=axes, **kwargs) + return + output = filter_func(array, footprint=footprint, axes=axes, **kwargs) + + missing_axis = tuple(set(range(3)) - set(axes % array.ndim))[0] + footprint_3d = numpy.expand_dims(footprint, missing_axis) + expected = filter_func(array, footprint=footprint_3d, **kwargs) + assert_allclose(output, expected) + + def test_rank01(self): + array = numpy.array([1, 2, 3, 4, 5]) + output = ndimage.rank_filter(array, 1, size=2) + assert_array_almost_equal(array, output) + output = ndimage.percentile_filter(array, 100, size=2) + assert_array_almost_equal(array, output) + output = ndimage.median_filter(array, 2) + assert_array_almost_equal(array, output) + + def test_rank02(self): + array = numpy.array([1, 2, 3, 4, 5]) + output = ndimage.rank_filter(array, 1, size=[3]) + assert_array_almost_equal(array, output) + output = ndimage.percentile_filter(array, 50, size=3) + assert_array_almost_equal(array, output) + output = ndimage.median_filter(array, (3,)) + assert_array_almost_equal(array, output) + + def test_rank03(self): + array = numpy.array([3, 2, 5, 1, 4]) + output = ndimage.rank_filter(array, 1, size=[2]) + assert_array_almost_equal([3, 3, 5, 5, 4], output) + output = ndimage.percentile_filter(array, 100, size=2) + assert_array_almost_equal([3, 3, 5, 5, 4], output) + + def test_rank04(self): + array = numpy.array([3, 2, 5, 1, 4]) + expected = [3, 3, 2, 4, 4] + output = ndimage.rank_filter(array, 1, size=3) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 50, size=3) + assert_array_almost_equal(expected, output) + output = ndimage.median_filter(array, size=3) + assert_array_almost_equal(expected, output) + + def test_rank05(self): + array = numpy.array([3, 2, 5, 1, 4]) + expected = [3, 3, 2, 4, 4] + output = ndimage.rank_filter(array, -2, size=3) + assert_array_almost_equal(expected, output) + + def test_rank06(self): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[2, 2, 1, 1, 1], + [3, 3, 2, 1, 1], + [5, 5, 3, 3, 1]] + output = ndimage.rank_filter(array, 1, size=[2, 3]) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 17, size=(2, 3)) + assert_array_almost_equal(expected, output) + + def test_rank06_overlap(self): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + array_copy = array.copy() + expected = [[2, 2, 1, 1, 1], + [3, 3, 2, 1, 1], + [5, 5, 3, 3, 1]] + ndimage.rank_filter(array, 1, size=[2, 3], output=array) + assert_array_almost_equal(expected, array) + + ndimage.percentile_filter(array_copy, 17, size=(2, 3), + output=array_copy) + assert_array_almost_equal(expected, array_copy) + + def test_rank07(self): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[3, 5, 5, 5, 4], + [5, 5, 7, 5, 4], + [6, 8, 8, 7, 5]] + output = ndimage.rank_filter(array, -2, size=[2, 3]) + assert_array_almost_equal(expected, output) + + def test_rank08(self): + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + expected = [[3, 3, 2, 4, 4], + [5, 5, 5, 4, 4], + [5, 6, 7, 5, 5]] + output = ndimage.percentile_filter(array, 50.0, size=(2, 3)) + assert_array_almost_equal(expected, output) + output = ndimage.rank_filter(array, 3, size=(2, 3)) + assert_array_almost_equal(expected, output) + output = ndimage.median_filter(array, size=(2, 3)) + assert_array_almost_equal(expected, output) + + # non-separable: does not allow mode sequence + with assert_raises(RuntimeError): + ndimage.percentile_filter(array, 50.0, size=(2, 3), + mode=['reflect', 'constant']) + with assert_raises(RuntimeError): + ndimage.rank_filter(array, 3, size=(2, 3), mode=['reflect']*2) + with assert_raises(RuntimeError): + ndimage.median_filter(array, size=(2, 3), mode=['reflect']*2) + + @pytest.mark.parametrize('dtype', types) + def test_rank09(self, dtype): + expected = [[3, 3, 2, 4, 4], + [3, 5, 2, 5, 1], + [5, 5, 8, 3, 5]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 35, footprint=footprint) + assert_array_almost_equal(expected, output) + + def test_rank10(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + expected = [[2, 2, 1, 1, 1], + [2, 3, 1, 3, 1], + [5, 5, 3, 3, 1]] + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.rank_filter(array, 0, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 0.0, footprint=footprint) + assert_array_almost_equal(expected, output) + + def test_rank11(self): + array = numpy.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + expected = [[3, 5, 5, 5, 4], + [7, 7, 9, 9, 5], + [7, 9, 8, 9, 7]] + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.rank_filter(array, -1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 100.0, footprint=footprint) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank12(self, dtype): + expected = [[3, 3, 2, 4, 4], + [3, 5, 2, 5, 1], + [5, 5, 8, 3, 5]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 50.0, + footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.median_filter(array, footprint=footprint) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank13(self, dtype): + expected = [[5, 2, 5, 1, 1], + [5, 8, 3, 5, 5], + [6, 6, 5, 5, 5]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint, + origin=-1) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank14(self, dtype): + expected = [[3, 5, 2, 5, 1], + [5, 5, 8, 3, 5], + [5, 6, 6, 5, 5]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank15(self, dtype): + expected = [[2, 3, 1, 4, 1], + [5, 3, 7, 1, 1], + [5, 5, 3, 3, 3]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = numpy.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 0, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_generic_filter1d01(self, dtype): + weights = numpy.array([1.1, 2.2, 3.3]) + + def _filter_func(input, output, fltr, total): + fltr = fltr / total + for ii in range(input.shape[0] - 2): + output[ii] = input[ii] * fltr[0] + output[ii] += input[ii + 1] * fltr[1] + output[ii] += input[ii + 2] * fltr[2] + a = numpy.arange(12, dtype=dtype) + a.shape = (3, 4) + r1 = ndimage.correlate1d(a, weights / weights.sum(), 0, origin=-1) + r2 = ndimage.generic_filter1d( + a, _filter_func, 3, axis=0, origin=-1, + extra_arguments=(weights,), + extra_keywords={'total': weights.sum()}) + assert_array_almost_equal(r1, r2) + + @pytest.mark.parametrize('dtype', types) + def test_generic_filter01(self, dtype): + filter_ = numpy.array([[1.0, 2.0], [3.0, 4.0]]) + footprint = numpy.array([[1, 0], [0, 1]]) + cf = numpy.array([1., 4.]) + + def _filter_func(buffer, weights, total=1.0): + weights = cf / total + return (buffer * weights).sum() + + a = numpy.arange(12, dtype=dtype) + a.shape = (3, 4) + r1 = ndimage.correlate(a, filter_ * footprint) + if dtype in float_types: + r1 /= 5 + else: + r1 //= 5 + r2 = ndimage.generic_filter( + a, _filter_func, footprint=footprint, extra_arguments=(cf,), + extra_keywords={'total': cf.sum()}) + assert_array_almost_equal(r1, r2) + + # generic_filter doesn't allow mode sequence + with assert_raises(RuntimeError): + r2 = ndimage.generic_filter( + a, _filter_func, mode=['reflect', 'reflect'], + footprint=footprint, extra_arguments=(cf,), + extra_keywords={'total': cf.sum()}) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 2]), + ('wrap', [3, 1, 2]), + ('reflect', [1, 1, 2]), + ('mirror', [2, 1, 2]), + ('constant', [0, 1, 2])] + ) + def test_extend01(self, mode, expected_value): + array = numpy.array([1, 2, 3]) + weights = numpy.array([1, 0]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 1]), + ('wrap', [3, 1, 2]), + ('reflect', [3, 3, 2]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend02(self, mode, expected_value): + array = numpy.array([1, 2, 3]) + weights = numpy.array([1, 0, 0, 0, 0, 0, 0, 0]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [2, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 3, 3]), + ('mirror', [2, 3, 2]), + ('constant', [2, 3, 0])] + ) + def test_extend03(self, mode, expected_value): + array = numpy.array([1, 2, 3]) + weights = numpy.array([0, 0, 1]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend04(self, mode, expected_value): + array = numpy.array([1, 2, 3]) + weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]), + ('wrap', [[9, 7, 8], [3, 1, 2], [6, 4, 5]]), + ('reflect', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]), + ('mirror', [[5, 4, 5], [2, 1, 2], [5, 4, 5]]), + ('constant', [[0, 0, 0], [0, 1, 2], [0, 4, 5]])] + ) + def test_extend05(self, mode, expected_value): + array = numpy.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + weights = numpy.array([[1, 0], [0, 0]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]), + ('wrap', [[5, 6, 4], [8, 9, 7], [2, 3, 1]]), + ('reflect', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]), + ('mirror', [[5, 6, 5], [8, 9, 8], [5, 6, 5]]), + ('constant', [[5, 6, 0], [8, 9, 0], [0, 0, 0]])] + ) + def test_extend06(self, mode, expected_value): + array = numpy.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + weights = numpy.array([[0, 0, 0], [0, 0, 0], [0, 0, 1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend07(self, mode, expected_value): + array = numpy.array([1, 2, 3]) + weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[3], [3], [3]]), + ('wrap', [[2], [3], [1]]), + ('reflect', [[2], [1], [1]]), + ('mirror', [[1], [2], [3]]), + ('constant', [[0], [0], [0]])] + ) + def test_extend08(self, mode, expected_value): + array = numpy.array([[1], [2], [3]]) + weights = numpy.array([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [3, 3, 3]), + ('wrap', [2, 3, 1]), + ('reflect', [2, 1, 1]), + ('mirror', [1, 2, 3]), + ('constant', [0, 0, 0])] + ) + def test_extend09(self, mode, expected_value): + array = numpy.array([1, 2, 3]) + weights = numpy.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [[3], [3], [3]]), + ('wrap', [[2], [3], [1]]), + ('reflect', [[2], [1], [1]]), + ('mirror', [[1], [2], [3]]), + ('constant', [[0], [0], [0]])] + ) + def test_extend10(self, mode, expected_value): + array = numpy.array([[1], [2], [3]]) + weights = numpy.array([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + +def test_ticket_701(): + # Test generic filter sizes + arr = numpy.arange(4).reshape((2, 2)) + def func(x): + return numpy.min(x) + res = ndimage.generic_filter(arr, func, size=(1, 1)) + # The following raises an error unless ticket 701 is fixed + res2 = ndimage.generic_filter(arr, func, size=1) + assert_equal(res, res2) + + +def test_gh_5430(): + # At least one of these raises an error unless gh-5430 is + # fixed. In py2k an int is implemented using a C long, so + # which one fails depends on your system. In py3k there is only + # one arbitrary precision integer type, so both should fail. + sigma = numpy.int32(1) + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert_equal(out, [sigma]) + sigma = numpy.int64(1) + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert_equal(out, [sigma]) + # This worked before; make sure it still works + sigma = 1 + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert_equal(out, [sigma]) + # This worked before; make sure it still works + sigma = [1, 1] + out = ndimage._ni_support._normalize_sequence(sigma, 2) + assert_equal(out, sigma) + # Also include the OPs original example to make sure we fixed the issue + x = numpy.random.normal(size=(256, 256)) + perlin = numpy.zeros_like(x) + for i in 2**numpy.arange(6): + perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2 + # This also fixes gh-4106, show that the OPs example now runs. + x = numpy.int64(21) + ndimage._ni_support._normalize_sequence(x, 0) + + +def test_gaussian_kernel1d(): + radius = 10 + sigma = 2 + sigma2 = sigma * sigma + x = numpy.arange(-radius, radius + 1, dtype=numpy.double) + phi_x = numpy.exp(-0.5 * x * x / sigma2) + phi_x /= phi_x.sum() + assert_allclose(phi_x, _gaussian_kernel1d(sigma, 0, radius)) + assert_allclose(-phi_x * x / sigma2, _gaussian_kernel1d(sigma, 1, radius)) + assert_allclose(phi_x * (x * x / sigma2 - 1) / sigma2, + _gaussian_kernel1d(sigma, 2, radius)) + assert_allclose(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2), + _gaussian_kernel1d(sigma, 3, radius)) + + +def test_orders_gauss(): + # Check order inputs to Gaussians + arr = numpy.zeros((1,)) + assert_equal(0, ndimage.gaussian_filter(arr, 1, order=0)) + assert_equal(0, ndimage.gaussian_filter(arr, 1, order=3)) + assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1) + assert_equal(0, ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0)) + assert_equal(0, ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3)) + assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1) + + +def test_valid_origins(): + """Regression test for #1311.""" + def func(x): + return numpy.mean(x) + data = numpy.array([1, 2, 3, 4, 5], dtype=numpy.float64) + assert_raises(ValueError, ndimage.generic_filter, data, func, size=3, + origin=2) + assert_raises(ValueError, ndimage.generic_filter1d, data, func, + filter_size=3, origin=2) + assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3, + origin=2) + + for filter in [ndimage.uniform_filter, ndimage.minimum_filter, + ndimage.maximum_filter, ndimage.maximum_filter1d, + ndimage.median_filter, ndimage.minimum_filter1d]: + # This should work, since for size == 3, the valid range for origin is + # -1 to 1. + list(filter(data, 3, origin=-1)) + list(filter(data, 3, origin=1)) + # Just check this raises an error instead of silently accepting or + # segfaulting. + assert_raises(ValueError, filter, data, 3, origin=2) + + +def test_bad_convolve_and_correlate_origins(): + """Regression test for gh-822.""" + # Before gh-822 was fixed, these would generate seg. faults or + # other crashes on many system. + assert_raises(ValueError, ndimage.correlate1d, + [0, 1, 2, 3, 4, 5], [1, 1, 2, 0], origin=2) + assert_raises(ValueError, ndimage.correlate, + [0, 1, 2, 3, 4, 5], [0, 1, 2], origin=[2]) + assert_raises(ValueError, ndimage.correlate, + numpy.ones((3, 5)), numpy.ones((2, 2)), origin=[0, 1]) + + assert_raises(ValueError, ndimage.convolve1d, + numpy.arange(10), numpy.ones(3), origin=-2) + assert_raises(ValueError, ndimage.convolve, + numpy.arange(10), numpy.ones(3), origin=[-2]) + assert_raises(ValueError, ndimage.convolve, + numpy.ones((3, 5)), numpy.ones((2, 2)), origin=[0, -2]) + + +def test_multiple_modes(): + # Test that the filters with multiple mode cababilities for different + # dimensions give the same result as applying a single mode. + arr = numpy.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + mode1 = 'reflect' + mode2 = ['reflect', 'reflect'] + + assert_equal(ndimage.gaussian_filter(arr, 1, mode=mode1), + ndimage.gaussian_filter(arr, 1, mode=mode2)) + assert_equal(ndimage.prewitt(arr, mode=mode1), + ndimage.prewitt(arr, mode=mode2)) + assert_equal(ndimage.sobel(arr, mode=mode1), + ndimage.sobel(arr, mode=mode2)) + assert_equal(ndimage.laplace(arr, mode=mode1), + ndimage.laplace(arr, mode=mode2)) + assert_equal(ndimage.gaussian_laplace(arr, 1, mode=mode1), + ndimage.gaussian_laplace(arr, 1, mode=mode2)) + assert_equal(ndimage.maximum_filter(arr, size=5, mode=mode1), + ndimage.maximum_filter(arr, size=5, mode=mode2)) + assert_equal(ndimage.minimum_filter(arr, size=5, mode=mode1), + ndimage.minimum_filter(arr, size=5, mode=mode2)) + assert_equal(ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode1), + ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode2)) + assert_equal(ndimage.uniform_filter(arr, 5, mode=mode1), + ndimage.uniform_filter(arr, 5, mode=mode2)) + + +def test_multiple_modes_sequentially(): + # Test that the filters with multiple mode cababilities for different + # dimensions give the same result as applying the filters with + # different modes sequentially + arr = numpy.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + modes = ['reflect', 'wrap'] + + expected = ndimage.gaussian_filter1d(arr, 1, axis=0, mode=modes[0]) + expected = ndimage.gaussian_filter1d(expected, 1, axis=1, mode=modes[1]) + assert_equal(expected, + ndimage.gaussian_filter(arr, 1, mode=modes)) + + expected = ndimage.uniform_filter1d(arr, 5, axis=0, mode=modes[0]) + expected = ndimage.uniform_filter1d(expected, 5, axis=1, mode=modes[1]) + assert_equal(expected, + ndimage.uniform_filter(arr, 5, mode=modes)) + + expected = ndimage.maximum_filter1d(arr, size=5, axis=0, mode=modes[0]) + expected = ndimage.maximum_filter1d(expected, size=5, axis=1, + mode=modes[1]) + assert_equal(expected, + ndimage.maximum_filter(arr, size=5, mode=modes)) + + expected = ndimage.minimum_filter1d(arr, size=5, axis=0, mode=modes[0]) + expected = ndimage.minimum_filter1d(expected, size=5, axis=1, + mode=modes[1]) + assert_equal(expected, + ndimage.minimum_filter(arr, size=5, mode=modes)) + + +def test_multiple_modes_prewitt(): + # Test prewitt filter for multiple extrapolation modes + arr = numpy.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = numpy.array([[1., -3., 2.], + [1., -2., 1.], + [1., -1., 0.]]) + + modes = ['reflect', 'wrap'] + + assert_equal(expected, + ndimage.prewitt(arr, mode=modes)) + + +def test_multiple_modes_sobel(): + # Test sobel filter for multiple extrapolation modes + arr = numpy.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = numpy.array([[1., -4., 3.], + [2., -3., 1.], + [1., -1., 0.]]) + + modes = ['reflect', 'wrap'] + + assert_equal(expected, + ndimage.sobel(arr, mode=modes)) + + +def test_multiple_modes_laplace(): + # Test laplace filter for multiple extrapolation modes + arr = numpy.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = numpy.array([[-2., 2., 1.], + [-2., -3., 2.], + [1., 1., 0.]]) + + modes = ['reflect', 'wrap'] + + assert_equal(expected, + ndimage.laplace(arr, mode=modes)) + + +def test_multiple_modes_gaussian_laplace(): + # Test gaussian_laplace filter for multiple extrapolation modes + arr = numpy.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = numpy.array([[-0.28438687, 0.01559809, 0.19773499], + [-0.36630503, -0.20069774, 0.07483620], + [0.15849176, 0.18495566, 0.21934094]]) + + modes = ['reflect', 'wrap'] + + assert_almost_equal(expected, + ndimage.gaussian_laplace(arr, 1, mode=modes)) + + +def test_multiple_modes_gaussian_gradient_magnitude(): + # Test gaussian_gradient_magnitude filter for multiple + # extrapolation modes + arr = numpy.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = numpy.array([[0.04928965, 0.09745625, 0.06405368], + [0.23056905, 0.14025305, 0.04550846], + [0.19894369, 0.14950060, 0.06796850]]) + + modes = ['reflect', 'wrap'] + + calculated = ndimage.gaussian_gradient_magnitude(arr, 1, mode=modes) + + assert_almost_equal(expected, calculated) + + +def test_multiple_modes_uniform(): + # Test uniform filter for multiple extrapolation modes + arr = numpy.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = numpy.array([[0.32, 0.40, 0.48], + [0.20, 0.28, 0.32], + [0.28, 0.32, 0.40]]) + + modes = ['reflect', 'wrap'] + + assert_almost_equal(expected, + ndimage.uniform_filter(arr, 5, mode=modes)) + + +def test_gaussian_truncate(): + # Test that Gaussian filters can be truncated at different widths. + # These tests only check that the result has the expected number + # of nonzero elements. + arr = numpy.zeros((100, 100), float) + arr[50, 50] = 1 + num_nonzeros_2 = (ndimage.gaussian_filter(arr, 5, truncate=2) > 0).sum() + assert_equal(num_nonzeros_2, 21**2) + num_nonzeros_5 = (ndimage.gaussian_filter(arr, 5, truncate=5) > 0).sum() + assert_equal(num_nonzeros_5, 51**2) + + # Test truncate when sigma is a sequence. + f = ndimage.gaussian_filter(arr, [0.5, 2.5], truncate=3.5) + fpos = f > 0 + n0 = fpos.any(axis=0).sum() + # n0 should be 2*int(2.5*3.5 + 0.5) + 1 + assert_equal(n0, 19) + n1 = fpos.any(axis=1).sum() + # n1 should be 2*int(0.5*3.5 + 0.5) + 1 + assert_equal(n1, 5) + + # Test gaussian_filter1d. + x = numpy.zeros(51) + x[25] = 1 + f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5) + n = (f > 0).sum() + assert_equal(n, 15) + + # Test gaussian_laplace + y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5) + nonzero_indices = numpy.nonzero(y != 0)[0] + n = numpy.ptp(nonzero_indices) + 1 + assert_equal(n, 15) + + # Test gaussian_gradient_magnitude + y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5) + nonzero_indices = numpy.nonzero(y != 0)[0] + n = numpy.ptp(nonzero_indices) + 1 + assert_equal(n, 15) + + +def test_gaussian_radius(): + # Test that Gaussian filters with radius argument produce the same + # results as the filters with corresponding truncate argument. + # radius = int(truncate * sigma + 0.5) + # Test gaussian_filter1d + x = numpy.zeros(7) + x[3] = 1 + f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5) + f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3) + assert_equal(f1, f2) + + # Test gaussian_filter when sigma is a number. + a = numpy.zeros((9, 9)) + a[4, 4] = 1 + f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5) + f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2) + assert_equal(f1, f2) + + # Test gaussian_filter when sigma is a sequence. + a = numpy.zeros((50, 50)) + a[25, 25] = 1 + f1 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], truncate=3.5) + f2 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], radius=[2, 9]) + assert_equal(f1, f2) + + +def test_gaussian_radius_invalid(): + # radius must be a nonnegative integer + with assert_raises(ValueError): + ndimage.gaussian_filter1d(numpy.zeros(8), sigma=1, radius=-1) + with assert_raises(ValueError): + ndimage.gaussian_filter1d(numpy.zeros(8), sigma=1, radius=1.1) + + +class TestThreading: + def check_func_thread(self, n, fun, args, out): + from threading import Thread + thrds = [Thread(target=fun, args=args, kwargs={'output': out[x]}) + for x in range(n)] + [t.start() for t in thrds] + [t.join() for t in thrds] + + def check_func_serial(self, n, fun, args, out): + for i in range(n): + fun(*args, output=out[i]) + + def test_correlate1d(self): + d = numpy.random.randn(5000) + os = numpy.empty((4, d.size)) + ot = numpy.empty_like(os) + k = numpy.arange(5) + self.check_func_serial(4, ndimage.correlate1d, (d, k), os) + self.check_func_thread(4, ndimage.correlate1d, (d, k), ot) + assert_array_equal(os, ot) + + def test_correlate(self): + d = numpy.random.randn(500, 500) + k = numpy.random.randn(10, 10) + os = numpy.empty([4] + list(d.shape)) + ot = numpy.empty_like(os) + self.check_func_serial(4, ndimage.correlate, (d, k), os) + self.check_func_thread(4, ndimage.correlate, (d, k), ot) + assert_array_equal(os, ot) + + def test_median_filter(self): + d = numpy.random.randn(500, 500) + os = numpy.empty([4] + list(d.shape)) + ot = numpy.empty_like(os) + self.check_func_serial(4, ndimage.median_filter, (d, 3), os) + self.check_func_thread(4, ndimage.median_filter, (d, 3), ot) + assert_array_equal(os, ot) + + def test_uniform_filter1d(self): + d = numpy.random.randn(5000) + os = numpy.empty((4, d.size)) + ot = numpy.empty_like(os) + self.check_func_serial(4, ndimage.uniform_filter1d, (d, 5), os) + self.check_func_thread(4, ndimage.uniform_filter1d, (d, 5), ot) + assert_array_equal(os, ot) + + def test_minmax_filter(self): + d = numpy.random.randn(500, 500) + os = numpy.empty([4] + list(d.shape)) + ot = numpy.empty_like(os) + self.check_func_serial(4, ndimage.maximum_filter, (d, 3), os) + self.check_func_thread(4, ndimage.maximum_filter, (d, 3), ot) + assert_array_equal(os, ot) + self.check_func_serial(4, ndimage.minimum_filter, (d, 3), os) + self.check_func_thread(4, ndimage.minimum_filter, (d, 3), ot) + assert_array_equal(os, ot) + + +def test_minmaximum_filter1d(): + # Regression gh-3898 + in_ = numpy.arange(10) + out = ndimage.minimum_filter1d(in_, 1) + assert_equal(in_, out) + out = ndimage.maximum_filter1d(in_, 1) + assert_equal(in_, out) + # Test reflect + out = ndimage.minimum_filter1d(in_, 5, mode='reflect') + assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 6, 7], out) + out = ndimage.maximum_filter1d(in_, 5, mode='reflect') + assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 9, 9], out) + # Test constant + out = ndimage.minimum_filter1d(in_, 5, mode='constant', cval=-1) + assert_equal([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1], out) + out = ndimage.maximum_filter1d(in_, 5, mode='constant', cval=10) + assert_equal([10, 10, 4, 5, 6, 7, 8, 9, 10, 10], out) + # Test nearest + out = ndimage.minimum_filter1d(in_, 5, mode='nearest') + assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 6, 7], out) + out = ndimage.maximum_filter1d(in_, 5, mode='nearest') + assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 9, 9], out) + # Test wrap + out = ndimage.minimum_filter1d(in_, 5, mode='wrap') + assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 0, 0], out) + out = ndimage.maximum_filter1d(in_, 5, mode='wrap') + assert_equal([9, 9, 4, 5, 6, 7, 8, 9, 9, 9], out) + + +def test_uniform_filter1d_roundoff_errors(): + # gh-6930 + in_ = numpy.repeat([0, 1, 0], [9, 9, 9]) + for filter_size in range(3, 10): + out = ndimage.uniform_filter1d(in_, filter_size) + assert_equal(out.sum(), 10 - filter_size) + + +def test_footprint_all_zeros(): + # regression test for gh-6876: footprint of all zeros segfaults + arr = numpy.random.randint(0, 100, (100, 100)) + kernel = numpy.zeros((3, 3), bool) + with assert_raises(ValueError): + ndimage.maximum_filter(arr, footprint=kernel) + + +def test_gaussian_filter(): + # Test gaussian filter with numpy.float16 + # gh-8207 + data = numpy.array([1], dtype=numpy.float16) + sigma = 1.0 + with assert_raises(RuntimeError): + ndimage.gaussian_filter(data, sigma) + + +def test_rank_filter_noninteger_rank(): + # regression test for issue 9388: ValueError for + # non integer rank when performing rank_filter + arr = numpy.random.random((10, 20, 30)) + assert_raises(TypeError, ndimage.rank_filter, arr, 0.5, + footprint=numpy.ones((1, 1, 10), dtype=bool)) + + +def test_size_footprint_both_set(): + # test for input validation, expect user warning when + # size and footprint is set + with suppress_warnings() as sup: + sup.filter(UserWarning, + "ignoring size because footprint is set") + arr = numpy.random.random((10, 20, 30)) + ndimage.rank_filter(arr, 5, size=2, footprint=numpy.ones((1, 1, 10), + dtype=bool)) + + +def test_byte_order_median(): + """Regression test for #413: median_filter does not handle bytes orders.""" + a = numpy.arange(9, dtype=' 3 raise NotImplementedError + x = numpy.ones((4, 6, 8, 10), dtype=numpy.complex128) + with pytest.raises(NotImplementedError): + ndimage.fourier_ellipsoid(x, 3) + + def test_fourier_ellipsoid_1d_complex(self): + # expected result of 1d ellipsoid is the same as for fourier_uniform + for shape in [(32, ), (31, )]: + for type_, dec in zip([numpy.complex64, numpy.complex128], + [5, 14]): + x = numpy.ones(shape, dtype=type_) + a = ndimage.fourier_ellipsoid(x, 5, -1, 0) + b = ndimage.fourier_uniform(x, 5, -1, 0) + assert_array_almost_equal(a, b, decimal=dec) + + @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)]) + @pytest.mark.parametrize('dtype', + [numpy.float32, numpy.float64, + numpy.complex64, numpy.complex128]) + @pytest.mark.parametrize('test_func', + [ndimage.fourier_ellipsoid, + ndimage.fourier_gaussian, + ndimage.fourier_uniform]) + def test_fourier_zero_length_dims(self, shape, dtype, test_func): + a = numpy.ones(shape, dtype) + b = test_func(a, 3) + assert_equal(a, b) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..beb8681e850bd682b789e97f901048d718627dd0 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_interpolation.py @@ -0,0 +1,1327 @@ +import sys + +import numpy +from numpy.testing import (assert_, assert_equal, assert_array_equal, + assert_array_almost_equal, assert_allclose, + suppress_warnings) +import pytest +from pytest import raises as assert_raises +import scipy.ndimage as ndimage + +from . import types + +eps = 1e-12 + +ndimage_to_numpy_mode = { + 'mirror': 'reflect', + 'reflect': 'symmetric', + 'grid-mirror': 'symmetric', + 'grid-wrap': 'wrap', + 'nearest': 'edge', + 'grid-constant': 'constant', +} + + +class TestNdimageInterpolation: + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]), + ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]), + ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]), + ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]), + ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]), + ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]), + ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])] + ) + def test_boundaries(self, mode, expected_value): + def shift(x): + return (x[0] + 0.5,) + + data = numpy.array([1, 2, 3, 4.]) + assert_array_equal( + expected_value, + ndimage.geometric_transform(data, shift, cval=-1, mode=mode, + output_shape=(7,), order=1)) + + @pytest.mark.parametrize( + 'mode, expected_value', + [('nearest', [1, 1, 2, 3]), + ('wrap', [3, 1, 2, 3]), + ('grid-wrap', [4, 1, 2, 3]), + ('mirror', [2, 1, 2, 3]), + ('reflect', [1, 1, 2, 3]), + ('constant', [-1, 1, 2, 3]), + ('grid-constant', [-1, 1, 2, 3])] + ) + def test_boundaries2(self, mode, expected_value): + def shift(x): + return (x[0] - 0.9,) + + data = numpy.array([1, 2, 3, 4]) + assert_array_equal( + expected_value, + ndimage.geometric_transform(data, shift, cval=-1, mode=mode, + output_shape=(4,))) + + @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror', + 'grid-wrap', 'grid-constant', + 'nearest']) + @pytest.mark.parametrize('order', range(6)) + def test_boundary_spline_accuracy(self, mode, order): + """Tests based on examples from gh-2640""" + data = numpy.arange(-6, 7, dtype=float) + x = numpy.linspace(-8, 15, num=1000) + y = ndimage.map_coordinates(data, [x], order=order, mode=mode) + + # compute expected value using explicit padding via numpy.pad + npad = 32 + pad_mode = ndimage_to_numpy_mode.get(mode) + padded = numpy.pad(data, npad, mode=pad_mode) + expected = ndimage.map_coordinates(padded, [npad + x], order=order, + mode=mode) + + atol = 1e-5 if mode == 'grid-constant' else 1e-12 + assert_allclose(y, expected, rtol=1e-7, atol=atol) + + @pytest.mark.parametrize('order', range(2, 6)) + @pytest.mark.parametrize('dtype', types) + def test_spline01(self, dtype, order): + data = numpy.ones([], dtype) + out = ndimage.spline_filter(data, order=order) + assert_array_almost_equal(out, 1) + + @pytest.mark.parametrize('order', range(2, 6)) + @pytest.mark.parametrize('dtype', types) + def test_spline02(self, dtype, order): + data = numpy.array([1], dtype) + out = ndimage.spline_filter(data, order=order) + assert_array_almost_equal(out, [1]) + + @pytest.mark.parametrize('order', range(2, 6)) + @pytest.mark.parametrize('dtype', types) + def test_spline03(self, dtype, order): + data = numpy.ones([], dtype) + out = ndimage.spline_filter(data, order, output=dtype) + assert_array_almost_equal(out, 1) + + @pytest.mark.parametrize('order', range(2, 6)) + @pytest.mark.parametrize('dtype', types) + def test_spline04(self, dtype, order): + data = numpy.ones([4], dtype) + out = ndimage.spline_filter(data, order) + assert_array_almost_equal(out, [1, 1, 1, 1]) + + @pytest.mark.parametrize('order', range(2, 6)) + @pytest.mark.parametrize('dtype', types) + def test_spline05(self, dtype, order): + data = numpy.ones([4, 4], dtype) + out = ndimage.spline_filter(data, order=order) + assert_array_almost_equal(out, [[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform01(self, order): + data = numpy.array([1]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, [1]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform02(self, order): + data = numpy.ones([4]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, [1, 1, 1, 1]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform03(self, order): + data = numpy.ones([4]) + + def mapping(x): + return (x[0] - 1,) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, [0, 1, 1, 1]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform04(self, order): + data = numpy.array([4, 1, 3, 2]) + + def mapping(x): + return (x[0] - 1,) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, [0, 4, 1, 3]) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', [numpy.float64, numpy.complex128]) + def test_geometric_transform05(self, order, dtype): + data = numpy.array([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = numpy.array([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + if data.dtype.kind == 'c': + data -= 1j * data + expected -= 1j * expected + + def mapping(x): + return (x[0], x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform06(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0], x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, [[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform07(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1]) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform08(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1] - 1) + + out = ndimage.geometric_transform(data, mapping, data.shape, + order=order) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform10(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + + def mapping(x): + return (x[0] - 1, x[1] - 1) + + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.geometric_transform(filtered, mapping, data.shape, + order=order, prefilter=False) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform13(self, order): + data = numpy.ones([2], numpy.float64) + + def mapping(x): + return (x[0] // 2,) + + out = ndimage.geometric_transform(data, mapping, [4], order=order) + assert_array_almost_equal(out, [1, 1, 1, 1]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform14(self, order): + data = [1, 5, 2, 6, 3, 7, 4, 4] + + def mapping(x): + return (2 * x[0],) + + out = ndimage.geometric_transform(data, mapping, [4], order=order) + assert_array_almost_equal(out, [1, 2, 3, 4]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform15(self, order): + data = [1, 2, 3, 4] + + def mapping(x): + return (x[0] / 2,) + + out = ndimage.geometric_transform(data, mapping, [8], order=order) + assert_array_almost_equal(out[::2], [1, 2, 3, 4]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform16(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9.0, 10, 11, 12]] + + def mapping(x): + return (x[0], x[1] * 2) + + out = ndimage.geometric_transform(data, mapping, (3, 2), + order=order) + assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform17(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0] * 2, x[1]) + + out = ndimage.geometric_transform(data, mapping, (1, 4), + order=order) + assert_array_almost_equal(out, [[1, 2, 3, 4]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform18(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0] * 2, x[1] * 2) + + out = ndimage.geometric_transform(data, mapping, (1, 2), + order=order) + assert_array_almost_equal(out, [[1, 3]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform19(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0], x[1] / 2) + + out = ndimage.geometric_transform(data, mapping, (3, 8), + order=order) + assert_array_almost_equal(out[..., ::2], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform20(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0] / 2, x[1]) + + out = ndimage.geometric_transform(data, mapping, (6, 4), + order=order) + assert_array_almost_equal(out[::2, ...], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform21(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (x[0] / 2, x[1] / 2) + + out = ndimage.geometric_transform(data, mapping, (6, 8), + order=order) + assert_array_almost_equal(out[::2, ::2], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform22(self, order): + data = numpy.array([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]], numpy.float64) + + def mapping1(x): + return (x[0] / 2, x[1] / 2) + + def mapping2(x): + return (x[0] * 2, x[1] * 2) + + out = ndimage.geometric_transform(data, mapping1, + (6, 8), order=order) + out = ndimage.geometric_transform(out, mapping2, + (3, 4), order=order) + assert_array_almost_equal(out, data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform23(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x): + return (1, x[0] * 2) + + out = ndimage.geometric_transform(data, mapping, (2,), order=order) + out = out.astype(numpy.int32) + assert_array_almost_equal(out, [5, 7]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_geometric_transform24(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + + def mapping(x, a, b): + return (a, x[0] * b) + + out = ndimage.geometric_transform( + data, mapping, (2,), order=order, extra_arguments=(1,), + extra_keywords={'b': 2}) + assert_array_almost_equal(out, [5, 7]) + + def test_geometric_transform_grid_constant_order1(self): + # verify interpolation outside the original bounds + x = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype=float) + + def mapping(x): + return (x[0] - 0.5), (x[1] - 0.5) + + expected_result = numpy.array([[0.25, 0.75, 1.25], + [1.25, 3.00, 4.00]]) + assert_array_almost_equal( + ndimage.geometric_transform(x, mapping, mode='grid-constant', + order=1), + expected_result, + ) + + @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest', + 'mirror', 'reflect']) + @pytest.mark.parametrize('order', range(6)) + def test_geometric_transform_vs_padded(self, order, mode): + x = numpy.arange(144, dtype=float).reshape(12, 12) + + def mapping(x): + return (x[0] - 0.4), (x[1] + 2.3) + + # Manually pad and then extract center after the transform to get the + # expected result. + npad = 24 + pad_mode = ndimage_to_numpy_mode.get(mode) + xp = numpy.pad(x, npad, mode=pad_mode) + center_slice = tuple([slice(npad, -npad)] * x.ndim) + expected_result = ndimage.geometric_transform( + xp, mapping, mode=mode, order=order)[center_slice] + + assert_allclose( + ndimage.geometric_transform(x, mapping, mode=mode, + order=order), + expected_result, + rtol=1e-7, + ) + + def test_geometric_transform_endianness_with_output_parameter(self): + # geometric transform given output ndarray or dtype with + # non-native endianness. see issue #4127 + data = numpy.array([1]) + + def mapping(x): + return x + + for out in [data.dtype, data.dtype.newbyteorder(), + numpy.empty_like(data), + numpy.empty_like(data).astype(data.dtype.newbyteorder())]: + returned = ndimage.geometric_transform(data, mapping, data.shape, + output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, [1]) + + def test_geometric_transform_with_string_output(self): + data = numpy.array([1]) + + def mapping(x): + return x + + out = ndimage.geometric_transform(data, mapping, output='f') + assert_(out.dtype is numpy.dtype('f')) + assert_array_almost_equal(out, [1]) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', [numpy.float64, numpy.complex128]) + def test_map_coordinates01(self, order, dtype): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + expected = numpy.array([[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + if data.dtype.kind == 'c': + data = data - 1j * data + expected = expected - 1j * expected + + idx = numpy.indices(data.shape) + idx -= 1 + + out = ndimage.map_coordinates(data, idx, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_map_coordinates02(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + idx = numpy.indices(data.shape, numpy.float64) + idx -= 0.5 + + out1 = ndimage.shift(data, 0.5, order=order) + out2 = ndimage.map_coordinates(data, idx, order=order) + assert_array_almost_equal(out1, out2) + + def test_map_coordinates03(self): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]], order='F') + idx = numpy.indices(data.shape) - 1 + out = ndimage.map_coordinates(data, idx) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + assert_array_almost_equal(out, ndimage.shift(data, (1, 1))) + idx = numpy.indices(data[::2].shape) - 1 + out = ndimage.map_coordinates(data[::2], idx) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3]]) + assert_array_almost_equal(out, ndimage.shift(data[::2], (1, 1))) + idx = numpy.indices(data[:, ::2].shape) - 1 + out = ndimage.map_coordinates(data[:, ::2], idx) + assert_array_almost_equal(out, [[0, 0], [0, 4], [0, 7]]) + assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1))) + + def test_map_coordinates_endianness_with_output_parameter(self): + # output parameter given as array or dtype with either endianness + # see issue #4127 + data = numpy.array([[1, 2], [7, 6]]) + expected = numpy.array([[0, 0], [0, 1]]) + idx = numpy.indices(data.shape) + idx -= 1 + for out in [ + data.dtype, + data.dtype.newbyteorder(), + numpy.empty_like(expected), + numpy.empty_like(expected).astype(expected.dtype.newbyteorder()) + ]: + returned = ndimage.map_coordinates(data, idx, output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, expected) + + def test_map_coordinates_with_string_output(self): + data = numpy.array([[1]]) + idx = numpy.indices(data.shape) + out = ndimage.map_coordinates(data, idx, output='f') + assert_(out.dtype is numpy.dtype('f')) + assert_array_almost_equal(out, [[1]]) + + @pytest.mark.skipif('win32' in sys.platform or numpy.intp(0).itemsize < 8, + reason='do not run on 32 bit or windows ' + '(no sparse memory)') + def test_map_coordinates_large_data(self): + # check crash on large data + try: + n = 30000 + a = numpy.empty(n**2, dtype=numpy.float32).reshape(n, n) + # fill the part we might read + a[n - 3:, n - 3:] = 0 + ndimage.map_coordinates(a, [[n - 1.5], [n - 1.5]], order=1) + except MemoryError as e: + raise pytest.skip('Not enough memory available') from e + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform01(self, order): + data = numpy.array([1]) + out = ndimage.affine_transform(data, [[1]], order=order) + assert_array_almost_equal(out, [1]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform02(self, order): + data = numpy.ones([4]) + out = ndimage.affine_transform(data, [[1]], order=order) + assert_array_almost_equal(out, [1, 1, 1, 1]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform03(self, order): + data = numpy.ones([4]) + out = ndimage.affine_transform(data, [[1]], -1, order=order) + assert_array_almost_equal(out, [0, 1, 1, 1]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform04(self, order): + data = numpy.array([4, 1, 3, 2]) + out = ndimage.affine_transform(data, [[1]], -1, order=order) + assert_array_almost_equal(out, [0, 4, 1, 3]) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', [numpy.float64, numpy.complex128]) + def test_affine_transform05(self, order, dtype): + data = numpy.array([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = numpy.array([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + if data.dtype.kind == 'c': + data -= 1j * data + expected -= 1j * expected + out = ndimage.affine_transform(data, [[1, 0], [0, 1]], + [0, -1], order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform06(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, [[1, 0], [0, 1]], + [0, -1], order=order) + assert_array_almost_equal(out, [[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform07(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, [[1, 0], [0, 1]], + [-1, 0], order=order) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform08(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.affine_transform(data, [[1, 0], [0, 1]], + [-1, -1], order=order) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform09(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.affine_transform(filtered, [[1, 0], [0, 1]], + [-1, -1], order=order, + prefilter=False) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform10(self, order): + data = numpy.ones([2], numpy.float64) + out = ndimage.affine_transform(data, [[0.5]], output_shape=(4,), + order=order) + assert_array_almost_equal(out, [1, 1, 1, 0]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform11(self, order): + data = [1, 5, 2, 6, 3, 7, 4, 4] + out = ndimage.affine_transform(data, [[2]], 0, (4,), order=order) + assert_array_almost_equal(out, [1, 2, 3, 4]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform12(self, order): + data = [1, 2, 3, 4] + out = ndimage.affine_transform(data, [[0.5]], 0, (8,), order=order) + assert_array_almost_equal(out[::2], [1, 2, 3, 4]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform13(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9.0, 10, 11, 12]] + out = ndimage.affine_transform(data, [[1, 0], [0, 2]], 0, (3, 2), + order=order) + assert_array_almost_equal(out, [[1, 3], [5, 7], [9, 11]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform14(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + out = ndimage.affine_transform(data, [[2, 0], [0, 1]], 0, (1, 4), + order=order) + assert_array_almost_equal(out, [[1, 2, 3, 4]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform15(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + out = ndimage.affine_transform(data, [[2, 0], [0, 2]], 0, (1, 2), + order=order) + assert_array_almost_equal(out, [[1, 3]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform16(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + out = ndimage.affine_transform(data, [[1, 0.0], [0, 0.5]], 0, + (3, 8), order=order) + assert_array_almost_equal(out[..., ::2], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform17(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + out = ndimage.affine_transform(data, [[0.5, 0], [0, 1]], 0, + (6, 4), order=order) + assert_array_almost_equal(out[::2, ...], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform18(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + out = ndimage.affine_transform(data, [[0.5, 0], [0, 0.5]], 0, + (6, 8), order=order) + assert_array_almost_equal(out[::2, ::2], data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform19(self, order): + data = numpy.array([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]], numpy.float64) + out = ndimage.affine_transform(data, [[0.5, 0], [0, 0.5]], 0, + (6, 8), order=order) + out = ndimage.affine_transform(out, [[2.0, 0], [0, 2.0]], 0, + (3, 4), order=order) + assert_array_almost_equal(out, data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform20(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + out = ndimage.affine_transform(data, [[0], [2]], 0, (2,), + order=order) + assert_array_almost_equal(out, [1, 3]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform21(self, order): + data = [[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]] + out = ndimage.affine_transform(data, [[2], [0]], 0, (2,), + order=order) + assert_array_almost_equal(out, [1, 9]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform22(self, order): + # shift and offset interaction; see issue #1547 + data = numpy.array([4, 1, 3, 2]) + out = ndimage.affine_transform(data, [[2]], [-1], (3,), + order=order) + assert_array_almost_equal(out, [0, 1, 2]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform23(self, order): + # shift and offset interaction; see issue #1547 + data = numpy.array([4, 1, 3, 2]) + out = ndimage.affine_transform(data, [[0.5]], [-1], (8,), + order=order) + assert_array_almost_equal(out[::2], [0, 4, 1, 3]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform24(self, order): + # consistency between diagonal and non-diagonal case; see issue #1547 + data = numpy.array([4, 1, 3, 2]) + with suppress_warnings() as sup: + sup.filter(UserWarning, + 'The behavior of affine_transform with a 1-D array .* ' + 'has changed') + out1 = ndimage.affine_transform(data, [2], -1, order=order) + out2 = ndimage.affine_transform(data, [[2]], -1, order=order) + assert_array_almost_equal(out1, out2) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform25(self, order): + # consistency between diagonal and non-diagonal case; see issue #1547 + data = numpy.array([4, 1, 3, 2]) + with suppress_warnings() as sup: + sup.filter(UserWarning, + 'The behavior of affine_transform with a 1-D array .* ' + 'has changed') + out1 = ndimage.affine_transform(data, [0.5], -1, order=order) + out2 = ndimage.affine_transform(data, [[0.5]], -1, order=order) + assert_array_almost_equal(out1, out2) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform26(self, order): + # test homogeneous coordinates + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + tform_original = numpy.eye(2) + offset_original = -numpy.ones((2, 1)) + tform_h1 = numpy.hstack((tform_original, offset_original)) + tform_h2 = numpy.vstack((tform_h1, [[0, 0, 1]])) + out1 = ndimage.affine_transform(filtered, tform_original, + offset_original.ravel(), + order=order, prefilter=False) + out2 = ndimage.affine_transform(filtered, tform_h1, order=order, + prefilter=False) + out3 = ndimage.affine_transform(filtered, tform_h2, order=order, + prefilter=False) + for out in [out1, out2, out3]: + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + + def test_affine_transform27(self): + # test valid homogeneous transformation matrix + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + tform_h1 = numpy.hstack((numpy.eye(2), -numpy.ones((2, 1)))) + tform_h2 = numpy.vstack((tform_h1, [[5, 2, 1]])) + assert_raises(ValueError, ndimage.affine_transform, data, tform_h2) + + def test_affine_transform_1d_endianness_with_output_parameter(self): + # 1d affine transform given output ndarray or dtype with + # either endianness. see issue #7388 + data = numpy.ones((2, 2)) + for out in [numpy.empty_like(data), + numpy.empty_like(data).astype(data.dtype.newbyteorder()), + data.dtype, data.dtype.newbyteorder()]: + with suppress_warnings() as sup: + sup.filter(UserWarning, + 'The behavior of affine_transform with a 1-D array ' + '.* has changed') + returned = ndimage.affine_transform(data, [1, 1], output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, [[1, 1], [1, 1]]) + + def test_affine_transform_multi_d_endianness_with_output_parameter(self): + # affine transform given output ndarray or dtype with either endianness + # see issue #4127 + data = numpy.array([1]) + for out in [data.dtype, data.dtype.newbyteorder(), + numpy.empty_like(data), + numpy.empty_like(data).astype(data.dtype.newbyteorder())]: + returned = ndimage.affine_transform(data, [[1]], output=out) + result = out if returned is None else returned + assert_array_almost_equal(result, [1]) + + def test_affine_transform_output_shape(self): + # don't require output_shape when out of a different size is given + data = numpy.arange(8, dtype=numpy.float64) + out = numpy.ones((16,)) + + ndimage.affine_transform(data, [[1]], output=out) + assert_array_almost_equal(out[:8], data) + + # mismatched output shape raises an error + with pytest.raises(RuntimeError): + ndimage.affine_transform( + data, [[1]], output=out, output_shape=(12,)) + + def test_affine_transform_with_string_output(self): + data = numpy.array([1]) + out = ndimage.affine_transform(data, [[1]], output='f') + assert_(out.dtype is numpy.dtype('f')) + assert_array_almost_equal(out, [1]) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform_shift_via_grid_wrap(self, shift, order): + # For mode 'grid-wrap', integer shifts should match numpy.roll + x = numpy.array([[0, 1], + [2, 3]]) + affine = numpy.zeros((2, 3)) + affine[:2, :2] = numpy.eye(2) + affine[:, 2] = shift + assert_array_almost_equal( + ndimage.affine_transform(x, affine, mode='grid-wrap', order=order), + numpy.roll(x, shift, axis=(0, 1)), + ) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_affine_transform_shift_reflect(self, order): + # shift by x.shape results in reflection + x = numpy.array([[0, 1, 2], + [3, 4, 5]]) + affine = numpy.zeros((2, 3)) + affine[:2, :2] = numpy.eye(2) + affine[:, 2] = x.shape + assert_array_almost_equal( + ndimage.affine_transform(x, affine, mode='reflect', order=order), + x[::-1, ::-1], + ) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift01(self, order): + data = numpy.array([1]) + out = ndimage.shift(data, [1], order=order) + assert_array_almost_equal(out, [0]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift02(self, order): + data = numpy.ones([4]) + out = ndimage.shift(data, [1], order=order) + assert_array_almost_equal(out, [0, 1, 1, 1]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift03(self, order): + data = numpy.ones([4]) + out = ndimage.shift(data, -1, order=order) + assert_array_almost_equal(out, [1, 1, 1, 0]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift04(self, order): + data = numpy.array([4, 1, 3, 2]) + out = ndimage.shift(data, 1, order=order) + assert_array_almost_equal(out, [0, 4, 1, 3]) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', [numpy.float64, numpy.complex128]) + def test_shift05(self, order, dtype): + data = numpy.array([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + expected = numpy.array([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + if data.dtype.kind == 'c': + data -= 1j * data + expected -= 1j * expected + out = ndimage.shift(data, [0, 1], order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('mode', ['constant', 'grid-constant']) + @pytest.mark.parametrize('dtype', [numpy.float64, numpy.complex128]) + def test_shift_with_nonzero_cval(self, order, mode, dtype): + data = numpy.array([[1, 1, 1, 1], + [1, 1, 1, 1], + [1, 1, 1, 1]], dtype=dtype) + + expected = numpy.array([[0, 1, 1, 1], + [0, 1, 1, 1], + [0, 1, 1, 1]], dtype=dtype) + + if data.dtype.kind == 'c': + data -= 1j * data + expected -= 1j * expected + cval = 5.0 + expected[:, 0] = cval # specific to shift of [0, 1] used below + out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift06(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [0, 1], order=order) + assert_array_almost_equal(out, [[0, 4, 1, 3], + [0, 7, 6, 8], + [0, 3, 5, 3]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift07(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [1, 0], order=order) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [4, 1, 3, 2], + [7, 6, 8, 5]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift08(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + out = ndimage.shift(data, [1, 1], order=order) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift09(self, order): + data = numpy.array([[4, 1, 3, 2], + [7, 6, 8, 5], + [3, 5, 3, 6]]) + if (order > 1): + filtered = ndimage.spline_filter(data, order=order) + else: + filtered = data + out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False) + assert_array_almost_equal(out, [[0, 0, 0, 0], + [0, 4, 1, 3], + [0, 7, 6, 8]]) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_grid_wrap(self, shift, order): + # For mode 'grid-wrap', integer shifts should match numpy.roll + x = numpy.array([[0, 1], + [2, 3]]) + assert_array_almost_equal( + ndimage.shift(x, shift, mode='grid-wrap', order=order), + numpy.roll(x, shift, axis=(0, 1)), + ) + + @pytest.mark.parametrize('shift', + [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)]) + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_grid_constant1(self, shift, order): + # For integer shifts, 'constant' and 'grid-constant' should be equal + x = numpy.arange(20).reshape((5, 4)) + assert_array_almost_equal( + ndimage.shift(x, shift, mode='grid-constant', order=order), + ndimage.shift(x, shift, mode='constant', order=order), + ) + + def test_shift_grid_constant_order1(self): + x = numpy.array([[1, 2, 3], + [4, 5, 6]], dtype=float) + expected_result = numpy.array([[0.25, 0.75, 1.25], + [1.25, 3.00, 4.00]]) + assert_array_almost_equal( + ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1), + expected_result, + ) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_shift_reflect(self, order): + # shift by x.shape results in reflection + x = numpy.array([[0, 1, 2], + [3, 4, 5]]) + assert_array_almost_equal( + ndimage.shift(x, x.shape, mode='reflect', order=order), + x[::-1, ::-1], + ) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('prefilter', [False, True]) + def test_shift_nearest_boundary(self, order, prefilter): + # verify that shifting at least order // 2 beyond the end of the array + # gives a value equal to the edge value. + x = numpy.arange(16) + kwargs = dict(mode='nearest', order=order, prefilter=prefilter) + assert_array_almost_equal( + ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0], + ) + assert_array_almost_equal( + ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1], + ) + + @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest', + 'mirror', 'reflect']) + @pytest.mark.parametrize('order', range(6)) + def test_shift_vs_padded(self, order, mode): + x = numpy.arange(144, dtype=float).reshape(12, 12) + shift = (0.4, -2.3) + + # manually pad and then extract center to get expected result + npad = 32 + pad_mode = ndimage_to_numpy_mode.get(mode) + xp = numpy.pad(x, npad, mode=pad_mode) + center_slice = tuple([slice(npad, -npad)] * x.ndim) + expected_result = ndimage.shift( + xp, shift, mode=mode, order=order)[center_slice] + + assert_allclose( + ndimage.shift(x, shift, mode=mode, order=order), + expected_result, + rtol=1e-7, + ) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_zoom1(self, order): + for z in [2, [2, 2]]: + arr = numpy.array(list(range(25))).reshape((5, 5)).astype(float) + arr = ndimage.zoom(arr, z, order=order) + assert_equal(arr.shape, (10, 10)) + assert_(numpy.all(arr[-1, :] != 0)) + assert_(numpy.all(arr[-1, :] >= (20 - eps))) + assert_(numpy.all(arr[0, :] <= (5 + eps))) + assert_(numpy.all(arr >= (0 - eps))) + assert_(numpy.all(arr <= (24 + eps))) + + def test_zoom2(self): + arr = numpy.arange(12).reshape((3, 4)) + out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5) + assert_array_equal(out, arr) + + def test_zoom3(self): + arr = numpy.array([[1, 2]]) + out1 = ndimage.zoom(arr, (2, 1)) + out2 = ndimage.zoom(arr, (1, 2)) + + assert_array_almost_equal(out1, numpy.array([[1, 2], [1, 2]])) + assert_array_almost_equal(out2, numpy.array([[1, 1, 2, 2]])) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', [numpy.float64, numpy.complex128]) + def test_zoom_affine01(self, order, dtype): + data = numpy.asarray([[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 10, 11, 12]], dtype=dtype) + if data.dtype.kind == 'c': + data -= 1j * data + with suppress_warnings() as sup: + sup.filter(UserWarning, + 'The behavior of affine_transform with a 1-D array .* ' + 'has changed') + out = ndimage.affine_transform(data, [0.5, 0.5], 0, + (6, 8), order=order) + assert_array_almost_equal(out[::2, ::2], data) + + def test_zoom_infinity(self): + # Ticket #1419 regression test + dim = 8 + ndimage.zoom(numpy.zeros((dim, dim)), 1. / dim, mode='nearest') + + def test_zoom_zoomfactor_one(self): + # Ticket #1122 regression test + arr = numpy.zeros((1, 5, 5)) + zoom = (1.0, 2.0, 2.0) + + out = ndimage.zoom(arr, zoom, cval=7) + ref = numpy.zeros((1, 10, 10)) + assert_array_almost_equal(out, ref) + + def test_zoom_output_shape_roundoff(self): + arr = numpy.zeros((3, 11, 25)) + zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25) + out = ndimage.zoom(arr, zoom) + assert_array_equal(out.shape, (4, 15, 29)) + + @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)]) + @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect', + 'mirror', 'grid-wrap', 'grid-mirror', + 'grid-constant']) + def test_zoom_by_int_order0(self, zoom, mode): + # order 0 zoom should be the same as replication via numpy.kron + # Note: This is not True for general x shapes when grid_mode is False, + # but works here for all modes because the size ratio happens to + # always be an integer when x.shape = (2, 2). + x = numpy.array([[0, 1], + [2, 3]], dtype=float) + # x = numpy.arange(16, dtype=float).reshape(4, 4) + assert_array_almost_equal( + ndimage.zoom(x, zoom, order=0, mode=mode), + numpy.kron(x, numpy.ones(zoom)) + ) + + @pytest.mark.parametrize('shape', [(2, 3), (4, 4)]) + @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)]) + @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror', + 'grid-wrap', 'grid-constant']) + def test_zoom_grid_by_int_order0(self, shape, zoom, mode): + # When grid_mode is True, order 0 zoom should be the same as + # replication via numpy.kron. The only exceptions to this are the + # non-grid modes 'constant' and 'wrap'. + x = numpy.arange(numpy.prod(shape), dtype=float).reshape(shape) + assert_array_almost_equal( + ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True), + numpy.kron(x, numpy.ones(zoom)) + ) + + @pytest.mark.parametrize('mode', ['constant', 'wrap']) + def test_zoom_grid_mode_warnings(self, mode): + # Warn on use of non-grid modes when grid_mode is True + x = numpy.arange(9, dtype=float).reshape((3, 3)) + with pytest.warns(UserWarning, + match="It is recommended to use mode"): + ndimage.zoom(x, 2, mode=mode, grid_mode=True), + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate01(self, order): + data = numpy.array([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=numpy.float64) + out = ndimage.rotate(data, 0, order=order) + assert_array_almost_equal(out, data) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate02(self, order): + data = numpy.array([[0, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 0, 0]], dtype=numpy.float64) + expected = numpy.array([[0, 0, 0], + [0, 0, 0], + [0, 1, 0], + [0, 0, 0]], dtype=numpy.float64) + out = ndimage.rotate(data, 90, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + @pytest.mark.parametrize('dtype', [numpy.float64, numpy.complex128]) + def test_rotate03(self, order, dtype): + data = numpy.array([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=dtype) + expected = numpy.array([[0, 0, 0], + [0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=dtype) + if data.dtype.kind == 'c': + data -= 1j * data + expected -= 1j * expected + out = ndimage.rotate(data, 90, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate04(self, order): + data = numpy.array([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]], dtype=numpy.float64) + expected = numpy.array([[0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0]], dtype=numpy.float64) + out = ndimage.rotate(data, 90, reshape=False, order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate05(self, order): + data = numpy.empty((4, 3, 3)) + for i in range(3): + data[:, :, i] = numpy.array([[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=numpy.float64) + expected = numpy.array([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=numpy.float64) + out = ndimage.rotate(data, 90, order=order) + for i in range(3): + assert_array_almost_equal(out[:, :, i], expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate06(self, order): + data = numpy.empty((3, 4, 3)) + for i in range(3): + data[:, :, i] = numpy.array([[0, 0, 0, 0], + [0, 1, 1, 0], + [0, 0, 0, 0]], dtype=numpy.float64) + expected = numpy.array([[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0]], dtype=numpy.float64) + out = ndimage.rotate(data, 90, order=order) + for i in range(3): + assert_array_almost_equal(out[:, :, i], expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate07(self, order): + data = numpy.array([[[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) + data = data.transpose() + expected = numpy.array([[[0, 0, 0], + [0, 1, 0], + [0, 1, 0], + [0, 0, 0], + [0, 0, 0]]] * 2, dtype=numpy.float64) + expected = expected.transpose([2, 1, 0]) + out = ndimage.rotate(data, 90, axes=(0, 1), order=order) + assert_array_almost_equal(out, expected) + + @pytest.mark.parametrize('order', range(0, 6)) + def test_rotate08(self, order): + data = numpy.array([[[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) + data = data.transpose() + expected = numpy.array([[[0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0]]] * 2, dtype=numpy.float64) + expected = expected.transpose() + out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order) + assert_array_almost_equal(out, expected) + + def test_rotate09(self): + data = numpy.array([[0, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 0, 0, 0, 0]] * 2, dtype=numpy.float64) + with assert_raises(ValueError): + ndimage.rotate(data, 90, axes=(0, data.ndim)) + + def test_rotate10(self): + data = numpy.arange(45, dtype=numpy.float64).reshape((3, 5, 3)) + + # The output of ndimage.rotate before refactoring + expected = numpy.array([[[0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [6.54914793, 7.54914793, 8.54914793], + [10.84520162, 11.84520162, 12.84520162], + [0.0, 0.0, 0.0]], + [[6.19286575, 7.19286575, 8.19286575], + [13.4730712, 14.4730712, 15.4730712], + [21.0, 22.0, 23.0], + [28.5269288, 29.5269288, 30.5269288], + [35.80713425, 36.80713425, 37.80713425]], + [[0.0, 0.0, 0.0], + [31.15479838, 32.15479838, 33.15479838], + [35.45085207, 36.45085207, 37.45085207], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0]]]) + + out = ndimage.rotate(data, angle=12, reshape=False) + assert_array_almost_equal(out, expected) + + def test_rotate_exact_180(self): + a = numpy.tile(numpy.arange(5), (5, 1)) + b = ndimage.rotate(ndimage.rotate(a, 180), -180) + assert_equal(a, b) + + +def test_zoom_output_shape(): + """Ticket #643""" + x = numpy.arange(12).reshape((3, 4)) + ndimage.zoom(x, 2, output=numpy.zeros((6, 8))) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py new file mode 100644 index 0000000000000000000000000000000000000000..a25429eebc8b3739e00465b43fd28ba24b320b45 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/ndimage/tests/test_ni_support.py @@ -0,0 +1,77 @@ +import pytest + +import numpy as np +from .._ni_support import _get_output + + +@pytest.mark.parametrize( + 'dtype', + [ + # String specifiers + 'f4', 'float32', 'complex64', 'complex128', + # Type and dtype specifiers + np.float32, float, np.dtype('f4'), + # Derive from input + None, + ], +) +def test_get_output_basic(dtype): + shape = (2, 3) + + input_ = np.zeros(shape, 'float32') + + # For None, derive dtype from input + expected_dtype = 'float32' if dtype is None else dtype + + # Output is dtype-specifier, retrieve shape from input + result = _get_output(dtype, input_) + assert result.shape == shape + assert result.dtype == np.dtype(expected_dtype) + + # Output is dtype specifier, with explicit shape, overriding input + result = _get_output(dtype, input_, shape=(3, 2)) + assert result.shape == (3, 2) + assert result.dtype == np.dtype(expected_dtype) + + # Output is pre-allocated array, return directly + output = np.zeros(shape, dtype) + result = _get_output(output, input_) + assert result is output + + +def test_get_output_complex(): + shape = (2, 3) + + input_ = np.zeros(shape) + + # None, promote input type to complex + result = _get_output(None, input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex128') + + # Explicit type, promote type to complex + with pytest.warns(UserWarning, match='promoting specified output dtype to complex'): + result = _get_output(float, input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex128') + + # String specifier, simply verify complex output + result = _get_output('complex64', input_, complex_output=True) + assert result.shape == shape + assert result.dtype == np.dtype('complex64') + + +def test_get_output_error_cases(): + input_ = np.zeros((2, 3), 'float32') + + # Two separate paths can raise the same error + with pytest.raises(RuntimeError, match='output must have complex dtype'): + _get_output('float32', input_, complex_output=True) + with pytest.raises(RuntimeError, match='output must have complex dtype'): + _get_output(np.zeros((2, 3)), input_, complex_output=True) + + with pytest.raises(RuntimeError, match='output must have numeric dtype'): + _get_output('void', input_) + + with pytest.raises(RuntimeError, match='shape not correct'): + _get_output(np.zeros((3, 2)), input_)