Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_bvp.py +1155 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py +224 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-310.pyc +0 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py +266 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py +663 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so +0 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/odepack.py +17 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/tests/__init__.py +0 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py +711 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/tests/test_integrate.py +834 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py +680 -0
- parrot/lib/python3.10/site-packages/scipy/integrate/vode.py +15 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h +174 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h +49 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h +25 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h +23 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h +42 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h +24 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h +62 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h +59 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h +21 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h +114 -0
- videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h +71 -0
- vllm/lib/python3.10/site-packages/sympy/benchmarks/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/benchmarks/bench_discrete_log.py +83 -0
- vllm/lib/python3.10/site-packages/sympy/benchmarks/bench_meijerint.py +261 -0
- vllm/lib/python3.10/site-packages/sympy/benchmarks/bench_symbench.py +134 -0
- vllm/lib/python3.10/site-packages/sympy/crypto/__init__.py +35 -0
- vllm/lib/python3.10/site-packages/sympy/crypto/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/crypto/__pycache__/crypto.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/crypto/crypto.py +3367 -0
- vllm/lib/python3.10/site-packages/sympy/crypto/tests/__init__.py +0 -0
- vllm/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/test_crypto.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py +562 -0
- vllm/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/series/__pycache__/aseries.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/series/__pycache__/formal.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/series/__pycache__/order.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/series/__pycache__/residues.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/series/__pycache__/series.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/series/__pycache__/series_class.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/sympy/series/benchmarks/__init__.py +0 -0
.gitattributes
CHANGED
|
@@ -1691,3 +1691,4 @@ vllm/lib/python3.10/site-packages/sympy/utilities/tests/__pycache__/test_wester.
|
|
| 1691 |
vllm/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1692 |
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/single.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1693 |
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 1691 |
vllm/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1692 |
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/single.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1693 |
vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1694 |
+
vllm/lib/python3.10/site-packages/sympy/solvers/diophantine/__p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|
| 8 |
+
from scipy.sparse.linalg import splu
|
| 9 |
+
from scipy.optimize import OptimizeResult
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
EPS = np.finfo(float).eps
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def estimate_fun_jac(fun, x, y, p, f0=None):
|
| 16 |
+
"""Estimate derivatives of an ODE system rhs with forward differences.
|
| 17 |
+
|
| 18 |
+
Returns
|
| 19 |
+
-------
|
| 20 |
+
df_dy : ndarray, shape (n, n, m)
|
| 21 |
+
Derivatives with respect to y. An element (i, j, q) corresponds to
|
| 22 |
+
d f_i(x_q, y_q) / d (y_q)_j.
|
| 23 |
+
df_dp : ndarray with shape (n, k, m) or None
|
| 24 |
+
Derivatives with respect to p. An element (i, j, q) corresponds to
|
| 25 |
+
d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned.
|
| 26 |
+
"""
|
| 27 |
+
n, m = y.shape
|
| 28 |
+
if f0 is None:
|
| 29 |
+
f0 = fun(x, y, p)
|
| 30 |
+
|
| 31 |
+
dtype = y.dtype
|
| 32 |
+
|
| 33 |
+
df_dy = np.empty((n, n, m), dtype=dtype)
|
| 34 |
+
h = EPS**0.5 * (1 + np.abs(y))
|
| 35 |
+
for i in range(n):
|
| 36 |
+
y_new = y.copy()
|
| 37 |
+
y_new[i] += h[i]
|
| 38 |
+
hi = y_new[i] - y[i]
|
| 39 |
+
f_new = fun(x, y_new, p)
|
| 40 |
+
df_dy[:, i, :] = (f_new - f0) / hi
|
| 41 |
+
|
| 42 |
+
k = p.shape[0]
|
| 43 |
+
if k == 0:
|
| 44 |
+
df_dp = None
|
| 45 |
+
else:
|
| 46 |
+
df_dp = np.empty((n, k, m), dtype=dtype)
|
| 47 |
+
h = EPS**0.5 * (1 + np.abs(p))
|
| 48 |
+
for i in range(k):
|
| 49 |
+
p_new = p.copy()
|
| 50 |
+
p_new[i] += h[i]
|
| 51 |
+
hi = p_new[i] - p[i]
|
| 52 |
+
f_new = fun(x, y, p_new)
|
| 53 |
+
df_dp[:, i, :] = (f_new - f0) / hi
|
| 54 |
+
|
| 55 |
+
return df_dy, df_dp
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def estimate_bc_jac(bc, ya, yb, p, bc0=None):
|
| 59 |
+
"""Estimate derivatives of boundary conditions with forward differences.
|
| 60 |
+
|
| 61 |
+
Returns
|
| 62 |
+
-------
|
| 63 |
+
dbc_dya : ndarray, shape (n + k, n)
|
| 64 |
+
Derivatives with respect to ya. An element (i, j) corresponds to
|
| 65 |
+
d bc_i / d ya_j.
|
| 66 |
+
dbc_dyb : ndarray, shape (n + k, n)
|
| 67 |
+
Derivatives with respect to yb. An element (i, j) corresponds to
|
| 68 |
+
d bc_i / d ya_j.
|
| 69 |
+
dbc_dp : ndarray with shape (n + k, k) or None
|
| 70 |
+
Derivatives with respect to p. An element (i, j) corresponds to
|
| 71 |
+
d bc_i / d p_j. If `p` is empty, None is returned.
|
| 72 |
+
"""
|
| 73 |
+
n = ya.shape[0]
|
| 74 |
+
k = p.shape[0]
|
| 75 |
+
|
| 76 |
+
if bc0 is None:
|
| 77 |
+
bc0 = bc(ya, yb, p)
|
| 78 |
+
|
| 79 |
+
dtype = ya.dtype
|
| 80 |
+
|
| 81 |
+
dbc_dya = np.empty((n, n + k), dtype=dtype)
|
| 82 |
+
h = EPS**0.5 * (1 + np.abs(ya))
|
| 83 |
+
for i in range(n):
|
| 84 |
+
ya_new = ya.copy()
|
| 85 |
+
ya_new[i] += h[i]
|
| 86 |
+
hi = ya_new[i] - ya[i]
|
| 87 |
+
bc_new = bc(ya_new, yb, p)
|
| 88 |
+
dbc_dya[i] = (bc_new - bc0) / hi
|
| 89 |
+
dbc_dya = dbc_dya.T
|
| 90 |
+
|
| 91 |
+
h = EPS**0.5 * (1 + np.abs(yb))
|
| 92 |
+
dbc_dyb = np.empty((n, n + k), dtype=dtype)
|
| 93 |
+
for i in range(n):
|
| 94 |
+
yb_new = yb.copy()
|
| 95 |
+
yb_new[i] += h[i]
|
| 96 |
+
hi = yb_new[i] - yb[i]
|
| 97 |
+
bc_new = bc(ya, yb_new, p)
|
| 98 |
+
dbc_dyb[i] = (bc_new - bc0) / hi
|
| 99 |
+
dbc_dyb = dbc_dyb.T
|
| 100 |
+
|
| 101 |
+
if k == 0:
|
| 102 |
+
dbc_dp = None
|
| 103 |
+
else:
|
| 104 |
+
h = EPS**0.5 * (1 + np.abs(p))
|
| 105 |
+
dbc_dp = np.empty((k, n + k), dtype=dtype)
|
| 106 |
+
for i in range(k):
|
| 107 |
+
p_new = p.copy()
|
| 108 |
+
p_new[i] += h[i]
|
| 109 |
+
hi = p_new[i] - p[i]
|
| 110 |
+
bc_new = bc(ya, yb, p_new)
|
| 111 |
+
dbc_dp[i] = (bc_new - bc0) / hi
|
| 112 |
+
dbc_dp = dbc_dp.T
|
| 113 |
+
|
| 114 |
+
return dbc_dya, dbc_dyb, dbc_dp
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def compute_jac_indices(n, m, k):
|
| 118 |
+
"""Compute indices for the collocation system Jacobian construction.
|
| 119 |
+
|
| 120 |
+
See `construct_global_jac` for the explanation.
|
| 121 |
+
"""
|
| 122 |
+
i_col = np.repeat(np.arange((m - 1) * n), n)
|
| 123 |
+
j_col = (np.tile(np.arange(n), n * (m - 1)) +
|
| 124 |
+
np.repeat(np.arange(m - 1) * n, n**2))
|
| 125 |
+
|
| 126 |
+
i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n)
|
| 127 |
+
j_bc = np.tile(np.arange(n), n + k)
|
| 128 |
+
|
| 129 |
+
i_p_col = np.repeat(np.arange((m - 1) * n), k)
|
| 130 |
+
j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n)
|
| 131 |
+
|
| 132 |
+
i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k)
|
| 133 |
+
j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k)
|
| 134 |
+
|
| 135 |
+
i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc))
|
| 136 |
+
j = np.hstack((j_col, j_col + n,
|
| 137 |
+
j_bc, j_bc + (m - 1) * n,
|
| 138 |
+
j_p_col, j_p_bc))
|
| 139 |
+
|
| 140 |
+
return i, j
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def stacked_matmul(a, b):
|
| 144 |
+
"""Stacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]).
|
| 145 |
+
|
| 146 |
+
Empirical optimization. Use outer Python loop and BLAS for large
|
| 147 |
+
matrices, otherwise use a single einsum call.
|
| 148 |
+
"""
|
| 149 |
+
if a.shape[1] > 50:
|
| 150 |
+
out = np.empty((a.shape[0], a.shape[1], b.shape[2]))
|
| 151 |
+
for i in range(a.shape[0]):
|
| 152 |
+
out[i] = np.dot(a[i], b[i])
|
| 153 |
+
return out
|
| 154 |
+
else:
|
| 155 |
+
return np.einsum('...ij,...jk->...ik', a, b)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp,
|
| 159 |
+
df_dp_middle, dbc_dya, dbc_dyb, dbc_dp):
|
| 160 |
+
"""Construct the Jacobian of the collocation system.
|
| 161 |
+
|
| 162 |
+
There are n * m + k functions: m - 1 collocations residuals, each
|
| 163 |
+
containing n components, followed by n + k boundary condition residuals.
|
| 164 |
+
|
| 165 |
+
There are n * m + k variables: m vectors of y, each containing n
|
| 166 |
+
components, followed by k values of vector p.
|
| 167 |
+
|
| 168 |
+
For example, let m = 4, n = 2 and k = 1, then the Jacobian will have
|
| 169 |
+
the following sparsity structure:
|
| 170 |
+
|
| 171 |
+
1 1 2 2 0 0 0 0 5
|
| 172 |
+
1 1 2 2 0 0 0 0 5
|
| 173 |
+
0 0 1 1 2 2 0 0 5
|
| 174 |
+
0 0 1 1 2 2 0 0 5
|
| 175 |
+
0 0 0 0 1 1 2 2 5
|
| 176 |
+
0 0 0 0 1 1 2 2 5
|
| 177 |
+
|
| 178 |
+
3 3 0 0 0 0 4 4 6
|
| 179 |
+
3 3 0 0 0 0 4 4 6
|
| 180 |
+
3 3 0 0 0 0 4 4 6
|
| 181 |
+
|
| 182 |
+
Zeros denote identically zero values, other values denote different kinds
|
| 183 |
+
of blocks in the matrix (see below). The blank row indicates the separation
|
| 184 |
+
of collocation residuals from boundary conditions. And the blank column
|
| 185 |
+
indicates the separation of y values from p values.
|
| 186 |
+
|
| 187 |
+
Refer to [1]_ (p. 306) for the formula of n x n blocks for derivatives
|
| 188 |
+
of collocation residuals with respect to y.
|
| 189 |
+
|
| 190 |
+
Parameters
|
| 191 |
+
----------
|
| 192 |
+
n : int
|
| 193 |
+
Number of equations in the ODE system.
|
| 194 |
+
m : int
|
| 195 |
+
Number of nodes in the mesh.
|
| 196 |
+
k : int
|
| 197 |
+
Number of the unknown parameters.
|
| 198 |
+
i_jac, j_jac : ndarray
|
| 199 |
+
Row and column indices returned by `compute_jac_indices`. They
|
| 200 |
+
represent different blocks in the Jacobian matrix in the following
|
| 201 |
+
order (see the scheme above):
|
| 202 |
+
|
| 203 |
+
* 1: m - 1 diagonal n x n blocks for the collocation residuals.
|
| 204 |
+
* 2: m - 1 off-diagonal n x n blocks for the collocation residuals.
|
| 205 |
+
* 3 : (n + k) x n block for the dependency of the boundary
|
| 206 |
+
conditions on ya.
|
| 207 |
+
* 4: (n + k) x n block for the dependency of the boundary
|
| 208 |
+
conditions on yb.
|
| 209 |
+
* 5: (m - 1) * n x k block for the dependency of the collocation
|
| 210 |
+
residuals on p.
|
| 211 |
+
* 6: (n + k) x k block for the dependency of the boundary
|
| 212 |
+
conditions on p.
|
| 213 |
+
|
| 214 |
+
df_dy : ndarray, shape (n, n, m)
|
| 215 |
+
Jacobian of f with respect to y computed at the mesh nodes.
|
| 216 |
+
df_dy_middle : ndarray, shape (n, n, m - 1)
|
| 217 |
+
Jacobian of f with respect to y computed at the middle between the
|
| 218 |
+
mesh nodes.
|
| 219 |
+
df_dp : ndarray with shape (n, k, m) or None
|
| 220 |
+
Jacobian of f with respect to p computed at the mesh nodes.
|
| 221 |
+
df_dp_middle : ndarray with shape (n, k, m - 1) or None
|
| 222 |
+
Jacobian of f with respect to p computed at the middle between the
|
| 223 |
+
mesh nodes.
|
| 224 |
+
dbc_dya, dbc_dyb : ndarray, shape (n, n)
|
| 225 |
+
Jacobian of bc with respect to ya and yb.
|
| 226 |
+
dbc_dp : ndarray with shape (n, k) or None
|
| 227 |
+
Jacobian of bc with respect to p.
|
| 228 |
+
|
| 229 |
+
Returns
|
| 230 |
+
-------
|
| 231 |
+
J : csc_matrix, shape (n * m + k, n * m + k)
|
| 232 |
+
Jacobian of the collocation system in a sparse form.
|
| 233 |
+
|
| 234 |
+
References
|
| 235 |
+
----------
|
| 236 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 237 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 238 |
+
Number 3, pp. 299-316, 2001.
|
| 239 |
+
"""
|
| 240 |
+
df_dy = np.transpose(df_dy, (2, 0, 1))
|
| 241 |
+
df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1))
|
| 242 |
+
|
| 243 |
+
h = h[:, np.newaxis, np.newaxis]
|
| 244 |
+
|
| 245 |
+
dtype = df_dy.dtype
|
| 246 |
+
|
| 247 |
+
# Computing diagonal n x n blocks.
|
| 248 |
+
dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype)
|
| 249 |
+
dPhi_dy_0[:] = -np.identity(n)
|
| 250 |
+
dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle)
|
| 251 |
+
T = stacked_matmul(df_dy_middle, df_dy[:-1])
|
| 252 |
+
dPhi_dy_0 -= h**2 / 12 * T
|
| 253 |
+
|
| 254 |
+
# Computing off-diagonal n x n blocks.
|
| 255 |
+
dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype)
|
| 256 |
+
dPhi_dy_1[:] = np.identity(n)
|
| 257 |
+
dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle)
|
| 258 |
+
T = stacked_matmul(df_dy_middle, df_dy[1:])
|
| 259 |
+
dPhi_dy_1 += h**2 / 12 * T
|
| 260 |
+
|
| 261 |
+
values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(),
|
| 262 |
+
dbc_dyb.ravel()))
|
| 263 |
+
|
| 264 |
+
if k > 0:
|
| 265 |
+
df_dp = np.transpose(df_dp, (2, 0, 1))
|
| 266 |
+
df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1))
|
| 267 |
+
T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:])
|
| 268 |
+
df_dp_middle += 0.125 * h * T
|
| 269 |
+
dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle)
|
| 270 |
+
values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel()))
|
| 271 |
+
|
| 272 |
+
J = coo_matrix((values, (i_jac, j_jac)))
|
| 273 |
+
return csc_matrix(J)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def collocation_fun(fun, y, p, x, h):
|
| 277 |
+
"""Evaluate collocation residuals.
|
| 278 |
+
|
| 279 |
+
This function lies in the core of the method. The solution is sought
|
| 280 |
+
as a cubic C1 continuous spline with derivatives matching the ODE rhs
|
| 281 |
+
at given nodes `x`. Collocation conditions are formed from the equality
|
| 282 |
+
of the spline derivatives and rhs of the ODE system in the middle points
|
| 283 |
+
between nodes.
|
| 284 |
+
|
| 285 |
+
Such method is classified to Lobbato IIIA family in ODE literature.
|
| 286 |
+
Refer to [1]_ for the formula and some discussion.
|
| 287 |
+
|
| 288 |
+
Returns
|
| 289 |
+
-------
|
| 290 |
+
col_res : ndarray, shape (n, m - 1)
|
| 291 |
+
Collocation residuals at the middle points of the mesh intervals.
|
| 292 |
+
y_middle : ndarray, shape (n, m - 1)
|
| 293 |
+
Values of the cubic spline evaluated at the middle points of the mesh
|
| 294 |
+
intervals.
|
| 295 |
+
f : ndarray, shape (n, m)
|
| 296 |
+
RHS of the ODE system evaluated at the mesh nodes.
|
| 297 |
+
f_middle : ndarray, shape (n, m - 1)
|
| 298 |
+
RHS of the ODE system evaluated at the middle points of the mesh
|
| 299 |
+
intervals (and using `y_middle`).
|
| 300 |
+
|
| 301 |
+
References
|
| 302 |
+
----------
|
| 303 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 304 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 305 |
+
Number 3, pp. 299-316, 2001.
|
| 306 |
+
"""
|
| 307 |
+
f = fun(x, y, p)
|
| 308 |
+
y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
|
| 309 |
+
0.125 * h * (f[:, 1:] - f[:, :-1]))
|
| 310 |
+
f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
|
| 311 |
+
col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
|
| 312 |
+
4 * f_middle)
|
| 313 |
+
|
| 314 |
+
return col_res, y_middle, f, f_middle
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h):
|
| 318 |
+
"""Create the function and the Jacobian for the collocation system."""
|
| 319 |
+
x_middle = x[:-1] + 0.5 * h
|
| 320 |
+
i_jac, j_jac = compute_jac_indices(n, m, k)
|
| 321 |
+
|
| 322 |
+
def col_fun(y, p):
|
| 323 |
+
return collocation_fun(fun, y, p, x, h)
|
| 324 |
+
|
| 325 |
+
def sys_jac(y, p, y_middle, f, f_middle, bc0):
|
| 326 |
+
if fun_jac is None:
|
| 327 |
+
df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f)
|
| 328 |
+
df_dy_middle, df_dp_middle = estimate_fun_jac(
|
| 329 |
+
fun, x_middle, y_middle, p, f_middle)
|
| 330 |
+
else:
|
| 331 |
+
df_dy, df_dp = fun_jac(x, y, p)
|
| 332 |
+
df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p)
|
| 333 |
+
|
| 334 |
+
if bc_jac is None:
|
| 335 |
+
dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1],
|
| 336 |
+
p, bc0)
|
| 337 |
+
else:
|
| 338 |
+
dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p)
|
| 339 |
+
|
| 340 |
+
return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy,
|
| 341 |
+
df_dy_middle, df_dp, df_dp_middle, dbc_dya,
|
| 342 |
+
dbc_dyb, dbc_dp)
|
| 343 |
+
|
| 344 |
+
return col_fun, sys_jac
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol):
|
| 348 |
+
"""Solve the nonlinear collocation system by a Newton method.
|
| 349 |
+
|
| 350 |
+
This is a simple Newton method with a backtracking line search. As
|
| 351 |
+
advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2
|
| 352 |
+
is used, where J is the Jacobian matrix at the current iteration and r is
|
| 353 |
+
the vector or collocation residuals (values of the system lhs).
|
| 354 |
+
|
| 355 |
+
The method alters between full Newton iterations and the fixed-Jacobian
|
| 356 |
+
iterations based
|
| 357 |
+
|
| 358 |
+
There are other tricks proposed in [1]_, but they are not used as they
|
| 359 |
+
don't seem to improve anything significantly, and even break the
|
| 360 |
+
convergence on some test problems I tried.
|
| 361 |
+
|
| 362 |
+
All important parameters of the algorithm are defined inside the function.
|
| 363 |
+
|
| 364 |
+
Parameters
|
| 365 |
+
----------
|
| 366 |
+
n : int
|
| 367 |
+
Number of equations in the ODE system.
|
| 368 |
+
m : int
|
| 369 |
+
Number of nodes in the mesh.
|
| 370 |
+
h : ndarray, shape (m-1,)
|
| 371 |
+
Mesh intervals.
|
| 372 |
+
col_fun : callable
|
| 373 |
+
Function computing collocation residuals.
|
| 374 |
+
bc : callable
|
| 375 |
+
Function computing boundary condition residuals.
|
| 376 |
+
jac : callable
|
| 377 |
+
Function computing the Jacobian of the whole system (including
|
| 378 |
+
collocation and boundary condition residuals). It is supposed to
|
| 379 |
+
return csc_matrix.
|
| 380 |
+
y : ndarray, shape (n, m)
|
| 381 |
+
Initial guess for the function values at the mesh nodes.
|
| 382 |
+
p : ndarray, shape (k,)
|
| 383 |
+
Initial guess for the unknown parameters.
|
| 384 |
+
B : ndarray with shape (n, n) or None
|
| 385 |
+
Matrix to force the S y(a) = 0 condition for a problems with the
|
| 386 |
+
singular term. If None, the singular term is assumed to be absent.
|
| 387 |
+
bvp_tol : float
|
| 388 |
+
Tolerance to which we want to solve a BVP.
|
| 389 |
+
bc_tol : float
|
| 390 |
+
Tolerance to which we want to satisfy the boundary conditions.
|
| 391 |
+
|
| 392 |
+
Returns
|
| 393 |
+
-------
|
| 394 |
+
y : ndarray, shape (n, m)
|
| 395 |
+
Final iterate for the function values at the mesh nodes.
|
| 396 |
+
p : ndarray, shape (k,)
|
| 397 |
+
Final iterate for the unknown parameters.
|
| 398 |
+
singular : bool
|
| 399 |
+
True, if the LU decomposition failed because Jacobian turned out
|
| 400 |
+
to be singular.
|
| 401 |
+
|
| 402 |
+
References
|
| 403 |
+
----------
|
| 404 |
+
.. [1] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
|
| 405 |
+
Boundary Value Problems for Ordinary Differential Equations"
|
| 406 |
+
"""
|
| 407 |
+
# We know that the solution residuals at the middle points of the mesh
|
| 408 |
+
# are connected with collocation residuals r_middle = 1.5 * col_res / h.
|
| 409 |
+
# As our BVP solver tries to decrease relative residuals below a certain
|
| 410 |
+
# tolerance, it seems reasonable to terminated Newton iterations by
|
| 411 |
+
# comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold,
|
| 412 |
+
# which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite
|
| 413 |
+
# the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r
|
| 414 |
+
# should be computed as follows:
|
| 415 |
+
tol_r = 2/3 * h * 5e-2 * bvp_tol
|
| 416 |
+
|
| 417 |
+
# Maximum allowed number of Jacobian evaluation and factorization, in
|
| 418 |
+
# other words, the maximum number of full Newton iterations. A small value
|
| 419 |
+
# is recommended in the literature.
|
| 420 |
+
max_njev = 4
|
| 421 |
+
|
| 422 |
+
# Maximum number of iterations, considering that some of them can be
|
| 423 |
+
# performed with the fixed Jacobian. In theory, such iterations are cheap,
|
| 424 |
+
# but it's not that simple in Python.
|
| 425 |
+
max_iter = 8
|
| 426 |
+
|
| 427 |
+
# Minimum relative improvement of the criterion function to accept the
|
| 428 |
+
# step (Armijo constant).
|
| 429 |
+
sigma = 0.2
|
| 430 |
+
|
| 431 |
+
# Step size decrease factor for backtracking.
|
| 432 |
+
tau = 0.5
|
| 433 |
+
|
| 434 |
+
# Maximum number of backtracking steps, the minimum step is then
|
| 435 |
+
# tau ** n_trial.
|
| 436 |
+
n_trial = 4
|
| 437 |
+
|
| 438 |
+
col_res, y_middle, f, f_middle = col_fun(y, p)
|
| 439 |
+
bc_res = bc(y[:, 0], y[:, -1], p)
|
| 440 |
+
res = np.hstack((col_res.ravel(order='F'), bc_res))
|
| 441 |
+
|
| 442 |
+
njev = 0
|
| 443 |
+
singular = False
|
| 444 |
+
recompute_jac = True
|
| 445 |
+
for iteration in range(max_iter):
|
| 446 |
+
if recompute_jac:
|
| 447 |
+
J = jac(y, p, y_middle, f, f_middle, bc_res)
|
| 448 |
+
njev += 1
|
| 449 |
+
try:
|
| 450 |
+
LU = splu(J)
|
| 451 |
+
except RuntimeError:
|
| 452 |
+
singular = True
|
| 453 |
+
break
|
| 454 |
+
|
| 455 |
+
step = LU.solve(res)
|
| 456 |
+
cost = np.dot(step, step)
|
| 457 |
+
|
| 458 |
+
y_step = step[:m * n].reshape((n, m), order='F')
|
| 459 |
+
p_step = step[m * n:]
|
| 460 |
+
|
| 461 |
+
alpha = 1
|
| 462 |
+
for trial in range(n_trial + 1):
|
| 463 |
+
y_new = y - alpha * y_step
|
| 464 |
+
if B is not None:
|
| 465 |
+
y_new[:, 0] = np.dot(B, y_new[:, 0])
|
| 466 |
+
p_new = p - alpha * p_step
|
| 467 |
+
|
| 468 |
+
col_res, y_middle, f, f_middle = col_fun(y_new, p_new)
|
| 469 |
+
bc_res = bc(y_new[:, 0], y_new[:, -1], p_new)
|
| 470 |
+
res = np.hstack((col_res.ravel(order='F'), bc_res))
|
| 471 |
+
|
| 472 |
+
step_new = LU.solve(res)
|
| 473 |
+
cost_new = np.dot(step_new, step_new)
|
| 474 |
+
if cost_new < (1 - 2 * alpha * sigma) * cost:
|
| 475 |
+
break
|
| 476 |
+
|
| 477 |
+
if trial < n_trial:
|
| 478 |
+
alpha *= tau
|
| 479 |
+
|
| 480 |
+
y = y_new
|
| 481 |
+
p = p_new
|
| 482 |
+
|
| 483 |
+
if njev == max_njev:
|
| 484 |
+
break
|
| 485 |
+
|
| 486 |
+
if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and
|
| 487 |
+
np.all(np.abs(bc_res) < bc_tol)):
|
| 488 |
+
break
|
| 489 |
+
|
| 490 |
+
# If the full step was taken, then we are going to continue with
|
| 491 |
+
# the same Jacobian. This is the approach of BVP_SOLVER.
|
| 492 |
+
if alpha == 1:
|
| 493 |
+
step = step_new
|
| 494 |
+
cost = cost_new
|
| 495 |
+
recompute_jac = False
|
| 496 |
+
else:
|
| 497 |
+
recompute_jac = True
|
| 498 |
+
|
| 499 |
+
return y, p, singular
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def print_iteration_header():
|
| 503 |
+
print("{:^15}{:^15}{:^15}{:^15}{:^15}".format(
|
| 504 |
+
"Iteration", "Max residual", "Max BC residual", "Total nodes",
|
| 505 |
+
"Nodes added"))
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def print_iteration_progress(iteration, residual, bc_residual, total_nodes,
|
| 509 |
+
nodes_added):
|
| 510 |
+
print("{:^15}{:^15.2e}{:^15.2e}{:^15}{:^15}".format(
|
| 511 |
+
iteration, residual, bc_residual, total_nodes, nodes_added))
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
class BVPResult(OptimizeResult):
|
| 515 |
+
pass
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
TERMINATION_MESSAGES = {
|
| 519 |
+
0: "The algorithm converged to the desired accuracy.",
|
| 520 |
+
1: "The maximum number of mesh nodes is exceeded.",
|
| 521 |
+
2: "A singular Jacobian encountered when solving the collocation system.",
|
| 522 |
+
3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10."
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle):
|
| 527 |
+
"""Estimate rms values of collocation residuals using Lobatto quadrature.
|
| 528 |
+
|
| 529 |
+
The residuals are defined as the difference between the derivatives of
|
| 530 |
+
our solution and rhs of the ODE system. We use relative residuals, i.e.,
|
| 531 |
+
normalized by 1 + np.abs(f). RMS values are computed as sqrt from the
|
| 532 |
+
normalized integrals of the squared relative residuals over each interval.
|
| 533 |
+
Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the
|
| 534 |
+
fact that residuals at the mesh nodes are identically zero.
|
| 535 |
+
|
| 536 |
+
In [2] they don't normalize integrals by interval lengths, which gives
|
| 537 |
+
a higher rate of convergence of the residuals by the factor of h**0.5.
|
| 538 |
+
I chose to do such normalization for an ease of interpretation of return
|
| 539 |
+
values as RMS estimates.
|
| 540 |
+
|
| 541 |
+
Returns
|
| 542 |
+
-------
|
| 543 |
+
rms_res : ndarray, shape (m - 1,)
|
| 544 |
+
Estimated rms values of the relative residuals over each interval.
|
| 545 |
+
|
| 546 |
+
References
|
| 547 |
+
----------
|
| 548 |
+
.. [1] http://mathworld.wolfram.com/LobattoQuadrature.html
|
| 549 |
+
.. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 550 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 551 |
+
Number 3, pp. 299-316, 2001.
|
| 552 |
+
"""
|
| 553 |
+
x_middle = x[:-1] + 0.5 * h
|
| 554 |
+
s = 0.5 * h * (3/7)**0.5
|
| 555 |
+
x1 = x_middle + s
|
| 556 |
+
x2 = x_middle - s
|
| 557 |
+
y1 = sol(x1)
|
| 558 |
+
y2 = sol(x2)
|
| 559 |
+
y1_prime = sol(x1, 1)
|
| 560 |
+
y2_prime = sol(x2, 1)
|
| 561 |
+
f1 = fun(x1, y1, p)
|
| 562 |
+
f2 = fun(x2, y2, p)
|
| 563 |
+
r1 = y1_prime - f1
|
| 564 |
+
r2 = y2_prime - f2
|
| 565 |
+
|
| 566 |
+
r_middle /= 1 + np.abs(f_middle)
|
| 567 |
+
r1 /= 1 + np.abs(f1)
|
| 568 |
+
r2 /= 1 + np.abs(f2)
|
| 569 |
+
|
| 570 |
+
r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0)
|
| 571 |
+
r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0)
|
| 572 |
+
r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0)
|
| 573 |
+
|
| 574 |
+
return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def create_spline(y, yp, x, h):
|
| 578 |
+
"""Create a cubic spline given values and derivatives.
|
| 579 |
+
|
| 580 |
+
Formulas for the coefficients are taken from interpolate.CubicSpline.
|
| 581 |
+
|
| 582 |
+
Returns
|
| 583 |
+
-------
|
| 584 |
+
sol : PPoly
|
| 585 |
+
Constructed spline as a PPoly instance.
|
| 586 |
+
"""
|
| 587 |
+
from scipy.interpolate import PPoly
|
| 588 |
+
|
| 589 |
+
n, m = y.shape
|
| 590 |
+
c = np.empty((4, n, m - 1), dtype=y.dtype)
|
| 591 |
+
slope = (y[:, 1:] - y[:, :-1]) / h
|
| 592 |
+
t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h
|
| 593 |
+
c[0] = t / h
|
| 594 |
+
c[1] = (slope - yp[:, :-1]) / h - t
|
| 595 |
+
c[2] = yp[:, :-1]
|
| 596 |
+
c[3] = y[:, :-1]
|
| 597 |
+
c = np.moveaxis(c, 1, 0)
|
| 598 |
+
|
| 599 |
+
return PPoly(c, x, extrapolate=True, axis=1)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def modify_mesh(x, insert_1, insert_2):
|
| 603 |
+
"""Insert nodes into a mesh.
|
| 604 |
+
|
| 605 |
+
Nodes removal logic is not established, its impact on the solver is
|
| 606 |
+
presumably negligible. So, only insertion is done in this function.
|
| 607 |
+
|
| 608 |
+
Parameters
|
| 609 |
+
----------
|
| 610 |
+
x : ndarray, shape (m,)
|
| 611 |
+
Mesh nodes.
|
| 612 |
+
insert_1 : ndarray
|
| 613 |
+
Intervals to each insert 1 new node in the middle.
|
| 614 |
+
insert_2 : ndarray
|
| 615 |
+
Intervals to each insert 2 new nodes, such that divide an interval
|
| 616 |
+
into 3 equal parts.
|
| 617 |
+
|
| 618 |
+
Returns
|
| 619 |
+
-------
|
| 620 |
+
x_new : ndarray
|
| 621 |
+
New mesh nodes.
|
| 622 |
+
|
| 623 |
+
Notes
|
| 624 |
+
-----
|
| 625 |
+
`insert_1` and `insert_2` should not have common values.
|
| 626 |
+
"""
|
| 627 |
+
# Because np.insert implementation apparently varies with a version of
|
| 628 |
+
# NumPy, we use a simple and reliable approach with sorting.
|
| 629 |
+
return np.sort(np.hstack((
|
| 630 |
+
x,
|
| 631 |
+
0.5 * (x[insert_1] + x[insert_1 + 1]),
|
| 632 |
+
(2 * x[insert_2] + x[insert_2 + 1]) / 3,
|
| 633 |
+
(x[insert_2] + 2 * x[insert_2 + 1]) / 3
|
| 634 |
+
)))
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
|
| 638 |
+
"""Wrap functions for unified usage in the solver."""
|
| 639 |
+
if fun_jac is None:
|
| 640 |
+
fun_jac_wrapped = None
|
| 641 |
+
|
| 642 |
+
if bc_jac is None:
|
| 643 |
+
bc_jac_wrapped = None
|
| 644 |
+
|
| 645 |
+
if k == 0:
|
| 646 |
+
def fun_p(x, y, _):
|
| 647 |
+
return np.asarray(fun(x, y), dtype)
|
| 648 |
+
|
| 649 |
+
def bc_wrapped(ya, yb, _):
|
| 650 |
+
return np.asarray(bc(ya, yb), dtype)
|
| 651 |
+
|
| 652 |
+
if fun_jac is not None:
|
| 653 |
+
def fun_jac_p(x, y, _):
|
| 654 |
+
return np.asarray(fun_jac(x, y), dtype), None
|
| 655 |
+
|
| 656 |
+
if bc_jac is not None:
|
| 657 |
+
def bc_jac_wrapped(ya, yb, _):
|
| 658 |
+
dbc_dya, dbc_dyb = bc_jac(ya, yb)
|
| 659 |
+
return (np.asarray(dbc_dya, dtype),
|
| 660 |
+
np.asarray(dbc_dyb, dtype), None)
|
| 661 |
+
else:
|
| 662 |
+
def fun_p(x, y, p):
|
| 663 |
+
return np.asarray(fun(x, y, p), dtype)
|
| 664 |
+
|
| 665 |
+
def bc_wrapped(x, y, p):
|
| 666 |
+
return np.asarray(bc(x, y, p), dtype)
|
| 667 |
+
|
| 668 |
+
if fun_jac is not None:
|
| 669 |
+
def fun_jac_p(x, y, p):
|
| 670 |
+
df_dy, df_dp = fun_jac(x, y, p)
|
| 671 |
+
return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
|
| 672 |
+
|
| 673 |
+
if bc_jac is not None:
|
| 674 |
+
def bc_jac_wrapped(ya, yb, p):
|
| 675 |
+
dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
|
| 676 |
+
return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
|
| 677 |
+
np.asarray(dbc_dp, dtype))
|
| 678 |
+
|
| 679 |
+
if S is None:
|
| 680 |
+
fun_wrapped = fun_p
|
| 681 |
+
else:
|
| 682 |
+
def fun_wrapped(x, y, p):
|
| 683 |
+
f = fun_p(x, y, p)
|
| 684 |
+
if x[0] == a:
|
| 685 |
+
f[:, 0] = np.dot(D, f[:, 0])
|
| 686 |
+
f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a)
|
| 687 |
+
else:
|
| 688 |
+
f += np.dot(S, y) / (x - a)
|
| 689 |
+
return f
|
| 690 |
+
|
| 691 |
+
if fun_jac is not None:
|
| 692 |
+
if S is None:
|
| 693 |
+
fun_jac_wrapped = fun_jac_p
|
| 694 |
+
else:
|
| 695 |
+
Sr = S[:, :, np.newaxis]
|
| 696 |
+
|
| 697 |
+
def fun_jac_wrapped(x, y, p):
|
| 698 |
+
df_dy, df_dp = fun_jac_p(x, y, p)
|
| 699 |
+
if x[0] == a:
|
| 700 |
+
df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0])
|
| 701 |
+
df_dy[:, :, 1:] += Sr / (x[1:] - a)
|
| 702 |
+
else:
|
| 703 |
+
df_dy += Sr / (x - a)
|
| 704 |
+
|
| 705 |
+
return df_dy, df_dp
|
| 706 |
+
|
| 707 |
+
return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None,
|
| 711 |
+
tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None):
|
| 712 |
+
"""Solve a boundary value problem for a system of ODEs.
|
| 713 |
+
|
| 714 |
+
This function numerically solves a first order system of ODEs subject to
|
| 715 |
+
two-point boundary conditions::
|
| 716 |
+
|
| 717 |
+
dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b
|
| 718 |
+
bc(y(a), y(b), p) = 0
|
| 719 |
+
|
| 720 |
+
Here x is a 1-D independent variable, y(x) is an N-D
|
| 721 |
+
vector-valued function and p is a k-D vector of unknown
|
| 722 |
+
parameters which is to be found along with y(x). For the problem to be
|
| 723 |
+
determined, there must be n + k boundary conditions, i.e., bc must be an
|
| 724 |
+
(n + k)-D function.
|
| 725 |
+
|
| 726 |
+
The last singular term on the right-hand side of the system is optional.
|
| 727 |
+
It is defined by an n-by-n matrix S, such that the solution must satisfy
|
| 728 |
+
S y(a) = 0. This condition will be forced during iterations, so it must not
|
| 729 |
+
contradict boundary conditions. See [2]_ for the explanation how this term
|
| 730 |
+
is handled when solving BVPs numerically.
|
| 731 |
+
|
| 732 |
+
Problems in a complex domain can be solved as well. In this case, y and p
|
| 733 |
+
are considered to be complex, and f and bc are assumed to be complex-valued
|
| 734 |
+
functions, but x stays real. Note that f and bc must be complex
|
| 735 |
+
differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you
|
| 736 |
+
should rewrite your problem for real and imaginary parts separately. To
|
| 737 |
+
solve a problem in a complex domain, pass an initial guess for y with a
|
| 738 |
+
complex data type (see below).
|
| 739 |
+
|
| 740 |
+
Parameters
|
| 741 |
+
----------
|
| 742 |
+
fun : callable
|
| 743 |
+
Right-hand side of the system. The calling signature is ``fun(x, y)``,
|
| 744 |
+
or ``fun(x, y, p)`` if parameters are present. All arguments are
|
| 745 |
+
ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that
|
| 746 |
+
``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The
|
| 747 |
+
return value must be an array with shape (n, m) and with the same
|
| 748 |
+
layout as ``y``.
|
| 749 |
+
bc : callable
|
| 750 |
+
Function evaluating residuals of the boundary conditions. The calling
|
| 751 |
+
signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are
|
| 752 |
+
present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,),
|
| 753 |
+
and ``p`` with shape (k,). The return value must be an array with
|
| 754 |
+
shape (n + k,).
|
| 755 |
+
x : array_like, shape (m,)
|
| 756 |
+
Initial mesh. Must be a strictly increasing sequence of real numbers
|
| 757 |
+
with ``x[0]=a`` and ``x[-1]=b``.
|
| 758 |
+
y : array_like, shape (n, m)
|
| 759 |
+
Initial guess for the function values at the mesh nodes, ith column
|
| 760 |
+
corresponds to ``x[i]``. For problems in a complex domain pass `y`
|
| 761 |
+
with a complex data type (even if the initial guess is purely real).
|
| 762 |
+
p : array_like with shape (k,) or None, optional
|
| 763 |
+
Initial guess for the unknown parameters. If None (default), it is
|
| 764 |
+
assumed that the problem doesn't depend on any parameters.
|
| 765 |
+
S : array_like with shape (n, n) or None
|
| 766 |
+
Matrix defining the singular term. If None (default), the problem is
|
| 767 |
+
solved without the singular term.
|
| 768 |
+
fun_jac : callable or None, optional
|
| 769 |
+
Function computing derivatives of f with respect to y and p. The
|
| 770 |
+
calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if
|
| 771 |
+
parameters are present. The return must contain 1 or 2 elements in the
|
| 772 |
+
following order:
|
| 773 |
+
|
| 774 |
+
* df_dy : array_like with shape (n, n, m), where an element
|
| 775 |
+
(i, j, q) equals to d f_i(x_q, y_q, p) / d (y_q)_j.
|
| 776 |
+
* df_dp : array_like with shape (n, k, m), where an element
|
| 777 |
+
(i, j, q) equals to d f_i(x_q, y_q, p) / d p_j.
|
| 778 |
+
|
| 779 |
+
Here q numbers nodes at which x and y are defined, whereas i and j
|
| 780 |
+
number vector components. If the problem is solved without unknown
|
| 781 |
+
parameters, df_dp should not be returned.
|
| 782 |
+
|
| 783 |
+
If `fun_jac` is None (default), the derivatives will be estimated
|
| 784 |
+
by the forward finite differences.
|
| 785 |
+
bc_jac : callable or None, optional
|
| 786 |
+
Function computing derivatives of bc with respect to ya, yb, and p.
|
| 787 |
+
The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)``
|
| 788 |
+
if parameters are present. The return must contain 2 or 3 elements in
|
| 789 |
+
the following order:
|
| 790 |
+
|
| 791 |
+
* dbc_dya : array_like with shape (n, n), where an element (i, j)
|
| 792 |
+
equals to d bc_i(ya, yb, p) / d ya_j.
|
| 793 |
+
* dbc_dyb : array_like with shape (n, n), where an element (i, j)
|
| 794 |
+
equals to d bc_i(ya, yb, p) / d yb_j.
|
| 795 |
+
* dbc_dp : array_like with shape (n, k), where an element (i, j)
|
| 796 |
+
equals to d bc_i(ya, yb, p) / d p_j.
|
| 797 |
+
|
| 798 |
+
If the problem is solved without unknown parameters, dbc_dp should not
|
| 799 |
+
be returned.
|
| 800 |
+
|
| 801 |
+
If `bc_jac` is None (default), the derivatives will be estimated by
|
| 802 |
+
the forward finite differences.
|
| 803 |
+
tol : float, optional
|
| 804 |
+
Desired tolerance of the solution. If we define ``r = y' - f(x, y)``,
|
| 805 |
+
where y is the found solution, then the solver tries to achieve on each
|
| 806 |
+
mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is
|
| 807 |
+
estimated in a root mean squared sense (using a numerical quadrature
|
| 808 |
+
formula). Default is 1e-3.
|
| 809 |
+
max_nodes : int, optional
|
| 810 |
+
Maximum allowed number of the mesh nodes. If exceeded, the algorithm
|
| 811 |
+
terminates. Default is 1000.
|
| 812 |
+
verbose : {0, 1, 2}, optional
|
| 813 |
+
Level of algorithm's verbosity:
|
| 814 |
+
|
| 815 |
+
* 0 (default) : work silently.
|
| 816 |
+
* 1 : display a termination report.
|
| 817 |
+
* 2 : display progress during iterations.
|
| 818 |
+
bc_tol : float, optional
|
| 819 |
+
Desired absolute tolerance for the boundary condition residuals: `bc`
|
| 820 |
+
value should satisfy ``abs(bc) < bc_tol`` component-wise.
|
| 821 |
+
Equals to `tol` by default. Up to 10 iterations are allowed to achieve this
|
| 822 |
+
tolerance.
|
| 823 |
+
|
| 824 |
+
Returns
|
| 825 |
+
-------
|
| 826 |
+
Bunch object with the following fields defined:
|
| 827 |
+
sol : PPoly
|
| 828 |
+
Found solution for y as `scipy.interpolate.PPoly` instance, a C1
|
| 829 |
+
continuous cubic spline.
|
| 830 |
+
p : ndarray or None, shape (k,)
|
| 831 |
+
Found parameters. None, if the parameters were not present in the
|
| 832 |
+
problem.
|
| 833 |
+
x : ndarray, shape (m,)
|
| 834 |
+
Nodes of the final mesh.
|
| 835 |
+
y : ndarray, shape (n, m)
|
| 836 |
+
Solution values at the mesh nodes.
|
| 837 |
+
yp : ndarray, shape (n, m)
|
| 838 |
+
Solution derivatives at the mesh nodes.
|
| 839 |
+
rms_residuals : ndarray, shape (m - 1,)
|
| 840 |
+
RMS values of the relative residuals over each mesh interval (see the
|
| 841 |
+
description of `tol` parameter).
|
| 842 |
+
niter : int
|
| 843 |
+
Number of completed iterations.
|
| 844 |
+
status : int
|
| 845 |
+
Reason for algorithm termination:
|
| 846 |
+
|
| 847 |
+
* 0: The algorithm converged to the desired accuracy.
|
| 848 |
+
* 1: The maximum number of mesh nodes is exceeded.
|
| 849 |
+
* 2: A singular Jacobian encountered when solving the collocation
|
| 850 |
+
system.
|
| 851 |
+
|
| 852 |
+
message : string
|
| 853 |
+
Verbal description of the termination reason.
|
| 854 |
+
success : bool
|
| 855 |
+
True if the algorithm converged to the desired accuracy (``status=0``).
|
| 856 |
+
|
| 857 |
+
Notes
|
| 858 |
+
-----
|
| 859 |
+
This function implements a 4th order collocation algorithm with the
|
| 860 |
+
control of residuals similar to [1]_. A collocation system is solved
|
| 861 |
+
by a damped Newton method with an affine-invariant criterion function as
|
| 862 |
+
described in [3]_.
|
| 863 |
+
|
| 864 |
+
Note that in [1]_ integral residuals are defined without normalization
|
| 865 |
+
by interval lengths. So, their definition is different by a multiplier of
|
| 866 |
+
h**0.5 (h is an interval length) from the definition used here.
|
| 867 |
+
|
| 868 |
+
.. versionadded:: 0.18.0
|
| 869 |
+
|
| 870 |
+
References
|
| 871 |
+
----------
|
| 872 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 873 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 874 |
+
Number 3, pp. 299-316, 2001.
|
| 875 |
+
.. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP
|
| 876 |
+
Solver".
|
| 877 |
+
.. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
|
| 878 |
+
Boundary Value Problems for Ordinary Differential Equations".
|
| 879 |
+
.. [4] `Cauchy-Riemann equations
|
| 880 |
+
<https://en.wikipedia.org/wiki/Cauchy-Riemann_equations>`_ on
|
| 881 |
+
Wikipedia.
|
| 882 |
+
|
| 883 |
+
Examples
|
| 884 |
+
--------
|
| 885 |
+
In the first example, we solve Bratu's problem::
|
| 886 |
+
|
| 887 |
+
y'' + k * exp(y) = 0
|
| 888 |
+
y(0) = y(1) = 0
|
| 889 |
+
|
| 890 |
+
for k = 1.
|
| 891 |
+
|
| 892 |
+
We rewrite the equation as a first-order system and implement its
|
| 893 |
+
right-hand side evaluation::
|
| 894 |
+
|
| 895 |
+
y1' = y2
|
| 896 |
+
y2' = -exp(y1)
|
| 897 |
+
|
| 898 |
+
>>> import numpy as np
|
| 899 |
+
>>> def fun(x, y):
|
| 900 |
+
... return np.vstack((y[1], -np.exp(y[0])))
|
| 901 |
+
|
| 902 |
+
Implement evaluation of the boundary condition residuals:
|
| 903 |
+
|
| 904 |
+
>>> def bc(ya, yb):
|
| 905 |
+
... return np.array([ya[0], yb[0]])
|
| 906 |
+
|
| 907 |
+
Define the initial mesh with 5 nodes:
|
| 908 |
+
|
| 909 |
+
>>> x = np.linspace(0, 1, 5)
|
| 910 |
+
|
| 911 |
+
This problem is known to have two solutions. To obtain both of them, we
|
| 912 |
+
use two different initial guesses for y. We denote them by subscripts
|
| 913 |
+
a and b.
|
| 914 |
+
|
| 915 |
+
>>> y_a = np.zeros((2, x.size))
|
| 916 |
+
>>> y_b = np.zeros((2, x.size))
|
| 917 |
+
>>> y_b[0] = 3
|
| 918 |
+
|
| 919 |
+
Now we are ready to run the solver.
|
| 920 |
+
|
| 921 |
+
>>> from scipy.integrate import solve_bvp
|
| 922 |
+
>>> res_a = solve_bvp(fun, bc, x, y_a)
|
| 923 |
+
>>> res_b = solve_bvp(fun, bc, x, y_b)
|
| 924 |
+
|
| 925 |
+
Let's plot the two found solutions. We take an advantage of having the
|
| 926 |
+
solution in a spline form to produce a smooth plot.
|
| 927 |
+
|
| 928 |
+
>>> x_plot = np.linspace(0, 1, 100)
|
| 929 |
+
>>> y_plot_a = res_a.sol(x_plot)[0]
|
| 930 |
+
>>> y_plot_b = res_b.sol(x_plot)[0]
|
| 931 |
+
>>> import matplotlib.pyplot as plt
|
| 932 |
+
>>> plt.plot(x_plot, y_plot_a, label='y_a')
|
| 933 |
+
>>> plt.plot(x_plot, y_plot_b, label='y_b')
|
| 934 |
+
>>> plt.legend()
|
| 935 |
+
>>> plt.xlabel("x")
|
| 936 |
+
>>> plt.ylabel("y")
|
| 937 |
+
>>> plt.show()
|
| 938 |
+
|
| 939 |
+
We see that the two solutions have similar shape, but differ in scale
|
| 940 |
+
significantly.
|
| 941 |
+
|
| 942 |
+
In the second example, we solve a simple Sturm-Liouville problem::
|
| 943 |
+
|
| 944 |
+
y'' + k**2 * y = 0
|
| 945 |
+
y(0) = y(1) = 0
|
| 946 |
+
|
| 947 |
+
It is known that a non-trivial solution y = A * sin(k * x) is possible for
|
| 948 |
+
k = pi * n, where n is an integer. To establish the normalization constant
|
| 949 |
+
A = 1 we add a boundary condition::
|
| 950 |
+
|
| 951 |
+
y'(0) = k
|
| 952 |
+
|
| 953 |
+
Again, we rewrite our equation as a first-order system and implement its
|
| 954 |
+
right-hand side evaluation::
|
| 955 |
+
|
| 956 |
+
y1' = y2
|
| 957 |
+
y2' = -k**2 * y1
|
| 958 |
+
|
| 959 |
+
>>> def fun(x, y, p):
|
| 960 |
+
... k = p[0]
|
| 961 |
+
... return np.vstack((y[1], -k**2 * y[0]))
|
| 962 |
+
|
| 963 |
+
Note that parameters p are passed as a vector (with one element in our
|
| 964 |
+
case).
|
| 965 |
+
|
| 966 |
+
Implement the boundary conditions:
|
| 967 |
+
|
| 968 |
+
>>> def bc(ya, yb, p):
|
| 969 |
+
... k = p[0]
|
| 970 |
+
... return np.array([ya[0], yb[0], ya[1] - k])
|
| 971 |
+
|
| 972 |
+
Set up the initial mesh and guess for y. We aim to find the solution for
|
| 973 |
+
k = 2 * pi, to achieve that we set values of y to approximately follow
|
| 974 |
+
sin(2 * pi * x):
|
| 975 |
+
|
| 976 |
+
>>> x = np.linspace(0, 1, 5)
|
| 977 |
+
>>> y = np.zeros((2, x.size))
|
| 978 |
+
>>> y[0, 1] = 1
|
| 979 |
+
>>> y[0, 3] = -1
|
| 980 |
+
|
| 981 |
+
Run the solver with 6 as an initial guess for k.
|
| 982 |
+
|
| 983 |
+
>>> sol = solve_bvp(fun, bc, x, y, p=[6])
|
| 984 |
+
|
| 985 |
+
We see that the found k is approximately correct:
|
| 986 |
+
|
| 987 |
+
>>> sol.p[0]
|
| 988 |
+
6.28329460046
|
| 989 |
+
|
| 990 |
+
And, finally, plot the solution to see the anticipated sinusoid:
|
| 991 |
+
|
| 992 |
+
>>> x_plot = np.linspace(0, 1, 100)
|
| 993 |
+
>>> y_plot = sol.sol(x_plot)[0]
|
| 994 |
+
>>> plt.plot(x_plot, y_plot)
|
| 995 |
+
>>> plt.xlabel("x")
|
| 996 |
+
>>> plt.ylabel("y")
|
| 997 |
+
>>> plt.show()
|
| 998 |
+
"""
|
| 999 |
+
x = np.asarray(x, dtype=float)
|
| 1000 |
+
if x.ndim != 1:
|
| 1001 |
+
raise ValueError("`x` must be 1 dimensional.")
|
| 1002 |
+
h = np.diff(x)
|
| 1003 |
+
if np.any(h <= 0):
|
| 1004 |
+
raise ValueError("`x` must be strictly increasing.")
|
| 1005 |
+
a = x[0]
|
| 1006 |
+
|
| 1007 |
+
y = np.asarray(y)
|
| 1008 |
+
if np.issubdtype(y.dtype, np.complexfloating):
|
| 1009 |
+
dtype = complex
|
| 1010 |
+
else:
|
| 1011 |
+
dtype = float
|
| 1012 |
+
y = y.astype(dtype, copy=False)
|
| 1013 |
+
|
| 1014 |
+
if y.ndim != 2:
|
| 1015 |
+
raise ValueError("`y` must be 2 dimensional.")
|
| 1016 |
+
if y.shape[1] != x.shape[0]:
|
| 1017 |
+
raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually "
|
| 1018 |
+
f"has {y.shape[1]}.")
|
| 1019 |
+
|
| 1020 |
+
if p is None:
|
| 1021 |
+
p = np.array([])
|
| 1022 |
+
else:
|
| 1023 |
+
p = np.asarray(p, dtype=dtype)
|
| 1024 |
+
if p.ndim != 1:
|
| 1025 |
+
raise ValueError("`p` must be 1 dimensional.")
|
| 1026 |
+
|
| 1027 |
+
if tol < 100 * EPS:
|
| 1028 |
+
warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2)
|
| 1029 |
+
tol = 100 * EPS
|
| 1030 |
+
|
| 1031 |
+
if verbose not in [0, 1, 2]:
|
| 1032 |
+
raise ValueError("`verbose` must be in [0, 1, 2].")
|
| 1033 |
+
|
| 1034 |
+
n = y.shape[0]
|
| 1035 |
+
k = p.shape[0]
|
| 1036 |
+
|
| 1037 |
+
if S is not None:
|
| 1038 |
+
S = np.asarray(S, dtype=dtype)
|
| 1039 |
+
if S.shape != (n, n):
|
| 1040 |
+
raise ValueError(f"`S` is expected to have shape {(n, n)}, "
|
| 1041 |
+
f"but actually has {S.shape}")
|
| 1042 |
+
|
| 1043 |
+
# Compute I - S^+ S to impose necessary boundary conditions.
|
| 1044 |
+
B = np.identity(n) - np.dot(pinv(S), S)
|
| 1045 |
+
|
| 1046 |
+
y[:, 0] = np.dot(B, y[:, 0])
|
| 1047 |
+
|
| 1048 |
+
# Compute (I - S)^+ to correct derivatives at x=a.
|
| 1049 |
+
D = pinv(np.identity(n) - S)
|
| 1050 |
+
else:
|
| 1051 |
+
B = None
|
| 1052 |
+
D = None
|
| 1053 |
+
|
| 1054 |
+
if bc_tol is None:
|
| 1055 |
+
bc_tol = tol
|
| 1056 |
+
|
| 1057 |
+
# Maximum number of iterations
|
| 1058 |
+
max_iteration = 10
|
| 1059 |
+
|
| 1060 |
+
fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
|
| 1061 |
+
fun, bc, fun_jac, bc_jac, k, a, S, D, dtype)
|
| 1062 |
+
|
| 1063 |
+
f = fun_wrapped(x, y, p)
|
| 1064 |
+
if f.shape != y.shape:
|
| 1065 |
+
raise ValueError(f"`fun` return is expected to have shape {y.shape}, "
|
| 1066 |
+
f"but actually has {f.shape}.")
|
| 1067 |
+
|
| 1068 |
+
bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
|
| 1069 |
+
if bc_res.shape != (n + k,):
|
| 1070 |
+
raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, "
|
| 1071 |
+
f"but actually has {bc_res.shape}.")
|
| 1072 |
+
|
| 1073 |
+
status = 0
|
| 1074 |
+
iteration = 0
|
| 1075 |
+
if verbose == 2:
|
| 1076 |
+
print_iteration_header()
|
| 1077 |
+
|
| 1078 |
+
while True:
|
| 1079 |
+
m = x.shape[0]
|
| 1080 |
+
|
| 1081 |
+
col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped,
|
| 1082 |
+
fun_jac_wrapped, bc_jac_wrapped, x, h)
|
| 1083 |
+
y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
|
| 1084 |
+
y, p, B, tol, bc_tol)
|
| 1085 |
+
iteration += 1
|
| 1086 |
+
|
| 1087 |
+
col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y,
|
| 1088 |
+
p, x, h)
|
| 1089 |
+
bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
|
| 1090 |
+
max_bc_res = np.max(abs(bc_res))
|
| 1091 |
+
|
| 1092 |
+
# This relation is not trivial, but can be verified.
|
| 1093 |
+
r_middle = 1.5 * col_res / h
|
| 1094 |
+
sol = create_spline(y, f, x, h)
|
| 1095 |
+
rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p,
|
| 1096 |
+
r_middle, f_middle)
|
| 1097 |
+
max_rms_res = np.max(rms_res)
|
| 1098 |
+
|
| 1099 |
+
if singular:
|
| 1100 |
+
status = 2
|
| 1101 |
+
break
|
| 1102 |
+
|
| 1103 |
+
insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol))
|
| 1104 |
+
insert_2, = np.nonzero(rms_res >= 100 * tol)
|
| 1105 |
+
nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0]
|
| 1106 |
+
|
| 1107 |
+
if m + nodes_added > max_nodes:
|
| 1108 |
+
status = 1
|
| 1109 |
+
if verbose == 2:
|
| 1110 |
+
nodes_added = f"({nodes_added})"
|
| 1111 |
+
print_iteration_progress(iteration, max_rms_res, max_bc_res,
|
| 1112 |
+
m, nodes_added)
|
| 1113 |
+
break
|
| 1114 |
+
|
| 1115 |
+
if verbose == 2:
|
| 1116 |
+
print_iteration_progress(iteration, max_rms_res, max_bc_res, m,
|
| 1117 |
+
nodes_added)
|
| 1118 |
+
|
| 1119 |
+
if nodes_added > 0:
|
| 1120 |
+
x = modify_mesh(x, insert_1, insert_2)
|
| 1121 |
+
h = np.diff(x)
|
| 1122 |
+
y = sol(x)
|
| 1123 |
+
elif max_bc_res <= bc_tol:
|
| 1124 |
+
status = 0
|
| 1125 |
+
break
|
| 1126 |
+
elif iteration >= max_iteration:
|
| 1127 |
+
status = 3
|
| 1128 |
+
break
|
| 1129 |
+
|
| 1130 |
+
if verbose > 0:
|
| 1131 |
+
if status == 0:
|
| 1132 |
+
print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n"
|
| 1133 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1134 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1135 |
+
elif status == 1:
|
| 1136 |
+
print(f"Number of nodes is exceeded after iteration {iteration}. \n"
|
| 1137 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1138 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1139 |
+
elif status == 2:
|
| 1140 |
+
print("Singular Jacobian encountered when solving the collocation "
|
| 1141 |
+
f"system on iteration {iteration}. \n"
|
| 1142 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1143 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1144 |
+
elif status == 3:
|
| 1145 |
+
print("The solver was unable to satisfy boundary conditions "
|
| 1146 |
+
f"tolerance on iteration {iteration}. \n"
|
| 1147 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1148 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1149 |
+
|
| 1150 |
+
if p.size == 0:
|
| 1151 |
+
p = None
|
| 1152 |
+
|
| 1153 |
+
return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res,
|
| 1154 |
+
niter=iteration, status=status,
|
| 1155 |
+
message=TERMINATION_MESSAGES[status], success=status == 0)
|
parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (535 Bytes). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc
ADDED
|
Binary file (10.8 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc
ADDED
|
Binary file (4.91 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc
ADDED
|
Binary file (29.3 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc
ADDED
|
Binary file (8.49 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from scipy.integrate import ode
|
| 3 |
+
from .common import validate_tol, validate_first_step, warn_extraneous
|
| 4 |
+
from .base import OdeSolver, DenseOutput
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class LSODA(OdeSolver):
|
| 8 |
+
"""Adams/BDF method with automatic stiffness detection and switching.
|
| 9 |
+
|
| 10 |
+
This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches
|
| 11 |
+
automatically between the nonstiff Adams method and the stiff BDF method.
|
| 12 |
+
The method was originally detailed in [2]_.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
----------
|
| 16 |
+
fun : callable
|
| 17 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
| 18 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
| 19 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
| 20 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
| 21 |
+
information.
|
| 22 |
+
t0 : float
|
| 23 |
+
Initial time.
|
| 24 |
+
y0 : array_like, shape (n,)
|
| 25 |
+
Initial state.
|
| 26 |
+
t_bound : float
|
| 27 |
+
Boundary time - the integration won't continue beyond it. It also
|
| 28 |
+
determines the direction of the integration.
|
| 29 |
+
first_step : float or None, optional
|
| 30 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
| 31 |
+
should choose.
|
| 32 |
+
min_step : float, optional
|
| 33 |
+
Minimum allowed step size. Default is 0.0, i.e., the step size is not
|
| 34 |
+
bounded and determined solely by the solver.
|
| 35 |
+
max_step : float, optional
|
| 36 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
| 37 |
+
bounded and determined solely by the solver.
|
| 38 |
+
rtol, atol : float and array_like, optional
|
| 39 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 40 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
| 41 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 42 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 43 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 44 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 45 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 46 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 47 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 48 |
+
than `atol`. If components of y have different scales, it might be
|
| 49 |
+
beneficial to set different `atol` values for different components by
|
| 50 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 51 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 52 |
+
jac : None or callable, optional
|
| 53 |
+
Jacobian matrix of the right-hand side of the system with respect to
|
| 54 |
+
``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is
|
| 55 |
+
equal to ``d f_i / d y_j``. The function will be called as
|
| 56 |
+
``jac(t, y)``. If None (default), the Jacobian will be
|
| 57 |
+
approximated by finite differences. It is generally recommended to
|
| 58 |
+
provide the Jacobian rather than relying on a finite-difference
|
| 59 |
+
approximation.
|
| 60 |
+
lband, uband : int or None
|
| 61 |
+
Parameters defining the bandwidth of the Jacobian,
|
| 62 |
+
i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting
|
| 63 |
+
these requires your jac routine to return the Jacobian in the packed format:
|
| 64 |
+
the returned array must have ``n`` columns and ``uband + lband + 1``
|
| 65 |
+
rows in which Jacobian diagonals are written. Specifically
|
| 66 |
+
``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used
|
| 67 |
+
in `scipy.linalg.solve_banded` (check for an illustration).
|
| 68 |
+
These parameters can be also used with ``jac=None`` to reduce the
|
| 69 |
+
number of Jacobian elements estimated by finite differences.
|
| 70 |
+
vectorized : bool, optional
|
| 71 |
+
Whether `fun` may be called in a vectorized fashion. False (default)
|
| 72 |
+
is recommended for this solver.
|
| 73 |
+
|
| 74 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
| 75 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
| 76 |
+
|
| 77 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
| 78 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
| 79 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
| 80 |
+
the returned array is the time derivative of the state corresponding
|
| 81 |
+
with a column of ``y``).
|
| 82 |
+
|
| 83 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
| 84 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
| 85 |
+
will result in slower execution for this solver.
|
| 86 |
+
|
| 87 |
+
Attributes
|
| 88 |
+
----------
|
| 89 |
+
n : int
|
| 90 |
+
Number of equations.
|
| 91 |
+
status : string
|
| 92 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 93 |
+
t_bound : float
|
| 94 |
+
Boundary time.
|
| 95 |
+
direction : float
|
| 96 |
+
Integration direction: +1 or -1.
|
| 97 |
+
t : float
|
| 98 |
+
Current time.
|
| 99 |
+
y : ndarray
|
| 100 |
+
Current state.
|
| 101 |
+
t_old : float
|
| 102 |
+
Previous time. None if no steps were made yet.
|
| 103 |
+
nfev : int
|
| 104 |
+
Number of evaluations of the right-hand side.
|
| 105 |
+
njev : int
|
| 106 |
+
Number of evaluations of the Jacobian.
|
| 107 |
+
|
| 108 |
+
References
|
| 109 |
+
----------
|
| 110 |
+
.. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
|
| 111 |
+
Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
|
| 112 |
+
pp. 55-64, 1983.
|
| 113 |
+
.. [2] L. Petzold, "Automatic selection of methods for solving stiff and
|
| 114 |
+
nonstiff systems of ordinary differential equations", SIAM Journal
|
| 115 |
+
on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
|
| 116 |
+
1983.
|
| 117 |
+
"""
|
| 118 |
+
def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0,
|
| 119 |
+
max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None,
|
| 120 |
+
uband=None, vectorized=False, **extraneous):
|
| 121 |
+
warn_extraneous(extraneous)
|
| 122 |
+
super().__init__(fun, t0, y0, t_bound, vectorized)
|
| 123 |
+
|
| 124 |
+
if first_step is None:
|
| 125 |
+
first_step = 0 # LSODA value for automatic selection.
|
| 126 |
+
else:
|
| 127 |
+
first_step = validate_first_step(first_step, t0, t_bound)
|
| 128 |
+
|
| 129 |
+
first_step *= self.direction
|
| 130 |
+
|
| 131 |
+
if max_step == np.inf:
|
| 132 |
+
max_step = 0 # LSODA value for infinity.
|
| 133 |
+
elif max_step <= 0:
|
| 134 |
+
raise ValueError("`max_step` must be positive.")
|
| 135 |
+
|
| 136 |
+
if min_step < 0:
|
| 137 |
+
raise ValueError("`min_step` must be nonnegative.")
|
| 138 |
+
|
| 139 |
+
rtol, atol = validate_tol(rtol, atol, self.n)
|
| 140 |
+
|
| 141 |
+
solver = ode(self.fun, jac)
|
| 142 |
+
solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step,
|
| 143 |
+
min_step=min_step, first_step=first_step,
|
| 144 |
+
lband=lband, uband=uband)
|
| 145 |
+
solver.set_initial_value(y0, t0)
|
| 146 |
+
|
| 147 |
+
# Inject t_bound into rwork array as needed for itask=5.
|
| 148 |
+
solver._integrator.rwork[0] = self.t_bound
|
| 149 |
+
solver._integrator.call_args[4] = solver._integrator.rwork
|
| 150 |
+
|
| 151 |
+
self._lsoda_solver = solver
|
| 152 |
+
|
| 153 |
+
def _step_impl(self):
|
| 154 |
+
solver = self._lsoda_solver
|
| 155 |
+
integrator = solver._integrator
|
| 156 |
+
|
| 157 |
+
# From lsoda.step and lsoda.integrate itask=5 means take a single
|
| 158 |
+
# step and do not go past t_bound.
|
| 159 |
+
itask = integrator.call_args[2]
|
| 160 |
+
integrator.call_args[2] = 5
|
| 161 |
+
solver._y, solver.t = integrator.run(
|
| 162 |
+
solver.f, solver.jac or (lambda: None), solver._y, solver.t,
|
| 163 |
+
self.t_bound, solver.f_params, solver.jac_params)
|
| 164 |
+
integrator.call_args[2] = itask
|
| 165 |
+
|
| 166 |
+
if solver.successful():
|
| 167 |
+
self.t = solver.t
|
| 168 |
+
self.y = solver._y
|
| 169 |
+
# From LSODA Fortran source njev is equal to nlu.
|
| 170 |
+
self.njev = integrator.iwork[12]
|
| 171 |
+
self.nlu = integrator.iwork[12]
|
| 172 |
+
return True, None
|
| 173 |
+
else:
|
| 174 |
+
return False, 'Unexpected istate in LSODA.'
|
| 175 |
+
|
| 176 |
+
def _dense_output_impl(self):
|
| 177 |
+
iwork = self._lsoda_solver._integrator.iwork
|
| 178 |
+
rwork = self._lsoda_solver._integrator.rwork
|
| 179 |
+
|
| 180 |
+
# We want to produce the Nordsieck history array, yh, up to the order
|
| 181 |
+
# used in the last successful iteration. The step size is unimportant
|
| 182 |
+
# because it will be scaled out in LsodaDenseOutput. Some additional
|
| 183 |
+
# work may be required because ODEPACK's LSODA implementation produces
|
| 184 |
+
# the Nordsieck history in the state needed for the next iteration.
|
| 185 |
+
|
| 186 |
+
# iwork[13] contains order from last successful iteration, while
|
| 187 |
+
# iwork[14] contains order to be attempted next.
|
| 188 |
+
order = iwork[13]
|
| 189 |
+
|
| 190 |
+
# rwork[11] contains the step size to be attempted next, while
|
| 191 |
+
# rwork[10] contains step size from last successful iteration.
|
| 192 |
+
h = rwork[11]
|
| 193 |
+
|
| 194 |
+
# rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the
|
| 195 |
+
# Nordsieck array in state needed for next iteration. We want
|
| 196 |
+
# the entries up to order for the last successful step so use the
|
| 197 |
+
# following.
|
| 198 |
+
yh = np.reshape(rwork[20:20 + (order + 1) * self.n],
|
| 199 |
+
(self.n, order + 1), order='F').copy()
|
| 200 |
+
if iwork[14] < order:
|
| 201 |
+
# If the order is set to decrease then the final column of yh
|
| 202 |
+
# has not been updated within ODEPACK's LSODA
|
| 203 |
+
# implementation because this column will not be used in the
|
| 204 |
+
# next iteration. We must rescale this column to make the
|
| 205 |
+
# associated step size consistent with the other columns.
|
| 206 |
+
yh[:, -1] *= (h / rwork[10]) ** order
|
| 207 |
+
|
| 208 |
+
return LsodaDenseOutput(self.t_old, self.t, h, order, yh)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class LsodaDenseOutput(DenseOutput):
|
| 212 |
+
def __init__(self, t_old, t, h, order, yh):
|
| 213 |
+
super().__init__(t_old, t)
|
| 214 |
+
self.h = h
|
| 215 |
+
self.yh = yh
|
| 216 |
+
self.p = np.arange(order + 1)
|
| 217 |
+
|
| 218 |
+
def _call_impl(self, t):
|
| 219 |
+
if t.ndim == 0:
|
| 220 |
+
x = ((t - self.t) / self.h) ** self.p
|
| 221 |
+
else:
|
| 222 |
+
x = ((t - self.t) / self.h) ** self.p[:, None]
|
| 223 |
+
|
| 224 |
+
return np.dot(self.yh, x)
|
parrot/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-310.pyc
ADDED
|
Binary file (32.8 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Author: Travis Oliphant
|
| 2 |
+
|
| 3 |
+
__all__ = ['odeint', 'ODEintWarning']
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from . import _odepack
|
| 7 |
+
from copy import copy
|
| 8 |
+
import warnings
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ODEintWarning(Warning):
|
| 12 |
+
"""Warning raised during the execution of `odeint`."""
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
_msgs = {2: "Integration successful.",
|
| 17 |
+
1: "Nothing was done; the integration time was 0.",
|
| 18 |
+
-1: "Excess work done on this call (perhaps wrong Dfun type).",
|
| 19 |
+
-2: "Excess accuracy requested (tolerances too small).",
|
| 20 |
+
-3: "Illegal input detected (internal error).",
|
| 21 |
+
-4: "Repeated error test failures (internal error).",
|
| 22 |
+
-5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
|
| 23 |
+
-6: "Error weight became zero during problem.",
|
| 24 |
+
-7: "Internal workspace insufficient to finish (internal error).",
|
| 25 |
+
-8: "Run terminated (internal error)."
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
|
| 30 |
+
ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
|
| 31 |
+
hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
|
| 32 |
+
mxords=5, printmessg=0, tfirst=False):
|
| 33 |
+
"""
|
| 34 |
+
Integrate a system of ordinary differential equations.
|
| 35 |
+
|
| 36 |
+
.. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
|
| 37 |
+
differential equation.
|
| 38 |
+
|
| 39 |
+
Solve a system of ordinary differential equations using lsoda from the
|
| 40 |
+
FORTRAN library odepack.
|
| 41 |
+
|
| 42 |
+
Solves the initial value problem for stiff or non-stiff systems
|
| 43 |
+
of first order ode-s::
|
| 44 |
+
|
| 45 |
+
dy/dt = func(y, t, ...) [or func(t, y, ...)]
|
| 46 |
+
|
| 47 |
+
where y can be a vector.
|
| 48 |
+
|
| 49 |
+
.. note:: By default, the required order of the first two arguments of
|
| 50 |
+
`func` are in the opposite order of the arguments in the system
|
| 51 |
+
definition function used by the `scipy.integrate.ode` class and
|
| 52 |
+
the function `scipy.integrate.solve_ivp`. To use a function with
|
| 53 |
+
the signature ``func(t, y, ...)``, the argument `tfirst` must be
|
| 54 |
+
set to ``True``.
|
| 55 |
+
|
| 56 |
+
Parameters
|
| 57 |
+
----------
|
| 58 |
+
func : callable(y, t, ...) or callable(t, y, ...)
|
| 59 |
+
Computes the derivative of y at t.
|
| 60 |
+
If the signature is ``callable(t, y, ...)``, then the argument
|
| 61 |
+
`tfirst` must be set ``True``.
|
| 62 |
+
`func` must not modify the data in `y`, as it is a
|
| 63 |
+
view of the data used internally by the ODE solver.
|
| 64 |
+
y0 : array
|
| 65 |
+
Initial condition on y (can be a vector).
|
| 66 |
+
t : array
|
| 67 |
+
A sequence of time points for which to solve for y. The initial
|
| 68 |
+
value point should be the first element of this sequence.
|
| 69 |
+
This sequence must be monotonically increasing or monotonically
|
| 70 |
+
decreasing; repeated values are allowed.
|
| 71 |
+
args : tuple, optional
|
| 72 |
+
Extra arguments to pass to function.
|
| 73 |
+
Dfun : callable(y, t, ...) or callable(t, y, ...)
|
| 74 |
+
Gradient (Jacobian) of `func`.
|
| 75 |
+
If the signature is ``callable(t, y, ...)``, then the argument
|
| 76 |
+
`tfirst` must be set ``True``.
|
| 77 |
+
`Dfun` must not modify the data in `y`, as it is a
|
| 78 |
+
view of the data used internally by the ODE solver.
|
| 79 |
+
col_deriv : bool, optional
|
| 80 |
+
True if `Dfun` defines derivatives down columns (faster),
|
| 81 |
+
otherwise `Dfun` should define derivatives across rows.
|
| 82 |
+
full_output : bool, optional
|
| 83 |
+
True if to return a dictionary of optional outputs as the second output
|
| 84 |
+
printmessg : bool, optional
|
| 85 |
+
Whether to print the convergence message
|
| 86 |
+
tfirst : bool, optional
|
| 87 |
+
If True, the first two arguments of `func` (and `Dfun`, if given)
|
| 88 |
+
must ``t, y`` instead of the default ``y, t``.
|
| 89 |
+
|
| 90 |
+
.. versionadded:: 1.1.0
|
| 91 |
+
|
| 92 |
+
Returns
|
| 93 |
+
-------
|
| 94 |
+
y : array, shape (len(t), len(y0))
|
| 95 |
+
Array containing the value of y for each desired time in t,
|
| 96 |
+
with the initial value `y0` in the first row.
|
| 97 |
+
infodict : dict, only returned if full_output == True
|
| 98 |
+
Dictionary containing additional output information
|
| 99 |
+
|
| 100 |
+
======= ============================================================
|
| 101 |
+
key meaning
|
| 102 |
+
======= ============================================================
|
| 103 |
+
'hu' vector of step sizes successfully used for each time step
|
| 104 |
+
'tcur' vector with the value of t reached for each time step
|
| 105 |
+
(will always be at least as large as the input times)
|
| 106 |
+
'tolsf' vector of tolerance scale factors, greater than 1.0,
|
| 107 |
+
computed when a request for too much accuracy was detected
|
| 108 |
+
'tsw' value of t at the time of the last method switch
|
| 109 |
+
(given for each time step)
|
| 110 |
+
'nst' cumulative number of time steps
|
| 111 |
+
'nfe' cumulative number of function evaluations for each time step
|
| 112 |
+
'nje' cumulative number of jacobian evaluations for each time step
|
| 113 |
+
'nqu' a vector of method orders for each successful step
|
| 114 |
+
'imxer' index of the component of largest magnitude in the
|
| 115 |
+
weighted local error vector (e / ewt) on an error return, -1
|
| 116 |
+
otherwise
|
| 117 |
+
'lenrw' the length of the double work array required
|
| 118 |
+
'leniw' the length of integer work array required
|
| 119 |
+
'mused' a vector of method indicators for each successful time step:
|
| 120 |
+
1: adams (nonstiff), 2: bdf (stiff)
|
| 121 |
+
======= ============================================================
|
| 122 |
+
|
| 123 |
+
Other Parameters
|
| 124 |
+
----------------
|
| 125 |
+
ml, mu : int, optional
|
| 126 |
+
If either of these are not None or non-negative, then the
|
| 127 |
+
Jacobian is assumed to be banded. These give the number of
|
| 128 |
+
lower and upper non-zero diagonals in this banded matrix.
|
| 129 |
+
For the banded case, `Dfun` should return a matrix whose
|
| 130 |
+
rows contain the non-zero bands (starting with the lowest diagonal).
|
| 131 |
+
Thus, the return matrix `jac` from `Dfun` should have shape
|
| 132 |
+
``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
|
| 133 |
+
The data in `jac` must be stored such that ``jac[i - j + mu, j]``
|
| 134 |
+
holds the derivative of the ``i``\\ th equation with respect to the
|
| 135 |
+
``j``\\ th state variable. If `col_deriv` is True, the transpose of
|
| 136 |
+
this `jac` must be returned.
|
| 137 |
+
rtol, atol : float, optional
|
| 138 |
+
The input parameters `rtol` and `atol` determine the error
|
| 139 |
+
control performed by the solver. The solver will control the
|
| 140 |
+
vector, e, of estimated local errors in y, according to an
|
| 141 |
+
inequality of the form ``max-norm of (e / ewt) <= 1``,
|
| 142 |
+
where ewt is a vector of positive error weights computed as
|
| 143 |
+
``ewt = rtol * abs(y) + atol``.
|
| 144 |
+
rtol and atol can be either vectors the same length as y or scalars.
|
| 145 |
+
Defaults to 1.49012e-8.
|
| 146 |
+
tcrit : ndarray, optional
|
| 147 |
+
Vector of critical points (e.g., singularities) where integration
|
| 148 |
+
care should be taken.
|
| 149 |
+
h0 : float, (0: solver-determined), optional
|
| 150 |
+
The step size to be attempted on the first step.
|
| 151 |
+
hmax : float, (0: solver-determined), optional
|
| 152 |
+
The maximum absolute step size allowed.
|
| 153 |
+
hmin : float, (0: solver-determined), optional
|
| 154 |
+
The minimum absolute step size allowed.
|
| 155 |
+
ixpr : bool, optional
|
| 156 |
+
Whether to generate extra printing at method switches.
|
| 157 |
+
mxstep : int, (0: solver-determined), optional
|
| 158 |
+
Maximum number of (internally defined) steps allowed for each
|
| 159 |
+
integration point in t.
|
| 160 |
+
mxhnil : int, (0: solver-determined), optional
|
| 161 |
+
Maximum number of messages printed.
|
| 162 |
+
mxordn : int, (0: solver-determined), optional
|
| 163 |
+
Maximum order to be allowed for the non-stiff (Adams) method.
|
| 164 |
+
mxords : int, (0: solver-determined), optional
|
| 165 |
+
Maximum order to be allowed for the stiff (BDF) method.
|
| 166 |
+
|
| 167 |
+
See Also
|
| 168 |
+
--------
|
| 169 |
+
solve_ivp : solve an initial value problem for a system of ODEs
|
| 170 |
+
ode : a more object-oriented integrator based on VODE
|
| 171 |
+
quad : for finding the area under a curve
|
| 172 |
+
|
| 173 |
+
Examples
|
| 174 |
+
--------
|
| 175 |
+
The second order differential equation for the angle `theta` of a
|
| 176 |
+
pendulum acted on by gravity with friction can be written::
|
| 177 |
+
|
| 178 |
+
theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
|
| 179 |
+
|
| 180 |
+
where `b` and `c` are positive constants, and a prime (') denotes a
|
| 181 |
+
derivative. To solve this equation with `odeint`, we must first convert
|
| 182 |
+
it to a system of first order equations. By defining the angular
|
| 183 |
+
velocity ``omega(t) = theta'(t)``, we obtain the system::
|
| 184 |
+
|
| 185 |
+
theta'(t) = omega(t)
|
| 186 |
+
omega'(t) = -b*omega(t) - c*sin(theta(t))
|
| 187 |
+
|
| 188 |
+
Let `y` be the vector [`theta`, `omega`]. We implement this system
|
| 189 |
+
in Python as:
|
| 190 |
+
|
| 191 |
+
>>> import numpy as np
|
| 192 |
+
>>> def pend(y, t, b, c):
|
| 193 |
+
... theta, omega = y
|
| 194 |
+
... dydt = [omega, -b*omega - c*np.sin(theta)]
|
| 195 |
+
... return dydt
|
| 196 |
+
...
|
| 197 |
+
|
| 198 |
+
We assume the constants are `b` = 0.25 and `c` = 5.0:
|
| 199 |
+
|
| 200 |
+
>>> b = 0.25
|
| 201 |
+
>>> c = 5.0
|
| 202 |
+
|
| 203 |
+
For initial conditions, we assume the pendulum is nearly vertical
|
| 204 |
+
with `theta(0)` = `pi` - 0.1, and is initially at rest, so
|
| 205 |
+
`omega(0)` = 0. Then the vector of initial conditions is
|
| 206 |
+
|
| 207 |
+
>>> y0 = [np.pi - 0.1, 0.0]
|
| 208 |
+
|
| 209 |
+
We will generate a solution at 101 evenly spaced samples in the interval
|
| 210 |
+
0 <= `t` <= 10. So our array of times is:
|
| 211 |
+
|
| 212 |
+
>>> t = np.linspace(0, 10, 101)
|
| 213 |
+
|
| 214 |
+
Call `odeint` to generate the solution. To pass the parameters
|
| 215 |
+
`b` and `c` to `pend`, we give them to `odeint` using the `args`
|
| 216 |
+
argument.
|
| 217 |
+
|
| 218 |
+
>>> from scipy.integrate import odeint
|
| 219 |
+
>>> sol = odeint(pend, y0, t, args=(b, c))
|
| 220 |
+
|
| 221 |
+
The solution is an array with shape (101, 2). The first column
|
| 222 |
+
is `theta(t)`, and the second is `omega(t)`. The following code
|
| 223 |
+
plots both components.
|
| 224 |
+
|
| 225 |
+
>>> import matplotlib.pyplot as plt
|
| 226 |
+
>>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
|
| 227 |
+
>>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
|
| 228 |
+
>>> plt.legend(loc='best')
|
| 229 |
+
>>> plt.xlabel('t')
|
| 230 |
+
>>> plt.grid()
|
| 231 |
+
>>> plt.show()
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
if ml is None:
|
| 235 |
+
ml = -1 # changed to zero inside function call
|
| 236 |
+
if mu is None:
|
| 237 |
+
mu = -1 # changed to zero inside function call
|
| 238 |
+
|
| 239 |
+
dt = np.diff(t)
|
| 240 |
+
if not ((dt >= 0).all() or (dt <= 0).all()):
|
| 241 |
+
raise ValueError("The values in t must be monotonically increasing "
|
| 242 |
+
"or monotonically decreasing; repeated values are "
|
| 243 |
+
"allowed.")
|
| 244 |
+
|
| 245 |
+
t = copy(t)
|
| 246 |
+
y0 = copy(y0)
|
| 247 |
+
output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
|
| 248 |
+
full_output, rtol, atol, tcrit, h0, hmax, hmin,
|
| 249 |
+
ixpr, mxstep, mxhnil, mxordn, mxords,
|
| 250 |
+
int(bool(tfirst)))
|
| 251 |
+
if output[-1] < 0:
|
| 252 |
+
warning_msg = (f"{_msgs[output[-1]]} Run with full_output = 1 to "
|
| 253 |
+
f"get quantitative information.")
|
| 254 |
+
warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
|
| 255 |
+
elif printmessg:
|
| 256 |
+
warning_msg = _msgs[output[-1]]
|
| 257 |
+
warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
|
| 258 |
+
|
| 259 |
+
if full_output:
|
| 260 |
+
output[1]['message'] = _msgs[output[-1]]
|
| 261 |
+
|
| 262 |
+
output = output[:-1]
|
| 263 |
+
if len(output) == 1:
|
| 264 |
+
return output[0]
|
| 265 |
+
else:
|
| 266 |
+
return output
|
parrot/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import copy
|
| 3 |
+
import heapq
|
| 4 |
+
import collections
|
| 5 |
+
import functools
|
| 6 |
+
import warnings
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from scipy._lib._util import MapWrapper, _FunctionWrapper
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class LRUDict(collections.OrderedDict):
|
| 14 |
+
def __init__(self, max_size):
|
| 15 |
+
self.__max_size = max_size
|
| 16 |
+
|
| 17 |
+
def __setitem__(self, key, value):
|
| 18 |
+
existing_key = (key in self)
|
| 19 |
+
super().__setitem__(key, value)
|
| 20 |
+
if existing_key:
|
| 21 |
+
self.move_to_end(key)
|
| 22 |
+
elif len(self) > self.__max_size:
|
| 23 |
+
self.popitem(last=False)
|
| 24 |
+
|
| 25 |
+
def update(self, other):
|
| 26 |
+
# Not needed below
|
| 27 |
+
raise NotImplementedError()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SemiInfiniteFunc:
|
| 31 |
+
"""
|
| 32 |
+
Argument transform from (start, +-oo) to (0, 1)
|
| 33 |
+
"""
|
| 34 |
+
def __init__(self, func, start, infty):
|
| 35 |
+
self._func = func
|
| 36 |
+
self._start = start
|
| 37 |
+
self._sgn = -1 if infty < 0 else 1
|
| 38 |
+
|
| 39 |
+
# Overflow threshold for the 1/t**2 factor
|
| 40 |
+
self._tmin = sys.float_info.min**0.5
|
| 41 |
+
|
| 42 |
+
def get_t(self, x):
|
| 43 |
+
z = self._sgn * (x - self._start) + 1
|
| 44 |
+
if z == 0:
|
| 45 |
+
# Can happen only if point not in range
|
| 46 |
+
return np.inf
|
| 47 |
+
return 1 / z
|
| 48 |
+
|
| 49 |
+
def __call__(self, t):
|
| 50 |
+
if t < self._tmin:
|
| 51 |
+
return 0.0
|
| 52 |
+
else:
|
| 53 |
+
x = self._start + self._sgn * (1 - t) / t
|
| 54 |
+
f = self._func(x)
|
| 55 |
+
return self._sgn * (f / t) / t
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class DoubleInfiniteFunc:
|
| 59 |
+
"""
|
| 60 |
+
Argument transform from (-oo, oo) to (-1, 1)
|
| 61 |
+
"""
|
| 62 |
+
def __init__(self, func):
|
| 63 |
+
self._func = func
|
| 64 |
+
|
| 65 |
+
# Overflow threshold for the 1/t**2 factor
|
| 66 |
+
self._tmin = sys.float_info.min**0.5
|
| 67 |
+
|
| 68 |
+
def get_t(self, x):
|
| 69 |
+
s = -1 if x < 0 else 1
|
| 70 |
+
return s / (abs(x) + 1)
|
| 71 |
+
|
| 72 |
+
def __call__(self, t):
|
| 73 |
+
if abs(t) < self._tmin:
|
| 74 |
+
return 0.0
|
| 75 |
+
else:
|
| 76 |
+
x = (1 - abs(t)) / t
|
| 77 |
+
f = self._func(x)
|
| 78 |
+
return (f / t) / t
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _max_norm(x):
|
| 82 |
+
return np.amax(abs(x))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _get_sizeof(obj):
|
| 86 |
+
try:
|
| 87 |
+
return sys.getsizeof(obj)
|
| 88 |
+
except TypeError:
|
| 89 |
+
# occurs on pypy
|
| 90 |
+
if hasattr(obj, '__sizeof__'):
|
| 91 |
+
return int(obj.__sizeof__())
|
| 92 |
+
return 64
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class _Bunch:
|
| 96 |
+
def __init__(self, **kwargs):
|
| 97 |
+
self.__keys = kwargs.keys()
|
| 98 |
+
self.__dict__.update(**kwargs)
|
| 99 |
+
|
| 100 |
+
def __repr__(self):
|
| 101 |
+
return "_Bunch({})".format(", ".join(f"{k}={repr(self.__dict__[k])}"
|
| 102 |
+
for k in self.__keys))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def quad_vec(f, a, b, epsabs=1e-200, epsrel=1e-8, norm='2', cache_size=100e6,
|
| 106 |
+
limit=10000, workers=1, points=None, quadrature=None, full_output=False,
|
| 107 |
+
*, args=()):
|
| 108 |
+
r"""Adaptive integration of a vector-valued function.
|
| 109 |
+
|
| 110 |
+
Parameters
|
| 111 |
+
----------
|
| 112 |
+
f : callable
|
| 113 |
+
Vector-valued function f(x) to integrate.
|
| 114 |
+
a : float
|
| 115 |
+
Initial point.
|
| 116 |
+
b : float
|
| 117 |
+
Final point.
|
| 118 |
+
epsabs : float, optional
|
| 119 |
+
Absolute tolerance.
|
| 120 |
+
epsrel : float, optional
|
| 121 |
+
Relative tolerance.
|
| 122 |
+
norm : {'max', '2'}, optional
|
| 123 |
+
Vector norm to use for error estimation.
|
| 124 |
+
cache_size : int, optional
|
| 125 |
+
Number of bytes to use for memoization.
|
| 126 |
+
limit : float or int, optional
|
| 127 |
+
An upper bound on the number of subintervals used in the adaptive
|
| 128 |
+
algorithm.
|
| 129 |
+
workers : int or map-like callable, optional
|
| 130 |
+
If `workers` is an integer, part of the computation is done in
|
| 131 |
+
parallel subdivided to this many tasks (using
|
| 132 |
+
:class:`python:multiprocessing.pool.Pool`).
|
| 133 |
+
Supply `-1` to use all cores available to the Process.
|
| 134 |
+
Alternatively, supply a map-like callable, such as
|
| 135 |
+
:meth:`python:multiprocessing.pool.Pool.map` for evaluating the
|
| 136 |
+
population in parallel.
|
| 137 |
+
This evaluation is carried out as ``workers(func, iterable)``.
|
| 138 |
+
points : list, optional
|
| 139 |
+
List of additional breakpoints.
|
| 140 |
+
quadrature : {'gk21', 'gk15', 'trapezoid'}, optional
|
| 141 |
+
Quadrature rule to use on subintervals.
|
| 142 |
+
Options: 'gk21' (Gauss-Kronrod 21-point rule),
|
| 143 |
+
'gk15' (Gauss-Kronrod 15-point rule),
|
| 144 |
+
'trapezoid' (composite trapezoid rule).
|
| 145 |
+
Default: 'gk21' for finite intervals and 'gk15' for (semi-)infinite
|
| 146 |
+
full_output : bool, optional
|
| 147 |
+
Return an additional ``info`` dictionary.
|
| 148 |
+
args : tuple, optional
|
| 149 |
+
Extra arguments to pass to function, if any.
|
| 150 |
+
|
| 151 |
+
.. versionadded:: 1.8.0
|
| 152 |
+
|
| 153 |
+
Returns
|
| 154 |
+
-------
|
| 155 |
+
res : {float, array-like}
|
| 156 |
+
Estimate for the result
|
| 157 |
+
err : float
|
| 158 |
+
Error estimate for the result in the given norm
|
| 159 |
+
info : dict
|
| 160 |
+
Returned only when ``full_output=True``.
|
| 161 |
+
Info dictionary. Is an object with the attributes:
|
| 162 |
+
|
| 163 |
+
success : bool
|
| 164 |
+
Whether integration reached target precision.
|
| 165 |
+
status : int
|
| 166 |
+
Indicator for convergence, success (0),
|
| 167 |
+
failure (1), and failure due to rounding error (2).
|
| 168 |
+
neval : int
|
| 169 |
+
Number of function evaluations.
|
| 170 |
+
intervals : ndarray, shape (num_intervals, 2)
|
| 171 |
+
Start and end points of subdivision intervals.
|
| 172 |
+
integrals : ndarray, shape (num_intervals, ...)
|
| 173 |
+
Integral for each interval.
|
| 174 |
+
Note that at most ``cache_size`` values are recorded,
|
| 175 |
+
and the array may contains *nan* for missing items.
|
| 176 |
+
errors : ndarray, shape (num_intervals,)
|
| 177 |
+
Estimated integration error for each interval.
|
| 178 |
+
|
| 179 |
+
Notes
|
| 180 |
+
-----
|
| 181 |
+
The algorithm mainly follows the implementation of QUADPACK's
|
| 182 |
+
DQAG* algorithms, implementing global error control and adaptive
|
| 183 |
+
subdivision.
|
| 184 |
+
|
| 185 |
+
The algorithm here has some differences to the QUADPACK approach:
|
| 186 |
+
|
| 187 |
+
Instead of subdividing one interval at a time, the algorithm
|
| 188 |
+
subdivides N intervals with largest errors at once. This enables
|
| 189 |
+
(partial) parallelization of the integration.
|
| 190 |
+
|
| 191 |
+
The logic of subdividing "next largest" intervals first is then
|
| 192 |
+
not implemented, and we rely on the above extension to avoid
|
| 193 |
+
concentrating on "small" intervals only.
|
| 194 |
+
|
| 195 |
+
The Wynn epsilon table extrapolation is not used (QUADPACK uses it
|
| 196 |
+
for infinite intervals). This is because the algorithm here is
|
| 197 |
+
supposed to work on vector-valued functions, in an user-specified
|
| 198 |
+
norm, and the extension of the epsilon algorithm to this case does
|
| 199 |
+
not appear to be widely agreed. For max-norm, using elementwise
|
| 200 |
+
Wynn epsilon could be possible, but we do not do this here with
|
| 201 |
+
the hope that the epsilon extrapolation is mainly useful in
|
| 202 |
+
special cases.
|
| 203 |
+
|
| 204 |
+
References
|
| 205 |
+
----------
|
| 206 |
+
[1] R. Piessens, E. de Doncker, QUADPACK (1983).
|
| 207 |
+
|
| 208 |
+
Examples
|
| 209 |
+
--------
|
| 210 |
+
We can compute integrations of a vector-valued function:
|
| 211 |
+
|
| 212 |
+
>>> from scipy.integrate import quad_vec
|
| 213 |
+
>>> import numpy as np
|
| 214 |
+
>>> import matplotlib.pyplot as plt
|
| 215 |
+
>>> alpha = np.linspace(0.0, 2.0, num=30)
|
| 216 |
+
>>> f = lambda x: x**alpha
|
| 217 |
+
>>> x0, x1 = 0, 2
|
| 218 |
+
>>> y, err = quad_vec(f, x0, x1)
|
| 219 |
+
>>> plt.plot(alpha, y)
|
| 220 |
+
>>> plt.xlabel(r"$\alpha$")
|
| 221 |
+
>>> plt.ylabel(r"$\int_{0}^{2} x^\alpha dx$")
|
| 222 |
+
>>> plt.show()
|
| 223 |
+
|
| 224 |
+
"""
|
| 225 |
+
a = float(a)
|
| 226 |
+
b = float(b)
|
| 227 |
+
|
| 228 |
+
if args:
|
| 229 |
+
if not isinstance(args, tuple):
|
| 230 |
+
args = (args,)
|
| 231 |
+
|
| 232 |
+
# create a wrapped function to allow the use of map and Pool.map
|
| 233 |
+
f = _FunctionWrapper(f, args)
|
| 234 |
+
|
| 235 |
+
# Use simple transformations to deal with integrals over infinite
|
| 236 |
+
# intervals.
|
| 237 |
+
kwargs = dict(epsabs=epsabs,
|
| 238 |
+
epsrel=epsrel,
|
| 239 |
+
norm=norm,
|
| 240 |
+
cache_size=cache_size,
|
| 241 |
+
limit=limit,
|
| 242 |
+
workers=workers,
|
| 243 |
+
points=points,
|
| 244 |
+
quadrature='gk15' if quadrature is None else quadrature,
|
| 245 |
+
full_output=full_output)
|
| 246 |
+
if np.isfinite(a) and np.isinf(b):
|
| 247 |
+
f2 = SemiInfiniteFunc(f, start=a, infty=b)
|
| 248 |
+
if points is not None:
|
| 249 |
+
kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
|
| 250 |
+
return quad_vec(f2, 0, 1, **kwargs)
|
| 251 |
+
elif np.isfinite(b) and np.isinf(a):
|
| 252 |
+
f2 = SemiInfiniteFunc(f, start=b, infty=a)
|
| 253 |
+
if points is not None:
|
| 254 |
+
kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
|
| 255 |
+
res = quad_vec(f2, 0, 1, **kwargs)
|
| 256 |
+
return (-res[0],) + res[1:]
|
| 257 |
+
elif np.isinf(a) and np.isinf(b):
|
| 258 |
+
sgn = -1 if b < a else 1
|
| 259 |
+
|
| 260 |
+
# NB. explicitly split integral at t=0, which separates
|
| 261 |
+
# the positive and negative sides
|
| 262 |
+
f2 = DoubleInfiniteFunc(f)
|
| 263 |
+
if points is not None:
|
| 264 |
+
kwargs['points'] = (0,) + tuple(f2.get_t(xp) for xp in points)
|
| 265 |
+
else:
|
| 266 |
+
kwargs['points'] = (0,)
|
| 267 |
+
|
| 268 |
+
if a != b:
|
| 269 |
+
res = quad_vec(f2, -1, 1, **kwargs)
|
| 270 |
+
else:
|
| 271 |
+
res = quad_vec(f2, 1, 1, **kwargs)
|
| 272 |
+
|
| 273 |
+
return (res[0]*sgn,) + res[1:]
|
| 274 |
+
elif not (np.isfinite(a) and np.isfinite(b)):
|
| 275 |
+
raise ValueError(f"invalid integration bounds a={a}, b={b}")
|
| 276 |
+
|
| 277 |
+
norm_funcs = {
|
| 278 |
+
None: _max_norm,
|
| 279 |
+
'max': _max_norm,
|
| 280 |
+
'2': np.linalg.norm
|
| 281 |
+
}
|
| 282 |
+
if callable(norm):
|
| 283 |
+
norm_func = norm
|
| 284 |
+
else:
|
| 285 |
+
norm_func = norm_funcs[norm]
|
| 286 |
+
|
| 287 |
+
parallel_count = 128
|
| 288 |
+
min_intervals = 2
|
| 289 |
+
|
| 290 |
+
try:
|
| 291 |
+
_quadrature = {None: _quadrature_gk21,
|
| 292 |
+
'gk21': _quadrature_gk21,
|
| 293 |
+
'gk15': _quadrature_gk15,
|
| 294 |
+
'trapz': _quadrature_trapezoid, # alias for backcompat
|
| 295 |
+
'trapezoid': _quadrature_trapezoid}[quadrature]
|
| 296 |
+
except KeyError as e:
|
| 297 |
+
raise ValueError(f"unknown quadrature {quadrature!r}") from e
|
| 298 |
+
|
| 299 |
+
if quadrature == "trapz":
|
| 300 |
+
msg = ("`quadrature='trapz'` is deprecated in favour of "
|
| 301 |
+
"`quadrature='trapezoid' and will raise an error from SciPy 1.16.0 "
|
| 302 |
+
"onwards.")
|
| 303 |
+
warnings.warn(msg, DeprecationWarning, stacklevel=2)
|
| 304 |
+
|
| 305 |
+
# Initial interval set
|
| 306 |
+
if points is None:
|
| 307 |
+
initial_intervals = [(a, b)]
|
| 308 |
+
else:
|
| 309 |
+
prev = a
|
| 310 |
+
initial_intervals = []
|
| 311 |
+
for p in sorted(points):
|
| 312 |
+
p = float(p)
|
| 313 |
+
if not (a < p < b) or p == prev:
|
| 314 |
+
continue
|
| 315 |
+
initial_intervals.append((prev, p))
|
| 316 |
+
prev = p
|
| 317 |
+
initial_intervals.append((prev, b))
|
| 318 |
+
|
| 319 |
+
global_integral = None
|
| 320 |
+
global_error = None
|
| 321 |
+
rounding_error = None
|
| 322 |
+
interval_cache = None
|
| 323 |
+
intervals = []
|
| 324 |
+
neval = 0
|
| 325 |
+
|
| 326 |
+
for x1, x2 in initial_intervals:
|
| 327 |
+
ig, err, rnd = _quadrature(x1, x2, f, norm_func)
|
| 328 |
+
neval += _quadrature.num_eval
|
| 329 |
+
|
| 330 |
+
if global_integral is None:
|
| 331 |
+
if isinstance(ig, (float, complex)):
|
| 332 |
+
# Specialize for scalars
|
| 333 |
+
if norm_func in (_max_norm, np.linalg.norm):
|
| 334 |
+
norm_func = abs
|
| 335 |
+
|
| 336 |
+
global_integral = ig
|
| 337 |
+
global_error = float(err)
|
| 338 |
+
rounding_error = float(rnd)
|
| 339 |
+
|
| 340 |
+
cache_count = cache_size // _get_sizeof(ig)
|
| 341 |
+
interval_cache = LRUDict(cache_count)
|
| 342 |
+
else:
|
| 343 |
+
global_integral += ig
|
| 344 |
+
global_error += err
|
| 345 |
+
rounding_error += rnd
|
| 346 |
+
|
| 347 |
+
interval_cache[(x1, x2)] = copy.copy(ig)
|
| 348 |
+
intervals.append((-err, x1, x2))
|
| 349 |
+
|
| 350 |
+
heapq.heapify(intervals)
|
| 351 |
+
|
| 352 |
+
CONVERGED = 0
|
| 353 |
+
NOT_CONVERGED = 1
|
| 354 |
+
ROUNDING_ERROR = 2
|
| 355 |
+
NOT_A_NUMBER = 3
|
| 356 |
+
|
| 357 |
+
status_msg = {
|
| 358 |
+
CONVERGED: "Target precision reached.",
|
| 359 |
+
NOT_CONVERGED: "Target precision not reached.",
|
| 360 |
+
ROUNDING_ERROR: "Target precision could not be reached due to rounding error.",
|
| 361 |
+
NOT_A_NUMBER: "Non-finite values encountered."
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
# Process intervals
|
| 365 |
+
with MapWrapper(workers) as mapwrapper:
|
| 366 |
+
ier = NOT_CONVERGED
|
| 367 |
+
|
| 368 |
+
while intervals and len(intervals) < limit:
|
| 369 |
+
# Select intervals with largest errors for subdivision
|
| 370 |
+
tol = max(epsabs, epsrel*norm_func(global_integral))
|
| 371 |
+
|
| 372 |
+
to_process = []
|
| 373 |
+
err_sum = 0
|
| 374 |
+
|
| 375 |
+
for j in range(parallel_count):
|
| 376 |
+
if not intervals:
|
| 377 |
+
break
|
| 378 |
+
|
| 379 |
+
if j > 0 and err_sum > global_error - tol/8:
|
| 380 |
+
# avoid unnecessary parallel splitting
|
| 381 |
+
break
|
| 382 |
+
|
| 383 |
+
interval = heapq.heappop(intervals)
|
| 384 |
+
|
| 385 |
+
neg_old_err, a, b = interval
|
| 386 |
+
old_int = interval_cache.pop((a, b), None)
|
| 387 |
+
to_process.append(
|
| 388 |
+
((-neg_old_err, a, b, old_int), f, norm_func, _quadrature)
|
| 389 |
+
)
|
| 390 |
+
err_sum += -neg_old_err
|
| 391 |
+
|
| 392 |
+
# Subdivide intervals
|
| 393 |
+
for parts in mapwrapper(_subdivide_interval, to_process):
|
| 394 |
+
dint, derr, dround_err, subint, dneval = parts
|
| 395 |
+
neval += dneval
|
| 396 |
+
global_integral += dint
|
| 397 |
+
global_error += derr
|
| 398 |
+
rounding_error += dround_err
|
| 399 |
+
for x in subint:
|
| 400 |
+
x1, x2, ig, err = x
|
| 401 |
+
interval_cache[(x1, x2)] = ig
|
| 402 |
+
heapq.heappush(intervals, (-err, x1, x2))
|
| 403 |
+
|
| 404 |
+
# Termination check
|
| 405 |
+
if len(intervals) >= min_intervals:
|
| 406 |
+
tol = max(epsabs, epsrel*norm_func(global_integral))
|
| 407 |
+
if global_error < tol/8:
|
| 408 |
+
ier = CONVERGED
|
| 409 |
+
break
|
| 410 |
+
if global_error < rounding_error:
|
| 411 |
+
ier = ROUNDING_ERROR
|
| 412 |
+
break
|
| 413 |
+
|
| 414 |
+
if not (np.isfinite(global_error) and np.isfinite(rounding_error)):
|
| 415 |
+
ier = NOT_A_NUMBER
|
| 416 |
+
break
|
| 417 |
+
|
| 418 |
+
res = global_integral
|
| 419 |
+
err = global_error + rounding_error
|
| 420 |
+
|
| 421 |
+
if full_output:
|
| 422 |
+
res_arr = np.asarray(res)
|
| 423 |
+
dummy = np.full(res_arr.shape, np.nan, dtype=res_arr.dtype)
|
| 424 |
+
integrals = np.array([interval_cache.get((z[1], z[2]), dummy)
|
| 425 |
+
for z in intervals], dtype=res_arr.dtype)
|
| 426 |
+
errors = np.array([-z[0] for z in intervals])
|
| 427 |
+
intervals = np.array([[z[1], z[2]] for z in intervals])
|
| 428 |
+
|
| 429 |
+
info = _Bunch(neval=neval,
|
| 430 |
+
success=(ier == CONVERGED),
|
| 431 |
+
status=ier,
|
| 432 |
+
message=status_msg[ier],
|
| 433 |
+
intervals=intervals,
|
| 434 |
+
integrals=integrals,
|
| 435 |
+
errors=errors)
|
| 436 |
+
return (res, err, info)
|
| 437 |
+
else:
|
| 438 |
+
return (res, err)
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def _subdivide_interval(args):
|
| 442 |
+
interval, f, norm_func, _quadrature = args
|
| 443 |
+
old_err, a, b, old_int = interval
|
| 444 |
+
|
| 445 |
+
c = 0.5 * (a + b)
|
| 446 |
+
|
| 447 |
+
# Left-hand side
|
| 448 |
+
if getattr(_quadrature, 'cache_size', 0) > 0:
|
| 449 |
+
f = functools.lru_cache(_quadrature.cache_size)(f)
|
| 450 |
+
|
| 451 |
+
s1, err1, round1 = _quadrature(a, c, f, norm_func)
|
| 452 |
+
dneval = _quadrature.num_eval
|
| 453 |
+
s2, err2, round2 = _quadrature(c, b, f, norm_func)
|
| 454 |
+
dneval += _quadrature.num_eval
|
| 455 |
+
if old_int is None:
|
| 456 |
+
old_int, _, _ = _quadrature(a, b, f, norm_func)
|
| 457 |
+
dneval += _quadrature.num_eval
|
| 458 |
+
|
| 459 |
+
if getattr(_quadrature, 'cache_size', 0) > 0:
|
| 460 |
+
dneval = f.cache_info().misses
|
| 461 |
+
|
| 462 |
+
dint = s1 + s2 - old_int
|
| 463 |
+
derr = err1 + err2 - old_err
|
| 464 |
+
dround_err = round1 + round2
|
| 465 |
+
|
| 466 |
+
subintervals = ((a, c, s1, err1), (c, b, s2, err2))
|
| 467 |
+
return dint, derr, dround_err, subintervals, dneval
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def _quadrature_trapezoid(x1, x2, f, norm_func):
|
| 471 |
+
"""
|
| 472 |
+
Composite trapezoid quadrature
|
| 473 |
+
"""
|
| 474 |
+
x3 = 0.5*(x1 + x2)
|
| 475 |
+
f1 = f(x1)
|
| 476 |
+
f2 = f(x2)
|
| 477 |
+
f3 = f(x3)
|
| 478 |
+
|
| 479 |
+
s2 = 0.25 * (x2 - x1) * (f1 + 2*f3 + f2)
|
| 480 |
+
|
| 481 |
+
round_err = 0.25 * abs(x2 - x1) * (float(norm_func(f1))
|
| 482 |
+
+ 2*float(norm_func(f3))
|
| 483 |
+
+ float(norm_func(f2))) * 2e-16
|
| 484 |
+
|
| 485 |
+
s1 = 0.5 * (x2 - x1) * (f1 + f2)
|
| 486 |
+
err = 1/3 * float(norm_func(s1 - s2))
|
| 487 |
+
return s2, err, round_err
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
_quadrature_trapezoid.cache_size = 3 * 3
|
| 491 |
+
_quadrature_trapezoid.num_eval = 3
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def _quadrature_gk(a, b, f, norm_func, x, w, v):
|
| 495 |
+
"""
|
| 496 |
+
Generic Gauss-Kronrod quadrature
|
| 497 |
+
"""
|
| 498 |
+
|
| 499 |
+
fv = [0.0]*len(x)
|
| 500 |
+
|
| 501 |
+
c = 0.5 * (a + b)
|
| 502 |
+
h = 0.5 * (b - a)
|
| 503 |
+
|
| 504 |
+
# Gauss-Kronrod
|
| 505 |
+
s_k = 0.0
|
| 506 |
+
s_k_abs = 0.0
|
| 507 |
+
for i in range(len(x)):
|
| 508 |
+
ff = f(c + h*x[i])
|
| 509 |
+
fv[i] = ff
|
| 510 |
+
|
| 511 |
+
vv = v[i]
|
| 512 |
+
|
| 513 |
+
# \int f(x)
|
| 514 |
+
s_k += vv * ff
|
| 515 |
+
# \int |f(x)|
|
| 516 |
+
s_k_abs += vv * abs(ff)
|
| 517 |
+
|
| 518 |
+
# Gauss
|
| 519 |
+
s_g = 0.0
|
| 520 |
+
for i in range(len(w)):
|
| 521 |
+
s_g += w[i] * fv[2*i + 1]
|
| 522 |
+
|
| 523 |
+
# Quadrature of abs-deviation from average
|
| 524 |
+
s_k_dabs = 0.0
|
| 525 |
+
y0 = s_k / 2.0
|
| 526 |
+
for i in range(len(x)):
|
| 527 |
+
# \int |f(x) - y0|
|
| 528 |
+
s_k_dabs += v[i] * abs(fv[i] - y0)
|
| 529 |
+
|
| 530 |
+
# Use similar error estimation as quadpack
|
| 531 |
+
err = float(norm_func((s_k - s_g) * h))
|
| 532 |
+
dabs = float(norm_func(s_k_dabs * h))
|
| 533 |
+
if dabs != 0 and err != 0:
|
| 534 |
+
err = dabs * min(1.0, (200 * err / dabs)**1.5)
|
| 535 |
+
|
| 536 |
+
eps = sys.float_info.epsilon
|
| 537 |
+
round_err = float(norm_func(50 * eps * h * s_k_abs))
|
| 538 |
+
|
| 539 |
+
if round_err > sys.float_info.min:
|
| 540 |
+
err = max(err, round_err)
|
| 541 |
+
|
| 542 |
+
return h * s_k, err, round_err
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def _quadrature_gk21(a, b, f, norm_func):
|
| 546 |
+
"""
|
| 547 |
+
Gauss-Kronrod 21 quadrature with error estimate
|
| 548 |
+
"""
|
| 549 |
+
# Gauss-Kronrod points
|
| 550 |
+
x = (0.995657163025808080735527280689003,
|
| 551 |
+
0.973906528517171720077964012084452,
|
| 552 |
+
0.930157491355708226001207180059508,
|
| 553 |
+
0.865063366688984510732096688423493,
|
| 554 |
+
0.780817726586416897063717578345042,
|
| 555 |
+
0.679409568299024406234327365114874,
|
| 556 |
+
0.562757134668604683339000099272694,
|
| 557 |
+
0.433395394129247190799265943165784,
|
| 558 |
+
0.294392862701460198131126603103866,
|
| 559 |
+
0.148874338981631210884826001129720,
|
| 560 |
+
0,
|
| 561 |
+
-0.148874338981631210884826001129720,
|
| 562 |
+
-0.294392862701460198131126603103866,
|
| 563 |
+
-0.433395394129247190799265943165784,
|
| 564 |
+
-0.562757134668604683339000099272694,
|
| 565 |
+
-0.679409568299024406234327365114874,
|
| 566 |
+
-0.780817726586416897063717578345042,
|
| 567 |
+
-0.865063366688984510732096688423493,
|
| 568 |
+
-0.930157491355708226001207180059508,
|
| 569 |
+
-0.973906528517171720077964012084452,
|
| 570 |
+
-0.995657163025808080735527280689003)
|
| 571 |
+
|
| 572 |
+
# 10-point weights
|
| 573 |
+
w = (0.066671344308688137593568809893332,
|
| 574 |
+
0.149451349150580593145776339657697,
|
| 575 |
+
0.219086362515982043995534934228163,
|
| 576 |
+
0.269266719309996355091226921569469,
|
| 577 |
+
0.295524224714752870173892994651338,
|
| 578 |
+
0.295524224714752870173892994651338,
|
| 579 |
+
0.269266719309996355091226921569469,
|
| 580 |
+
0.219086362515982043995534934228163,
|
| 581 |
+
0.149451349150580593145776339657697,
|
| 582 |
+
0.066671344308688137593568809893332)
|
| 583 |
+
|
| 584 |
+
# 21-point weights
|
| 585 |
+
v = (0.011694638867371874278064396062192,
|
| 586 |
+
0.032558162307964727478818972459390,
|
| 587 |
+
0.054755896574351996031381300244580,
|
| 588 |
+
0.075039674810919952767043140916190,
|
| 589 |
+
0.093125454583697605535065465083366,
|
| 590 |
+
0.109387158802297641899210590325805,
|
| 591 |
+
0.123491976262065851077958109831074,
|
| 592 |
+
0.134709217311473325928054001771707,
|
| 593 |
+
0.142775938577060080797094273138717,
|
| 594 |
+
0.147739104901338491374841515972068,
|
| 595 |
+
0.149445554002916905664936468389821,
|
| 596 |
+
0.147739104901338491374841515972068,
|
| 597 |
+
0.142775938577060080797094273138717,
|
| 598 |
+
0.134709217311473325928054001771707,
|
| 599 |
+
0.123491976262065851077958109831074,
|
| 600 |
+
0.109387158802297641899210590325805,
|
| 601 |
+
0.093125454583697605535065465083366,
|
| 602 |
+
0.075039674810919952767043140916190,
|
| 603 |
+
0.054755896574351996031381300244580,
|
| 604 |
+
0.032558162307964727478818972459390,
|
| 605 |
+
0.011694638867371874278064396062192)
|
| 606 |
+
|
| 607 |
+
return _quadrature_gk(a, b, f, norm_func, x, w, v)
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
_quadrature_gk21.num_eval = 21
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _quadrature_gk15(a, b, f, norm_func):
|
| 614 |
+
"""
|
| 615 |
+
Gauss-Kronrod 15 quadrature with error estimate
|
| 616 |
+
"""
|
| 617 |
+
# Gauss-Kronrod points
|
| 618 |
+
x = (0.991455371120812639206854697526329,
|
| 619 |
+
0.949107912342758524526189684047851,
|
| 620 |
+
0.864864423359769072789712788640926,
|
| 621 |
+
0.741531185599394439863864773280788,
|
| 622 |
+
0.586087235467691130294144838258730,
|
| 623 |
+
0.405845151377397166906606412076961,
|
| 624 |
+
0.207784955007898467600689403773245,
|
| 625 |
+
0.000000000000000000000000000000000,
|
| 626 |
+
-0.207784955007898467600689403773245,
|
| 627 |
+
-0.405845151377397166906606412076961,
|
| 628 |
+
-0.586087235467691130294144838258730,
|
| 629 |
+
-0.741531185599394439863864773280788,
|
| 630 |
+
-0.864864423359769072789712788640926,
|
| 631 |
+
-0.949107912342758524526189684047851,
|
| 632 |
+
-0.991455371120812639206854697526329)
|
| 633 |
+
|
| 634 |
+
# 7-point weights
|
| 635 |
+
w = (0.129484966168869693270611432679082,
|
| 636 |
+
0.279705391489276667901467771423780,
|
| 637 |
+
0.381830050505118944950369775488975,
|
| 638 |
+
0.417959183673469387755102040816327,
|
| 639 |
+
0.381830050505118944950369775488975,
|
| 640 |
+
0.279705391489276667901467771423780,
|
| 641 |
+
0.129484966168869693270611432679082)
|
| 642 |
+
|
| 643 |
+
# 15-point weights
|
| 644 |
+
v = (0.022935322010529224963732008058970,
|
| 645 |
+
0.063092092629978553290700663189204,
|
| 646 |
+
0.104790010322250183839876322541518,
|
| 647 |
+
0.140653259715525918745189590510238,
|
| 648 |
+
0.169004726639267902826583426598550,
|
| 649 |
+
0.190350578064785409913256402421014,
|
| 650 |
+
0.204432940075298892414161999234649,
|
| 651 |
+
0.209482141084727828012999174891714,
|
| 652 |
+
0.204432940075298892414161999234649,
|
| 653 |
+
0.190350578064785409913256402421014,
|
| 654 |
+
0.169004726639267902826583426598550,
|
| 655 |
+
0.140653259715525918745189590510238,
|
| 656 |
+
0.104790010322250183839876322541518,
|
| 657 |
+
0.063092092629978553290700663189204,
|
| 658 |
+
0.022935322010529224963732008058970)
|
| 659 |
+
|
| 660 |
+
return _quadrature_gk(a, b, f, norm_func, x, w, v)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
_quadrature_gk15.num_eval = 15
|
parrot/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (16.9 kB). View file
|
|
|
parrot/lib/python3.10/site-packages/scipy/integrate/odepack.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
# Use the `scipy.integrate` namespace for importing the functions
|
| 3 |
+
# included below.
|
| 4 |
+
|
| 5 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 6 |
+
|
| 7 |
+
__all__ = ['odeint', 'ODEintWarning'] # noqa: F822
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def __dir__():
|
| 11 |
+
return __all__
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
return _sub_module_deprecation(sub_package="integrate", module="odepack",
|
| 16 |
+
private_modules=["_odepack_py"], all=__all__,
|
| 17 |
+
attribute=name)
|
parrot/lib/python3.10/site-packages/scipy/integrate/tests/__init__.py
ADDED
|
File without changes
|
parrot/lib/python3.10/site-packages/scipy/integrate/tests/test_bvp.py
ADDED
|
@@ -0,0 +1,711 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
try:
|
| 4 |
+
from StringIO import StringIO
|
| 5 |
+
except ImportError:
|
| 6 |
+
from io import StringIO
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
from numpy.testing import (assert_, assert_array_equal, assert_allclose,
|
| 10 |
+
assert_equal)
|
| 11 |
+
from pytest import raises as assert_raises
|
| 12 |
+
|
| 13 |
+
from scipy.sparse import coo_matrix
|
| 14 |
+
from scipy.special import erf
|
| 15 |
+
from scipy.integrate._bvp import (modify_mesh, estimate_fun_jac,
|
| 16 |
+
estimate_bc_jac, compute_jac_indices,
|
| 17 |
+
construct_global_jac, solve_bvp)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def exp_fun(x, y):
|
| 21 |
+
return np.vstack((y[1], y[0]))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def exp_fun_jac(x, y):
|
| 25 |
+
df_dy = np.empty((2, 2, x.shape[0]))
|
| 26 |
+
df_dy[0, 0] = 0
|
| 27 |
+
df_dy[0, 1] = 1
|
| 28 |
+
df_dy[1, 0] = 1
|
| 29 |
+
df_dy[1, 1] = 0
|
| 30 |
+
return df_dy
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def exp_bc(ya, yb):
|
| 34 |
+
return np.hstack((ya[0] - 1, yb[0]))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def exp_bc_complex(ya, yb):
|
| 38 |
+
return np.hstack((ya[0] - 1 - 1j, yb[0]))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def exp_bc_jac(ya, yb):
|
| 42 |
+
dbc_dya = np.array([
|
| 43 |
+
[1, 0],
|
| 44 |
+
[0, 0]
|
| 45 |
+
])
|
| 46 |
+
dbc_dyb = np.array([
|
| 47 |
+
[0, 0],
|
| 48 |
+
[1, 0]
|
| 49 |
+
])
|
| 50 |
+
return dbc_dya, dbc_dyb
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def exp_sol(x):
|
| 54 |
+
return (np.exp(-x) - np.exp(x - 2)) / (1 - np.exp(-2))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def sl_fun(x, y, p):
|
| 58 |
+
return np.vstack((y[1], -p[0]**2 * y[0]))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def sl_fun_jac(x, y, p):
|
| 62 |
+
n, m = y.shape
|
| 63 |
+
df_dy = np.empty((n, 2, m))
|
| 64 |
+
df_dy[0, 0] = 0
|
| 65 |
+
df_dy[0, 1] = 1
|
| 66 |
+
df_dy[1, 0] = -p[0]**2
|
| 67 |
+
df_dy[1, 1] = 0
|
| 68 |
+
|
| 69 |
+
df_dp = np.empty((n, 1, m))
|
| 70 |
+
df_dp[0, 0] = 0
|
| 71 |
+
df_dp[1, 0] = -2 * p[0] * y[0]
|
| 72 |
+
|
| 73 |
+
return df_dy, df_dp
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def sl_bc(ya, yb, p):
|
| 77 |
+
return np.hstack((ya[0], yb[0], ya[1] - p[0]))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def sl_bc_jac(ya, yb, p):
|
| 81 |
+
dbc_dya = np.zeros((3, 2))
|
| 82 |
+
dbc_dya[0, 0] = 1
|
| 83 |
+
dbc_dya[2, 1] = 1
|
| 84 |
+
|
| 85 |
+
dbc_dyb = np.zeros((3, 2))
|
| 86 |
+
dbc_dyb[1, 0] = 1
|
| 87 |
+
|
| 88 |
+
dbc_dp = np.zeros((3, 1))
|
| 89 |
+
dbc_dp[2, 0] = -1
|
| 90 |
+
|
| 91 |
+
return dbc_dya, dbc_dyb, dbc_dp
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def sl_sol(x, p):
|
| 95 |
+
return np.sin(p[0] * x)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def emden_fun(x, y):
|
| 99 |
+
return np.vstack((y[1], -y[0]**5))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def emden_fun_jac(x, y):
|
| 103 |
+
df_dy = np.empty((2, 2, x.shape[0]))
|
| 104 |
+
df_dy[0, 0] = 0
|
| 105 |
+
df_dy[0, 1] = 1
|
| 106 |
+
df_dy[1, 0] = -5 * y[0]**4
|
| 107 |
+
df_dy[1, 1] = 0
|
| 108 |
+
return df_dy
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def emden_bc(ya, yb):
|
| 112 |
+
return np.array([ya[1], yb[0] - (3/4)**0.5])
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def emden_bc_jac(ya, yb):
|
| 116 |
+
dbc_dya = np.array([
|
| 117 |
+
[0, 1],
|
| 118 |
+
[0, 0]
|
| 119 |
+
])
|
| 120 |
+
dbc_dyb = np.array([
|
| 121 |
+
[0, 0],
|
| 122 |
+
[1, 0]
|
| 123 |
+
])
|
| 124 |
+
return dbc_dya, dbc_dyb
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def emden_sol(x):
|
| 128 |
+
return (1 + x**2/3)**-0.5
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def undefined_fun(x, y):
|
| 132 |
+
return np.zeros_like(y)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def undefined_bc(ya, yb):
|
| 136 |
+
return np.array([ya[0], yb[0] - 1])
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def big_fun(x, y):
|
| 140 |
+
f = np.zeros_like(y)
|
| 141 |
+
f[::2] = y[1::2]
|
| 142 |
+
return f
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def big_bc(ya, yb):
|
| 146 |
+
return np.hstack((ya[::2], yb[::2] - 1))
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def big_sol(x, n):
|
| 150 |
+
y = np.ones((2 * n, x.size))
|
| 151 |
+
y[::2] = x
|
| 152 |
+
return x
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def big_fun_with_parameters(x, y, p):
|
| 156 |
+
""" Big version of sl_fun, with two parameters.
|
| 157 |
+
|
| 158 |
+
The two differential equations represented by sl_fun are broadcast to the
|
| 159 |
+
number of rows of y, rotating between the parameters p[0] and p[1].
|
| 160 |
+
Here are the differential equations:
|
| 161 |
+
|
| 162 |
+
dy[0]/dt = y[1]
|
| 163 |
+
dy[1]/dt = -p[0]**2 * y[0]
|
| 164 |
+
dy[2]/dt = y[3]
|
| 165 |
+
dy[3]/dt = -p[1]**2 * y[2]
|
| 166 |
+
dy[4]/dt = y[5]
|
| 167 |
+
dy[5]/dt = -p[0]**2 * y[4]
|
| 168 |
+
dy[6]/dt = y[7]
|
| 169 |
+
dy[7]/dt = -p[1]**2 * y[6]
|
| 170 |
+
.
|
| 171 |
+
.
|
| 172 |
+
.
|
| 173 |
+
|
| 174 |
+
"""
|
| 175 |
+
f = np.zeros_like(y)
|
| 176 |
+
f[::2] = y[1::2]
|
| 177 |
+
f[1::4] = -p[0]**2 * y[::4]
|
| 178 |
+
f[3::4] = -p[1]**2 * y[2::4]
|
| 179 |
+
return f
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def big_fun_with_parameters_jac(x, y, p):
|
| 183 |
+
# big version of sl_fun_jac, with two parameters
|
| 184 |
+
n, m = y.shape
|
| 185 |
+
df_dy = np.zeros((n, n, m))
|
| 186 |
+
df_dy[range(0, n, 2), range(1, n, 2)] = 1
|
| 187 |
+
df_dy[range(1, n, 4), range(0, n, 4)] = -p[0]**2
|
| 188 |
+
df_dy[range(3, n, 4), range(2, n, 4)] = -p[1]**2
|
| 189 |
+
|
| 190 |
+
df_dp = np.zeros((n, 2, m))
|
| 191 |
+
df_dp[range(1, n, 4), 0] = -2 * p[0] * y[range(0, n, 4)]
|
| 192 |
+
df_dp[range(3, n, 4), 1] = -2 * p[1] * y[range(2, n, 4)]
|
| 193 |
+
|
| 194 |
+
return df_dy, df_dp
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def big_bc_with_parameters(ya, yb, p):
|
| 198 |
+
# big version of sl_bc, with two parameters
|
| 199 |
+
return np.hstack((ya[::2], yb[::2], ya[1] - p[0], ya[3] - p[1]))
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def big_bc_with_parameters_jac(ya, yb, p):
|
| 203 |
+
# big version of sl_bc_jac, with two parameters
|
| 204 |
+
n = ya.shape[0]
|
| 205 |
+
dbc_dya = np.zeros((n + 2, n))
|
| 206 |
+
dbc_dyb = np.zeros((n + 2, n))
|
| 207 |
+
|
| 208 |
+
dbc_dya[range(n // 2), range(0, n, 2)] = 1
|
| 209 |
+
dbc_dyb[range(n // 2, n), range(0, n, 2)] = 1
|
| 210 |
+
|
| 211 |
+
dbc_dp = np.zeros((n + 2, 2))
|
| 212 |
+
dbc_dp[n, 0] = -1
|
| 213 |
+
dbc_dya[n, 1] = 1
|
| 214 |
+
dbc_dp[n + 1, 1] = -1
|
| 215 |
+
dbc_dya[n + 1, 3] = 1
|
| 216 |
+
|
| 217 |
+
return dbc_dya, dbc_dyb, dbc_dp
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def big_sol_with_parameters(x, p):
|
| 221 |
+
# big version of sl_sol, with two parameters
|
| 222 |
+
return np.vstack((np.sin(p[0] * x), np.sin(p[1] * x)))
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def shock_fun(x, y):
|
| 226 |
+
eps = 1e-3
|
| 227 |
+
return np.vstack((
|
| 228 |
+
y[1],
|
| 229 |
+
-(x * y[1] + eps * np.pi**2 * np.cos(np.pi * x) +
|
| 230 |
+
np.pi * x * np.sin(np.pi * x)) / eps
|
| 231 |
+
))
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def shock_bc(ya, yb):
|
| 235 |
+
return np.array([ya[0] + 2, yb[0]])
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def shock_sol(x):
|
| 239 |
+
eps = 1e-3
|
| 240 |
+
k = np.sqrt(2 * eps)
|
| 241 |
+
return np.cos(np.pi * x) + erf(x / k) / erf(1 / k)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def nonlin_bc_fun(x, y):
|
| 245 |
+
# laplace eq.
|
| 246 |
+
return np.stack([y[1], np.zeros_like(x)])
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def nonlin_bc_bc(ya, yb):
|
| 250 |
+
phiA, phipA = ya
|
| 251 |
+
phiC, phipC = yb
|
| 252 |
+
|
| 253 |
+
kappa, ioA, ioC, V, f = 1.64, 0.01, 1.0e-4, 0.5, 38.9
|
| 254 |
+
|
| 255 |
+
# Butler-Volmer Kinetics at Anode
|
| 256 |
+
hA = 0.0-phiA-0.0
|
| 257 |
+
iA = ioA * (np.exp(f*hA) - np.exp(-f*hA))
|
| 258 |
+
res0 = iA + kappa * phipA
|
| 259 |
+
|
| 260 |
+
# Butler-Volmer Kinetics at Cathode
|
| 261 |
+
hC = V - phiC - 1.0
|
| 262 |
+
iC = ioC * (np.exp(f*hC) - np.exp(-f*hC))
|
| 263 |
+
res1 = iC - kappa*phipC
|
| 264 |
+
|
| 265 |
+
return np.array([res0, res1])
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def nonlin_bc_sol(x):
|
| 269 |
+
return -0.13426436116763119 - 1.1308709 * x
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def test_modify_mesh():
|
| 273 |
+
x = np.array([0, 1, 3, 9], dtype=float)
|
| 274 |
+
x_new = modify_mesh(x, np.array([0]), np.array([2]))
|
| 275 |
+
assert_array_equal(x_new, np.array([0, 0.5, 1, 3, 5, 7, 9]))
|
| 276 |
+
|
| 277 |
+
x = np.array([-6, -3, 0, 3, 6], dtype=float)
|
| 278 |
+
x_new = modify_mesh(x, np.array([1], dtype=int), np.array([0, 2, 3]))
|
| 279 |
+
assert_array_equal(x_new, [-6, -5, -4, -3, -1.5, 0, 1, 2, 3, 4, 5, 6])
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def test_compute_fun_jac():
|
| 283 |
+
x = np.linspace(0, 1, 5)
|
| 284 |
+
y = np.empty((2, x.shape[0]))
|
| 285 |
+
y[0] = 0.01
|
| 286 |
+
y[1] = 0.02
|
| 287 |
+
p = np.array([])
|
| 288 |
+
df_dy, df_dp = estimate_fun_jac(lambda x, y, p: exp_fun(x, y), x, y, p)
|
| 289 |
+
df_dy_an = exp_fun_jac(x, y)
|
| 290 |
+
assert_allclose(df_dy, df_dy_an)
|
| 291 |
+
assert_(df_dp is None)
|
| 292 |
+
|
| 293 |
+
x = np.linspace(0, np.pi, 5)
|
| 294 |
+
y = np.empty((2, x.shape[0]))
|
| 295 |
+
y[0] = np.sin(x)
|
| 296 |
+
y[1] = np.cos(x)
|
| 297 |
+
p = np.array([1.0])
|
| 298 |
+
df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p)
|
| 299 |
+
df_dy_an, df_dp_an = sl_fun_jac(x, y, p)
|
| 300 |
+
assert_allclose(df_dy, df_dy_an)
|
| 301 |
+
assert_allclose(df_dp, df_dp_an)
|
| 302 |
+
|
| 303 |
+
x = np.linspace(0, 1, 10)
|
| 304 |
+
y = np.empty((2, x.shape[0]))
|
| 305 |
+
y[0] = (3/4)**0.5
|
| 306 |
+
y[1] = 1e-4
|
| 307 |
+
p = np.array([])
|
| 308 |
+
df_dy, df_dp = estimate_fun_jac(lambda x, y, p: emden_fun(x, y), x, y, p)
|
| 309 |
+
df_dy_an = emden_fun_jac(x, y)
|
| 310 |
+
assert_allclose(df_dy, df_dy_an)
|
| 311 |
+
assert_(df_dp is None)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def test_compute_bc_jac():
|
| 315 |
+
ya = np.array([-1.0, 2])
|
| 316 |
+
yb = np.array([0.5, 3])
|
| 317 |
+
p = np.array([])
|
| 318 |
+
dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(
|
| 319 |
+
lambda ya, yb, p: exp_bc(ya, yb), ya, yb, p)
|
| 320 |
+
dbc_dya_an, dbc_dyb_an = exp_bc_jac(ya, yb)
|
| 321 |
+
assert_allclose(dbc_dya, dbc_dya_an)
|
| 322 |
+
assert_allclose(dbc_dyb, dbc_dyb_an)
|
| 323 |
+
assert_(dbc_dp is None)
|
| 324 |
+
|
| 325 |
+
ya = np.array([0.0, 1])
|
| 326 |
+
yb = np.array([0.0, -1])
|
| 327 |
+
p = np.array([0.5])
|
| 328 |
+
dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, ya, yb, p)
|
| 329 |
+
dbc_dya_an, dbc_dyb_an, dbc_dp_an = sl_bc_jac(ya, yb, p)
|
| 330 |
+
assert_allclose(dbc_dya, dbc_dya_an)
|
| 331 |
+
assert_allclose(dbc_dyb, dbc_dyb_an)
|
| 332 |
+
assert_allclose(dbc_dp, dbc_dp_an)
|
| 333 |
+
|
| 334 |
+
ya = np.array([0.5, 100])
|
| 335 |
+
yb = np.array([-1000, 10.5])
|
| 336 |
+
p = np.array([])
|
| 337 |
+
dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(
|
| 338 |
+
lambda ya, yb, p: emden_bc(ya, yb), ya, yb, p)
|
| 339 |
+
dbc_dya_an, dbc_dyb_an = emden_bc_jac(ya, yb)
|
| 340 |
+
assert_allclose(dbc_dya, dbc_dya_an)
|
| 341 |
+
assert_allclose(dbc_dyb, dbc_dyb_an)
|
| 342 |
+
assert_(dbc_dp is None)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def test_compute_jac_indices():
|
| 346 |
+
n = 2
|
| 347 |
+
m = 4
|
| 348 |
+
k = 2
|
| 349 |
+
i, j = compute_jac_indices(n, m, k)
|
| 350 |
+
s = coo_matrix((np.ones_like(i), (i, j))).toarray()
|
| 351 |
+
s_true = np.array([
|
| 352 |
+
[1, 1, 1, 1, 0, 0, 0, 0, 1, 1],
|
| 353 |
+
[1, 1, 1, 1, 0, 0, 0, 0, 1, 1],
|
| 354 |
+
[0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
|
| 355 |
+
[0, 0, 1, 1, 1, 1, 0, 0, 1, 1],
|
| 356 |
+
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
|
| 357 |
+
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1],
|
| 358 |
+
[1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
|
| 359 |
+
[1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
|
| 360 |
+
[1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
|
| 361 |
+
[1, 1, 0, 0, 0, 0, 1, 1, 1, 1],
|
| 362 |
+
])
|
| 363 |
+
assert_array_equal(s, s_true)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def test_compute_global_jac():
|
| 367 |
+
n = 2
|
| 368 |
+
m = 5
|
| 369 |
+
k = 1
|
| 370 |
+
i_jac, j_jac = compute_jac_indices(2, 5, 1)
|
| 371 |
+
x = np.linspace(0, 1, 5)
|
| 372 |
+
h = np.diff(x)
|
| 373 |
+
y = np.vstack((np.sin(np.pi * x), np.pi * np.cos(np.pi * x)))
|
| 374 |
+
p = np.array([3.0])
|
| 375 |
+
|
| 376 |
+
f = sl_fun(x, y, p)
|
| 377 |
+
|
| 378 |
+
x_middle = x[:-1] + 0.5 * h
|
| 379 |
+
y_middle = 0.5 * (y[:, :-1] + y[:, 1:]) - h/8 * (f[:, 1:] - f[:, :-1])
|
| 380 |
+
|
| 381 |
+
df_dy, df_dp = sl_fun_jac(x, y, p)
|
| 382 |
+
df_dy_middle, df_dp_middle = sl_fun_jac(x_middle, y_middle, p)
|
| 383 |
+
dbc_dya, dbc_dyb, dbc_dp = sl_bc_jac(y[:, 0], y[:, -1], p)
|
| 384 |
+
|
| 385 |
+
J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle,
|
| 386 |
+
df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp)
|
| 387 |
+
J = J.toarray()
|
| 388 |
+
|
| 389 |
+
def J_block(h, p):
|
| 390 |
+
return np.array([
|
| 391 |
+
[h**2*p**2/12 - 1, -0.5*h, -h**2*p**2/12 + 1, -0.5*h],
|
| 392 |
+
[0.5*h*p**2, h**2*p**2/12 - 1, 0.5*h*p**2, 1 - h**2*p**2/12]
|
| 393 |
+
])
|
| 394 |
+
|
| 395 |
+
J_true = np.zeros((m * n + k, m * n + k))
|
| 396 |
+
for i in range(m - 1):
|
| 397 |
+
J_true[i * n: (i + 1) * n, i * n: (i + 2) * n] = J_block(h[i], p[0])
|
| 398 |
+
|
| 399 |
+
J_true[:(m - 1) * n:2, -1] = p * h**2/6 * (y[0, :-1] - y[0, 1:])
|
| 400 |
+
J_true[1:(m - 1) * n:2, -1] = p * (h * (y[0, :-1] + y[0, 1:]) +
|
| 401 |
+
h**2/6 * (y[1, :-1] - y[1, 1:]))
|
| 402 |
+
|
| 403 |
+
J_true[8, 0] = 1
|
| 404 |
+
J_true[9, 8] = 1
|
| 405 |
+
J_true[10, 1] = 1
|
| 406 |
+
J_true[10, 10] = -1
|
| 407 |
+
|
| 408 |
+
assert_allclose(J, J_true, rtol=1e-10)
|
| 409 |
+
|
| 410 |
+
df_dy, df_dp = estimate_fun_jac(sl_fun, x, y, p)
|
| 411 |
+
df_dy_middle, df_dp_middle = estimate_fun_jac(sl_fun, x_middle, y_middle, p)
|
| 412 |
+
dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(sl_bc, y[:, 0], y[:, -1], p)
|
| 413 |
+
J = construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle,
|
| 414 |
+
df_dp, df_dp_middle, dbc_dya, dbc_dyb, dbc_dp)
|
| 415 |
+
J = J.toarray()
|
| 416 |
+
assert_allclose(J, J_true, rtol=2e-8, atol=2e-8)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def test_parameter_validation():
|
| 420 |
+
x = [0, 1, 0.5]
|
| 421 |
+
y = np.zeros((2, 3))
|
| 422 |
+
assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y)
|
| 423 |
+
|
| 424 |
+
x = np.linspace(0, 1, 5)
|
| 425 |
+
y = np.zeros((2, 4))
|
| 426 |
+
assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y)
|
| 427 |
+
|
| 428 |
+
def fun(x, y, p):
|
| 429 |
+
return exp_fun(x, y)
|
| 430 |
+
def bc(ya, yb, p):
|
| 431 |
+
return exp_bc(ya, yb)
|
| 432 |
+
|
| 433 |
+
y = np.zeros((2, x.shape[0]))
|
| 434 |
+
assert_raises(ValueError, solve_bvp, fun, bc, x, y, p=[1])
|
| 435 |
+
|
| 436 |
+
def wrong_shape_fun(x, y):
|
| 437 |
+
return np.zeros(3)
|
| 438 |
+
|
| 439 |
+
assert_raises(ValueError, solve_bvp, wrong_shape_fun, bc, x, y)
|
| 440 |
+
|
| 441 |
+
S = np.array([[0, 0]])
|
| 442 |
+
assert_raises(ValueError, solve_bvp, exp_fun, exp_bc, x, y, S=S)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def test_no_params():
|
| 446 |
+
x = np.linspace(0, 1, 5)
|
| 447 |
+
x_test = np.linspace(0, 1, 100)
|
| 448 |
+
y = np.zeros((2, x.shape[0]))
|
| 449 |
+
for fun_jac in [None, exp_fun_jac]:
|
| 450 |
+
for bc_jac in [None, exp_bc_jac]:
|
| 451 |
+
sol = solve_bvp(exp_fun, exp_bc, x, y, fun_jac=fun_jac,
|
| 452 |
+
bc_jac=bc_jac)
|
| 453 |
+
|
| 454 |
+
assert_equal(sol.status, 0)
|
| 455 |
+
assert_(sol.success)
|
| 456 |
+
|
| 457 |
+
assert_equal(sol.x.size, 5)
|
| 458 |
+
|
| 459 |
+
sol_test = sol.sol(x_test)
|
| 460 |
+
|
| 461 |
+
assert_allclose(sol_test[0], exp_sol(x_test), atol=1e-5)
|
| 462 |
+
|
| 463 |
+
f_test = exp_fun(x_test, sol_test)
|
| 464 |
+
r = sol.sol(x_test, 1) - f_test
|
| 465 |
+
rel_res = r / (1 + np.abs(f_test))
|
| 466 |
+
norm_res = np.sum(rel_res**2, axis=0)**0.5
|
| 467 |
+
assert_(np.all(norm_res < 1e-3))
|
| 468 |
+
|
| 469 |
+
assert_(np.all(sol.rms_residuals < 1e-3))
|
| 470 |
+
assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
|
| 471 |
+
assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def test_with_params():
|
| 475 |
+
x = np.linspace(0, np.pi, 5)
|
| 476 |
+
x_test = np.linspace(0, np.pi, 100)
|
| 477 |
+
y = np.ones((2, x.shape[0]))
|
| 478 |
+
|
| 479 |
+
for fun_jac in [None, sl_fun_jac]:
|
| 480 |
+
for bc_jac in [None, sl_bc_jac]:
|
| 481 |
+
sol = solve_bvp(sl_fun, sl_bc, x, y, p=[0.5], fun_jac=fun_jac,
|
| 482 |
+
bc_jac=bc_jac)
|
| 483 |
+
|
| 484 |
+
assert_equal(sol.status, 0)
|
| 485 |
+
assert_(sol.success)
|
| 486 |
+
|
| 487 |
+
assert_(sol.x.size < 10)
|
| 488 |
+
|
| 489 |
+
assert_allclose(sol.p, [1], rtol=1e-4)
|
| 490 |
+
|
| 491 |
+
sol_test = sol.sol(x_test)
|
| 492 |
+
|
| 493 |
+
assert_allclose(sol_test[0], sl_sol(x_test, [1]),
|
| 494 |
+
rtol=1e-4, atol=1e-4)
|
| 495 |
+
|
| 496 |
+
f_test = sl_fun(x_test, sol_test, [1])
|
| 497 |
+
r = sol.sol(x_test, 1) - f_test
|
| 498 |
+
rel_res = r / (1 + np.abs(f_test))
|
| 499 |
+
norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
|
| 500 |
+
assert_(np.all(norm_res < 1e-3))
|
| 501 |
+
|
| 502 |
+
assert_(np.all(sol.rms_residuals < 1e-3))
|
| 503 |
+
assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
|
| 504 |
+
assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def test_singular_term():
|
| 508 |
+
x = np.linspace(0, 1, 10)
|
| 509 |
+
x_test = np.linspace(0.05, 1, 100)
|
| 510 |
+
y = np.empty((2, 10))
|
| 511 |
+
y[0] = (3/4)**0.5
|
| 512 |
+
y[1] = 1e-4
|
| 513 |
+
S = np.array([[0, 0], [0, -2]])
|
| 514 |
+
|
| 515 |
+
for fun_jac in [None, emden_fun_jac]:
|
| 516 |
+
for bc_jac in [None, emden_bc_jac]:
|
| 517 |
+
sol = solve_bvp(emden_fun, emden_bc, x, y, S=S, fun_jac=fun_jac,
|
| 518 |
+
bc_jac=bc_jac)
|
| 519 |
+
|
| 520 |
+
assert_equal(sol.status, 0)
|
| 521 |
+
assert_(sol.success)
|
| 522 |
+
|
| 523 |
+
assert_equal(sol.x.size, 10)
|
| 524 |
+
|
| 525 |
+
sol_test = sol.sol(x_test)
|
| 526 |
+
assert_allclose(sol_test[0], emden_sol(x_test), atol=1e-5)
|
| 527 |
+
|
| 528 |
+
f_test = emden_fun(x_test, sol_test) + S.dot(sol_test) / x_test
|
| 529 |
+
r = sol.sol(x_test, 1) - f_test
|
| 530 |
+
rel_res = r / (1 + np.abs(f_test))
|
| 531 |
+
norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
|
| 532 |
+
|
| 533 |
+
assert_(np.all(norm_res < 1e-3))
|
| 534 |
+
assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
|
| 535 |
+
assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def test_complex():
|
| 539 |
+
# The test is essentially the same as test_no_params, but boundary
|
| 540 |
+
# conditions are turned into complex.
|
| 541 |
+
x = np.linspace(0, 1, 5)
|
| 542 |
+
x_test = np.linspace(0, 1, 100)
|
| 543 |
+
y = np.zeros((2, x.shape[0]), dtype=complex)
|
| 544 |
+
for fun_jac in [None, exp_fun_jac]:
|
| 545 |
+
for bc_jac in [None, exp_bc_jac]:
|
| 546 |
+
sol = solve_bvp(exp_fun, exp_bc_complex, x, y, fun_jac=fun_jac,
|
| 547 |
+
bc_jac=bc_jac)
|
| 548 |
+
|
| 549 |
+
assert_equal(sol.status, 0)
|
| 550 |
+
assert_(sol.success)
|
| 551 |
+
|
| 552 |
+
sol_test = sol.sol(x_test)
|
| 553 |
+
|
| 554 |
+
assert_allclose(sol_test[0].real, exp_sol(x_test), atol=1e-5)
|
| 555 |
+
assert_allclose(sol_test[0].imag, exp_sol(x_test), atol=1e-5)
|
| 556 |
+
|
| 557 |
+
f_test = exp_fun(x_test, sol_test)
|
| 558 |
+
r = sol.sol(x_test, 1) - f_test
|
| 559 |
+
rel_res = r / (1 + np.abs(f_test))
|
| 560 |
+
norm_res = np.sum(np.real(rel_res * np.conj(rel_res)),
|
| 561 |
+
axis=0) ** 0.5
|
| 562 |
+
assert_(np.all(norm_res < 1e-3))
|
| 563 |
+
|
| 564 |
+
assert_(np.all(sol.rms_residuals < 1e-3))
|
| 565 |
+
assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
|
| 566 |
+
assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def test_failures():
|
| 570 |
+
x = np.linspace(0, 1, 2)
|
| 571 |
+
y = np.zeros((2, x.size))
|
| 572 |
+
res = solve_bvp(exp_fun, exp_bc, x, y, tol=1e-5, max_nodes=5)
|
| 573 |
+
assert_equal(res.status, 1)
|
| 574 |
+
assert_(not res.success)
|
| 575 |
+
|
| 576 |
+
x = np.linspace(0, 1, 5)
|
| 577 |
+
y = np.zeros((2, x.size))
|
| 578 |
+
res = solve_bvp(undefined_fun, undefined_bc, x, y)
|
| 579 |
+
assert_equal(res.status, 2)
|
| 580 |
+
assert_(not res.success)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def test_big_problem():
|
| 584 |
+
n = 30
|
| 585 |
+
x = np.linspace(0, 1, 5)
|
| 586 |
+
y = np.zeros((2 * n, x.size))
|
| 587 |
+
sol = solve_bvp(big_fun, big_bc, x, y)
|
| 588 |
+
|
| 589 |
+
assert_equal(sol.status, 0)
|
| 590 |
+
assert_(sol.success)
|
| 591 |
+
|
| 592 |
+
sol_test = sol.sol(x)
|
| 593 |
+
|
| 594 |
+
assert_allclose(sol_test[0], big_sol(x, n))
|
| 595 |
+
|
| 596 |
+
f_test = big_fun(x, sol_test)
|
| 597 |
+
r = sol.sol(x, 1) - f_test
|
| 598 |
+
rel_res = r / (1 + np.abs(f_test))
|
| 599 |
+
norm_res = np.sum(np.real(rel_res * np.conj(rel_res)), axis=0) ** 0.5
|
| 600 |
+
assert_(np.all(norm_res < 1e-3))
|
| 601 |
+
|
| 602 |
+
assert_(np.all(sol.rms_residuals < 1e-3))
|
| 603 |
+
assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
|
| 604 |
+
assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def test_big_problem_with_parameters():
|
| 608 |
+
n = 30
|
| 609 |
+
x = np.linspace(0, np.pi, 5)
|
| 610 |
+
x_test = np.linspace(0, np.pi, 100)
|
| 611 |
+
y = np.ones((2 * n, x.size))
|
| 612 |
+
|
| 613 |
+
for fun_jac in [None, big_fun_with_parameters_jac]:
|
| 614 |
+
for bc_jac in [None, big_bc_with_parameters_jac]:
|
| 615 |
+
sol = solve_bvp(big_fun_with_parameters, big_bc_with_parameters, x,
|
| 616 |
+
y, p=[0.5, 0.5], fun_jac=fun_jac, bc_jac=bc_jac)
|
| 617 |
+
|
| 618 |
+
assert_equal(sol.status, 0)
|
| 619 |
+
assert_(sol.success)
|
| 620 |
+
|
| 621 |
+
assert_allclose(sol.p, [1, 1], rtol=1e-4)
|
| 622 |
+
|
| 623 |
+
sol_test = sol.sol(x_test)
|
| 624 |
+
|
| 625 |
+
for isol in range(0, n, 4):
|
| 626 |
+
assert_allclose(sol_test[isol],
|
| 627 |
+
big_sol_with_parameters(x_test, [1, 1])[0],
|
| 628 |
+
rtol=1e-4, atol=1e-4)
|
| 629 |
+
assert_allclose(sol_test[isol + 2],
|
| 630 |
+
big_sol_with_parameters(x_test, [1, 1])[1],
|
| 631 |
+
rtol=1e-4, atol=1e-4)
|
| 632 |
+
|
| 633 |
+
f_test = big_fun_with_parameters(x_test, sol_test, [1, 1])
|
| 634 |
+
r = sol.sol(x_test, 1) - f_test
|
| 635 |
+
rel_res = r / (1 + np.abs(f_test))
|
| 636 |
+
norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
|
| 637 |
+
assert_(np.all(norm_res < 1e-3))
|
| 638 |
+
|
| 639 |
+
assert_(np.all(sol.rms_residuals < 1e-3))
|
| 640 |
+
assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
|
| 641 |
+
assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def test_shock_layer():
|
| 645 |
+
x = np.linspace(-1, 1, 5)
|
| 646 |
+
x_test = np.linspace(-1, 1, 100)
|
| 647 |
+
y = np.zeros((2, x.size))
|
| 648 |
+
sol = solve_bvp(shock_fun, shock_bc, x, y)
|
| 649 |
+
|
| 650 |
+
assert_equal(sol.status, 0)
|
| 651 |
+
assert_(sol.success)
|
| 652 |
+
|
| 653 |
+
assert_(sol.x.size < 110)
|
| 654 |
+
|
| 655 |
+
sol_test = sol.sol(x_test)
|
| 656 |
+
assert_allclose(sol_test[0], shock_sol(x_test), rtol=1e-5, atol=1e-5)
|
| 657 |
+
|
| 658 |
+
f_test = shock_fun(x_test, sol_test)
|
| 659 |
+
r = sol.sol(x_test, 1) - f_test
|
| 660 |
+
rel_res = r / (1 + np.abs(f_test))
|
| 661 |
+
norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
|
| 662 |
+
|
| 663 |
+
assert_(np.all(norm_res < 1e-3))
|
| 664 |
+
assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
|
| 665 |
+
assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
def test_nonlin_bc():
|
| 669 |
+
x = np.linspace(0, 0.1, 5)
|
| 670 |
+
x_test = x
|
| 671 |
+
y = np.zeros([2, x.size])
|
| 672 |
+
sol = solve_bvp(nonlin_bc_fun, nonlin_bc_bc, x, y)
|
| 673 |
+
|
| 674 |
+
assert_equal(sol.status, 0)
|
| 675 |
+
assert_(sol.success)
|
| 676 |
+
|
| 677 |
+
assert_(sol.x.size < 8)
|
| 678 |
+
|
| 679 |
+
sol_test = sol.sol(x_test)
|
| 680 |
+
assert_allclose(sol_test[0], nonlin_bc_sol(x_test), rtol=1e-5, atol=1e-5)
|
| 681 |
+
|
| 682 |
+
f_test = nonlin_bc_fun(x_test, sol_test)
|
| 683 |
+
r = sol.sol(x_test, 1) - f_test
|
| 684 |
+
rel_res = r / (1 + np.abs(f_test))
|
| 685 |
+
norm_res = np.sum(rel_res ** 2, axis=0) ** 0.5
|
| 686 |
+
|
| 687 |
+
assert_(np.all(norm_res < 1e-3))
|
| 688 |
+
assert_allclose(sol.sol(sol.x), sol.y, rtol=1e-10, atol=1e-10)
|
| 689 |
+
assert_allclose(sol.sol(sol.x, 1), sol.yp, rtol=1e-10, atol=1e-10)
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def test_verbose():
|
| 693 |
+
# Smoke test that checks the printing does something and does not crash
|
| 694 |
+
x = np.linspace(0, 1, 5)
|
| 695 |
+
y = np.zeros((2, x.shape[0]))
|
| 696 |
+
for verbose in [0, 1, 2]:
|
| 697 |
+
old_stdout = sys.stdout
|
| 698 |
+
sys.stdout = StringIO()
|
| 699 |
+
try:
|
| 700 |
+
sol = solve_bvp(exp_fun, exp_bc, x, y, verbose=verbose)
|
| 701 |
+
text = sys.stdout.getvalue()
|
| 702 |
+
finally:
|
| 703 |
+
sys.stdout = old_stdout
|
| 704 |
+
|
| 705 |
+
assert_(sol.success)
|
| 706 |
+
if verbose == 0:
|
| 707 |
+
assert_(not text, text)
|
| 708 |
+
if verbose >= 1:
|
| 709 |
+
assert_("Solved in" in text, text)
|
| 710 |
+
if verbose >= 2:
|
| 711 |
+
assert_("Max residual" in text, text)
|
parrot/lib/python3.10/site-packages/scipy/integrate/tests/test_integrate.py
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: Nils Wagner, Ed Schofield, Pauli Virtanen, John Travers
|
| 2 |
+
"""
|
| 3 |
+
Tests for numerical integration.
|
| 4 |
+
"""
|
| 5 |
+
import numpy as np
|
| 6 |
+
from numpy import (arange, zeros, array, dot, sqrt, cos, sin, eye, pi, exp,
|
| 7 |
+
allclose)
|
| 8 |
+
|
| 9 |
+
from numpy.testing import (
|
| 10 |
+
assert_, assert_array_almost_equal,
|
| 11 |
+
assert_allclose, assert_array_equal, assert_equal, assert_warns)
|
| 12 |
+
from pytest import raises as assert_raises
|
| 13 |
+
from scipy.integrate import odeint, ode, complex_ode
|
| 14 |
+
|
| 15 |
+
#------------------------------------------------------------------------------
|
| 16 |
+
# Test ODE integrators
|
| 17 |
+
#------------------------------------------------------------------------------
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class TestOdeint:
|
| 21 |
+
# Check integrate.odeint
|
| 22 |
+
|
| 23 |
+
def _do_problem(self, problem):
|
| 24 |
+
t = arange(0.0, problem.stop_t, 0.05)
|
| 25 |
+
|
| 26 |
+
# Basic case
|
| 27 |
+
z, infodict = odeint(problem.f, problem.z0, t, full_output=True)
|
| 28 |
+
assert_(problem.verify(z, t))
|
| 29 |
+
|
| 30 |
+
# Use tfirst=True
|
| 31 |
+
z, infodict = odeint(lambda t, y: problem.f(y, t), problem.z0, t,
|
| 32 |
+
full_output=True, tfirst=True)
|
| 33 |
+
assert_(problem.verify(z, t))
|
| 34 |
+
|
| 35 |
+
if hasattr(problem, 'jac'):
|
| 36 |
+
# Use Dfun
|
| 37 |
+
z, infodict = odeint(problem.f, problem.z0, t, Dfun=problem.jac,
|
| 38 |
+
full_output=True)
|
| 39 |
+
assert_(problem.verify(z, t))
|
| 40 |
+
|
| 41 |
+
# Use Dfun and tfirst=True
|
| 42 |
+
z, infodict = odeint(lambda t, y: problem.f(y, t), problem.z0, t,
|
| 43 |
+
Dfun=lambda t, y: problem.jac(y, t),
|
| 44 |
+
full_output=True, tfirst=True)
|
| 45 |
+
assert_(problem.verify(z, t))
|
| 46 |
+
|
| 47 |
+
def test_odeint(self):
|
| 48 |
+
for problem_cls in PROBLEMS:
|
| 49 |
+
problem = problem_cls()
|
| 50 |
+
if problem.cmplx:
|
| 51 |
+
continue
|
| 52 |
+
self._do_problem(problem)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class TestODEClass:
|
| 56 |
+
|
| 57 |
+
ode_class = None # Set in subclass.
|
| 58 |
+
|
| 59 |
+
def _do_problem(self, problem, integrator, method='adams'):
|
| 60 |
+
|
| 61 |
+
# ode has callback arguments in different order than odeint
|
| 62 |
+
def f(t, z):
|
| 63 |
+
return problem.f(z, t)
|
| 64 |
+
jac = None
|
| 65 |
+
if hasattr(problem, 'jac'):
|
| 66 |
+
def jac(t, z):
|
| 67 |
+
return problem.jac(z, t)
|
| 68 |
+
|
| 69 |
+
integrator_params = {}
|
| 70 |
+
if problem.lband is not None or problem.uband is not None:
|
| 71 |
+
integrator_params['uband'] = problem.uband
|
| 72 |
+
integrator_params['lband'] = problem.lband
|
| 73 |
+
|
| 74 |
+
ig = self.ode_class(f, jac)
|
| 75 |
+
ig.set_integrator(integrator,
|
| 76 |
+
atol=problem.atol/10,
|
| 77 |
+
rtol=problem.rtol/10,
|
| 78 |
+
method=method,
|
| 79 |
+
**integrator_params)
|
| 80 |
+
|
| 81 |
+
ig.set_initial_value(problem.z0, t=0.0)
|
| 82 |
+
z = ig.integrate(problem.stop_t)
|
| 83 |
+
|
| 84 |
+
assert_array_equal(z, ig.y)
|
| 85 |
+
assert_(ig.successful(), (problem, method))
|
| 86 |
+
assert_(ig.get_return_code() > 0, (problem, method))
|
| 87 |
+
assert_(problem.verify(array([z]), problem.stop_t), (problem, method))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class TestOde(TestODEClass):
|
| 91 |
+
|
| 92 |
+
ode_class = ode
|
| 93 |
+
|
| 94 |
+
def test_vode(self):
|
| 95 |
+
# Check the vode solver
|
| 96 |
+
for problem_cls in PROBLEMS:
|
| 97 |
+
problem = problem_cls()
|
| 98 |
+
if problem.cmplx:
|
| 99 |
+
continue
|
| 100 |
+
if not problem.stiff:
|
| 101 |
+
self._do_problem(problem, 'vode', 'adams')
|
| 102 |
+
self._do_problem(problem, 'vode', 'bdf')
|
| 103 |
+
|
| 104 |
+
def test_zvode(self):
|
| 105 |
+
# Check the zvode solver
|
| 106 |
+
for problem_cls in PROBLEMS:
|
| 107 |
+
problem = problem_cls()
|
| 108 |
+
if not problem.stiff:
|
| 109 |
+
self._do_problem(problem, 'zvode', 'adams')
|
| 110 |
+
self._do_problem(problem, 'zvode', 'bdf')
|
| 111 |
+
|
| 112 |
+
def test_lsoda(self):
|
| 113 |
+
# Check the lsoda solver
|
| 114 |
+
for problem_cls in PROBLEMS:
|
| 115 |
+
problem = problem_cls()
|
| 116 |
+
if problem.cmplx:
|
| 117 |
+
continue
|
| 118 |
+
self._do_problem(problem, 'lsoda')
|
| 119 |
+
|
| 120 |
+
def test_dopri5(self):
|
| 121 |
+
# Check the dopri5 solver
|
| 122 |
+
for problem_cls in PROBLEMS:
|
| 123 |
+
problem = problem_cls()
|
| 124 |
+
if problem.cmplx:
|
| 125 |
+
continue
|
| 126 |
+
if problem.stiff:
|
| 127 |
+
continue
|
| 128 |
+
if hasattr(problem, 'jac'):
|
| 129 |
+
continue
|
| 130 |
+
self._do_problem(problem, 'dopri5')
|
| 131 |
+
|
| 132 |
+
def test_dop853(self):
|
| 133 |
+
# Check the dop853 solver
|
| 134 |
+
for problem_cls in PROBLEMS:
|
| 135 |
+
problem = problem_cls()
|
| 136 |
+
if problem.cmplx:
|
| 137 |
+
continue
|
| 138 |
+
if problem.stiff:
|
| 139 |
+
continue
|
| 140 |
+
if hasattr(problem, 'jac'):
|
| 141 |
+
continue
|
| 142 |
+
self._do_problem(problem, 'dop853')
|
| 143 |
+
|
| 144 |
+
def test_concurrent_fail(self):
|
| 145 |
+
for sol in ('vode', 'zvode', 'lsoda'):
|
| 146 |
+
def f(t, y):
|
| 147 |
+
return 1.0
|
| 148 |
+
|
| 149 |
+
r = ode(f).set_integrator(sol)
|
| 150 |
+
r.set_initial_value(0, 0)
|
| 151 |
+
|
| 152 |
+
r2 = ode(f).set_integrator(sol)
|
| 153 |
+
r2.set_initial_value(0, 0)
|
| 154 |
+
|
| 155 |
+
r.integrate(r.t + 0.1)
|
| 156 |
+
r2.integrate(r2.t + 0.1)
|
| 157 |
+
|
| 158 |
+
assert_raises(RuntimeError, r.integrate, r.t + 0.1)
|
| 159 |
+
|
| 160 |
+
def test_concurrent_ok(self):
|
| 161 |
+
def f(t, y):
|
| 162 |
+
return 1.0
|
| 163 |
+
|
| 164 |
+
for k in range(3):
|
| 165 |
+
for sol in ('vode', 'zvode', 'lsoda', 'dopri5', 'dop853'):
|
| 166 |
+
r = ode(f).set_integrator(sol)
|
| 167 |
+
r.set_initial_value(0, 0)
|
| 168 |
+
|
| 169 |
+
r2 = ode(f).set_integrator(sol)
|
| 170 |
+
r2.set_initial_value(0, 0)
|
| 171 |
+
|
| 172 |
+
r.integrate(r.t + 0.1)
|
| 173 |
+
r2.integrate(r2.t + 0.1)
|
| 174 |
+
r2.integrate(r2.t + 0.1)
|
| 175 |
+
|
| 176 |
+
assert_allclose(r.y, 0.1)
|
| 177 |
+
assert_allclose(r2.y, 0.2)
|
| 178 |
+
|
| 179 |
+
for sol in ('dopri5', 'dop853'):
|
| 180 |
+
r = ode(f).set_integrator(sol)
|
| 181 |
+
r.set_initial_value(0, 0)
|
| 182 |
+
|
| 183 |
+
r2 = ode(f).set_integrator(sol)
|
| 184 |
+
r2.set_initial_value(0, 0)
|
| 185 |
+
|
| 186 |
+
r.integrate(r.t + 0.1)
|
| 187 |
+
r.integrate(r.t + 0.1)
|
| 188 |
+
r2.integrate(r2.t + 0.1)
|
| 189 |
+
r.integrate(r.t + 0.1)
|
| 190 |
+
r2.integrate(r2.t + 0.1)
|
| 191 |
+
|
| 192 |
+
assert_allclose(r.y, 0.3)
|
| 193 |
+
assert_allclose(r2.y, 0.2)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class TestComplexOde(TestODEClass):
|
| 197 |
+
|
| 198 |
+
ode_class = complex_ode
|
| 199 |
+
|
| 200 |
+
def test_vode(self):
|
| 201 |
+
# Check the vode solver
|
| 202 |
+
for problem_cls in PROBLEMS:
|
| 203 |
+
problem = problem_cls()
|
| 204 |
+
if not problem.stiff:
|
| 205 |
+
self._do_problem(problem, 'vode', 'adams')
|
| 206 |
+
else:
|
| 207 |
+
self._do_problem(problem, 'vode', 'bdf')
|
| 208 |
+
|
| 209 |
+
def test_lsoda(self):
|
| 210 |
+
# Check the lsoda solver
|
| 211 |
+
for problem_cls in PROBLEMS:
|
| 212 |
+
problem = problem_cls()
|
| 213 |
+
self._do_problem(problem, 'lsoda')
|
| 214 |
+
|
| 215 |
+
def test_dopri5(self):
|
| 216 |
+
# Check the dopri5 solver
|
| 217 |
+
for problem_cls in PROBLEMS:
|
| 218 |
+
problem = problem_cls()
|
| 219 |
+
if problem.stiff:
|
| 220 |
+
continue
|
| 221 |
+
if hasattr(problem, 'jac'):
|
| 222 |
+
continue
|
| 223 |
+
self._do_problem(problem, 'dopri5')
|
| 224 |
+
|
| 225 |
+
def test_dop853(self):
|
| 226 |
+
# Check the dop853 solver
|
| 227 |
+
for problem_cls in PROBLEMS:
|
| 228 |
+
problem = problem_cls()
|
| 229 |
+
if problem.stiff:
|
| 230 |
+
continue
|
| 231 |
+
if hasattr(problem, 'jac'):
|
| 232 |
+
continue
|
| 233 |
+
self._do_problem(problem, 'dop853')
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class TestSolout:
|
| 237 |
+
# Check integrate.ode correctly handles solout for dopri5 and dop853
|
| 238 |
+
def _run_solout_test(self, integrator):
|
| 239 |
+
# Check correct usage of solout
|
| 240 |
+
ts = []
|
| 241 |
+
ys = []
|
| 242 |
+
t0 = 0.0
|
| 243 |
+
tend = 10.0
|
| 244 |
+
y0 = [1.0, 2.0]
|
| 245 |
+
|
| 246 |
+
def solout(t, y):
|
| 247 |
+
ts.append(t)
|
| 248 |
+
ys.append(y.copy())
|
| 249 |
+
|
| 250 |
+
def rhs(t, y):
|
| 251 |
+
return [y[0] + y[1], -y[1]**2]
|
| 252 |
+
|
| 253 |
+
ig = ode(rhs).set_integrator(integrator)
|
| 254 |
+
ig.set_solout(solout)
|
| 255 |
+
ig.set_initial_value(y0, t0)
|
| 256 |
+
ret = ig.integrate(tend)
|
| 257 |
+
assert_array_equal(ys[0], y0)
|
| 258 |
+
assert_array_equal(ys[-1], ret)
|
| 259 |
+
assert_equal(ts[0], t0)
|
| 260 |
+
assert_equal(ts[-1], tend)
|
| 261 |
+
|
| 262 |
+
def test_solout(self):
|
| 263 |
+
for integrator in ('dopri5', 'dop853'):
|
| 264 |
+
self._run_solout_test(integrator)
|
| 265 |
+
|
| 266 |
+
def _run_solout_after_initial_test(self, integrator):
|
| 267 |
+
# Check if solout works even if it is set after the initial value.
|
| 268 |
+
ts = []
|
| 269 |
+
ys = []
|
| 270 |
+
t0 = 0.0
|
| 271 |
+
tend = 10.0
|
| 272 |
+
y0 = [1.0, 2.0]
|
| 273 |
+
|
| 274 |
+
def solout(t, y):
|
| 275 |
+
ts.append(t)
|
| 276 |
+
ys.append(y.copy())
|
| 277 |
+
|
| 278 |
+
def rhs(t, y):
|
| 279 |
+
return [y[0] + y[1], -y[1]**2]
|
| 280 |
+
|
| 281 |
+
ig = ode(rhs).set_integrator(integrator)
|
| 282 |
+
ig.set_initial_value(y0, t0)
|
| 283 |
+
ig.set_solout(solout)
|
| 284 |
+
ret = ig.integrate(tend)
|
| 285 |
+
assert_array_equal(ys[0], y0)
|
| 286 |
+
assert_array_equal(ys[-1], ret)
|
| 287 |
+
assert_equal(ts[0], t0)
|
| 288 |
+
assert_equal(ts[-1], tend)
|
| 289 |
+
|
| 290 |
+
def test_solout_after_initial(self):
|
| 291 |
+
for integrator in ('dopri5', 'dop853'):
|
| 292 |
+
self._run_solout_after_initial_test(integrator)
|
| 293 |
+
|
| 294 |
+
def _run_solout_break_test(self, integrator):
|
| 295 |
+
# Check correct usage of stopping via solout
|
| 296 |
+
ts = []
|
| 297 |
+
ys = []
|
| 298 |
+
t0 = 0.0
|
| 299 |
+
tend = 10.0
|
| 300 |
+
y0 = [1.0, 2.0]
|
| 301 |
+
|
| 302 |
+
def solout(t, y):
|
| 303 |
+
ts.append(t)
|
| 304 |
+
ys.append(y.copy())
|
| 305 |
+
if t > tend/2.0:
|
| 306 |
+
return -1
|
| 307 |
+
|
| 308 |
+
def rhs(t, y):
|
| 309 |
+
return [y[0] + y[1], -y[1]**2]
|
| 310 |
+
|
| 311 |
+
ig = ode(rhs).set_integrator(integrator)
|
| 312 |
+
ig.set_solout(solout)
|
| 313 |
+
ig.set_initial_value(y0, t0)
|
| 314 |
+
ret = ig.integrate(tend)
|
| 315 |
+
assert_array_equal(ys[0], y0)
|
| 316 |
+
assert_array_equal(ys[-1], ret)
|
| 317 |
+
assert_equal(ts[0], t0)
|
| 318 |
+
assert_(ts[-1] > tend/2.0)
|
| 319 |
+
assert_(ts[-1] < tend)
|
| 320 |
+
|
| 321 |
+
def test_solout_break(self):
|
| 322 |
+
for integrator in ('dopri5', 'dop853'):
|
| 323 |
+
self._run_solout_break_test(integrator)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
class TestComplexSolout:
|
| 327 |
+
# Check integrate.ode correctly handles solout for dopri5 and dop853
|
| 328 |
+
def _run_solout_test(self, integrator):
|
| 329 |
+
# Check correct usage of solout
|
| 330 |
+
ts = []
|
| 331 |
+
ys = []
|
| 332 |
+
t0 = 0.0
|
| 333 |
+
tend = 20.0
|
| 334 |
+
y0 = [0.0]
|
| 335 |
+
|
| 336 |
+
def solout(t, y):
|
| 337 |
+
ts.append(t)
|
| 338 |
+
ys.append(y.copy())
|
| 339 |
+
|
| 340 |
+
def rhs(t, y):
|
| 341 |
+
return [1.0/(t - 10.0 - 1j)]
|
| 342 |
+
|
| 343 |
+
ig = complex_ode(rhs).set_integrator(integrator)
|
| 344 |
+
ig.set_solout(solout)
|
| 345 |
+
ig.set_initial_value(y0, t0)
|
| 346 |
+
ret = ig.integrate(tend)
|
| 347 |
+
assert_array_equal(ys[0], y0)
|
| 348 |
+
assert_array_equal(ys[-1], ret)
|
| 349 |
+
assert_equal(ts[0], t0)
|
| 350 |
+
assert_equal(ts[-1], tend)
|
| 351 |
+
|
| 352 |
+
def test_solout(self):
|
| 353 |
+
for integrator in ('dopri5', 'dop853'):
|
| 354 |
+
self._run_solout_test(integrator)
|
| 355 |
+
|
| 356 |
+
def _run_solout_break_test(self, integrator):
|
| 357 |
+
# Check correct usage of stopping via solout
|
| 358 |
+
ts = []
|
| 359 |
+
ys = []
|
| 360 |
+
t0 = 0.0
|
| 361 |
+
tend = 20.0
|
| 362 |
+
y0 = [0.0]
|
| 363 |
+
|
| 364 |
+
def solout(t, y):
|
| 365 |
+
ts.append(t)
|
| 366 |
+
ys.append(y.copy())
|
| 367 |
+
if t > tend/2.0:
|
| 368 |
+
return -1
|
| 369 |
+
|
| 370 |
+
def rhs(t, y):
|
| 371 |
+
return [1.0/(t - 10.0 - 1j)]
|
| 372 |
+
|
| 373 |
+
ig = complex_ode(rhs).set_integrator(integrator)
|
| 374 |
+
ig.set_solout(solout)
|
| 375 |
+
ig.set_initial_value(y0, t0)
|
| 376 |
+
ret = ig.integrate(tend)
|
| 377 |
+
assert_array_equal(ys[0], y0)
|
| 378 |
+
assert_array_equal(ys[-1], ret)
|
| 379 |
+
assert_equal(ts[0], t0)
|
| 380 |
+
assert_(ts[-1] > tend/2.0)
|
| 381 |
+
assert_(ts[-1] < tend)
|
| 382 |
+
|
| 383 |
+
def test_solout_break(self):
|
| 384 |
+
for integrator in ('dopri5', 'dop853'):
|
| 385 |
+
self._run_solout_break_test(integrator)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
#------------------------------------------------------------------------------
|
| 389 |
+
# Test problems
|
| 390 |
+
#------------------------------------------------------------------------------
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class ODE:
|
| 394 |
+
"""
|
| 395 |
+
ODE problem
|
| 396 |
+
"""
|
| 397 |
+
stiff = False
|
| 398 |
+
cmplx = False
|
| 399 |
+
stop_t = 1
|
| 400 |
+
z0 = []
|
| 401 |
+
|
| 402 |
+
lband = None
|
| 403 |
+
uband = None
|
| 404 |
+
|
| 405 |
+
atol = 1e-6
|
| 406 |
+
rtol = 1e-5
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
class SimpleOscillator(ODE):
|
| 410 |
+
r"""
|
| 411 |
+
Free vibration of a simple oscillator::
|
| 412 |
+
m \ddot{u} + k u = 0, u(0) = u_0 \dot{u}(0) \dot{u}_0
|
| 413 |
+
Solution::
|
| 414 |
+
u(t) = u_0*cos(sqrt(k/m)*t)+\dot{u}_0*sin(sqrt(k/m)*t)/sqrt(k/m)
|
| 415 |
+
"""
|
| 416 |
+
stop_t = 1 + 0.09
|
| 417 |
+
z0 = array([1.0, 0.1], float)
|
| 418 |
+
|
| 419 |
+
k = 4.0
|
| 420 |
+
m = 1.0
|
| 421 |
+
|
| 422 |
+
def f(self, z, t):
|
| 423 |
+
tmp = zeros((2, 2), float)
|
| 424 |
+
tmp[0, 1] = 1.0
|
| 425 |
+
tmp[1, 0] = -self.k / self.m
|
| 426 |
+
return dot(tmp, z)
|
| 427 |
+
|
| 428 |
+
def verify(self, zs, t):
|
| 429 |
+
omega = sqrt(self.k / self.m)
|
| 430 |
+
u = self.z0[0]*cos(omega*t) + self.z0[1]*sin(omega*t)/omega
|
| 431 |
+
return allclose(u, zs[:, 0], atol=self.atol, rtol=self.rtol)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
class ComplexExp(ODE):
|
| 435 |
+
r"""The equation :lm:`\dot u = i u`"""
|
| 436 |
+
stop_t = 1.23*pi
|
| 437 |
+
z0 = exp([1j, 2j, 3j, 4j, 5j])
|
| 438 |
+
cmplx = True
|
| 439 |
+
|
| 440 |
+
def f(self, z, t):
|
| 441 |
+
return 1j*z
|
| 442 |
+
|
| 443 |
+
def jac(self, z, t):
|
| 444 |
+
return 1j*eye(5)
|
| 445 |
+
|
| 446 |
+
def verify(self, zs, t):
|
| 447 |
+
u = self.z0 * exp(1j*t)
|
| 448 |
+
return allclose(u, zs, atol=self.atol, rtol=self.rtol)
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class Pi(ODE):
|
| 452 |
+
r"""Integrate 1/(t + 1j) from t=-10 to t=10"""
|
| 453 |
+
stop_t = 20
|
| 454 |
+
z0 = [0]
|
| 455 |
+
cmplx = True
|
| 456 |
+
|
| 457 |
+
def f(self, z, t):
|
| 458 |
+
return array([1./(t - 10 + 1j)])
|
| 459 |
+
|
| 460 |
+
def verify(self, zs, t):
|
| 461 |
+
u = -2j * np.arctan(10)
|
| 462 |
+
return allclose(u, zs[-1, :], atol=self.atol, rtol=self.rtol)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
class CoupledDecay(ODE):
|
| 466 |
+
r"""
|
| 467 |
+
3 coupled decays suited for banded treatment
|
| 468 |
+
(banded mode makes it necessary when N>>3)
|
| 469 |
+
"""
|
| 470 |
+
|
| 471 |
+
stiff = True
|
| 472 |
+
stop_t = 0.5
|
| 473 |
+
z0 = [5.0, 7.0, 13.0]
|
| 474 |
+
lband = 1
|
| 475 |
+
uband = 0
|
| 476 |
+
|
| 477 |
+
lmbd = [0.17, 0.23, 0.29] # fictitious decay constants
|
| 478 |
+
|
| 479 |
+
def f(self, z, t):
|
| 480 |
+
lmbd = self.lmbd
|
| 481 |
+
return np.array([-lmbd[0]*z[0],
|
| 482 |
+
-lmbd[1]*z[1] + lmbd[0]*z[0],
|
| 483 |
+
-lmbd[2]*z[2] + lmbd[1]*z[1]])
|
| 484 |
+
|
| 485 |
+
def jac(self, z, t):
|
| 486 |
+
# The full Jacobian is
|
| 487 |
+
#
|
| 488 |
+
# [-lmbd[0] 0 0 ]
|
| 489 |
+
# [ lmbd[0] -lmbd[1] 0 ]
|
| 490 |
+
# [ 0 lmbd[1] -lmbd[2]]
|
| 491 |
+
#
|
| 492 |
+
# The lower and upper bandwidths are lband=1 and uband=0, resp.
|
| 493 |
+
# The representation of this array in packed format is
|
| 494 |
+
#
|
| 495 |
+
# [-lmbd[0] -lmbd[1] -lmbd[2]]
|
| 496 |
+
# [ lmbd[0] lmbd[1] 0 ]
|
| 497 |
+
|
| 498 |
+
lmbd = self.lmbd
|
| 499 |
+
j = np.zeros((self.lband + self.uband + 1, 3), order='F')
|
| 500 |
+
|
| 501 |
+
def set_j(ri, ci, val):
|
| 502 |
+
j[self.uband + ri - ci, ci] = val
|
| 503 |
+
set_j(0, 0, -lmbd[0])
|
| 504 |
+
set_j(1, 0, lmbd[0])
|
| 505 |
+
set_j(1, 1, -lmbd[1])
|
| 506 |
+
set_j(2, 1, lmbd[1])
|
| 507 |
+
set_j(2, 2, -lmbd[2])
|
| 508 |
+
return j
|
| 509 |
+
|
| 510 |
+
def verify(self, zs, t):
|
| 511 |
+
# Formulae derived by hand
|
| 512 |
+
lmbd = np.array(self.lmbd)
|
| 513 |
+
d10 = lmbd[1] - lmbd[0]
|
| 514 |
+
d21 = lmbd[2] - lmbd[1]
|
| 515 |
+
d20 = lmbd[2] - lmbd[0]
|
| 516 |
+
e0 = np.exp(-lmbd[0] * t)
|
| 517 |
+
e1 = np.exp(-lmbd[1] * t)
|
| 518 |
+
e2 = np.exp(-lmbd[2] * t)
|
| 519 |
+
u = np.vstack((
|
| 520 |
+
self.z0[0] * e0,
|
| 521 |
+
self.z0[1] * e1 + self.z0[0] * lmbd[0] / d10 * (e0 - e1),
|
| 522 |
+
self.z0[2] * e2 + self.z0[1] * lmbd[1] / d21 * (e1 - e2) +
|
| 523 |
+
lmbd[1] * lmbd[0] * self.z0[0] / d10 *
|
| 524 |
+
(1 / d20 * (e0 - e2) - 1 / d21 * (e1 - e2)))).transpose()
|
| 525 |
+
return allclose(u, zs, atol=self.atol, rtol=self.rtol)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
PROBLEMS = [SimpleOscillator, ComplexExp, Pi, CoupledDecay]
|
| 529 |
+
|
| 530 |
+
#------------------------------------------------------------------------------
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def f(t, x):
|
| 534 |
+
dxdt = [x[1], -x[0]]
|
| 535 |
+
return dxdt
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def jac(t, x):
|
| 539 |
+
j = array([[0.0, 1.0],
|
| 540 |
+
[-1.0, 0.0]])
|
| 541 |
+
return j
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def f1(t, x, omega):
|
| 545 |
+
dxdt = [omega*x[1], -omega*x[0]]
|
| 546 |
+
return dxdt
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def jac1(t, x, omega):
|
| 550 |
+
j = array([[0.0, omega],
|
| 551 |
+
[-omega, 0.0]])
|
| 552 |
+
return j
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def f2(t, x, omega1, omega2):
|
| 556 |
+
dxdt = [omega1*x[1], -omega2*x[0]]
|
| 557 |
+
return dxdt
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def jac2(t, x, omega1, omega2):
|
| 561 |
+
j = array([[0.0, omega1],
|
| 562 |
+
[-omega2, 0.0]])
|
| 563 |
+
return j
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def fv(t, x, omega):
|
| 567 |
+
dxdt = [omega[0]*x[1], -omega[1]*x[0]]
|
| 568 |
+
return dxdt
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def jacv(t, x, omega):
|
| 572 |
+
j = array([[0.0, omega[0]],
|
| 573 |
+
[-omega[1], 0.0]])
|
| 574 |
+
return j
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class ODECheckParameterUse:
|
| 578 |
+
"""Call an ode-class solver with several cases of parameter use."""
|
| 579 |
+
|
| 580 |
+
# solver_name must be set before tests can be run with this class.
|
| 581 |
+
|
| 582 |
+
# Set these in subclasses.
|
| 583 |
+
solver_name = ''
|
| 584 |
+
solver_uses_jac = False
|
| 585 |
+
|
| 586 |
+
def _get_solver(self, f, jac):
|
| 587 |
+
solver = ode(f, jac)
|
| 588 |
+
if self.solver_uses_jac:
|
| 589 |
+
solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7,
|
| 590 |
+
with_jacobian=self.solver_uses_jac)
|
| 591 |
+
else:
|
| 592 |
+
# XXX Shouldn't set_integrator *always* accept the keyword arg
|
| 593 |
+
# 'with_jacobian', and perhaps raise an exception if it is set
|
| 594 |
+
# to True if the solver can't actually use it?
|
| 595 |
+
solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7)
|
| 596 |
+
return solver
|
| 597 |
+
|
| 598 |
+
def _check_solver(self, solver):
|
| 599 |
+
ic = [1.0, 0.0]
|
| 600 |
+
solver.set_initial_value(ic, 0.0)
|
| 601 |
+
solver.integrate(pi)
|
| 602 |
+
assert_array_almost_equal(solver.y, [-1.0, 0.0])
|
| 603 |
+
|
| 604 |
+
def test_no_params(self):
|
| 605 |
+
solver = self._get_solver(f, jac)
|
| 606 |
+
self._check_solver(solver)
|
| 607 |
+
|
| 608 |
+
def test_one_scalar_param(self):
|
| 609 |
+
solver = self._get_solver(f1, jac1)
|
| 610 |
+
omega = 1.0
|
| 611 |
+
solver.set_f_params(omega)
|
| 612 |
+
if self.solver_uses_jac:
|
| 613 |
+
solver.set_jac_params(omega)
|
| 614 |
+
self._check_solver(solver)
|
| 615 |
+
|
| 616 |
+
def test_two_scalar_params(self):
|
| 617 |
+
solver = self._get_solver(f2, jac2)
|
| 618 |
+
omega1 = 1.0
|
| 619 |
+
omega2 = 1.0
|
| 620 |
+
solver.set_f_params(omega1, omega2)
|
| 621 |
+
if self.solver_uses_jac:
|
| 622 |
+
solver.set_jac_params(omega1, omega2)
|
| 623 |
+
self._check_solver(solver)
|
| 624 |
+
|
| 625 |
+
def test_vector_param(self):
|
| 626 |
+
solver = self._get_solver(fv, jacv)
|
| 627 |
+
omega = [1.0, 1.0]
|
| 628 |
+
solver.set_f_params(omega)
|
| 629 |
+
if self.solver_uses_jac:
|
| 630 |
+
solver.set_jac_params(omega)
|
| 631 |
+
self._check_solver(solver)
|
| 632 |
+
|
| 633 |
+
def test_warns_on_failure(self):
|
| 634 |
+
# Set nsteps small to ensure failure
|
| 635 |
+
solver = self._get_solver(f, jac)
|
| 636 |
+
solver.set_integrator(self.solver_name, nsteps=1)
|
| 637 |
+
ic = [1.0, 0.0]
|
| 638 |
+
solver.set_initial_value(ic, 0.0)
|
| 639 |
+
assert_warns(UserWarning, solver.integrate, pi)
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
class TestDOPRI5CheckParameterUse(ODECheckParameterUse):
|
| 643 |
+
solver_name = 'dopri5'
|
| 644 |
+
solver_uses_jac = False
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
class TestDOP853CheckParameterUse(ODECheckParameterUse):
|
| 648 |
+
solver_name = 'dop853'
|
| 649 |
+
solver_uses_jac = False
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
class TestVODECheckParameterUse(ODECheckParameterUse):
|
| 653 |
+
solver_name = 'vode'
|
| 654 |
+
solver_uses_jac = True
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
class TestZVODECheckParameterUse(ODECheckParameterUse):
|
| 658 |
+
solver_name = 'zvode'
|
| 659 |
+
solver_uses_jac = True
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
class TestLSODACheckParameterUse(ODECheckParameterUse):
|
| 663 |
+
solver_name = 'lsoda'
|
| 664 |
+
solver_uses_jac = True
|
| 665 |
+
|
| 666 |
+
|
| 667 |
+
def test_odeint_trivial_time():
|
| 668 |
+
# Test that odeint succeeds when given a single time point
|
| 669 |
+
# and full_output=True. This is a regression test for gh-4282.
|
| 670 |
+
y0 = 1
|
| 671 |
+
t = [0]
|
| 672 |
+
y, info = odeint(lambda y, t: -y, y0, t, full_output=True)
|
| 673 |
+
assert_array_equal(y, np.array([[y0]]))
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
def test_odeint_banded_jacobian():
|
| 677 |
+
# Test the use of the `Dfun`, `ml` and `mu` options of odeint.
|
| 678 |
+
|
| 679 |
+
def func(y, t, c):
|
| 680 |
+
return c.dot(y)
|
| 681 |
+
|
| 682 |
+
def jac(y, t, c):
|
| 683 |
+
return c
|
| 684 |
+
|
| 685 |
+
def jac_transpose(y, t, c):
|
| 686 |
+
return c.T.copy(order='C')
|
| 687 |
+
|
| 688 |
+
def bjac_rows(y, t, c):
|
| 689 |
+
jac = np.vstack((np.r_[0, np.diag(c, 1)],
|
| 690 |
+
np.diag(c),
|
| 691 |
+
np.r_[np.diag(c, -1), 0],
|
| 692 |
+
np.r_[np.diag(c, -2), 0, 0]))
|
| 693 |
+
return jac
|
| 694 |
+
|
| 695 |
+
def bjac_cols(y, t, c):
|
| 696 |
+
return bjac_rows(y, t, c).T.copy(order='C')
|
| 697 |
+
|
| 698 |
+
c = array([[-205, 0.01, 0.00, 0.0],
|
| 699 |
+
[0.1, -2.50, 0.02, 0.0],
|
| 700 |
+
[1e-3, 0.01, -2.0, 0.01],
|
| 701 |
+
[0.00, 0.00, 0.1, -1.0]])
|
| 702 |
+
|
| 703 |
+
y0 = np.ones(4)
|
| 704 |
+
t = np.array([0, 5, 10, 100])
|
| 705 |
+
|
| 706 |
+
# Use the full Jacobian.
|
| 707 |
+
sol1, info1 = odeint(func, y0, t, args=(c,), full_output=True,
|
| 708 |
+
atol=1e-13, rtol=1e-11, mxstep=10000,
|
| 709 |
+
Dfun=jac)
|
| 710 |
+
|
| 711 |
+
# Use the transposed full Jacobian, with col_deriv=True.
|
| 712 |
+
sol2, info2 = odeint(func, y0, t, args=(c,), full_output=True,
|
| 713 |
+
atol=1e-13, rtol=1e-11, mxstep=10000,
|
| 714 |
+
Dfun=jac_transpose, col_deriv=True)
|
| 715 |
+
|
| 716 |
+
# Use the banded Jacobian.
|
| 717 |
+
sol3, info3 = odeint(func, y0, t, args=(c,), full_output=True,
|
| 718 |
+
atol=1e-13, rtol=1e-11, mxstep=10000,
|
| 719 |
+
Dfun=bjac_rows, ml=2, mu=1)
|
| 720 |
+
|
| 721 |
+
# Use the transposed banded Jacobian, with col_deriv=True.
|
| 722 |
+
sol4, info4 = odeint(func, y0, t, args=(c,), full_output=True,
|
| 723 |
+
atol=1e-13, rtol=1e-11, mxstep=10000,
|
| 724 |
+
Dfun=bjac_cols, ml=2, mu=1, col_deriv=True)
|
| 725 |
+
|
| 726 |
+
assert_allclose(sol1, sol2, err_msg="sol1 != sol2")
|
| 727 |
+
assert_allclose(sol1, sol3, atol=1e-12, err_msg="sol1 != sol3")
|
| 728 |
+
assert_allclose(sol3, sol4, err_msg="sol3 != sol4")
|
| 729 |
+
|
| 730 |
+
# Verify that the number of jacobian evaluations was the same for the
|
| 731 |
+
# calls of odeint with a full jacobian and with a banded jacobian. This is
|
| 732 |
+
# a regression test--there was a bug in the handling of banded jacobians
|
| 733 |
+
# that resulted in an incorrect jacobian matrix being passed to the LSODA
|
| 734 |
+
# code. That would cause errors or excessive jacobian evaluations.
|
| 735 |
+
assert_array_equal(info1['nje'], info2['nje'])
|
| 736 |
+
assert_array_equal(info3['nje'], info4['nje'])
|
| 737 |
+
|
| 738 |
+
# Test the use of tfirst
|
| 739 |
+
sol1ty, info1ty = odeint(lambda t, y, c: func(y, t, c), y0, t, args=(c,),
|
| 740 |
+
full_output=True, atol=1e-13, rtol=1e-11,
|
| 741 |
+
mxstep=10000,
|
| 742 |
+
Dfun=lambda t, y, c: jac(y, t, c), tfirst=True)
|
| 743 |
+
# The code should execute the exact same sequence of floating point
|
| 744 |
+
# calculations, so these should be exactly equal. We'll be safe and use
|
| 745 |
+
# a small tolerance.
|
| 746 |
+
assert_allclose(sol1, sol1ty, rtol=1e-12, err_msg="sol1 != sol1ty")
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def test_odeint_errors():
|
| 750 |
+
def sys1d(x, t):
|
| 751 |
+
return -100*x
|
| 752 |
+
|
| 753 |
+
def bad1(x, t):
|
| 754 |
+
return 1.0/0
|
| 755 |
+
|
| 756 |
+
def bad2(x, t):
|
| 757 |
+
return "foo"
|
| 758 |
+
|
| 759 |
+
def bad_jac1(x, t):
|
| 760 |
+
return 1.0/0
|
| 761 |
+
|
| 762 |
+
def bad_jac2(x, t):
|
| 763 |
+
return [["foo"]]
|
| 764 |
+
|
| 765 |
+
def sys2d(x, t):
|
| 766 |
+
return [-100*x[0], -0.1*x[1]]
|
| 767 |
+
|
| 768 |
+
def sys2d_bad_jac(x, t):
|
| 769 |
+
return [[1.0/0, 0], [0, -0.1]]
|
| 770 |
+
|
| 771 |
+
assert_raises(ZeroDivisionError, odeint, bad1, 1.0, [0, 1])
|
| 772 |
+
assert_raises(ValueError, odeint, bad2, 1.0, [0, 1])
|
| 773 |
+
|
| 774 |
+
assert_raises(ZeroDivisionError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac1)
|
| 775 |
+
assert_raises(ValueError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac2)
|
| 776 |
+
|
| 777 |
+
assert_raises(ZeroDivisionError, odeint, sys2d, [1.0, 1.0], [0, 1],
|
| 778 |
+
Dfun=sys2d_bad_jac)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
def test_odeint_bad_shapes():
|
| 782 |
+
# Tests of some errors that can occur with odeint.
|
| 783 |
+
|
| 784 |
+
def badrhs(x, t):
|
| 785 |
+
return [1, -1]
|
| 786 |
+
|
| 787 |
+
def sys1(x, t):
|
| 788 |
+
return -100*x
|
| 789 |
+
|
| 790 |
+
def badjac(x, t):
|
| 791 |
+
return [[0, 0, 0]]
|
| 792 |
+
|
| 793 |
+
# y0 must be at most 1-d.
|
| 794 |
+
bad_y0 = [[0, 0], [0, 0]]
|
| 795 |
+
assert_raises(ValueError, odeint, sys1, bad_y0, [0, 1])
|
| 796 |
+
|
| 797 |
+
# t must be at most 1-d.
|
| 798 |
+
bad_t = [[0, 1], [2, 3]]
|
| 799 |
+
assert_raises(ValueError, odeint, sys1, [10.0], bad_t)
|
| 800 |
+
|
| 801 |
+
# y0 is 10, but badrhs(x, t) returns [1, -1].
|
| 802 |
+
assert_raises(RuntimeError, odeint, badrhs, 10, [0, 1])
|
| 803 |
+
|
| 804 |
+
# shape of array returned by badjac(x, t) is not correct.
|
| 805 |
+
assert_raises(RuntimeError, odeint, sys1, [10, 10], [0, 1], Dfun=badjac)
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def test_repeated_t_values():
|
| 809 |
+
"""Regression test for gh-8217."""
|
| 810 |
+
|
| 811 |
+
def func(x, t):
|
| 812 |
+
return -0.25*x
|
| 813 |
+
|
| 814 |
+
t = np.zeros(10)
|
| 815 |
+
sol = odeint(func, [1.], t)
|
| 816 |
+
assert_array_equal(sol, np.ones((len(t), 1)))
|
| 817 |
+
|
| 818 |
+
tau = 4*np.log(2)
|
| 819 |
+
t = [0]*9 + [tau, 2*tau, 2*tau, 3*tau]
|
| 820 |
+
sol = odeint(func, [1, 2], t, rtol=1e-12, atol=1e-12)
|
| 821 |
+
expected_sol = np.array([[1.0, 2.0]]*9 +
|
| 822 |
+
[[0.5, 1.0],
|
| 823 |
+
[0.25, 0.5],
|
| 824 |
+
[0.25, 0.5],
|
| 825 |
+
[0.125, 0.25]])
|
| 826 |
+
assert_allclose(sol, expected_sol)
|
| 827 |
+
|
| 828 |
+
# Edge case: empty t sequence.
|
| 829 |
+
sol = odeint(func, [1.], [])
|
| 830 |
+
assert_array_equal(sol, np.array([], dtype=np.float64).reshape((0, 1)))
|
| 831 |
+
|
| 832 |
+
# t values are not monotonic.
|
| 833 |
+
assert_raises(ValueError, odeint, func, [1.], [0, 1, 0.5, 0])
|
| 834 |
+
assert_raises(ValueError, odeint, func, [1, 2, 3], [0, -1, -2, 3])
|
parrot/lib/python3.10/site-packages/scipy/integrate/tests/test_quadpack.py
ADDED
|
@@ -0,0 +1,680 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import math
|
| 3 |
+
import numpy as np
|
| 4 |
+
from numpy import sqrt, cos, sin, arctan, exp, log, pi
|
| 5 |
+
from numpy.testing import (assert_,
|
| 6 |
+
assert_allclose, assert_array_less, assert_almost_equal)
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from scipy.integrate import quad, dblquad, tplquad, nquad
|
| 10 |
+
from scipy.special import erf, erfc
|
| 11 |
+
from scipy._lib._ccallback import LowLevelCallable
|
| 12 |
+
|
| 13 |
+
import ctypes
|
| 14 |
+
import ctypes.util
|
| 15 |
+
from scipy._lib._ccallback_c import sine_ctypes
|
| 16 |
+
|
| 17 |
+
import scipy.integrate._test_multivariate as clib_test
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def assert_quad(value_and_err, tabled_value, error_tolerance=1.5e-8):
|
| 21 |
+
value, err = value_and_err
|
| 22 |
+
assert_allclose(value, tabled_value, atol=err, rtol=0)
|
| 23 |
+
if error_tolerance is not None:
|
| 24 |
+
assert_array_less(err, error_tolerance)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_clib_test_routine(name, restype, *argtypes):
|
| 28 |
+
ptr = getattr(clib_test, name)
|
| 29 |
+
return ctypes.cast(ptr, ctypes.CFUNCTYPE(restype, *argtypes))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TestCtypesQuad:
|
| 33 |
+
def setup_method(self):
|
| 34 |
+
if sys.platform == 'win32':
|
| 35 |
+
files = ['api-ms-win-crt-math-l1-1-0.dll']
|
| 36 |
+
elif sys.platform == 'darwin':
|
| 37 |
+
files = ['libm.dylib']
|
| 38 |
+
else:
|
| 39 |
+
files = ['libm.so', 'libm.so.6']
|
| 40 |
+
|
| 41 |
+
for file in files:
|
| 42 |
+
try:
|
| 43 |
+
self.lib = ctypes.CDLL(file)
|
| 44 |
+
break
|
| 45 |
+
except OSError:
|
| 46 |
+
pass
|
| 47 |
+
else:
|
| 48 |
+
# This test doesn't work on some Linux platforms (Fedora for
|
| 49 |
+
# example) that put an ld script in libm.so - see gh-5370
|
| 50 |
+
pytest.skip("Ctypes can't import libm.so")
|
| 51 |
+
|
| 52 |
+
restype = ctypes.c_double
|
| 53 |
+
argtypes = (ctypes.c_double,)
|
| 54 |
+
for name in ['sin', 'cos', 'tan']:
|
| 55 |
+
func = getattr(self.lib, name)
|
| 56 |
+
func.restype = restype
|
| 57 |
+
func.argtypes = argtypes
|
| 58 |
+
|
| 59 |
+
def test_typical(self):
|
| 60 |
+
assert_quad(quad(self.lib.sin, 0, 5), quad(math.sin, 0, 5)[0])
|
| 61 |
+
assert_quad(quad(self.lib.cos, 0, 5), quad(math.cos, 0, 5)[0])
|
| 62 |
+
assert_quad(quad(self.lib.tan, 0, 1), quad(math.tan, 0, 1)[0])
|
| 63 |
+
|
| 64 |
+
def test_ctypes_sine(self):
|
| 65 |
+
quad(LowLevelCallable(sine_ctypes), 0, 1)
|
| 66 |
+
|
| 67 |
+
def test_ctypes_variants(self):
|
| 68 |
+
sin_0 = get_clib_test_routine('_sin_0', ctypes.c_double,
|
| 69 |
+
ctypes.c_double, ctypes.c_void_p)
|
| 70 |
+
|
| 71 |
+
sin_1 = get_clib_test_routine('_sin_1', ctypes.c_double,
|
| 72 |
+
ctypes.c_int, ctypes.POINTER(ctypes.c_double),
|
| 73 |
+
ctypes.c_void_p)
|
| 74 |
+
|
| 75 |
+
sin_2 = get_clib_test_routine('_sin_2', ctypes.c_double,
|
| 76 |
+
ctypes.c_double)
|
| 77 |
+
|
| 78 |
+
sin_3 = get_clib_test_routine('_sin_3', ctypes.c_double,
|
| 79 |
+
ctypes.c_int, ctypes.POINTER(ctypes.c_double))
|
| 80 |
+
|
| 81 |
+
sin_4 = get_clib_test_routine('_sin_3', ctypes.c_double,
|
| 82 |
+
ctypes.c_int, ctypes.c_double)
|
| 83 |
+
|
| 84 |
+
all_sigs = [sin_0, sin_1, sin_2, sin_3, sin_4]
|
| 85 |
+
legacy_sigs = [sin_2, sin_4]
|
| 86 |
+
legacy_only_sigs = [sin_4]
|
| 87 |
+
|
| 88 |
+
# LowLevelCallables work for new signatures
|
| 89 |
+
for j, func in enumerate(all_sigs):
|
| 90 |
+
callback = LowLevelCallable(func)
|
| 91 |
+
if func in legacy_only_sigs:
|
| 92 |
+
pytest.raises(ValueError, quad, callback, 0, pi)
|
| 93 |
+
else:
|
| 94 |
+
assert_allclose(quad(callback, 0, pi)[0], 2.0)
|
| 95 |
+
|
| 96 |
+
# Plain ctypes items work only for legacy signatures
|
| 97 |
+
for j, func in enumerate(legacy_sigs):
|
| 98 |
+
if func in legacy_sigs:
|
| 99 |
+
assert_allclose(quad(func, 0, pi)[0], 2.0)
|
| 100 |
+
else:
|
| 101 |
+
pytest.raises(ValueError, quad, func, 0, pi)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class TestMultivariateCtypesQuad:
|
| 105 |
+
def setup_method(self):
|
| 106 |
+
restype = ctypes.c_double
|
| 107 |
+
argtypes = (ctypes.c_int, ctypes.c_double)
|
| 108 |
+
for name in ['_multivariate_typical', '_multivariate_indefinite',
|
| 109 |
+
'_multivariate_sin']:
|
| 110 |
+
func = get_clib_test_routine(name, restype, *argtypes)
|
| 111 |
+
setattr(self, name, func)
|
| 112 |
+
|
| 113 |
+
def test_typical(self):
|
| 114 |
+
# 1) Typical function with two extra arguments:
|
| 115 |
+
assert_quad(quad(self._multivariate_typical, 0, pi, (2, 1.8)),
|
| 116 |
+
0.30614353532540296487)
|
| 117 |
+
|
| 118 |
+
def test_indefinite(self):
|
| 119 |
+
# 2) Infinite integration limits --- Euler's constant
|
| 120 |
+
assert_quad(quad(self._multivariate_indefinite, 0, np.inf),
|
| 121 |
+
0.577215664901532860606512)
|
| 122 |
+
|
| 123 |
+
def test_threadsafety(self):
|
| 124 |
+
# Ensure multivariate ctypes are threadsafe
|
| 125 |
+
def threadsafety(y):
|
| 126 |
+
return y + quad(self._multivariate_sin, 0, 1)[0]
|
| 127 |
+
assert_quad(quad(threadsafety, 0, 1), 0.9596976941318602)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class TestQuad:
|
| 131 |
+
def test_typical(self):
|
| 132 |
+
# 1) Typical function with two extra arguments:
|
| 133 |
+
def myfunc(x, n, z): # Bessel function integrand
|
| 134 |
+
return cos(n*x-z*sin(x))/pi
|
| 135 |
+
assert_quad(quad(myfunc, 0, pi, (2, 1.8)), 0.30614353532540296487)
|
| 136 |
+
|
| 137 |
+
def test_indefinite(self):
|
| 138 |
+
# 2) Infinite integration limits --- Euler's constant
|
| 139 |
+
def myfunc(x): # Euler's constant integrand
|
| 140 |
+
return -exp(-x)*log(x)
|
| 141 |
+
assert_quad(quad(myfunc, 0, np.inf), 0.577215664901532860606512)
|
| 142 |
+
|
| 143 |
+
def test_singular(self):
|
| 144 |
+
# 3) Singular points in region of integration.
|
| 145 |
+
def myfunc(x):
|
| 146 |
+
if 0 < x < 2.5:
|
| 147 |
+
return sin(x)
|
| 148 |
+
elif 2.5 <= x <= 5.0:
|
| 149 |
+
return exp(-x)
|
| 150 |
+
else:
|
| 151 |
+
return 0.0
|
| 152 |
+
|
| 153 |
+
assert_quad(quad(myfunc, 0, 10, points=[2.5, 5.0]),
|
| 154 |
+
1 - cos(2.5) + exp(-2.5) - exp(-5.0))
|
| 155 |
+
|
| 156 |
+
def test_sine_weighted_finite(self):
|
| 157 |
+
# 4) Sine weighted integral (finite limits)
|
| 158 |
+
def myfunc(x, a):
|
| 159 |
+
return exp(a*(x-1))
|
| 160 |
+
|
| 161 |
+
ome = 2.0**3.4
|
| 162 |
+
assert_quad(quad(myfunc, 0, 1, args=20, weight='sin', wvar=ome),
|
| 163 |
+
(20*sin(ome)-ome*cos(ome)+ome*exp(-20))/(20**2 + ome**2))
|
| 164 |
+
|
| 165 |
+
def test_sine_weighted_infinite(self):
|
| 166 |
+
# 5) Sine weighted integral (infinite limits)
|
| 167 |
+
def myfunc(x, a):
|
| 168 |
+
return exp(-x*a)
|
| 169 |
+
|
| 170 |
+
a = 4.0
|
| 171 |
+
ome = 3.0
|
| 172 |
+
assert_quad(quad(myfunc, 0, np.inf, args=a, weight='sin', wvar=ome),
|
| 173 |
+
ome/(a**2 + ome**2))
|
| 174 |
+
|
| 175 |
+
def test_cosine_weighted_infinite(self):
|
| 176 |
+
# 6) Cosine weighted integral (negative infinite limits)
|
| 177 |
+
def myfunc(x, a):
|
| 178 |
+
return exp(x*a)
|
| 179 |
+
|
| 180 |
+
a = 2.5
|
| 181 |
+
ome = 2.3
|
| 182 |
+
assert_quad(quad(myfunc, -np.inf, 0, args=a, weight='cos', wvar=ome),
|
| 183 |
+
a/(a**2 + ome**2))
|
| 184 |
+
|
| 185 |
+
def test_algebraic_log_weight(self):
|
| 186 |
+
# 6) Algebraic-logarithmic weight.
|
| 187 |
+
def myfunc(x, a):
|
| 188 |
+
return 1/(1+x+2**(-a))
|
| 189 |
+
|
| 190 |
+
a = 1.5
|
| 191 |
+
assert_quad(quad(myfunc, -1, 1, args=a, weight='alg',
|
| 192 |
+
wvar=(-0.5, -0.5)),
|
| 193 |
+
pi/sqrt((1+2**(-a))**2 - 1))
|
| 194 |
+
|
| 195 |
+
def test_cauchypv_weight(self):
|
| 196 |
+
# 7) Cauchy prinicpal value weighting w(x) = 1/(x-c)
|
| 197 |
+
def myfunc(x, a):
|
| 198 |
+
return 2.0**(-a)/((x-1)**2+4.0**(-a))
|
| 199 |
+
|
| 200 |
+
a = 0.4
|
| 201 |
+
tabledValue = ((2.0**(-0.4)*log(1.5) -
|
| 202 |
+
2.0**(-1.4)*log((4.0**(-a)+16) / (4.0**(-a)+1)) -
|
| 203 |
+
arctan(2.0**(a+2)) -
|
| 204 |
+
arctan(2.0**a)) /
|
| 205 |
+
(4.0**(-a) + 1))
|
| 206 |
+
assert_quad(quad(myfunc, 0, 5, args=0.4, weight='cauchy', wvar=2.0),
|
| 207 |
+
tabledValue, error_tolerance=1.9e-8)
|
| 208 |
+
|
| 209 |
+
def test_b_less_than_a(self):
|
| 210 |
+
def f(x, p, q):
|
| 211 |
+
return p * np.exp(-q*x)
|
| 212 |
+
|
| 213 |
+
val_1, err_1 = quad(f, 0, np.inf, args=(2, 3))
|
| 214 |
+
val_2, err_2 = quad(f, np.inf, 0, args=(2, 3))
|
| 215 |
+
assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
|
| 216 |
+
|
| 217 |
+
def test_b_less_than_a_2(self):
|
| 218 |
+
def f(x, s):
|
| 219 |
+
return np.exp(-x**2 / 2 / s) / np.sqrt(2.*s)
|
| 220 |
+
|
| 221 |
+
val_1, err_1 = quad(f, -np.inf, np.inf, args=(2,))
|
| 222 |
+
val_2, err_2 = quad(f, np.inf, -np.inf, args=(2,))
|
| 223 |
+
assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
|
| 224 |
+
|
| 225 |
+
def test_b_less_than_a_3(self):
|
| 226 |
+
def f(x):
|
| 227 |
+
return 1.0
|
| 228 |
+
|
| 229 |
+
val_1, err_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0))
|
| 230 |
+
val_2, err_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0))
|
| 231 |
+
assert_allclose(val_1, -val_2, atol=max(err_1, err_2))
|
| 232 |
+
|
| 233 |
+
def test_b_less_than_a_full_output(self):
|
| 234 |
+
def f(x):
|
| 235 |
+
return 1.0
|
| 236 |
+
|
| 237 |
+
res_1 = quad(f, 0, 1, weight='alg', wvar=(0, 0), full_output=True)
|
| 238 |
+
res_2 = quad(f, 1, 0, weight='alg', wvar=(0, 0), full_output=True)
|
| 239 |
+
err = max(res_1[1], res_2[1])
|
| 240 |
+
assert_allclose(res_1[0], -res_2[0], atol=err)
|
| 241 |
+
|
| 242 |
+
def test_double_integral(self):
|
| 243 |
+
# 8) Double Integral test
|
| 244 |
+
def simpfunc(y, x): # Note order of arguments.
|
| 245 |
+
return x+y
|
| 246 |
+
|
| 247 |
+
a, b = 1.0, 2.0
|
| 248 |
+
assert_quad(dblquad(simpfunc, a, b, lambda x: x, lambda x: 2*x),
|
| 249 |
+
5/6.0 * (b**3.0-a**3.0))
|
| 250 |
+
|
| 251 |
+
def test_double_integral2(self):
|
| 252 |
+
def func(x0, x1, t0, t1):
|
| 253 |
+
return x0 + x1 + t0 + t1
|
| 254 |
+
def g(x):
|
| 255 |
+
return x
|
| 256 |
+
def h(x):
|
| 257 |
+
return 2 * x
|
| 258 |
+
args = 1, 2
|
| 259 |
+
assert_quad(dblquad(func, 1, 2, g, h, args=args),35./6 + 9*.5)
|
| 260 |
+
|
| 261 |
+
def test_double_integral3(self):
|
| 262 |
+
def func(x0, x1):
|
| 263 |
+
return x0 + x1 + 1 + 2
|
| 264 |
+
assert_quad(dblquad(func, 1, 2, 1, 2),6.)
|
| 265 |
+
|
| 266 |
+
@pytest.mark.parametrize(
|
| 267 |
+
"x_lower, x_upper, y_lower, y_upper, expected",
|
| 268 |
+
[
|
| 269 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 270 |
+
# over domain D = [-inf, 0] for all n.
|
| 271 |
+
(-np.inf, 0, -np.inf, 0, np.pi / 4),
|
| 272 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 273 |
+
# over domain D = [-inf, -1] for each n (one at a time).
|
| 274 |
+
(-np.inf, -1, -np.inf, 0, np.pi / 4 * erfc(1)),
|
| 275 |
+
(-np.inf, 0, -np.inf, -1, np.pi / 4 * erfc(1)),
|
| 276 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 277 |
+
# over domain D = [-inf, -1] for all n.
|
| 278 |
+
(-np.inf, -1, -np.inf, -1, np.pi / 4 * (erfc(1) ** 2)),
|
| 279 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 280 |
+
# over domain D = [-inf, 1] for each n (one at a time).
|
| 281 |
+
(-np.inf, 1, -np.inf, 0, np.pi / 4 * (erf(1) + 1)),
|
| 282 |
+
(-np.inf, 0, -np.inf, 1, np.pi / 4 * (erf(1) + 1)),
|
| 283 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 284 |
+
# over domain D = [-inf, 1] for all n.
|
| 285 |
+
(-np.inf, 1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) ** 2)),
|
| 286 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 287 |
+
# over domain Dx = [-inf, -1] and Dy = [-inf, 1].
|
| 288 |
+
(-np.inf, -1, -np.inf, 1, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
|
| 289 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 290 |
+
# over domain Dx = [-inf, 1] and Dy = [-inf, -1].
|
| 291 |
+
(-np.inf, 1, -np.inf, -1, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
|
| 292 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 293 |
+
# over domain D = [0, inf] for all n.
|
| 294 |
+
(0, np.inf, 0, np.inf, np.pi / 4),
|
| 295 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 296 |
+
# over domain D = [1, inf] for each n (one at a time).
|
| 297 |
+
(1, np.inf, 0, np.inf, np.pi / 4 * erfc(1)),
|
| 298 |
+
(0, np.inf, 1, np.inf, np.pi / 4 * erfc(1)),
|
| 299 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 300 |
+
# over domain D = [1, inf] for all n.
|
| 301 |
+
(1, np.inf, 1, np.inf, np.pi / 4 * (erfc(1) ** 2)),
|
| 302 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 303 |
+
# over domain D = [-1, inf] for each n (one at a time).
|
| 304 |
+
(-1, np.inf, 0, np.inf, np.pi / 4 * (erf(1) + 1)),
|
| 305 |
+
(0, np.inf, -1, np.inf, np.pi / 4 * (erf(1) + 1)),
|
| 306 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 307 |
+
# over domain D = [-1, inf] for all n.
|
| 308 |
+
(-1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) ** 2)),
|
| 309 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 310 |
+
# over domain Dx = [-1, inf] and Dy = [1, inf].
|
| 311 |
+
(-1, np.inf, 1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
|
| 312 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 313 |
+
# over domain Dx = [1, inf] and Dy = [-1, inf].
|
| 314 |
+
(1, np.inf, -1, np.inf, np.pi / 4 * ((erf(1) + 1) * erfc(1))),
|
| 315 |
+
# Multiple integration of a function in n = 2 variables: f(x, y, z)
|
| 316 |
+
# over domain D = [-inf, inf] for all n.
|
| 317 |
+
(-np.inf, np.inf, -np.inf, np.inf, np.pi)
|
| 318 |
+
]
|
| 319 |
+
)
|
| 320 |
+
def test_double_integral_improper(
|
| 321 |
+
self, x_lower, x_upper, y_lower, y_upper, expected
|
| 322 |
+
):
|
| 323 |
+
# The Gaussian Integral.
|
| 324 |
+
def f(x, y):
|
| 325 |
+
return np.exp(-x ** 2 - y ** 2)
|
| 326 |
+
|
| 327 |
+
assert_quad(
|
| 328 |
+
dblquad(f, x_lower, x_upper, y_lower, y_upper),
|
| 329 |
+
expected,
|
| 330 |
+
error_tolerance=3e-8
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
def test_triple_integral(self):
|
| 334 |
+
# 9) Triple Integral test
|
| 335 |
+
def simpfunc(z, y, x, t): # Note order of arguments.
|
| 336 |
+
return (x+y+z)*t
|
| 337 |
+
|
| 338 |
+
a, b = 1.0, 2.0
|
| 339 |
+
assert_quad(tplquad(simpfunc, a, b,
|
| 340 |
+
lambda x: x, lambda x: 2*x,
|
| 341 |
+
lambda x, y: x - y, lambda x, y: x + y,
|
| 342 |
+
(2.,)),
|
| 343 |
+
2*8/3.0 * (b**4.0 - a**4.0))
|
| 344 |
+
|
| 345 |
+
@pytest.mark.xslow
|
| 346 |
+
@pytest.mark.parametrize(
|
| 347 |
+
"x_lower, x_upper, y_lower, y_upper, z_lower, z_upper, expected",
|
| 348 |
+
[
|
| 349 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 350 |
+
# over domain D = [-inf, 0] for all n.
|
| 351 |
+
(-np.inf, 0, -np.inf, 0, -np.inf, 0, (np.pi ** (3 / 2)) / 8),
|
| 352 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 353 |
+
# over domain D = [-inf, -1] for each n (one at a time).
|
| 354 |
+
(-np.inf, -1, -np.inf, 0, -np.inf, 0,
|
| 355 |
+
(np.pi ** (3 / 2)) / 8 * erfc(1)),
|
| 356 |
+
(-np.inf, 0, -np.inf, -1, -np.inf, 0,
|
| 357 |
+
(np.pi ** (3 / 2)) / 8 * erfc(1)),
|
| 358 |
+
(-np.inf, 0, -np.inf, 0, -np.inf, -1,
|
| 359 |
+
(np.pi ** (3 / 2)) / 8 * erfc(1)),
|
| 360 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 361 |
+
# over domain D = [-inf, -1] for each n (two at a time).
|
| 362 |
+
(-np.inf, -1, -np.inf, -1, -np.inf, 0,
|
| 363 |
+
(np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
|
| 364 |
+
(-np.inf, -1, -np.inf, 0, -np.inf, -1,
|
| 365 |
+
(np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
|
| 366 |
+
(-np.inf, 0, -np.inf, -1, -np.inf, -1,
|
| 367 |
+
(np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
|
| 368 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 369 |
+
# over domain D = [-inf, -1] for all n.
|
| 370 |
+
(-np.inf, -1, -np.inf, -1, -np.inf, -1,
|
| 371 |
+
(np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)),
|
| 372 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 373 |
+
# over domain Dx = [-inf, -1] and Dy = Dz = [-inf, 1].
|
| 374 |
+
(-np.inf, -1, -np.inf, 1, -np.inf, 1,
|
| 375 |
+
(np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
|
| 376 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 377 |
+
# over domain Dx = Dy = [-inf, -1] and Dz = [-inf, 1].
|
| 378 |
+
(-np.inf, -1, -np.inf, -1, -np.inf, 1,
|
| 379 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
|
| 380 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 381 |
+
# over domain Dx = Dz = [-inf, -1] and Dy = [-inf, 1].
|
| 382 |
+
(-np.inf, -1, -np.inf, 1, -np.inf, -1,
|
| 383 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
|
| 384 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 385 |
+
# over domain Dx = [-inf, 1] and Dy = Dz = [-inf, -1].
|
| 386 |
+
(-np.inf, 1, -np.inf, -1, -np.inf, -1,
|
| 387 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
|
| 388 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 389 |
+
# over domain Dx = Dy = [-inf, 1] and Dz = [-inf, -1].
|
| 390 |
+
(-np.inf, 1, -np.inf, 1, -np.inf, -1,
|
| 391 |
+
(np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
|
| 392 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 393 |
+
# over domain Dx = Dz = [-inf, 1] and Dy = [-inf, -1].
|
| 394 |
+
(-np.inf, 1, -np.inf, -1, -np.inf, 1,
|
| 395 |
+
(np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
|
| 396 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 397 |
+
# over domain D = [-inf, 1] for each n (one at a time).
|
| 398 |
+
(-np.inf, 1, -np.inf, 0, -np.inf, 0,
|
| 399 |
+
(np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
|
| 400 |
+
(-np.inf, 0, -np.inf, 1, -np.inf, 0,
|
| 401 |
+
(np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
|
| 402 |
+
(-np.inf, 0, -np.inf, 0, -np.inf, 1,
|
| 403 |
+
(np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
|
| 404 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 405 |
+
# over domain D = [-inf, 1] for each n (two at a time).
|
| 406 |
+
(-np.inf, 1, -np.inf, 1, -np.inf, 0,
|
| 407 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
|
| 408 |
+
(-np.inf, 1, -np.inf, 0, -np.inf, 1,
|
| 409 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
|
| 410 |
+
(-np.inf, 0, -np.inf, 1, -np.inf, 1,
|
| 411 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
|
| 412 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 413 |
+
# over domain D = [-inf, 1] for all n.
|
| 414 |
+
(-np.inf, 1, -np.inf, 1, -np.inf, 1,
|
| 415 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)),
|
| 416 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 417 |
+
# over domain D = [0, inf] for all n.
|
| 418 |
+
(0, np.inf, 0, np.inf, 0, np.inf, (np.pi ** (3 / 2)) / 8),
|
| 419 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 420 |
+
# over domain D = [1, inf] for each n (one at a time).
|
| 421 |
+
(1, np.inf, 0, np.inf, 0, np.inf,
|
| 422 |
+
(np.pi ** (3 / 2)) / 8 * erfc(1)),
|
| 423 |
+
(0, np.inf, 1, np.inf, 0, np.inf,
|
| 424 |
+
(np.pi ** (3 / 2)) / 8 * erfc(1)),
|
| 425 |
+
(0, np.inf, 0, np.inf, 1, np.inf,
|
| 426 |
+
(np.pi ** (3 / 2)) / 8 * erfc(1)),
|
| 427 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 428 |
+
# over domain D = [1, inf] for each n (two at a time).
|
| 429 |
+
(1, np.inf, 1, np.inf, 0, np.inf,
|
| 430 |
+
(np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
|
| 431 |
+
(1, np.inf, 0, np.inf, 1, np.inf,
|
| 432 |
+
(np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
|
| 433 |
+
(0, np.inf, 1, np.inf, 1, np.inf,
|
| 434 |
+
(np.pi ** (3 / 2)) / 8 * (erfc(1) ** 2)),
|
| 435 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 436 |
+
# over domain D = [1, inf] for all n.
|
| 437 |
+
(1, np.inf, 1, np.inf, 1, np.inf,
|
| 438 |
+
(np.pi ** (3 / 2)) / 8 * (erfc(1) ** 3)),
|
| 439 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 440 |
+
# over domain D = [-1, inf] for each n (one at a time).
|
| 441 |
+
(-1, np.inf, 0, np.inf, 0, np.inf,
|
| 442 |
+
(np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
|
| 443 |
+
(0, np.inf, -1, np.inf, 0, np.inf,
|
| 444 |
+
(np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
|
| 445 |
+
(0, np.inf, 0, np.inf, -1, np.inf,
|
| 446 |
+
(np.pi ** (3 / 2)) / 8 * (erf(1) + 1)),
|
| 447 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 448 |
+
# over domain D = [-1, inf] for each n (two at a time).
|
| 449 |
+
(-1, np.inf, -1, np.inf, 0, np.inf,
|
| 450 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
|
| 451 |
+
(-1, np.inf, 0, np.inf, -1, np.inf,
|
| 452 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
|
| 453 |
+
(0, np.inf, -1, np.inf, -1, np.inf,
|
| 454 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 2)),
|
| 455 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 456 |
+
# over domain D = [-1, inf] for all n.
|
| 457 |
+
(-1, np.inf, -1, np.inf, -1, np.inf,
|
| 458 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) ** 3)),
|
| 459 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 460 |
+
# over domain Dx = [1, inf] and Dy = Dz = [-1, inf].
|
| 461 |
+
(1, np.inf, -1, np.inf, -1, np.inf,
|
| 462 |
+
(np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
|
| 463 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 464 |
+
# over domain Dx = Dy = [1, inf] and Dz = [-1, inf].
|
| 465 |
+
(1, np.inf, 1, np.inf, -1, np.inf,
|
| 466 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
|
| 467 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 468 |
+
# over domain Dx = Dz = [1, inf] and Dy = [-1, inf].
|
| 469 |
+
(1, np.inf, -1, np.inf, 1, np.inf,
|
| 470 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
|
| 471 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 472 |
+
# over domain Dx = [-1, inf] and Dy = Dz = [1, inf].
|
| 473 |
+
(-1, np.inf, 1, np.inf, 1, np.inf,
|
| 474 |
+
(np.pi ** (3 / 2)) / 8 * ((erf(1) + 1) * (erfc(1) ** 2))),
|
| 475 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 476 |
+
# over domain Dx = Dy = [-1, inf] and Dz = [1, inf].
|
| 477 |
+
(-1, np.inf, -1, np.inf, 1, np.inf,
|
| 478 |
+
(np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
|
| 479 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 480 |
+
# over domain Dx = Dz = [-1, inf] and Dy = [1, inf].
|
| 481 |
+
(-1, np.inf, 1, np.inf, -1, np.inf,
|
| 482 |
+
(np.pi ** (3 / 2)) / 8 * (((erf(1) + 1) ** 2) * erfc(1))),
|
| 483 |
+
# Multiple integration of a function in n = 3 variables: f(x, y, z)
|
| 484 |
+
# over domain D = [-inf, inf] for all n.
|
| 485 |
+
(-np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf,
|
| 486 |
+
np.pi ** (3 / 2)),
|
| 487 |
+
],
|
| 488 |
+
)
|
| 489 |
+
def test_triple_integral_improper(
|
| 490 |
+
self,
|
| 491 |
+
x_lower,
|
| 492 |
+
x_upper,
|
| 493 |
+
y_lower,
|
| 494 |
+
y_upper,
|
| 495 |
+
z_lower,
|
| 496 |
+
z_upper,
|
| 497 |
+
expected
|
| 498 |
+
):
|
| 499 |
+
# The Gaussian Integral.
|
| 500 |
+
def f(x, y, z):
|
| 501 |
+
return np.exp(-x ** 2 - y ** 2 - z ** 2)
|
| 502 |
+
|
| 503 |
+
assert_quad(
|
| 504 |
+
tplquad(f, x_lower, x_upper, y_lower, y_upper, z_lower, z_upper),
|
| 505 |
+
expected,
|
| 506 |
+
error_tolerance=6e-8
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
def test_complex(self):
|
| 510 |
+
def tfunc(x):
|
| 511 |
+
return np.exp(1j*x)
|
| 512 |
+
|
| 513 |
+
assert np.allclose(
|
| 514 |
+
quad(tfunc, 0, np.pi/2, complex_func=True)[0],
|
| 515 |
+
1+1j)
|
| 516 |
+
|
| 517 |
+
# We consider a divergent case in order to force quadpack
|
| 518 |
+
# to return an error message. The output is compared
|
| 519 |
+
# against what is returned by explicit integration
|
| 520 |
+
# of the parts.
|
| 521 |
+
kwargs = {'a': 0, 'b': np.inf, 'full_output': True,
|
| 522 |
+
'weight': 'cos', 'wvar': 1}
|
| 523 |
+
res_c = quad(tfunc, complex_func=True, **kwargs)
|
| 524 |
+
res_r = quad(lambda x: np.real(np.exp(1j*x)),
|
| 525 |
+
complex_func=False,
|
| 526 |
+
**kwargs)
|
| 527 |
+
res_i = quad(lambda x: np.imag(np.exp(1j*x)),
|
| 528 |
+
complex_func=False,
|
| 529 |
+
**kwargs)
|
| 530 |
+
|
| 531 |
+
np.testing.assert_equal(res_c[0], res_r[0] + 1j*res_i[0])
|
| 532 |
+
np.testing.assert_equal(res_c[1], res_r[1] + 1j*res_i[1])
|
| 533 |
+
|
| 534 |
+
assert len(res_c[2]['real']) == len(res_r[2:]) == 3
|
| 535 |
+
assert res_c[2]['real'][2] == res_r[4]
|
| 536 |
+
assert res_c[2]['real'][1] == res_r[3]
|
| 537 |
+
assert res_c[2]['real'][0]['lst'] == res_r[2]['lst']
|
| 538 |
+
|
| 539 |
+
assert len(res_c[2]['imag']) == len(res_i[2:]) == 1
|
| 540 |
+
assert res_c[2]['imag'][0]['lst'] == res_i[2]['lst']
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
class TestNQuad:
|
| 544 |
+
@pytest.mark.fail_slow(2)
|
| 545 |
+
def test_fixed_limits(self):
|
| 546 |
+
def func1(x0, x1, x2, x3):
|
| 547 |
+
val = (x0**2 + x1*x2 - x3**3 + np.sin(x0) +
|
| 548 |
+
(1 if (x0 - 0.2*x3 - 0.5 - 0.25*x1 > 0) else 0))
|
| 549 |
+
return val
|
| 550 |
+
|
| 551 |
+
def opts_basic(*args):
|
| 552 |
+
return {'points': [0.2*args[2] + 0.5 + 0.25*args[0]]}
|
| 553 |
+
|
| 554 |
+
res = nquad(func1, [[0, 1], [-1, 1], [.13, .8], [-.15, 1]],
|
| 555 |
+
opts=[opts_basic, {}, {}, {}], full_output=True)
|
| 556 |
+
assert_quad(res[:-1], 1.5267454070738635)
|
| 557 |
+
assert_(res[-1]['neval'] > 0 and res[-1]['neval'] < 4e5)
|
| 558 |
+
|
| 559 |
+
@pytest.mark.fail_slow(2)
|
| 560 |
+
def test_variable_limits(self):
|
| 561 |
+
scale = .1
|
| 562 |
+
|
| 563 |
+
def func2(x0, x1, x2, x3, t0, t1):
|
| 564 |
+
val = (x0*x1*x3**2 + np.sin(x2) + 1 +
|
| 565 |
+
(1 if x0 + t1*x1 - t0 > 0 else 0))
|
| 566 |
+
return val
|
| 567 |
+
|
| 568 |
+
def lim0(x1, x2, x3, t0, t1):
|
| 569 |
+
return [scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) - 1,
|
| 570 |
+
scale * (x1**2 + x2 + np.cos(x3)*t0*t1 + 1) + 1]
|
| 571 |
+
|
| 572 |
+
def lim1(x2, x3, t0, t1):
|
| 573 |
+
return [scale * (t0*x2 + t1*x3) - 1,
|
| 574 |
+
scale * (t0*x2 + t1*x3) + 1]
|
| 575 |
+
|
| 576 |
+
def lim2(x3, t0, t1):
|
| 577 |
+
return [scale * (x3 + t0**2*t1**3) - 1,
|
| 578 |
+
scale * (x3 + t0**2*t1**3) + 1]
|
| 579 |
+
|
| 580 |
+
def lim3(t0, t1):
|
| 581 |
+
return [scale * (t0 + t1) - 1, scale * (t0 + t1) + 1]
|
| 582 |
+
|
| 583 |
+
def opts0(x1, x2, x3, t0, t1):
|
| 584 |
+
return {'points': [t0 - t1*x1]}
|
| 585 |
+
|
| 586 |
+
def opts1(x2, x3, t0, t1):
|
| 587 |
+
return {}
|
| 588 |
+
|
| 589 |
+
def opts2(x3, t0, t1):
|
| 590 |
+
return {}
|
| 591 |
+
|
| 592 |
+
def opts3(t0, t1):
|
| 593 |
+
return {}
|
| 594 |
+
|
| 595 |
+
res = nquad(func2, [lim0, lim1, lim2, lim3], args=(0, 0),
|
| 596 |
+
opts=[opts0, opts1, opts2, opts3])
|
| 597 |
+
assert_quad(res, 25.066666666666663)
|
| 598 |
+
|
| 599 |
+
def test_square_separate_ranges_and_opts(self):
|
| 600 |
+
def f(y, x):
|
| 601 |
+
return 1.0
|
| 602 |
+
|
| 603 |
+
assert_quad(nquad(f, [[-1, 1], [-1, 1]], opts=[{}, {}]), 4.0)
|
| 604 |
+
|
| 605 |
+
def test_square_aliased_ranges_and_opts(self):
|
| 606 |
+
def f(y, x):
|
| 607 |
+
return 1.0
|
| 608 |
+
|
| 609 |
+
r = [-1, 1]
|
| 610 |
+
opt = {}
|
| 611 |
+
assert_quad(nquad(f, [r, r], opts=[opt, opt]), 4.0)
|
| 612 |
+
|
| 613 |
+
def test_square_separate_fn_ranges_and_opts(self):
|
| 614 |
+
def f(y, x):
|
| 615 |
+
return 1.0
|
| 616 |
+
|
| 617 |
+
def fn_range0(*args):
|
| 618 |
+
return (-1, 1)
|
| 619 |
+
|
| 620 |
+
def fn_range1(*args):
|
| 621 |
+
return (-1, 1)
|
| 622 |
+
|
| 623 |
+
def fn_opt0(*args):
|
| 624 |
+
return {}
|
| 625 |
+
|
| 626 |
+
def fn_opt1(*args):
|
| 627 |
+
return {}
|
| 628 |
+
|
| 629 |
+
ranges = [fn_range0, fn_range1]
|
| 630 |
+
opts = [fn_opt0, fn_opt1]
|
| 631 |
+
assert_quad(nquad(f, ranges, opts=opts), 4.0)
|
| 632 |
+
|
| 633 |
+
def test_square_aliased_fn_ranges_and_opts(self):
|
| 634 |
+
def f(y, x):
|
| 635 |
+
return 1.0
|
| 636 |
+
|
| 637 |
+
def fn_range(*args):
|
| 638 |
+
return (-1, 1)
|
| 639 |
+
|
| 640 |
+
def fn_opt(*args):
|
| 641 |
+
return {}
|
| 642 |
+
|
| 643 |
+
ranges = [fn_range, fn_range]
|
| 644 |
+
opts = [fn_opt, fn_opt]
|
| 645 |
+
assert_quad(nquad(f, ranges, opts=opts), 4.0)
|
| 646 |
+
|
| 647 |
+
def test_matching_quad(self):
|
| 648 |
+
def func(x):
|
| 649 |
+
return x**2 + 1
|
| 650 |
+
|
| 651 |
+
res, reserr = quad(func, 0, 4)
|
| 652 |
+
res2, reserr2 = nquad(func, ranges=[[0, 4]])
|
| 653 |
+
assert_almost_equal(res, res2)
|
| 654 |
+
assert_almost_equal(reserr, reserr2)
|
| 655 |
+
|
| 656 |
+
def test_matching_dblquad(self):
|
| 657 |
+
def func2d(x0, x1):
|
| 658 |
+
return x0**2 + x1**3 - x0 * x1 + 1
|
| 659 |
+
|
| 660 |
+
res, reserr = dblquad(func2d, -2, 2, lambda x: -3, lambda x: 3)
|
| 661 |
+
res2, reserr2 = nquad(func2d, [[-3, 3], (-2, 2)])
|
| 662 |
+
assert_almost_equal(res, res2)
|
| 663 |
+
assert_almost_equal(reserr, reserr2)
|
| 664 |
+
|
| 665 |
+
def test_matching_tplquad(self):
|
| 666 |
+
def func3d(x0, x1, x2, c0, c1):
|
| 667 |
+
return x0**2 + c0 * x1**3 - x0 * x1 + 1 + c1 * np.sin(x2)
|
| 668 |
+
|
| 669 |
+
res = tplquad(func3d, -1, 2, lambda x: -2, lambda x: 2,
|
| 670 |
+
lambda x, y: -np.pi, lambda x, y: np.pi,
|
| 671 |
+
args=(2, 3))
|
| 672 |
+
res2 = nquad(func3d, [[-np.pi, np.pi], [-2, 2], (-1, 2)], args=(2, 3))
|
| 673 |
+
assert_almost_equal(res, res2)
|
| 674 |
+
|
| 675 |
+
def test_dict_as_opts(self):
|
| 676 |
+
try:
|
| 677 |
+
nquad(lambda x, y: x * y, [[0, 1], [0, 1]], opts={'epsrel': 0.0001})
|
| 678 |
+
except TypeError:
|
| 679 |
+
assert False
|
| 680 |
+
|
parrot/lib/python3.10/site-packages/scipy/integrate/vode.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is not meant for public use and will be removed in SciPy v2.0.0.
|
| 2 |
+
|
| 3 |
+
from scipy._lib.deprecation import _sub_module_deprecation
|
| 4 |
+
|
| 5 |
+
__all__: list[str] = []
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def __dir__():
|
| 9 |
+
return __all__
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def __getattr__(name):
|
| 13 |
+
return _sub_module_deprecation(sub_package="integrate", module="vode",
|
| 14 |
+
private_modules=["_vode"], all=__all__,
|
| 15 |
+
attribute=name)
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/context/context.h
ADDED
|
@@ -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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <cstdint>
|
| 4 |
+
#include <functional>
|
| 5 |
+
|
| 6 |
+
#include <ATen/core/Dict.h>
|
| 7 |
+
#include <torch/csrc/autograd/engine.h>
|
| 8 |
+
#include <torch/csrc/distributed/autograd/functions/recvrpc_backward.h>
|
| 9 |
+
#include <torch/csrc/distributed/autograd/functions/sendrpc_backward.h>
|
| 10 |
+
#include <torch/csrc/distributed/rpc/rpc_agent.h>
|
| 11 |
+
|
| 12 |
+
namespace torch {
|
| 13 |
+
namespace distributed {
|
| 14 |
+
namespace autograd {
|
| 15 |
+
|
| 16 |
+
class RecvRpcBackward;
|
| 17 |
+
|
| 18 |
+
// DistAutogradContext which stores information for a single distributed
|
| 19 |
+
// autograd pass on a worker.
|
| 20 |
+
class TORCH_API DistAutogradContext {
|
| 21 |
+
public:
|
| 22 |
+
using GradCallback = std::function<bool(torch::Tensor&)>;
|
| 23 |
+
|
| 24 |
+
explicit DistAutogradContext(int64_t contextId);
|
| 25 |
+
|
| 26 |
+
// Retrieves the autograd context id for this context.
|
| 27 |
+
int64_t contextId() const;
|
| 28 |
+
|
| 29 |
+
// Records a 'send' autograd function for this context with the provided
|
| 30 |
+
// message id.
|
| 31 |
+
void addSendFunction(
|
| 32 |
+
const std::shared_ptr<SendRpcBackward>& func,
|
| 33 |
+
int64_t autograd_message_id);
|
| 34 |
+
|
| 35 |
+
// Records a 'recv' autograd function for this context with the provided
|
| 36 |
+
// message id.
|
| 37 |
+
void addRecvFunction(
|
| 38 |
+
std::shared_ptr<RecvRpcBackward>& func,
|
| 39 |
+
int64_t autograd_message_id);
|
| 40 |
+
|
| 41 |
+
// Given an autograd_message_id, retrieve the appropriate send function.
|
| 42 |
+
std::shared_ptr<SendRpcBackward> retrieveSendFunction(
|
| 43 |
+
int64_t autograd_message_id);
|
| 44 |
+
|
| 45 |
+
// Return all send functions for this context.
|
| 46 |
+
std::unordered_map<int64_t, std::shared_ptr<SendRpcBackward>> sendFunctions()
|
| 47 |
+
const;
|
| 48 |
+
|
| 49 |
+
// Return all recv functions for this context.
|
| 50 |
+
std::unordered_map<int64_t, std::shared_ptr<RecvRpcBackward>> recvFunctions()
|
| 51 |
+
const;
|
| 52 |
+
|
| 53 |
+
// Adds a future message recording an outstanding RPC.
|
| 54 |
+
void addOutstandingRpc(const c10::intrusive_ptr<rpc::JitFuture>& jitFuture);
|
| 55 |
+
|
| 56 |
+
// Returns all gradients.
|
| 57 |
+
const c10::Dict<torch::Tensor, torch::Tensor> getGradients() const;
|
| 58 |
+
|
| 59 |
+
// This function gives a mutable grad reference to the callback.
|
| 60 |
+
// If the callback returns true, it means the grad in the context
|
| 61 |
+
// needs to be updated.
|
| 62 |
+
void runGradCallbackForVariable(
|
| 63 |
+
const torch::autograd::Variable& variable,
|
| 64 |
+
GradCallback&& cb);
|
| 65 |
+
|
| 66 |
+
DistAutogradContext(const DistAutogradContext&) = delete;
|
| 67 |
+
DistAutogradContext& operator=(const DistAutogradContext&) = delete;
|
| 68 |
+
DistAutogradContext(DistAutogradContext&&) = delete;
|
| 69 |
+
DistAutogradContext& operator=(DistAutogradContext&&) = delete;
|
| 70 |
+
|
| 71 |
+
// records the workerID of a node that we sent an RPC to.
|
| 72 |
+
// workerIDs are added here when we attach a send function to this autograd
|
| 73 |
+
// context
|
| 74 |
+
void addKnownWorkerId(const rpc::worker_id_t workerId);
|
| 75 |
+
|
| 76 |
+
// Retrieves a set containing the known workerIds for this context
|
| 77 |
+
// These are the different workers that this context has sent RPCs to.
|
| 78 |
+
std::unordered_set<rpc::worker_id_t> getKnownWorkerIds() const;
|
| 79 |
+
|
| 80 |
+
private:
|
| 81 |
+
friend class BackwardPassCleanupGuard;
|
| 82 |
+
friend class DistEngine;
|
| 83 |
+
friend class RecvRpcBackward;
|
| 84 |
+
friend class DistAccumulateGradCaptureHook;
|
| 85 |
+
|
| 86 |
+
// Record that we would like to accumulate the provided gradient on the given
|
| 87 |
+
// variable.
|
| 88 |
+
void accumulateGrad(
|
| 89 |
+
const torch::autograd::Variable& variable,
|
| 90 |
+
const torch::Tensor& grad,
|
| 91 |
+
size_t num_expected_refs);
|
| 92 |
+
|
| 93 |
+
// Retrieve the GraphTask.
|
| 94 |
+
std::shared_ptr<torch::autograd::GraphTask> retrieveGraphTask();
|
| 95 |
+
|
| 96 |
+
// Set the appropriate graph task for the backward pass. Can be called only
|
| 97 |
+
// once.
|
| 98 |
+
void setGraphTask(std::shared_ptr<torch::autograd::GraphTask> graphTask);
|
| 99 |
+
|
| 100 |
+
// Resets the graph task to ensure we can run another distributed backward
|
| 101 |
+
// pass for the same autograd context.
|
| 102 |
+
void resetGraphTask();
|
| 103 |
+
|
| 104 |
+
// Waits for all outstanding RPCs for this context to finish and clears all
|
| 105 |
+
// outstanding rpcs held in this context. This should be called only once.
|
| 106 |
+
c10::intrusive_ptr<c10::ivalue::Future> clearAndWaitForOutstandingRpcsAsync();
|
| 107 |
+
|
| 108 |
+
void clearOutstandingRpcs();
|
| 109 |
+
|
| 110 |
+
// Record an event to mark the completion of gradient computation. These
|
| 111 |
+
// events will later help to properly synchronize gradients consumptions
|
| 112 |
+
// in getGradients(). We need these events because backward and
|
| 113 |
+
// optimizer.step are separate RPC calls, and will occur on different CUDA
|
| 114 |
+
// streams. Without synchronization, it is possible that gradients are
|
| 115 |
+
// consumed before they are ready.
|
| 116 |
+
void recordGradEvent(c10::Device device);
|
| 117 |
+
|
| 118 |
+
const int64_t contextId_;
|
| 119 |
+
|
| 120 |
+
// Set containing known worker IDs, used in cleaning up autograd context.
|
| 121 |
+
// Whenever a sendRpcBackward is attached to the autograd graph for this
|
| 122 |
+
// context, the destination is added here.
|
| 123 |
+
std::unordered_set<rpc::worker_id_t> knownWorkerIds_;
|
| 124 |
+
|
| 125 |
+
// Map from autograd_message_id to appropriate 'send' autograd function.
|
| 126 |
+
std::unordered_map<int64_t, std::shared_ptr<SendRpcBackward>>
|
| 127 |
+
sendAutogradFunctions_;
|
| 128 |
+
|
| 129 |
+
// Map from autograd_message_id to appropriate 'recv' autograd function.
|
| 130 |
+
std::unordered_map<int64_t, std::shared_ptr<RecvRpcBackward>>
|
| 131 |
+
recvAutogradFunctions_;
|
| 132 |
+
|
| 133 |
+
// Gradients accumulated in this context so far. The key is the variable on
|
| 134 |
+
// which the gradient needs to be accumulated and the value is the gradient
|
| 135 |
+
// that needs to be accumulated on that variable..
|
| 136 |
+
c10::Dict<torch::Tensor, torch::Tensor> accumulatedGrads_;
|
| 137 |
+
|
| 138 |
+
// See comments for recordGradEvent(c10::Device device);
|
| 139 |
+
std::unordered_map<c10::Device, c10::Event> gradReadyEvents_;
|
| 140 |
+
const c10::impl::VirtualGuardImpl impl_;
|
| 141 |
+
|
| 142 |
+
// The autograd GraphTask for the backward pass on this node for this context.
|
| 143 |
+
std::shared_ptr<torch::autograd::GraphTask> graphTask_;
|
| 144 |
+
|
| 145 |
+
// List of futures for RPCs initiated by this node to propagate gradients to
|
| 146 |
+
// other nodes. The distributed autograd engine on this node can return
|
| 147 |
+
// successfully only if all these futures are done and are successful.
|
| 148 |
+
std::vector<c10::intrusive_ptr<rpc::JitFuture>> outStandingRpcs_;
|
| 149 |
+
|
| 150 |
+
// Lock to protect concurrent modification of the context.
|
| 151 |
+
mutable std::mutex lock_;
|
| 152 |
+
};
|
| 153 |
+
|
| 154 |
+
using ContextPtr = std::shared_ptr<DistAutogradContext>;
|
| 155 |
+
|
| 156 |
+
// This class stores a shared_ptr to a DistAutogradContext instance in a
|
| 157 |
+
// thread local variable. The instance is given by the call site. The class
|
| 158 |
+
// doesn't know the current context. It's just a util class.
|
| 159 |
+
class TORCH_API ThreadLocalDistAutogradContext {
|
| 160 |
+
public:
|
| 161 |
+
// Store 'new_context' to the thread local variable maintained by this class.
|
| 162 |
+
explicit ThreadLocalDistAutogradContext(ContextPtr&& new_context);
|
| 163 |
+
~ThreadLocalDistAutogradContext();
|
| 164 |
+
|
| 165 |
+
// Retrieve the stored DistAutogradContext instance.
|
| 166 |
+
static ContextPtr getContextPtr();
|
| 167 |
+
|
| 168 |
+
private:
|
| 169 |
+
ContextPtr prev_context_ptr_;
|
| 170 |
+
};
|
| 171 |
+
|
| 172 |
+
} // namespace autograd
|
| 173 |
+
} // namespace distributed
|
| 174 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/functions/recvrpc_backward.h
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/autograd/function.h>
|
| 4 |
+
#include <torch/csrc/distributed/autograd/context/context.h>
|
| 5 |
+
#include <torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h>
|
| 6 |
+
#include <torch/csrc/distributed/rpc/rpc_agent.h>
|
| 7 |
+
|
| 8 |
+
namespace torch {
|
| 9 |
+
namespace distributed {
|
| 10 |
+
namespace autograd {
|
| 11 |
+
|
| 12 |
+
// Forward declarations.
|
| 13 |
+
class DistAutogradContext;
|
| 14 |
+
|
| 15 |
+
// As part of our distributed autograd implementation, whenever we receive an
|
| 16 |
+
// RPC from a node, we add a 'RecvRpcBackward' autograd function to the
|
| 17 |
+
// autograd graph. This is more or less a placeholder function that is used to
|
| 18 |
+
// pass gradients to the remote host during the backward pass. The inputs to the
|
| 19 |
+
// RPC function are the inputs to this autograd function.
|
| 20 |
+
class TORCH_API RecvRpcBackward : public torch::autograd::Node {
|
| 21 |
+
public:
|
| 22 |
+
explicit RecvRpcBackward(
|
| 23 |
+
const AutogradMetadata& autogradMetadata,
|
| 24 |
+
std::shared_ptr<DistAutogradContext> autogradContext,
|
| 25 |
+
rpc::worker_id_t fromWorkerId,
|
| 26 |
+
rpc::DeviceMap deviceMap);
|
| 27 |
+
|
| 28 |
+
torch::autograd::variable_list apply(
|
| 29 |
+
torch::autograd::variable_list&& grads) override;
|
| 30 |
+
|
| 31 |
+
private:
|
| 32 |
+
const AutogradMetadata autogradMetadata_;
|
| 33 |
+
|
| 34 |
+
// Hold a weak reference to the autograd context to avoid circular
|
| 35 |
+
// dependencies with the context (since it holds a reference to
|
| 36 |
+
// RecvRpcBackward).
|
| 37 |
+
std::weak_ptr<DistAutogradContext> autogradContext_;
|
| 38 |
+
|
| 39 |
+
// The worker id from which the RPC was received. During the backward pass,
|
| 40 |
+
// we need to propagate the gradients to this workerId.
|
| 41 |
+
rpc::worker_id_t fromWorkerId_;
|
| 42 |
+
|
| 43 |
+
// Device mapping for tensors sent over RPC.
|
| 44 |
+
const rpc::DeviceMap deviceMap_;
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
} // namespace autograd
|
| 48 |
+
} // namespace distributed
|
| 49 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/Export.h>
|
| 4 |
+
#include <cstdint>
|
| 5 |
+
|
| 6 |
+
namespace torch {
|
| 7 |
+
namespace distributed {
|
| 8 |
+
namespace autograd {
|
| 9 |
+
|
| 10 |
+
// This structure represents autograd metadata that we need to pass across
|
| 11 |
+
// different nodes when we call an RPC which needs autograd computation.
|
| 12 |
+
struct TORCH_API AutogradMetadata {
|
| 13 |
+
AutogradMetadata(int64_t autogradContextId, int64_t autogradMessageId);
|
| 14 |
+
|
| 15 |
+
// autogradContextId_ is a globally unique integer that identifies a
|
| 16 |
+
// particular distributed autograd pass.
|
| 17 |
+
int64_t autogradContextId;
|
| 18 |
+
// autogradMessageId_ is a globally unique integer that identifies a pair
|
| 19 |
+
// of send/recv autograd functions.
|
| 20 |
+
int64_t autogradMessageId;
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
} // namespace autograd
|
| 24 |
+
} // namespace distributed
|
| 25 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/cleanup_autograd_context_resp.h
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/distributed/rpc/message.h>
|
| 4 |
+
#include <torch/csrc/distributed/rpc/rpc_command_base.h>
|
| 5 |
+
|
| 6 |
+
namespace torch {
|
| 7 |
+
namespace distributed {
|
| 8 |
+
namespace autograd {
|
| 9 |
+
|
| 10 |
+
// Empty response for CleanupAutogradContextReq. Send to acknowledge receipt of
|
| 11 |
+
// a CleanupAutogradContextReq.
|
| 12 |
+
class TORCH_API CleanupAutogradContextResp : public rpc::RpcCommandBase {
|
| 13 |
+
public:
|
| 14 |
+
CleanupAutogradContextResp() = default;
|
| 15 |
+
// Serialization and deserialization methods.
|
| 16 |
+
c10::intrusive_ptr<rpc::Message> toMessageImpl() && override;
|
| 17 |
+
static std::unique_ptr<CleanupAutogradContextResp> fromMessage(
|
| 18 |
+
const rpc::Message& message);
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
} // namespace autograd
|
| 22 |
+
} // namespace distributed
|
| 23 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_req.h
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h>
|
| 4 |
+
#include <torch/csrc/distributed/rpc/message.h>
|
| 5 |
+
#include <torch/csrc/distributed/rpc/rpc_command_base.h>
|
| 6 |
+
#include <vector>
|
| 7 |
+
|
| 8 |
+
namespace torch {
|
| 9 |
+
namespace distributed {
|
| 10 |
+
namespace autograd {
|
| 11 |
+
|
| 12 |
+
// Used to propagate gradients from one node to another during a distributed
|
| 13 |
+
// backwards pass. This RPC call is invoked when we hit a `recv` autograd
|
| 14 |
+
// function during backward pass execution.
|
| 15 |
+
class TORCH_API PropagateGradientsReq : public rpc::RpcCommandBase {
|
| 16 |
+
public:
|
| 17 |
+
PropagateGradientsReq(
|
| 18 |
+
const AutogradMetadata& autogradMetadata,
|
| 19 |
+
std::vector<torch::autograd::Variable> grads,
|
| 20 |
+
bool retainGraph = false);
|
| 21 |
+
|
| 22 |
+
const AutogradMetadata& getAutogradMetadata();
|
| 23 |
+
|
| 24 |
+
const std::vector<torch::autograd::Variable>& getGrads();
|
| 25 |
+
|
| 26 |
+
// Serialization and deserialization methods.
|
| 27 |
+
c10::intrusive_ptr<rpc::Message> toMessageImpl() && override;
|
| 28 |
+
static std::unique_ptr<PropagateGradientsReq> fromMessage(
|
| 29 |
+
const rpc::Message& message);
|
| 30 |
+
|
| 31 |
+
// Whether or not to retain the autograd graph.
|
| 32 |
+
bool retainGraph();
|
| 33 |
+
|
| 34 |
+
private:
|
| 35 |
+
AutogradMetadata autogradMetadata_;
|
| 36 |
+
std::vector<torch::autograd::Variable> grads_;
|
| 37 |
+
bool retainGraph_;
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
} // namespace autograd
|
| 41 |
+
} // namespace distributed
|
| 42 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/propagate_gradients_resp.h
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/distributed/rpc/message.h>
|
| 4 |
+
#include <torch/csrc/distributed/rpc/rpc_command_base.h>
|
| 5 |
+
|
| 6 |
+
namespace torch {
|
| 7 |
+
namespace distributed {
|
| 8 |
+
namespace autograd {
|
| 9 |
+
|
| 10 |
+
// Response for the PropagateGradients call. Currently, this class is mostly
|
| 11 |
+
// just a placeholder and sends an empty message over the wire. The purpose of
|
| 12 |
+
// this RPC command is to indicate whether or not the PropagateGradientsReq call
|
| 13 |
+
// was successfully or not.
|
| 14 |
+
class TORCH_API PropagateGradientsResp : public rpc::RpcCommandBase {
|
| 15 |
+
public:
|
| 16 |
+
PropagateGradientsResp() = default;
|
| 17 |
+
c10::intrusive_ptr<rpc::Message> toMessageImpl() && override;
|
| 18 |
+
static std::unique_ptr<PropagateGradientsResp> fromMessage(
|
| 19 |
+
const rpc::Message& message);
|
| 20 |
+
};
|
| 21 |
+
|
| 22 |
+
} // namespace autograd
|
| 23 |
+
} // namespace distributed
|
| 24 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_req.h
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/autograd/profiler.h>
|
| 4 |
+
#include <torch/csrc/distributed/rpc/message.h>
|
| 5 |
+
#include <torch/csrc/distributed/rpc/rpc_agent.h>
|
| 6 |
+
#include <torch/csrc/distributed/rpc/rpc_command_base.h>
|
| 7 |
+
#include <torch/csrc/distributed/rpc/types.h>
|
| 8 |
+
|
| 9 |
+
namespace torch {
|
| 10 |
+
namespace distributed {
|
| 11 |
+
namespace autograd {
|
| 12 |
+
|
| 13 |
+
class TORCH_API RpcWithProfilingReq : public rpc::RpcCommandBase {
|
| 14 |
+
public:
|
| 15 |
+
// For sending RPCs, invoked when client is creating this RPC command.
|
| 16 |
+
RpcWithProfilingReq(
|
| 17 |
+
rpc::MessageType messageType,
|
| 18 |
+
c10::intrusive_ptr<rpc::Message> wrappedMessage,
|
| 19 |
+
torch::autograd::profiler::ProfilerConfig&& profilerConfig,
|
| 20 |
+
rpc::ProfilingId profilingKeyId);
|
| 21 |
+
|
| 22 |
+
// For receiving an RPC
|
| 23 |
+
// Used in fromMessage.
|
| 24 |
+
RpcWithProfilingReq(
|
| 25 |
+
rpc::MessageType messageType,
|
| 26 |
+
std::unique_ptr<rpc::RpcCommandBase> wrappedRpc,
|
| 27 |
+
rpc::MessageType wrappedMessageType,
|
| 28 |
+
std::vector<torch::Tensor> tensors,
|
| 29 |
+
torch::autograd::profiler::ProfilerConfig&& profilerConfig,
|
| 30 |
+
rpc::ProfilingId profilingKeyId);
|
| 31 |
+
|
| 32 |
+
// Convert this RPC Command to a Message that can be sent over the wire.
|
| 33 |
+
c10::intrusive_ptr<rpc::Message> toMessageImpl() && override;
|
| 34 |
+
static std::unique_ptr<RpcWithProfilingReq> fromMessage(
|
| 35 |
+
const rpc::Message& message);
|
| 36 |
+
|
| 37 |
+
// Retrieve the profiling data that is associated with this command.
|
| 38 |
+
torch::autograd::profiler::ProfilerConfig getProfilingConfig() const;
|
| 39 |
+
// Retrieve the globally unique profiling ID corresponding to this command.
|
| 40 |
+
const rpc::ProfilingId& getProfilingId() const;
|
| 41 |
+
// Retrieve the original RPC which this ProfilingRPC wraps.
|
| 42 |
+
RpcCommandBase& wrappedRpc();
|
| 43 |
+
// Destructively move the wrapped RPC.
|
| 44 |
+
std::unique_ptr<RpcCommandBase> moveWrappedRpc() &&;
|
| 45 |
+
// Message type of the wrapped RPC
|
| 46 |
+
rpc::MessageType wrappedMessageType() const;
|
| 47 |
+
void setWrappedRpc(std::unique_ptr<RpcCommandBase> wrappedRpc);
|
| 48 |
+
|
| 49 |
+
private:
|
| 50 |
+
// message type
|
| 51 |
+
const rpc::MessageType messageType_;
|
| 52 |
+
// wrapped message
|
| 53 |
+
c10::intrusive_ptr<rpc::Message> wrappedMessage_;
|
| 54 |
+
std::unique_ptr<RpcCommandBase> wrappedRpc_;
|
| 55 |
+
rpc::MessageType wrappedMessageType_;
|
| 56 |
+
std::vector<torch::Tensor> tensors_;
|
| 57 |
+
const torch::autograd::profiler::ProfilerConfig profilerConfig_;
|
| 58 |
+
const rpc::ProfilingId profilingKeyId_;
|
| 59 |
+
};
|
| 60 |
+
} // namespace autograd
|
| 61 |
+
} // namespace distributed
|
| 62 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rpc_with_profiling_resp.h
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/autograd/profiler.h>
|
| 4 |
+
#include <torch/csrc/distributed/rpc/message.h>
|
| 5 |
+
#include <torch/csrc/distributed/rpc/rpc_agent.h>
|
| 6 |
+
#include <torch/csrc/distributed/rpc/rpc_command_base.h>
|
| 7 |
+
#include <torch/csrc/distributed/rpc/types.h>
|
| 8 |
+
|
| 9 |
+
namespace torch {
|
| 10 |
+
namespace distributed {
|
| 11 |
+
namespace autograd {
|
| 12 |
+
class TORCH_API RpcWithProfilingResp : public rpc::RpcCommandBase {
|
| 13 |
+
public:
|
| 14 |
+
// For sending RPCs over the wire
|
| 15 |
+
RpcWithProfilingResp(
|
| 16 |
+
rpc::MessageType messageType,
|
| 17 |
+
c10::intrusive_ptr<rpc::Message> wrappedMessage,
|
| 18 |
+
std::vector<torch::autograd::profiler::LegacyEvent> profiledEvents,
|
| 19 |
+
rpc::ProfilingId profilingId);
|
| 20 |
+
|
| 21 |
+
// For receiving RPCs. Used in from message when converting a message received
|
| 22 |
+
// over the wire.
|
| 23 |
+
RpcWithProfilingResp(
|
| 24 |
+
rpc::MessageType messageType,
|
| 25 |
+
std::unique_ptr<rpc::RpcCommandBase> wrappedRpc,
|
| 26 |
+
rpc::MessageType wrappedMessageType,
|
| 27 |
+
std::vector<torch::Tensor> tensors,
|
| 28 |
+
std::vector<torch::autograd::profiler::LegacyEvent> profiledEvents,
|
| 29 |
+
rpc::ProfilingId profilingId);
|
| 30 |
+
c10::intrusive_ptr<rpc::Message> toMessageImpl() && override;
|
| 31 |
+
static std::unique_ptr<RpcWithProfilingResp> fromMessage(
|
| 32 |
+
const rpc::Message& message);
|
| 33 |
+
// Retrieve remote Events
|
| 34 |
+
std::vector<torch::autograd::profiler::LegacyEvent> getProfiledEvents() const;
|
| 35 |
+
// Retrieve the globally unique profiling ID corresponding to this command.
|
| 36 |
+
const rpc::ProfilingId& getProfilingId() const;
|
| 37 |
+
// Retrieve the original RPC which this ProfilingRPC wraps.
|
| 38 |
+
RpcCommandBase& wrappedRpc();
|
| 39 |
+
// Destructively move the wrapped RPC.
|
| 40 |
+
std::unique_ptr<RpcCommandBase> moveWrappedRpc() &&;
|
| 41 |
+
// Message type of the wrapped RPC
|
| 42 |
+
rpc::MessageType wrappedMessageType() const;
|
| 43 |
+
// Set the wrapped RPC for this RPC.
|
| 44 |
+
void setWrappedRpc(std::unique_ptr<RpcCommandBase> wrappedRpc);
|
| 45 |
+
|
| 46 |
+
private:
|
| 47 |
+
// message type
|
| 48 |
+
const rpc::MessageType messageType_;
|
| 49 |
+
// wrapped message
|
| 50 |
+
c10::intrusive_ptr<rpc::Message> wrappedMessage_;
|
| 51 |
+
std::unique_ptr<RpcCommandBase> wrappedRpc_;
|
| 52 |
+
rpc::MessageType wrappedMessageType_;
|
| 53 |
+
std::vector<torch::Tensor> tensors_;
|
| 54 |
+
const std::vector<torch::autograd::profiler::LegacyEvent> profiledEvents_;
|
| 55 |
+
const rpc::ProfilingId profilingId_;
|
| 56 |
+
};
|
| 57 |
+
} // namespace autograd
|
| 58 |
+
} // namespace distributed
|
| 59 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/autograd/rpc_messages/rref_backward_resp.h
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/distributed/rpc/message.h>
|
| 4 |
+
#include <torch/csrc/distributed/rpc/rpc_command_base.h>
|
| 5 |
+
|
| 6 |
+
namespace torch {
|
| 7 |
+
namespace distributed {
|
| 8 |
+
namespace autograd {
|
| 9 |
+
|
| 10 |
+
// Response for the RRefBackwardReq.
|
| 11 |
+
class TORCH_API RRefBackwardResp : public rpc::RpcCommandBase {
|
| 12 |
+
public:
|
| 13 |
+
RRefBackwardResp() = default;
|
| 14 |
+
c10::intrusive_ptr<rpc::Message> toMessageImpl() && override;
|
| 15 |
+
static std::unique_ptr<RRefBackwardResp> fromMessage(
|
| 16 |
+
const rpc::Message& message);
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
} // namespace autograd
|
| 20 |
+
} // namespace distributed
|
| 21 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/backend/lowering_context.h
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <memory>
|
| 4 |
+
#include <string>
|
| 5 |
+
#include <unordered_map>
|
| 6 |
+
#include <utility>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
#include <torch/csrc/lazy/backend/backend_data.h>
|
| 10 |
+
#include <torch/csrc/lazy/backend/backend_device.h>
|
| 11 |
+
#include <torch/csrc/lazy/core/ir.h>
|
| 12 |
+
#include <torch/csrc/lazy/core/ir_util.h>
|
| 13 |
+
|
| 14 |
+
namespace torch {
|
| 15 |
+
namespace lazy {
|
| 16 |
+
|
| 17 |
+
class TORCH_API Computation {
|
| 18 |
+
public:
|
| 19 |
+
virtual int parameters_size() const = 0;
|
| 20 |
+
|
| 21 |
+
virtual const std::vector<Shape>& parameter_shapes() const = 0;
|
| 22 |
+
|
| 23 |
+
virtual const std::vector<std::string>& parameter_names() const = 0;
|
| 24 |
+
|
| 25 |
+
virtual const Shape& result_shape() const = 0;
|
| 26 |
+
|
| 27 |
+
virtual const std::string to_string() const = 0;
|
| 28 |
+
|
| 29 |
+
virtual ~Computation() = default;
|
| 30 |
+
|
| 31 |
+
// Indicates whether this computation is being executed inside a mark step
|
| 32 |
+
// Assume false unless set otherwise
|
| 33 |
+
bool in_mark_step = false;
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
using ComputationPtr = std::shared_ptr<Computation>;
|
| 37 |
+
|
| 38 |
+
// Keeps track of the code generation state.
|
| 39 |
+
class TORCH_API LoweringContext {
|
| 40 |
+
public:
|
| 41 |
+
LoweringContext(const std::string& name, BackendDevice device);
|
| 42 |
+
LoweringContext(
|
| 43 |
+
const std::string& name,
|
| 44 |
+
BackendDevice device,
|
| 45 |
+
c10::ArrayRef<const torch::lazy::Node*> post_order,
|
| 46 |
+
Util::EmissionMap emit_status);
|
| 47 |
+
|
| 48 |
+
virtual ~LoweringContext() = default;
|
| 49 |
+
|
| 50 |
+
static std::unique_ptr<LoweringContext> Create(
|
| 51 |
+
const std::string& name,
|
| 52 |
+
BackendDevice device,
|
| 53 |
+
c10::ArrayRef<const torch::lazy::Node*> post_order,
|
| 54 |
+
Util::EmissionMap emit_status);
|
| 55 |
+
|
| 56 |
+
static std::unique_ptr<LoweringContext> Create(
|
| 57 |
+
const std::string& name,
|
| 58 |
+
BackendDevice device);
|
| 59 |
+
|
| 60 |
+
const BackendDevice& device() const {
|
| 61 |
+
return device_;
|
| 62 |
+
};
|
| 63 |
+
|
| 64 |
+
// Retrieves the vector holding all the tensors associated with the parameter
|
| 65 |
+
// instructions which have been created.
|
| 66 |
+
const std::vector<BackendDataPtr>& GetParametersData() const;
|
| 67 |
+
|
| 68 |
+
// Adds a new input/output alias.
|
| 69 |
+
virtual void SetUpAlias(
|
| 70 |
+
const std::vector<int64_t>& output_index,
|
| 71 |
+
int64_t param_number,
|
| 72 |
+
const std::vector<int64_t>& param_index,
|
| 73 |
+
bool must_alias = false) {
|
| 74 |
+
// Dummy default implementation to do nothing.
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
// Check if parameter shape matches result at index.
|
| 78 |
+
virtual bool CheckResultShape(
|
| 79 |
+
const BackendDataPtr& parameter_data,
|
| 80 |
+
size_t result_idx) {
|
| 81 |
+
// Dummy default implementation to do nothing.
|
| 82 |
+
return false;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
// Adds the given output as a component of the result tuple and returns its
|
| 86 |
+
// assigned position within the tuple.
|
| 87 |
+
virtual size_t AddResult(const torch::lazy::Output& output) = 0;
|
| 88 |
+
|
| 89 |
+
// Associates the given output with the input parameter of the given index and
|
| 90 |
+
// shape. Only used for the operator-by-operator execution, mostly for
|
| 91 |
+
// debugging purposes.
|
| 92 |
+
virtual void AddParameter(
|
| 93 |
+
const torch::lazy::Output& output,
|
| 94 |
+
size_t index,
|
| 95 |
+
const Shape& shape,
|
| 96 |
+
const std::string& name) = 0;
|
| 97 |
+
|
| 98 |
+
// Build the computation capturing all the operations created with the
|
| 99 |
+
// embedded builder (returned by the builder() API).
|
| 100 |
+
virtual ComputationPtr Build() = 0;
|
| 101 |
+
|
| 102 |
+
size_t GetEmittedNodeCount() const {
|
| 103 |
+
return emit_status_.size();
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
protected:
|
| 107 |
+
BackendDevice device_;
|
| 108 |
+
std::vector<BackendDataPtr> parameters_;
|
| 109 |
+
std::vector<size_t> parameter_sequence_;
|
| 110 |
+
Util::EmissionMap emit_status_;
|
| 111 |
+
};
|
| 112 |
+
|
| 113 |
+
} // namespace lazy
|
| 114 |
+
} // namespace torch
|
videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/lazy/ts_backend/ir_builder.h
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/lazy/core/internal_ops/ltc_ops.h>
|
| 4 |
+
#include <torch/csrc/lazy/core/ir.h>
|
| 5 |
+
#include <torch/csrc/lazy/core/ir_builder.h>
|
| 6 |
+
#include <torch/csrc/lazy/core/shape_inference.h>
|
| 7 |
+
#include <torch/csrc/lazy/generated/LazyNonNativeIr.h>
|
| 8 |
+
#include <torch/csrc/lazy/ts_backend/dynamic_ir.h>
|
| 9 |
+
#include <torch/csrc/lazy/ts_backend/ops/device_data.h>
|
| 10 |
+
#include <torch/csrc/lazy/ts_backend/ops/generic.h>
|
| 11 |
+
#include <torch/csrc/lazy/ts_backend/ts_node.h>
|
| 12 |
+
|
| 13 |
+
namespace torch {
|
| 14 |
+
namespace lazy {
|
| 15 |
+
|
| 16 |
+
struct TorchScriptIrBuilder : IrBuilder {
|
| 17 |
+
NodePtr MakeDeviceData(
|
| 18 |
+
const std::shared_ptr<BackendData>& data) const override {
|
| 19 |
+
return DeviceData::Create(data);
|
| 20 |
+
}
|
| 21 |
+
// TODO: Scalar node is not currently used by ts_backend. Enable reusing
|
| 22 |
+
// Scalar node later if needed.
|
| 23 |
+
NodePtr MakeScalar(const at::Scalar& value, const at::ScalarType& type)
|
| 24 |
+
const override {
|
| 25 |
+
return MakeNode<Scalar>(value, type);
|
| 26 |
+
}
|
| 27 |
+
NodePtr MakeExpand(
|
| 28 |
+
const Value& input0,
|
| 29 |
+
const std::vector<int64_t>& size,
|
| 30 |
+
const bool& is_scalar_expand) const override {
|
| 31 |
+
return ReuseOrMakeNode<Expand>(input0, size, is_scalar_expand);
|
| 32 |
+
}
|
| 33 |
+
NodePtr MakeCast(
|
| 34 |
+
const Value& input0,
|
| 35 |
+
const at::ScalarType& dtype,
|
| 36 |
+
const c10::optional<at::ScalarType>& stype =
|
| 37 |
+
c10::nullopt) const override {
|
| 38 |
+
return ReuseOrMakeNode<Cast>(input0, dtype, stype);
|
| 39 |
+
}
|
| 40 |
+
NodePtr MakeTensorList(const OpList& inputs) const override {
|
| 41 |
+
return ReuseOrMakeNode<TensorList>(inputs);
|
| 42 |
+
}
|
| 43 |
+
// Generic needs cleanup
|
| 44 |
+
NodePtr MakeGeneric(
|
| 45 |
+
const OpKind& op,
|
| 46 |
+
const OpList& operands,
|
| 47 |
+
const Shape& shape,
|
| 48 |
+
const size_t& num_outputs = 1,
|
| 49 |
+
const hash_t& hash_seed =
|
| 50 |
+
static_cast<uint32_t>(0x5a2d296e9)) const override {
|
| 51 |
+
return MakeNode<Generic>(op, operands, shape, num_outputs, hash_seed);
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
// dynamic ir nodes
|
| 55 |
+
// TODO: verify if IR node reusing works for Dynamic shape ops
|
| 56 |
+
NodePtr MakeSizeNode(const Value& input, size_t dim) const override {
|
| 57 |
+
return MakeNode<SizeNode>(input, dim);
|
| 58 |
+
}
|
| 59 |
+
NodePtr MakeSizeAdd(const Value& a, const Value& b) const override {
|
| 60 |
+
return MakeNode<SizeAdd>(a, b);
|
| 61 |
+
}
|
| 62 |
+
NodePtr MakeSizeMul(const Value& a, const Value& b) const override {
|
| 63 |
+
return MakeNode<SizeMul>(a, b);
|
| 64 |
+
}
|
| 65 |
+
NodePtr MakeSizeDiv(const Value& a, const Value& b) const override {
|
| 66 |
+
return MakeNode<SizeDiv>(a, b);
|
| 67 |
+
}
|
| 68 |
+
};
|
| 69 |
+
|
| 70 |
+
} // namespace lazy
|
| 71 |
+
} // namespace torch
|
vllm/lib/python3.10/site-packages/sympy/benchmarks/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/sympy/benchmarks/__pycache__/bench_meijerint.cpython-310.pyc
ADDED
|
Binary file (10.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/benchmarks/bench_discrete_log.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from time import time
|
| 3 |
+
from sympy.ntheory.residue_ntheory import (discrete_log,
|
| 4 |
+
_discrete_log_trial_mul, _discrete_log_shanks_steps,
|
| 5 |
+
_discrete_log_pollard_rho, _discrete_log_pohlig_hellman)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# Cyclic group (Z/pZ)* with p prime, order p - 1 and generator g
|
| 9 |
+
data_set_1 = [
|
| 10 |
+
# p, p - 1, g
|
| 11 |
+
[191, 190, 19],
|
| 12 |
+
[46639, 46638, 6],
|
| 13 |
+
[14789363, 14789362, 2],
|
| 14 |
+
[4254225211, 4254225210, 2],
|
| 15 |
+
[432751500361, 432751500360, 7],
|
| 16 |
+
[158505390797053, 158505390797052, 2],
|
| 17 |
+
[6575202655312007, 6575202655312006, 5],
|
| 18 |
+
[8430573471995353769, 8430573471995353768, 3],
|
| 19 |
+
[3938471339744997827267, 3938471339744997827266, 2],
|
| 20 |
+
[875260951364705563393093, 875260951364705563393092, 5],
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# Cyclic sub-groups of (Z/nZ)* with prime order p and generator g
|
| 25 |
+
# (n, p are primes and n = 2 * p + 1)
|
| 26 |
+
data_set_2 = [
|
| 27 |
+
# n, p, g
|
| 28 |
+
[227, 113, 3],
|
| 29 |
+
[2447, 1223, 2],
|
| 30 |
+
[24527, 12263, 2],
|
| 31 |
+
[245639, 122819, 2],
|
| 32 |
+
[2456747, 1228373, 3],
|
| 33 |
+
[24567899, 12283949, 3],
|
| 34 |
+
[245679023, 122839511, 2],
|
| 35 |
+
[2456791307, 1228395653, 3],
|
| 36 |
+
[24567913439, 12283956719, 2],
|
| 37 |
+
[245679135407, 122839567703, 2],
|
| 38 |
+
[2456791354763, 1228395677381, 3],
|
| 39 |
+
[24567913550903, 12283956775451, 2],
|
| 40 |
+
[245679135509519, 122839567754759, 2],
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Cyclic sub-groups of (Z/nZ)* with smooth order o and generator g
|
| 45 |
+
data_set_3 = [
|
| 46 |
+
# n, o, g
|
| 47 |
+
[2**118, 2**116, 3],
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def bench_discrete_log(data_set, algo=None):
|
| 52 |
+
if algo is None:
|
| 53 |
+
f = discrete_log
|
| 54 |
+
elif algo == 'trial':
|
| 55 |
+
f = _discrete_log_trial_mul
|
| 56 |
+
elif algo == 'shanks':
|
| 57 |
+
f = _discrete_log_shanks_steps
|
| 58 |
+
elif algo == 'rho':
|
| 59 |
+
f = _discrete_log_pollard_rho
|
| 60 |
+
elif algo == 'ph':
|
| 61 |
+
f = _discrete_log_pohlig_hellman
|
| 62 |
+
else:
|
| 63 |
+
raise ValueError("Argument 'algo' should be one"
|
| 64 |
+
" of ('trial', 'shanks', 'rho' or 'ph')")
|
| 65 |
+
|
| 66 |
+
for i, data in enumerate(data_set):
|
| 67 |
+
for j, (n, p, g) in enumerate(data):
|
| 68 |
+
t = time()
|
| 69 |
+
l = f(n, pow(g, p - 1, n), g, p)
|
| 70 |
+
t = time() - t
|
| 71 |
+
print('[%02d-%03d] %15.10f' % (i, j, t))
|
| 72 |
+
assert l == p - 1
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == '__main__':
|
| 76 |
+
algo = sys.argv[1] \
|
| 77 |
+
if len(sys.argv) > 1 else None
|
| 78 |
+
data_set = [
|
| 79 |
+
data_set_1,
|
| 80 |
+
data_set_2,
|
| 81 |
+
data_set_3,
|
| 82 |
+
]
|
| 83 |
+
bench_discrete_log(data_set, algo)
|
vllm/lib/python3.10/site-packages/sympy/benchmarks/bench_meijerint.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# conceal the implicit import from the code quality tester
|
| 2 |
+
from sympy.core.numbers import (oo, pi)
|
| 3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 4 |
+
from sympy.functions.elementary.exponential import exp
|
| 5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 6 |
+
from sympy.functions.special.bessel import besseli
|
| 7 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 8 |
+
from sympy.integrals.integrals import integrate
|
| 9 |
+
from sympy.integrals.transforms import (mellin_transform,
|
| 10 |
+
inverse_fourier_transform, inverse_mellin_transform,
|
| 11 |
+
laplace_transform, inverse_laplace_transform, fourier_transform)
|
| 12 |
+
|
| 13 |
+
LT = laplace_transform
|
| 14 |
+
FT = fourier_transform
|
| 15 |
+
MT = mellin_transform
|
| 16 |
+
IFT = inverse_fourier_transform
|
| 17 |
+
ILT = inverse_laplace_transform
|
| 18 |
+
IMT = inverse_mellin_transform
|
| 19 |
+
|
| 20 |
+
from sympy.abc import x, y
|
| 21 |
+
nu, beta, rho = symbols('nu beta rho')
|
| 22 |
+
|
| 23 |
+
apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True)
|
| 24 |
+
k = Symbol('k', real=True)
|
| 25 |
+
negk = Symbol('k', negative=True)
|
| 26 |
+
|
| 27 |
+
mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True)
|
| 28 |
+
sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True,
|
| 29 |
+
finite=True, positive=True)
|
| 30 |
+
rate = Symbol('lambda', positive=True)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def normal(x, mu, sigma):
|
| 34 |
+
return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def exponential(x, rate):
|
| 38 |
+
return rate*exp(-rate*x)
|
| 39 |
+
alpha, beta = symbols('alpha beta', positive=True)
|
| 40 |
+
betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \
|
| 41 |
+
/gamma(alpha)/gamma(beta)
|
| 42 |
+
kint = Symbol('k', integer=True, positive=True)
|
| 43 |
+
chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2)
|
| 44 |
+
chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2)
|
| 45 |
+
dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1)
|
| 46 |
+
d1, d2 = symbols('d1 d2', positive=True)
|
| 47 |
+
f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \
|
| 48 |
+
/gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2)
|
| 49 |
+
nupos, sigmapos = symbols('nu sigma', positive=True)
|
| 50 |
+
rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x*
|
| 51 |
+
nupos/sigmapos**2)
|
| 52 |
+
mu = Symbol('mu', real=True)
|
| 53 |
+
laplace = exp(-abs(x - mu)/bpos)/2/bpos
|
| 54 |
+
|
| 55 |
+
u = Symbol('u', polar=True)
|
| 56 |
+
tpos = Symbol('t', positive=True)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def E(expr):
|
| 60 |
+
integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
|
| 61 |
+
(x, 0, oo), (y, -oo, oo), meijerg=True)
|
| 62 |
+
integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1),
|
| 63 |
+
(y, -oo, oo), (x, 0, oo), meijerg=True)
|
| 64 |
+
|
| 65 |
+
bench = [
|
| 66 |
+
'MT(x**nu*Heaviside(x - 1), x, s)',
|
| 67 |
+
'MT(x**nu*Heaviside(1 - x), x, s)',
|
| 68 |
+
'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)',
|
| 69 |
+
'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)',
|
| 70 |
+
'MT((1+x)**(-rho), x, s)',
|
| 71 |
+
'MT(abs(1-x)**(-rho), x, s)',
|
| 72 |
+
'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)',
|
| 73 |
+
'MT((x**a-b**a)/(x-b), x, s)',
|
| 74 |
+
'MT((x**a-bpos**a)/(x-bpos), x, s)',
|
| 75 |
+
'MT(exp(-x), x, s)',
|
| 76 |
+
'MT(exp(-1/x), x, s)',
|
| 77 |
+
'MT(log(x)**4*Heaviside(1-x), x, s)',
|
| 78 |
+
'MT(log(x)**3*Heaviside(x-1), x, s)',
|
| 79 |
+
'MT(log(x + 1), x, s)',
|
| 80 |
+
'MT(log(1/x + 1), x, s)',
|
| 81 |
+
'MT(log(abs(1 - x)), x, s)',
|
| 82 |
+
'MT(log(abs(1 - 1/x)), x, s)',
|
| 83 |
+
'MT(log(x)/(x+1), x, s)',
|
| 84 |
+
'MT(log(x)**2/(x+1), x, s)',
|
| 85 |
+
'MT(log(x)/(x+1)**2, x, s)',
|
| 86 |
+
'MT(erf(sqrt(x)), x, s)',
|
| 87 |
+
|
| 88 |
+
'MT(besselj(a, 2*sqrt(x)), x, s)',
|
| 89 |
+
'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)',
|
| 90 |
+
'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)',
|
| 91 |
+
'MT(besselj(a, sqrt(x))**2, x, s)',
|
| 92 |
+
'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)',
|
| 93 |
+
'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)',
|
| 94 |
+
'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)',
|
| 95 |
+
'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)',
|
| 96 |
+
'MT(bessely(a, 2*sqrt(x)), x, s)',
|
| 97 |
+
'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)',
|
| 98 |
+
'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)',
|
| 99 |
+
'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)',
|
| 100 |
+
'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)',
|
| 101 |
+
'MT(bessely(a, sqrt(x))**2, x, s)',
|
| 102 |
+
|
| 103 |
+
'MT(besselk(a, 2*sqrt(x)), x, s)',
|
| 104 |
+
'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)',
|
| 105 |
+
'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)',
|
| 106 |
+
'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)',
|
| 107 |
+
'MT(exp(-x/2)*besselk(a, x/2), x, s)',
|
| 108 |
+
|
| 109 |
+
# later: ILT, IMT
|
| 110 |
+
|
| 111 |
+
'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)',
|
| 112 |
+
'LT(t**apos, t, s)',
|
| 113 |
+
'LT(Heaviside(t), t, s)',
|
| 114 |
+
'LT(Heaviside(t - apos), t, s)',
|
| 115 |
+
'LT(1 - exp(-apos*t), t, s)',
|
| 116 |
+
'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)',
|
| 117 |
+
'LT(exp(t), t, s)',
|
| 118 |
+
'LT(exp(2*t), t, s)',
|
| 119 |
+
'LT(exp(apos*t), t, s)',
|
| 120 |
+
'LT(log(t/apos), t, s)',
|
| 121 |
+
'LT(erf(t), t, s)',
|
| 122 |
+
'LT(sin(apos*t), t, s)',
|
| 123 |
+
'LT(cos(apos*t), t, s)',
|
| 124 |
+
'LT(exp(-apos*t)*sin(bpos*t), t, s)',
|
| 125 |
+
'LT(exp(-apos*t)*cos(bpos*t), t, s)',
|
| 126 |
+
'LT(besselj(0, t), t, s, noconds=True)',
|
| 127 |
+
'LT(besselj(1, t), t, s, noconds=True)',
|
| 128 |
+
|
| 129 |
+
'FT(Heaviside(1 - abs(2*apos*x)), x, k)',
|
| 130 |
+
'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)',
|
| 131 |
+
'FT(exp(-apos*x)*Heaviside(x), x, k)',
|
| 132 |
+
'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)',
|
| 133 |
+
'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)',
|
| 134 |
+
'IFT(1/(apos + 2*pi*I*x), x, negk)',
|
| 135 |
+
'FT(x*exp(-apos*x)*Heaviside(x), x, k)',
|
| 136 |
+
'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)',
|
| 137 |
+
'FT(exp(-apos*x**2), x, k)',
|
| 138 |
+
'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)',
|
| 139 |
+
'FT(exp(-apos*abs(x)), x, k)',
|
| 140 |
+
|
| 141 |
+
'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
|
| 142 |
+
'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
|
| 143 |
+
'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
|
| 144 |
+
'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)',
|
| 145 |
+
'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
| 146 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
| 147 |
+
'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
| 148 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
| 149 |
+
'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
| 150 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
| 151 |
+
'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
| 152 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
| 153 |
+
'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
| 154 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
| 155 |
+
'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
| 156 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
| 157 |
+
'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
| 158 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
| 159 |
+
'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),'
|
| 160 |
+
' (x, -oo, oo), (y, -oo, oo), meijerg=True)',
|
| 161 |
+
'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)',
|
| 162 |
+
'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)',
|
| 163 |
+
'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)',
|
| 164 |
+
'E(1)',
|
| 165 |
+
'E(x*y)',
|
| 166 |
+
'E(x*y**2)',
|
| 167 |
+
'E((x+y+1)**2)',
|
| 168 |
+
'E(x+y+1)',
|
| 169 |
+
'E((x+y-1)**2)',
|
| 170 |
+
'integrate(betadist, (x, 0, oo), meijerg=True)',
|
| 171 |
+
'integrate(x*betadist, (x, 0, oo), meijerg=True)',
|
| 172 |
+
'integrate(x**2*betadist, (x, 0, oo), meijerg=True)',
|
| 173 |
+
'integrate(chi, (x, 0, oo), meijerg=True)',
|
| 174 |
+
'integrate(x*chi, (x, 0, oo), meijerg=True)',
|
| 175 |
+
'integrate(x**2*chi, (x, 0, oo), meijerg=True)',
|
| 176 |
+
'integrate(chisquared, (x, 0, oo), meijerg=True)',
|
| 177 |
+
'integrate(x*chisquared, (x, 0, oo), meijerg=True)',
|
| 178 |
+
'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)',
|
| 179 |
+
'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)',
|
| 180 |
+
'integrate(dagum, (x, 0, oo), meijerg=True)',
|
| 181 |
+
'integrate(x*dagum, (x, 0, oo), meijerg=True)',
|
| 182 |
+
'integrate(x**2*dagum, (x, 0, oo), meijerg=True)',
|
| 183 |
+
'integrate(f, (x, 0, oo), meijerg=True)',
|
| 184 |
+
'integrate(x*f, (x, 0, oo), meijerg=True)',
|
| 185 |
+
'integrate(x**2*f, (x, 0, oo), meijerg=True)',
|
| 186 |
+
'integrate(rice, (x, 0, oo), meijerg=True)',
|
| 187 |
+
'integrate(laplace, (x, -oo, oo), meijerg=True)',
|
| 188 |
+
'integrate(x*laplace, (x, -oo, oo), meijerg=True)',
|
| 189 |
+
'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)',
|
| 190 |
+
'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))',
|
| 191 |
+
|
| 192 |
+
'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)',
|
| 193 |
+
'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
|
| 194 |
+
'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)',
|
| 195 |
+
'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)',
|
| 196 |
+
'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)',
|
| 197 |
+
|
| 198 |
+
'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))',
|
| 199 |
+
"gammasimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))",
|
| 200 |
+
|
| 201 |
+
'mellin_transform(E1(x), x, s)',
|
| 202 |
+
'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))',
|
| 203 |
+
'mellin_transform(expint(a, x), x, s)',
|
| 204 |
+
'mellin_transform(Si(x), x, s)',
|
| 205 |
+
'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))',
|
| 206 |
+
'mellin_transform(Ci(sqrt(x)), x, s)',
|
| 207 |
+
'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))',
|
| 208 |
+
'laplace_transform(Ci(x), x, s)',
|
| 209 |
+
'laplace_transform(expint(a, x), x, s)',
|
| 210 |
+
'laplace_transform(expint(1, x), x, s)',
|
| 211 |
+
'laplace_transform(expint(2, x), x, s)',
|
| 212 |
+
'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)',
|
| 213 |
+
'inverse_laplace_transform(log(s + 1)/s, s, x)',
|
| 214 |
+
'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)',
|
| 215 |
+
'laplace_transform(Chi(x), x, s)',
|
| 216 |
+
'laplace_transform(Shi(x), x, s)',
|
| 217 |
+
|
| 218 |
+
'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")',
|
| 219 |
+
'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")',
|
| 220 |
+
'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")',
|
| 221 |
+
'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)',
|
| 222 |
+
'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)',
|
| 223 |
+
'integrate(sin(x)/x, (x, 0, z), meijerg=True)',
|
| 224 |
+
'integrate(sinh(x)/x, (x, 0, z), meijerg=True)',
|
| 225 |
+
'integrate(exp(-x)/x, x, meijerg=True)',
|
| 226 |
+
'integrate(exp(-x)/x**2, x, meijerg=True)',
|
| 227 |
+
'integrate(cos(u)/u, u, meijerg=True)',
|
| 228 |
+
'integrate(cosh(u)/u, u, meijerg=True)',
|
| 229 |
+
'integrate(expint(1, x), x, meijerg=True)',
|
| 230 |
+
'integrate(expint(2, x), x, meijerg=True)',
|
| 231 |
+
'integrate(Si(x), x, meijerg=True)',
|
| 232 |
+
'integrate(Ci(u), u, meijerg=True)',
|
| 233 |
+
'integrate(Shi(x), x, meijerg=True)',
|
| 234 |
+
'integrate(Chi(u), u, meijerg=True)',
|
| 235 |
+
'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)',
|
| 236 |
+
'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)'
|
| 237 |
+
]
|
| 238 |
+
|
| 239 |
+
from time import time
|
| 240 |
+
from sympy.core.cache import clear_cache
|
| 241 |
+
import sys
|
| 242 |
+
|
| 243 |
+
timings = []
|
| 244 |
+
|
| 245 |
+
if __name__ == '__main__':
|
| 246 |
+
for n, string in enumerate(bench):
|
| 247 |
+
clear_cache()
|
| 248 |
+
_t = time()
|
| 249 |
+
exec(string)
|
| 250 |
+
_t = time() - _t
|
| 251 |
+
timings += [(_t, string)]
|
| 252 |
+
sys.stdout.write('.')
|
| 253 |
+
sys.stdout.flush()
|
| 254 |
+
if n % (len(bench) // 10) == 0:
|
| 255 |
+
sys.stdout.write('%s' % (10*n // len(bench)))
|
| 256 |
+
print()
|
| 257 |
+
|
| 258 |
+
timings.sort(key=lambda x: -x[0])
|
| 259 |
+
|
| 260 |
+
for ti, string in timings:
|
| 261 |
+
print('%.2fs %s' % (ti, string))
|
vllm/lib/python3.10/site-packages/sympy/benchmarks/bench_symbench.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
from sympy.core.random import random
|
| 3 |
+
from sympy.core.numbers import (I, Integer, pi)
|
| 4 |
+
from sympy.core.symbol import Symbol
|
| 5 |
+
from sympy.core.sympify import sympify
|
| 6 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 7 |
+
from sympy.functions.elementary.trigonometric import sin
|
| 8 |
+
from sympy.polys.polytools import factor
|
| 9 |
+
from sympy.simplify.simplify import simplify
|
| 10 |
+
from sympy.abc import x, y, z
|
| 11 |
+
from timeit import default_timer as clock
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def bench_R1():
|
| 15 |
+
"real(f(f(f(f(f(f(f(f(f(f(i/2)))))))))))"
|
| 16 |
+
def f(z):
|
| 17 |
+
return sqrt(Integer(1)/3)*z**2 + I/3
|
| 18 |
+
f(f(f(f(f(f(f(f(f(f(I/2)))))))))).as_real_imag()[0]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def bench_R2():
|
| 22 |
+
"Hermite polynomial hermite(15, y)"
|
| 23 |
+
def hermite(n, y):
|
| 24 |
+
if n == 1:
|
| 25 |
+
return 2*y
|
| 26 |
+
if n == 0:
|
| 27 |
+
return 1
|
| 28 |
+
return (2*y*hermite(n - 1, y) - 2*(n - 1)*hermite(n - 2, y)).expand()
|
| 29 |
+
|
| 30 |
+
hermite(15, y)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def bench_R3():
|
| 34 |
+
"a = [bool(f==f) for _ in range(10)]"
|
| 35 |
+
f = x + y + z
|
| 36 |
+
[bool(f == f) for _ in range(10)]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def bench_R4():
|
| 40 |
+
# we don't have Tuples
|
| 41 |
+
pass
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def bench_R5():
|
| 45 |
+
"blowup(L, 8); L=uniq(L)"
|
| 46 |
+
def blowup(L, n):
|
| 47 |
+
for i in range(n):
|
| 48 |
+
L.append( (L[i] + L[i + 1]) * L[i + 2] )
|
| 49 |
+
|
| 50 |
+
def uniq(x):
|
| 51 |
+
v = set(x)
|
| 52 |
+
return v
|
| 53 |
+
L = [x, y, z]
|
| 54 |
+
blowup(L, 8)
|
| 55 |
+
L = uniq(L)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def bench_R6():
|
| 59 |
+
"sum(simplify((x+sin(i))/x+(x-sin(i))/x) for i in range(100))"
|
| 60 |
+
sum(simplify((x + sin(i))/x + (x - sin(i))/x) for i in range(100))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def bench_R7():
|
| 64 |
+
"[f.subs(x, random()) for _ in range(10**4)]"
|
| 65 |
+
f = x**24 + 34*x**12 + 45*x**3 + 9*x**18 + 34*x**10 + 32*x**21
|
| 66 |
+
[f.subs(x, random()) for _ in range(10**4)]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def bench_R8():
|
| 70 |
+
"right(x^2,0,5,10^4)"
|
| 71 |
+
def right(f, a, b, n):
|
| 72 |
+
a = sympify(a)
|
| 73 |
+
b = sympify(b)
|
| 74 |
+
n = sympify(n)
|
| 75 |
+
x = f.atoms(Symbol).pop()
|
| 76 |
+
Deltax = (b - a)/n
|
| 77 |
+
c = a
|
| 78 |
+
est = 0
|
| 79 |
+
for i in range(n):
|
| 80 |
+
c += Deltax
|
| 81 |
+
est += f.subs(x, c)
|
| 82 |
+
return est*Deltax
|
| 83 |
+
|
| 84 |
+
right(x**2, 0, 5, 10**4)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _bench_R9():
|
| 88 |
+
"factor(x^20 - pi^5*y^20)"
|
| 89 |
+
factor(x**20 - pi**5*y**20)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def bench_R10():
|
| 93 |
+
"v = [-pi,-pi+1/10..,pi]"
|
| 94 |
+
def srange(min, max, step):
|
| 95 |
+
v = [min]
|
| 96 |
+
while (max - v[-1]).evalf() > 0:
|
| 97 |
+
v.append(v[-1] + step)
|
| 98 |
+
return v[:-1]
|
| 99 |
+
srange(-pi, pi, sympify(1)/10)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def bench_R11():
|
| 103 |
+
"a = [random() + random()*I for w in [0..1000]]"
|
| 104 |
+
[random() + random()*I for w in range(1000)]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def bench_S1():
|
| 108 |
+
"e=(x+y+z+1)**7;f=e*(e+1);f.expand()"
|
| 109 |
+
e = (x + y + z + 1)**7
|
| 110 |
+
f = e*(e + 1)
|
| 111 |
+
f.expand()
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == '__main__':
|
| 115 |
+
benchmarks = [
|
| 116 |
+
bench_R1,
|
| 117 |
+
bench_R2,
|
| 118 |
+
bench_R3,
|
| 119 |
+
bench_R5,
|
| 120 |
+
bench_R6,
|
| 121 |
+
bench_R7,
|
| 122 |
+
bench_R8,
|
| 123 |
+
#_bench_R9,
|
| 124 |
+
bench_R10,
|
| 125 |
+
bench_R11,
|
| 126 |
+
#bench_S1,
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
report = []
|
| 130 |
+
for b in benchmarks:
|
| 131 |
+
t = clock()
|
| 132 |
+
b()
|
| 133 |
+
t = clock() - t
|
| 134 |
+
print("%s%65s: %f" % (b.__name__, b.__doc__, t))
|
vllm/lib/python3.10/site-packages/sympy/crypto/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.crypto.crypto import (cycle_list,
|
| 2 |
+
encipher_shift, encipher_affine, encipher_substitution,
|
| 3 |
+
check_and_join, encipher_vigenere, decipher_vigenere, bifid5_square,
|
| 4 |
+
bifid6_square, encipher_hill, decipher_hill,
|
| 5 |
+
encipher_bifid5, encipher_bifid6, decipher_bifid5,
|
| 6 |
+
decipher_bifid6, encipher_kid_rsa, decipher_kid_rsa,
|
| 7 |
+
kid_rsa_private_key, kid_rsa_public_key, decipher_rsa, rsa_private_key,
|
| 8 |
+
rsa_public_key, encipher_rsa, lfsr_connection_polynomial,
|
| 9 |
+
lfsr_autocorrelation, lfsr_sequence, encode_morse, decode_morse,
|
| 10 |
+
elgamal_private_key, elgamal_public_key, decipher_elgamal,
|
| 11 |
+
encipher_elgamal, dh_private_key, dh_public_key, dh_shared_key,
|
| 12 |
+
padded_key, encipher_bifid, decipher_bifid, bifid_square, bifid5,
|
| 13 |
+
bifid6, bifid10, decipher_gm, encipher_gm, gm_public_key,
|
| 14 |
+
gm_private_key, bg_private_key, bg_public_key, encipher_bg, decipher_bg,
|
| 15 |
+
encipher_rot13, decipher_rot13, encipher_atbash, decipher_atbash,
|
| 16 |
+
encipher_railfence, decipher_railfence)
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
'cycle_list', 'encipher_shift', 'encipher_affine',
|
| 20 |
+
'encipher_substitution', 'check_and_join', 'encipher_vigenere',
|
| 21 |
+
'decipher_vigenere', 'bifid5_square', 'bifid6_square', 'encipher_hill',
|
| 22 |
+
'decipher_hill', 'encipher_bifid5', 'encipher_bifid6', 'decipher_bifid5',
|
| 23 |
+
'decipher_bifid6', 'encipher_kid_rsa', 'decipher_kid_rsa',
|
| 24 |
+
'kid_rsa_private_key', 'kid_rsa_public_key', 'decipher_rsa',
|
| 25 |
+
'rsa_private_key', 'rsa_public_key', 'encipher_rsa',
|
| 26 |
+
'lfsr_connection_polynomial', 'lfsr_autocorrelation', 'lfsr_sequence',
|
| 27 |
+
'encode_morse', 'decode_morse', 'elgamal_private_key',
|
| 28 |
+
'elgamal_public_key', 'decipher_elgamal', 'encipher_elgamal',
|
| 29 |
+
'dh_private_key', 'dh_public_key', 'dh_shared_key', 'padded_key',
|
| 30 |
+
'encipher_bifid', 'decipher_bifid', 'bifid_square', 'bifid5', 'bifid6',
|
| 31 |
+
'bifid10', 'decipher_gm', 'encipher_gm', 'gm_public_key',
|
| 32 |
+
'gm_private_key', 'bg_private_key', 'bg_public_key', 'encipher_bg',
|
| 33 |
+
'decipher_bg', 'encipher_rot13', 'decipher_rot13', 'encipher_atbash',
|
| 34 |
+
'decipher_atbash', 'encipher_railfence', 'decipher_railfence',
|
| 35 |
+
]
|
vllm/lib/python3.10/site-packages/sympy/crypto/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.63 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/crypto/__pycache__/crypto.cpython-310.pyc
ADDED
|
Binary file (94.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/crypto/crypto.py
ADDED
|
@@ -0,0 +1,3367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This file contains some classical ciphers and routines
|
| 3 |
+
implementing a linear-feedback shift register (LFSR)
|
| 4 |
+
and the Diffie-Hellman key exchange.
|
| 5 |
+
|
| 6 |
+
.. warning::
|
| 7 |
+
|
| 8 |
+
This module is intended for educational purposes only. Do not use the
|
| 9 |
+
functions in this module for real cryptographic applications. If you wish
|
| 10 |
+
to encrypt real data, we recommend using something like the `cryptography
|
| 11 |
+
<https://cryptography.io/en/latest/>`_ module.
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from string import whitespace, ascii_uppercase as uppercase, printable
|
| 16 |
+
from functools import reduce
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from itertools import cycle
|
| 20 |
+
|
| 21 |
+
from sympy.external.gmpy import GROUND_TYPES
|
| 22 |
+
from sympy.core import Symbol
|
| 23 |
+
from sympy.core.numbers import Rational
|
| 24 |
+
from sympy.core.random import _randrange, _randint
|
| 25 |
+
from sympy.external.gmpy import gcd, invert
|
| 26 |
+
from sympy.functions.combinatorial.numbers import (totient as _euler,
|
| 27 |
+
reduced_totient as _carmichael)
|
| 28 |
+
from sympy.matrices import Matrix
|
| 29 |
+
from sympy.ntheory import isprime, primitive_root, factorint
|
| 30 |
+
from sympy.ntheory.generate import nextprime
|
| 31 |
+
from sympy.ntheory.modular import crt
|
| 32 |
+
from sympy.polys.domains import FF
|
| 33 |
+
from sympy.polys.polytools import Poly
|
| 34 |
+
from sympy.utilities.misc import as_int, filldedent, translate
|
| 35 |
+
from sympy.utilities.iterables import uniq, multiset
|
| 36 |
+
from sympy.utilities.decorator import doctest_depends_on
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if GROUND_TYPES == 'flint':
|
| 40 |
+
__doctest_skip__ = ['lfsr_sequence']
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class NonInvertibleCipherWarning(RuntimeWarning):
|
| 44 |
+
"""A warning raised if the cipher is not invertible."""
|
| 45 |
+
def __init__(self, msg):
|
| 46 |
+
self.fullMessage = msg
|
| 47 |
+
|
| 48 |
+
def __str__(self):
|
| 49 |
+
return '\n\t' + self.fullMessage
|
| 50 |
+
|
| 51 |
+
def warn(self, stacklevel=3):
|
| 52 |
+
warnings.warn(self, stacklevel=stacklevel)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def AZ(s=None):
|
| 56 |
+
"""Return the letters of ``s`` in uppercase. In case more than
|
| 57 |
+
one string is passed, each of them will be processed and a list
|
| 58 |
+
of upper case strings will be returned.
|
| 59 |
+
|
| 60 |
+
Examples
|
| 61 |
+
========
|
| 62 |
+
|
| 63 |
+
>>> from sympy.crypto.crypto import AZ
|
| 64 |
+
>>> AZ('Hello, world!')
|
| 65 |
+
'HELLOWORLD'
|
| 66 |
+
>>> AZ('Hello, world!'.split())
|
| 67 |
+
['HELLO', 'WORLD']
|
| 68 |
+
|
| 69 |
+
See Also
|
| 70 |
+
========
|
| 71 |
+
|
| 72 |
+
check_and_join
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
if not s:
|
| 76 |
+
return uppercase
|
| 77 |
+
t = isinstance(s, str)
|
| 78 |
+
if t:
|
| 79 |
+
s = [s]
|
| 80 |
+
rv = [check_and_join(i.upper().split(), uppercase, filter=True)
|
| 81 |
+
for i in s]
|
| 82 |
+
if t:
|
| 83 |
+
return rv[0]
|
| 84 |
+
return rv
|
| 85 |
+
|
| 86 |
+
bifid5 = AZ().replace('J', '')
|
| 87 |
+
bifid6 = AZ() + '0123456789'
|
| 88 |
+
bifid10 = printable
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def padded_key(key, symbols):
|
| 92 |
+
"""Return a string of the distinct characters of ``symbols`` with
|
| 93 |
+
those of ``key`` appearing first. A ValueError is raised if
|
| 94 |
+
a) there are duplicate characters in ``symbols`` or
|
| 95 |
+
b) there are characters in ``key`` that are not in ``symbols``.
|
| 96 |
+
|
| 97 |
+
Examples
|
| 98 |
+
========
|
| 99 |
+
|
| 100 |
+
>>> from sympy.crypto.crypto import padded_key
|
| 101 |
+
>>> padded_key('PUPPY', 'OPQRSTUVWXY')
|
| 102 |
+
'PUYOQRSTVWX'
|
| 103 |
+
>>> padded_key('RSA', 'ARTIST')
|
| 104 |
+
Traceback (most recent call last):
|
| 105 |
+
...
|
| 106 |
+
ValueError: duplicate characters in symbols: T
|
| 107 |
+
|
| 108 |
+
"""
|
| 109 |
+
syms = list(uniq(symbols))
|
| 110 |
+
if len(syms) != len(symbols):
|
| 111 |
+
extra = ''.join(sorted({
|
| 112 |
+
i for i in symbols if symbols.count(i) > 1}))
|
| 113 |
+
raise ValueError('duplicate characters in symbols: %s' % extra)
|
| 114 |
+
extra = set(key) - set(syms)
|
| 115 |
+
if extra:
|
| 116 |
+
raise ValueError(
|
| 117 |
+
'characters in key but not symbols: %s' % ''.join(
|
| 118 |
+
sorted(extra)))
|
| 119 |
+
key0 = ''.join(list(uniq(key)))
|
| 120 |
+
# remove from syms characters in key0
|
| 121 |
+
return key0 + translate(''.join(syms), None, key0)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def check_and_join(phrase, symbols=None, filter=None):
|
| 125 |
+
"""
|
| 126 |
+
Joins characters of ``phrase`` and if ``symbols`` is given, raises
|
| 127 |
+
an error if any character in ``phrase`` is not in ``symbols``.
|
| 128 |
+
|
| 129 |
+
Parameters
|
| 130 |
+
==========
|
| 131 |
+
|
| 132 |
+
phrase
|
| 133 |
+
String or list of strings to be returned as a string.
|
| 134 |
+
|
| 135 |
+
symbols
|
| 136 |
+
Iterable of characters allowed in ``phrase``.
|
| 137 |
+
|
| 138 |
+
If ``symbols`` is ``None``, no checking is performed.
|
| 139 |
+
|
| 140 |
+
Examples
|
| 141 |
+
========
|
| 142 |
+
|
| 143 |
+
>>> from sympy.crypto.crypto import check_and_join
|
| 144 |
+
>>> check_and_join('a phrase')
|
| 145 |
+
'a phrase'
|
| 146 |
+
>>> check_and_join('a phrase'.upper().split())
|
| 147 |
+
'APHRASE'
|
| 148 |
+
>>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True)
|
| 149 |
+
'ARAE'
|
| 150 |
+
>>> check_and_join('a phrase!'.upper().split(), 'ARE')
|
| 151 |
+
Traceback (most recent call last):
|
| 152 |
+
...
|
| 153 |
+
ValueError: characters in phrase but not symbols: "!HPS"
|
| 154 |
+
|
| 155 |
+
"""
|
| 156 |
+
rv = ''.join(''.join(phrase))
|
| 157 |
+
if symbols is not None:
|
| 158 |
+
symbols = check_and_join(symbols)
|
| 159 |
+
missing = ''.join(sorted(set(rv) - set(symbols)))
|
| 160 |
+
if missing:
|
| 161 |
+
if not filter:
|
| 162 |
+
raise ValueError(
|
| 163 |
+
'characters in phrase but not symbols: "%s"' % missing)
|
| 164 |
+
rv = translate(rv, None, missing)
|
| 165 |
+
return rv
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _prep(msg, key, alp, default=None):
|
| 169 |
+
if not alp:
|
| 170 |
+
if not default:
|
| 171 |
+
alp = AZ()
|
| 172 |
+
msg = AZ(msg)
|
| 173 |
+
key = AZ(key)
|
| 174 |
+
else:
|
| 175 |
+
alp = default
|
| 176 |
+
else:
|
| 177 |
+
alp = ''.join(alp)
|
| 178 |
+
key = check_and_join(key, alp, filter=True)
|
| 179 |
+
msg = check_and_join(msg, alp, filter=True)
|
| 180 |
+
return msg, key, alp
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def cycle_list(k, n):
|
| 184 |
+
"""
|
| 185 |
+
Returns the elements of the list ``range(n)`` shifted to the
|
| 186 |
+
left by ``k`` (so the list starts with ``k`` (mod ``n``)).
|
| 187 |
+
|
| 188 |
+
Examples
|
| 189 |
+
========
|
| 190 |
+
|
| 191 |
+
>>> from sympy.crypto.crypto import cycle_list
|
| 192 |
+
>>> cycle_list(3, 10)
|
| 193 |
+
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
|
| 194 |
+
|
| 195 |
+
"""
|
| 196 |
+
k = k % n
|
| 197 |
+
return list(range(k, n)) + list(range(k))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
######## shift cipher examples ############
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def encipher_shift(msg, key, symbols=None):
|
| 204 |
+
"""
|
| 205 |
+
Performs shift cipher encryption on plaintext msg, and returns the
|
| 206 |
+
ciphertext.
|
| 207 |
+
|
| 208 |
+
Parameters
|
| 209 |
+
==========
|
| 210 |
+
|
| 211 |
+
key : int
|
| 212 |
+
The secret key.
|
| 213 |
+
|
| 214 |
+
msg : str
|
| 215 |
+
Plaintext of upper-case letters.
|
| 216 |
+
|
| 217 |
+
Returns
|
| 218 |
+
=======
|
| 219 |
+
|
| 220 |
+
str
|
| 221 |
+
Ciphertext of upper-case letters.
|
| 222 |
+
|
| 223 |
+
Examples
|
| 224 |
+
========
|
| 225 |
+
|
| 226 |
+
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift
|
| 227 |
+
>>> msg = "GONAVYBEATARMY"
|
| 228 |
+
>>> ct = encipher_shift(msg, 1); ct
|
| 229 |
+
'HPOBWZCFBUBSNZ'
|
| 230 |
+
|
| 231 |
+
To decipher the shifted text, change the sign of the key:
|
| 232 |
+
|
| 233 |
+
>>> encipher_shift(ct, -1)
|
| 234 |
+
'GONAVYBEATARMY'
|
| 235 |
+
|
| 236 |
+
There is also a convenience function that does this with the
|
| 237 |
+
original key:
|
| 238 |
+
|
| 239 |
+
>>> decipher_shift(ct, 1)
|
| 240 |
+
'GONAVYBEATARMY'
|
| 241 |
+
|
| 242 |
+
Notes
|
| 243 |
+
=====
|
| 244 |
+
|
| 245 |
+
ALGORITHM:
|
| 246 |
+
|
| 247 |
+
STEPS:
|
| 248 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 249 |
+
1. Compute from the string ``msg`` a list ``L1`` of
|
| 250 |
+
corresponding integers.
|
| 251 |
+
2. Compute from the list ``L1`` a new list ``L2``, given by
|
| 252 |
+
adding ``(k mod 26)`` to each element in ``L1``.
|
| 253 |
+
3. Compute from the list ``L2`` a string ``ct`` of
|
| 254 |
+
corresponding letters.
|
| 255 |
+
|
| 256 |
+
The shift cipher is also called the Caesar cipher, after
|
| 257 |
+
Julius Caesar, who, according to Suetonius, used it with a
|
| 258 |
+
shift of three to protect messages of military significance.
|
| 259 |
+
Caesar's nephew Augustus reportedly used a similar cipher, but
|
| 260 |
+
with a right shift of 1.
|
| 261 |
+
|
| 262 |
+
References
|
| 263 |
+
==========
|
| 264 |
+
|
| 265 |
+
.. [1] https://en.wikipedia.org/wiki/Caesar_cipher
|
| 266 |
+
.. [2] https://mathworld.wolfram.com/CaesarsMethod.html
|
| 267 |
+
|
| 268 |
+
See Also
|
| 269 |
+
========
|
| 270 |
+
|
| 271 |
+
decipher_shift
|
| 272 |
+
|
| 273 |
+
"""
|
| 274 |
+
msg, _, A = _prep(msg, '', symbols)
|
| 275 |
+
shift = len(A) - key % len(A)
|
| 276 |
+
key = A[shift:] + A[:shift]
|
| 277 |
+
return translate(msg, key, A)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def decipher_shift(msg, key, symbols=None):
|
| 281 |
+
"""
|
| 282 |
+
Return the text by shifting the characters of ``msg`` to the
|
| 283 |
+
left by the amount given by ``key``.
|
| 284 |
+
|
| 285 |
+
Examples
|
| 286 |
+
========
|
| 287 |
+
|
| 288 |
+
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift
|
| 289 |
+
>>> msg = "GONAVYBEATARMY"
|
| 290 |
+
>>> ct = encipher_shift(msg, 1); ct
|
| 291 |
+
'HPOBWZCFBUBSNZ'
|
| 292 |
+
|
| 293 |
+
To decipher the shifted text, change the sign of the key:
|
| 294 |
+
|
| 295 |
+
>>> encipher_shift(ct, -1)
|
| 296 |
+
'GONAVYBEATARMY'
|
| 297 |
+
|
| 298 |
+
Or use this function with the original key:
|
| 299 |
+
|
| 300 |
+
>>> decipher_shift(ct, 1)
|
| 301 |
+
'GONAVYBEATARMY'
|
| 302 |
+
|
| 303 |
+
"""
|
| 304 |
+
return encipher_shift(msg, -key, symbols)
|
| 305 |
+
|
| 306 |
+
def encipher_rot13(msg, symbols=None):
|
| 307 |
+
"""
|
| 308 |
+
Performs the ROT13 encryption on a given plaintext ``msg``.
|
| 309 |
+
|
| 310 |
+
Explanation
|
| 311 |
+
===========
|
| 312 |
+
|
| 313 |
+
ROT13 is a substitution cipher which substitutes each letter
|
| 314 |
+
in the plaintext message for the letter furthest away from it
|
| 315 |
+
in the English alphabet.
|
| 316 |
+
|
| 317 |
+
Equivalently, it is just a Caeser (shift) cipher with a shift
|
| 318 |
+
key of 13 (midway point of the alphabet).
|
| 319 |
+
|
| 320 |
+
References
|
| 321 |
+
==========
|
| 322 |
+
|
| 323 |
+
.. [1] https://en.wikipedia.org/wiki/ROT13
|
| 324 |
+
|
| 325 |
+
See Also
|
| 326 |
+
========
|
| 327 |
+
|
| 328 |
+
decipher_rot13
|
| 329 |
+
encipher_shift
|
| 330 |
+
|
| 331 |
+
"""
|
| 332 |
+
return encipher_shift(msg, 13, symbols)
|
| 333 |
+
|
| 334 |
+
def decipher_rot13(msg, symbols=None):
|
| 335 |
+
"""
|
| 336 |
+
Performs the ROT13 decryption on a given plaintext ``msg``.
|
| 337 |
+
|
| 338 |
+
Explanation
|
| 339 |
+
============
|
| 340 |
+
|
| 341 |
+
``decipher_rot13`` is equivalent to ``encipher_rot13`` as both
|
| 342 |
+
``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a
|
| 343 |
+
key of 13 will return the same results. Nonetheless,
|
| 344 |
+
``decipher_rot13`` has nonetheless been explicitly defined here for
|
| 345 |
+
consistency.
|
| 346 |
+
|
| 347 |
+
Examples
|
| 348 |
+
========
|
| 349 |
+
|
| 350 |
+
>>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13
|
| 351 |
+
>>> msg = 'GONAVYBEATARMY'
|
| 352 |
+
>>> ciphertext = encipher_rot13(msg);ciphertext
|
| 353 |
+
'TBANILORNGNEZL'
|
| 354 |
+
>>> decipher_rot13(ciphertext)
|
| 355 |
+
'GONAVYBEATARMY'
|
| 356 |
+
>>> encipher_rot13(msg) == decipher_rot13(msg)
|
| 357 |
+
True
|
| 358 |
+
>>> msg == decipher_rot13(ciphertext)
|
| 359 |
+
True
|
| 360 |
+
|
| 361 |
+
"""
|
| 362 |
+
return decipher_shift(msg, 13, symbols)
|
| 363 |
+
|
| 364 |
+
######## affine cipher examples ############
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def encipher_affine(msg, key, symbols=None, _inverse=False):
|
| 368 |
+
r"""
|
| 369 |
+
Performs the affine cipher encryption on plaintext ``msg``, and
|
| 370 |
+
returns the ciphertext.
|
| 371 |
+
|
| 372 |
+
Explanation
|
| 373 |
+
===========
|
| 374 |
+
|
| 375 |
+
Encryption is based on the map `x \rightarrow ax+b` (mod `N`)
|
| 376 |
+
where ``N`` is the number of characters in the alphabet.
|
| 377 |
+
Decryption is based on the map `x \rightarrow cx+d` (mod `N`),
|
| 378 |
+
where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
|
| 379 |
+
In particular, for the map to be invertible, we need
|
| 380 |
+
`\mathrm{gcd}(a, N) = 1` and an error will be raised if this is
|
| 381 |
+
not true.
|
| 382 |
+
|
| 383 |
+
Parameters
|
| 384 |
+
==========
|
| 385 |
+
|
| 386 |
+
msg : str
|
| 387 |
+
Characters that appear in ``symbols``.
|
| 388 |
+
|
| 389 |
+
a, b : int, int
|
| 390 |
+
A pair integers, with ``gcd(a, N) = 1`` (the secret key).
|
| 391 |
+
|
| 392 |
+
symbols
|
| 393 |
+
String of characters (default = uppercase letters).
|
| 394 |
+
|
| 395 |
+
When no symbols are given, ``msg`` is converted to upper case
|
| 396 |
+
letters and all other characters are ignored.
|
| 397 |
+
|
| 398 |
+
Returns
|
| 399 |
+
=======
|
| 400 |
+
|
| 401 |
+
ct
|
| 402 |
+
String of characters (the ciphertext message)
|
| 403 |
+
|
| 404 |
+
Notes
|
| 405 |
+
=====
|
| 406 |
+
|
| 407 |
+
ALGORITHM:
|
| 408 |
+
|
| 409 |
+
STEPS:
|
| 410 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 411 |
+
1. Compute from the string ``msg`` a list ``L1`` of
|
| 412 |
+
corresponding integers.
|
| 413 |
+
2. Compute from the list ``L1`` a new list ``L2``, given by
|
| 414 |
+
replacing ``x`` by ``a*x + b (mod N)``, for each element
|
| 415 |
+
``x`` in ``L1``.
|
| 416 |
+
3. Compute from the list ``L2`` a string ``ct`` of
|
| 417 |
+
corresponding letters.
|
| 418 |
+
|
| 419 |
+
This is a straightforward generalization of the shift cipher with
|
| 420 |
+
the added complexity of requiring 2 characters to be deciphered in
|
| 421 |
+
order to recover the key.
|
| 422 |
+
|
| 423 |
+
References
|
| 424 |
+
==========
|
| 425 |
+
|
| 426 |
+
.. [1] https://en.wikipedia.org/wiki/Affine_cipher
|
| 427 |
+
|
| 428 |
+
See Also
|
| 429 |
+
========
|
| 430 |
+
|
| 431 |
+
decipher_affine
|
| 432 |
+
|
| 433 |
+
"""
|
| 434 |
+
msg, _, A = _prep(msg, '', symbols)
|
| 435 |
+
N = len(A)
|
| 436 |
+
a, b = key
|
| 437 |
+
assert gcd(a, N) == 1
|
| 438 |
+
if _inverse:
|
| 439 |
+
c = invert(a, N)
|
| 440 |
+
d = -b*c
|
| 441 |
+
a, b = c, d
|
| 442 |
+
B = ''.join([A[(a*i + b) % N] for i in range(N)])
|
| 443 |
+
return translate(msg, A, B)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def decipher_affine(msg, key, symbols=None):
|
| 447 |
+
r"""
|
| 448 |
+
Return the deciphered text that was made from the mapping,
|
| 449 |
+
`x \rightarrow ax+b` (mod `N`), where ``N`` is the
|
| 450 |
+
number of characters in the alphabet. Deciphering is done by
|
| 451 |
+
reciphering with a new key: `x \rightarrow cx+d` (mod `N`),
|
| 452 |
+
where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
|
| 453 |
+
|
| 454 |
+
Examples
|
| 455 |
+
========
|
| 456 |
+
|
| 457 |
+
>>> from sympy.crypto.crypto import encipher_affine, decipher_affine
|
| 458 |
+
>>> msg = "GO NAVY BEAT ARMY"
|
| 459 |
+
>>> key = (3, 1)
|
| 460 |
+
>>> encipher_affine(msg, key)
|
| 461 |
+
'TROBMVENBGBALV'
|
| 462 |
+
>>> decipher_affine(_, key)
|
| 463 |
+
'GONAVYBEATARMY'
|
| 464 |
+
|
| 465 |
+
See Also
|
| 466 |
+
========
|
| 467 |
+
|
| 468 |
+
encipher_affine
|
| 469 |
+
|
| 470 |
+
"""
|
| 471 |
+
return encipher_affine(msg, key, symbols, _inverse=True)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def encipher_atbash(msg, symbols=None):
|
| 475 |
+
r"""
|
| 476 |
+
Enciphers a given ``msg`` into its Atbash ciphertext and returns it.
|
| 477 |
+
|
| 478 |
+
Explanation
|
| 479 |
+
===========
|
| 480 |
+
|
| 481 |
+
Atbash is a substitution cipher originally used to encrypt the Hebrew
|
| 482 |
+
alphabet. Atbash works on the principle of mapping each alphabet to its
|
| 483 |
+
reverse / counterpart (i.e. a would map to z, b to y etc.)
|
| 484 |
+
|
| 485 |
+
Atbash is functionally equivalent to the affine cipher with ``a = 25``
|
| 486 |
+
and ``b = 25``
|
| 487 |
+
|
| 488 |
+
See Also
|
| 489 |
+
========
|
| 490 |
+
|
| 491 |
+
decipher_atbash
|
| 492 |
+
|
| 493 |
+
"""
|
| 494 |
+
return encipher_affine(msg, (25, 25), symbols)
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def decipher_atbash(msg, symbols=None):
|
| 498 |
+
r"""
|
| 499 |
+
Deciphers a given ``msg`` using Atbash cipher and returns it.
|
| 500 |
+
|
| 501 |
+
Explanation
|
| 502 |
+
===========
|
| 503 |
+
|
| 504 |
+
``decipher_atbash`` is functionally equivalent to ``encipher_atbash``.
|
| 505 |
+
However, it has still been added as a separate function to maintain
|
| 506 |
+
consistency.
|
| 507 |
+
|
| 508 |
+
Examples
|
| 509 |
+
========
|
| 510 |
+
|
| 511 |
+
>>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash
|
| 512 |
+
>>> msg = 'GONAVYBEATARMY'
|
| 513 |
+
>>> encipher_atbash(msg)
|
| 514 |
+
'TLMZEBYVZGZINB'
|
| 515 |
+
>>> decipher_atbash(msg)
|
| 516 |
+
'TLMZEBYVZGZINB'
|
| 517 |
+
>>> encipher_atbash(msg) == decipher_atbash(msg)
|
| 518 |
+
True
|
| 519 |
+
>>> msg == encipher_atbash(encipher_atbash(msg))
|
| 520 |
+
True
|
| 521 |
+
|
| 522 |
+
References
|
| 523 |
+
==========
|
| 524 |
+
|
| 525 |
+
.. [1] https://en.wikipedia.org/wiki/Atbash
|
| 526 |
+
|
| 527 |
+
See Also
|
| 528 |
+
========
|
| 529 |
+
|
| 530 |
+
encipher_atbash
|
| 531 |
+
|
| 532 |
+
"""
|
| 533 |
+
return decipher_affine(msg, (25, 25), symbols)
|
| 534 |
+
|
| 535 |
+
#################### substitution cipher ###########################
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def encipher_substitution(msg, old, new=None):
|
| 539 |
+
r"""
|
| 540 |
+
Returns the ciphertext obtained by replacing each character that
|
| 541 |
+
appears in ``old`` with the corresponding character in ``new``.
|
| 542 |
+
If ``old`` is a mapping, then new is ignored and the replacements
|
| 543 |
+
defined by ``old`` are used.
|
| 544 |
+
|
| 545 |
+
Explanation
|
| 546 |
+
===========
|
| 547 |
+
|
| 548 |
+
This is a more general than the affine cipher in that the key can
|
| 549 |
+
only be recovered by determining the mapping for each symbol.
|
| 550 |
+
Though in practice, once a few symbols are recognized the mappings
|
| 551 |
+
for other characters can be quickly guessed.
|
| 552 |
+
|
| 553 |
+
Examples
|
| 554 |
+
========
|
| 555 |
+
|
| 556 |
+
>>> from sympy.crypto.crypto import encipher_substitution, AZ
|
| 557 |
+
>>> old = 'OEYAG'
|
| 558 |
+
>>> new = '034^6'
|
| 559 |
+
>>> msg = AZ("go navy! beat army!")
|
| 560 |
+
>>> ct = encipher_substitution(msg, old, new); ct
|
| 561 |
+
'60N^V4B3^T^RM4'
|
| 562 |
+
|
| 563 |
+
To decrypt a substitution, reverse the last two arguments:
|
| 564 |
+
|
| 565 |
+
>>> encipher_substitution(ct, new, old)
|
| 566 |
+
'GONAVYBEATARMY'
|
| 567 |
+
|
| 568 |
+
In the special case where ``old`` and ``new`` are a permutation of
|
| 569 |
+
order 2 (representing a transposition of characters) their order
|
| 570 |
+
is immaterial:
|
| 571 |
+
|
| 572 |
+
>>> old = 'NAVY'
|
| 573 |
+
>>> new = 'ANYV'
|
| 574 |
+
>>> encipher = lambda x: encipher_substitution(x, old, new)
|
| 575 |
+
>>> encipher('NAVY')
|
| 576 |
+
'ANYV'
|
| 577 |
+
>>> encipher(_)
|
| 578 |
+
'NAVY'
|
| 579 |
+
|
| 580 |
+
The substitution cipher, in general, is a method
|
| 581 |
+
whereby "units" (not necessarily single characters) of plaintext
|
| 582 |
+
are replaced with ciphertext according to a regular system.
|
| 583 |
+
|
| 584 |
+
>>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc']))
|
| 585 |
+
>>> print(encipher_substitution('abc', ords))
|
| 586 |
+
\97\98\99
|
| 587 |
+
|
| 588 |
+
References
|
| 589 |
+
==========
|
| 590 |
+
|
| 591 |
+
.. [1] https://en.wikipedia.org/wiki/Substitution_cipher
|
| 592 |
+
|
| 593 |
+
"""
|
| 594 |
+
return translate(msg, old, new)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
######################################################################
|
| 598 |
+
#################### Vigenere cipher examples ########################
|
| 599 |
+
######################################################################
|
| 600 |
+
|
| 601 |
+
def encipher_vigenere(msg, key, symbols=None):
|
| 602 |
+
"""
|
| 603 |
+
Performs the Vigenere cipher encryption on plaintext ``msg``, and
|
| 604 |
+
returns the ciphertext.
|
| 605 |
+
|
| 606 |
+
Examples
|
| 607 |
+
========
|
| 608 |
+
|
| 609 |
+
>>> from sympy.crypto.crypto import encipher_vigenere, AZ
|
| 610 |
+
>>> key = "encrypt"
|
| 611 |
+
>>> msg = "meet me on monday"
|
| 612 |
+
>>> encipher_vigenere(msg, key)
|
| 613 |
+
'QRGKKTHRZQEBPR'
|
| 614 |
+
|
| 615 |
+
Section 1 of the Kryptos sculpture at the CIA headquarters
|
| 616 |
+
uses this cipher and also changes the order of the
|
| 617 |
+
alphabet [2]_. Here is the first line of that section of
|
| 618 |
+
the sculpture:
|
| 619 |
+
|
| 620 |
+
>>> from sympy.crypto.crypto import decipher_vigenere, padded_key
|
| 621 |
+
>>> alp = padded_key('KRYPTOS', AZ())
|
| 622 |
+
>>> key = 'PALIMPSEST'
|
| 623 |
+
>>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ'
|
| 624 |
+
>>> decipher_vigenere(msg, key, alp)
|
| 625 |
+
'BETWEENSUBTLESHADINGANDTHEABSENC'
|
| 626 |
+
|
| 627 |
+
Explanation
|
| 628 |
+
===========
|
| 629 |
+
|
| 630 |
+
The Vigenere cipher is named after Blaise de Vigenere, a sixteenth
|
| 631 |
+
century diplomat and cryptographer, by a historical accident.
|
| 632 |
+
Vigenere actually invented a different and more complicated cipher.
|
| 633 |
+
The so-called *Vigenere cipher* was actually invented
|
| 634 |
+
by Giovan Batista Belaso in 1553.
|
| 635 |
+
|
| 636 |
+
This cipher was used in the 1800's, for example, during the American
|
| 637 |
+
Civil War. The Confederacy used a brass cipher disk to implement the
|
| 638 |
+
Vigenere cipher (now on display in the NSA Museum in Fort
|
| 639 |
+
Meade) [1]_.
|
| 640 |
+
|
| 641 |
+
The Vigenere cipher is a generalization of the shift cipher.
|
| 642 |
+
Whereas the shift cipher shifts each letter by the same amount
|
| 643 |
+
(that amount being the key of the shift cipher) the Vigenere
|
| 644 |
+
cipher shifts a letter by an amount determined by the key (which is
|
| 645 |
+
a word or phrase known only to the sender and receiver).
|
| 646 |
+
|
| 647 |
+
For example, if the key was a single letter, such as "C", then the
|
| 648 |
+
so-called Vigenere cipher is actually a shift cipher with a
|
| 649 |
+
shift of `2` (since "C" is the 2nd letter of the alphabet, if
|
| 650 |
+
you start counting at `0`). If the key was a word with two
|
| 651 |
+
letters, such as "CA", then the so-called Vigenere cipher will
|
| 652 |
+
shift letters in even positions by `2` and letters in odd positions
|
| 653 |
+
are left alone (shifted by `0`, since "A" is the 0th letter, if
|
| 654 |
+
you start counting at `0`).
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
ALGORITHM:
|
| 658 |
+
|
| 659 |
+
INPUT:
|
| 660 |
+
|
| 661 |
+
``msg``: string of characters that appear in ``symbols``
|
| 662 |
+
(the plaintext)
|
| 663 |
+
|
| 664 |
+
``key``: a string of characters that appear in ``symbols``
|
| 665 |
+
(the secret key)
|
| 666 |
+
|
| 667 |
+
``symbols``: a string of letters defining the alphabet
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
OUTPUT:
|
| 671 |
+
|
| 672 |
+
``ct``: string of characters (the ciphertext message)
|
| 673 |
+
|
| 674 |
+
STEPS:
|
| 675 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 676 |
+
1. Compute from the string ``key`` a list ``L1`` of
|
| 677 |
+
corresponding integers. Let ``n1 = len(L1)``.
|
| 678 |
+
2. Compute from the string ``msg`` a list ``L2`` of
|
| 679 |
+
corresponding integers. Let ``n2 = len(L2)``.
|
| 680 |
+
3. Break ``L2`` up sequentially into sublists of size
|
| 681 |
+
``n1``; the last sublist may be smaller than ``n1``
|
| 682 |
+
4. For each of these sublists ``L`` of ``L2``, compute a
|
| 683 |
+
new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)``
|
| 684 |
+
to the ``i``-th element in the sublist, for each ``i``.
|
| 685 |
+
5. Assemble these lists ``C`` by concatenation into a new
|
| 686 |
+
list of length ``n2``.
|
| 687 |
+
6. Compute from the new list a string ``ct`` of
|
| 688 |
+
corresponding letters.
|
| 689 |
+
|
| 690 |
+
Once it is known that the key is, say, `n` characters long,
|
| 691 |
+
frequency analysis can be applied to every `n`-th letter of
|
| 692 |
+
the ciphertext to determine the plaintext. This method is
|
| 693 |
+
called *Kasiski examination* (although it was first discovered
|
| 694 |
+
by Babbage). If they key is as long as the message and is
|
| 695 |
+
comprised of randomly selected characters -- a one-time pad -- the
|
| 696 |
+
message is theoretically unbreakable.
|
| 697 |
+
|
| 698 |
+
The cipher Vigenere actually discovered is an "auto-key" cipher
|
| 699 |
+
described as follows.
|
| 700 |
+
|
| 701 |
+
ALGORITHM:
|
| 702 |
+
|
| 703 |
+
INPUT:
|
| 704 |
+
|
| 705 |
+
``key``: a string of letters (the secret key)
|
| 706 |
+
|
| 707 |
+
``msg``: string of letters (the plaintext message)
|
| 708 |
+
|
| 709 |
+
OUTPUT:
|
| 710 |
+
|
| 711 |
+
``ct``: string of upper-case letters (the ciphertext message)
|
| 712 |
+
|
| 713 |
+
STEPS:
|
| 714 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 715 |
+
1. Compute from the string ``msg`` a list ``L2`` of
|
| 716 |
+
corresponding integers. Let ``n2 = len(L2)``.
|
| 717 |
+
2. Let ``n1`` be the length of the key. Append to the
|
| 718 |
+
string ``key`` the first ``n2 - n1`` characters of
|
| 719 |
+
the plaintext message. Compute from this string (also of
|
| 720 |
+
length ``n2``) a list ``L1`` of integers corresponding
|
| 721 |
+
to the letter numbers in the first step.
|
| 722 |
+
3. Compute a new list ``C`` given by
|
| 723 |
+
``C[i] = L1[i] + L2[i] (mod N)``.
|
| 724 |
+
4. Compute from the new list a string ``ct`` of letters
|
| 725 |
+
corresponding to the new integers.
|
| 726 |
+
|
| 727 |
+
To decipher the auto-key ciphertext, the key is used to decipher
|
| 728 |
+
the first ``n1`` characters and then those characters become the
|
| 729 |
+
key to decipher the next ``n1`` characters, etc...:
|
| 730 |
+
|
| 731 |
+
>>> m = AZ('go navy, beat army! yes you can'); m
|
| 732 |
+
'GONAVYBEATARMYYESYOUCAN'
|
| 733 |
+
>>> key = AZ('gold bug'); n1 = len(key); n2 = len(m)
|
| 734 |
+
>>> auto_key = key + m[:n2 - n1]; auto_key
|
| 735 |
+
'GOLDBUGGONAVYBEATARMYYE'
|
| 736 |
+
>>> ct = encipher_vigenere(m, auto_key); ct
|
| 737 |
+
'MCYDWSHKOGAMKZCELYFGAYR'
|
| 738 |
+
>>> n1 = len(key)
|
| 739 |
+
>>> pt = []
|
| 740 |
+
>>> while ct:
|
| 741 |
+
... part, ct = ct[:n1], ct[n1:]
|
| 742 |
+
... pt.append(decipher_vigenere(part, key))
|
| 743 |
+
... key = pt[-1]
|
| 744 |
+
...
|
| 745 |
+
>>> ''.join(pt) == m
|
| 746 |
+
True
|
| 747 |
+
|
| 748 |
+
References
|
| 749 |
+
==========
|
| 750 |
+
|
| 751 |
+
.. [1] https://en.wikipedia.org/wiki/Vigenere_cipher
|
| 752 |
+
.. [2] https://web.archive.org/web/20071116100808/https://filebox.vt.edu/users/batman/kryptos.html
|
| 753 |
+
(short URL: https://goo.gl/ijr22d)
|
| 754 |
+
|
| 755 |
+
"""
|
| 756 |
+
msg, key, A = _prep(msg, key, symbols)
|
| 757 |
+
map = {c: i for i, c in enumerate(A)}
|
| 758 |
+
key = [map[c] for c in key]
|
| 759 |
+
N = len(map)
|
| 760 |
+
k = len(key)
|
| 761 |
+
rv = []
|
| 762 |
+
for i, m in enumerate(msg):
|
| 763 |
+
rv.append(A[(map[m] + key[i % k]) % N])
|
| 764 |
+
rv = ''.join(rv)
|
| 765 |
+
return rv
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
def decipher_vigenere(msg, key, symbols=None):
|
| 769 |
+
"""
|
| 770 |
+
Decode using the Vigenere cipher.
|
| 771 |
+
|
| 772 |
+
Examples
|
| 773 |
+
========
|
| 774 |
+
|
| 775 |
+
>>> from sympy.crypto.crypto import decipher_vigenere
|
| 776 |
+
>>> key = "encrypt"
|
| 777 |
+
>>> ct = "QRGK kt HRZQE BPR"
|
| 778 |
+
>>> decipher_vigenere(ct, key)
|
| 779 |
+
'MEETMEONMONDAY'
|
| 780 |
+
|
| 781 |
+
"""
|
| 782 |
+
msg, key, A = _prep(msg, key, symbols)
|
| 783 |
+
map = {c: i for i, c in enumerate(A)}
|
| 784 |
+
N = len(A) # normally, 26
|
| 785 |
+
K = [map[c] for c in key]
|
| 786 |
+
n = len(K)
|
| 787 |
+
C = [map[c] for c in msg]
|
| 788 |
+
rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)])
|
| 789 |
+
return rv
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
#################### Hill cipher ########################
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def encipher_hill(msg, key, symbols=None, pad="Q"):
|
| 796 |
+
r"""
|
| 797 |
+
Return the Hill cipher encryption of ``msg``.
|
| 798 |
+
|
| 799 |
+
Explanation
|
| 800 |
+
===========
|
| 801 |
+
|
| 802 |
+
The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_,
|
| 803 |
+
was the first polygraphic cipher in which it was practical
|
| 804 |
+
(though barely) to operate on more than three symbols at once.
|
| 805 |
+
The following discussion assumes an elementary knowledge of
|
| 806 |
+
matrices.
|
| 807 |
+
|
| 808 |
+
First, each letter is first encoded as a number starting with 0.
|
| 809 |
+
Suppose your message `msg` consists of `n` capital letters, with no
|
| 810 |
+
spaces. This may be regarded an `n`-tuple M of elements of
|
| 811 |
+
`Z_{26}` (if the letters are those of the English alphabet). A key
|
| 812 |
+
in the Hill cipher is a `k x k` matrix `K`, all of whose entries
|
| 813 |
+
are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the
|
| 814 |
+
linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k`
|
| 815 |
+
is one-to-one).
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
Parameters
|
| 819 |
+
==========
|
| 820 |
+
|
| 821 |
+
msg
|
| 822 |
+
Plaintext message of `n` upper-case letters.
|
| 823 |
+
|
| 824 |
+
key
|
| 825 |
+
A `k \times k` invertible matrix `K`, all of whose entries are
|
| 826 |
+
in `Z_{26}` (or whatever number of symbols are being used).
|
| 827 |
+
|
| 828 |
+
pad
|
| 829 |
+
Character (default "Q") to use to make length of text be a
|
| 830 |
+
multiple of ``k``.
|
| 831 |
+
|
| 832 |
+
Returns
|
| 833 |
+
=======
|
| 834 |
+
|
| 835 |
+
ct
|
| 836 |
+
Ciphertext of upper-case letters.
|
| 837 |
+
|
| 838 |
+
Notes
|
| 839 |
+
=====
|
| 840 |
+
|
| 841 |
+
ALGORITHM:
|
| 842 |
+
|
| 843 |
+
STEPS:
|
| 844 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 845 |
+
1. Compute from the string ``msg`` a list ``L`` of
|
| 846 |
+
corresponding integers. Let ``n = len(L)``.
|
| 847 |
+
2. Break the list ``L`` up into ``t = ceiling(n/k)``
|
| 848 |
+
sublists ``L_1``, ..., ``L_t`` of size ``k`` (with
|
| 849 |
+
the last list "padded" to ensure its size is
|
| 850 |
+
``k``).
|
| 851 |
+
3. Compute new list ``C_1``, ..., ``C_t`` given by
|
| 852 |
+
``C[i] = K*L_i`` (arithmetic is done mod N), for each
|
| 853 |
+
``i``.
|
| 854 |
+
4. Concatenate these into a list ``C = C_1 + ... + C_t``.
|
| 855 |
+
5. Compute from ``C`` a string ``ct`` of corresponding
|
| 856 |
+
letters. This has length ``k*t``.
|
| 857 |
+
|
| 858 |
+
References
|
| 859 |
+
==========
|
| 860 |
+
|
| 861 |
+
.. [1] https://en.wikipedia.org/wiki/Hill_cipher
|
| 862 |
+
.. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet,
|
| 863 |
+
The American Mathematical Monthly Vol.36, June-July 1929,
|
| 864 |
+
pp.306-312.
|
| 865 |
+
|
| 866 |
+
See Also
|
| 867 |
+
========
|
| 868 |
+
|
| 869 |
+
decipher_hill
|
| 870 |
+
|
| 871 |
+
"""
|
| 872 |
+
assert key.is_square
|
| 873 |
+
assert len(pad) == 1
|
| 874 |
+
msg, pad, A = _prep(msg, pad, symbols)
|
| 875 |
+
map = {c: i for i, c in enumerate(A)}
|
| 876 |
+
P = [map[c] for c in msg]
|
| 877 |
+
N = len(A)
|
| 878 |
+
k = key.cols
|
| 879 |
+
n = len(P)
|
| 880 |
+
m, r = divmod(n, k)
|
| 881 |
+
if r:
|
| 882 |
+
P = P + [map[pad]]*(k - r)
|
| 883 |
+
m += 1
|
| 884 |
+
rv = ''.join([A[c % N] for j in range(m) for c in
|
| 885 |
+
list(key*Matrix(k, 1, [P[i]
|
| 886 |
+
for i in range(k*j, k*(j + 1))]))])
|
| 887 |
+
return rv
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def decipher_hill(msg, key, symbols=None):
|
| 891 |
+
"""
|
| 892 |
+
Deciphering is the same as enciphering but using the inverse of the
|
| 893 |
+
key matrix.
|
| 894 |
+
|
| 895 |
+
Examples
|
| 896 |
+
========
|
| 897 |
+
|
| 898 |
+
>>> from sympy.crypto.crypto import encipher_hill, decipher_hill
|
| 899 |
+
>>> from sympy import Matrix
|
| 900 |
+
|
| 901 |
+
>>> key = Matrix([[1, 2], [3, 5]])
|
| 902 |
+
>>> encipher_hill("meet me on monday", key)
|
| 903 |
+
'UEQDUEODOCTCWQ'
|
| 904 |
+
>>> decipher_hill(_, key)
|
| 905 |
+
'MEETMEONMONDAY'
|
| 906 |
+
|
| 907 |
+
When the length of the plaintext (stripped of invalid characters)
|
| 908 |
+
is not a multiple of the key dimension, extra characters will
|
| 909 |
+
appear at the end of the enciphered and deciphered text. In order to
|
| 910 |
+
decipher the text, those characters must be included in the text to
|
| 911 |
+
be deciphered. In the following, the key has a dimension of 4 but
|
| 912 |
+
the text is 2 short of being a multiple of 4 so two characters will
|
| 913 |
+
be added.
|
| 914 |
+
|
| 915 |
+
>>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0],
|
| 916 |
+
... [2, 2, 3, 4], [1, 1, 0, 1]])
|
| 917 |
+
>>> msg = "ST"
|
| 918 |
+
>>> encipher_hill(msg, key)
|
| 919 |
+
'HJEB'
|
| 920 |
+
>>> decipher_hill(_, key)
|
| 921 |
+
'STQQ'
|
| 922 |
+
>>> encipher_hill(msg, key, pad="Z")
|
| 923 |
+
'ISPK'
|
| 924 |
+
>>> decipher_hill(_, key)
|
| 925 |
+
'STZZ'
|
| 926 |
+
|
| 927 |
+
If the last two characters of the ciphertext were ignored in
|
| 928 |
+
either case, the wrong plaintext would be recovered:
|
| 929 |
+
|
| 930 |
+
>>> decipher_hill("HD", key)
|
| 931 |
+
'ORMV'
|
| 932 |
+
>>> decipher_hill("IS", key)
|
| 933 |
+
'UIKY'
|
| 934 |
+
|
| 935 |
+
See Also
|
| 936 |
+
========
|
| 937 |
+
|
| 938 |
+
encipher_hill
|
| 939 |
+
|
| 940 |
+
"""
|
| 941 |
+
assert key.is_square
|
| 942 |
+
msg, _, A = _prep(msg, '', symbols)
|
| 943 |
+
map = {c: i for i, c in enumerate(A)}
|
| 944 |
+
C = [map[c] for c in msg]
|
| 945 |
+
N = len(A)
|
| 946 |
+
k = key.cols
|
| 947 |
+
n = len(C)
|
| 948 |
+
m, r = divmod(n, k)
|
| 949 |
+
if r:
|
| 950 |
+
C = C + [0]*(k - r)
|
| 951 |
+
m += 1
|
| 952 |
+
key_inv = key.inv_mod(N)
|
| 953 |
+
rv = ''.join([A[p % N] for j in range(m) for p in
|
| 954 |
+
list(key_inv*Matrix(
|
| 955 |
+
k, 1, [C[i] for i in range(k*j, k*(j + 1))]))])
|
| 956 |
+
return rv
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
#################### Bifid cipher ########################
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
def encipher_bifid(msg, key, symbols=None):
|
| 963 |
+
r"""
|
| 964 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
| 965 |
+
returns the ciphertext.
|
| 966 |
+
|
| 967 |
+
This is the version of the Bifid cipher that uses an `n \times n`
|
| 968 |
+
Polybius square.
|
| 969 |
+
|
| 970 |
+
Parameters
|
| 971 |
+
==========
|
| 972 |
+
|
| 973 |
+
msg
|
| 974 |
+
Plaintext string.
|
| 975 |
+
|
| 976 |
+
key
|
| 977 |
+
Short string for key.
|
| 978 |
+
|
| 979 |
+
Duplicate characters are ignored and then it is padded with the
|
| 980 |
+
characters in ``symbols`` that were not in the short key.
|
| 981 |
+
|
| 982 |
+
symbols
|
| 983 |
+
`n \times n` characters defining the alphabet.
|
| 984 |
+
|
| 985 |
+
(default is string.printable)
|
| 986 |
+
|
| 987 |
+
Returns
|
| 988 |
+
=======
|
| 989 |
+
|
| 990 |
+
ciphertext
|
| 991 |
+
Ciphertext using Bifid5 cipher without spaces.
|
| 992 |
+
|
| 993 |
+
See Also
|
| 994 |
+
========
|
| 995 |
+
|
| 996 |
+
decipher_bifid, encipher_bifid5, encipher_bifid6
|
| 997 |
+
|
| 998 |
+
References
|
| 999 |
+
==========
|
| 1000 |
+
|
| 1001 |
+
.. [1] https://en.wikipedia.org/wiki/Bifid_cipher
|
| 1002 |
+
|
| 1003 |
+
"""
|
| 1004 |
+
msg, key, A = _prep(msg, key, symbols, bifid10)
|
| 1005 |
+
long_key = ''.join(uniq(key)) or A
|
| 1006 |
+
|
| 1007 |
+
n = len(A)**.5
|
| 1008 |
+
if n != int(n):
|
| 1009 |
+
raise ValueError(
|
| 1010 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
| 1011 |
+
N = int(n)
|
| 1012 |
+
if len(long_key) < N**2:
|
| 1013 |
+
long_key = list(long_key) + [x for x in A if x not in long_key]
|
| 1014 |
+
|
| 1015 |
+
# the fractionalization
|
| 1016 |
+
row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)}
|
| 1017 |
+
r, c = zip(*[row_col[x] for x in msg])
|
| 1018 |
+
rc = r + c
|
| 1019 |
+
ch = {i: ch for ch, i in row_col.items()}
|
| 1020 |
+
rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2]))
|
| 1021 |
+
return rv
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
def decipher_bifid(msg, key, symbols=None):
|
| 1025 |
+
r"""
|
| 1026 |
+
Performs the Bifid cipher decryption on ciphertext ``msg``, and
|
| 1027 |
+
returns the plaintext.
|
| 1028 |
+
|
| 1029 |
+
This is the version of the Bifid cipher that uses the `n \times n`
|
| 1030 |
+
Polybius square.
|
| 1031 |
+
|
| 1032 |
+
Parameters
|
| 1033 |
+
==========
|
| 1034 |
+
|
| 1035 |
+
msg
|
| 1036 |
+
Ciphertext string.
|
| 1037 |
+
|
| 1038 |
+
key
|
| 1039 |
+
Short string for key.
|
| 1040 |
+
|
| 1041 |
+
Duplicate characters are ignored and then it is padded with the
|
| 1042 |
+
characters in symbols that were not in the short key.
|
| 1043 |
+
|
| 1044 |
+
symbols
|
| 1045 |
+
`n \times n` characters defining the alphabet.
|
| 1046 |
+
|
| 1047 |
+
(default=string.printable, a `10 \times 10` matrix)
|
| 1048 |
+
|
| 1049 |
+
Returns
|
| 1050 |
+
=======
|
| 1051 |
+
|
| 1052 |
+
deciphered
|
| 1053 |
+
Deciphered text.
|
| 1054 |
+
|
| 1055 |
+
Examples
|
| 1056 |
+
========
|
| 1057 |
+
|
| 1058 |
+
>>> from sympy.crypto.crypto import (
|
| 1059 |
+
... encipher_bifid, decipher_bifid, AZ)
|
| 1060 |
+
|
| 1061 |
+
Do an encryption using the bifid5 alphabet:
|
| 1062 |
+
|
| 1063 |
+
>>> alp = AZ().replace('J', '')
|
| 1064 |
+
>>> ct = AZ("meet me on monday!")
|
| 1065 |
+
>>> key = AZ("gold bug")
|
| 1066 |
+
>>> encipher_bifid(ct, key, alp)
|
| 1067 |
+
'IEILHHFSTSFQYE'
|
| 1068 |
+
|
| 1069 |
+
When entering the text or ciphertext, spaces are ignored so it
|
| 1070 |
+
can be formatted as desired. Re-entering the ciphertext from the
|
| 1071 |
+
preceding, putting 4 characters per line and padding with an extra
|
| 1072 |
+
J, does not cause problems for the deciphering:
|
| 1073 |
+
|
| 1074 |
+
>>> decipher_bifid('''
|
| 1075 |
+
... IEILH
|
| 1076 |
+
... HFSTS
|
| 1077 |
+
... FQYEJ''', key, alp)
|
| 1078 |
+
'MEETMEONMONDAY'
|
| 1079 |
+
|
| 1080 |
+
When no alphabet is given, all 100 printable characters will be
|
| 1081 |
+
used:
|
| 1082 |
+
|
| 1083 |
+
>>> key = ''
|
| 1084 |
+
>>> encipher_bifid('hello world!', key)
|
| 1085 |
+
'bmtwmg-bIo*w'
|
| 1086 |
+
>>> decipher_bifid(_, key)
|
| 1087 |
+
'hello world!'
|
| 1088 |
+
|
| 1089 |
+
If the key is changed, a different encryption is obtained:
|
| 1090 |
+
|
| 1091 |
+
>>> key = 'gold bug'
|
| 1092 |
+
>>> encipher_bifid('hello world!', 'gold_bug')
|
| 1093 |
+
'hg2sfuei7t}w'
|
| 1094 |
+
|
| 1095 |
+
And if the key used to decrypt the message is not exact, the
|
| 1096 |
+
original text will not be perfectly obtained:
|
| 1097 |
+
|
| 1098 |
+
>>> decipher_bifid(_, 'gold pug')
|
| 1099 |
+
'heldo~wor6d!'
|
| 1100 |
+
|
| 1101 |
+
"""
|
| 1102 |
+
msg, _, A = _prep(msg, '', symbols, bifid10)
|
| 1103 |
+
long_key = ''.join(uniq(key)) or A
|
| 1104 |
+
|
| 1105 |
+
n = len(A)**.5
|
| 1106 |
+
if n != int(n):
|
| 1107 |
+
raise ValueError(
|
| 1108 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
| 1109 |
+
N = int(n)
|
| 1110 |
+
if len(long_key) < N**2:
|
| 1111 |
+
long_key = list(long_key) + [x for x in A if x not in long_key]
|
| 1112 |
+
|
| 1113 |
+
# the reverse fractionalization
|
| 1114 |
+
row_col = {
|
| 1115 |
+
ch: divmod(i, N) for i, ch in enumerate(long_key)}
|
| 1116 |
+
rc = [i for c in msg for i in row_col[c]]
|
| 1117 |
+
n = len(msg)
|
| 1118 |
+
rc = zip(*(rc[:n], rc[n:]))
|
| 1119 |
+
ch = {i: ch for ch, i in row_col.items()}
|
| 1120 |
+
rv = ''.join(ch[i] for i in rc)
|
| 1121 |
+
return rv
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
def bifid_square(key):
|
| 1125 |
+
"""Return characters of ``key`` arranged in a square.
|
| 1126 |
+
|
| 1127 |
+
Examples
|
| 1128 |
+
========
|
| 1129 |
+
|
| 1130 |
+
>>> from sympy.crypto.crypto import (
|
| 1131 |
+
... bifid_square, AZ, padded_key, bifid5)
|
| 1132 |
+
>>> bifid_square(AZ().replace('J', ''))
|
| 1133 |
+
Matrix([
|
| 1134 |
+
[A, B, C, D, E],
|
| 1135 |
+
[F, G, H, I, K],
|
| 1136 |
+
[L, M, N, O, P],
|
| 1137 |
+
[Q, R, S, T, U],
|
| 1138 |
+
[V, W, X, Y, Z]])
|
| 1139 |
+
|
| 1140 |
+
>>> bifid_square(padded_key(AZ('gold bug!'), bifid5))
|
| 1141 |
+
Matrix([
|
| 1142 |
+
[G, O, L, D, B],
|
| 1143 |
+
[U, A, C, E, F],
|
| 1144 |
+
[H, I, K, M, N],
|
| 1145 |
+
[P, Q, R, S, T],
|
| 1146 |
+
[V, W, X, Y, Z]])
|
| 1147 |
+
|
| 1148 |
+
See Also
|
| 1149 |
+
========
|
| 1150 |
+
|
| 1151 |
+
padded_key
|
| 1152 |
+
|
| 1153 |
+
"""
|
| 1154 |
+
A = ''.join(uniq(''.join(key)))
|
| 1155 |
+
n = len(A)**.5
|
| 1156 |
+
if n != int(n):
|
| 1157 |
+
raise ValueError(
|
| 1158 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
| 1159 |
+
n = int(n)
|
| 1160 |
+
f = lambda i, j: Symbol(A[n*i + j])
|
| 1161 |
+
rv = Matrix(n, n, f)
|
| 1162 |
+
return rv
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
def encipher_bifid5(msg, key):
|
| 1166 |
+
r"""
|
| 1167 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
| 1168 |
+
returns the ciphertext.
|
| 1169 |
+
|
| 1170 |
+
Explanation
|
| 1171 |
+
===========
|
| 1172 |
+
|
| 1173 |
+
This is the version of the Bifid cipher that uses the `5 \times 5`
|
| 1174 |
+
Polybius square. The letter "J" is ignored so it must be replaced
|
| 1175 |
+
with something else (traditionally an "I") before encryption.
|
| 1176 |
+
|
| 1177 |
+
ALGORITHM: (5x5 case)
|
| 1178 |
+
|
| 1179 |
+
STEPS:
|
| 1180 |
+
0. Create the `5 \times 5` Polybius square ``S`` associated
|
| 1181 |
+
to ``key`` as follows:
|
| 1182 |
+
|
| 1183 |
+
a) moving from left-to-right, top-to-bottom,
|
| 1184 |
+
place the letters of the key into a `5 \times 5`
|
| 1185 |
+
matrix,
|
| 1186 |
+
b) if the key has less than 25 letters, add the
|
| 1187 |
+
letters of the alphabet not in the key until the
|
| 1188 |
+
`5 \times 5` square is filled.
|
| 1189 |
+
|
| 1190 |
+
1. Create a list ``P`` of pairs of numbers which are the
|
| 1191 |
+
coordinates in the Polybius square of the letters in
|
| 1192 |
+
``msg``.
|
| 1193 |
+
2. Let ``L1`` be the list of all first coordinates of ``P``
|
| 1194 |
+
(length of ``L1 = n``), let ``L2`` be the list of all
|
| 1195 |
+
second coordinates of ``P`` (so the length of ``L2``
|
| 1196 |
+
is also ``n``).
|
| 1197 |
+
3. Let ``L`` be the concatenation of ``L1`` and ``L2``
|
| 1198 |
+
(length ``L = 2*n``), except that consecutive numbers
|
| 1199 |
+
are paired ``(L[2*i], L[2*i + 1])``. You can regard
|
| 1200 |
+
``L`` as a list of pairs of length ``n``.
|
| 1201 |
+
4. Let ``C`` be the list of all letters which are of the
|
| 1202 |
+
form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a
|
| 1203 |
+
string, this is the ciphertext of ``msg``.
|
| 1204 |
+
|
| 1205 |
+
Parameters
|
| 1206 |
+
==========
|
| 1207 |
+
|
| 1208 |
+
msg : str
|
| 1209 |
+
Plaintext string.
|
| 1210 |
+
|
| 1211 |
+
Converted to upper case and filtered of anything but all letters
|
| 1212 |
+
except J.
|
| 1213 |
+
|
| 1214 |
+
key
|
| 1215 |
+
Short string for key; non-alphabetic letters, J and duplicated
|
| 1216 |
+
characters are ignored and then, if the length is less than 25
|
| 1217 |
+
characters, it is padded with other letters of the alphabet
|
| 1218 |
+
(in alphabetical order).
|
| 1219 |
+
|
| 1220 |
+
Returns
|
| 1221 |
+
=======
|
| 1222 |
+
|
| 1223 |
+
ct
|
| 1224 |
+
Ciphertext (all caps, no spaces).
|
| 1225 |
+
|
| 1226 |
+
Examples
|
| 1227 |
+
========
|
| 1228 |
+
|
| 1229 |
+
>>> from sympy.crypto.crypto import (
|
| 1230 |
+
... encipher_bifid5, decipher_bifid5)
|
| 1231 |
+
|
| 1232 |
+
"J" will be omitted unless it is replaced with something else:
|
| 1233 |
+
|
| 1234 |
+
>>> round_trip = lambda m, k: \
|
| 1235 |
+
... decipher_bifid5(encipher_bifid5(m, k), k)
|
| 1236 |
+
>>> key = 'a'
|
| 1237 |
+
>>> msg = "JOSIE"
|
| 1238 |
+
>>> round_trip(msg, key)
|
| 1239 |
+
'OSIE'
|
| 1240 |
+
>>> round_trip(msg.replace("J", "I"), key)
|
| 1241 |
+
'IOSIE'
|
| 1242 |
+
>>> j = "QIQ"
|
| 1243 |
+
>>> round_trip(msg.replace("J", j), key).replace(j, "J")
|
| 1244 |
+
'JOSIE'
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
Notes
|
| 1248 |
+
=====
|
| 1249 |
+
|
| 1250 |
+
The Bifid cipher was invented around 1901 by Felix Delastelle.
|
| 1251 |
+
It is a *fractional substitution* cipher, where letters are
|
| 1252 |
+
replaced by pairs of symbols from a smaller alphabet. The
|
| 1253 |
+
cipher uses a `5 \times 5` square filled with some ordering of the
|
| 1254 |
+
alphabet, except that "J" is replaced with "I" (this is a so-called
|
| 1255 |
+
Polybius square; there is a `6 \times 6` analog if you add back in
|
| 1256 |
+
"J" and also append onto the usual 26 letter alphabet, the digits
|
| 1257 |
+
0, 1, ..., 9).
|
| 1258 |
+
According to Helen Gaines' book *Cryptanalysis*, this type of cipher
|
| 1259 |
+
was used in the field by the German Army during World War I.
|
| 1260 |
+
|
| 1261 |
+
See Also
|
| 1262 |
+
========
|
| 1263 |
+
|
| 1264 |
+
decipher_bifid5, encipher_bifid
|
| 1265 |
+
|
| 1266 |
+
"""
|
| 1267 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
|
| 1268 |
+
key = padded_key(key, bifid5)
|
| 1269 |
+
return encipher_bifid(msg, '', key)
|
| 1270 |
+
|
| 1271 |
+
|
| 1272 |
+
def decipher_bifid5(msg, key):
|
| 1273 |
+
r"""
|
| 1274 |
+
Return the Bifid cipher decryption of ``msg``.
|
| 1275 |
+
|
| 1276 |
+
Explanation
|
| 1277 |
+
===========
|
| 1278 |
+
|
| 1279 |
+
This is the version of the Bifid cipher that uses the `5 \times 5`
|
| 1280 |
+
Polybius square; the letter "J" is ignored unless a ``key`` of
|
| 1281 |
+
length 25 is used.
|
| 1282 |
+
|
| 1283 |
+
Parameters
|
| 1284 |
+
==========
|
| 1285 |
+
|
| 1286 |
+
msg
|
| 1287 |
+
Ciphertext string.
|
| 1288 |
+
|
| 1289 |
+
key
|
| 1290 |
+
Short string for key; duplicated characters are ignored and if
|
| 1291 |
+
the length is less then 25 characters, it will be padded with
|
| 1292 |
+
other letters from the alphabet omitting "J".
|
| 1293 |
+
Non-alphabetic characters are ignored.
|
| 1294 |
+
|
| 1295 |
+
Returns
|
| 1296 |
+
=======
|
| 1297 |
+
|
| 1298 |
+
plaintext
|
| 1299 |
+
Plaintext from Bifid5 cipher (all caps, no spaces).
|
| 1300 |
+
|
| 1301 |
+
Examples
|
| 1302 |
+
========
|
| 1303 |
+
|
| 1304 |
+
>>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
|
| 1305 |
+
>>> key = "gold bug"
|
| 1306 |
+
>>> encipher_bifid5('meet me on friday', key)
|
| 1307 |
+
'IEILEHFSTSFXEE'
|
| 1308 |
+
>>> encipher_bifid5('meet me on monday', key)
|
| 1309 |
+
'IEILHHFSTSFQYE'
|
| 1310 |
+
>>> decipher_bifid5(_, key)
|
| 1311 |
+
'MEETMEONMONDAY'
|
| 1312 |
+
|
| 1313 |
+
"""
|
| 1314 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
|
| 1315 |
+
key = padded_key(key, bifid5)
|
| 1316 |
+
return decipher_bifid(msg, '', key)
|
| 1317 |
+
|
| 1318 |
+
|
| 1319 |
+
def bifid5_square(key=None):
|
| 1320 |
+
r"""
|
| 1321 |
+
5x5 Polybius square.
|
| 1322 |
+
|
| 1323 |
+
Produce the Polybius square for the `5 \times 5` Bifid cipher.
|
| 1324 |
+
|
| 1325 |
+
Examples
|
| 1326 |
+
========
|
| 1327 |
+
|
| 1328 |
+
>>> from sympy.crypto.crypto import bifid5_square
|
| 1329 |
+
>>> bifid5_square("gold bug")
|
| 1330 |
+
Matrix([
|
| 1331 |
+
[G, O, L, D, B],
|
| 1332 |
+
[U, A, C, E, F],
|
| 1333 |
+
[H, I, K, M, N],
|
| 1334 |
+
[P, Q, R, S, T],
|
| 1335 |
+
[V, W, X, Y, Z]])
|
| 1336 |
+
|
| 1337 |
+
"""
|
| 1338 |
+
if not key:
|
| 1339 |
+
key = bifid5
|
| 1340 |
+
else:
|
| 1341 |
+
_, key, _ = _prep('', key.upper(), None, bifid5)
|
| 1342 |
+
key = padded_key(key, bifid5)
|
| 1343 |
+
return bifid_square(key)
|
| 1344 |
+
|
| 1345 |
+
|
| 1346 |
+
def encipher_bifid6(msg, key):
|
| 1347 |
+
r"""
|
| 1348 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
| 1349 |
+
returns the ciphertext.
|
| 1350 |
+
|
| 1351 |
+
This is the version of the Bifid cipher that uses the `6 \times 6`
|
| 1352 |
+
Polybius square.
|
| 1353 |
+
|
| 1354 |
+
Parameters
|
| 1355 |
+
==========
|
| 1356 |
+
|
| 1357 |
+
msg
|
| 1358 |
+
Plaintext string (digits okay).
|
| 1359 |
+
|
| 1360 |
+
key
|
| 1361 |
+
Short string for key (digits okay).
|
| 1362 |
+
|
| 1363 |
+
If ``key`` is less than 36 characters long, the square will be
|
| 1364 |
+
filled with letters A through Z and digits 0 through 9.
|
| 1365 |
+
|
| 1366 |
+
Returns
|
| 1367 |
+
=======
|
| 1368 |
+
|
| 1369 |
+
ciphertext
|
| 1370 |
+
Ciphertext from Bifid cipher (all caps, no spaces).
|
| 1371 |
+
|
| 1372 |
+
See Also
|
| 1373 |
+
========
|
| 1374 |
+
|
| 1375 |
+
decipher_bifid6, encipher_bifid
|
| 1376 |
+
|
| 1377 |
+
"""
|
| 1378 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
|
| 1379 |
+
key = padded_key(key, bifid6)
|
| 1380 |
+
return encipher_bifid(msg, '', key)
|
| 1381 |
+
|
| 1382 |
+
|
| 1383 |
+
def decipher_bifid6(msg, key):
|
| 1384 |
+
r"""
|
| 1385 |
+
Performs the Bifid cipher decryption on ciphertext ``msg``, and
|
| 1386 |
+
returns the plaintext.
|
| 1387 |
+
|
| 1388 |
+
This is the version of the Bifid cipher that uses the `6 \times 6`
|
| 1389 |
+
Polybius square.
|
| 1390 |
+
|
| 1391 |
+
Parameters
|
| 1392 |
+
==========
|
| 1393 |
+
|
| 1394 |
+
msg
|
| 1395 |
+
Ciphertext string (digits okay); converted to upper case
|
| 1396 |
+
|
| 1397 |
+
key
|
| 1398 |
+
Short string for key (digits okay).
|
| 1399 |
+
|
| 1400 |
+
If ``key`` is less than 36 characters long, the square will be
|
| 1401 |
+
filled with letters A through Z and digits 0 through 9.
|
| 1402 |
+
All letters are converted to uppercase.
|
| 1403 |
+
|
| 1404 |
+
Returns
|
| 1405 |
+
=======
|
| 1406 |
+
|
| 1407 |
+
plaintext
|
| 1408 |
+
Plaintext from Bifid cipher (all caps, no spaces).
|
| 1409 |
+
|
| 1410 |
+
Examples
|
| 1411 |
+
========
|
| 1412 |
+
|
| 1413 |
+
>>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
|
| 1414 |
+
>>> key = "gold bug"
|
| 1415 |
+
>>> encipher_bifid6('meet me on monday at 8am', key)
|
| 1416 |
+
'KFKLJJHF5MMMKTFRGPL'
|
| 1417 |
+
>>> decipher_bifid6(_, key)
|
| 1418 |
+
'MEETMEONMONDAYAT8AM'
|
| 1419 |
+
|
| 1420 |
+
"""
|
| 1421 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
|
| 1422 |
+
key = padded_key(key, bifid6)
|
| 1423 |
+
return decipher_bifid(msg, '', key)
|
| 1424 |
+
|
| 1425 |
+
|
| 1426 |
+
def bifid6_square(key=None):
|
| 1427 |
+
r"""
|
| 1428 |
+
6x6 Polybius square.
|
| 1429 |
+
|
| 1430 |
+
Produces the Polybius square for the `6 \times 6` Bifid cipher.
|
| 1431 |
+
Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".
|
| 1432 |
+
|
| 1433 |
+
Examples
|
| 1434 |
+
========
|
| 1435 |
+
|
| 1436 |
+
>>> from sympy.crypto.crypto import bifid6_square
|
| 1437 |
+
>>> key = "gold bug"
|
| 1438 |
+
>>> bifid6_square(key)
|
| 1439 |
+
Matrix([
|
| 1440 |
+
[G, O, L, D, B, U],
|
| 1441 |
+
[A, C, E, F, H, I],
|
| 1442 |
+
[J, K, M, N, P, Q],
|
| 1443 |
+
[R, S, T, V, W, X],
|
| 1444 |
+
[Y, Z, 0, 1, 2, 3],
|
| 1445 |
+
[4, 5, 6, 7, 8, 9]])
|
| 1446 |
+
|
| 1447 |
+
"""
|
| 1448 |
+
if not key:
|
| 1449 |
+
key = bifid6
|
| 1450 |
+
else:
|
| 1451 |
+
_, key, _ = _prep('', key.upper(), None, bifid6)
|
| 1452 |
+
key = padded_key(key, bifid6)
|
| 1453 |
+
return bifid_square(key)
|
| 1454 |
+
|
| 1455 |
+
|
| 1456 |
+
#################### RSA #############################
|
| 1457 |
+
|
| 1458 |
+
def _decipher_rsa_crt(i, d, factors):
|
| 1459 |
+
"""Decipher RSA using chinese remainder theorem from the information
|
| 1460 |
+
of the relatively-prime factors of the modulus.
|
| 1461 |
+
|
| 1462 |
+
Parameters
|
| 1463 |
+
==========
|
| 1464 |
+
|
| 1465 |
+
i : integer
|
| 1466 |
+
Ciphertext
|
| 1467 |
+
|
| 1468 |
+
d : integer
|
| 1469 |
+
The exponent component.
|
| 1470 |
+
|
| 1471 |
+
factors : list of relatively-prime integers
|
| 1472 |
+
The integers given must be coprime and the product must equal
|
| 1473 |
+
the modulus component of the original RSA key.
|
| 1474 |
+
|
| 1475 |
+
Examples
|
| 1476 |
+
========
|
| 1477 |
+
|
| 1478 |
+
How to decrypt RSA with CRT:
|
| 1479 |
+
|
| 1480 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
| 1481 |
+
>>> primes = [61, 53]
|
| 1482 |
+
>>> e = 17
|
| 1483 |
+
>>> args = primes + [e]
|
| 1484 |
+
>>> puk = rsa_public_key(*args)
|
| 1485 |
+
>>> prk = rsa_private_key(*args)
|
| 1486 |
+
|
| 1487 |
+
>>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt
|
| 1488 |
+
>>> msg = 65
|
| 1489 |
+
>>> crt_primes = primes
|
| 1490 |
+
>>> encrypted = encipher_rsa(msg, puk)
|
| 1491 |
+
>>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes)
|
| 1492 |
+
>>> decrypted
|
| 1493 |
+
65
|
| 1494 |
+
"""
|
| 1495 |
+
moduluses = [pow(i, d, p) for p in factors]
|
| 1496 |
+
|
| 1497 |
+
result = crt(factors, moduluses)
|
| 1498 |
+
if not result:
|
| 1499 |
+
raise ValueError("CRT failed")
|
| 1500 |
+
return result[0]
|
| 1501 |
+
|
| 1502 |
+
|
| 1503 |
+
def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None):
|
| 1504 |
+
r"""A private subroutine to generate RSA key
|
| 1505 |
+
|
| 1506 |
+
Parameters
|
| 1507 |
+
==========
|
| 1508 |
+
|
| 1509 |
+
public, private : bool, optional
|
| 1510 |
+
Flag to generate either a public key, a private key.
|
| 1511 |
+
|
| 1512 |
+
totient : 'Euler' or 'Carmichael'
|
| 1513 |
+
Different notation used for totient.
|
| 1514 |
+
|
| 1515 |
+
multipower : bool, optional
|
| 1516 |
+
Flag to bypass warning for multipower RSA.
|
| 1517 |
+
"""
|
| 1518 |
+
|
| 1519 |
+
if len(args) < 2:
|
| 1520 |
+
return False
|
| 1521 |
+
|
| 1522 |
+
if totient not in ('Euler', 'Carmichael'):
|
| 1523 |
+
raise ValueError(
|
| 1524 |
+
"The argument totient={} should either be " \
|
| 1525 |
+
"'Euler', 'Carmichalel'." \
|
| 1526 |
+
.format(totient))
|
| 1527 |
+
|
| 1528 |
+
if totient == 'Euler':
|
| 1529 |
+
_totient = _euler
|
| 1530 |
+
else:
|
| 1531 |
+
_totient = _carmichael
|
| 1532 |
+
|
| 1533 |
+
if index is not None:
|
| 1534 |
+
index = as_int(index)
|
| 1535 |
+
if totient != 'Carmichael':
|
| 1536 |
+
raise ValueError(
|
| 1537 |
+
"Setting the 'index' keyword argument requires totient"
|
| 1538 |
+
"notation to be specified as 'Carmichael'.")
|
| 1539 |
+
|
| 1540 |
+
primes, e = args[:-1], args[-1]
|
| 1541 |
+
|
| 1542 |
+
if not all(isprime(p) for p in primes):
|
| 1543 |
+
new_primes = []
|
| 1544 |
+
for i in primes:
|
| 1545 |
+
new_primes.extend(factorint(i, multiple=True))
|
| 1546 |
+
primes = new_primes
|
| 1547 |
+
|
| 1548 |
+
n = reduce(lambda i, j: i*j, primes)
|
| 1549 |
+
|
| 1550 |
+
tally = multiset(primes)
|
| 1551 |
+
if all(v == 1 for v in tally.values()):
|
| 1552 |
+
phi = int(_totient(tally))
|
| 1553 |
+
|
| 1554 |
+
else:
|
| 1555 |
+
if not multipower:
|
| 1556 |
+
NonInvertibleCipherWarning(
|
| 1557 |
+
'Non-distinctive primes found in the factors {}. '
|
| 1558 |
+
'The cipher may not be decryptable for some numbers '
|
| 1559 |
+
'in the complete residue system Z[{}], but the cipher '
|
| 1560 |
+
'can still be valid if you restrict the domain to be '
|
| 1561 |
+
'the reduced residue system Z*[{}]. You can pass '
|
| 1562 |
+
'the flag multipower=True if you want to suppress this '
|
| 1563 |
+
'warning.'
|
| 1564 |
+
.format(primes, n, n)
|
| 1565 |
+
# stacklevel=4 because most users will call a function that
|
| 1566 |
+
# calls this function
|
| 1567 |
+
).warn(stacklevel=4)
|
| 1568 |
+
phi = int(_totient(tally))
|
| 1569 |
+
|
| 1570 |
+
if gcd(e, phi) == 1:
|
| 1571 |
+
if public and not private:
|
| 1572 |
+
if isinstance(index, int):
|
| 1573 |
+
e = e % phi
|
| 1574 |
+
e += index * phi
|
| 1575 |
+
return n, e
|
| 1576 |
+
|
| 1577 |
+
if private and not public:
|
| 1578 |
+
d = invert(e, phi)
|
| 1579 |
+
if isinstance(index, int):
|
| 1580 |
+
d += index * phi
|
| 1581 |
+
return n, d
|
| 1582 |
+
|
| 1583 |
+
return False
|
| 1584 |
+
|
| 1585 |
+
|
| 1586 |
+
def rsa_public_key(*args, **kwargs):
|
| 1587 |
+
r"""Return the RSA *public key* pair, `(n, e)`
|
| 1588 |
+
|
| 1589 |
+
Parameters
|
| 1590 |
+
==========
|
| 1591 |
+
|
| 1592 |
+
args : naturals
|
| 1593 |
+
If specified as `p, q, e` where `p` and `q` are distinct primes
|
| 1594 |
+
and `e` is a desired public exponent of the RSA, `n = p q` and
|
| 1595 |
+
`e` will be verified against the totient
|
| 1596 |
+
`\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient)
|
| 1597 |
+
to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`.
|
| 1598 |
+
|
| 1599 |
+
If specified as `p_1, p_2, \dots, p_n, e` where
|
| 1600 |
+
`p_1, p_2, \dots, p_n` are specified as primes,
|
| 1601 |
+
and `e` is specified as a desired public exponent of the RSA,
|
| 1602 |
+
it will be able to form a multi-prime RSA, which is a more
|
| 1603 |
+
generalized form of the popular 2-prime RSA.
|
| 1604 |
+
|
| 1605 |
+
It can also be possible to form a single-prime RSA by specifying
|
| 1606 |
+
the argument as `p, e`, which can be considered a trivial case
|
| 1607 |
+
of a multiprime RSA.
|
| 1608 |
+
|
| 1609 |
+
Furthermore, it can be possible to form a multi-power RSA by
|
| 1610 |
+
specifying two or more pairs of the primes to be same.
|
| 1611 |
+
However, unlike the two-distinct prime RSA or multi-prime
|
| 1612 |
+
RSA, not every numbers in the complete residue system
|
| 1613 |
+
(`\mathbb{Z}_n`) will be decryptable since the mapping
|
| 1614 |
+
`\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}`
|
| 1615 |
+
will not be bijective.
|
| 1616 |
+
(Only except for the trivial case when
|
| 1617 |
+
`e = 1`
|
| 1618 |
+
or more generally,
|
| 1619 |
+
|
| 1620 |
+
.. math::
|
| 1621 |
+
e \in \left \{ 1 + k \lambda(n)
|
| 1622 |
+
\mid k \in \mathbb{Z} \land k \geq 0 \right \}
|
| 1623 |
+
|
| 1624 |
+
when RSA reduces to the identity.)
|
| 1625 |
+
However, the RSA can still be decryptable for the numbers in the
|
| 1626 |
+
reduced residue system (`\mathbb{Z}_n^{\times}`), since the
|
| 1627 |
+
mapping
|
| 1628 |
+
`\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}`
|
| 1629 |
+
can still be bijective.
|
| 1630 |
+
|
| 1631 |
+
If you pass a non-prime integer to the arguments
|
| 1632 |
+
`p_1, p_2, \dots, p_n`, the particular number will be
|
| 1633 |
+
prime-factored and it will become either a multi-prime RSA or a
|
| 1634 |
+
multi-power RSA in its canonical form, depending on whether the
|
| 1635 |
+
product equals its radical or not.
|
| 1636 |
+
`p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)`
|
| 1637 |
+
|
| 1638 |
+
totient : bool, optional
|
| 1639 |
+
If ``'Euler'``, it uses Euler's totient `\phi(n)` which is
|
| 1640 |
+
:meth:`sympy.functions.combinatorial.numbers.totient` in SymPy.
|
| 1641 |
+
|
| 1642 |
+
If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)`
|
| 1643 |
+
which is :meth:`sympy.functions.combinatorial.numbers.reduced_totient` in SymPy.
|
| 1644 |
+
|
| 1645 |
+
Unlike private key generation, this is a trivial keyword for
|
| 1646 |
+
public key generation because
|
| 1647 |
+
`\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`.
|
| 1648 |
+
|
| 1649 |
+
index : nonnegative integer, optional
|
| 1650 |
+
Returns an arbitrary solution of a RSA public key at the index
|
| 1651 |
+
specified at `0, 1, 2, \dots`. This parameter needs to be
|
| 1652 |
+
specified along with ``totient='Carmichael'``.
|
| 1653 |
+
|
| 1654 |
+
Similarly to the non-uniquenss of a RSA private key as described
|
| 1655 |
+
in the ``index`` parameter documentation in
|
| 1656 |
+
:meth:`rsa_private_key`, RSA public key is also not unique and
|
| 1657 |
+
there is an infinite number of RSA public exponents which
|
| 1658 |
+
can behave in the same manner.
|
| 1659 |
+
|
| 1660 |
+
From any given RSA public exponent `e`, there are can be an
|
| 1661 |
+
another RSA public exponent `e + k \lambda(n)` where `k` is an
|
| 1662 |
+
integer, `\lambda` is a Carmichael's totient function.
|
| 1663 |
+
|
| 1664 |
+
However, considering only the positive cases, there can be
|
| 1665 |
+
a principal solution of a RSA public exponent `e_0` in
|
| 1666 |
+
`0 < e_0 < \lambda(n)`, and all the other solutions
|
| 1667 |
+
can be canonicalzed in a form of `e_0 + k \lambda(n)`.
|
| 1668 |
+
|
| 1669 |
+
``index`` specifies the `k` notation to yield any possible value
|
| 1670 |
+
an RSA public key can have.
|
| 1671 |
+
|
| 1672 |
+
An example of computing any arbitrary RSA public key:
|
| 1673 |
+
|
| 1674 |
+
>>> from sympy.crypto.crypto import rsa_public_key
|
| 1675 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0)
|
| 1676 |
+
(3233, 17)
|
| 1677 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1)
|
| 1678 |
+
(3233, 797)
|
| 1679 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2)
|
| 1680 |
+
(3233, 1577)
|
| 1681 |
+
|
| 1682 |
+
multipower : bool, optional
|
| 1683 |
+
Any pair of non-distinct primes found in the RSA specification
|
| 1684 |
+
will restrict the domain of the cryptosystem, as noted in the
|
| 1685 |
+
explanation of the parameter ``args``.
|
| 1686 |
+
|
| 1687 |
+
SymPy RSA key generator may give a warning before dispatching it
|
| 1688 |
+
as a multi-power RSA, however, you can disable the warning if
|
| 1689 |
+
you pass ``True`` to this keyword.
|
| 1690 |
+
|
| 1691 |
+
Returns
|
| 1692 |
+
=======
|
| 1693 |
+
|
| 1694 |
+
(n, e) : int, int
|
| 1695 |
+
`n` is a product of any arbitrary number of primes given as
|
| 1696 |
+
the argument.
|
| 1697 |
+
|
| 1698 |
+
`e` is relatively prime (coprime) to the Euler totient
|
| 1699 |
+
`\phi(n)`.
|
| 1700 |
+
|
| 1701 |
+
False
|
| 1702 |
+
Returned if less than two arguments are given, or `e` is
|
| 1703 |
+
not relatively prime to the modulus.
|
| 1704 |
+
|
| 1705 |
+
Examples
|
| 1706 |
+
========
|
| 1707 |
+
|
| 1708 |
+
>>> from sympy.crypto.crypto import rsa_public_key
|
| 1709 |
+
|
| 1710 |
+
A public key of a two-prime RSA:
|
| 1711 |
+
|
| 1712 |
+
>>> p, q, e = 3, 5, 7
|
| 1713 |
+
>>> rsa_public_key(p, q, e)
|
| 1714 |
+
(15, 7)
|
| 1715 |
+
>>> rsa_public_key(p, q, 30)
|
| 1716 |
+
False
|
| 1717 |
+
|
| 1718 |
+
A public key of a multiprime RSA:
|
| 1719 |
+
|
| 1720 |
+
>>> primes = [2, 3, 5, 7, 11, 13]
|
| 1721 |
+
>>> e = 7
|
| 1722 |
+
>>> args = primes + [e]
|
| 1723 |
+
>>> rsa_public_key(*args)
|
| 1724 |
+
(30030, 7)
|
| 1725 |
+
|
| 1726 |
+
Notes
|
| 1727 |
+
=====
|
| 1728 |
+
|
| 1729 |
+
Although the RSA can be generalized over any modulus `n`, using
|
| 1730 |
+
two large primes had became the most popular specification because a
|
| 1731 |
+
product of two large primes is usually the hardest to factor
|
| 1732 |
+
relatively to the digits of `n` can have.
|
| 1733 |
+
|
| 1734 |
+
However, it may need further understanding of the time complexities
|
| 1735 |
+
of each prime-factoring algorithms to verify the claim.
|
| 1736 |
+
|
| 1737 |
+
See Also
|
| 1738 |
+
========
|
| 1739 |
+
|
| 1740 |
+
rsa_private_key
|
| 1741 |
+
encipher_rsa
|
| 1742 |
+
decipher_rsa
|
| 1743 |
+
|
| 1744 |
+
References
|
| 1745 |
+
==========
|
| 1746 |
+
|
| 1747 |
+
.. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
|
| 1748 |
+
|
| 1749 |
+
.. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
|
| 1750 |
+
|
| 1751 |
+
.. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
|
| 1752 |
+
|
| 1753 |
+
.. [4] https://www.itiis.org/digital-library/manuscript/1381
|
| 1754 |
+
"""
|
| 1755 |
+
return _rsa_key(*args, public=True, private=False, **kwargs)
|
| 1756 |
+
|
| 1757 |
+
|
| 1758 |
+
def rsa_private_key(*args, **kwargs):
|
| 1759 |
+
r"""Return the RSA *private key* pair, `(n, d)`
|
| 1760 |
+
|
| 1761 |
+
Parameters
|
| 1762 |
+
==========
|
| 1763 |
+
|
| 1764 |
+
args : naturals
|
| 1765 |
+
The keyword is identical to the ``args`` in
|
| 1766 |
+
:meth:`rsa_public_key`.
|
| 1767 |
+
|
| 1768 |
+
totient : bool, optional
|
| 1769 |
+
If ``'Euler'``, it uses Euler's totient convention `\phi(n)`
|
| 1770 |
+
which is :meth:`sympy.functions.combinatorial.numbers.totient` in SymPy.
|
| 1771 |
+
|
| 1772 |
+
If ``'Carmichael'``, it uses Carmichael's totient convention
|
| 1773 |
+
`\lambda(n)` which is
|
| 1774 |
+
:meth:`sympy.functions.combinatorial.numbers.reduced_totient` in SymPy.
|
| 1775 |
+
|
| 1776 |
+
There can be some output differences for private key generation
|
| 1777 |
+
as examples below.
|
| 1778 |
+
|
| 1779 |
+
Example using Euler's totient:
|
| 1780 |
+
|
| 1781 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
| 1782 |
+
>>> rsa_private_key(61, 53, 17, totient='Euler')
|
| 1783 |
+
(3233, 2753)
|
| 1784 |
+
|
| 1785 |
+
Example using Carmichael's totient:
|
| 1786 |
+
|
| 1787 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
| 1788 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael')
|
| 1789 |
+
(3233, 413)
|
| 1790 |
+
|
| 1791 |
+
index : nonnegative integer, optional
|
| 1792 |
+
Returns an arbitrary solution of a RSA private key at the index
|
| 1793 |
+
specified at `0, 1, 2, \dots`. This parameter needs to be
|
| 1794 |
+
specified along with ``totient='Carmichael'``.
|
| 1795 |
+
|
| 1796 |
+
RSA private exponent is a non-unique solution of
|
| 1797 |
+
`e d \mod \lambda(n) = 1` and it is possible in any form of
|
| 1798 |
+
`d + k \lambda(n)`, where `d` is an another
|
| 1799 |
+
already-computed private exponent, and `\lambda` is a
|
| 1800 |
+
Carmichael's totient function, and `k` is any integer.
|
| 1801 |
+
|
| 1802 |
+
However, considering only the positive cases, there can be
|
| 1803 |
+
a principal solution of a RSA private exponent `d_0` in
|
| 1804 |
+
`0 < d_0 < \lambda(n)`, and all the other solutions
|
| 1805 |
+
can be canonicalzed in a form of `d_0 + k \lambda(n)`.
|
| 1806 |
+
|
| 1807 |
+
``index`` specifies the `k` notation to yield any possible value
|
| 1808 |
+
an RSA private key can have.
|
| 1809 |
+
|
| 1810 |
+
An example of computing any arbitrary RSA private key:
|
| 1811 |
+
|
| 1812 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
| 1813 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0)
|
| 1814 |
+
(3233, 413)
|
| 1815 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1)
|
| 1816 |
+
(3233, 1193)
|
| 1817 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2)
|
| 1818 |
+
(3233, 1973)
|
| 1819 |
+
|
| 1820 |
+
multipower : bool, optional
|
| 1821 |
+
The keyword is identical to the ``multipower`` in
|
| 1822 |
+
:meth:`rsa_public_key`.
|
| 1823 |
+
|
| 1824 |
+
Returns
|
| 1825 |
+
=======
|
| 1826 |
+
|
| 1827 |
+
(n, d) : int, int
|
| 1828 |
+
`n` is a product of any arbitrary number of primes given as
|
| 1829 |
+
the argument.
|
| 1830 |
+
|
| 1831 |
+
`d` is the inverse of `e` (mod `\phi(n)`) where `e` is the
|
| 1832 |
+
exponent given, and `\phi` is a Euler totient.
|
| 1833 |
+
|
| 1834 |
+
False
|
| 1835 |
+
Returned if less than two arguments are given, or `e` is
|
| 1836 |
+
not relatively prime to the totient of the modulus.
|
| 1837 |
+
|
| 1838 |
+
Examples
|
| 1839 |
+
========
|
| 1840 |
+
|
| 1841 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
| 1842 |
+
|
| 1843 |
+
A private key of a two-prime RSA:
|
| 1844 |
+
|
| 1845 |
+
>>> p, q, e = 3, 5, 7
|
| 1846 |
+
>>> rsa_private_key(p, q, e)
|
| 1847 |
+
(15, 7)
|
| 1848 |
+
>>> rsa_private_key(p, q, 30)
|
| 1849 |
+
False
|
| 1850 |
+
|
| 1851 |
+
A private key of a multiprime RSA:
|
| 1852 |
+
|
| 1853 |
+
>>> primes = [2, 3, 5, 7, 11, 13]
|
| 1854 |
+
>>> e = 7
|
| 1855 |
+
>>> args = primes + [e]
|
| 1856 |
+
>>> rsa_private_key(*args)
|
| 1857 |
+
(30030, 823)
|
| 1858 |
+
|
| 1859 |
+
See Also
|
| 1860 |
+
========
|
| 1861 |
+
|
| 1862 |
+
rsa_public_key
|
| 1863 |
+
encipher_rsa
|
| 1864 |
+
decipher_rsa
|
| 1865 |
+
|
| 1866 |
+
References
|
| 1867 |
+
==========
|
| 1868 |
+
|
| 1869 |
+
.. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
|
| 1870 |
+
|
| 1871 |
+
.. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
|
| 1872 |
+
|
| 1873 |
+
.. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
|
| 1874 |
+
|
| 1875 |
+
.. [4] https://www.itiis.org/digital-library/manuscript/1381
|
| 1876 |
+
"""
|
| 1877 |
+
return _rsa_key(*args, public=False, private=True, **kwargs)
|
| 1878 |
+
|
| 1879 |
+
|
| 1880 |
+
def _encipher_decipher_rsa(i, key, factors=None):
|
| 1881 |
+
n, d = key
|
| 1882 |
+
if not factors:
|
| 1883 |
+
return pow(i, d, n)
|
| 1884 |
+
|
| 1885 |
+
def _is_coprime_set(l):
|
| 1886 |
+
is_coprime_set = True
|
| 1887 |
+
for i in range(len(l)):
|
| 1888 |
+
for j in range(i+1, len(l)):
|
| 1889 |
+
if gcd(l[i], l[j]) != 1:
|
| 1890 |
+
is_coprime_set = False
|
| 1891 |
+
break
|
| 1892 |
+
return is_coprime_set
|
| 1893 |
+
|
| 1894 |
+
prod = reduce(lambda i, j: i*j, factors)
|
| 1895 |
+
if prod == n and _is_coprime_set(factors):
|
| 1896 |
+
return _decipher_rsa_crt(i, d, factors)
|
| 1897 |
+
return _encipher_decipher_rsa(i, key, factors=None)
|
| 1898 |
+
|
| 1899 |
+
|
| 1900 |
+
def encipher_rsa(i, key, factors=None):
|
| 1901 |
+
r"""Encrypt the plaintext with RSA.
|
| 1902 |
+
|
| 1903 |
+
Parameters
|
| 1904 |
+
==========
|
| 1905 |
+
|
| 1906 |
+
i : integer
|
| 1907 |
+
The plaintext to be encrypted for.
|
| 1908 |
+
|
| 1909 |
+
key : (n, e) where n, e are integers
|
| 1910 |
+
`n` is the modulus of the key and `e` is the exponent of the
|
| 1911 |
+
key. The encryption is computed by `i^e \bmod n`.
|
| 1912 |
+
|
| 1913 |
+
The key can either be a public key or a private key, however,
|
| 1914 |
+
the message encrypted by a public key can only be decrypted by
|
| 1915 |
+
a private key, and vice versa, as RSA is an asymmetric
|
| 1916 |
+
cryptography system.
|
| 1917 |
+
|
| 1918 |
+
factors : list of coprime integers
|
| 1919 |
+
This is identical to the keyword ``factors`` in
|
| 1920 |
+
:meth:`decipher_rsa`.
|
| 1921 |
+
|
| 1922 |
+
Notes
|
| 1923 |
+
=====
|
| 1924 |
+
|
| 1925 |
+
Some specifications may make the RSA not cryptographically
|
| 1926 |
+
meaningful.
|
| 1927 |
+
|
| 1928 |
+
For example, `0`, `1` will remain always same after taking any
|
| 1929 |
+
number of exponentiation, thus, should be avoided.
|
| 1930 |
+
|
| 1931 |
+
Furthermore, if `i^e < n`, `i` may easily be figured out by taking
|
| 1932 |
+
`e` th root.
|
| 1933 |
+
|
| 1934 |
+
And also, specifying the exponent as `1` or in more generalized form
|
| 1935 |
+
as `1 + k \lambda(n)` where `k` is an nonnegative integer,
|
| 1936 |
+
`\lambda` is a carmichael totient, the RSA becomes an identity
|
| 1937 |
+
mapping.
|
| 1938 |
+
|
| 1939 |
+
Examples
|
| 1940 |
+
========
|
| 1941 |
+
|
| 1942 |
+
>>> from sympy.crypto.crypto import encipher_rsa
|
| 1943 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
| 1944 |
+
|
| 1945 |
+
Public Key Encryption:
|
| 1946 |
+
|
| 1947 |
+
>>> p, q, e = 3, 5, 7
|
| 1948 |
+
>>> puk = rsa_public_key(p, q, e)
|
| 1949 |
+
>>> msg = 12
|
| 1950 |
+
>>> encipher_rsa(msg, puk)
|
| 1951 |
+
3
|
| 1952 |
+
|
| 1953 |
+
Private Key Encryption:
|
| 1954 |
+
|
| 1955 |
+
>>> p, q, e = 3, 5, 7
|
| 1956 |
+
>>> prk = rsa_private_key(p, q, e)
|
| 1957 |
+
>>> msg = 12
|
| 1958 |
+
>>> encipher_rsa(msg, prk)
|
| 1959 |
+
3
|
| 1960 |
+
|
| 1961 |
+
Encryption using chinese remainder theorem:
|
| 1962 |
+
|
| 1963 |
+
>>> encipher_rsa(msg, prk, factors=[p, q])
|
| 1964 |
+
3
|
| 1965 |
+
"""
|
| 1966 |
+
return _encipher_decipher_rsa(i, key, factors=factors)
|
| 1967 |
+
|
| 1968 |
+
|
| 1969 |
+
def decipher_rsa(i, key, factors=None):
|
| 1970 |
+
r"""Decrypt the ciphertext with RSA.
|
| 1971 |
+
|
| 1972 |
+
Parameters
|
| 1973 |
+
==========
|
| 1974 |
+
|
| 1975 |
+
i : integer
|
| 1976 |
+
The ciphertext to be decrypted for.
|
| 1977 |
+
|
| 1978 |
+
key : (n, d) where n, d are integers
|
| 1979 |
+
`n` is the modulus of the key and `d` is the exponent of the
|
| 1980 |
+
key. The decryption is computed by `i^d \bmod n`.
|
| 1981 |
+
|
| 1982 |
+
The key can either be a public key or a private key, however,
|
| 1983 |
+
the message encrypted by a public key can only be decrypted by
|
| 1984 |
+
a private key, and vice versa, as RSA is an asymmetric
|
| 1985 |
+
cryptography system.
|
| 1986 |
+
|
| 1987 |
+
factors : list of coprime integers
|
| 1988 |
+
As the modulus `n` created from RSA key generation is composed
|
| 1989 |
+
of arbitrary prime factors
|
| 1990 |
+
`n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where
|
| 1991 |
+
`p_1, p_2, \dots, p_n` are distinct primes and
|
| 1992 |
+
`k_1, k_2, \dots, k_n` are positive integers, chinese remainder
|
| 1993 |
+
theorem can be used to compute `i^d \bmod n` from the
|
| 1994 |
+
fragmented modulo operations like
|
| 1995 |
+
|
| 1996 |
+
.. math::
|
| 1997 |
+
i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots,
|
| 1998 |
+
i^d \bmod {p_n}^{k_n}
|
| 1999 |
+
|
| 2000 |
+
or like
|
| 2001 |
+
|
| 2002 |
+
.. math::
|
| 2003 |
+
i^d \bmod {p_1}^{k_1}{p_2}^{k_2},
|
| 2004 |
+
i^d \bmod {p_3}^{k_3}, \dots ,
|
| 2005 |
+
i^d \bmod {p_n}^{k_n}
|
| 2006 |
+
|
| 2007 |
+
as long as every moduli does not share any common divisor each
|
| 2008 |
+
other.
|
| 2009 |
+
|
| 2010 |
+
The raw primes used in generating the RSA key pair can be a good
|
| 2011 |
+
option.
|
| 2012 |
+
|
| 2013 |
+
Note that the speed advantage of using this is only viable for
|
| 2014 |
+
very large cases (Like 2048-bit RSA keys) since the
|
| 2015 |
+
overhead of using pure Python implementation of
|
| 2016 |
+
:meth:`sympy.ntheory.modular.crt` may overcompensate the
|
| 2017 |
+
theoretical speed advantage.
|
| 2018 |
+
|
| 2019 |
+
Notes
|
| 2020 |
+
=====
|
| 2021 |
+
|
| 2022 |
+
See the ``Notes`` section in the documentation of
|
| 2023 |
+
:meth:`encipher_rsa`
|
| 2024 |
+
|
| 2025 |
+
Examples
|
| 2026 |
+
========
|
| 2027 |
+
|
| 2028 |
+
>>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa
|
| 2029 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
| 2030 |
+
|
| 2031 |
+
Public Key Encryption and Decryption:
|
| 2032 |
+
|
| 2033 |
+
>>> p, q, e = 3, 5, 7
|
| 2034 |
+
>>> prk = rsa_private_key(p, q, e)
|
| 2035 |
+
>>> puk = rsa_public_key(p, q, e)
|
| 2036 |
+
>>> msg = 12
|
| 2037 |
+
>>> new_msg = encipher_rsa(msg, prk)
|
| 2038 |
+
>>> new_msg
|
| 2039 |
+
3
|
| 2040 |
+
>>> decipher_rsa(new_msg, puk)
|
| 2041 |
+
12
|
| 2042 |
+
|
| 2043 |
+
Private Key Encryption and Decryption:
|
| 2044 |
+
|
| 2045 |
+
>>> p, q, e = 3, 5, 7
|
| 2046 |
+
>>> prk = rsa_private_key(p, q, e)
|
| 2047 |
+
>>> puk = rsa_public_key(p, q, e)
|
| 2048 |
+
>>> msg = 12
|
| 2049 |
+
>>> new_msg = encipher_rsa(msg, puk)
|
| 2050 |
+
>>> new_msg
|
| 2051 |
+
3
|
| 2052 |
+
>>> decipher_rsa(new_msg, prk)
|
| 2053 |
+
12
|
| 2054 |
+
|
| 2055 |
+
Decryption using chinese remainder theorem:
|
| 2056 |
+
|
| 2057 |
+
>>> decipher_rsa(new_msg, prk, factors=[p, q])
|
| 2058 |
+
12
|
| 2059 |
+
|
| 2060 |
+
See Also
|
| 2061 |
+
========
|
| 2062 |
+
|
| 2063 |
+
encipher_rsa
|
| 2064 |
+
"""
|
| 2065 |
+
return _encipher_decipher_rsa(i, key, factors=factors)
|
| 2066 |
+
|
| 2067 |
+
|
| 2068 |
+
#################### kid krypto (kid RSA) #############################
|
| 2069 |
+
|
| 2070 |
+
|
| 2071 |
+
def kid_rsa_public_key(a, b, A, B):
|
| 2072 |
+
r"""
|
| 2073 |
+
Kid RSA is a version of RSA useful to teach grade school children
|
| 2074 |
+
since it does not involve exponentiation.
|
| 2075 |
+
|
| 2076 |
+
Explanation
|
| 2077 |
+
===========
|
| 2078 |
+
|
| 2079 |
+
Alice wants to talk to Bob. Bob generates keys as follows.
|
| 2080 |
+
Key generation:
|
| 2081 |
+
|
| 2082 |
+
* Select positive integers `a, b, A, B` at random.
|
| 2083 |
+
* Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
|
| 2084 |
+
`n = (e d - 1)//M`.
|
| 2085 |
+
* The *public key* is `(n, e)`. Bob sends these to Alice.
|
| 2086 |
+
* The *private key* is `(n, d)`, which Bob keeps secret.
|
| 2087 |
+
|
| 2088 |
+
Encryption: If `p` is the plaintext message then the
|
| 2089 |
+
ciphertext is `c = p e \pmod n`.
|
| 2090 |
+
|
| 2091 |
+
Decryption: If `c` is the ciphertext message then the
|
| 2092 |
+
plaintext is `p = c d \pmod n`.
|
| 2093 |
+
|
| 2094 |
+
Examples
|
| 2095 |
+
========
|
| 2096 |
+
|
| 2097 |
+
>>> from sympy.crypto.crypto import kid_rsa_public_key
|
| 2098 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
| 2099 |
+
>>> kid_rsa_public_key(a, b, A, B)
|
| 2100 |
+
(369, 58)
|
| 2101 |
+
|
| 2102 |
+
"""
|
| 2103 |
+
M = a*b - 1
|
| 2104 |
+
e = A*M + a
|
| 2105 |
+
d = B*M + b
|
| 2106 |
+
n = (e*d - 1)//M
|
| 2107 |
+
return n, e
|
| 2108 |
+
|
| 2109 |
+
|
| 2110 |
+
def kid_rsa_private_key(a, b, A, B):
|
| 2111 |
+
"""
|
| 2112 |
+
Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
|
| 2113 |
+
`n = (e d - 1) / M`. The *private key* is `d`, which Bob
|
| 2114 |
+
keeps secret.
|
| 2115 |
+
|
| 2116 |
+
Examples
|
| 2117 |
+
========
|
| 2118 |
+
|
| 2119 |
+
>>> from sympy.crypto.crypto import kid_rsa_private_key
|
| 2120 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
| 2121 |
+
>>> kid_rsa_private_key(a, b, A, B)
|
| 2122 |
+
(369, 70)
|
| 2123 |
+
|
| 2124 |
+
"""
|
| 2125 |
+
M = a*b - 1
|
| 2126 |
+
e = A*M + a
|
| 2127 |
+
d = B*M + b
|
| 2128 |
+
n = (e*d - 1)//M
|
| 2129 |
+
return n, d
|
| 2130 |
+
|
| 2131 |
+
|
| 2132 |
+
def encipher_kid_rsa(msg, key):
|
| 2133 |
+
"""
|
| 2134 |
+
Here ``msg`` is the plaintext and ``key`` is the public key.
|
| 2135 |
+
|
| 2136 |
+
Examples
|
| 2137 |
+
========
|
| 2138 |
+
|
| 2139 |
+
>>> from sympy.crypto.crypto import (
|
| 2140 |
+
... encipher_kid_rsa, kid_rsa_public_key)
|
| 2141 |
+
>>> msg = 200
|
| 2142 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
| 2143 |
+
>>> key = kid_rsa_public_key(a, b, A, B)
|
| 2144 |
+
>>> encipher_kid_rsa(msg, key)
|
| 2145 |
+
161
|
| 2146 |
+
|
| 2147 |
+
"""
|
| 2148 |
+
n, e = key
|
| 2149 |
+
return (msg*e) % n
|
| 2150 |
+
|
| 2151 |
+
|
| 2152 |
+
def decipher_kid_rsa(msg, key):
|
| 2153 |
+
"""
|
| 2154 |
+
Here ``msg`` is the plaintext and ``key`` is the private key.
|
| 2155 |
+
|
| 2156 |
+
Examples
|
| 2157 |
+
========
|
| 2158 |
+
|
| 2159 |
+
>>> from sympy.crypto.crypto import (
|
| 2160 |
+
... kid_rsa_public_key, kid_rsa_private_key,
|
| 2161 |
+
... decipher_kid_rsa, encipher_kid_rsa)
|
| 2162 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
| 2163 |
+
>>> d = kid_rsa_private_key(a, b, A, B)
|
| 2164 |
+
>>> msg = 200
|
| 2165 |
+
>>> pub = kid_rsa_public_key(a, b, A, B)
|
| 2166 |
+
>>> pri = kid_rsa_private_key(a, b, A, B)
|
| 2167 |
+
>>> ct = encipher_kid_rsa(msg, pub)
|
| 2168 |
+
>>> decipher_kid_rsa(ct, pri)
|
| 2169 |
+
200
|
| 2170 |
+
|
| 2171 |
+
"""
|
| 2172 |
+
n, d = key
|
| 2173 |
+
return (msg*d) % n
|
| 2174 |
+
|
| 2175 |
+
|
| 2176 |
+
#################### Morse Code ######################################
|
| 2177 |
+
|
| 2178 |
+
morse_char = {
|
| 2179 |
+
".-": "A", "-...": "B",
|
| 2180 |
+
"-.-.": "C", "-..": "D",
|
| 2181 |
+
".": "E", "..-.": "F",
|
| 2182 |
+
"--.": "G", "....": "H",
|
| 2183 |
+
"..": "I", ".---": "J",
|
| 2184 |
+
"-.-": "K", ".-..": "L",
|
| 2185 |
+
"--": "M", "-.": "N",
|
| 2186 |
+
"---": "O", ".--.": "P",
|
| 2187 |
+
"--.-": "Q", ".-.": "R",
|
| 2188 |
+
"...": "S", "-": "T",
|
| 2189 |
+
"..-": "U", "...-": "V",
|
| 2190 |
+
".--": "W", "-..-": "X",
|
| 2191 |
+
"-.--": "Y", "--..": "Z",
|
| 2192 |
+
"-----": "0", ".----": "1",
|
| 2193 |
+
"..---": "2", "...--": "3",
|
| 2194 |
+
"....-": "4", ".....": "5",
|
| 2195 |
+
"-....": "6", "--...": "7",
|
| 2196 |
+
"---..": "8", "----.": "9",
|
| 2197 |
+
".-.-.-": ".", "--..--": ",",
|
| 2198 |
+
"---...": ":", "-.-.-.": ";",
|
| 2199 |
+
"..--..": "?", "-....-": "-",
|
| 2200 |
+
"..--.-": "_", "-.--.": "(",
|
| 2201 |
+
"-.--.-": ")", ".----.": "'",
|
| 2202 |
+
"-...-": "=", ".-.-.": "+",
|
| 2203 |
+
"-..-.": "/", ".--.-.": "@",
|
| 2204 |
+
"...-..-": "$", "-.-.--": "!"}
|
| 2205 |
+
char_morse = {v: k for k, v in morse_char.items()}
|
| 2206 |
+
|
| 2207 |
+
|
| 2208 |
+
def encode_morse(msg, sep='|', mapping=None):
|
| 2209 |
+
"""
|
| 2210 |
+
Encodes a plaintext into popular Morse Code with letters
|
| 2211 |
+
separated by ``sep`` and words by a double ``sep``.
|
| 2212 |
+
|
| 2213 |
+
Examples
|
| 2214 |
+
========
|
| 2215 |
+
|
| 2216 |
+
>>> from sympy.crypto.crypto import encode_morse
|
| 2217 |
+
>>> msg = 'ATTACK RIGHT FLANK'
|
| 2218 |
+
>>> encode_morse(msg)
|
| 2219 |
+
'.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-'
|
| 2220 |
+
|
| 2221 |
+
References
|
| 2222 |
+
==========
|
| 2223 |
+
|
| 2224 |
+
.. [1] https://en.wikipedia.org/wiki/Morse_code
|
| 2225 |
+
|
| 2226 |
+
"""
|
| 2227 |
+
|
| 2228 |
+
mapping = mapping or char_morse
|
| 2229 |
+
assert sep not in mapping
|
| 2230 |
+
word_sep = 2*sep
|
| 2231 |
+
mapping[" "] = word_sep
|
| 2232 |
+
suffix = msg and msg[-1] in whitespace
|
| 2233 |
+
|
| 2234 |
+
# normalize whitespace
|
| 2235 |
+
msg = (' ' if word_sep else '').join(msg.split())
|
| 2236 |
+
# omit unmapped chars
|
| 2237 |
+
chars = set(''.join(msg.split()))
|
| 2238 |
+
ok = set(mapping.keys())
|
| 2239 |
+
msg = translate(msg, None, ''.join(chars - ok))
|
| 2240 |
+
|
| 2241 |
+
morsestring = []
|
| 2242 |
+
words = msg.split()
|
| 2243 |
+
for word in words:
|
| 2244 |
+
morseword = []
|
| 2245 |
+
for letter in word:
|
| 2246 |
+
morseletter = mapping[letter]
|
| 2247 |
+
morseword.append(morseletter)
|
| 2248 |
+
|
| 2249 |
+
word = sep.join(morseword)
|
| 2250 |
+
morsestring.append(word)
|
| 2251 |
+
|
| 2252 |
+
return word_sep.join(morsestring) + (word_sep if suffix else '')
|
| 2253 |
+
|
| 2254 |
+
|
| 2255 |
+
def decode_morse(msg, sep='|', mapping=None):
|
| 2256 |
+
"""
|
| 2257 |
+
Decodes a Morse Code with letters separated by ``sep``
|
| 2258 |
+
(default is '|') and words by `word_sep` (default is '||)
|
| 2259 |
+
into plaintext.
|
| 2260 |
+
|
| 2261 |
+
Examples
|
| 2262 |
+
========
|
| 2263 |
+
|
| 2264 |
+
>>> from sympy.crypto.crypto import decode_morse
|
| 2265 |
+
>>> mc = '--|---|...-|.||.|.-|...|-'
|
| 2266 |
+
>>> decode_morse(mc)
|
| 2267 |
+
'MOVE EAST'
|
| 2268 |
+
|
| 2269 |
+
References
|
| 2270 |
+
==========
|
| 2271 |
+
|
| 2272 |
+
.. [1] https://en.wikipedia.org/wiki/Morse_code
|
| 2273 |
+
|
| 2274 |
+
"""
|
| 2275 |
+
|
| 2276 |
+
mapping = mapping or morse_char
|
| 2277 |
+
word_sep = 2*sep
|
| 2278 |
+
characterstring = []
|
| 2279 |
+
words = msg.strip(word_sep).split(word_sep)
|
| 2280 |
+
for word in words:
|
| 2281 |
+
letters = word.split(sep)
|
| 2282 |
+
chars = [mapping[c] for c in letters]
|
| 2283 |
+
word = ''.join(chars)
|
| 2284 |
+
characterstring.append(word)
|
| 2285 |
+
rv = " ".join(characterstring)
|
| 2286 |
+
return rv
|
| 2287 |
+
|
| 2288 |
+
|
| 2289 |
+
#################### LFSRs ##########################################
|
| 2290 |
+
|
| 2291 |
+
|
| 2292 |
+
@doctest_depends_on(ground_types=['python', 'gmpy'])
|
| 2293 |
+
def lfsr_sequence(key, fill, n):
|
| 2294 |
+
r"""
|
| 2295 |
+
This function creates an LFSR sequence.
|
| 2296 |
+
|
| 2297 |
+
Parameters
|
| 2298 |
+
==========
|
| 2299 |
+
|
| 2300 |
+
key : list
|
| 2301 |
+
A list of finite field elements, `[c_0, c_1, \ldots, c_k].`
|
| 2302 |
+
|
| 2303 |
+
fill : list
|
| 2304 |
+
The list of the initial terms of the LFSR sequence,
|
| 2305 |
+
`[x_0, x_1, \ldots, x_k].`
|
| 2306 |
+
|
| 2307 |
+
n
|
| 2308 |
+
Number of terms of the sequence that the function returns.
|
| 2309 |
+
|
| 2310 |
+
Returns
|
| 2311 |
+
=======
|
| 2312 |
+
|
| 2313 |
+
L
|
| 2314 |
+
The LFSR sequence defined by
|
| 2315 |
+
`x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for
|
| 2316 |
+
`n \leq k`.
|
| 2317 |
+
|
| 2318 |
+
Notes
|
| 2319 |
+
=====
|
| 2320 |
+
|
| 2321 |
+
S. Golomb [G]_ gives a list of three statistical properties a
|
| 2322 |
+
sequence of numbers `a = \{a_n\}_{n=1}^\infty`,
|
| 2323 |
+
`a_n \in \{0,1\}`, should display to be considered
|
| 2324 |
+
"random". Define the autocorrelation of `a` to be
|
| 2325 |
+
|
| 2326 |
+
.. math::
|
| 2327 |
+
|
| 2328 |
+
C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}.
|
| 2329 |
+
|
| 2330 |
+
In the case where `a` is periodic with period
|
| 2331 |
+
`P` then this reduces to
|
| 2332 |
+
|
| 2333 |
+
.. math::
|
| 2334 |
+
|
| 2335 |
+
C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}.
|
| 2336 |
+
|
| 2337 |
+
Assume `a` is periodic with period `P`.
|
| 2338 |
+
|
| 2339 |
+
- balance:
|
| 2340 |
+
|
| 2341 |
+
.. math::
|
| 2342 |
+
|
| 2343 |
+
\left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1.
|
| 2344 |
+
|
| 2345 |
+
- low autocorrelation:
|
| 2346 |
+
|
| 2347 |
+
.. math::
|
| 2348 |
+
|
| 2349 |
+
C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.
|
| 2350 |
+
|
| 2351 |
+
(For sequences satisfying these first two properties, it is known
|
| 2352 |
+
that `\epsilon = -1/P` must hold.)
|
| 2353 |
+
|
| 2354 |
+
- proportional runs property: In each period, half the runs have
|
| 2355 |
+
length `1`, one-fourth have length `2`, etc.
|
| 2356 |
+
Moreover, there are as many runs of `1`'s as there are of
|
| 2357 |
+
`0`'s.
|
| 2358 |
+
|
| 2359 |
+
Examples
|
| 2360 |
+
========
|
| 2361 |
+
|
| 2362 |
+
>>> from sympy.crypto.crypto import lfsr_sequence
|
| 2363 |
+
>>> from sympy.polys.domains import FF
|
| 2364 |
+
>>> F = FF(2)
|
| 2365 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
| 2366 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
| 2367 |
+
>>> lfsr_sequence(key, fill, 10)
|
| 2368 |
+
[1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2,
|
| 2369 |
+
1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]
|
| 2370 |
+
|
| 2371 |
+
References
|
| 2372 |
+
==========
|
| 2373 |
+
|
| 2374 |
+
.. [G] Solomon Golomb, Shift register sequences, Aegean Park Press,
|
| 2375 |
+
Laguna Hills, Ca, 1967
|
| 2376 |
+
|
| 2377 |
+
"""
|
| 2378 |
+
if not isinstance(key, list):
|
| 2379 |
+
raise TypeError("key must be a list")
|
| 2380 |
+
if not isinstance(fill, list):
|
| 2381 |
+
raise TypeError("fill must be a list")
|
| 2382 |
+
p = key[0].modulus()
|
| 2383 |
+
F = FF(p)
|
| 2384 |
+
s = fill
|
| 2385 |
+
k = len(fill)
|
| 2386 |
+
L = []
|
| 2387 |
+
for i in range(n):
|
| 2388 |
+
s0 = s[:]
|
| 2389 |
+
L.append(s[0])
|
| 2390 |
+
s = s[1:k]
|
| 2391 |
+
x = sum(int(key[i]*s0[i]) for i in range(k))
|
| 2392 |
+
s.append(F(x))
|
| 2393 |
+
return L # use [int(x) for x in L] for int version
|
| 2394 |
+
|
| 2395 |
+
|
| 2396 |
+
def lfsr_autocorrelation(L, P, k):
|
| 2397 |
+
"""
|
| 2398 |
+
This function computes the LFSR autocorrelation function.
|
| 2399 |
+
|
| 2400 |
+
Parameters
|
| 2401 |
+
==========
|
| 2402 |
+
|
| 2403 |
+
L
|
| 2404 |
+
A periodic sequence of elements of `GF(2)`.
|
| 2405 |
+
L must have length larger than P.
|
| 2406 |
+
|
| 2407 |
+
P
|
| 2408 |
+
The period of L.
|
| 2409 |
+
|
| 2410 |
+
k : int
|
| 2411 |
+
An integer `k` (`0 < k < P`).
|
| 2412 |
+
|
| 2413 |
+
Returns
|
| 2414 |
+
=======
|
| 2415 |
+
|
| 2416 |
+
autocorrelation
|
| 2417 |
+
The k-th value of the autocorrelation of the LFSR L.
|
| 2418 |
+
|
| 2419 |
+
Examples
|
| 2420 |
+
========
|
| 2421 |
+
|
| 2422 |
+
>>> from sympy.crypto.crypto import (
|
| 2423 |
+
... lfsr_sequence, lfsr_autocorrelation)
|
| 2424 |
+
>>> from sympy.polys.domains import FF
|
| 2425 |
+
>>> F = FF(2)
|
| 2426 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
| 2427 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
| 2428 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2429 |
+
>>> lfsr_autocorrelation(s, 15, 7)
|
| 2430 |
+
-1/15
|
| 2431 |
+
>>> lfsr_autocorrelation(s, 15, 0)
|
| 2432 |
+
1
|
| 2433 |
+
|
| 2434 |
+
"""
|
| 2435 |
+
if not isinstance(L, list):
|
| 2436 |
+
raise TypeError("L (=%s) must be a list" % L)
|
| 2437 |
+
P = int(P)
|
| 2438 |
+
k = int(k)
|
| 2439 |
+
L0 = L[:P] # slices makes a copy
|
| 2440 |
+
L1 = L0 + L0[:k]
|
| 2441 |
+
L2 = [(-1)**(int(L1[i]) + int(L1[i + k])) for i in range(P)]
|
| 2442 |
+
tot = sum(L2)
|
| 2443 |
+
return Rational(tot, P)
|
| 2444 |
+
|
| 2445 |
+
|
| 2446 |
+
def lfsr_connection_polynomial(s):
|
| 2447 |
+
"""
|
| 2448 |
+
This function computes the LFSR connection polynomial.
|
| 2449 |
+
|
| 2450 |
+
Parameters
|
| 2451 |
+
==========
|
| 2452 |
+
|
| 2453 |
+
s
|
| 2454 |
+
A sequence of elements of even length, with entries in a finite
|
| 2455 |
+
field.
|
| 2456 |
+
|
| 2457 |
+
Returns
|
| 2458 |
+
=======
|
| 2459 |
+
|
| 2460 |
+
C(x)
|
| 2461 |
+
The connection polynomial of a minimal LFSR yielding s.
|
| 2462 |
+
|
| 2463 |
+
This implements the algorithm in section 3 of J. L. Massey's
|
| 2464 |
+
article [M]_.
|
| 2465 |
+
|
| 2466 |
+
Examples
|
| 2467 |
+
========
|
| 2468 |
+
|
| 2469 |
+
>>> from sympy.crypto.crypto import (
|
| 2470 |
+
... lfsr_sequence, lfsr_connection_polynomial)
|
| 2471 |
+
>>> from sympy.polys.domains import FF
|
| 2472 |
+
>>> F = FF(2)
|
| 2473 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
| 2474 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
| 2475 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2476 |
+
>>> lfsr_connection_polynomial(s)
|
| 2477 |
+
x**4 + x + 1
|
| 2478 |
+
>>> fill = [F(1), F(0), F(0), F(1)]
|
| 2479 |
+
>>> key = [F(1), F(1), F(0), F(1)]
|
| 2480 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2481 |
+
>>> lfsr_connection_polynomial(s)
|
| 2482 |
+
x**3 + 1
|
| 2483 |
+
>>> fill = [F(1), F(0), F(1)]
|
| 2484 |
+
>>> key = [F(1), F(1), F(0)]
|
| 2485 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2486 |
+
>>> lfsr_connection_polynomial(s)
|
| 2487 |
+
x**3 + x**2 + 1
|
| 2488 |
+
>>> fill = [F(1), F(0), F(1)]
|
| 2489 |
+
>>> key = [F(1), F(0), F(1)]
|
| 2490 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2491 |
+
>>> lfsr_connection_polynomial(s)
|
| 2492 |
+
x**3 + x + 1
|
| 2493 |
+
|
| 2494 |
+
References
|
| 2495 |
+
==========
|
| 2496 |
+
|
| 2497 |
+
.. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding."
|
| 2498 |
+
IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127,
|
| 2499 |
+
Jan 1969.
|
| 2500 |
+
|
| 2501 |
+
"""
|
| 2502 |
+
# Initialization:
|
| 2503 |
+
p = s[0].modulus()
|
| 2504 |
+
x = Symbol("x")
|
| 2505 |
+
C = 1*x**0
|
| 2506 |
+
B = 1*x**0
|
| 2507 |
+
m = 1
|
| 2508 |
+
b = 1*x**0
|
| 2509 |
+
L = 0
|
| 2510 |
+
N = 0
|
| 2511 |
+
while N < len(s):
|
| 2512 |
+
if L > 0:
|
| 2513 |
+
dC = Poly(C).degree()
|
| 2514 |
+
r = min(L + 1, dC + 1)
|
| 2515 |
+
coeffsC = [C.subs(x, 0)] + [C.coeff(x**i)
|
| 2516 |
+
for i in range(1, dC + 1)]
|
| 2517 |
+
d = (int(s[N]) + sum(coeffsC[i]*int(s[N - i])
|
| 2518 |
+
for i in range(1, r))) % p
|
| 2519 |
+
if L == 0:
|
| 2520 |
+
d = int(s[N])*x**0
|
| 2521 |
+
if d == 0:
|
| 2522 |
+
m += 1
|
| 2523 |
+
N += 1
|
| 2524 |
+
if d > 0:
|
| 2525 |
+
if 2*L > N:
|
| 2526 |
+
C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
|
| 2527 |
+
m += 1
|
| 2528 |
+
N += 1
|
| 2529 |
+
else:
|
| 2530 |
+
T = C
|
| 2531 |
+
C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
|
| 2532 |
+
L = N + 1 - L
|
| 2533 |
+
m = 1
|
| 2534 |
+
b = d
|
| 2535 |
+
B = T
|
| 2536 |
+
N += 1
|
| 2537 |
+
dC = Poly(C).degree()
|
| 2538 |
+
coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)]
|
| 2539 |
+
return sum(coeffsC[i] % p*x**i for i in range(dC + 1)
|
| 2540 |
+
if coeffsC[i] is not None)
|
| 2541 |
+
|
| 2542 |
+
|
| 2543 |
+
#################### ElGamal #############################
|
| 2544 |
+
|
| 2545 |
+
|
| 2546 |
+
def elgamal_private_key(digit=10, seed=None):
|
| 2547 |
+
r"""
|
| 2548 |
+
Return three number tuple as private key.
|
| 2549 |
+
|
| 2550 |
+
Explanation
|
| 2551 |
+
===========
|
| 2552 |
+
|
| 2553 |
+
Elgamal encryption is based on the mathematical problem
|
| 2554 |
+
called the Discrete Logarithm Problem (DLP). For example,
|
| 2555 |
+
|
| 2556 |
+
`a^{b} \equiv c \pmod p`
|
| 2557 |
+
|
| 2558 |
+
In general, if ``a`` and ``b`` are known, ``ct`` is easily
|
| 2559 |
+
calculated. If ``b`` is unknown, it is hard to use
|
| 2560 |
+
``a`` and ``ct`` to get ``b``.
|
| 2561 |
+
|
| 2562 |
+
Parameters
|
| 2563 |
+
==========
|
| 2564 |
+
|
| 2565 |
+
digit : int
|
| 2566 |
+
Minimum number of binary digits for key.
|
| 2567 |
+
|
| 2568 |
+
Returns
|
| 2569 |
+
=======
|
| 2570 |
+
|
| 2571 |
+
tuple : (p, r, d)
|
| 2572 |
+
p = prime number.
|
| 2573 |
+
|
| 2574 |
+
r = primitive root.
|
| 2575 |
+
|
| 2576 |
+
d = random number.
|
| 2577 |
+
|
| 2578 |
+
Notes
|
| 2579 |
+
=====
|
| 2580 |
+
|
| 2581 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
| 2582 |
+
the output of this routine. See sympy.core.random._randrange.
|
| 2583 |
+
|
| 2584 |
+
Examples
|
| 2585 |
+
========
|
| 2586 |
+
|
| 2587 |
+
>>> from sympy.crypto.crypto import elgamal_private_key
|
| 2588 |
+
>>> from sympy.ntheory import is_primitive_root, isprime
|
| 2589 |
+
>>> a, b, _ = elgamal_private_key()
|
| 2590 |
+
>>> isprime(a)
|
| 2591 |
+
True
|
| 2592 |
+
>>> is_primitive_root(b, a)
|
| 2593 |
+
True
|
| 2594 |
+
|
| 2595 |
+
"""
|
| 2596 |
+
randrange = _randrange(seed)
|
| 2597 |
+
p = nextprime(2**digit)
|
| 2598 |
+
return p, primitive_root(p), randrange(2, p)
|
| 2599 |
+
|
| 2600 |
+
|
| 2601 |
+
def elgamal_public_key(key):
|
| 2602 |
+
r"""
|
| 2603 |
+
Return three number tuple as public key.
|
| 2604 |
+
|
| 2605 |
+
Parameters
|
| 2606 |
+
==========
|
| 2607 |
+
|
| 2608 |
+
key : (p, r, e)
|
| 2609 |
+
Tuple generated by ``elgamal_private_key``.
|
| 2610 |
+
|
| 2611 |
+
Returns
|
| 2612 |
+
=======
|
| 2613 |
+
|
| 2614 |
+
tuple : (p, r, e)
|
| 2615 |
+
`e = r**d \bmod p`
|
| 2616 |
+
|
| 2617 |
+
`d` is a random number in private key.
|
| 2618 |
+
|
| 2619 |
+
Examples
|
| 2620 |
+
========
|
| 2621 |
+
|
| 2622 |
+
>>> from sympy.crypto.crypto import elgamal_public_key
|
| 2623 |
+
>>> elgamal_public_key((1031, 14, 636))
|
| 2624 |
+
(1031, 14, 212)
|
| 2625 |
+
|
| 2626 |
+
"""
|
| 2627 |
+
p, r, e = key
|
| 2628 |
+
return p, r, pow(r, e, p)
|
| 2629 |
+
|
| 2630 |
+
|
| 2631 |
+
def encipher_elgamal(i, key, seed=None):
|
| 2632 |
+
r"""
|
| 2633 |
+
Encrypt message with public key.
|
| 2634 |
+
|
| 2635 |
+
Explanation
|
| 2636 |
+
===========
|
| 2637 |
+
|
| 2638 |
+
``i`` is a plaintext message expressed as an integer.
|
| 2639 |
+
``key`` is public key (p, r, e). In order to encrypt
|
| 2640 |
+
a message, a random number ``a`` in ``range(2, p)``
|
| 2641 |
+
is generated and the encryped message is returned as
|
| 2642 |
+
`c_{1}` and `c_{2}` where:
|
| 2643 |
+
|
| 2644 |
+
`c_{1} \equiv r^{a} \pmod p`
|
| 2645 |
+
|
| 2646 |
+
`c_{2} \equiv m e^{a} \pmod p`
|
| 2647 |
+
|
| 2648 |
+
Parameters
|
| 2649 |
+
==========
|
| 2650 |
+
|
| 2651 |
+
msg
|
| 2652 |
+
int of encoded message.
|
| 2653 |
+
|
| 2654 |
+
key
|
| 2655 |
+
Public key.
|
| 2656 |
+
|
| 2657 |
+
Returns
|
| 2658 |
+
=======
|
| 2659 |
+
|
| 2660 |
+
tuple : (c1, c2)
|
| 2661 |
+
Encipher into two number.
|
| 2662 |
+
|
| 2663 |
+
Notes
|
| 2664 |
+
=====
|
| 2665 |
+
|
| 2666 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
| 2667 |
+
the output of this routine. See sympy.core.random._randrange.
|
| 2668 |
+
|
| 2669 |
+
Examples
|
| 2670 |
+
========
|
| 2671 |
+
|
| 2672 |
+
>>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key
|
| 2673 |
+
>>> pri = elgamal_private_key(5, seed=[3]); pri
|
| 2674 |
+
(37, 2, 3)
|
| 2675 |
+
>>> pub = elgamal_public_key(pri); pub
|
| 2676 |
+
(37, 2, 8)
|
| 2677 |
+
>>> msg = 36
|
| 2678 |
+
>>> encipher_elgamal(msg, pub, seed=[3])
|
| 2679 |
+
(8, 6)
|
| 2680 |
+
|
| 2681 |
+
"""
|
| 2682 |
+
p, r, e = key
|
| 2683 |
+
if i < 0 or i >= p:
|
| 2684 |
+
raise ValueError(
|
| 2685 |
+
'Message (%s) should be in range(%s)' % (i, p))
|
| 2686 |
+
randrange = _randrange(seed)
|
| 2687 |
+
a = randrange(2, p)
|
| 2688 |
+
return pow(r, a, p), i*pow(e, a, p) % p
|
| 2689 |
+
|
| 2690 |
+
|
| 2691 |
+
def decipher_elgamal(msg, key):
|
| 2692 |
+
r"""
|
| 2693 |
+
Decrypt message with private key.
|
| 2694 |
+
|
| 2695 |
+
`msg = (c_{1}, c_{2})`
|
| 2696 |
+
|
| 2697 |
+
`key = (p, r, d)`
|
| 2698 |
+
|
| 2699 |
+
According to extended Eucliden theorem,
|
| 2700 |
+
`u c_{1}^{d} + p n = 1`
|
| 2701 |
+
|
| 2702 |
+
`u \equiv 1/{{c_{1}}^d} \pmod p`
|
| 2703 |
+
|
| 2704 |
+
`u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p`
|
| 2705 |
+
|
| 2706 |
+
`\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p`
|
| 2707 |
+
|
| 2708 |
+
Examples
|
| 2709 |
+
========
|
| 2710 |
+
|
| 2711 |
+
>>> from sympy.crypto.crypto import decipher_elgamal
|
| 2712 |
+
>>> from sympy.crypto.crypto import encipher_elgamal
|
| 2713 |
+
>>> from sympy.crypto.crypto import elgamal_private_key
|
| 2714 |
+
>>> from sympy.crypto.crypto import elgamal_public_key
|
| 2715 |
+
|
| 2716 |
+
>>> pri = elgamal_private_key(5, seed=[3])
|
| 2717 |
+
>>> pub = elgamal_public_key(pri); pub
|
| 2718 |
+
(37, 2, 8)
|
| 2719 |
+
>>> msg = 17
|
| 2720 |
+
>>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg
|
| 2721 |
+
True
|
| 2722 |
+
|
| 2723 |
+
"""
|
| 2724 |
+
p, _, d = key
|
| 2725 |
+
c1, c2 = msg
|
| 2726 |
+
u = pow(c1, -d, p)
|
| 2727 |
+
return u * c2 % p
|
| 2728 |
+
|
| 2729 |
+
|
| 2730 |
+
################ Diffie-Hellman Key Exchange #########################
|
| 2731 |
+
|
| 2732 |
+
def dh_private_key(digit=10, seed=None):
|
| 2733 |
+
r"""
|
| 2734 |
+
Return three integer tuple as private key.
|
| 2735 |
+
|
| 2736 |
+
Explanation
|
| 2737 |
+
===========
|
| 2738 |
+
|
| 2739 |
+
Diffie-Hellman key exchange is based on the mathematical problem
|
| 2740 |
+
called the Discrete Logarithm Problem (see ElGamal).
|
| 2741 |
+
|
| 2742 |
+
Diffie-Hellman key exchange is divided into the following steps:
|
| 2743 |
+
|
| 2744 |
+
* Alice and Bob agree on a base that consist of a prime ``p``
|
| 2745 |
+
and a primitive root of ``p`` called ``g``
|
| 2746 |
+
* Alice choses a number ``a`` and Bob choses a number ``b`` where
|
| 2747 |
+
``a`` and ``b`` are random numbers in range `[2, p)`. These are
|
| 2748 |
+
their private keys.
|
| 2749 |
+
* Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends
|
| 2750 |
+
Alice `g^{b} \pmod p`
|
| 2751 |
+
* They both raise the received value to their secretly chosen
|
| 2752 |
+
number (``a`` or ``b``) and now have both as their shared key
|
| 2753 |
+
`g^{ab} \pmod p`
|
| 2754 |
+
|
| 2755 |
+
Parameters
|
| 2756 |
+
==========
|
| 2757 |
+
|
| 2758 |
+
digit
|
| 2759 |
+
Minimum number of binary digits required in key.
|
| 2760 |
+
|
| 2761 |
+
Returns
|
| 2762 |
+
=======
|
| 2763 |
+
|
| 2764 |
+
tuple : (p, g, a)
|
| 2765 |
+
p = prime number.
|
| 2766 |
+
|
| 2767 |
+
g = primitive root of p.
|
| 2768 |
+
|
| 2769 |
+
a = random number from 2 through p - 1.
|
| 2770 |
+
|
| 2771 |
+
Notes
|
| 2772 |
+
=====
|
| 2773 |
+
|
| 2774 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
| 2775 |
+
the output of this routine. See sympy.core.random._randrange.
|
| 2776 |
+
|
| 2777 |
+
Examples
|
| 2778 |
+
========
|
| 2779 |
+
|
| 2780 |
+
>>> from sympy.crypto.crypto import dh_private_key
|
| 2781 |
+
>>> from sympy.ntheory import isprime, is_primitive_root
|
| 2782 |
+
>>> p, g, _ = dh_private_key()
|
| 2783 |
+
>>> isprime(p)
|
| 2784 |
+
True
|
| 2785 |
+
>>> is_primitive_root(g, p)
|
| 2786 |
+
True
|
| 2787 |
+
>>> p, g, _ = dh_private_key(5)
|
| 2788 |
+
>>> isprime(p)
|
| 2789 |
+
True
|
| 2790 |
+
>>> is_primitive_root(g, p)
|
| 2791 |
+
True
|
| 2792 |
+
|
| 2793 |
+
"""
|
| 2794 |
+
p = nextprime(2**digit)
|
| 2795 |
+
g = primitive_root(p)
|
| 2796 |
+
randrange = _randrange(seed)
|
| 2797 |
+
a = randrange(2, p)
|
| 2798 |
+
return p, g, a
|
| 2799 |
+
|
| 2800 |
+
|
| 2801 |
+
def dh_public_key(key):
|
| 2802 |
+
r"""
|
| 2803 |
+
Return three number tuple as public key.
|
| 2804 |
+
|
| 2805 |
+
This is the tuple that Alice sends to Bob.
|
| 2806 |
+
|
| 2807 |
+
Parameters
|
| 2808 |
+
==========
|
| 2809 |
+
|
| 2810 |
+
key : (p, g, a)
|
| 2811 |
+
A tuple generated by ``dh_private_key``.
|
| 2812 |
+
|
| 2813 |
+
Returns
|
| 2814 |
+
=======
|
| 2815 |
+
|
| 2816 |
+
tuple : int, int, int
|
| 2817 |
+
A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as
|
| 2818 |
+
parameters.s
|
| 2819 |
+
|
| 2820 |
+
Examples
|
| 2821 |
+
========
|
| 2822 |
+
|
| 2823 |
+
>>> from sympy.crypto.crypto import dh_private_key, dh_public_key
|
| 2824 |
+
>>> p, g, a = dh_private_key();
|
| 2825 |
+
>>> _p, _g, x = dh_public_key((p, g, a))
|
| 2826 |
+
>>> p == _p and g == _g
|
| 2827 |
+
True
|
| 2828 |
+
>>> x == pow(g, a, p)
|
| 2829 |
+
True
|
| 2830 |
+
|
| 2831 |
+
"""
|
| 2832 |
+
p, g, a = key
|
| 2833 |
+
return p, g, pow(g, a, p)
|
| 2834 |
+
|
| 2835 |
+
|
| 2836 |
+
def dh_shared_key(key, b):
|
| 2837 |
+
"""
|
| 2838 |
+
Return an integer that is the shared key.
|
| 2839 |
+
|
| 2840 |
+
This is what Bob and Alice can both calculate using the public
|
| 2841 |
+
keys they received from each other and their private keys.
|
| 2842 |
+
|
| 2843 |
+
Parameters
|
| 2844 |
+
==========
|
| 2845 |
+
|
| 2846 |
+
key : (p, g, x)
|
| 2847 |
+
Tuple `(p, g, x)` generated by ``dh_public_key``.
|
| 2848 |
+
|
| 2849 |
+
b
|
| 2850 |
+
Random number in the range of `2` to `p - 1`
|
| 2851 |
+
(Chosen by second key exchange member (Bob)).
|
| 2852 |
+
|
| 2853 |
+
Returns
|
| 2854 |
+
=======
|
| 2855 |
+
|
| 2856 |
+
int
|
| 2857 |
+
A shared key.
|
| 2858 |
+
|
| 2859 |
+
Examples
|
| 2860 |
+
========
|
| 2861 |
+
|
| 2862 |
+
>>> from sympy.crypto.crypto import (
|
| 2863 |
+
... dh_private_key, dh_public_key, dh_shared_key)
|
| 2864 |
+
>>> prk = dh_private_key();
|
| 2865 |
+
>>> p, g, x = dh_public_key(prk);
|
| 2866 |
+
>>> sk = dh_shared_key((p, g, x), 1000)
|
| 2867 |
+
>>> sk == pow(x, 1000, p)
|
| 2868 |
+
True
|
| 2869 |
+
|
| 2870 |
+
"""
|
| 2871 |
+
p, _, x = key
|
| 2872 |
+
if 1 >= b or b >= p:
|
| 2873 |
+
raise ValueError(filldedent('''
|
| 2874 |
+
Value of b should be greater 1 and less
|
| 2875 |
+
than prime %s.''' % p))
|
| 2876 |
+
|
| 2877 |
+
return pow(x, b, p)
|
| 2878 |
+
|
| 2879 |
+
|
| 2880 |
+
################ Goldwasser-Micali Encryption #########################
|
| 2881 |
+
|
| 2882 |
+
|
| 2883 |
+
def _legendre(a, p):
|
| 2884 |
+
"""
|
| 2885 |
+
Returns the legendre symbol of a and p
|
| 2886 |
+
assuming that p is a prime.
|
| 2887 |
+
|
| 2888 |
+
i.e. 1 if a is a quadratic residue mod p
|
| 2889 |
+
-1 if a is not a quadratic residue mod p
|
| 2890 |
+
0 if a is divisible by p
|
| 2891 |
+
|
| 2892 |
+
Parameters
|
| 2893 |
+
==========
|
| 2894 |
+
|
| 2895 |
+
a : int
|
| 2896 |
+
The number to test.
|
| 2897 |
+
|
| 2898 |
+
p : prime
|
| 2899 |
+
The prime to test ``a`` against.
|
| 2900 |
+
|
| 2901 |
+
Returns
|
| 2902 |
+
=======
|
| 2903 |
+
|
| 2904 |
+
int
|
| 2905 |
+
Legendre symbol (a / p).
|
| 2906 |
+
|
| 2907 |
+
"""
|
| 2908 |
+
sig = pow(a, (p - 1)//2, p)
|
| 2909 |
+
if sig == 1:
|
| 2910 |
+
return 1
|
| 2911 |
+
elif sig == 0:
|
| 2912 |
+
return 0
|
| 2913 |
+
else:
|
| 2914 |
+
return -1
|
| 2915 |
+
|
| 2916 |
+
|
| 2917 |
+
def _random_coprime_stream(n, seed=None):
|
| 2918 |
+
randrange = _randrange(seed)
|
| 2919 |
+
while True:
|
| 2920 |
+
y = randrange(n)
|
| 2921 |
+
if gcd(y, n) == 1:
|
| 2922 |
+
yield y
|
| 2923 |
+
|
| 2924 |
+
|
| 2925 |
+
def gm_private_key(p, q, a=None):
|
| 2926 |
+
r"""
|
| 2927 |
+
Check if ``p`` and ``q`` can be used as private keys for
|
| 2928 |
+
the Goldwasser-Micali encryption. The method works
|
| 2929 |
+
roughly as follows.
|
| 2930 |
+
|
| 2931 |
+
Explanation
|
| 2932 |
+
===========
|
| 2933 |
+
|
| 2934 |
+
#. Pick two large primes $p$ and $q$.
|
| 2935 |
+
#. Call their product $N$.
|
| 2936 |
+
#. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$.
|
| 2937 |
+
#. For each $k$,
|
| 2938 |
+
|
| 2939 |
+
if $b_k = 0$:
|
| 2940 |
+
let $a_k$ be a random square
|
| 2941 |
+
(quadratic residue) modulo $p q$
|
| 2942 |
+
such that ``jacobi_symbol(a, p*q) = 1``
|
| 2943 |
+
if $b_k = 1$:
|
| 2944 |
+
let $a_k$ be a random non-square
|
| 2945 |
+
(non-quadratic residue) modulo $p q$
|
| 2946 |
+
such that ``jacobi_symbol(a, p*q) = 1``
|
| 2947 |
+
|
| 2948 |
+
returns $\left[a_1, a_2, \dots\right]$
|
| 2949 |
+
|
| 2950 |
+
$b_k$ can be recovered by checking whether or not
|
| 2951 |
+
$a_k$ is a residue. And from the $b_k$'s, the message
|
| 2952 |
+
can be reconstructed.
|
| 2953 |
+
|
| 2954 |
+
The idea is that, while ``jacobi_symbol(a, p*q)``
|
| 2955 |
+
can be easily computed (and when it is equal to $-1$ will
|
| 2956 |
+
tell you that $a$ is not a square mod $p q$), quadratic
|
| 2957 |
+
residuosity modulo a composite number is hard to compute
|
| 2958 |
+
without knowing its factorization.
|
| 2959 |
+
|
| 2960 |
+
Moreover, approximately half the numbers coprime to $p q$ have
|
| 2961 |
+
:func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half
|
| 2962 |
+
are residues and approximately half are not. This maximizes the
|
| 2963 |
+
entropy of the code.
|
| 2964 |
+
|
| 2965 |
+
Parameters
|
| 2966 |
+
==========
|
| 2967 |
+
|
| 2968 |
+
p, q, a
|
| 2969 |
+
Initialization variables.
|
| 2970 |
+
|
| 2971 |
+
Returns
|
| 2972 |
+
=======
|
| 2973 |
+
|
| 2974 |
+
tuple : (p, q)
|
| 2975 |
+
The input value ``p`` and ``q``.
|
| 2976 |
+
|
| 2977 |
+
Raises
|
| 2978 |
+
======
|
| 2979 |
+
|
| 2980 |
+
ValueError
|
| 2981 |
+
If ``p`` and ``q`` are not distinct odd primes.
|
| 2982 |
+
|
| 2983 |
+
"""
|
| 2984 |
+
if p == q:
|
| 2985 |
+
raise ValueError("expected distinct primes, "
|
| 2986 |
+
"got two copies of %i" % p)
|
| 2987 |
+
elif not isprime(p) or not isprime(q):
|
| 2988 |
+
raise ValueError("first two arguments must be prime, "
|
| 2989 |
+
"got %i of %i" % (p, q))
|
| 2990 |
+
elif p == 2 or q == 2:
|
| 2991 |
+
raise ValueError("first two arguments must not be even, "
|
| 2992 |
+
"got %i of %i" % (p, q))
|
| 2993 |
+
return p, q
|
| 2994 |
+
|
| 2995 |
+
|
| 2996 |
+
def gm_public_key(p, q, a=None, seed=None):
|
| 2997 |
+
"""
|
| 2998 |
+
Compute public keys for ``p`` and ``q``.
|
| 2999 |
+
Note that in Goldwasser-Micali Encryption,
|
| 3000 |
+
public keys are randomly selected.
|
| 3001 |
+
|
| 3002 |
+
Parameters
|
| 3003 |
+
==========
|
| 3004 |
+
|
| 3005 |
+
p, q, a : int, int, int
|
| 3006 |
+
Initialization variables.
|
| 3007 |
+
|
| 3008 |
+
Returns
|
| 3009 |
+
=======
|
| 3010 |
+
|
| 3011 |
+
tuple : (a, N)
|
| 3012 |
+
``a`` is the input ``a`` if it is not ``None`` otherwise
|
| 3013 |
+
some random integer coprime to ``p`` and ``q``.
|
| 3014 |
+
|
| 3015 |
+
``N`` is the product of ``p`` and ``q``.
|
| 3016 |
+
|
| 3017 |
+
"""
|
| 3018 |
+
|
| 3019 |
+
p, q = gm_private_key(p, q)
|
| 3020 |
+
N = p * q
|
| 3021 |
+
|
| 3022 |
+
if a is None:
|
| 3023 |
+
randrange = _randrange(seed)
|
| 3024 |
+
while True:
|
| 3025 |
+
a = randrange(N)
|
| 3026 |
+
if _legendre(a, p) == _legendre(a, q) == -1:
|
| 3027 |
+
break
|
| 3028 |
+
else:
|
| 3029 |
+
if _legendre(a, p) != -1 or _legendre(a, q) != -1:
|
| 3030 |
+
return False
|
| 3031 |
+
return (a, N)
|
| 3032 |
+
|
| 3033 |
+
|
| 3034 |
+
def encipher_gm(i, key, seed=None):
|
| 3035 |
+
"""
|
| 3036 |
+
Encrypt integer 'i' using public_key 'key'
|
| 3037 |
+
Note that gm uses random encryption.
|
| 3038 |
+
|
| 3039 |
+
Parameters
|
| 3040 |
+
==========
|
| 3041 |
+
|
| 3042 |
+
i : int
|
| 3043 |
+
The message to encrypt.
|
| 3044 |
+
|
| 3045 |
+
key : (a, N)
|
| 3046 |
+
The public key.
|
| 3047 |
+
|
| 3048 |
+
Returns
|
| 3049 |
+
=======
|
| 3050 |
+
|
| 3051 |
+
list : list of int
|
| 3052 |
+
The randomized encrypted message.
|
| 3053 |
+
|
| 3054 |
+
"""
|
| 3055 |
+
if i < 0:
|
| 3056 |
+
raise ValueError(
|
| 3057 |
+
"message must be a non-negative "
|
| 3058 |
+
"integer: got %d instead" % i)
|
| 3059 |
+
a, N = key
|
| 3060 |
+
bits = []
|
| 3061 |
+
while i > 0:
|
| 3062 |
+
bits.append(i % 2)
|
| 3063 |
+
i //= 2
|
| 3064 |
+
|
| 3065 |
+
gen = _random_coprime_stream(N, seed)
|
| 3066 |
+
rev = reversed(bits)
|
| 3067 |
+
encode = lambda b: next(gen)**2*pow(a, b) % N
|
| 3068 |
+
return [ encode(b) for b in rev ]
|
| 3069 |
+
|
| 3070 |
+
|
| 3071 |
+
|
| 3072 |
+
def decipher_gm(message, key):
|
| 3073 |
+
"""
|
| 3074 |
+
Decrypt message 'message' using public_key 'key'.
|
| 3075 |
+
|
| 3076 |
+
Parameters
|
| 3077 |
+
==========
|
| 3078 |
+
|
| 3079 |
+
message : list of int
|
| 3080 |
+
The randomized encrypted message.
|
| 3081 |
+
|
| 3082 |
+
key : (p, q)
|
| 3083 |
+
The private key.
|
| 3084 |
+
|
| 3085 |
+
Returns
|
| 3086 |
+
=======
|
| 3087 |
+
|
| 3088 |
+
int
|
| 3089 |
+
The encrypted message.
|
| 3090 |
+
|
| 3091 |
+
"""
|
| 3092 |
+
p, q = key
|
| 3093 |
+
res = lambda m, p: _legendre(m, p) > 0
|
| 3094 |
+
bits = [res(m, p) * res(m, q) for m in message]
|
| 3095 |
+
m = 0
|
| 3096 |
+
for b in bits:
|
| 3097 |
+
m <<= 1
|
| 3098 |
+
m += not b
|
| 3099 |
+
return m
|
| 3100 |
+
|
| 3101 |
+
|
| 3102 |
+
|
| 3103 |
+
########### RailFence Cipher #############
|
| 3104 |
+
|
| 3105 |
+
def encipher_railfence(message,rails):
|
| 3106 |
+
"""
|
| 3107 |
+
Performs Railfence Encryption on plaintext and returns ciphertext
|
| 3108 |
+
|
| 3109 |
+
Examples
|
| 3110 |
+
========
|
| 3111 |
+
|
| 3112 |
+
>>> from sympy.crypto.crypto import encipher_railfence
|
| 3113 |
+
>>> message = "hello world"
|
| 3114 |
+
>>> encipher_railfence(message,3)
|
| 3115 |
+
'horel ollwd'
|
| 3116 |
+
|
| 3117 |
+
Parameters
|
| 3118 |
+
==========
|
| 3119 |
+
|
| 3120 |
+
message : string, the message to encrypt.
|
| 3121 |
+
rails : int, the number of rails.
|
| 3122 |
+
|
| 3123 |
+
Returns
|
| 3124 |
+
=======
|
| 3125 |
+
|
| 3126 |
+
The Encrypted string message.
|
| 3127 |
+
|
| 3128 |
+
References
|
| 3129 |
+
==========
|
| 3130 |
+
.. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher
|
| 3131 |
+
|
| 3132 |
+
"""
|
| 3133 |
+
r = list(range(rails))
|
| 3134 |
+
p = cycle(r + r[-2:0:-1])
|
| 3135 |
+
return ''.join(sorted(message, key=lambda i: next(p)))
|
| 3136 |
+
|
| 3137 |
+
|
| 3138 |
+
def decipher_railfence(ciphertext,rails):
|
| 3139 |
+
"""
|
| 3140 |
+
Decrypt the message using the given rails
|
| 3141 |
+
|
| 3142 |
+
Examples
|
| 3143 |
+
========
|
| 3144 |
+
|
| 3145 |
+
>>> from sympy.crypto.crypto import decipher_railfence
|
| 3146 |
+
>>> decipher_railfence("horel ollwd",3)
|
| 3147 |
+
'hello world'
|
| 3148 |
+
|
| 3149 |
+
Parameters
|
| 3150 |
+
==========
|
| 3151 |
+
|
| 3152 |
+
message : string, the message to encrypt.
|
| 3153 |
+
rails : int, the number of rails.
|
| 3154 |
+
|
| 3155 |
+
Returns
|
| 3156 |
+
=======
|
| 3157 |
+
|
| 3158 |
+
The Decrypted string message.
|
| 3159 |
+
|
| 3160 |
+
"""
|
| 3161 |
+
r = list(range(rails))
|
| 3162 |
+
p = cycle(r + r[-2:0:-1])
|
| 3163 |
+
|
| 3164 |
+
idx = sorted(range(len(ciphertext)), key=lambda i: next(p))
|
| 3165 |
+
res = [''] * len(ciphertext)
|
| 3166 |
+
for i, c in zip(idx, ciphertext):
|
| 3167 |
+
res[i] = c
|
| 3168 |
+
return ''.join(res)
|
| 3169 |
+
|
| 3170 |
+
|
| 3171 |
+
################ Blum-Goldwasser cryptosystem #########################
|
| 3172 |
+
|
| 3173 |
+
def bg_private_key(p, q):
|
| 3174 |
+
"""
|
| 3175 |
+
Check if p and q can be used as private keys for
|
| 3176 |
+
the Blum-Goldwasser cryptosystem.
|
| 3177 |
+
|
| 3178 |
+
Explanation
|
| 3179 |
+
===========
|
| 3180 |
+
|
| 3181 |
+
The three necessary checks for p and q to pass
|
| 3182 |
+
so that they can be used as private keys:
|
| 3183 |
+
|
| 3184 |
+
1. p and q must both be prime
|
| 3185 |
+
2. p and q must be distinct
|
| 3186 |
+
3. p and q must be congruent to 3 mod 4
|
| 3187 |
+
|
| 3188 |
+
Parameters
|
| 3189 |
+
==========
|
| 3190 |
+
|
| 3191 |
+
p, q
|
| 3192 |
+
The keys to be checked.
|
| 3193 |
+
|
| 3194 |
+
Returns
|
| 3195 |
+
=======
|
| 3196 |
+
|
| 3197 |
+
p, q
|
| 3198 |
+
Input values.
|
| 3199 |
+
|
| 3200 |
+
Raises
|
| 3201 |
+
======
|
| 3202 |
+
|
| 3203 |
+
ValueError
|
| 3204 |
+
If p and q do not pass the above conditions.
|
| 3205 |
+
|
| 3206 |
+
"""
|
| 3207 |
+
|
| 3208 |
+
if not isprime(p) or not isprime(q):
|
| 3209 |
+
raise ValueError("the two arguments must be prime, "
|
| 3210 |
+
"got %i and %i" %(p, q))
|
| 3211 |
+
elif p == q:
|
| 3212 |
+
raise ValueError("the two arguments must be distinct, "
|
| 3213 |
+
"got two copies of %i. " %p)
|
| 3214 |
+
elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0:
|
| 3215 |
+
raise ValueError("the two arguments must be congruent to 3 mod 4, "
|
| 3216 |
+
"got %i and %i" %(p, q))
|
| 3217 |
+
return p, q
|
| 3218 |
+
|
| 3219 |
+
def bg_public_key(p, q):
|
| 3220 |
+
"""
|
| 3221 |
+
Calculates public keys from private keys.
|
| 3222 |
+
|
| 3223 |
+
Explanation
|
| 3224 |
+
===========
|
| 3225 |
+
|
| 3226 |
+
The function first checks the validity of
|
| 3227 |
+
private keys passed as arguments and
|
| 3228 |
+
then returns their product.
|
| 3229 |
+
|
| 3230 |
+
Parameters
|
| 3231 |
+
==========
|
| 3232 |
+
|
| 3233 |
+
p, q
|
| 3234 |
+
The private keys.
|
| 3235 |
+
|
| 3236 |
+
Returns
|
| 3237 |
+
=======
|
| 3238 |
+
|
| 3239 |
+
N
|
| 3240 |
+
The public key.
|
| 3241 |
+
|
| 3242 |
+
"""
|
| 3243 |
+
p, q = bg_private_key(p, q)
|
| 3244 |
+
N = p * q
|
| 3245 |
+
return N
|
| 3246 |
+
|
| 3247 |
+
def encipher_bg(i, key, seed=None):
|
| 3248 |
+
"""
|
| 3249 |
+
Encrypts the message using public key and seed.
|
| 3250 |
+
|
| 3251 |
+
Explanation
|
| 3252 |
+
===========
|
| 3253 |
+
|
| 3254 |
+
ALGORITHM:
|
| 3255 |
+
1. Encodes i as a string of L bits, m.
|
| 3256 |
+
2. Select a random element r, where 1 < r < key, and computes
|
| 3257 |
+
x = r^2 mod key.
|
| 3258 |
+
3. Use BBS pseudo-random number generator to generate L random bits, b,
|
| 3259 |
+
using the initial seed as x.
|
| 3260 |
+
4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L.
|
| 3261 |
+
5. x_L = x^(2^L) mod key.
|
| 3262 |
+
6. Return (c, x_L)
|
| 3263 |
+
|
| 3264 |
+
Parameters
|
| 3265 |
+
==========
|
| 3266 |
+
|
| 3267 |
+
i
|
| 3268 |
+
Message, a non-negative integer
|
| 3269 |
+
|
| 3270 |
+
key
|
| 3271 |
+
The public key
|
| 3272 |
+
|
| 3273 |
+
Returns
|
| 3274 |
+
=======
|
| 3275 |
+
|
| 3276 |
+
Tuple
|
| 3277 |
+
(encrypted_message, x_L)
|
| 3278 |
+
|
| 3279 |
+
Raises
|
| 3280 |
+
======
|
| 3281 |
+
|
| 3282 |
+
ValueError
|
| 3283 |
+
If i is negative.
|
| 3284 |
+
|
| 3285 |
+
"""
|
| 3286 |
+
|
| 3287 |
+
if i < 0:
|
| 3288 |
+
raise ValueError(
|
| 3289 |
+
"message must be a non-negative "
|
| 3290 |
+
"integer: got %d instead" % i)
|
| 3291 |
+
|
| 3292 |
+
enc_msg = []
|
| 3293 |
+
while i > 0:
|
| 3294 |
+
enc_msg.append(i % 2)
|
| 3295 |
+
i //= 2
|
| 3296 |
+
enc_msg.reverse()
|
| 3297 |
+
L = len(enc_msg)
|
| 3298 |
+
|
| 3299 |
+
r = _randint(seed)(2, key - 1)
|
| 3300 |
+
x = r**2 % key
|
| 3301 |
+
x_L = pow(int(x), int(2**L), int(key))
|
| 3302 |
+
|
| 3303 |
+
rand_bits = []
|
| 3304 |
+
for _ in range(L):
|
| 3305 |
+
rand_bits.append(x % 2)
|
| 3306 |
+
x = x**2 % key
|
| 3307 |
+
|
| 3308 |
+
encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)]
|
| 3309 |
+
|
| 3310 |
+
return (encrypt_msg, x_L)
|
| 3311 |
+
|
| 3312 |
+
def decipher_bg(message, key):
|
| 3313 |
+
"""
|
| 3314 |
+
Decrypts the message using private keys.
|
| 3315 |
+
|
| 3316 |
+
Explanation
|
| 3317 |
+
===========
|
| 3318 |
+
|
| 3319 |
+
ALGORITHM:
|
| 3320 |
+
1. Let, c be the encrypted message, y the second number received,
|
| 3321 |
+
and p and q be the private keys.
|
| 3322 |
+
2. Compute, r_p = y^((p+1)/4 ^ L) mod p and
|
| 3323 |
+
r_q = y^((q+1)/4 ^ L) mod q.
|
| 3324 |
+
3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N.
|
| 3325 |
+
4. From, recompute the bits using the BBS generator, as in the
|
| 3326 |
+
encryption algorithm.
|
| 3327 |
+
5. Compute original message by XORing c and b.
|
| 3328 |
+
|
| 3329 |
+
Parameters
|
| 3330 |
+
==========
|
| 3331 |
+
|
| 3332 |
+
message
|
| 3333 |
+
Tuple of encrypted message and a non-negative integer.
|
| 3334 |
+
|
| 3335 |
+
key
|
| 3336 |
+
Tuple of private keys.
|
| 3337 |
+
|
| 3338 |
+
Returns
|
| 3339 |
+
=======
|
| 3340 |
+
|
| 3341 |
+
orig_msg
|
| 3342 |
+
The original message
|
| 3343 |
+
|
| 3344 |
+
"""
|
| 3345 |
+
|
| 3346 |
+
p, q = key
|
| 3347 |
+
encrypt_msg, y = message
|
| 3348 |
+
public_key = p * q
|
| 3349 |
+
L = len(encrypt_msg)
|
| 3350 |
+
p_t = ((p + 1)/4)**L
|
| 3351 |
+
q_t = ((q + 1)/4)**L
|
| 3352 |
+
r_p = pow(int(y), int(p_t), int(p))
|
| 3353 |
+
r_q = pow(int(y), int(q_t), int(q))
|
| 3354 |
+
|
| 3355 |
+
x = (q * invert(q, p) * r_p + p * invert(p, q) * r_q) % public_key
|
| 3356 |
+
|
| 3357 |
+
orig_bits = []
|
| 3358 |
+
for _ in range(L):
|
| 3359 |
+
orig_bits.append(x % 2)
|
| 3360 |
+
x = x**2 % public_key
|
| 3361 |
+
|
| 3362 |
+
orig_msg = 0
|
| 3363 |
+
for (m, b) in zip(encrypt_msg, orig_bits):
|
| 3364 |
+
orig_msg = orig_msg * 2
|
| 3365 |
+
orig_msg += (m ^ b)
|
| 3366 |
+
|
| 3367 |
+
return orig_msg
|
vllm/lib/python3.10/site-packages/sympy/crypto/tests/__init__.py
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (168 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/crypto/tests/__pycache__/test_crypto.cpython-310.pyc
ADDED
|
Binary file (20.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/crypto/tests/test_crypto.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import symbols
|
| 2 |
+
from sympy.crypto.crypto import (cycle_list,
|
| 3 |
+
encipher_shift, encipher_affine, encipher_substitution,
|
| 4 |
+
check_and_join, encipher_vigenere, decipher_vigenere,
|
| 5 |
+
encipher_hill, decipher_hill, encipher_bifid5, encipher_bifid6,
|
| 6 |
+
bifid5_square, bifid6_square, bifid5, bifid6,
|
| 7 |
+
decipher_bifid5, decipher_bifid6, encipher_kid_rsa,
|
| 8 |
+
decipher_kid_rsa, kid_rsa_private_key, kid_rsa_public_key,
|
| 9 |
+
decipher_rsa, rsa_private_key, rsa_public_key, encipher_rsa,
|
| 10 |
+
lfsr_connection_polynomial, lfsr_autocorrelation, lfsr_sequence,
|
| 11 |
+
encode_morse, decode_morse, elgamal_private_key, elgamal_public_key,
|
| 12 |
+
encipher_elgamal, decipher_elgamal, dh_private_key, dh_public_key,
|
| 13 |
+
dh_shared_key, decipher_shift, decipher_affine, encipher_bifid,
|
| 14 |
+
decipher_bifid, bifid_square, padded_key, uniq, decipher_gm,
|
| 15 |
+
encipher_gm, gm_public_key, gm_private_key, encipher_bg, decipher_bg,
|
| 16 |
+
bg_private_key, bg_public_key, encipher_rot13, decipher_rot13,
|
| 17 |
+
encipher_atbash, decipher_atbash, NonInvertibleCipherWarning,
|
| 18 |
+
encipher_railfence, decipher_railfence)
|
| 19 |
+
from sympy.external.gmpy import gcd
|
| 20 |
+
from sympy.matrices import Matrix
|
| 21 |
+
from sympy.ntheory import isprime, is_primitive_root
|
| 22 |
+
from sympy.polys.domains import FF
|
| 23 |
+
|
| 24 |
+
from sympy.testing.pytest import raises, warns
|
| 25 |
+
|
| 26 |
+
from sympy.core.random import randrange
|
| 27 |
+
|
| 28 |
+
def test_encipher_railfence():
|
| 29 |
+
assert encipher_railfence("hello world",2) == "hlowrdel ol"
|
| 30 |
+
assert encipher_railfence("hello world",3) == "horel ollwd"
|
| 31 |
+
assert encipher_railfence("hello world",4) == "hwe olordll"
|
| 32 |
+
|
| 33 |
+
def test_decipher_railfence():
|
| 34 |
+
assert decipher_railfence("hlowrdel ol",2) == "hello world"
|
| 35 |
+
assert decipher_railfence("horel ollwd",3) == "hello world"
|
| 36 |
+
assert decipher_railfence("hwe olordll",4) == "hello world"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_cycle_list():
|
| 40 |
+
assert cycle_list(3, 4) == [3, 0, 1, 2]
|
| 41 |
+
assert cycle_list(-1, 4) == [3, 0, 1, 2]
|
| 42 |
+
assert cycle_list(1, 4) == [1, 2, 3, 0]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_encipher_shift():
|
| 46 |
+
assert encipher_shift("ABC", 0) == "ABC"
|
| 47 |
+
assert encipher_shift("ABC", 1) == "BCD"
|
| 48 |
+
assert encipher_shift("ABC", -1) == "ZAB"
|
| 49 |
+
assert decipher_shift("ZAB", -1) == "ABC"
|
| 50 |
+
|
| 51 |
+
def test_encipher_rot13():
|
| 52 |
+
assert encipher_rot13("ABC") == "NOP"
|
| 53 |
+
assert encipher_rot13("NOP") == "ABC"
|
| 54 |
+
assert decipher_rot13("ABC") == "NOP"
|
| 55 |
+
assert decipher_rot13("NOP") == "ABC"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_encipher_affine():
|
| 59 |
+
assert encipher_affine("ABC", (1, 0)) == "ABC"
|
| 60 |
+
assert encipher_affine("ABC", (1, 1)) == "BCD"
|
| 61 |
+
assert encipher_affine("ABC", (-1, 0)) == "AZY"
|
| 62 |
+
assert encipher_affine("ABC", (-1, 1), symbols="ABCD") == "BAD"
|
| 63 |
+
assert encipher_affine("123", (-1, 1), symbols="1234") == "214"
|
| 64 |
+
assert encipher_affine("ABC", (3, 16)) == "QTW"
|
| 65 |
+
assert decipher_affine("QTW", (3, 16)) == "ABC"
|
| 66 |
+
|
| 67 |
+
def test_encipher_atbash():
|
| 68 |
+
assert encipher_atbash("ABC") == "ZYX"
|
| 69 |
+
assert encipher_atbash("ZYX") == "ABC"
|
| 70 |
+
assert decipher_atbash("ABC") == "ZYX"
|
| 71 |
+
assert decipher_atbash("ZYX") == "ABC"
|
| 72 |
+
|
| 73 |
+
def test_encipher_substitution():
|
| 74 |
+
assert encipher_substitution("ABC", "BAC", "ABC") == "BAC"
|
| 75 |
+
assert encipher_substitution("123", "1243", "1234") == "124"
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_check_and_join():
|
| 79 |
+
assert check_and_join("abc") == "abc"
|
| 80 |
+
assert check_and_join(uniq("aaabc")) == "abc"
|
| 81 |
+
assert check_and_join("ab c".split()) == "abc"
|
| 82 |
+
assert check_and_join("abc", "a", filter=True) == "a"
|
| 83 |
+
raises(ValueError, lambda: check_and_join('ab', 'a'))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_encipher_vigenere():
|
| 87 |
+
assert encipher_vigenere("ABC", "ABC") == "ACE"
|
| 88 |
+
assert encipher_vigenere("ABC", "ABC", symbols="ABCD") == "ACA"
|
| 89 |
+
assert encipher_vigenere("ABC", "AB", symbols="ABCD") == "ACC"
|
| 90 |
+
assert encipher_vigenere("AB", "ABC", symbols="ABCD") == "AC"
|
| 91 |
+
assert encipher_vigenere("A", "ABC", symbols="ABCD") == "A"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_decipher_vigenere():
|
| 95 |
+
assert decipher_vigenere("ABC", "ABC") == "AAA"
|
| 96 |
+
assert decipher_vigenere("ABC", "ABC", symbols="ABCD") == "AAA"
|
| 97 |
+
assert decipher_vigenere("ABC", "AB", symbols="ABCD") == "AAC"
|
| 98 |
+
assert decipher_vigenere("AB", "ABC", symbols="ABCD") == "AA"
|
| 99 |
+
assert decipher_vigenere("A", "ABC", symbols="ABCD") == "A"
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_encipher_hill():
|
| 103 |
+
A = Matrix(2, 2, [1, 2, 3, 5])
|
| 104 |
+
assert encipher_hill("ABCD", A) == "CFIV"
|
| 105 |
+
A = Matrix(2, 2, [1, 0, 0, 1])
|
| 106 |
+
assert encipher_hill("ABCD", A) == "ABCD"
|
| 107 |
+
assert encipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
|
| 108 |
+
A = Matrix(2, 2, [1, 2, 3, 5])
|
| 109 |
+
assert encipher_hill("ABCD", A, symbols="ABCD") == "CBAB"
|
| 110 |
+
assert encipher_hill("AB", A, symbols="ABCD") == "CB"
|
| 111 |
+
# message length, n, does not need to be a multiple of k;
|
| 112 |
+
# it is padded
|
| 113 |
+
assert encipher_hill("ABA", A) == "CFGC"
|
| 114 |
+
assert encipher_hill("ABA", A, pad="Z") == "CFYV"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_decipher_hill():
|
| 118 |
+
A = Matrix(2, 2, [1, 2, 3, 5])
|
| 119 |
+
assert decipher_hill("CFIV", A) == "ABCD"
|
| 120 |
+
A = Matrix(2, 2, [1, 0, 0, 1])
|
| 121 |
+
assert decipher_hill("ABCD", A) == "ABCD"
|
| 122 |
+
assert decipher_hill("ABCD", A, symbols="ABCD") == "ABCD"
|
| 123 |
+
A = Matrix(2, 2, [1, 2, 3, 5])
|
| 124 |
+
assert decipher_hill("CBAB", A, symbols="ABCD") == "ABCD"
|
| 125 |
+
assert decipher_hill("CB", A, symbols="ABCD") == "AB"
|
| 126 |
+
# n does not need to be a multiple of k
|
| 127 |
+
assert decipher_hill("CFA", A) == "ABAA"
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_encipher_bifid5():
|
| 131 |
+
assert encipher_bifid5("AB", "AB") == "AB"
|
| 132 |
+
assert encipher_bifid5("AB", "CD") == "CO"
|
| 133 |
+
assert encipher_bifid5("ab", "c") == "CH"
|
| 134 |
+
assert encipher_bifid5("a bc", "b") == "BAC"
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_bifid5_square():
|
| 138 |
+
A = bifid5
|
| 139 |
+
f = lambda i, j: symbols(A[5*i + j])
|
| 140 |
+
M = Matrix(5, 5, f)
|
| 141 |
+
assert bifid5_square("") == M
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def test_decipher_bifid5():
|
| 145 |
+
assert decipher_bifid5("AB", "AB") == "AB"
|
| 146 |
+
assert decipher_bifid5("CO", "CD") == "AB"
|
| 147 |
+
assert decipher_bifid5("ch", "c") == "AB"
|
| 148 |
+
assert decipher_bifid5("b ac", "b") == "ABC"
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_encipher_bifid6():
|
| 152 |
+
assert encipher_bifid6("AB", "AB") == "AB"
|
| 153 |
+
assert encipher_bifid6("AB", "CD") == "CP"
|
| 154 |
+
assert encipher_bifid6("ab", "c") == "CI"
|
| 155 |
+
assert encipher_bifid6("a bc", "b") == "BAC"
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def test_decipher_bifid6():
|
| 159 |
+
assert decipher_bifid6("AB", "AB") == "AB"
|
| 160 |
+
assert decipher_bifid6("CP", "CD") == "AB"
|
| 161 |
+
assert decipher_bifid6("ci", "c") == "AB"
|
| 162 |
+
assert decipher_bifid6("b ac", "b") == "ABC"
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_bifid6_square():
|
| 166 |
+
A = bifid6
|
| 167 |
+
f = lambda i, j: symbols(A[6*i + j])
|
| 168 |
+
M = Matrix(6, 6, f)
|
| 169 |
+
assert bifid6_square("") == M
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def test_rsa_public_key():
|
| 173 |
+
assert rsa_public_key(2, 3, 1) == (6, 1)
|
| 174 |
+
assert rsa_public_key(5, 3, 3) == (15, 3)
|
| 175 |
+
|
| 176 |
+
with warns(NonInvertibleCipherWarning):
|
| 177 |
+
assert rsa_public_key(2, 2, 1) == (4, 1)
|
| 178 |
+
assert rsa_public_key(8, 8, 8) is False
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_rsa_private_key():
|
| 182 |
+
assert rsa_private_key(2, 3, 1) == (6, 1)
|
| 183 |
+
assert rsa_private_key(5, 3, 3) == (15, 3)
|
| 184 |
+
assert rsa_private_key(23,29,5) == (667,493)
|
| 185 |
+
|
| 186 |
+
with warns(NonInvertibleCipherWarning):
|
| 187 |
+
assert rsa_private_key(2, 2, 1) == (4, 1)
|
| 188 |
+
assert rsa_private_key(8, 8, 8) is False
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def test_rsa_large_key():
|
| 192 |
+
# Sample from
|
| 193 |
+
# http://www.herongyang.com/Cryptography/JCE-Public-Key-RSA-Private-Public-Key-Pair-Sample.html
|
| 194 |
+
p = int('101565610013301240713207239558950144682174355406589305284428666'\
|
| 195 |
+
'903702505233009')
|
| 196 |
+
q = int('894687191887545488935455605955948413812376003053143521429242133'\
|
| 197 |
+
'12069293984003')
|
| 198 |
+
e = int('65537')
|
| 199 |
+
d = int('893650581832704239530398858744759129594796235440844479456143566'\
|
| 200 |
+
'6999402846577625762582824202269399672579058991442587406384754958587'\
|
| 201 |
+
'400493169361356902030209')
|
| 202 |
+
assert rsa_public_key(p, q, e) == (p*q, e)
|
| 203 |
+
assert rsa_private_key(p, q, e) == (p*q, d)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def test_encipher_rsa():
|
| 207 |
+
puk = rsa_public_key(2, 3, 1)
|
| 208 |
+
assert encipher_rsa(2, puk) == 2
|
| 209 |
+
puk = rsa_public_key(5, 3, 3)
|
| 210 |
+
assert encipher_rsa(2, puk) == 8
|
| 211 |
+
|
| 212 |
+
with warns(NonInvertibleCipherWarning):
|
| 213 |
+
puk = rsa_public_key(2, 2, 1)
|
| 214 |
+
assert encipher_rsa(2, puk) == 2
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def test_decipher_rsa():
|
| 218 |
+
prk = rsa_private_key(2, 3, 1)
|
| 219 |
+
assert decipher_rsa(2, prk) == 2
|
| 220 |
+
prk = rsa_private_key(5, 3, 3)
|
| 221 |
+
assert decipher_rsa(8, prk) == 2
|
| 222 |
+
|
| 223 |
+
with warns(NonInvertibleCipherWarning):
|
| 224 |
+
prk = rsa_private_key(2, 2, 1)
|
| 225 |
+
assert decipher_rsa(2, prk) == 2
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def test_mutltiprime_rsa_full_example():
|
| 229 |
+
# Test example from
|
| 230 |
+
# https://iopscience.iop.org/article/10.1088/1742-6596/995/1/012030
|
| 231 |
+
puk = rsa_public_key(2, 3, 5, 7, 11, 13, 7)
|
| 232 |
+
prk = rsa_private_key(2, 3, 5, 7, 11, 13, 7)
|
| 233 |
+
assert puk == (30030, 7)
|
| 234 |
+
assert prk == (30030, 823)
|
| 235 |
+
|
| 236 |
+
msg = 10
|
| 237 |
+
encrypted = encipher_rsa(2 * msg - 15, puk)
|
| 238 |
+
assert encrypted == 18065
|
| 239 |
+
decrypted = (decipher_rsa(encrypted, prk) + 15) / 2
|
| 240 |
+
assert decrypted == msg
|
| 241 |
+
|
| 242 |
+
# Test example from
|
| 243 |
+
# https://www.scirp.org/pdf/JCC_2018032215502008.pdf
|
| 244 |
+
puk1 = rsa_public_key(53, 41, 43, 47, 41)
|
| 245 |
+
prk1 = rsa_private_key(53, 41, 43, 47, 41)
|
| 246 |
+
puk2 = rsa_public_key(53, 41, 43, 47, 97)
|
| 247 |
+
prk2 = rsa_private_key(53, 41, 43, 47, 97)
|
| 248 |
+
|
| 249 |
+
assert puk1 == (4391633, 41)
|
| 250 |
+
assert prk1 == (4391633, 294041)
|
| 251 |
+
assert puk2 == (4391633, 97)
|
| 252 |
+
assert prk2 == (4391633, 455713)
|
| 253 |
+
|
| 254 |
+
msg = 12321
|
| 255 |
+
encrypted = encipher_rsa(encipher_rsa(msg, puk1), puk2)
|
| 256 |
+
assert encrypted == 1081588
|
| 257 |
+
decrypted = decipher_rsa(decipher_rsa(encrypted, prk2), prk1)
|
| 258 |
+
assert decrypted == msg
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def test_rsa_crt_extreme():
|
| 262 |
+
p = int(
|
| 263 |
+
'10177157607154245068023861503693082120906487143725062283406501' \
|
| 264 |
+
'54082258226204046999838297167140821364638180697194879500245557' \
|
| 265 |
+
'65445186962893346463841419427008800341257468600224049986260471' \
|
| 266 |
+
'92257248163014468841725476918639415726709736077813632961290911' \
|
| 267 |
+
'0256421232977833028677441206049309220354796014376698325101693')
|
| 268 |
+
|
| 269 |
+
q = int(
|
| 270 |
+
'28752342353095132872290181526607275886182793241660805077850801' \
|
| 271 |
+
'75689512797754286972952273553128181861830576836289738668745250' \
|
| 272 |
+
'34028199691128870676414118458442900035778874482624765513861643' \
|
| 273 |
+
'27966696316822188398336199002306588703902894100476186823849595' \
|
| 274 |
+
'103239410527279605442148285816149368667083114802852804976893')
|
| 275 |
+
|
| 276 |
+
r = int(
|
| 277 |
+
'17698229259868825776879500736350186838850961935956310134378261' \
|
| 278 |
+
'89771862186717463067541369694816245225291921138038800171125596' \
|
| 279 |
+
'07315449521981157084370187887650624061033066022458512942411841' \
|
| 280 |
+
'18747893789972315277160085086164119879536041875335384844820566' \
|
| 281 |
+
'0287479617671726408053319619892052000850883994343378882717849')
|
| 282 |
+
|
| 283 |
+
s = int(
|
| 284 |
+
'68925428438585431029269182233502611027091755064643742383515623' \
|
| 285 |
+
'64321310582896893395529367074942808353187138794422745718419645' \
|
| 286 |
+
'28291231865157212604266903677599180789896916456120289112752835' \
|
| 287 |
+
'98502265889669730331688206825220074713977607415178738015831030' \
|
| 288 |
+
'364290585369150502819743827343552098197095520550865360159439'
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
t = int(
|
| 292 |
+
'69035483433453632820551311892368908779778144568711455301541094' \
|
| 293 |
+
'31487047642322695357696860925747923189635033183069823820910521' \
|
| 294 |
+
'71172909106797748883261493224162414050106920442445896819806600' \
|
| 295 |
+
'15448444826108008217972129130625571421904893252804729877353352' \
|
| 296 |
+
'739420480574842850202181462656251626522910618936534699566291'
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
e = 65537
|
| 300 |
+
puk = rsa_public_key(p, q, r, s, t, e)
|
| 301 |
+
prk = rsa_private_key(p, q, r, s, t, e)
|
| 302 |
+
|
| 303 |
+
plaintext = 1000
|
| 304 |
+
ciphertext_1 = encipher_rsa(plaintext, puk)
|
| 305 |
+
ciphertext_2 = encipher_rsa(plaintext, puk, [p, q, r, s, t])
|
| 306 |
+
assert ciphertext_1 == ciphertext_2
|
| 307 |
+
assert decipher_rsa(ciphertext_1, prk) == \
|
| 308 |
+
decipher_rsa(ciphertext_1, prk, [p, q, r, s, t])
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def test_rsa_exhaustive():
|
| 312 |
+
p, q = 61, 53
|
| 313 |
+
e = 17
|
| 314 |
+
puk = rsa_public_key(p, q, e, totient='Carmichael')
|
| 315 |
+
prk = rsa_private_key(p, q, e, totient='Carmichael')
|
| 316 |
+
|
| 317 |
+
for msg in range(puk[0]):
|
| 318 |
+
encrypted = encipher_rsa(msg, puk)
|
| 319 |
+
decrypted = decipher_rsa(encrypted, prk)
|
| 320 |
+
try:
|
| 321 |
+
assert decrypted == msg
|
| 322 |
+
except AssertionError:
|
| 323 |
+
raise AssertionError(
|
| 324 |
+
"The RSA is not correctly decrypted " \
|
| 325 |
+
"(Original : {}, Encrypted : {}, Decrypted : {})" \
|
| 326 |
+
.format(msg, encrypted, decrypted)
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def test_rsa_multiprime_exhanstive():
|
| 331 |
+
primes = [3, 5, 7, 11]
|
| 332 |
+
e = 7
|
| 333 |
+
args = primes + [e]
|
| 334 |
+
puk = rsa_public_key(*args, totient='Carmichael')
|
| 335 |
+
prk = rsa_private_key(*args, totient='Carmichael')
|
| 336 |
+
n = puk[0]
|
| 337 |
+
|
| 338 |
+
for msg in range(n):
|
| 339 |
+
encrypted = encipher_rsa(msg, puk)
|
| 340 |
+
decrypted = decipher_rsa(encrypted, prk)
|
| 341 |
+
try:
|
| 342 |
+
assert decrypted == msg
|
| 343 |
+
except AssertionError:
|
| 344 |
+
raise AssertionError(
|
| 345 |
+
"The RSA is not correctly decrypted " \
|
| 346 |
+
"(Original : {}, Encrypted : {}, Decrypted : {})" \
|
| 347 |
+
.format(msg, encrypted, decrypted)
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def test_rsa_multipower_exhanstive():
|
| 352 |
+
primes = [5, 5, 7]
|
| 353 |
+
e = 7
|
| 354 |
+
args = primes + [e]
|
| 355 |
+
puk = rsa_public_key(*args, multipower=True)
|
| 356 |
+
prk = rsa_private_key(*args, multipower=True)
|
| 357 |
+
n = puk[0]
|
| 358 |
+
|
| 359 |
+
for msg in range(n):
|
| 360 |
+
if gcd(msg, n) != 1:
|
| 361 |
+
continue
|
| 362 |
+
|
| 363 |
+
encrypted = encipher_rsa(msg, puk)
|
| 364 |
+
decrypted = decipher_rsa(encrypted, prk)
|
| 365 |
+
try:
|
| 366 |
+
assert decrypted == msg
|
| 367 |
+
except AssertionError:
|
| 368 |
+
raise AssertionError(
|
| 369 |
+
"The RSA is not correctly decrypted " \
|
| 370 |
+
"(Original : {}, Encrypted : {}, Decrypted : {})" \
|
| 371 |
+
.format(msg, encrypted, decrypted)
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def test_kid_rsa_public_key():
|
| 376 |
+
assert kid_rsa_public_key(1, 2, 1, 1) == (5, 2)
|
| 377 |
+
assert kid_rsa_public_key(1, 2, 2, 1) == (8, 3)
|
| 378 |
+
assert kid_rsa_public_key(1, 2, 1, 2) == (7, 2)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def test_kid_rsa_private_key():
|
| 382 |
+
assert kid_rsa_private_key(1, 2, 1, 1) == (5, 3)
|
| 383 |
+
assert kid_rsa_private_key(1, 2, 2, 1) == (8, 3)
|
| 384 |
+
assert kid_rsa_private_key(1, 2, 1, 2) == (7, 4)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def test_encipher_kid_rsa():
|
| 388 |
+
assert encipher_kid_rsa(1, (5, 2)) == 2
|
| 389 |
+
assert encipher_kid_rsa(1, (8, 3)) == 3
|
| 390 |
+
assert encipher_kid_rsa(1, (7, 2)) == 2
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def test_decipher_kid_rsa():
|
| 394 |
+
assert decipher_kid_rsa(2, (5, 3)) == 1
|
| 395 |
+
assert decipher_kid_rsa(3, (8, 3)) == 1
|
| 396 |
+
assert decipher_kid_rsa(2, (7, 4)) == 1
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def test_encode_morse():
|
| 400 |
+
assert encode_morse('ABC') == '.-|-...|-.-.'
|
| 401 |
+
assert encode_morse('SMS ') == '...|--|...||'
|
| 402 |
+
assert encode_morse('SMS\n') == '...|--|...||'
|
| 403 |
+
assert encode_morse('') == ''
|
| 404 |
+
assert encode_morse(' ') == '||'
|
| 405 |
+
assert encode_morse(' ', sep='`') == '``'
|
| 406 |
+
assert encode_morse(' ', sep='``') == '````'
|
| 407 |
+
assert encode_morse('!@#$%^&*()_+') == '-.-.--|.--.-.|...-..-|-.--.|-.--.-|..--.-|.-.-.'
|
| 408 |
+
assert encode_morse('12345') == '.----|..---|...--|....-|.....'
|
| 409 |
+
assert encode_morse('67890') == '-....|--...|---..|----.|-----'
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def test_decode_morse():
|
| 413 |
+
assert decode_morse('-.-|.|-.--') == 'KEY'
|
| 414 |
+
assert decode_morse('.-.|..-|-.||') == 'RUN'
|
| 415 |
+
raises(KeyError, lambda: decode_morse('.....----'))
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def test_lfsr_sequence():
|
| 419 |
+
raises(TypeError, lambda: lfsr_sequence(1, [1], 1))
|
| 420 |
+
raises(TypeError, lambda: lfsr_sequence([1], 1, 1))
|
| 421 |
+
F = FF(2)
|
| 422 |
+
assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
|
| 423 |
+
assert lfsr_sequence([F(0)], [F(1)], 2) == [F(1), F(0)]
|
| 424 |
+
F = FF(3)
|
| 425 |
+
assert lfsr_sequence([F(1)], [F(1)], 2) == [F(1), F(1)]
|
| 426 |
+
assert lfsr_sequence([F(0)], [F(2)], 2) == [F(2), F(0)]
|
| 427 |
+
assert lfsr_sequence([F(1)], [F(2)], 2) == [F(2), F(2)]
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def test_lfsr_autocorrelation():
|
| 431 |
+
raises(TypeError, lambda: lfsr_autocorrelation(1, 2, 3))
|
| 432 |
+
F = FF(2)
|
| 433 |
+
s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
|
| 434 |
+
assert lfsr_autocorrelation(s, 2, 0) == 1
|
| 435 |
+
assert lfsr_autocorrelation(s, 2, 1) == -1
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def test_lfsr_connection_polynomial():
|
| 439 |
+
F = FF(2)
|
| 440 |
+
x = symbols("x")
|
| 441 |
+
s = lfsr_sequence([F(1), F(0)], [F(0), F(1)], 5)
|
| 442 |
+
assert lfsr_connection_polynomial(s) == x**2 + 1
|
| 443 |
+
s = lfsr_sequence([F(1), F(1)], [F(0), F(1)], 5)
|
| 444 |
+
assert lfsr_connection_polynomial(s) == x**2 + x + 1
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def test_elgamal_private_key():
|
| 448 |
+
a, b, _ = elgamal_private_key(digit=100)
|
| 449 |
+
assert isprime(a)
|
| 450 |
+
assert is_primitive_root(b, a)
|
| 451 |
+
assert len(bin(a)) >= 102
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def test_elgamal():
|
| 455 |
+
dk = elgamal_private_key(5)
|
| 456 |
+
ek = elgamal_public_key(dk)
|
| 457 |
+
P = ek[0]
|
| 458 |
+
assert P - 1 == decipher_elgamal(encipher_elgamal(P - 1, ek), dk)
|
| 459 |
+
raises(ValueError, lambda: encipher_elgamal(P, dk))
|
| 460 |
+
raises(ValueError, lambda: encipher_elgamal(-1, dk))
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def test_dh_private_key():
|
| 464 |
+
p, g, _ = dh_private_key(digit = 100)
|
| 465 |
+
assert isprime(p)
|
| 466 |
+
assert is_primitive_root(g, p)
|
| 467 |
+
assert len(bin(p)) >= 102
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def test_dh_public_key():
|
| 471 |
+
p1, g1, a = dh_private_key(digit = 100)
|
| 472 |
+
p2, g2, ga = dh_public_key((p1, g1, a))
|
| 473 |
+
assert p1 == p2
|
| 474 |
+
assert g1 == g2
|
| 475 |
+
assert ga == pow(g1, a, p1)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def test_dh_shared_key():
|
| 479 |
+
prk = dh_private_key(digit = 100)
|
| 480 |
+
p, _, ga = dh_public_key(prk)
|
| 481 |
+
b = randrange(2, p)
|
| 482 |
+
sk = dh_shared_key((p, _, ga), b)
|
| 483 |
+
assert sk == pow(ga, b, p)
|
| 484 |
+
raises(ValueError, lambda: dh_shared_key((1031, 14, 565), 2000))
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def test_padded_key():
|
| 488 |
+
assert padded_key('b', 'ab') == 'ba'
|
| 489 |
+
raises(ValueError, lambda: padded_key('ab', 'ace'))
|
| 490 |
+
raises(ValueError, lambda: padded_key('ab', 'abba'))
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def test_bifid():
|
| 494 |
+
raises(ValueError, lambda: encipher_bifid('abc', 'b', 'abcde'))
|
| 495 |
+
assert encipher_bifid('abc', 'b', 'abcd') == 'bdb'
|
| 496 |
+
raises(ValueError, lambda: decipher_bifid('bdb', 'b', 'abcde'))
|
| 497 |
+
assert encipher_bifid('bdb', 'b', 'abcd') == 'abc'
|
| 498 |
+
raises(ValueError, lambda: bifid_square('abcde'))
|
| 499 |
+
assert bifid5_square("B") == \
|
| 500 |
+
bifid5_square('BACDEFGHIKLMNOPQRSTUVWXYZ')
|
| 501 |
+
assert bifid6_square('B0') == \
|
| 502 |
+
bifid6_square('B0ACDEFGHIJKLMNOPQRSTUVWXYZ123456789')
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def test_encipher_decipher_gm():
|
| 506 |
+
ps = [131, 137, 139, 149, 151, 157, 163, 167,
|
| 507 |
+
173, 179, 181, 191, 193, 197, 199]
|
| 508 |
+
qs = [89, 97, 101, 103, 107, 109, 113, 127,
|
| 509 |
+
131, 137, 139, 149, 151, 157, 47]
|
| 510 |
+
messages = [
|
| 511 |
+
0, 32855, 34303, 14805, 1280, 75859, 38368,
|
| 512 |
+
724, 60356, 51675, 76697, 61854, 18661,
|
| 513 |
+
]
|
| 514 |
+
for p, q in zip(ps, qs):
|
| 515 |
+
pri = gm_private_key(p, q)
|
| 516 |
+
for msg in messages:
|
| 517 |
+
pub = gm_public_key(p, q)
|
| 518 |
+
enc = encipher_gm(msg, pub)
|
| 519 |
+
dec = decipher_gm(enc, pri)
|
| 520 |
+
assert dec == msg
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def test_gm_private_key():
|
| 524 |
+
raises(ValueError, lambda: gm_public_key(13, 15))
|
| 525 |
+
raises(ValueError, lambda: gm_public_key(0, 0))
|
| 526 |
+
raises(ValueError, lambda: gm_public_key(0, 5))
|
| 527 |
+
assert 17, 19 == gm_public_key(17, 19)
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def test_gm_public_key():
|
| 531 |
+
assert 323 == gm_public_key(17, 19)[1]
|
| 532 |
+
assert 15 == gm_public_key(3, 5)[1]
|
| 533 |
+
raises(ValueError, lambda: gm_public_key(15, 19))
|
| 534 |
+
|
| 535 |
+
def test_encipher_decipher_bg():
|
| 536 |
+
ps = [67, 7, 71, 103, 11, 43, 107, 47,
|
| 537 |
+
79, 19, 83, 23, 59, 127, 31]
|
| 538 |
+
qs = qs = [7, 71, 103, 11, 43, 107, 47,
|
| 539 |
+
79, 19, 83, 23, 59, 127, 31, 67]
|
| 540 |
+
messages = [
|
| 541 |
+
0, 328, 343, 148, 1280, 758, 383,
|
| 542 |
+
724, 603, 516, 766, 618, 186,
|
| 543 |
+
]
|
| 544 |
+
|
| 545 |
+
for p, q in zip(ps, qs):
|
| 546 |
+
pri = bg_private_key(p, q)
|
| 547 |
+
for msg in messages:
|
| 548 |
+
pub = bg_public_key(p, q)
|
| 549 |
+
enc = encipher_bg(msg, pub)
|
| 550 |
+
dec = decipher_bg(enc, pri)
|
| 551 |
+
assert dec == msg
|
| 552 |
+
|
| 553 |
+
def test_bg_private_key():
|
| 554 |
+
raises(ValueError, lambda: bg_private_key(8, 16))
|
| 555 |
+
raises(ValueError, lambda: bg_private_key(8, 8))
|
| 556 |
+
raises(ValueError, lambda: bg_private_key(13, 17))
|
| 557 |
+
assert 23, 31 == bg_private_key(23, 31)
|
| 558 |
+
|
| 559 |
+
def test_bg_public_key():
|
| 560 |
+
assert 5293 == bg_public_key(67, 79)
|
| 561 |
+
assert 713 == bg_public_key(23, 31)
|
| 562 |
+
raises(ValueError, lambda: bg_private_key(13, 17))
|
vllm/lib/python3.10/site-packages/sympy/series/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (922 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/series/__pycache__/aseries.cpython-310.pyc
ADDED
|
Binary file (470 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/series/__pycache__/formal.cpython-310.pyc
ADDED
|
Binary file (51.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/series/__pycache__/order.cpython-310.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/series/__pycache__/residues.cpython-310.pyc
ADDED
|
Binary file (1.73 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/series/__pycache__/series.cpython-310.pyc
ADDED
|
Binary file (2.09 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/series/__pycache__/series_class.cpython-310.pyc
ADDED
|
Binary file (3.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/sympy/series/benchmarks/__init__.py
ADDED
|
File without changes
|