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 +3 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/__init__.py +12 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__init__.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/dpll.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/dpll2.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/lra_theory.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/pycosat_wrapper.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/z3_wrapper.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py +308 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/dpll2.py +684 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/lra_theory.py +915 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/minisat22_wrapper.py +46 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/pycosat_wrapper.py +41 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/z3_wrapper.py +115 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/boolalg.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/inference.py +340 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/test_boolalg.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/utilities/__init__.py +3 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/utilities/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/utilities/__pycache__/dimacs.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/logic/utilities/dimacs.py +70 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/plotgrid.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/series.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/textplot.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__init__.py +12 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_arithmetic.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py +452 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_functions.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_series.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/__init__.py +23 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/acceleration.py +101 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/approximants.py +103 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/aseries.py +10 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/formal.py +1869 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/fourier.py +811 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/gruntz.py +739 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/kauers.py +51 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/limits.py +385 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/limitseq.py +257 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/order.py +517 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/series/residues.py +73 -0
.gitattributes
CHANGED
|
@@ -1638,3 +1638,6 @@ evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycach
|
|
| 1638 |
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1639 |
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_systems.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1640 |
evalkit_tf437/lib/python3.10/site-packages/pydantic_core/_pydantic_core.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 1638 |
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1639 |
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_systems.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1640 |
evalkit_tf437/lib/python3.10/site-packages/pydantic_core/_pydantic_core.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1641 |
+
infer_4_47_1/lib/python3.10/site-packages/wandb/bin/wandb-core filter=lfs diff=lfs merge=lfs -text
|
| 1642 |
+
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/ode.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1643 |
+
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .boolalg import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, Implies,
|
| 2 |
+
Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, true, false,
|
| 3 |
+
gateinputcount)
|
| 4 |
+
from .inference import satisfiable
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
|
| 8 |
+
'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
|
| 9 |
+
'bool_map', 'true', 'false', 'gateinputcount',
|
| 10 |
+
|
| 11 |
+
'satisfiable',
|
| 12 |
+
]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc
ADDED
|
Binary file (9.16 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__init__.py
ADDED
|
File without changes
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/dpll.cpython-310.pyc
ADDED
|
Binary file (8.02 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/dpll2.cpython-310.pyc
ADDED
|
Binary file (17.9 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/lra_theory.cpython-310.pyc
ADDED
|
Binary file (29 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/pycosat_wrapper.cpython-310.pyc
ADDED
|
Binary file (1.41 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/__pycache__/z3_wrapper.cpython-310.pyc
ADDED
|
Binary file (4.21 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Implementation of DPLL algorithm
|
| 2 |
+
|
| 3 |
+
Further improvements: eliminate calls to pl_true, implement branching rules,
|
| 4 |
+
efficient unit propagation.
|
| 5 |
+
|
| 6 |
+
References:
|
| 7 |
+
- https://en.wikipedia.org/wiki/DPLL_algorithm
|
| 8 |
+
- https://www.researchgate.net/publication/242384772_Implementations_of_the_DPLL_Algorithm
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from sympy.core.sorting import default_sort_key
|
| 12 |
+
from sympy.logic.boolalg import Or, Not, conjuncts, disjuncts, to_cnf, \
|
| 13 |
+
to_int_repr, _find_predicates
|
| 14 |
+
from sympy.assumptions.cnf import CNF
|
| 15 |
+
from sympy.logic.inference import pl_true, literal_symbol
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def dpll_satisfiable(expr):
|
| 19 |
+
"""
|
| 20 |
+
Check satisfiability of a propositional sentence.
|
| 21 |
+
It returns a model rather than True when it succeeds
|
| 22 |
+
|
| 23 |
+
>>> from sympy.abc import A, B
|
| 24 |
+
>>> from sympy.logic.algorithms.dpll import dpll_satisfiable
|
| 25 |
+
>>> dpll_satisfiable(A & ~B)
|
| 26 |
+
{A: True, B: False}
|
| 27 |
+
>>> dpll_satisfiable(A & ~A)
|
| 28 |
+
False
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
if not isinstance(expr, CNF):
|
| 32 |
+
clauses = conjuncts(to_cnf(expr))
|
| 33 |
+
else:
|
| 34 |
+
clauses = expr.clauses
|
| 35 |
+
if False in clauses:
|
| 36 |
+
return False
|
| 37 |
+
symbols = sorted(_find_predicates(expr), key=default_sort_key)
|
| 38 |
+
symbols_int_repr = set(range(1, len(symbols) + 1))
|
| 39 |
+
clauses_int_repr = to_int_repr(clauses, symbols)
|
| 40 |
+
result = dpll_int_repr(clauses_int_repr, symbols_int_repr, {})
|
| 41 |
+
if not result:
|
| 42 |
+
return result
|
| 43 |
+
output = {}
|
| 44 |
+
for key in result:
|
| 45 |
+
output.update({symbols[key - 1]: result[key]})
|
| 46 |
+
return output
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def dpll(clauses, symbols, model):
|
| 50 |
+
"""
|
| 51 |
+
Compute satisfiability in a partial model.
|
| 52 |
+
Clauses is an array of conjuncts.
|
| 53 |
+
|
| 54 |
+
>>> from sympy.abc import A, B, D
|
| 55 |
+
>>> from sympy.logic.algorithms.dpll import dpll
|
| 56 |
+
>>> dpll([A, B, D], [A, B], {D: False})
|
| 57 |
+
False
|
| 58 |
+
|
| 59 |
+
"""
|
| 60 |
+
# compute DP kernel
|
| 61 |
+
P, value = find_unit_clause(clauses, model)
|
| 62 |
+
while P:
|
| 63 |
+
model.update({P: value})
|
| 64 |
+
symbols.remove(P)
|
| 65 |
+
if not value:
|
| 66 |
+
P = ~P
|
| 67 |
+
clauses = unit_propagate(clauses, P)
|
| 68 |
+
P, value = find_unit_clause(clauses, model)
|
| 69 |
+
P, value = find_pure_symbol(symbols, clauses)
|
| 70 |
+
while P:
|
| 71 |
+
model.update({P: value})
|
| 72 |
+
symbols.remove(P)
|
| 73 |
+
if not value:
|
| 74 |
+
P = ~P
|
| 75 |
+
clauses = unit_propagate(clauses, P)
|
| 76 |
+
P, value = find_pure_symbol(symbols, clauses)
|
| 77 |
+
# end DP kernel
|
| 78 |
+
unknown_clauses = []
|
| 79 |
+
for c in clauses:
|
| 80 |
+
val = pl_true(c, model)
|
| 81 |
+
if val is False:
|
| 82 |
+
return False
|
| 83 |
+
if val is not True:
|
| 84 |
+
unknown_clauses.append(c)
|
| 85 |
+
if not unknown_clauses:
|
| 86 |
+
return model
|
| 87 |
+
if not clauses:
|
| 88 |
+
return model
|
| 89 |
+
P = symbols.pop()
|
| 90 |
+
model_copy = model.copy()
|
| 91 |
+
model.update({P: True})
|
| 92 |
+
model_copy.update({P: False})
|
| 93 |
+
symbols_copy = symbols[:]
|
| 94 |
+
return (dpll(unit_propagate(unknown_clauses, P), symbols, model) or
|
| 95 |
+
dpll(unit_propagate(unknown_clauses, Not(P)), symbols_copy, model_copy))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def dpll_int_repr(clauses, symbols, model):
|
| 99 |
+
"""
|
| 100 |
+
Compute satisfiability in a partial model.
|
| 101 |
+
Arguments are expected to be in integer representation
|
| 102 |
+
|
| 103 |
+
>>> from sympy.logic.algorithms.dpll import dpll_int_repr
|
| 104 |
+
>>> dpll_int_repr([{1}, {2}, {3}], {1, 2}, {3: False})
|
| 105 |
+
False
|
| 106 |
+
|
| 107 |
+
"""
|
| 108 |
+
# compute DP kernel
|
| 109 |
+
P, value = find_unit_clause_int_repr(clauses, model)
|
| 110 |
+
while P:
|
| 111 |
+
model.update({P: value})
|
| 112 |
+
symbols.remove(P)
|
| 113 |
+
if not value:
|
| 114 |
+
P = -P
|
| 115 |
+
clauses = unit_propagate_int_repr(clauses, P)
|
| 116 |
+
P, value = find_unit_clause_int_repr(clauses, model)
|
| 117 |
+
P, value = find_pure_symbol_int_repr(symbols, clauses)
|
| 118 |
+
while P:
|
| 119 |
+
model.update({P: value})
|
| 120 |
+
symbols.remove(P)
|
| 121 |
+
if not value:
|
| 122 |
+
P = -P
|
| 123 |
+
clauses = unit_propagate_int_repr(clauses, P)
|
| 124 |
+
P, value = find_pure_symbol_int_repr(symbols, clauses)
|
| 125 |
+
# end DP kernel
|
| 126 |
+
unknown_clauses = []
|
| 127 |
+
for c in clauses:
|
| 128 |
+
val = pl_true_int_repr(c, model)
|
| 129 |
+
if val is False:
|
| 130 |
+
return False
|
| 131 |
+
if val is not True:
|
| 132 |
+
unknown_clauses.append(c)
|
| 133 |
+
if not unknown_clauses:
|
| 134 |
+
return model
|
| 135 |
+
P = symbols.pop()
|
| 136 |
+
model_copy = model.copy()
|
| 137 |
+
model.update({P: True})
|
| 138 |
+
model_copy.update({P: False})
|
| 139 |
+
symbols_copy = symbols.copy()
|
| 140 |
+
return (dpll_int_repr(unit_propagate_int_repr(unknown_clauses, P), symbols, model) or
|
| 141 |
+
dpll_int_repr(unit_propagate_int_repr(unknown_clauses, -P), symbols_copy, model_copy))
|
| 142 |
+
|
| 143 |
+
### helper methods for DPLL
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def pl_true_int_repr(clause, model={}):
|
| 147 |
+
"""
|
| 148 |
+
Lightweight version of pl_true.
|
| 149 |
+
Argument clause represents the set of args of an Or clause. This is used
|
| 150 |
+
inside dpll_int_repr, it is not meant to be used directly.
|
| 151 |
+
|
| 152 |
+
>>> from sympy.logic.algorithms.dpll import pl_true_int_repr
|
| 153 |
+
>>> pl_true_int_repr({1, 2}, {1: False})
|
| 154 |
+
>>> pl_true_int_repr({1, 2}, {1: False, 2: False})
|
| 155 |
+
False
|
| 156 |
+
|
| 157 |
+
"""
|
| 158 |
+
result = False
|
| 159 |
+
for lit in clause:
|
| 160 |
+
if lit < 0:
|
| 161 |
+
p = model.get(-lit)
|
| 162 |
+
if p is not None:
|
| 163 |
+
p = not p
|
| 164 |
+
else:
|
| 165 |
+
p = model.get(lit)
|
| 166 |
+
if p is True:
|
| 167 |
+
return True
|
| 168 |
+
elif p is None:
|
| 169 |
+
result = None
|
| 170 |
+
return result
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def unit_propagate(clauses, symbol):
|
| 174 |
+
"""
|
| 175 |
+
Returns an equivalent set of clauses
|
| 176 |
+
If a set of clauses contains the unit clause l, the other clauses are
|
| 177 |
+
simplified by the application of the two following rules:
|
| 178 |
+
|
| 179 |
+
1. every clause containing l is removed
|
| 180 |
+
2. in every clause that contains ~l this literal is deleted
|
| 181 |
+
|
| 182 |
+
Arguments are expected to be in CNF.
|
| 183 |
+
|
| 184 |
+
>>> from sympy.abc import A, B, D
|
| 185 |
+
>>> from sympy.logic.algorithms.dpll import unit_propagate
|
| 186 |
+
>>> unit_propagate([A | B, D | ~B, B], B)
|
| 187 |
+
[D, B]
|
| 188 |
+
|
| 189 |
+
"""
|
| 190 |
+
output = []
|
| 191 |
+
for c in clauses:
|
| 192 |
+
if c.func != Or:
|
| 193 |
+
output.append(c)
|
| 194 |
+
continue
|
| 195 |
+
for arg in c.args:
|
| 196 |
+
if arg == ~symbol:
|
| 197 |
+
output.append(Or(*[x for x in c.args if x != ~symbol]))
|
| 198 |
+
break
|
| 199 |
+
if arg == symbol:
|
| 200 |
+
break
|
| 201 |
+
else:
|
| 202 |
+
output.append(c)
|
| 203 |
+
return output
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def unit_propagate_int_repr(clauses, s):
|
| 207 |
+
"""
|
| 208 |
+
Same as unit_propagate, but arguments are expected to be in integer
|
| 209 |
+
representation
|
| 210 |
+
|
| 211 |
+
>>> from sympy.logic.algorithms.dpll import unit_propagate_int_repr
|
| 212 |
+
>>> unit_propagate_int_repr([{1, 2}, {3, -2}, {2}], 2)
|
| 213 |
+
[{3}]
|
| 214 |
+
|
| 215 |
+
"""
|
| 216 |
+
negated = {-s}
|
| 217 |
+
return [clause - negated for clause in clauses if s not in clause]
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def find_pure_symbol(symbols, unknown_clauses):
|
| 221 |
+
"""
|
| 222 |
+
Find a symbol and its value if it appears only as a positive literal
|
| 223 |
+
(or only as a negative) in clauses.
|
| 224 |
+
|
| 225 |
+
>>> from sympy.abc import A, B, D
|
| 226 |
+
>>> from sympy.logic.algorithms.dpll import find_pure_symbol
|
| 227 |
+
>>> find_pure_symbol([A, B, D], [A|~B,~B|~D,D|A])
|
| 228 |
+
(A, True)
|
| 229 |
+
|
| 230 |
+
"""
|
| 231 |
+
for sym in symbols:
|
| 232 |
+
found_pos, found_neg = False, False
|
| 233 |
+
for c in unknown_clauses:
|
| 234 |
+
if not found_pos and sym in disjuncts(c):
|
| 235 |
+
found_pos = True
|
| 236 |
+
if not found_neg and Not(sym) in disjuncts(c):
|
| 237 |
+
found_neg = True
|
| 238 |
+
if found_pos != found_neg:
|
| 239 |
+
return sym, found_pos
|
| 240 |
+
return None, None
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def find_pure_symbol_int_repr(symbols, unknown_clauses):
|
| 244 |
+
"""
|
| 245 |
+
Same as find_pure_symbol, but arguments are expected
|
| 246 |
+
to be in integer representation
|
| 247 |
+
|
| 248 |
+
>>> from sympy.logic.algorithms.dpll import find_pure_symbol_int_repr
|
| 249 |
+
>>> find_pure_symbol_int_repr({1,2,3},
|
| 250 |
+
... [{1, -2}, {-2, -3}, {3, 1}])
|
| 251 |
+
(1, True)
|
| 252 |
+
|
| 253 |
+
"""
|
| 254 |
+
all_symbols = set().union(*unknown_clauses)
|
| 255 |
+
found_pos = all_symbols.intersection(symbols)
|
| 256 |
+
found_neg = all_symbols.intersection([-s for s in symbols])
|
| 257 |
+
for p in found_pos:
|
| 258 |
+
if -p not in found_neg:
|
| 259 |
+
return p, True
|
| 260 |
+
for p in found_neg:
|
| 261 |
+
if -p not in found_pos:
|
| 262 |
+
return -p, False
|
| 263 |
+
return None, None
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def find_unit_clause(clauses, model):
|
| 267 |
+
"""
|
| 268 |
+
A unit clause has only 1 variable that is not bound in the model.
|
| 269 |
+
|
| 270 |
+
>>> from sympy.abc import A, B, D
|
| 271 |
+
>>> from sympy.logic.algorithms.dpll import find_unit_clause
|
| 272 |
+
>>> find_unit_clause([A | B | D, B | ~D, A | ~B], {A:True})
|
| 273 |
+
(B, False)
|
| 274 |
+
|
| 275 |
+
"""
|
| 276 |
+
for clause in clauses:
|
| 277 |
+
num_not_in_model = 0
|
| 278 |
+
for literal in disjuncts(clause):
|
| 279 |
+
sym = literal_symbol(literal)
|
| 280 |
+
if sym not in model:
|
| 281 |
+
num_not_in_model += 1
|
| 282 |
+
P, value = sym, not isinstance(literal, Not)
|
| 283 |
+
if num_not_in_model == 1:
|
| 284 |
+
return P, value
|
| 285 |
+
return None, None
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def find_unit_clause_int_repr(clauses, model):
|
| 289 |
+
"""
|
| 290 |
+
Same as find_unit_clause, but arguments are expected to be in
|
| 291 |
+
integer representation.
|
| 292 |
+
|
| 293 |
+
>>> from sympy.logic.algorithms.dpll import find_unit_clause_int_repr
|
| 294 |
+
>>> find_unit_clause_int_repr([{1, 2, 3},
|
| 295 |
+
... {2, -3}, {1, -2}], {1: True})
|
| 296 |
+
(2, False)
|
| 297 |
+
|
| 298 |
+
"""
|
| 299 |
+
bound = set(model) | {-sym for sym in model}
|
| 300 |
+
for clause in clauses:
|
| 301 |
+
unbound = clause - bound
|
| 302 |
+
if len(unbound) == 1:
|
| 303 |
+
p = unbound.pop()
|
| 304 |
+
if p < 0:
|
| 305 |
+
return -p, False
|
| 306 |
+
else:
|
| 307 |
+
return p, True
|
| 308 |
+
return None, None
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/dpll2.py
ADDED
|
@@ -0,0 +1,684 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Implementation of DPLL algorithm
|
| 2 |
+
|
| 3 |
+
Features:
|
| 4 |
+
- Clause learning
|
| 5 |
+
- Watch literal scheme
|
| 6 |
+
- VSIDS heuristic
|
| 7 |
+
|
| 8 |
+
References:
|
| 9 |
+
- https://en.wikipedia.org/wiki/DPLL_algorithm
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
from heapq import heappush, heappop
|
| 14 |
+
|
| 15 |
+
from sympy.core.sorting import ordered
|
| 16 |
+
from sympy.assumptions.cnf import EncodedCNF
|
| 17 |
+
|
| 18 |
+
from sympy.logic.algorithms.lra_theory import LRASolver
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def dpll_satisfiable(expr, all_models=False, use_lra_theory=False):
|
| 22 |
+
"""
|
| 23 |
+
Check satisfiability of a propositional sentence.
|
| 24 |
+
It returns a model rather than True when it succeeds.
|
| 25 |
+
Returns a generator of all models if all_models is True.
|
| 26 |
+
|
| 27 |
+
Examples
|
| 28 |
+
========
|
| 29 |
+
|
| 30 |
+
>>> from sympy.abc import A, B
|
| 31 |
+
>>> from sympy.logic.algorithms.dpll2 import dpll_satisfiable
|
| 32 |
+
>>> dpll_satisfiable(A & ~B)
|
| 33 |
+
{A: True, B: False}
|
| 34 |
+
>>> dpll_satisfiable(A & ~A)
|
| 35 |
+
False
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
if not isinstance(expr, EncodedCNF):
|
| 39 |
+
exprs = EncodedCNF()
|
| 40 |
+
exprs.add_prop(expr)
|
| 41 |
+
expr = exprs
|
| 42 |
+
|
| 43 |
+
# Return UNSAT when False (encoded as 0) is present in the CNF
|
| 44 |
+
if {0} in expr.data:
|
| 45 |
+
if all_models:
|
| 46 |
+
return (f for f in [False])
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
if use_lra_theory:
|
| 50 |
+
lra, immediate_conflicts = LRASolver.from_encoded_cnf(expr)
|
| 51 |
+
else:
|
| 52 |
+
lra = None
|
| 53 |
+
immediate_conflicts = []
|
| 54 |
+
solver = SATSolver(expr.data + immediate_conflicts, expr.variables, set(), expr.symbols, lra_theory=lra)
|
| 55 |
+
models = solver._find_model()
|
| 56 |
+
|
| 57 |
+
if all_models:
|
| 58 |
+
return _all_models(models)
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
return next(models)
|
| 62 |
+
except StopIteration:
|
| 63 |
+
return False
|
| 64 |
+
|
| 65 |
+
# Uncomment to confirm the solution is valid (hitting set for the clauses)
|
| 66 |
+
#else:
|
| 67 |
+
#for cls in clauses_int_repr:
|
| 68 |
+
#assert solver.var_settings.intersection(cls)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _all_models(models):
|
| 72 |
+
satisfiable = False
|
| 73 |
+
try:
|
| 74 |
+
while True:
|
| 75 |
+
yield next(models)
|
| 76 |
+
satisfiable = True
|
| 77 |
+
except StopIteration:
|
| 78 |
+
if not satisfiable:
|
| 79 |
+
yield False
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class SATSolver:
|
| 83 |
+
"""
|
| 84 |
+
Class for representing a SAT solver capable of
|
| 85 |
+
finding a model to a boolean theory in conjunctive
|
| 86 |
+
normal form.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(self, clauses, variables, var_settings, symbols=None,
|
| 90 |
+
heuristic='vsids', clause_learning='none', INTERVAL=500,
|
| 91 |
+
lra_theory = None):
|
| 92 |
+
|
| 93 |
+
self.var_settings = var_settings
|
| 94 |
+
self.heuristic = heuristic
|
| 95 |
+
self.is_unsatisfied = False
|
| 96 |
+
self._unit_prop_queue = []
|
| 97 |
+
self.update_functions = []
|
| 98 |
+
self.INTERVAL = INTERVAL
|
| 99 |
+
|
| 100 |
+
if symbols is None:
|
| 101 |
+
self.symbols = list(ordered(variables))
|
| 102 |
+
else:
|
| 103 |
+
self.symbols = symbols
|
| 104 |
+
|
| 105 |
+
self._initialize_variables(variables)
|
| 106 |
+
self._initialize_clauses(clauses)
|
| 107 |
+
|
| 108 |
+
if 'vsids' == heuristic:
|
| 109 |
+
self._vsids_init()
|
| 110 |
+
self.heur_calculate = self._vsids_calculate
|
| 111 |
+
self.heur_lit_assigned = self._vsids_lit_assigned
|
| 112 |
+
self.heur_lit_unset = self._vsids_lit_unset
|
| 113 |
+
self.heur_clause_added = self._vsids_clause_added
|
| 114 |
+
|
| 115 |
+
# Note: Uncomment this if/when clause learning is enabled
|
| 116 |
+
#self.update_functions.append(self._vsids_decay)
|
| 117 |
+
|
| 118 |
+
else:
|
| 119 |
+
raise NotImplementedError
|
| 120 |
+
|
| 121 |
+
if 'simple' == clause_learning:
|
| 122 |
+
self.add_learned_clause = self._simple_add_learned_clause
|
| 123 |
+
self.compute_conflict = self._simple_compute_conflict
|
| 124 |
+
self.update_functions.append(self._simple_clean_clauses)
|
| 125 |
+
elif 'none' == clause_learning:
|
| 126 |
+
self.add_learned_clause = lambda x: None
|
| 127 |
+
self.compute_conflict = lambda: None
|
| 128 |
+
else:
|
| 129 |
+
raise NotImplementedError
|
| 130 |
+
|
| 131 |
+
# Create the base level
|
| 132 |
+
self.levels = [Level(0)]
|
| 133 |
+
self._current_level.varsettings = var_settings
|
| 134 |
+
|
| 135 |
+
# Keep stats
|
| 136 |
+
self.num_decisions = 0
|
| 137 |
+
self.num_learned_clauses = 0
|
| 138 |
+
self.original_num_clauses = len(self.clauses)
|
| 139 |
+
|
| 140 |
+
self.lra = lra_theory
|
| 141 |
+
|
| 142 |
+
def _initialize_variables(self, variables):
|
| 143 |
+
"""Set up the variable data structures needed."""
|
| 144 |
+
self.sentinels = defaultdict(set)
|
| 145 |
+
self.occurrence_count = defaultdict(int)
|
| 146 |
+
self.variable_set = [False] * (len(variables) + 1)
|
| 147 |
+
|
| 148 |
+
def _initialize_clauses(self, clauses):
|
| 149 |
+
"""Set up the clause data structures needed.
|
| 150 |
+
|
| 151 |
+
For each clause, the following changes are made:
|
| 152 |
+
- Unit clauses are queued for propagation right away.
|
| 153 |
+
- Non-unit clauses have their first and last literals set as sentinels.
|
| 154 |
+
- The number of clauses a literal appears in is computed.
|
| 155 |
+
"""
|
| 156 |
+
self.clauses = [list(clause) for clause in clauses]
|
| 157 |
+
|
| 158 |
+
for i, clause in enumerate(self.clauses):
|
| 159 |
+
|
| 160 |
+
# Handle the unit clauses
|
| 161 |
+
if 1 == len(clause):
|
| 162 |
+
self._unit_prop_queue.append(clause[0])
|
| 163 |
+
continue
|
| 164 |
+
|
| 165 |
+
self.sentinels[clause[0]].add(i)
|
| 166 |
+
self.sentinels[clause[-1]].add(i)
|
| 167 |
+
|
| 168 |
+
for lit in clause:
|
| 169 |
+
self.occurrence_count[lit] += 1
|
| 170 |
+
|
| 171 |
+
def _find_model(self):
|
| 172 |
+
"""
|
| 173 |
+
Main DPLL loop. Returns a generator of models.
|
| 174 |
+
|
| 175 |
+
Variables are chosen successively, and assigned to be either
|
| 176 |
+
True or False. If a solution is not found with this setting,
|
| 177 |
+
the opposite is chosen and the search continues. The solver
|
| 178 |
+
halts when every variable has a setting.
|
| 179 |
+
|
| 180 |
+
Examples
|
| 181 |
+
========
|
| 182 |
+
|
| 183 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 184 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 185 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 186 |
+
>>> list(l._find_model())
|
| 187 |
+
[{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}]
|
| 188 |
+
|
| 189 |
+
>>> from sympy.abc import A, B, C
|
| 190 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 191 |
+
... {3, -2}], {1, 2, 3}, set(), [A, B, C])
|
| 192 |
+
>>> list(l._find_model())
|
| 193 |
+
[{A: True, B: False, C: False}, {A: True, B: True, C: True}]
|
| 194 |
+
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
# We use this variable to keep track of if we should flip a
|
| 198 |
+
# variable setting in successive rounds
|
| 199 |
+
flip_var = False
|
| 200 |
+
|
| 201 |
+
# Check if unit prop says the theory is unsat right off the bat
|
| 202 |
+
self._simplify()
|
| 203 |
+
if self.is_unsatisfied:
|
| 204 |
+
return
|
| 205 |
+
|
| 206 |
+
# While the theory still has clauses remaining
|
| 207 |
+
while True:
|
| 208 |
+
# Perform cleanup / fixup at regular intervals
|
| 209 |
+
if self.num_decisions % self.INTERVAL == 0:
|
| 210 |
+
for func in self.update_functions:
|
| 211 |
+
func()
|
| 212 |
+
|
| 213 |
+
if flip_var:
|
| 214 |
+
# We have just backtracked and we are trying to opposite literal
|
| 215 |
+
flip_var = False
|
| 216 |
+
lit = self._current_level.decision
|
| 217 |
+
|
| 218 |
+
else:
|
| 219 |
+
# Pick a literal to set
|
| 220 |
+
lit = self.heur_calculate()
|
| 221 |
+
self.num_decisions += 1
|
| 222 |
+
|
| 223 |
+
# Stopping condition for a satisfying theory
|
| 224 |
+
if 0 == lit:
|
| 225 |
+
|
| 226 |
+
# check if assignment satisfies lra theory
|
| 227 |
+
if self.lra:
|
| 228 |
+
for enc_var in self.var_settings:
|
| 229 |
+
res = self.lra.assert_lit(enc_var)
|
| 230 |
+
if res is not None:
|
| 231 |
+
break
|
| 232 |
+
res = self.lra.check()
|
| 233 |
+
self.lra.reset_bounds()
|
| 234 |
+
else:
|
| 235 |
+
res = None
|
| 236 |
+
if res is None or res[0]:
|
| 237 |
+
yield {self.symbols[abs(lit) - 1]:
|
| 238 |
+
lit > 0 for lit in self.var_settings}
|
| 239 |
+
else:
|
| 240 |
+
self._simple_add_learned_clause(res[1])
|
| 241 |
+
|
| 242 |
+
while self._current_level.flipped:
|
| 243 |
+
self._undo()
|
| 244 |
+
if len(self.levels) == 1:
|
| 245 |
+
return
|
| 246 |
+
flip_lit = -self._current_level.decision
|
| 247 |
+
self._undo()
|
| 248 |
+
self.levels.append(Level(flip_lit, flipped=True))
|
| 249 |
+
flip_var = True
|
| 250 |
+
continue
|
| 251 |
+
|
| 252 |
+
# Start the new decision level
|
| 253 |
+
self.levels.append(Level(lit))
|
| 254 |
+
|
| 255 |
+
# Assign the literal, updating the clauses it satisfies
|
| 256 |
+
self._assign_literal(lit)
|
| 257 |
+
|
| 258 |
+
# _simplify the theory
|
| 259 |
+
self._simplify()
|
| 260 |
+
|
| 261 |
+
# Check if we've made the theory unsat
|
| 262 |
+
if self.is_unsatisfied:
|
| 263 |
+
|
| 264 |
+
self.is_unsatisfied = False
|
| 265 |
+
|
| 266 |
+
# We unroll all of the decisions until we can flip a literal
|
| 267 |
+
while self._current_level.flipped:
|
| 268 |
+
self._undo()
|
| 269 |
+
|
| 270 |
+
# If we've unrolled all the way, the theory is unsat
|
| 271 |
+
if 1 == len(self.levels):
|
| 272 |
+
return
|
| 273 |
+
|
| 274 |
+
# Detect and add a learned clause
|
| 275 |
+
self.add_learned_clause(self.compute_conflict())
|
| 276 |
+
|
| 277 |
+
# Try the opposite setting of the most recent decision
|
| 278 |
+
flip_lit = -self._current_level.decision
|
| 279 |
+
self._undo()
|
| 280 |
+
self.levels.append(Level(flip_lit, flipped=True))
|
| 281 |
+
flip_var = True
|
| 282 |
+
|
| 283 |
+
########################
|
| 284 |
+
# Helper Methods #
|
| 285 |
+
########################
|
| 286 |
+
@property
|
| 287 |
+
def _current_level(self):
|
| 288 |
+
"""The current decision level data structure
|
| 289 |
+
|
| 290 |
+
Examples
|
| 291 |
+
========
|
| 292 |
+
|
| 293 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 294 |
+
>>> l = SATSolver([{1}, {2}], {1, 2}, set())
|
| 295 |
+
>>> next(l._find_model())
|
| 296 |
+
{1: True, 2: True}
|
| 297 |
+
>>> l._current_level.decision
|
| 298 |
+
0
|
| 299 |
+
>>> l._current_level.flipped
|
| 300 |
+
False
|
| 301 |
+
>>> l._current_level.var_settings
|
| 302 |
+
{1, 2}
|
| 303 |
+
|
| 304 |
+
"""
|
| 305 |
+
return self.levels[-1]
|
| 306 |
+
|
| 307 |
+
def _clause_sat(self, cls):
|
| 308 |
+
"""Check if a clause is satisfied by the current variable setting.
|
| 309 |
+
|
| 310 |
+
Examples
|
| 311 |
+
========
|
| 312 |
+
|
| 313 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 314 |
+
>>> l = SATSolver([{1}, {-1}], {1}, set())
|
| 315 |
+
>>> try:
|
| 316 |
+
... next(l._find_model())
|
| 317 |
+
... except StopIteration:
|
| 318 |
+
... pass
|
| 319 |
+
>>> l._clause_sat(0)
|
| 320 |
+
False
|
| 321 |
+
>>> l._clause_sat(1)
|
| 322 |
+
True
|
| 323 |
+
|
| 324 |
+
"""
|
| 325 |
+
for lit in self.clauses[cls]:
|
| 326 |
+
if lit in self.var_settings:
|
| 327 |
+
return True
|
| 328 |
+
return False
|
| 329 |
+
|
| 330 |
+
def _is_sentinel(self, lit, cls):
|
| 331 |
+
"""Check if a literal is a sentinel of a given clause.
|
| 332 |
+
|
| 333 |
+
Examples
|
| 334 |
+
========
|
| 335 |
+
|
| 336 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 337 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 338 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 339 |
+
>>> next(l._find_model())
|
| 340 |
+
{1: True, 2: False, 3: False}
|
| 341 |
+
>>> l._is_sentinel(2, 3)
|
| 342 |
+
True
|
| 343 |
+
>>> l._is_sentinel(-3, 1)
|
| 344 |
+
False
|
| 345 |
+
|
| 346 |
+
"""
|
| 347 |
+
return cls in self.sentinels[lit]
|
| 348 |
+
|
| 349 |
+
def _assign_literal(self, lit):
|
| 350 |
+
"""Make a literal assignment.
|
| 351 |
+
|
| 352 |
+
The literal assignment must be recorded as part of the current
|
| 353 |
+
decision level. Additionally, if the literal is marked as a
|
| 354 |
+
sentinel of any clause, then a new sentinel must be chosen. If
|
| 355 |
+
this is not possible, then unit propagation is triggered and
|
| 356 |
+
another literal is added to the queue to be set in the future.
|
| 357 |
+
|
| 358 |
+
Examples
|
| 359 |
+
========
|
| 360 |
+
|
| 361 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 362 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 363 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 364 |
+
>>> next(l._find_model())
|
| 365 |
+
{1: True, 2: False, 3: False}
|
| 366 |
+
>>> l.var_settings
|
| 367 |
+
{-3, -2, 1}
|
| 368 |
+
|
| 369 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 370 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 371 |
+
>>> l._assign_literal(-1)
|
| 372 |
+
>>> try:
|
| 373 |
+
... next(l._find_model())
|
| 374 |
+
... except StopIteration:
|
| 375 |
+
... pass
|
| 376 |
+
>>> l.var_settings
|
| 377 |
+
{-1}
|
| 378 |
+
|
| 379 |
+
"""
|
| 380 |
+
self.var_settings.add(lit)
|
| 381 |
+
self._current_level.var_settings.add(lit)
|
| 382 |
+
self.variable_set[abs(lit)] = True
|
| 383 |
+
self.heur_lit_assigned(lit)
|
| 384 |
+
|
| 385 |
+
sentinel_list = list(self.sentinels[-lit])
|
| 386 |
+
|
| 387 |
+
for cls in sentinel_list:
|
| 388 |
+
if not self._clause_sat(cls):
|
| 389 |
+
other_sentinel = None
|
| 390 |
+
for newlit in self.clauses[cls]:
|
| 391 |
+
if newlit != -lit:
|
| 392 |
+
if self._is_sentinel(newlit, cls):
|
| 393 |
+
other_sentinel = newlit
|
| 394 |
+
elif not self.variable_set[abs(newlit)]:
|
| 395 |
+
self.sentinels[-lit].remove(cls)
|
| 396 |
+
self.sentinels[newlit].add(cls)
|
| 397 |
+
other_sentinel = None
|
| 398 |
+
break
|
| 399 |
+
|
| 400 |
+
# Check if no sentinel update exists
|
| 401 |
+
if other_sentinel:
|
| 402 |
+
self._unit_prop_queue.append(other_sentinel)
|
| 403 |
+
|
| 404 |
+
def _undo(self):
|
| 405 |
+
"""
|
| 406 |
+
_undo the changes of the most recent decision level.
|
| 407 |
+
|
| 408 |
+
Examples
|
| 409 |
+
========
|
| 410 |
+
|
| 411 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 412 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 413 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 414 |
+
>>> next(l._find_model())
|
| 415 |
+
{1: True, 2: False, 3: False}
|
| 416 |
+
>>> level = l._current_level
|
| 417 |
+
>>> level.decision, level.var_settings, level.flipped
|
| 418 |
+
(-3, {-3, -2}, False)
|
| 419 |
+
>>> l._undo()
|
| 420 |
+
>>> level = l._current_level
|
| 421 |
+
>>> level.decision, level.var_settings, level.flipped
|
| 422 |
+
(0, {1}, False)
|
| 423 |
+
|
| 424 |
+
"""
|
| 425 |
+
# Undo the variable settings
|
| 426 |
+
for lit in self._current_level.var_settings:
|
| 427 |
+
self.var_settings.remove(lit)
|
| 428 |
+
self.heur_lit_unset(lit)
|
| 429 |
+
self.variable_set[abs(lit)] = False
|
| 430 |
+
|
| 431 |
+
# Pop the level off the stack
|
| 432 |
+
self.levels.pop()
|
| 433 |
+
|
| 434 |
+
#########################
|
| 435 |
+
# Propagation #
|
| 436 |
+
#########################
|
| 437 |
+
"""
|
| 438 |
+
Propagation methods should attempt to soundly simplify the boolean
|
| 439 |
+
theory, and return True if any simplification occurred and False
|
| 440 |
+
otherwise.
|
| 441 |
+
"""
|
| 442 |
+
def _simplify(self):
|
| 443 |
+
"""Iterate over the various forms of propagation to simplify the theory.
|
| 444 |
+
|
| 445 |
+
Examples
|
| 446 |
+
========
|
| 447 |
+
|
| 448 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 449 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 450 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 451 |
+
>>> l.variable_set
|
| 452 |
+
[False, False, False, False]
|
| 453 |
+
>>> l.sentinels
|
| 454 |
+
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
|
| 455 |
+
|
| 456 |
+
>>> l._simplify()
|
| 457 |
+
|
| 458 |
+
>>> l.variable_set
|
| 459 |
+
[False, True, False, False]
|
| 460 |
+
>>> l.sentinels
|
| 461 |
+
{-3: {0, 2}, -2: {3, 4}, -1: set(), 2: {0, 3},
|
| 462 |
+
...3: {2, 4}}
|
| 463 |
+
|
| 464 |
+
"""
|
| 465 |
+
changed = True
|
| 466 |
+
while changed:
|
| 467 |
+
changed = False
|
| 468 |
+
changed |= self._unit_prop()
|
| 469 |
+
changed |= self._pure_literal()
|
| 470 |
+
|
| 471 |
+
def _unit_prop(self):
|
| 472 |
+
"""Perform unit propagation on the current theory."""
|
| 473 |
+
result = len(self._unit_prop_queue) > 0
|
| 474 |
+
while self._unit_prop_queue:
|
| 475 |
+
next_lit = self._unit_prop_queue.pop()
|
| 476 |
+
if -next_lit in self.var_settings:
|
| 477 |
+
self.is_unsatisfied = True
|
| 478 |
+
self._unit_prop_queue = []
|
| 479 |
+
return False
|
| 480 |
+
else:
|
| 481 |
+
self._assign_literal(next_lit)
|
| 482 |
+
|
| 483 |
+
return result
|
| 484 |
+
|
| 485 |
+
def _pure_literal(self):
|
| 486 |
+
"""Look for pure literals and assign them when found."""
|
| 487 |
+
return False
|
| 488 |
+
|
| 489 |
+
#########################
|
| 490 |
+
# Heuristics #
|
| 491 |
+
#########################
|
| 492 |
+
def _vsids_init(self):
|
| 493 |
+
"""Initialize the data structures needed for the VSIDS heuristic."""
|
| 494 |
+
self.lit_heap = []
|
| 495 |
+
self.lit_scores = {}
|
| 496 |
+
|
| 497 |
+
for var in range(1, len(self.variable_set)):
|
| 498 |
+
self.lit_scores[var] = float(-self.occurrence_count[var])
|
| 499 |
+
self.lit_scores[-var] = float(-self.occurrence_count[-var])
|
| 500 |
+
heappush(self.lit_heap, (self.lit_scores[var], var))
|
| 501 |
+
heappush(self.lit_heap, (self.lit_scores[-var], -var))
|
| 502 |
+
|
| 503 |
+
def _vsids_decay(self):
|
| 504 |
+
"""Decay the VSIDS scores for every literal.
|
| 505 |
+
|
| 506 |
+
Examples
|
| 507 |
+
========
|
| 508 |
+
|
| 509 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 510 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 511 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 512 |
+
|
| 513 |
+
>>> l.lit_scores
|
| 514 |
+
{-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
|
| 515 |
+
|
| 516 |
+
>>> l._vsids_decay()
|
| 517 |
+
|
| 518 |
+
>>> l.lit_scores
|
| 519 |
+
{-3: -1.0, -2: -1.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -1.0}
|
| 520 |
+
|
| 521 |
+
"""
|
| 522 |
+
# We divide every literal score by 2 for a decay factor
|
| 523 |
+
# Note: This doesn't change the heap property
|
| 524 |
+
for lit in self.lit_scores.keys():
|
| 525 |
+
self.lit_scores[lit] /= 2.0
|
| 526 |
+
|
| 527 |
+
def _vsids_calculate(self):
|
| 528 |
+
"""
|
| 529 |
+
VSIDS Heuristic Calculation
|
| 530 |
+
|
| 531 |
+
Examples
|
| 532 |
+
========
|
| 533 |
+
|
| 534 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 535 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 536 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 537 |
+
|
| 538 |
+
>>> l.lit_heap
|
| 539 |
+
[(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
|
| 540 |
+
|
| 541 |
+
>>> l._vsids_calculate()
|
| 542 |
+
-3
|
| 543 |
+
|
| 544 |
+
>>> l.lit_heap
|
| 545 |
+
[(-2.0, -2), (-2.0, 2), (0.0, -1), (0.0, 1), (-2.0, 3)]
|
| 546 |
+
|
| 547 |
+
"""
|
| 548 |
+
if len(self.lit_heap) == 0:
|
| 549 |
+
return 0
|
| 550 |
+
|
| 551 |
+
# Clean out the front of the heap as long the variables are set
|
| 552 |
+
while self.variable_set[abs(self.lit_heap[0][1])]:
|
| 553 |
+
heappop(self.lit_heap)
|
| 554 |
+
if len(self.lit_heap) == 0:
|
| 555 |
+
return 0
|
| 556 |
+
|
| 557 |
+
return heappop(self.lit_heap)[1]
|
| 558 |
+
|
| 559 |
+
def _vsids_lit_assigned(self, lit):
|
| 560 |
+
"""Handle the assignment of a literal for the VSIDS heuristic."""
|
| 561 |
+
pass
|
| 562 |
+
|
| 563 |
+
def _vsids_lit_unset(self, lit):
|
| 564 |
+
"""Handle the unsetting of a literal for the VSIDS heuristic.
|
| 565 |
+
|
| 566 |
+
Examples
|
| 567 |
+
========
|
| 568 |
+
|
| 569 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 570 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 571 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 572 |
+
>>> l.lit_heap
|
| 573 |
+
[(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
|
| 574 |
+
|
| 575 |
+
>>> l._vsids_lit_unset(2)
|
| 576 |
+
|
| 577 |
+
>>> l.lit_heap
|
| 578 |
+
[(-2.0, -3), (-2.0, -2), (-2.0, -2), (-2.0, 2), (-2.0, 3), (0.0, -1),
|
| 579 |
+
...(-2.0, 2), (0.0, 1)]
|
| 580 |
+
|
| 581 |
+
"""
|
| 582 |
+
var = abs(lit)
|
| 583 |
+
heappush(self.lit_heap, (self.lit_scores[var], var))
|
| 584 |
+
heappush(self.lit_heap, (self.lit_scores[-var], -var))
|
| 585 |
+
|
| 586 |
+
def _vsids_clause_added(self, cls):
|
| 587 |
+
"""Handle the addition of a new clause for the VSIDS heuristic.
|
| 588 |
+
|
| 589 |
+
Examples
|
| 590 |
+
========
|
| 591 |
+
|
| 592 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 593 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 594 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 595 |
+
|
| 596 |
+
>>> l.num_learned_clauses
|
| 597 |
+
0
|
| 598 |
+
>>> l.lit_scores
|
| 599 |
+
{-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
|
| 600 |
+
|
| 601 |
+
>>> l._vsids_clause_added({2, -3})
|
| 602 |
+
|
| 603 |
+
>>> l.num_learned_clauses
|
| 604 |
+
1
|
| 605 |
+
>>> l.lit_scores
|
| 606 |
+
{-3: -1.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -2.0}
|
| 607 |
+
|
| 608 |
+
"""
|
| 609 |
+
self.num_learned_clauses += 1
|
| 610 |
+
for lit in cls:
|
| 611 |
+
self.lit_scores[lit] += 1
|
| 612 |
+
|
| 613 |
+
########################
|
| 614 |
+
# Clause Learning #
|
| 615 |
+
########################
|
| 616 |
+
def _simple_add_learned_clause(self, cls):
|
| 617 |
+
"""Add a new clause to the theory.
|
| 618 |
+
|
| 619 |
+
Examples
|
| 620 |
+
========
|
| 621 |
+
|
| 622 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 623 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 624 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 625 |
+
|
| 626 |
+
>>> l.num_learned_clauses
|
| 627 |
+
0
|
| 628 |
+
>>> l.clauses
|
| 629 |
+
[[2, -3], [1], [3, -3], [2, -2], [3, -2]]
|
| 630 |
+
>>> l.sentinels
|
| 631 |
+
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
|
| 632 |
+
|
| 633 |
+
>>> l._simple_add_learned_clause([3])
|
| 634 |
+
|
| 635 |
+
>>> l.clauses
|
| 636 |
+
[[2, -3], [1], [3, -3], [2, -2], [3, -2], [3]]
|
| 637 |
+
>>> l.sentinels
|
| 638 |
+
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4, 5}}
|
| 639 |
+
|
| 640 |
+
"""
|
| 641 |
+
cls_num = len(self.clauses)
|
| 642 |
+
self.clauses.append(cls)
|
| 643 |
+
|
| 644 |
+
for lit in cls:
|
| 645 |
+
self.occurrence_count[lit] += 1
|
| 646 |
+
|
| 647 |
+
self.sentinels[cls[0]].add(cls_num)
|
| 648 |
+
self.sentinels[cls[-1]].add(cls_num)
|
| 649 |
+
|
| 650 |
+
self.heur_clause_added(cls)
|
| 651 |
+
|
| 652 |
+
def _simple_compute_conflict(self):
|
| 653 |
+
""" Build a clause representing the fact that at least one decision made
|
| 654 |
+
so far is wrong.
|
| 655 |
+
|
| 656 |
+
Examples
|
| 657 |
+
========
|
| 658 |
+
|
| 659 |
+
>>> from sympy.logic.algorithms.dpll2 import SATSolver
|
| 660 |
+
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
|
| 661 |
+
... {3, -2}], {1, 2, 3}, set())
|
| 662 |
+
>>> next(l._find_model())
|
| 663 |
+
{1: True, 2: False, 3: False}
|
| 664 |
+
>>> l._simple_compute_conflict()
|
| 665 |
+
[3]
|
| 666 |
+
|
| 667 |
+
"""
|
| 668 |
+
return [-(level.decision) for level in self.levels[1:]]
|
| 669 |
+
|
| 670 |
+
def _simple_clean_clauses(self):
|
| 671 |
+
"""Clean up learned clauses."""
|
| 672 |
+
pass
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
class Level:
|
| 676 |
+
"""
|
| 677 |
+
Represents a single level in the DPLL algorithm, and contains
|
| 678 |
+
enough information for a sound backtracking procedure.
|
| 679 |
+
"""
|
| 680 |
+
|
| 681 |
+
def __init__(self, decision, flipped=False):
|
| 682 |
+
self.decision = decision
|
| 683 |
+
self.var_settings = set()
|
| 684 |
+
self.flipped = flipped
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/lra_theory.py
ADDED
|
@@ -0,0 +1,915 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Implements "A Fast Linear-Arithmetic Solver for DPLL(T)"
|
| 2 |
+
|
| 3 |
+
The LRASolver class defined in this file can be used
|
| 4 |
+
in conjunction with a SAT solver to check the
|
| 5 |
+
satisfiability of formulas involving inequalities.
|
| 6 |
+
|
| 7 |
+
Here's an example of how that would work:
|
| 8 |
+
|
| 9 |
+
Suppose you want to check the satisfiability of
|
| 10 |
+
the following formula:
|
| 11 |
+
|
| 12 |
+
>>> from sympy.core.relational import Eq
|
| 13 |
+
>>> from sympy.abc import x, y
|
| 14 |
+
>>> f = ((x > 0) | (x < 0)) & (Eq(x, 0) | Eq(y, 1)) & (~Eq(y, 1) | Eq(1, 2))
|
| 15 |
+
|
| 16 |
+
First a preprocessing step should be done on f. During preprocessing,
|
| 17 |
+
f should be checked for any predicates such as `Q.prime` that can't be
|
| 18 |
+
handled. Also unequality like `~Eq(y, 1)` should be split.
|
| 19 |
+
|
| 20 |
+
I should mention that the paper says to split both equalities and
|
| 21 |
+
unequality, but this implementation only requires that unequality
|
| 22 |
+
be split.
|
| 23 |
+
|
| 24 |
+
>>> f = ((x > 0) | (x < 0)) & (Eq(x, 0) | Eq(y, 1)) & ((y < 1) | (y > 1) | Eq(1, 2))
|
| 25 |
+
|
| 26 |
+
Then an LRASolver instance needs to be initialized with this formula.
|
| 27 |
+
|
| 28 |
+
>>> from sympy.assumptions.cnf import CNF, EncodedCNF
|
| 29 |
+
>>> from sympy.assumptions.ask import Q
|
| 30 |
+
>>> from sympy.logic.algorithms.lra_theory import LRASolver
|
| 31 |
+
>>> cnf = CNF.from_prop(f)
|
| 32 |
+
>>> enc = EncodedCNF()
|
| 33 |
+
>>> enc.add_from_cnf(cnf)
|
| 34 |
+
>>> lra, conflicts = LRASolver.from_encoded_cnf(enc)
|
| 35 |
+
|
| 36 |
+
Any immediate one-lital conflicts clauses will be detected here.
|
| 37 |
+
In this example, `~Eq(1, 2)` is one such conflict clause. We'll
|
| 38 |
+
want to add it to `f` so that the SAT solver is forced to
|
| 39 |
+
assign Eq(1, 2) to False.
|
| 40 |
+
|
| 41 |
+
>>> f = f & ~Eq(1, 2)
|
| 42 |
+
|
| 43 |
+
Now that the one-literal conflict clauses have been added
|
| 44 |
+
and an lra object has been initialized, we can pass `f`
|
| 45 |
+
to a SAT solver. The SAT solver will give us a satisfying
|
| 46 |
+
assignment such as:
|
| 47 |
+
|
| 48 |
+
(1 = 2): False
|
| 49 |
+
(y = 1): True
|
| 50 |
+
(y < 1): True
|
| 51 |
+
(y > 1): True
|
| 52 |
+
(x = 0): True
|
| 53 |
+
(x < 0): True
|
| 54 |
+
(x > 0): True
|
| 55 |
+
|
| 56 |
+
Next you would pass this assignment to the LRASolver
|
| 57 |
+
which will be able to determine that this particular
|
| 58 |
+
assignment is satisfiable or not.
|
| 59 |
+
|
| 60 |
+
Note that since EncodedCNF is inherently non-deterministic,
|
| 61 |
+
the int each predicate is encoded as is not consistent. As a
|
| 62 |
+
result, the code bellow likely does not reflect the assignment
|
| 63 |
+
given above.
|
| 64 |
+
|
| 65 |
+
>>> lra.assert_lit(-1) #doctest: +SKIP
|
| 66 |
+
>>> lra.assert_lit(2) #doctest: +SKIP
|
| 67 |
+
>>> lra.assert_lit(3) #doctest: +SKIP
|
| 68 |
+
>>> lra.assert_lit(4) #doctest: +SKIP
|
| 69 |
+
>>> lra.assert_lit(5) #doctest: +SKIP
|
| 70 |
+
>>> lra.assert_lit(6) #doctest: +SKIP
|
| 71 |
+
>>> lra.assert_lit(7) #doctest: +SKIP
|
| 72 |
+
>>> is_sat, conflict_or_assignment = lra.check()
|
| 73 |
+
|
| 74 |
+
As the particular assignment suggested is not satisfiable,
|
| 75 |
+
the LRASolver will return unsat and a conflict clause when
|
| 76 |
+
given that assignment. The conflict clause will always be
|
| 77 |
+
minimal, but there can be multiple minimal conflict clauses.
|
| 78 |
+
One possible conflict clause could be `~(x < 0) | ~(x > 0)`.
|
| 79 |
+
|
| 80 |
+
We would then add whatever conflict clause is given to
|
| 81 |
+
`f` to prevent the SAT solver from coming up with an
|
| 82 |
+
assignment with the same conflicting literals. In this case,
|
| 83 |
+
the conflict clause `~(x < 0) | ~(x > 0)` would prevent
|
| 84 |
+
any assignment where both (x < 0) and (x > 0) were both
|
| 85 |
+
true.
|
| 86 |
+
|
| 87 |
+
The SAT solver would then find another assignment
|
| 88 |
+
and we would check that assignment with the LRASolver
|
| 89 |
+
and so on. Eventually either a satisfying assignment
|
| 90 |
+
that the SAT solver and LRASolver agreed on would be found
|
| 91 |
+
or enough conflict clauses would be added so that the
|
| 92 |
+
boolean formula was unsatisfiable.
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
This implementation is based on [1]_, which includes a
|
| 96 |
+
detailed explanation of the algorithm and pseudocode
|
| 97 |
+
for the most important functions.
|
| 98 |
+
|
| 99 |
+
[1]_ also explains how backtracking and theory propagation
|
| 100 |
+
could be implemented to speed up the current implementation,
|
| 101 |
+
but these are not currently implemented.
|
| 102 |
+
|
| 103 |
+
TODO:
|
| 104 |
+
- Handle non-rational real numbers
|
| 105 |
+
- Handle positive and negative infinity
|
| 106 |
+
- Implement backtracking and theory proposition
|
| 107 |
+
- Simplify matrix by removing unused variables using Gaussian elimination
|
| 108 |
+
|
| 109 |
+
References
|
| 110 |
+
==========
|
| 111 |
+
|
| 112 |
+
.. [1] Dutertre, B., de Moura, L.:
|
| 113 |
+
A Fast Linear-Arithmetic Solver for DPLL(T)
|
| 114 |
+
https://link.springer.com/chapter/10.1007/11817963_11
|
| 115 |
+
"""
|
| 116 |
+
from sympy.solvers.solveset import linear_eq_to_matrix
|
| 117 |
+
from sympy.matrices.dense import eye
|
| 118 |
+
from sympy.assumptions import Predicate
|
| 119 |
+
from sympy.assumptions.assume import AppliedPredicate
|
| 120 |
+
from sympy.assumptions.ask import Q
|
| 121 |
+
from sympy.core import Dummy
|
| 122 |
+
from sympy.core.mul import Mul
|
| 123 |
+
from sympy.core.add import Add
|
| 124 |
+
from sympy.core.relational import Eq, Ne
|
| 125 |
+
from sympy.core.sympify import sympify
|
| 126 |
+
from sympy.core.singleton import S
|
| 127 |
+
from sympy.core.numbers import Rational, oo
|
| 128 |
+
from sympy.matrices.dense import Matrix
|
| 129 |
+
|
| 130 |
+
class UnhandledInput(Exception):
|
| 131 |
+
"""
|
| 132 |
+
Raised while creating an LRASolver if non-linearity
|
| 133 |
+
or non-rational numbers are present.
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
# predicates that LRASolver understands and makes use of
|
| 137 |
+
ALLOWED_PRED = {Q.eq, Q.gt, Q.lt, Q.le, Q.ge}
|
| 138 |
+
|
| 139 |
+
# if true ~Q.gt(x, y) implies Q.le(x, y)
|
| 140 |
+
HANDLE_NEGATION = True
|
| 141 |
+
|
| 142 |
+
class LRASolver():
|
| 143 |
+
"""
|
| 144 |
+
Linear Arithmetic Solver for DPLL(T) implemented with an algorithm based on
|
| 145 |
+
the Dual Simplex method. Uses Bland's pivoting rule to avoid cycling.
|
| 146 |
+
|
| 147 |
+
References
|
| 148 |
+
==========
|
| 149 |
+
|
| 150 |
+
.. [1] Dutertre, B., de Moura, L.:
|
| 151 |
+
A Fast Linear-Arithmetic Solver for DPLL(T)
|
| 152 |
+
https://link.springer.com/chapter/10.1007/11817963_11
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
def __init__(self, A, slack_variables, nonslack_variables, enc_to_boundary, s_subs, testing_mode):
|
| 156 |
+
"""
|
| 157 |
+
Use the "from_encoded_cnf" method to create a new LRASolver.
|
| 158 |
+
"""
|
| 159 |
+
self.run_checks = testing_mode
|
| 160 |
+
self.s_subs = s_subs # used only for test_lra_theory.test_random_problems
|
| 161 |
+
|
| 162 |
+
if any(not isinstance(a, Rational) for a in A):
|
| 163 |
+
raise UnhandledInput("Non-rational numbers are not handled")
|
| 164 |
+
if any(not isinstance(b.bound, Rational) for b in enc_to_boundary.values()):
|
| 165 |
+
raise UnhandledInput("Non-rational numbers are not handled")
|
| 166 |
+
m, n = len(slack_variables), len(slack_variables)+len(nonslack_variables)
|
| 167 |
+
if m != 0:
|
| 168 |
+
assert A.shape == (m, n)
|
| 169 |
+
if self.run_checks:
|
| 170 |
+
assert A[:, n-m:] == -eye(m)
|
| 171 |
+
|
| 172 |
+
self.enc_to_boundary = enc_to_boundary # mapping of int to Boundry objects
|
| 173 |
+
self.boundary_to_enc = {value: key for key, value in enc_to_boundary.items()}
|
| 174 |
+
self.A = A
|
| 175 |
+
self.slack = slack_variables
|
| 176 |
+
self.nonslack = nonslack_variables
|
| 177 |
+
self.all_var = nonslack_variables + slack_variables
|
| 178 |
+
|
| 179 |
+
self.slack_set = set(slack_variables)
|
| 180 |
+
|
| 181 |
+
self.is_sat = True # While True, all constraints asserted so far are satisfiable
|
| 182 |
+
self.result = None # always one of: (True, assignment), (False, conflict clause), None
|
| 183 |
+
|
| 184 |
+
@staticmethod
|
| 185 |
+
def from_encoded_cnf(encoded_cnf, testing_mode=False):
|
| 186 |
+
"""
|
| 187 |
+
Creates an LRASolver from an EncodedCNF object
|
| 188 |
+
and a list of conflict clauses for propositions
|
| 189 |
+
that can be simplified to True or False.
|
| 190 |
+
|
| 191 |
+
Parameters
|
| 192 |
+
==========
|
| 193 |
+
|
| 194 |
+
encoded_cnf : EncodedCNF
|
| 195 |
+
|
| 196 |
+
testing_mode : bool
|
| 197 |
+
Setting testing_mode to True enables some slow assert statements
|
| 198 |
+
and sorting to reduce nonterministic behavior.
|
| 199 |
+
|
| 200 |
+
Returns
|
| 201 |
+
=======
|
| 202 |
+
|
| 203 |
+
(lra, conflicts)
|
| 204 |
+
|
| 205 |
+
lra : LRASolver
|
| 206 |
+
|
| 207 |
+
conflicts : list
|
| 208 |
+
Contains a one-literal conflict clause for each proposition
|
| 209 |
+
that can be simplified to True or False.
|
| 210 |
+
|
| 211 |
+
Example
|
| 212 |
+
=======
|
| 213 |
+
|
| 214 |
+
>>> from sympy.core.relational import Eq
|
| 215 |
+
>>> from sympy.assumptions.cnf import CNF, EncodedCNF
|
| 216 |
+
>>> from sympy.assumptions.ask import Q
|
| 217 |
+
>>> from sympy.logic.algorithms.lra_theory import LRASolver
|
| 218 |
+
>>> from sympy.abc import x, y, z
|
| 219 |
+
>>> phi = (x >= 0) & ((x + y <= 2) | (x + 2 * y - z >= 6))
|
| 220 |
+
>>> phi = phi & (Eq(x + y, 2) | (x + 2 * y - z > 4))
|
| 221 |
+
>>> phi = phi & Q.gt(2, 1)
|
| 222 |
+
>>> cnf = CNF.from_prop(phi)
|
| 223 |
+
>>> enc = EncodedCNF()
|
| 224 |
+
>>> enc.from_cnf(cnf)
|
| 225 |
+
>>> lra, conflicts = LRASolver.from_encoded_cnf(enc, testing_mode=True)
|
| 226 |
+
>>> lra #doctest: +SKIP
|
| 227 |
+
<sympy.logic.algorithms.lra_theory.LRASolver object at 0x7fdcb0e15b70>
|
| 228 |
+
>>> conflicts #doctest: +SKIP
|
| 229 |
+
[[4]]
|
| 230 |
+
"""
|
| 231 |
+
# This function has three main jobs:
|
| 232 |
+
# - raise errors if the input formula is not handled
|
| 233 |
+
# - preprocesses the formula into a matirx and single variable constraints
|
| 234 |
+
# - create one-literal conflict clauses from predicates that are always True
|
| 235 |
+
# or always False such as Q.gt(3, 2)
|
| 236 |
+
#
|
| 237 |
+
# See the preprocessing section of "A Fast Linear-Arithmetic Solver for DPLL(T)"
|
| 238 |
+
# for an explanation of how the formula is converted into a matrix
|
| 239 |
+
# and a set of single variable constraints.
|
| 240 |
+
|
| 241 |
+
encoding = {} # maps int to boundary
|
| 242 |
+
A = []
|
| 243 |
+
|
| 244 |
+
basic = []
|
| 245 |
+
s_count = 0
|
| 246 |
+
s_subs = {}
|
| 247 |
+
nonbasic = []
|
| 248 |
+
|
| 249 |
+
if testing_mode:
|
| 250 |
+
# sort to reduce nondeterminism
|
| 251 |
+
encoded_cnf_items = sorted(encoded_cnf.encoding.items(), key=lambda x: str(x))
|
| 252 |
+
else:
|
| 253 |
+
encoded_cnf_items = encoded_cnf.encoding.items()
|
| 254 |
+
|
| 255 |
+
empty_var = Dummy()
|
| 256 |
+
var_to_lra_var = {}
|
| 257 |
+
conflicts = []
|
| 258 |
+
|
| 259 |
+
for prop, enc in encoded_cnf_items:
|
| 260 |
+
if isinstance(prop, Predicate):
|
| 261 |
+
prop = prop(empty_var)
|
| 262 |
+
if not isinstance(prop, AppliedPredicate):
|
| 263 |
+
if prop == True:
|
| 264 |
+
conflicts.append([enc])
|
| 265 |
+
continue
|
| 266 |
+
if prop == False:
|
| 267 |
+
conflicts.append([-enc])
|
| 268 |
+
continue
|
| 269 |
+
|
| 270 |
+
raise ValueError(f"Unhandled Predicate: {prop}")
|
| 271 |
+
|
| 272 |
+
assert prop.function in ALLOWED_PRED
|
| 273 |
+
if prop.lhs == S.NaN or prop.rhs == S.NaN:
|
| 274 |
+
raise ValueError(f"{prop} contains nan")
|
| 275 |
+
if prop.lhs.is_imaginary or prop.rhs.is_imaginary:
|
| 276 |
+
raise UnhandledInput(f"{prop} contains an imaginary component")
|
| 277 |
+
if prop.lhs == oo or prop.rhs == oo:
|
| 278 |
+
raise UnhandledInput(f"{prop} contains infinity")
|
| 279 |
+
|
| 280 |
+
prop = _eval_binrel(prop) # simplify variable-less quantities to True / False if possible
|
| 281 |
+
if prop == True:
|
| 282 |
+
conflicts.append([enc])
|
| 283 |
+
continue
|
| 284 |
+
elif prop == False:
|
| 285 |
+
conflicts.append([-enc])
|
| 286 |
+
continue
|
| 287 |
+
elif prop is None:
|
| 288 |
+
raise UnhandledInput(f"{prop} could not be simplified")
|
| 289 |
+
|
| 290 |
+
expr = prop.lhs - prop.rhs
|
| 291 |
+
if prop.function in [Q.ge, Q.gt]:
|
| 292 |
+
expr = -expr
|
| 293 |
+
|
| 294 |
+
# expr should be less than (or equal to) 0
|
| 295 |
+
# otherwise prop is False
|
| 296 |
+
if prop.function in [Q.le, Q.ge]:
|
| 297 |
+
bool = (expr <= 0)
|
| 298 |
+
elif prop.function in [Q.lt, Q.gt]:
|
| 299 |
+
bool = (expr < 0)
|
| 300 |
+
else:
|
| 301 |
+
assert prop.function == Q.eq
|
| 302 |
+
bool = Eq(expr, 0)
|
| 303 |
+
|
| 304 |
+
if bool == True:
|
| 305 |
+
conflicts.append([enc])
|
| 306 |
+
continue
|
| 307 |
+
elif bool == False:
|
| 308 |
+
conflicts.append([-enc])
|
| 309 |
+
continue
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
vars, const = _sep_const_terms(expr) # example: (2x + 3y + 2) --> (2x + 3y), (2)
|
| 313 |
+
vars, var_coeff = _sep_const_coeff(vars) # examples: (2x) --> (x, 2); (2x + 3y) --> (2x + 3y), (1)
|
| 314 |
+
const = const / var_coeff
|
| 315 |
+
|
| 316 |
+
terms = _list_terms(vars) # example: (2x + 3y) --> [2x, 3y]
|
| 317 |
+
for term in terms:
|
| 318 |
+
term, _ = _sep_const_coeff(term)
|
| 319 |
+
assert len(term.free_symbols) > 0
|
| 320 |
+
if term not in var_to_lra_var:
|
| 321 |
+
var_to_lra_var[term] = LRAVariable(term)
|
| 322 |
+
nonbasic.append(term)
|
| 323 |
+
|
| 324 |
+
if len(terms) > 1:
|
| 325 |
+
if vars not in s_subs:
|
| 326 |
+
s_count += 1
|
| 327 |
+
d = Dummy(f"s{s_count}")
|
| 328 |
+
var_to_lra_var[d] = LRAVariable(d)
|
| 329 |
+
basic.append(d)
|
| 330 |
+
s_subs[vars] = d
|
| 331 |
+
A.append(vars - d)
|
| 332 |
+
var = s_subs[vars]
|
| 333 |
+
else:
|
| 334 |
+
var = terms[0]
|
| 335 |
+
|
| 336 |
+
assert var_coeff != 0
|
| 337 |
+
|
| 338 |
+
equality = prop.function == Q.eq
|
| 339 |
+
upper = var_coeff > 0 if not equality else None
|
| 340 |
+
strict = prop.function in [Q.gt, Q.lt]
|
| 341 |
+
b = Boundary(var_to_lra_var[var], -const, upper, equality, strict)
|
| 342 |
+
encoding[enc] = b
|
| 343 |
+
|
| 344 |
+
fs = [v.free_symbols for v in nonbasic + basic]
|
| 345 |
+
assert all(len(syms) > 0 for syms in fs)
|
| 346 |
+
fs_count = sum(len(syms) for syms in fs)
|
| 347 |
+
if len(fs) > 0 and len(set.union(*fs)) < fs_count:
|
| 348 |
+
raise UnhandledInput("Nonlinearity is not handled")
|
| 349 |
+
|
| 350 |
+
A, _ = linear_eq_to_matrix(A, nonbasic + basic)
|
| 351 |
+
nonbasic = [var_to_lra_var[nb] for nb in nonbasic]
|
| 352 |
+
basic = [var_to_lra_var[b] for b in basic]
|
| 353 |
+
for idx, var in enumerate(nonbasic + basic):
|
| 354 |
+
var.col_idx = idx
|
| 355 |
+
|
| 356 |
+
return LRASolver(A, basic, nonbasic, encoding, s_subs, testing_mode), conflicts
|
| 357 |
+
|
| 358 |
+
def reset_bounds(self):
|
| 359 |
+
"""
|
| 360 |
+
Resets the state of the LRASolver to before
|
| 361 |
+
anything was asserted.
|
| 362 |
+
"""
|
| 363 |
+
self.result = None
|
| 364 |
+
for var in self.all_var:
|
| 365 |
+
var.lower = LRARational(-float("inf"), 0)
|
| 366 |
+
var.lower_from_eq = False
|
| 367 |
+
var.lower_from_neg = False
|
| 368 |
+
var.upper = LRARational(float("inf"), 0)
|
| 369 |
+
var.upper_from_eq= False
|
| 370 |
+
var.lower_from_neg = False
|
| 371 |
+
var.assign = LRARational(0, 0)
|
| 372 |
+
|
| 373 |
+
def assert_lit(self, enc_constraint):
|
| 374 |
+
"""
|
| 375 |
+
Assert a literal representing a constraint
|
| 376 |
+
and update the internal state accordingly.
|
| 377 |
+
|
| 378 |
+
Note that due to peculiarities of this implementation
|
| 379 |
+
asserting ~(x > 0) will assert (x <= 0) but asserting
|
| 380 |
+
~Eq(x, 0) will not do anything.
|
| 381 |
+
|
| 382 |
+
Parameters
|
| 383 |
+
==========
|
| 384 |
+
|
| 385 |
+
enc_constraint : int
|
| 386 |
+
A mapping of encodings to constraints
|
| 387 |
+
can be found in `self.enc_to_boundary`.
|
| 388 |
+
|
| 389 |
+
Returns
|
| 390 |
+
=======
|
| 391 |
+
|
| 392 |
+
None or (False, explanation)
|
| 393 |
+
|
| 394 |
+
explanation : set of ints
|
| 395 |
+
A conflict clause that "explains" why
|
| 396 |
+
the literals asserted so far are unsatisfiable.
|
| 397 |
+
"""
|
| 398 |
+
if abs(enc_constraint) not in self.enc_to_boundary:
|
| 399 |
+
return None
|
| 400 |
+
|
| 401 |
+
if not HANDLE_NEGATION and enc_constraint < 0:
|
| 402 |
+
return None
|
| 403 |
+
|
| 404 |
+
boundary = self.enc_to_boundary[abs(enc_constraint)]
|
| 405 |
+
sym, c, negated = boundary.var, boundary.bound, enc_constraint < 0
|
| 406 |
+
|
| 407 |
+
if boundary.equality and negated:
|
| 408 |
+
return None # negated equality is not handled and should only appear in conflict clauses
|
| 409 |
+
|
| 410 |
+
upper = boundary.upper != negated
|
| 411 |
+
if boundary.strict != negated:
|
| 412 |
+
delta = -1 if upper else 1
|
| 413 |
+
c = LRARational(c, delta)
|
| 414 |
+
else:
|
| 415 |
+
c = LRARational(c, 0)
|
| 416 |
+
|
| 417 |
+
if boundary.equality:
|
| 418 |
+
res1 = self._assert_lower(sym, c, from_equality=True, from_neg=negated)
|
| 419 |
+
if res1 and res1[0] == False:
|
| 420 |
+
res = res1
|
| 421 |
+
else:
|
| 422 |
+
res2 = self._assert_upper(sym, c, from_equality=True, from_neg=negated)
|
| 423 |
+
res = res2
|
| 424 |
+
elif upper:
|
| 425 |
+
res = self._assert_upper(sym, c, from_neg=negated)
|
| 426 |
+
else:
|
| 427 |
+
res = self._assert_lower(sym, c, from_neg=negated)
|
| 428 |
+
|
| 429 |
+
if self.is_sat and sym not in self.slack_set:
|
| 430 |
+
self.is_sat = res is None
|
| 431 |
+
else:
|
| 432 |
+
self.is_sat = False
|
| 433 |
+
|
| 434 |
+
return res
|
| 435 |
+
|
| 436 |
+
def _assert_upper(self, xi, ci, from_equality=False, from_neg=False):
|
| 437 |
+
"""
|
| 438 |
+
Adjusts the upper bound on variable xi if the new upper bound is
|
| 439 |
+
more limiting. The assignment of variable xi is adjusted to be
|
| 440 |
+
within the new bound if needed.
|
| 441 |
+
|
| 442 |
+
Also calls `self._update` to update the assignment for slack variables
|
| 443 |
+
to keep all equalities satisfied.
|
| 444 |
+
"""
|
| 445 |
+
if self.result:
|
| 446 |
+
assert self.result[0] != False
|
| 447 |
+
self.result = None
|
| 448 |
+
if ci >= xi.upper:
|
| 449 |
+
return None
|
| 450 |
+
if ci < xi.lower:
|
| 451 |
+
assert (xi.lower[1] >= 0) is True
|
| 452 |
+
assert (ci[1] <= 0) is True
|
| 453 |
+
|
| 454 |
+
lit1, neg1 = Boundary.from_lower(xi)
|
| 455 |
+
|
| 456 |
+
lit2 = Boundary(var=xi, const=ci[0], strict=ci[1] != 0, upper=True, equality=from_equality)
|
| 457 |
+
if from_neg:
|
| 458 |
+
lit2 = lit2.get_negated()
|
| 459 |
+
neg2 = -1 if from_neg else 1
|
| 460 |
+
|
| 461 |
+
conflict = [-neg1*self.boundary_to_enc[lit1], -neg2*self.boundary_to_enc[lit2]]
|
| 462 |
+
self.result = False, conflict
|
| 463 |
+
return self.result
|
| 464 |
+
xi.upper = ci
|
| 465 |
+
xi.upper_from_eq = from_equality
|
| 466 |
+
xi.upper_from_neg = from_neg
|
| 467 |
+
if xi in self.nonslack and xi.assign > ci:
|
| 468 |
+
self._update(xi, ci)
|
| 469 |
+
|
| 470 |
+
if self.run_checks and all(v.assign[0] != float("inf") and v.assign[0] != -float("inf")
|
| 471 |
+
for v in self.all_var):
|
| 472 |
+
M = self.A
|
| 473 |
+
X = Matrix([v.assign[0] for v in self.all_var])
|
| 474 |
+
assert all(abs(val) < 10 ** (-10) for val in M * X)
|
| 475 |
+
|
| 476 |
+
return None
|
| 477 |
+
|
| 478 |
+
def _assert_lower(self, xi, ci, from_equality=False, from_neg=False):
|
| 479 |
+
"""
|
| 480 |
+
Adjusts the lower bound on variable xi if the new lower bound is
|
| 481 |
+
more limiting. The assignment of variable xi is adjusted to be
|
| 482 |
+
within the new bound if needed.
|
| 483 |
+
|
| 484 |
+
Also calls `self._update` to update the assignment for slack variables
|
| 485 |
+
to keep all equalities satisfied.
|
| 486 |
+
"""
|
| 487 |
+
if self.result:
|
| 488 |
+
assert self.result[0] != False
|
| 489 |
+
self.result = None
|
| 490 |
+
if ci <= xi.lower:
|
| 491 |
+
return None
|
| 492 |
+
if ci > xi.upper:
|
| 493 |
+
assert (xi.upper[1] <= 0) is True
|
| 494 |
+
assert (ci[1] >= 0) is True
|
| 495 |
+
|
| 496 |
+
lit1, neg1 = Boundary.from_upper(xi)
|
| 497 |
+
|
| 498 |
+
lit2 = Boundary(var=xi, const=ci[0], strict=ci[1] != 0, upper=False, equality=from_equality)
|
| 499 |
+
if from_neg:
|
| 500 |
+
lit2 = lit2.get_negated()
|
| 501 |
+
neg2 = -1 if from_neg else 1
|
| 502 |
+
|
| 503 |
+
conflict = [-neg1*self.boundary_to_enc[lit1],-neg2*self.boundary_to_enc[lit2]]
|
| 504 |
+
self.result = False, conflict
|
| 505 |
+
return self.result
|
| 506 |
+
xi.lower = ci
|
| 507 |
+
xi.lower_from_eq = from_equality
|
| 508 |
+
xi.lower_from_neg = from_neg
|
| 509 |
+
if xi in self.nonslack and xi.assign < ci:
|
| 510 |
+
self._update(xi, ci)
|
| 511 |
+
|
| 512 |
+
if self.run_checks and all(v.assign[0] != float("inf") and v.assign[0] != -float("inf")
|
| 513 |
+
for v in self.all_var):
|
| 514 |
+
M = self.A
|
| 515 |
+
X = Matrix([v.assign[0] for v in self.all_var])
|
| 516 |
+
assert all(abs(val) < 10 ** (-10) for val in M * X)
|
| 517 |
+
|
| 518 |
+
return None
|
| 519 |
+
|
| 520 |
+
def _update(self, xi, v):
|
| 521 |
+
"""
|
| 522 |
+
Updates all slack variables that have equations that contain
|
| 523 |
+
variable xi so that they stay satisfied given xi is equal to v.
|
| 524 |
+
"""
|
| 525 |
+
i = xi.col_idx
|
| 526 |
+
for j, b in enumerate(self.slack):
|
| 527 |
+
aji = self.A[j, i]
|
| 528 |
+
b.assign = b.assign + (v - xi.assign)*aji
|
| 529 |
+
xi.assign = v
|
| 530 |
+
|
| 531 |
+
def check(self):
|
| 532 |
+
"""
|
| 533 |
+
Searches for an assignment that satisfies all constraints
|
| 534 |
+
or determines that no such assignment exists and gives
|
| 535 |
+
a minimal conflict clause that "explains" why the
|
| 536 |
+
constraints are unsatisfiable.
|
| 537 |
+
|
| 538 |
+
Returns
|
| 539 |
+
=======
|
| 540 |
+
|
| 541 |
+
(True, assignment) or (False, explanation)
|
| 542 |
+
|
| 543 |
+
assignment : dict of LRAVariables to values
|
| 544 |
+
Assigned values are tuples that represent a rational number
|
| 545 |
+
plus some infinatesimal delta.
|
| 546 |
+
|
| 547 |
+
explanation : set of ints
|
| 548 |
+
"""
|
| 549 |
+
if self.is_sat:
|
| 550 |
+
return True, {var: var.assign for var in self.all_var}
|
| 551 |
+
if self.result:
|
| 552 |
+
return self.result
|
| 553 |
+
|
| 554 |
+
from sympy.matrices.dense import Matrix
|
| 555 |
+
M = self.A.copy()
|
| 556 |
+
basic = {s: i for i, s in enumerate(self.slack)} # contains the row index associated with each basic variable
|
| 557 |
+
nonbasic = set(self.nonslack)
|
| 558 |
+
iteration = 0
|
| 559 |
+
while True:
|
| 560 |
+
iteration += 1
|
| 561 |
+
|
| 562 |
+
if self.run_checks:
|
| 563 |
+
# nonbasic variables must always be within bounds
|
| 564 |
+
assert all(((nb.assign >= nb.lower) == True) and ((nb.assign <= nb.upper) == True) for nb in nonbasic)
|
| 565 |
+
|
| 566 |
+
# assignments for x must always satisfy Ax = 0
|
| 567 |
+
# probably have to turn this off when dealing with strict ineq
|
| 568 |
+
if all(v.assign[0] != float("inf") and v.assign[0] != -float("inf")
|
| 569 |
+
for v in self.all_var):
|
| 570 |
+
X = Matrix([v.assign[0] for v in self.all_var])
|
| 571 |
+
assert all(abs(val) < 10**(-10) for val in M*X)
|
| 572 |
+
|
| 573 |
+
# check upper and lower match this format:
|
| 574 |
+
# x <= rat + delta iff x < rat
|
| 575 |
+
# x >= rat - delta iff x > rat
|
| 576 |
+
# this wouldn't make sense:
|
| 577 |
+
# x <= rat - delta
|
| 578 |
+
# x >= rat + delta
|
| 579 |
+
assert all(x.upper[1] <= 0 for x in self.all_var)
|
| 580 |
+
assert all(x.lower[1] >= 0 for x in self.all_var)
|
| 581 |
+
|
| 582 |
+
cand = [b for b in basic if b.assign < b.lower or b.assign > b.upper]
|
| 583 |
+
|
| 584 |
+
if len(cand) == 0:
|
| 585 |
+
return True, {var: var.assign for var in self.all_var}
|
| 586 |
+
|
| 587 |
+
xi = min(cand, key=lambda v: v.col_idx) # Bland's rule
|
| 588 |
+
i = basic[xi]
|
| 589 |
+
|
| 590 |
+
if xi.assign < xi.lower:
|
| 591 |
+
cand = [nb for nb in nonbasic
|
| 592 |
+
if (M[i, nb.col_idx] > 0 and nb.assign < nb.upper)
|
| 593 |
+
or (M[i, nb.col_idx] < 0 and nb.assign > nb.lower)]
|
| 594 |
+
if len(cand) == 0:
|
| 595 |
+
N_plus = [nb for nb in nonbasic if M[i, nb.col_idx] > 0]
|
| 596 |
+
N_minus = [nb for nb in nonbasic if M[i, nb.col_idx] < 0]
|
| 597 |
+
|
| 598 |
+
conflict = []
|
| 599 |
+
conflict += [Boundary.from_upper(nb) for nb in N_plus]
|
| 600 |
+
conflict += [Boundary.from_lower(nb) for nb in N_minus]
|
| 601 |
+
conflict.append(Boundary.from_lower(xi))
|
| 602 |
+
conflict = [-neg*self.boundary_to_enc[c] for c, neg in conflict]
|
| 603 |
+
return False, conflict
|
| 604 |
+
xj = min(cand, key=str)
|
| 605 |
+
M = self._pivot_and_update(M, basic, nonbasic, xi, xj, xi.lower)
|
| 606 |
+
|
| 607 |
+
if xi.assign > xi.upper:
|
| 608 |
+
cand = [nb for nb in nonbasic
|
| 609 |
+
if (M[i, nb.col_idx] < 0 and nb.assign < nb.upper)
|
| 610 |
+
or (M[i, nb.col_idx] > 0 and nb.assign > nb.lower)]
|
| 611 |
+
|
| 612 |
+
if len(cand) == 0:
|
| 613 |
+
N_plus = [nb for nb in nonbasic if M[i, nb.col_idx] > 0]
|
| 614 |
+
N_minus = [nb for nb in nonbasic if M[i, nb.col_idx] < 0]
|
| 615 |
+
|
| 616 |
+
conflict = []
|
| 617 |
+
conflict += [Boundary.from_upper(nb) for nb in N_minus]
|
| 618 |
+
conflict += [Boundary.from_lower(nb) for nb in N_plus]
|
| 619 |
+
conflict.append(Boundary.from_upper(xi))
|
| 620 |
+
|
| 621 |
+
conflict = [-neg*self.boundary_to_enc[c] for c, neg in conflict]
|
| 622 |
+
return False, conflict
|
| 623 |
+
xj = min(cand, key=lambda v: v.col_idx)
|
| 624 |
+
M = self._pivot_and_update(M, basic, nonbasic, xi, xj, xi.upper)
|
| 625 |
+
|
| 626 |
+
def _pivot_and_update(self, M, basic, nonbasic, xi, xj, v):
|
| 627 |
+
"""
|
| 628 |
+
Pivots basic variable xi with nonbasic variable xj,
|
| 629 |
+
and sets value of xi to v and adjusts the values of all basic variables
|
| 630 |
+
to keep equations satisfied.
|
| 631 |
+
"""
|
| 632 |
+
i, j = basic[xi], xj.col_idx
|
| 633 |
+
assert M[i, j] != 0
|
| 634 |
+
theta = (v - xi.assign)*(1/M[i, j])
|
| 635 |
+
xi.assign = v
|
| 636 |
+
xj.assign = xj.assign + theta
|
| 637 |
+
for xk in basic:
|
| 638 |
+
if xk != xi:
|
| 639 |
+
k = basic[xk]
|
| 640 |
+
akj = M[k, j]
|
| 641 |
+
xk.assign = xk.assign + theta*akj
|
| 642 |
+
# pivot
|
| 643 |
+
basic[xj] = basic[xi]
|
| 644 |
+
del basic[xi]
|
| 645 |
+
nonbasic.add(xi)
|
| 646 |
+
nonbasic.remove(xj)
|
| 647 |
+
return self._pivot(M, i, j)
|
| 648 |
+
|
| 649 |
+
@staticmethod
|
| 650 |
+
def _pivot(M, i, j):
|
| 651 |
+
"""
|
| 652 |
+
Performs a pivot operation about entry i, j of M by performing
|
| 653 |
+
a series of row operations on a copy of M and returing the result.
|
| 654 |
+
The original M is left unmodified.
|
| 655 |
+
|
| 656 |
+
Conceptually, M represents a system of equations and pivoting
|
| 657 |
+
can be thought of as rearranging equation i to be in terms of
|
| 658 |
+
variable j and then substituting in the rest of the equations
|
| 659 |
+
to get rid of other occurances of variable j.
|
| 660 |
+
|
| 661 |
+
Example
|
| 662 |
+
=======
|
| 663 |
+
|
| 664 |
+
>>> from sympy.matrices.dense import Matrix
|
| 665 |
+
>>> from sympy.logic.algorithms.lra_theory import LRASolver
|
| 666 |
+
>>> from sympy import var
|
| 667 |
+
>>> Matrix(3, 3, var('a:i'))
|
| 668 |
+
Matrix([
|
| 669 |
+
[a, b, c],
|
| 670 |
+
[d, e, f],
|
| 671 |
+
[g, h, i]])
|
| 672 |
+
|
| 673 |
+
This matrix is equivalent to:
|
| 674 |
+
0 = a*x + b*y + c*z
|
| 675 |
+
0 = d*x + e*y + f*z
|
| 676 |
+
0 = g*x + h*y + i*z
|
| 677 |
+
|
| 678 |
+
>>> LRASolver._pivot(_, 1, 0)
|
| 679 |
+
Matrix([
|
| 680 |
+
[ 0, -a*e/d + b, -a*f/d + c],
|
| 681 |
+
[-1, -e/d, -f/d],
|
| 682 |
+
[ 0, h - e*g/d, i - f*g/d]])
|
| 683 |
+
|
| 684 |
+
We rearrange equation 1 in terms of variable 0 (x)
|
| 685 |
+
and substitute to remove x from the other equations.
|
| 686 |
+
|
| 687 |
+
0 = 0 + (-a*e/d + b)*y + (-a*f/d + c)*z
|
| 688 |
+
0 = -x + (-e/d)*y + (-f/d)*z
|
| 689 |
+
0 = 0 + (h - e*g/d)*y + (i - f*g/d)*z
|
| 690 |
+
"""
|
| 691 |
+
_, _, Mij = M[i, :], M[:, j], M[i, j]
|
| 692 |
+
if Mij == 0:
|
| 693 |
+
raise ZeroDivisionError("Tried to pivot about zero-valued entry.")
|
| 694 |
+
A = M.copy()
|
| 695 |
+
A[i, :] = -A[i, :]/Mij
|
| 696 |
+
for row in range(M.shape[0]):
|
| 697 |
+
if row != i:
|
| 698 |
+
A[row, :] = A[row, :] + A[row, j] * A[i, :]
|
| 699 |
+
|
| 700 |
+
return A
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def _sep_const_coeff(expr):
|
| 704 |
+
"""
|
| 705 |
+
Example
|
| 706 |
+
=======
|
| 707 |
+
|
| 708 |
+
>>> from sympy.logic.algorithms.lra_theory import _sep_const_coeff
|
| 709 |
+
>>> from sympy.abc import x, y
|
| 710 |
+
>>> _sep_const_coeff(2*x)
|
| 711 |
+
(x, 2)
|
| 712 |
+
>>> _sep_const_coeff(2*x + 3*y)
|
| 713 |
+
(2*x + 3*y, 1)
|
| 714 |
+
"""
|
| 715 |
+
if isinstance(expr, Add):
|
| 716 |
+
return expr, sympify(1)
|
| 717 |
+
|
| 718 |
+
if isinstance(expr, Mul):
|
| 719 |
+
coeffs = expr.args
|
| 720 |
+
else:
|
| 721 |
+
coeffs = [expr]
|
| 722 |
+
|
| 723 |
+
var, const = [], []
|
| 724 |
+
for c in coeffs:
|
| 725 |
+
c = sympify(c)
|
| 726 |
+
if len(c.free_symbols)==0:
|
| 727 |
+
const.append(c)
|
| 728 |
+
else:
|
| 729 |
+
var.append(c)
|
| 730 |
+
return Mul(*var), Mul(*const)
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
def _list_terms(expr):
|
| 734 |
+
if not isinstance(expr, Add):
|
| 735 |
+
return [expr]
|
| 736 |
+
|
| 737 |
+
return expr.args
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def _sep_const_terms(expr):
|
| 741 |
+
"""
|
| 742 |
+
Example
|
| 743 |
+
=======
|
| 744 |
+
|
| 745 |
+
>>> from sympy.logic.algorithms.lra_theory import _sep_const_terms
|
| 746 |
+
>>> from sympy.abc import x, y
|
| 747 |
+
>>> _sep_const_terms(2*x + 3*y + 2)
|
| 748 |
+
(2*x + 3*y, 2)
|
| 749 |
+
"""
|
| 750 |
+
if isinstance(expr, Add):
|
| 751 |
+
terms = expr.args
|
| 752 |
+
else:
|
| 753 |
+
terms = [expr]
|
| 754 |
+
|
| 755 |
+
var, const = [], []
|
| 756 |
+
for t in terms:
|
| 757 |
+
if len(t.free_symbols) == 0:
|
| 758 |
+
const.append(t)
|
| 759 |
+
else:
|
| 760 |
+
var.append(t)
|
| 761 |
+
return sum(var), sum(const)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def _eval_binrel(binrel):
|
| 765 |
+
"""
|
| 766 |
+
Simplify binary relation to True / False if possible.
|
| 767 |
+
"""
|
| 768 |
+
if not (len(binrel.lhs.free_symbols) == 0 and len(binrel.rhs.free_symbols) == 0):
|
| 769 |
+
return binrel
|
| 770 |
+
if binrel.function == Q.lt:
|
| 771 |
+
res = binrel.lhs < binrel.rhs
|
| 772 |
+
elif binrel.function == Q.gt:
|
| 773 |
+
res = binrel.lhs > binrel.rhs
|
| 774 |
+
elif binrel.function == Q.le:
|
| 775 |
+
res = binrel.lhs <= binrel.rhs
|
| 776 |
+
elif binrel.function == Q.ge:
|
| 777 |
+
res = binrel.lhs >= binrel.rhs
|
| 778 |
+
elif binrel.function == Q.eq:
|
| 779 |
+
res = Eq(binrel.lhs, binrel.rhs)
|
| 780 |
+
elif binrel.function == Q.ne:
|
| 781 |
+
res = Ne(binrel.lhs, binrel.rhs)
|
| 782 |
+
|
| 783 |
+
if res == True or res == False:
|
| 784 |
+
return res
|
| 785 |
+
else:
|
| 786 |
+
return None
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
class Boundary:
|
| 790 |
+
"""
|
| 791 |
+
Represents an upper or lower bound or an equality between a symbol
|
| 792 |
+
and some constant.
|
| 793 |
+
"""
|
| 794 |
+
def __init__(self, var, const, upper, equality, strict=None):
|
| 795 |
+
if not equality in [True, False]:
|
| 796 |
+
assert equality in [True, False]
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
self.var = var
|
| 800 |
+
if isinstance(const, tuple):
|
| 801 |
+
s = const[1] != 0
|
| 802 |
+
if strict:
|
| 803 |
+
assert s == strict
|
| 804 |
+
self.bound = const[0]
|
| 805 |
+
self.strict = s
|
| 806 |
+
else:
|
| 807 |
+
self.bound = const
|
| 808 |
+
self.strict = strict
|
| 809 |
+
self.upper = upper if not equality else None
|
| 810 |
+
self.equality = equality
|
| 811 |
+
self.strict = strict
|
| 812 |
+
assert self.strict is not None
|
| 813 |
+
|
| 814 |
+
@staticmethod
|
| 815 |
+
def from_upper(var):
|
| 816 |
+
neg = -1 if var.upper_from_neg else 1
|
| 817 |
+
b = Boundary(var, var.upper[0], True, var.upper_from_eq, var.upper[1] != 0)
|
| 818 |
+
if neg < 0:
|
| 819 |
+
b = b.get_negated()
|
| 820 |
+
return b, neg
|
| 821 |
+
|
| 822 |
+
@staticmethod
|
| 823 |
+
def from_lower(var):
|
| 824 |
+
neg = -1 if var.lower_from_neg else 1
|
| 825 |
+
b = Boundary(var, var.lower[0], False, var.lower_from_eq, var.lower[1] != 0)
|
| 826 |
+
if neg < 0:
|
| 827 |
+
b = b.get_negated()
|
| 828 |
+
return b, neg
|
| 829 |
+
|
| 830 |
+
def get_negated(self):
|
| 831 |
+
return Boundary(self.var, self.bound, not self.upper, self.equality, not self.strict)
|
| 832 |
+
|
| 833 |
+
def get_inequality(self):
|
| 834 |
+
if self.equality:
|
| 835 |
+
return Eq(self.var.var, self.bound)
|
| 836 |
+
elif self.upper and self.strict:
|
| 837 |
+
return self.var.var < self.bound
|
| 838 |
+
elif not self.upper and self.strict:
|
| 839 |
+
return self.var.var > self.bound
|
| 840 |
+
elif self.upper:
|
| 841 |
+
return self.var.var <= self.bound
|
| 842 |
+
else:
|
| 843 |
+
return self.var.var >= self.bound
|
| 844 |
+
|
| 845 |
+
def __repr__(self):
|
| 846 |
+
return repr("Boundry(" + repr(self.get_inequality()) + ")")
|
| 847 |
+
|
| 848 |
+
def __eq__(self, other):
|
| 849 |
+
other = (other.var, other.bound, other.strict, other.upper, other.equality)
|
| 850 |
+
return (self.var, self.bound, self.strict, self.upper, self.equality) == other
|
| 851 |
+
|
| 852 |
+
def __hash__(self):
|
| 853 |
+
return hash((self.var, self.bound, self.strict, self.upper, self.equality))
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
class LRARational():
|
| 857 |
+
"""
|
| 858 |
+
Represents a rational plus or minus some amount
|
| 859 |
+
of arbitrary small deltas.
|
| 860 |
+
"""
|
| 861 |
+
def __init__(self, rational, delta):
|
| 862 |
+
self.value = (rational, delta)
|
| 863 |
+
|
| 864 |
+
def __lt__(self, other):
|
| 865 |
+
return self.value < other.value
|
| 866 |
+
|
| 867 |
+
def __le__(self, other):
|
| 868 |
+
return self.value <= other.value
|
| 869 |
+
|
| 870 |
+
def __eq__(self, other):
|
| 871 |
+
return self.value == other.value
|
| 872 |
+
|
| 873 |
+
def __add__(self, other):
|
| 874 |
+
return LRARational(self.value[0] + other.value[0], self.value[1] + other.value[1])
|
| 875 |
+
|
| 876 |
+
def __sub__(self, other):
|
| 877 |
+
return LRARational(self.value[0] - other.value[0], self.value[1] - other.value[1])
|
| 878 |
+
|
| 879 |
+
def __mul__(self, other):
|
| 880 |
+
assert not isinstance(other, LRARational)
|
| 881 |
+
return LRARational(self.value[0] * other, self.value[1] * other)
|
| 882 |
+
|
| 883 |
+
def __getitem__(self, index):
|
| 884 |
+
return self.value[index]
|
| 885 |
+
|
| 886 |
+
def __repr__(self):
|
| 887 |
+
return repr(self.value)
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
class LRAVariable():
|
| 891 |
+
"""
|
| 892 |
+
Object to keep track of upper and lower bounds
|
| 893 |
+
on `self.var`.
|
| 894 |
+
"""
|
| 895 |
+
def __init__(self, var):
|
| 896 |
+
self.upper = LRARational(float("inf"), 0)
|
| 897 |
+
self.upper_from_eq = False
|
| 898 |
+
self.upper_from_neg = False
|
| 899 |
+
self.lower = LRARational(-float("inf"), 0)
|
| 900 |
+
self.lower_from_eq = False
|
| 901 |
+
self.lower_from_neg = False
|
| 902 |
+
self.assign = LRARational(0,0)
|
| 903 |
+
self.var = var
|
| 904 |
+
self.col_idx = None
|
| 905 |
+
|
| 906 |
+
def __repr__(self):
|
| 907 |
+
return repr(self.var)
|
| 908 |
+
|
| 909 |
+
def __eq__(self, other):
|
| 910 |
+
if not isinstance(other, LRAVariable):
|
| 911 |
+
return False
|
| 912 |
+
return other.var == self.var
|
| 913 |
+
|
| 914 |
+
def __hash__(self):
|
| 915 |
+
return hash(self.var)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/minisat22_wrapper.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.assumptions.cnf import EncodedCNF
|
| 2 |
+
|
| 3 |
+
def minisat22_satisfiable(expr, all_models=False, minimal=False):
|
| 4 |
+
|
| 5 |
+
if not isinstance(expr, EncodedCNF):
|
| 6 |
+
exprs = EncodedCNF()
|
| 7 |
+
exprs.add_prop(expr)
|
| 8 |
+
expr = exprs
|
| 9 |
+
|
| 10 |
+
from pysat.solvers import Minisat22
|
| 11 |
+
|
| 12 |
+
# Return UNSAT when False (encoded as 0) is present in the CNF
|
| 13 |
+
if {0} in expr.data:
|
| 14 |
+
if all_models:
|
| 15 |
+
return (f for f in [False])
|
| 16 |
+
return False
|
| 17 |
+
|
| 18 |
+
r = Minisat22(expr.data)
|
| 19 |
+
|
| 20 |
+
if minimal:
|
| 21 |
+
r.set_phases([-(i+1) for i in range(r.nof_vars())])
|
| 22 |
+
|
| 23 |
+
if not r.solve():
|
| 24 |
+
return False
|
| 25 |
+
|
| 26 |
+
if not all_models:
|
| 27 |
+
return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r.get_model()}
|
| 28 |
+
|
| 29 |
+
else:
|
| 30 |
+
# Make solutions SymPy compatible by creating a generator
|
| 31 |
+
def _gen(results):
|
| 32 |
+
satisfiable = False
|
| 33 |
+
while results.solve():
|
| 34 |
+
sol = results.get_model()
|
| 35 |
+
yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol}
|
| 36 |
+
if minimal:
|
| 37 |
+
results.add_clause([-i for i in sol if i>0])
|
| 38 |
+
else:
|
| 39 |
+
results.add_clause([-i for i in sol])
|
| 40 |
+
satisfiable = True
|
| 41 |
+
if not satisfiable:
|
| 42 |
+
yield False
|
| 43 |
+
raise StopIteration
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
return _gen(r)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/pycosat_wrapper.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.assumptions.cnf import EncodedCNF
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def pycosat_satisfiable(expr, all_models=False):
|
| 5 |
+
import pycosat
|
| 6 |
+
if not isinstance(expr, EncodedCNF):
|
| 7 |
+
exprs = EncodedCNF()
|
| 8 |
+
exprs.add_prop(expr)
|
| 9 |
+
expr = exprs
|
| 10 |
+
|
| 11 |
+
# Return UNSAT when False (encoded as 0) is present in the CNF
|
| 12 |
+
if {0} in expr.data:
|
| 13 |
+
if all_models:
|
| 14 |
+
return (f for f in [False])
|
| 15 |
+
return False
|
| 16 |
+
|
| 17 |
+
if not all_models:
|
| 18 |
+
r = pycosat.solve(expr.data)
|
| 19 |
+
result = (r != "UNSAT")
|
| 20 |
+
if not result:
|
| 21 |
+
return result
|
| 22 |
+
return {expr.symbols[abs(lit) - 1]: lit > 0 for lit in r}
|
| 23 |
+
else:
|
| 24 |
+
r = pycosat.itersolve(expr.data)
|
| 25 |
+
result = (r != "UNSAT")
|
| 26 |
+
if not result:
|
| 27 |
+
return result
|
| 28 |
+
|
| 29 |
+
# Make solutions SymPy compatible by creating a generator
|
| 30 |
+
def _gen(results):
|
| 31 |
+
satisfiable = False
|
| 32 |
+
try:
|
| 33 |
+
while True:
|
| 34 |
+
sol = next(results)
|
| 35 |
+
yield {expr.symbols[abs(lit) - 1]: lit > 0 for lit in sol}
|
| 36 |
+
satisfiable = True
|
| 37 |
+
except StopIteration:
|
| 38 |
+
if not satisfiable:
|
| 39 |
+
yield False
|
| 40 |
+
|
| 41 |
+
return _gen(r)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/algorithms/z3_wrapper.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.printing.smtlib import smtlib_code
|
| 2 |
+
from sympy.assumptions.assume import AppliedPredicate
|
| 3 |
+
from sympy.assumptions.cnf import EncodedCNF
|
| 4 |
+
from sympy.assumptions.ask import Q
|
| 5 |
+
|
| 6 |
+
from sympy.core import Add, Mul
|
| 7 |
+
from sympy.core.relational import Equality, LessThan, GreaterThan, StrictLessThan, StrictGreaterThan
|
| 8 |
+
from sympy.functions.elementary.complexes import Abs
|
| 9 |
+
from sympy.functions.elementary.exponential import Pow
|
| 10 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
| 11 |
+
from sympy.logic.boolalg import And, Or, Xor, Implies
|
| 12 |
+
from sympy.logic.boolalg import Not, ITE
|
| 13 |
+
from sympy.assumptions.relation.equality import StrictGreaterThanPredicate, StrictLessThanPredicate, GreaterThanPredicate, LessThanPredicate, EqualityPredicate
|
| 14 |
+
from sympy.external import import_module
|
| 15 |
+
|
| 16 |
+
def z3_satisfiable(expr, all_models=False):
|
| 17 |
+
if not isinstance(expr, EncodedCNF):
|
| 18 |
+
exprs = EncodedCNF()
|
| 19 |
+
exprs.add_prop(expr)
|
| 20 |
+
expr = exprs
|
| 21 |
+
|
| 22 |
+
z3 = import_module("z3")
|
| 23 |
+
if z3 is None:
|
| 24 |
+
raise ImportError("z3 is not installed")
|
| 25 |
+
|
| 26 |
+
s = encoded_cnf_to_z3_solver(expr, z3)
|
| 27 |
+
|
| 28 |
+
res = str(s.check())
|
| 29 |
+
if res == "unsat":
|
| 30 |
+
return False
|
| 31 |
+
elif res == "sat":
|
| 32 |
+
return z3_model_to_sympy_model(s.model(), expr)
|
| 33 |
+
else:
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def z3_model_to_sympy_model(z3_model, enc_cnf):
|
| 38 |
+
rev_enc = {value : key for key, value in enc_cnf.encoding.items()}
|
| 39 |
+
return {rev_enc[int(var.name()[1:])] : bool(z3_model[var]) for var in z3_model}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def clause_to_assertion(clause):
|
| 43 |
+
clause_strings = [f"d{abs(lit)}" if lit > 0 else f"(not d{abs(lit)})" for lit in clause]
|
| 44 |
+
return "(assert (or " + " ".join(clause_strings) + "))"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def encoded_cnf_to_z3_solver(enc_cnf, z3):
|
| 48 |
+
def dummify_bool(pred):
|
| 49 |
+
return False
|
| 50 |
+
assert isinstance(pred, AppliedPredicate)
|
| 51 |
+
|
| 52 |
+
if pred.function in [Q.positive, Q.negative, Q.zero]:
|
| 53 |
+
return pred
|
| 54 |
+
else:
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
s = z3.Solver()
|
| 58 |
+
|
| 59 |
+
declarations = [f"(declare-const d{var} Bool)" for var in enc_cnf.variables]
|
| 60 |
+
assertions = [clause_to_assertion(clause) for clause in enc_cnf.data]
|
| 61 |
+
|
| 62 |
+
symbols = set()
|
| 63 |
+
for pred, enc in enc_cnf.encoding.items():
|
| 64 |
+
if not isinstance(pred, AppliedPredicate):
|
| 65 |
+
continue
|
| 66 |
+
if pred.function not in (Q.gt, Q.lt, Q.ge, Q.le, Q.ne, Q.eq, Q.positive, Q.negative, Q.extended_negative, Q.extended_positive, Q.zero, Q.nonzero, Q.nonnegative, Q.nonpositive, Q.extended_nonzero, Q.extended_nonnegative, Q.extended_nonpositive):
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
pred_str = smtlib_code(pred, auto_declare=False, auto_assert=False, known_functions=known_functions)
|
| 70 |
+
|
| 71 |
+
symbols |= pred.free_symbols
|
| 72 |
+
pred = pred_str
|
| 73 |
+
clause = f"(implies d{enc} {pred})"
|
| 74 |
+
assertion = "(assert " + clause + ")"
|
| 75 |
+
assertions.append(assertion)
|
| 76 |
+
|
| 77 |
+
for sym in symbols:
|
| 78 |
+
declarations.append(f"(declare-const {sym} Real)")
|
| 79 |
+
|
| 80 |
+
declarations = "\n".join(declarations)
|
| 81 |
+
assertions = "\n".join(assertions)
|
| 82 |
+
s.from_string(declarations)
|
| 83 |
+
s.from_string(assertions)
|
| 84 |
+
|
| 85 |
+
return s
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
known_functions = {
|
| 89 |
+
Add: '+',
|
| 90 |
+
Mul: '*',
|
| 91 |
+
|
| 92 |
+
Equality: '=',
|
| 93 |
+
LessThan: '<=',
|
| 94 |
+
GreaterThan: '>=',
|
| 95 |
+
StrictLessThan: '<',
|
| 96 |
+
StrictGreaterThan: '>',
|
| 97 |
+
|
| 98 |
+
EqualityPredicate(): '=',
|
| 99 |
+
LessThanPredicate(): '<=',
|
| 100 |
+
GreaterThanPredicate(): '>=',
|
| 101 |
+
StrictLessThanPredicate(): '<',
|
| 102 |
+
StrictGreaterThanPredicate(): '>',
|
| 103 |
+
|
| 104 |
+
Abs: 'abs',
|
| 105 |
+
Min: 'min',
|
| 106 |
+
Max: 'max',
|
| 107 |
+
Pow: '^',
|
| 108 |
+
|
| 109 |
+
And: 'and',
|
| 110 |
+
Or: 'or',
|
| 111 |
+
Xor: 'xor',
|
| 112 |
+
Not: 'not',
|
| 113 |
+
ITE: 'ite',
|
| 114 |
+
Implies: '=>',
|
| 115 |
+
}
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/boolalg.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/inference.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Inference in propositional logic"""
|
| 2 |
+
|
| 3 |
+
from sympy.logic.boolalg import And, Not, conjuncts, to_cnf, BooleanFunction
|
| 4 |
+
from sympy.core.sorting import ordered
|
| 5 |
+
from sympy.core.sympify import sympify
|
| 6 |
+
from sympy.external.importtools import import_module
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def literal_symbol(literal):
|
| 10 |
+
"""
|
| 11 |
+
The symbol in this literal (without the negation).
|
| 12 |
+
|
| 13 |
+
Examples
|
| 14 |
+
========
|
| 15 |
+
|
| 16 |
+
>>> from sympy.abc import A
|
| 17 |
+
>>> from sympy.logic.inference import literal_symbol
|
| 18 |
+
>>> literal_symbol(A)
|
| 19 |
+
A
|
| 20 |
+
>>> literal_symbol(~A)
|
| 21 |
+
A
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
if literal is True or literal is False:
|
| 26 |
+
return literal
|
| 27 |
+
elif literal.is_Symbol:
|
| 28 |
+
return literal
|
| 29 |
+
elif literal.is_Not:
|
| 30 |
+
return literal_symbol(literal.args[0])
|
| 31 |
+
else:
|
| 32 |
+
raise ValueError("Argument must be a boolean literal.")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def satisfiable(expr, algorithm=None, all_models=False, minimal=False, use_lra_theory=False):
|
| 36 |
+
"""
|
| 37 |
+
Check satisfiability of a propositional sentence.
|
| 38 |
+
Returns a model when it succeeds.
|
| 39 |
+
Returns {true: true} for trivially true expressions.
|
| 40 |
+
|
| 41 |
+
On setting all_models to True, if given expr is satisfiable then
|
| 42 |
+
returns a generator of models. However, if expr is unsatisfiable
|
| 43 |
+
then returns a generator containing the single element False.
|
| 44 |
+
|
| 45 |
+
Examples
|
| 46 |
+
========
|
| 47 |
+
|
| 48 |
+
>>> from sympy.abc import A, B
|
| 49 |
+
>>> from sympy.logic.inference import satisfiable
|
| 50 |
+
>>> satisfiable(A & ~B)
|
| 51 |
+
{A: True, B: False}
|
| 52 |
+
>>> satisfiable(A & ~A)
|
| 53 |
+
False
|
| 54 |
+
>>> satisfiable(True)
|
| 55 |
+
{True: True}
|
| 56 |
+
>>> next(satisfiable(A & ~A, all_models=True))
|
| 57 |
+
False
|
| 58 |
+
>>> models = satisfiable((A >> B) & B, all_models=True)
|
| 59 |
+
>>> next(models)
|
| 60 |
+
{A: False, B: True}
|
| 61 |
+
>>> next(models)
|
| 62 |
+
{A: True, B: True}
|
| 63 |
+
>>> def use_models(models):
|
| 64 |
+
... for model in models:
|
| 65 |
+
... if model:
|
| 66 |
+
... # Do something with the model.
|
| 67 |
+
... print(model)
|
| 68 |
+
... else:
|
| 69 |
+
... # Given expr is unsatisfiable.
|
| 70 |
+
... print("UNSAT")
|
| 71 |
+
>>> use_models(satisfiable(A >> ~A, all_models=True))
|
| 72 |
+
{A: False}
|
| 73 |
+
>>> use_models(satisfiable(A ^ A, all_models=True))
|
| 74 |
+
UNSAT
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
if use_lra_theory:
|
| 78 |
+
if algorithm is not None and algorithm != "dpll2":
|
| 79 |
+
raise ValueError(f"Currently only dpll2 can handle using lra theory. {algorithm} is not handled.")
|
| 80 |
+
algorithm = "dpll2"
|
| 81 |
+
|
| 82 |
+
if algorithm is None or algorithm == "pycosat":
|
| 83 |
+
pycosat = import_module('pycosat')
|
| 84 |
+
if pycosat is not None:
|
| 85 |
+
algorithm = "pycosat"
|
| 86 |
+
else:
|
| 87 |
+
if algorithm == "pycosat":
|
| 88 |
+
raise ImportError("pycosat module is not present")
|
| 89 |
+
# Silently fall back to dpll2 if pycosat
|
| 90 |
+
# is not installed
|
| 91 |
+
algorithm = "dpll2"
|
| 92 |
+
|
| 93 |
+
if algorithm=="minisat22":
|
| 94 |
+
pysat = import_module('pysat')
|
| 95 |
+
if pysat is None:
|
| 96 |
+
algorithm = "dpll2"
|
| 97 |
+
|
| 98 |
+
if algorithm=="z3":
|
| 99 |
+
z3 = import_module('z3')
|
| 100 |
+
if z3 is None:
|
| 101 |
+
algorithm = "dpll2"
|
| 102 |
+
|
| 103 |
+
if algorithm == "dpll":
|
| 104 |
+
from sympy.logic.algorithms.dpll import dpll_satisfiable
|
| 105 |
+
return dpll_satisfiable(expr)
|
| 106 |
+
elif algorithm == "dpll2":
|
| 107 |
+
from sympy.logic.algorithms.dpll2 import dpll_satisfiable
|
| 108 |
+
return dpll_satisfiable(expr, all_models, use_lra_theory=use_lra_theory)
|
| 109 |
+
elif algorithm == "pycosat":
|
| 110 |
+
from sympy.logic.algorithms.pycosat_wrapper import pycosat_satisfiable
|
| 111 |
+
return pycosat_satisfiable(expr, all_models)
|
| 112 |
+
elif algorithm == "minisat22":
|
| 113 |
+
from sympy.logic.algorithms.minisat22_wrapper import minisat22_satisfiable
|
| 114 |
+
return minisat22_satisfiable(expr, all_models, minimal)
|
| 115 |
+
elif algorithm == "z3":
|
| 116 |
+
from sympy.logic.algorithms.z3_wrapper import z3_satisfiable
|
| 117 |
+
return z3_satisfiable(expr, all_models)
|
| 118 |
+
|
| 119 |
+
raise NotImplementedError
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def valid(expr):
|
| 123 |
+
"""
|
| 124 |
+
Check validity of a propositional sentence.
|
| 125 |
+
A valid propositional sentence is True under every assignment.
|
| 126 |
+
|
| 127 |
+
Examples
|
| 128 |
+
========
|
| 129 |
+
|
| 130 |
+
>>> from sympy.abc import A, B
|
| 131 |
+
>>> from sympy.logic.inference import valid
|
| 132 |
+
>>> valid(A | ~A)
|
| 133 |
+
True
|
| 134 |
+
>>> valid(A | B)
|
| 135 |
+
False
|
| 136 |
+
|
| 137 |
+
References
|
| 138 |
+
==========
|
| 139 |
+
|
| 140 |
+
.. [1] https://en.wikipedia.org/wiki/Validity
|
| 141 |
+
|
| 142 |
+
"""
|
| 143 |
+
return not satisfiable(Not(expr))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def pl_true(expr, model=None, deep=False):
|
| 147 |
+
"""
|
| 148 |
+
Returns whether the given assignment is a model or not.
|
| 149 |
+
|
| 150 |
+
If the assignment does not specify the value for every proposition,
|
| 151 |
+
this may return None to indicate 'not obvious'.
|
| 152 |
+
|
| 153 |
+
Parameters
|
| 154 |
+
==========
|
| 155 |
+
|
| 156 |
+
model : dict, optional, default: {}
|
| 157 |
+
Mapping of symbols to boolean values to indicate assignment.
|
| 158 |
+
deep: boolean, optional, default: False
|
| 159 |
+
Gives the value of the expression under partial assignments
|
| 160 |
+
correctly. May still return None to indicate 'not obvious'.
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
Examples
|
| 164 |
+
========
|
| 165 |
+
|
| 166 |
+
>>> from sympy.abc import A, B
|
| 167 |
+
>>> from sympy.logic.inference import pl_true
|
| 168 |
+
>>> pl_true( A & B, {A: True, B: True})
|
| 169 |
+
True
|
| 170 |
+
>>> pl_true(A & B, {A: False})
|
| 171 |
+
False
|
| 172 |
+
>>> pl_true(A & B, {A: True})
|
| 173 |
+
>>> pl_true(A & B, {A: True}, deep=True)
|
| 174 |
+
>>> pl_true(A >> (B >> A))
|
| 175 |
+
>>> pl_true(A >> (B >> A), deep=True)
|
| 176 |
+
True
|
| 177 |
+
>>> pl_true(A & ~A)
|
| 178 |
+
>>> pl_true(A & ~A, deep=True)
|
| 179 |
+
False
|
| 180 |
+
>>> pl_true(A & B & (~A | ~B), {A: True})
|
| 181 |
+
>>> pl_true(A & B & (~A | ~B), {A: True}, deep=True)
|
| 182 |
+
False
|
| 183 |
+
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
from sympy.core.symbol import Symbol
|
| 187 |
+
|
| 188 |
+
boolean = (True, False)
|
| 189 |
+
|
| 190 |
+
def _validate(expr):
|
| 191 |
+
if isinstance(expr, Symbol) or expr in boolean:
|
| 192 |
+
return True
|
| 193 |
+
if not isinstance(expr, BooleanFunction):
|
| 194 |
+
return False
|
| 195 |
+
return all(_validate(arg) for arg in expr.args)
|
| 196 |
+
|
| 197 |
+
if expr in boolean:
|
| 198 |
+
return expr
|
| 199 |
+
expr = sympify(expr)
|
| 200 |
+
if not _validate(expr):
|
| 201 |
+
raise ValueError("%s is not a valid boolean expression" % expr)
|
| 202 |
+
if not model:
|
| 203 |
+
model = {}
|
| 204 |
+
model = {k: v for k, v in model.items() if v in boolean}
|
| 205 |
+
result = expr.subs(model)
|
| 206 |
+
if result in boolean:
|
| 207 |
+
return bool(result)
|
| 208 |
+
if deep:
|
| 209 |
+
model = dict.fromkeys(result.atoms(), True)
|
| 210 |
+
if pl_true(result, model):
|
| 211 |
+
if valid(result):
|
| 212 |
+
return True
|
| 213 |
+
else:
|
| 214 |
+
if not satisfiable(result):
|
| 215 |
+
return False
|
| 216 |
+
return None
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def entails(expr, formula_set=None):
|
| 220 |
+
"""
|
| 221 |
+
Check whether the given expr_set entail an expr.
|
| 222 |
+
If formula_set is empty then it returns the validity of expr.
|
| 223 |
+
|
| 224 |
+
Examples
|
| 225 |
+
========
|
| 226 |
+
|
| 227 |
+
>>> from sympy.abc import A, B, C
|
| 228 |
+
>>> from sympy.logic.inference import entails
|
| 229 |
+
>>> entails(A, [A >> B, B >> C])
|
| 230 |
+
False
|
| 231 |
+
>>> entails(C, [A >> B, B >> C, A])
|
| 232 |
+
True
|
| 233 |
+
>>> entails(A >> B)
|
| 234 |
+
False
|
| 235 |
+
>>> entails(A >> (B >> A))
|
| 236 |
+
True
|
| 237 |
+
|
| 238 |
+
References
|
| 239 |
+
==========
|
| 240 |
+
|
| 241 |
+
.. [1] https://en.wikipedia.org/wiki/Logical_consequence
|
| 242 |
+
|
| 243 |
+
"""
|
| 244 |
+
if formula_set:
|
| 245 |
+
formula_set = list(formula_set)
|
| 246 |
+
else:
|
| 247 |
+
formula_set = []
|
| 248 |
+
formula_set.append(Not(expr))
|
| 249 |
+
return not satisfiable(And(*formula_set))
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class KB:
|
| 253 |
+
"""Base class for all knowledge bases"""
|
| 254 |
+
def __init__(self, sentence=None):
|
| 255 |
+
self.clauses_ = set()
|
| 256 |
+
if sentence:
|
| 257 |
+
self.tell(sentence)
|
| 258 |
+
|
| 259 |
+
def tell(self, sentence):
|
| 260 |
+
raise NotImplementedError
|
| 261 |
+
|
| 262 |
+
def ask(self, query):
|
| 263 |
+
raise NotImplementedError
|
| 264 |
+
|
| 265 |
+
def retract(self, sentence):
|
| 266 |
+
raise NotImplementedError
|
| 267 |
+
|
| 268 |
+
@property
|
| 269 |
+
def clauses(self):
|
| 270 |
+
return list(ordered(self.clauses_))
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class PropKB(KB):
|
| 274 |
+
"""A KB for Propositional Logic. Inefficient, with no indexing."""
|
| 275 |
+
|
| 276 |
+
def tell(self, sentence):
|
| 277 |
+
"""Add the sentence's clauses to the KB
|
| 278 |
+
|
| 279 |
+
Examples
|
| 280 |
+
========
|
| 281 |
+
|
| 282 |
+
>>> from sympy.logic.inference import PropKB
|
| 283 |
+
>>> from sympy.abc import x, y
|
| 284 |
+
>>> l = PropKB()
|
| 285 |
+
>>> l.clauses
|
| 286 |
+
[]
|
| 287 |
+
|
| 288 |
+
>>> l.tell(x | y)
|
| 289 |
+
>>> l.clauses
|
| 290 |
+
[x | y]
|
| 291 |
+
|
| 292 |
+
>>> l.tell(y)
|
| 293 |
+
>>> l.clauses
|
| 294 |
+
[y, x | y]
|
| 295 |
+
|
| 296 |
+
"""
|
| 297 |
+
for c in conjuncts(to_cnf(sentence)):
|
| 298 |
+
self.clauses_.add(c)
|
| 299 |
+
|
| 300 |
+
def ask(self, query):
|
| 301 |
+
"""Checks if the query is true given the set of clauses.
|
| 302 |
+
|
| 303 |
+
Examples
|
| 304 |
+
========
|
| 305 |
+
|
| 306 |
+
>>> from sympy.logic.inference import PropKB
|
| 307 |
+
>>> from sympy.abc import x, y
|
| 308 |
+
>>> l = PropKB()
|
| 309 |
+
>>> l.tell(x & ~y)
|
| 310 |
+
>>> l.ask(x)
|
| 311 |
+
True
|
| 312 |
+
>>> l.ask(y)
|
| 313 |
+
False
|
| 314 |
+
|
| 315 |
+
"""
|
| 316 |
+
return entails(query, self.clauses_)
|
| 317 |
+
|
| 318 |
+
def retract(self, sentence):
|
| 319 |
+
"""Remove the sentence's clauses from the KB
|
| 320 |
+
|
| 321 |
+
Examples
|
| 322 |
+
========
|
| 323 |
+
|
| 324 |
+
>>> from sympy.logic.inference import PropKB
|
| 325 |
+
>>> from sympy.abc import x, y
|
| 326 |
+
>>> l = PropKB()
|
| 327 |
+
>>> l.clauses
|
| 328 |
+
[]
|
| 329 |
+
|
| 330 |
+
>>> l.tell(x | y)
|
| 331 |
+
>>> l.clauses
|
| 332 |
+
[x | y]
|
| 333 |
+
|
| 334 |
+
>>> l.retract(x | y)
|
| 335 |
+
>>> l.clauses
|
| 336 |
+
[]
|
| 337 |
+
|
| 338 |
+
"""
|
| 339 |
+
for c in conjuncts(to_cnf(sentence)):
|
| 340 |
+
self.clauses_.discard(c)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (179 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/tests/__pycache__/test_boolalg.cpython-310.pyc
ADDED
|
Binary file (49 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/utilities/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .dimacs import load_file
|
| 2 |
+
|
| 3 |
+
__all__ = ['load_file']
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/utilities/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (245 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/utilities/__pycache__/dimacs.cpython-310.pyc
ADDED
|
Binary file (1.54 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/logic/utilities/dimacs.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""For reading in DIMACS file format
|
| 2 |
+
|
| 3 |
+
www.cs.ubc.ca/~hoos/SATLIB/Benchmarks/SAT/satformat.ps
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from sympy.core import Symbol
|
| 8 |
+
from sympy.logic.boolalg import And, Or
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load(s):
|
| 13 |
+
"""Loads a boolean expression from a string.
|
| 14 |
+
|
| 15 |
+
Examples
|
| 16 |
+
========
|
| 17 |
+
|
| 18 |
+
>>> from sympy.logic.utilities.dimacs import load
|
| 19 |
+
>>> load('1')
|
| 20 |
+
cnf_1
|
| 21 |
+
>>> load('1 2')
|
| 22 |
+
cnf_1 | cnf_2
|
| 23 |
+
>>> load('1 \\n 2')
|
| 24 |
+
cnf_1 & cnf_2
|
| 25 |
+
>>> load('1 2 \\n 3')
|
| 26 |
+
cnf_3 & (cnf_1 | cnf_2)
|
| 27 |
+
"""
|
| 28 |
+
clauses = []
|
| 29 |
+
|
| 30 |
+
lines = s.split('\n')
|
| 31 |
+
|
| 32 |
+
pComment = re.compile(r'c.*')
|
| 33 |
+
pStats = re.compile(r'p\s*cnf\s*(\d*)\s*(\d*)')
|
| 34 |
+
|
| 35 |
+
while len(lines) > 0:
|
| 36 |
+
line = lines.pop(0)
|
| 37 |
+
|
| 38 |
+
# Only deal with lines that aren't comments
|
| 39 |
+
if not pComment.match(line):
|
| 40 |
+
m = pStats.match(line)
|
| 41 |
+
|
| 42 |
+
if not m:
|
| 43 |
+
nums = line.rstrip('\n').split(' ')
|
| 44 |
+
list = []
|
| 45 |
+
for lit in nums:
|
| 46 |
+
if lit != '':
|
| 47 |
+
if int(lit) == 0:
|
| 48 |
+
continue
|
| 49 |
+
num = abs(int(lit))
|
| 50 |
+
sign = True
|
| 51 |
+
if int(lit) < 0:
|
| 52 |
+
sign = False
|
| 53 |
+
|
| 54 |
+
if sign:
|
| 55 |
+
list.append(Symbol("cnf_%s" % num))
|
| 56 |
+
else:
|
| 57 |
+
list.append(~Symbol("cnf_%s" % num))
|
| 58 |
+
|
| 59 |
+
if len(list) > 0:
|
| 60 |
+
clauses.append(Or(*list))
|
| 61 |
+
|
| 62 |
+
return And(*clauses)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load_file(location):
|
| 66 |
+
"""Loads a boolean expression from a file."""
|
| 67 |
+
with open(location) as f:
|
| 68 |
+
s = f.read()
|
| 69 |
+
|
| 70 |
+
return load(s)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (593 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/experimental_lambdify.cpython-310.pyc
ADDED
|
Binary file (14.3 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot.cpython-310.pyc
ADDED
|
Binary file (36.9 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/plot_implicit.cpython-310.pyc
ADDED
|
Binary file (7.42 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/plotgrid.cpython-310.pyc
ADDED
|
Binary file (6.61 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/series.cpython-310.pyc
ADDED
|
Binary file (76.9 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/__pycache__/textplot.cpython-310.pyc
ADDED
|
Binary file (4.72 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .interval_arithmetic import interval
|
| 2 |
+
from .lib_interval import (Abs, exp, log, log10, sin, cos, tan, sqrt,
|
| 3 |
+
imin, imax, sinh, cosh, tanh, acosh, asinh, atanh,
|
| 4 |
+
asin, acos, atan, ceil, floor, And, Or)
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
'interval',
|
| 8 |
+
|
| 9 |
+
'Abs', 'exp', 'log', 'log10', 'sin', 'cos', 'tan', 'sqrt', 'imin', 'imax',
|
| 10 |
+
'sinh', 'cosh', 'tanh', 'acosh', 'asinh', 'atanh', 'asin', 'acos', 'atan',
|
| 11 |
+
'ceil', 'floor', 'And', 'Or',
|
| 12 |
+
]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (749 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_arithmetic.cpython-310.pyc
ADDED
|
Binary file (9.25 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/interval_membership.cpython-310.pyc
ADDED
|
Binary file (3.06 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/__pycache__/lib_interval.cpython-310.pyc
ADDED
|
Binary file (9.6 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/lib_interval.py
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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4 |
+
from sympy.plotting.intervalmath import interval
|
| 5 |
+
from sympy.external import import_module
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def Abs(x):
|
| 9 |
+
if isinstance(x, (int, float)):
|
| 10 |
+
return interval(abs(x))
|
| 11 |
+
elif isinstance(x, interval):
|
| 12 |
+
if x.start < 0 and x.end > 0:
|
| 13 |
+
return interval(0, max(abs(x.start), abs(x.end)), is_valid=x.is_valid)
|
| 14 |
+
else:
|
| 15 |
+
return interval(abs(x.start), abs(x.end))
|
| 16 |
+
else:
|
| 17 |
+
raise NotImplementedError
|
| 18 |
+
|
| 19 |
+
#Monotonic
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def exp(x):
|
| 23 |
+
"""evaluates the exponential of an interval"""
|
| 24 |
+
np = import_module('numpy')
|
| 25 |
+
if isinstance(x, (int, float)):
|
| 26 |
+
return interval(np.exp(x), np.exp(x))
|
| 27 |
+
elif isinstance(x, interval):
|
| 28 |
+
return interval(np.exp(x.start), np.exp(x.end), is_valid=x.is_valid)
|
| 29 |
+
else:
|
| 30 |
+
raise NotImplementedError
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
#Monotonic
|
| 34 |
+
def log(x):
|
| 35 |
+
"""evaluates the natural logarithm of an interval"""
|
| 36 |
+
np = import_module('numpy')
|
| 37 |
+
if isinstance(x, (int, float)):
|
| 38 |
+
if x <= 0:
|
| 39 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 40 |
+
else:
|
| 41 |
+
return interval(np.log(x))
|
| 42 |
+
elif isinstance(x, interval):
|
| 43 |
+
if not x.is_valid:
|
| 44 |
+
return interval(-np.inf, np.inf, is_valid=x.is_valid)
|
| 45 |
+
elif x.end <= 0:
|
| 46 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 47 |
+
elif x.start <= 0:
|
| 48 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 49 |
+
|
| 50 |
+
return interval(np.log(x.start), np.log(x.end))
|
| 51 |
+
else:
|
| 52 |
+
raise NotImplementedError
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
#Monotonic
|
| 56 |
+
def log10(x):
|
| 57 |
+
"""evaluates the logarithm to the base 10 of an interval"""
|
| 58 |
+
np = import_module('numpy')
|
| 59 |
+
if isinstance(x, (int, float)):
|
| 60 |
+
if x <= 0:
|
| 61 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 62 |
+
else:
|
| 63 |
+
return interval(np.log10(x))
|
| 64 |
+
elif isinstance(x, interval):
|
| 65 |
+
if not x.is_valid:
|
| 66 |
+
return interval(-np.inf, np.inf, is_valid=x.is_valid)
|
| 67 |
+
elif x.end <= 0:
|
| 68 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 69 |
+
elif x.start <= 0:
|
| 70 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 71 |
+
return interval(np.log10(x.start), np.log10(x.end))
|
| 72 |
+
else:
|
| 73 |
+
raise NotImplementedError
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
#Monotonic
|
| 77 |
+
def atan(x):
|
| 78 |
+
"""evaluates the tan inverse of an interval"""
|
| 79 |
+
np = import_module('numpy')
|
| 80 |
+
if isinstance(x, (int, float)):
|
| 81 |
+
return interval(np.arctan(x))
|
| 82 |
+
elif isinstance(x, interval):
|
| 83 |
+
start = np.arctan(x.start)
|
| 84 |
+
end = np.arctan(x.end)
|
| 85 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 86 |
+
else:
|
| 87 |
+
raise NotImplementedError
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
#periodic
|
| 91 |
+
def sin(x):
|
| 92 |
+
"""evaluates the sine of an interval"""
|
| 93 |
+
np = import_module('numpy')
|
| 94 |
+
if isinstance(x, (int, float)):
|
| 95 |
+
return interval(np.sin(x))
|
| 96 |
+
elif isinstance(x, interval):
|
| 97 |
+
if not x.is_valid:
|
| 98 |
+
return interval(-1, 1, is_valid=x.is_valid)
|
| 99 |
+
na, __ = divmod(x.start, np.pi / 2.0)
|
| 100 |
+
nb, __ = divmod(x.end, np.pi / 2.0)
|
| 101 |
+
start = min(np.sin(x.start), np.sin(x.end))
|
| 102 |
+
end = max(np.sin(x.start), np.sin(x.end))
|
| 103 |
+
if nb - na > 4:
|
| 104 |
+
return interval(-1, 1, is_valid=x.is_valid)
|
| 105 |
+
elif na == nb:
|
| 106 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 107 |
+
else:
|
| 108 |
+
if (na - 1) // 4 != (nb - 1) // 4:
|
| 109 |
+
#sin has max
|
| 110 |
+
end = 1
|
| 111 |
+
if (na - 3) // 4 != (nb - 3) // 4:
|
| 112 |
+
#sin has min
|
| 113 |
+
start = -1
|
| 114 |
+
return interval(start, end)
|
| 115 |
+
else:
|
| 116 |
+
raise NotImplementedError
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
#periodic
|
| 120 |
+
def cos(x):
|
| 121 |
+
"""Evaluates the cos of an interval"""
|
| 122 |
+
np = import_module('numpy')
|
| 123 |
+
if isinstance(x, (int, float)):
|
| 124 |
+
return interval(np.sin(x))
|
| 125 |
+
elif isinstance(x, interval):
|
| 126 |
+
if not (np.isfinite(x.start) and np.isfinite(x.end)):
|
| 127 |
+
return interval(-1, 1, is_valid=x.is_valid)
|
| 128 |
+
na, __ = divmod(x.start, np.pi / 2.0)
|
| 129 |
+
nb, __ = divmod(x.end, np.pi / 2.0)
|
| 130 |
+
start = min(np.cos(x.start), np.cos(x.end))
|
| 131 |
+
end = max(np.cos(x.start), np.cos(x.end))
|
| 132 |
+
if nb - na > 4:
|
| 133 |
+
#differ more than 2*pi
|
| 134 |
+
return interval(-1, 1, is_valid=x.is_valid)
|
| 135 |
+
elif na == nb:
|
| 136 |
+
#in the same quadarant
|
| 137 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 138 |
+
else:
|
| 139 |
+
if (na) // 4 != (nb) // 4:
|
| 140 |
+
#cos has max
|
| 141 |
+
end = 1
|
| 142 |
+
if (na - 2) // 4 != (nb - 2) // 4:
|
| 143 |
+
#cos has min
|
| 144 |
+
start = -1
|
| 145 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 146 |
+
else:
|
| 147 |
+
raise NotImplementedError
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def tan(x):
|
| 151 |
+
"""Evaluates the tan of an interval"""
|
| 152 |
+
return sin(x) / cos(x)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
#Monotonic
|
| 156 |
+
def sqrt(x):
|
| 157 |
+
"""Evaluates the square root of an interval"""
|
| 158 |
+
np = import_module('numpy')
|
| 159 |
+
if isinstance(x, (int, float)):
|
| 160 |
+
if x > 0:
|
| 161 |
+
return interval(np.sqrt(x))
|
| 162 |
+
else:
|
| 163 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 164 |
+
elif isinstance(x, interval):
|
| 165 |
+
#Outside the domain
|
| 166 |
+
if x.end < 0:
|
| 167 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 168 |
+
#Partially outside the domain
|
| 169 |
+
elif x.start < 0:
|
| 170 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 171 |
+
else:
|
| 172 |
+
return interval(np.sqrt(x.start), np.sqrt(x.end),
|
| 173 |
+
is_valid=x.is_valid)
|
| 174 |
+
else:
|
| 175 |
+
raise NotImplementedError
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def imin(*args):
|
| 179 |
+
"""Evaluates the minimum of a list of intervals"""
|
| 180 |
+
np = import_module('numpy')
|
| 181 |
+
if not all(isinstance(arg, (int, float, interval)) for arg in args):
|
| 182 |
+
return NotImplementedError
|
| 183 |
+
else:
|
| 184 |
+
new_args = [a for a in args if isinstance(a, (int, float))
|
| 185 |
+
or a.is_valid]
|
| 186 |
+
if len(new_args) == 0:
|
| 187 |
+
if all(a.is_valid is False for a in args):
|
| 188 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 189 |
+
else:
|
| 190 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 191 |
+
start_array = [a if isinstance(a, (int, float)) else a.start
|
| 192 |
+
for a in new_args]
|
| 193 |
+
|
| 194 |
+
end_array = [a if isinstance(a, (int, float)) else a.end
|
| 195 |
+
for a in new_args]
|
| 196 |
+
return interval(min(start_array), min(end_array))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def imax(*args):
|
| 200 |
+
"""Evaluates the maximum of a list of intervals"""
|
| 201 |
+
np = import_module('numpy')
|
| 202 |
+
if not all(isinstance(arg, (int, float, interval)) for arg in args):
|
| 203 |
+
return NotImplementedError
|
| 204 |
+
else:
|
| 205 |
+
new_args = [a for a in args if isinstance(a, (int, float))
|
| 206 |
+
or a.is_valid]
|
| 207 |
+
if len(new_args) == 0:
|
| 208 |
+
if all(a.is_valid is False for a in args):
|
| 209 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 210 |
+
else:
|
| 211 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 212 |
+
start_array = [a if isinstance(a, (int, float)) else a.start
|
| 213 |
+
for a in new_args]
|
| 214 |
+
|
| 215 |
+
end_array = [a if isinstance(a, (int, float)) else a.end
|
| 216 |
+
for a in new_args]
|
| 217 |
+
|
| 218 |
+
return interval(max(start_array), max(end_array))
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
#Monotonic
|
| 222 |
+
def sinh(x):
|
| 223 |
+
"""Evaluates the hyperbolic sine of an interval"""
|
| 224 |
+
np = import_module('numpy')
|
| 225 |
+
if isinstance(x, (int, float)):
|
| 226 |
+
return interval(np.sinh(x), np.sinh(x))
|
| 227 |
+
elif isinstance(x, interval):
|
| 228 |
+
return interval(np.sinh(x.start), np.sinh(x.end), is_valid=x.is_valid)
|
| 229 |
+
else:
|
| 230 |
+
raise NotImplementedError
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def cosh(x):
|
| 234 |
+
"""Evaluates the hyperbolic cos of an interval"""
|
| 235 |
+
np = import_module('numpy')
|
| 236 |
+
if isinstance(x, (int, float)):
|
| 237 |
+
return interval(np.cosh(x), np.cosh(x))
|
| 238 |
+
elif isinstance(x, interval):
|
| 239 |
+
#both signs
|
| 240 |
+
if x.start < 0 and x.end > 0:
|
| 241 |
+
end = max(np.cosh(x.start), np.cosh(x.end))
|
| 242 |
+
return interval(1, end, is_valid=x.is_valid)
|
| 243 |
+
else:
|
| 244 |
+
#Monotonic
|
| 245 |
+
start = np.cosh(x.start)
|
| 246 |
+
end = np.cosh(x.end)
|
| 247 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 248 |
+
else:
|
| 249 |
+
raise NotImplementedError
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
#Monotonic
|
| 253 |
+
def tanh(x):
|
| 254 |
+
"""Evaluates the hyperbolic tan of an interval"""
|
| 255 |
+
np = import_module('numpy')
|
| 256 |
+
if isinstance(x, (int, float)):
|
| 257 |
+
return interval(np.tanh(x), np.tanh(x))
|
| 258 |
+
elif isinstance(x, interval):
|
| 259 |
+
return interval(np.tanh(x.start), np.tanh(x.end), is_valid=x.is_valid)
|
| 260 |
+
else:
|
| 261 |
+
raise NotImplementedError
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def asin(x):
|
| 265 |
+
"""Evaluates the inverse sine of an interval"""
|
| 266 |
+
np = import_module('numpy')
|
| 267 |
+
if isinstance(x, (int, float)):
|
| 268 |
+
#Outside the domain
|
| 269 |
+
if abs(x) > 1:
|
| 270 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 271 |
+
else:
|
| 272 |
+
return interval(np.arcsin(x), np.arcsin(x))
|
| 273 |
+
elif isinstance(x, interval):
|
| 274 |
+
#Outside the domain
|
| 275 |
+
if x.is_valid is False or x.start > 1 or x.end < -1:
|
| 276 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 277 |
+
#Partially outside the domain
|
| 278 |
+
elif x.start < -1 or x.end > 1:
|
| 279 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 280 |
+
else:
|
| 281 |
+
start = np.arcsin(x.start)
|
| 282 |
+
end = np.arcsin(x.end)
|
| 283 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def acos(x):
|
| 287 |
+
"""Evaluates the inverse cos of an interval"""
|
| 288 |
+
np = import_module('numpy')
|
| 289 |
+
if isinstance(x, (int, float)):
|
| 290 |
+
if abs(x) > 1:
|
| 291 |
+
#Outside the domain
|
| 292 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 293 |
+
else:
|
| 294 |
+
return interval(np.arccos(x), np.arccos(x))
|
| 295 |
+
elif isinstance(x, interval):
|
| 296 |
+
#Outside the domain
|
| 297 |
+
if x.is_valid is False or x.start > 1 or x.end < -1:
|
| 298 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 299 |
+
#Partially outside the domain
|
| 300 |
+
elif x.start < -1 or x.end > 1:
|
| 301 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 302 |
+
else:
|
| 303 |
+
start = np.arccos(x.start)
|
| 304 |
+
end = np.arccos(x.end)
|
| 305 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def ceil(x):
|
| 309 |
+
"""Evaluates the ceiling of an interval"""
|
| 310 |
+
np = import_module('numpy')
|
| 311 |
+
if isinstance(x, (int, float)):
|
| 312 |
+
return interval(np.ceil(x))
|
| 313 |
+
elif isinstance(x, interval):
|
| 314 |
+
if x.is_valid is False:
|
| 315 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 316 |
+
else:
|
| 317 |
+
start = np.ceil(x.start)
|
| 318 |
+
end = np.ceil(x.end)
|
| 319 |
+
#Continuous over the interval
|
| 320 |
+
if start == end:
|
| 321 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 322 |
+
else:
|
| 323 |
+
#Not continuous over the interval
|
| 324 |
+
return interval(start, end, is_valid=None)
|
| 325 |
+
else:
|
| 326 |
+
return NotImplementedError
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def floor(x):
|
| 330 |
+
"""Evaluates the floor of an interval"""
|
| 331 |
+
np = import_module('numpy')
|
| 332 |
+
if isinstance(x, (int, float)):
|
| 333 |
+
return interval(np.floor(x))
|
| 334 |
+
elif isinstance(x, interval):
|
| 335 |
+
if x.is_valid is False:
|
| 336 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 337 |
+
else:
|
| 338 |
+
start = np.floor(x.start)
|
| 339 |
+
end = np.floor(x.end)
|
| 340 |
+
#continuous over the argument
|
| 341 |
+
if start == end:
|
| 342 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 343 |
+
else:
|
| 344 |
+
#not continuous over the interval
|
| 345 |
+
return interval(start, end, is_valid=None)
|
| 346 |
+
else:
|
| 347 |
+
return NotImplementedError
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def acosh(x):
|
| 351 |
+
"""Evaluates the inverse hyperbolic cosine of an interval"""
|
| 352 |
+
np = import_module('numpy')
|
| 353 |
+
if isinstance(x, (int, float)):
|
| 354 |
+
#Outside the domain
|
| 355 |
+
if x < 1:
|
| 356 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 357 |
+
else:
|
| 358 |
+
return interval(np.arccosh(x))
|
| 359 |
+
elif isinstance(x, interval):
|
| 360 |
+
#Outside the domain
|
| 361 |
+
if x.end < 1:
|
| 362 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 363 |
+
#Partly outside the domain
|
| 364 |
+
elif x.start < 1:
|
| 365 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 366 |
+
else:
|
| 367 |
+
start = np.arccosh(x.start)
|
| 368 |
+
end = np.arccosh(x.end)
|
| 369 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 370 |
+
else:
|
| 371 |
+
return NotImplementedError
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
#Monotonic
|
| 375 |
+
def asinh(x):
|
| 376 |
+
"""Evaluates the inverse hyperbolic sine of an interval"""
|
| 377 |
+
np = import_module('numpy')
|
| 378 |
+
if isinstance(x, (int, float)):
|
| 379 |
+
return interval(np.arcsinh(x))
|
| 380 |
+
elif isinstance(x, interval):
|
| 381 |
+
start = np.arcsinh(x.start)
|
| 382 |
+
end = np.arcsinh(x.end)
|
| 383 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 384 |
+
else:
|
| 385 |
+
return NotImplementedError
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def atanh(x):
|
| 389 |
+
"""Evaluates the inverse hyperbolic tangent of an interval"""
|
| 390 |
+
np = import_module('numpy')
|
| 391 |
+
if isinstance(x, (int, float)):
|
| 392 |
+
#Outside the domain
|
| 393 |
+
if abs(x) >= 1:
|
| 394 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 395 |
+
else:
|
| 396 |
+
return interval(np.arctanh(x))
|
| 397 |
+
elif isinstance(x, interval):
|
| 398 |
+
#outside the domain
|
| 399 |
+
if x.is_valid is False or x.start >= 1 or x.end <= -1:
|
| 400 |
+
return interval(-np.inf, np.inf, is_valid=False)
|
| 401 |
+
#partly outside the domain
|
| 402 |
+
elif x.start <= -1 or x.end >= 1:
|
| 403 |
+
return interval(-np.inf, np.inf, is_valid=None)
|
| 404 |
+
else:
|
| 405 |
+
start = np.arctanh(x.start)
|
| 406 |
+
end = np.arctanh(x.end)
|
| 407 |
+
return interval(start, end, is_valid=x.is_valid)
|
| 408 |
+
else:
|
| 409 |
+
return NotImplementedError
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
#Three valued logic for interval plotting.
|
| 413 |
+
|
| 414 |
+
def And(*args):
|
| 415 |
+
"""Defines the three valued ``And`` behaviour for a 2-tuple of
|
| 416 |
+
three valued logic values"""
|
| 417 |
+
def reduce_and(cmp_intervala, cmp_intervalb):
|
| 418 |
+
if cmp_intervala[0] is False or cmp_intervalb[0] is False:
|
| 419 |
+
first = False
|
| 420 |
+
elif cmp_intervala[0] is None or cmp_intervalb[0] is None:
|
| 421 |
+
first = None
|
| 422 |
+
else:
|
| 423 |
+
first = True
|
| 424 |
+
if cmp_intervala[1] is False or cmp_intervalb[1] is False:
|
| 425 |
+
second = False
|
| 426 |
+
elif cmp_intervala[1] is None or cmp_intervalb[1] is None:
|
| 427 |
+
second = None
|
| 428 |
+
else:
|
| 429 |
+
second = True
|
| 430 |
+
return (first, second)
|
| 431 |
+
return reduce(reduce_and, args)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def Or(*args):
|
| 435 |
+
"""Defines the three valued ``Or`` behaviour for a 2-tuple of
|
| 436 |
+
three valued logic values"""
|
| 437 |
+
def reduce_or(cmp_intervala, cmp_intervalb):
|
| 438 |
+
if cmp_intervala[0] is True or cmp_intervalb[0] is True:
|
| 439 |
+
first = True
|
| 440 |
+
elif cmp_intervala[0] is None or cmp_intervalb[0] is None:
|
| 441 |
+
first = None
|
| 442 |
+
else:
|
| 443 |
+
first = False
|
| 444 |
+
|
| 445 |
+
if cmp_intervala[1] is True or cmp_intervalb[1] is True:
|
| 446 |
+
second = True
|
| 447 |
+
elif cmp_intervala[1] is None or cmp_intervalb[1] is None:
|
| 448 |
+
second = None
|
| 449 |
+
else:
|
| 450 |
+
second = False
|
| 451 |
+
return (first, second)
|
| 452 |
+
return reduce(reduce_or, args)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/intervalmath/tests/__pycache__/test_interval_functions.cpython-310.pyc
ADDED
|
Binary file (9.29 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/plotting/tests/__pycache__/test_series.cpython-310.pyc
ADDED
|
Binary file (49.2 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A module that handles series: find a limit, order the series etc.
|
| 2 |
+
"""
|
| 3 |
+
from .order import Order
|
| 4 |
+
from .limits import limit, Limit
|
| 5 |
+
from .gruntz import gruntz
|
| 6 |
+
from .series import series
|
| 7 |
+
from .approximants import approximants
|
| 8 |
+
from .residues import residue
|
| 9 |
+
from .sequences import SeqPer, SeqFormula, sequence, SeqAdd, SeqMul
|
| 10 |
+
from .fourier import fourier_series
|
| 11 |
+
from .formal import fps
|
| 12 |
+
from .limitseq import difference_delta, limit_seq
|
| 13 |
+
|
| 14 |
+
from sympy.core.singleton import S
|
| 15 |
+
EmptySequence = S.EmptySequence
|
| 16 |
+
|
| 17 |
+
O = Order
|
| 18 |
+
|
| 19 |
+
__all__ = ['Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants',
|
| 20 |
+
'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence',
|
| 21 |
+
'SeqAdd', 'SeqMul', 'fourier_series', 'fps', 'difference_delta',
|
| 22 |
+
'limit_seq'
|
| 23 |
+
]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/acceleration.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Convergence acceleration / extrapolation methods for series and
|
| 3 |
+
sequences.
|
| 4 |
+
|
| 5 |
+
References:
|
| 6 |
+
Carl M. Bender & Steven A. Orszag, "Advanced Mathematical Methods for
|
| 7 |
+
Scientists and Engineers: Asymptotic Methods and Perturbation Theory",
|
| 8 |
+
Springer 1999. (Shanks transformation: pp. 368-375, Richardson
|
| 9 |
+
extrapolation: pp. 375-377.)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from sympy.core.numbers import Integer
|
| 13 |
+
from sympy.core.singleton import S
|
| 14 |
+
from sympy.functions.combinatorial.factorials import factorial
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def richardson(A, k, n, N):
|
| 18 |
+
"""
|
| 19 |
+
Calculate an approximation for lim k->oo A(k) using Richardson
|
| 20 |
+
extrapolation with the terms A(n), A(n+1), ..., A(n+N+1).
|
| 21 |
+
Choosing N ~= 2*n often gives good results.
|
| 22 |
+
|
| 23 |
+
Examples
|
| 24 |
+
========
|
| 25 |
+
|
| 26 |
+
A simple example is to calculate exp(1) using the limit definition.
|
| 27 |
+
This limit converges slowly; n = 100 only produces two accurate
|
| 28 |
+
digits:
|
| 29 |
+
|
| 30 |
+
>>> from sympy.abc import n
|
| 31 |
+
>>> e = (1 + 1/n)**n
|
| 32 |
+
>>> print(round(e.subs(n, 100).evalf(), 10))
|
| 33 |
+
2.7048138294
|
| 34 |
+
|
| 35 |
+
Richardson extrapolation with 11 appropriately chosen terms gives
|
| 36 |
+
a value that is accurate to the indicated precision:
|
| 37 |
+
|
| 38 |
+
>>> from sympy import E
|
| 39 |
+
>>> from sympy.series.acceleration import richardson
|
| 40 |
+
>>> print(round(richardson(e, n, 10, 20).evalf(), 10))
|
| 41 |
+
2.7182818285
|
| 42 |
+
>>> print(round(E.evalf(), 10))
|
| 43 |
+
2.7182818285
|
| 44 |
+
|
| 45 |
+
Another useful application is to speed up convergence of series.
|
| 46 |
+
Computing 100 terms of the zeta(2) series 1/k**2 yields only
|
| 47 |
+
two accurate digits:
|
| 48 |
+
|
| 49 |
+
>>> from sympy.abc import k, n
|
| 50 |
+
>>> from sympy import Sum
|
| 51 |
+
>>> A = Sum(k**-2, (k, 1, n))
|
| 52 |
+
>>> print(round(A.subs(n, 100).evalf(), 10))
|
| 53 |
+
1.6349839002
|
| 54 |
+
|
| 55 |
+
Richardson extrapolation performs much better:
|
| 56 |
+
|
| 57 |
+
>>> from sympy import pi
|
| 58 |
+
>>> print(round(richardson(A, n, 10, 20).evalf(), 10))
|
| 59 |
+
1.6449340668
|
| 60 |
+
>>> print(round(((pi**2)/6).evalf(), 10)) # Exact value
|
| 61 |
+
1.6449340668
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
s = S.Zero
|
| 65 |
+
for j in range(0, N + 1):
|
| 66 |
+
s += (A.subs(k, Integer(n + j)).doit() * (n + j)**N *
|
| 67 |
+
S.NegativeOne**(j + N) / (factorial(j) * factorial(N - j)))
|
| 68 |
+
return s
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def shanks(A, k, n, m=1):
|
| 72 |
+
"""
|
| 73 |
+
Calculate an approximation for lim k->oo A(k) using the n-term Shanks
|
| 74 |
+
transformation S(A)(n). With m > 1, calculate the m-fold recursive
|
| 75 |
+
Shanks transformation S(S(...S(A)...))(n).
|
| 76 |
+
|
| 77 |
+
The Shanks transformation is useful for summing Taylor series that
|
| 78 |
+
converge slowly near a pole or singularity, e.g. for log(2):
|
| 79 |
+
|
| 80 |
+
>>> from sympy.abc import k, n
|
| 81 |
+
>>> from sympy import Sum, Integer
|
| 82 |
+
>>> from sympy.series.acceleration import shanks
|
| 83 |
+
>>> A = Sum(Integer(-1)**(k+1) / k, (k, 1, n))
|
| 84 |
+
>>> print(round(A.subs(n, 100).doit().evalf(), 10))
|
| 85 |
+
0.6881721793
|
| 86 |
+
>>> print(round(shanks(A, n, 25).evalf(), 10))
|
| 87 |
+
0.6931396564
|
| 88 |
+
>>> print(round(shanks(A, n, 25, 5).evalf(), 10))
|
| 89 |
+
0.6931471806
|
| 90 |
+
|
| 91 |
+
The correct value is 0.6931471805599453094172321215.
|
| 92 |
+
"""
|
| 93 |
+
table = [A.subs(k, Integer(j)).doit() for j in range(n + m + 2)]
|
| 94 |
+
table2 = table[:]
|
| 95 |
+
|
| 96 |
+
for i in range(1, m + 1):
|
| 97 |
+
for j in range(i, n + m + 1):
|
| 98 |
+
x, y, z = table[j - 1], table[j], table[j + 1]
|
| 99 |
+
table2[j] = (z*x - y**2) / (z + x - 2*y)
|
| 100 |
+
table = table2[:]
|
| 101 |
+
return table[n]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/approximants.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.singleton import S
|
| 2 |
+
from sympy.core.symbol import Symbol
|
| 3 |
+
from sympy.polys.polytools import lcm
|
| 4 |
+
from sympy.utilities import public
|
| 5 |
+
|
| 6 |
+
@public
|
| 7 |
+
def approximants(l, X=Symbol('x'), simplify=False):
|
| 8 |
+
"""
|
| 9 |
+
Return a generator for consecutive Pade approximants for a series.
|
| 10 |
+
It can also be used for computing the rational generating function of a
|
| 11 |
+
series when possible, since the last approximant returned by the generator
|
| 12 |
+
will be the generating function (if any).
|
| 13 |
+
|
| 14 |
+
Explanation
|
| 15 |
+
===========
|
| 16 |
+
|
| 17 |
+
The input list can contain more complex expressions than integer or rational
|
| 18 |
+
numbers; symbols may also be involved in the computation. An example below
|
| 19 |
+
show how to compute the generating function of the whole Pascal triangle.
|
| 20 |
+
|
| 21 |
+
The generator can be asked to apply the sympy.simplify function on each
|
| 22 |
+
generated term, which will make the computation slower; however it may be
|
| 23 |
+
useful when symbols are involved in the expressions.
|
| 24 |
+
|
| 25 |
+
Examples
|
| 26 |
+
========
|
| 27 |
+
|
| 28 |
+
>>> from sympy.series import approximants
|
| 29 |
+
>>> from sympy import lucas, fibonacci, symbols, binomial
|
| 30 |
+
>>> g = [lucas(k) for k in range(16)]
|
| 31 |
+
>>> [e for e in approximants(g)]
|
| 32 |
+
[2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)]
|
| 33 |
+
|
| 34 |
+
>>> h = [fibonacci(k) for k in range(16)]
|
| 35 |
+
>>> [e for e in approximants(h)]
|
| 36 |
+
[x, -x/(x - 1), (x**2 - x)/(2*x - 1), -x/(x**2 + x - 1)]
|
| 37 |
+
|
| 38 |
+
>>> x, t = symbols("x,t")
|
| 39 |
+
>>> p=[sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)]
|
| 40 |
+
>>> y = approximants(p, t)
|
| 41 |
+
>>> for k in range(3): print(next(y))
|
| 42 |
+
1
|
| 43 |
+
(x + 1)/((-x - 1)*(t*(x + 1) + (x + 1)/(-x - 1)))
|
| 44 |
+
nan
|
| 45 |
+
|
| 46 |
+
>>> y = approximants(p, t, simplify=True)
|
| 47 |
+
>>> for k in range(3): print(next(y))
|
| 48 |
+
1
|
| 49 |
+
-1/(t*(x + 1) - 1)
|
| 50 |
+
nan
|
| 51 |
+
|
| 52 |
+
See Also
|
| 53 |
+
========
|
| 54 |
+
|
| 55 |
+
sympy.concrete.guess.guess_generating_function_rational
|
| 56 |
+
mpmath.pade
|
| 57 |
+
"""
|
| 58 |
+
from sympy.simplify import simplify as simp
|
| 59 |
+
from sympy.simplify.radsimp import denom
|
| 60 |
+
p1, q1 = [S.One], [S.Zero]
|
| 61 |
+
p2, q2 = [S.Zero], [S.One]
|
| 62 |
+
while len(l):
|
| 63 |
+
b = 0
|
| 64 |
+
while l[b]==0:
|
| 65 |
+
b += 1
|
| 66 |
+
if b == len(l):
|
| 67 |
+
return
|
| 68 |
+
m = [S.One/l[b]]
|
| 69 |
+
for k in range(b+1, len(l)):
|
| 70 |
+
s = 0
|
| 71 |
+
for j in range(b, k):
|
| 72 |
+
s -= l[j+1] * m[b-j-1]
|
| 73 |
+
m.append(s/l[b])
|
| 74 |
+
l = m
|
| 75 |
+
a, l[0] = l[0], 0
|
| 76 |
+
p = [0] * max(len(p2), b+len(p1))
|
| 77 |
+
q = [0] * max(len(q2), b+len(q1))
|
| 78 |
+
for k in range(len(p2)):
|
| 79 |
+
p[k] = a*p2[k]
|
| 80 |
+
for k in range(b, b+len(p1)):
|
| 81 |
+
p[k] += p1[k-b]
|
| 82 |
+
for k in range(len(q2)):
|
| 83 |
+
q[k] = a*q2[k]
|
| 84 |
+
for k in range(b, b+len(q1)):
|
| 85 |
+
q[k] += q1[k-b]
|
| 86 |
+
while p[-1]==0: p.pop()
|
| 87 |
+
while q[-1]==0: q.pop()
|
| 88 |
+
p1, p2 = p2, p
|
| 89 |
+
q1, q2 = q2, q
|
| 90 |
+
|
| 91 |
+
# yield result
|
| 92 |
+
c = 1
|
| 93 |
+
for x in p:
|
| 94 |
+
c = lcm(c, denom(x))
|
| 95 |
+
for x in q:
|
| 96 |
+
c = lcm(c, denom(x))
|
| 97 |
+
out = ( sum(c*e*X**k for k, e in enumerate(p))
|
| 98 |
+
/ sum(c*e*X**k for k, e in enumerate(q)) )
|
| 99 |
+
if simplify:
|
| 100 |
+
yield(simp(out))
|
| 101 |
+
else:
|
| 102 |
+
yield out
|
| 103 |
+
return
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/aseries.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.sympify import sympify
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def aseries(expr, x=None, n=6, bound=0, hir=False):
|
| 5 |
+
"""
|
| 6 |
+
See the docstring of Expr.aseries() for complete details of this wrapper.
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
expr = sympify(expr)
|
| 10 |
+
return expr.aseries(x, n, bound, hir)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/formal.py
ADDED
|
@@ -0,0 +1,1869 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Formal Power Series"""
|
| 2 |
+
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
|
| 5 |
+
from sympy.core.numbers import (nan, oo, zoo)
|
| 6 |
+
from sympy.core.add import Add
|
| 7 |
+
from sympy.core.expr import Expr
|
| 8 |
+
from sympy.core.function import Derivative, Function, expand
|
| 9 |
+
from sympy.core.mul import Mul
|
| 10 |
+
from sympy.core.numbers import Rational
|
| 11 |
+
from sympy.core.relational import Eq
|
| 12 |
+
from sympy.sets.sets import Interval
|
| 13 |
+
from sympy.core.singleton import S
|
| 14 |
+
from sympy.core.symbol import Wild, Dummy, symbols, Symbol
|
| 15 |
+
from sympy.core.sympify import sympify
|
| 16 |
+
from sympy.discrete.convolutions import convolution
|
| 17 |
+
from sympy.functions.combinatorial.factorials import binomial, factorial, rf
|
| 18 |
+
from sympy.functions.combinatorial.numbers import bell
|
| 19 |
+
from sympy.functions.elementary.integers import floor, frac, ceiling
|
| 20 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
| 21 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 22 |
+
from sympy.series.limits import Limit
|
| 23 |
+
from sympy.series.order import Order
|
| 24 |
+
from sympy.series.sequences import sequence
|
| 25 |
+
from sympy.series.series_class import SeriesBase
|
| 26 |
+
from sympy.utilities.iterables import iterable
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def rational_algorithm(f, x, k, order=4, full=False):
|
| 31 |
+
"""
|
| 32 |
+
Rational algorithm for computing
|
| 33 |
+
formula of coefficients of Formal Power Series
|
| 34 |
+
of a function.
|
| 35 |
+
|
| 36 |
+
Explanation
|
| 37 |
+
===========
|
| 38 |
+
|
| 39 |
+
Applicable when f(x) or some derivative of f(x)
|
| 40 |
+
is a rational function in x.
|
| 41 |
+
|
| 42 |
+
:func:`rational_algorithm` uses :func:`~.apart` function for partial fraction
|
| 43 |
+
decomposition. :func:`~.apart` by default uses 'undetermined coefficients
|
| 44 |
+
method'. By setting ``full=True``, 'Bronstein's algorithm' can be used
|
| 45 |
+
instead.
|
| 46 |
+
|
| 47 |
+
Looks for derivative of a function up to 4'th order (by default).
|
| 48 |
+
This can be overridden using order option.
|
| 49 |
+
|
| 50 |
+
Parameters
|
| 51 |
+
==========
|
| 52 |
+
|
| 53 |
+
x : Symbol
|
| 54 |
+
order : int, optional
|
| 55 |
+
Order of the derivative of ``f``, Default is 4.
|
| 56 |
+
full : bool
|
| 57 |
+
|
| 58 |
+
Returns
|
| 59 |
+
=======
|
| 60 |
+
|
| 61 |
+
formula : Expr
|
| 62 |
+
ind : Expr
|
| 63 |
+
Independent terms.
|
| 64 |
+
order : int
|
| 65 |
+
full : bool
|
| 66 |
+
|
| 67 |
+
Examples
|
| 68 |
+
========
|
| 69 |
+
|
| 70 |
+
>>> from sympy import log, atan
|
| 71 |
+
>>> from sympy.series.formal import rational_algorithm as ra
|
| 72 |
+
>>> from sympy.abc import x, k
|
| 73 |
+
|
| 74 |
+
>>> ra(1 / (1 - x), x, k)
|
| 75 |
+
(1, 0, 0)
|
| 76 |
+
>>> ra(log(1 + x), x, k)
|
| 77 |
+
(-1/((-1)**k*k), 0, 1)
|
| 78 |
+
|
| 79 |
+
>>> ra(atan(x), x, k, full=True)
|
| 80 |
+
((-I/(2*(-I)**k) + I/(2*I**k))/k, 0, 1)
|
| 81 |
+
|
| 82 |
+
Notes
|
| 83 |
+
=====
|
| 84 |
+
|
| 85 |
+
By setting ``full=True``, range of admissible functions to be solved using
|
| 86 |
+
``rational_algorithm`` can be increased. This option should be used
|
| 87 |
+
carefully as it can significantly slow down the computation as ``doit`` is
|
| 88 |
+
performed on the :class:`~.RootSum` object returned by the :func:`~.apart`
|
| 89 |
+
function. Use ``full=False`` whenever possible.
|
| 90 |
+
|
| 91 |
+
See Also
|
| 92 |
+
========
|
| 93 |
+
|
| 94 |
+
sympy.polys.partfrac.apart
|
| 95 |
+
|
| 96 |
+
References
|
| 97 |
+
==========
|
| 98 |
+
|
| 99 |
+
.. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
|
| 100 |
+
.. [2] Power Series in Computer Algebra - Wolfram Koepf
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
from sympy.polys import RootSum, apart
|
| 104 |
+
from sympy.integrals import integrate
|
| 105 |
+
|
| 106 |
+
diff = f
|
| 107 |
+
ds = [] # list of diff
|
| 108 |
+
|
| 109 |
+
for i in range(order + 1):
|
| 110 |
+
if i:
|
| 111 |
+
diff = diff.diff(x)
|
| 112 |
+
|
| 113 |
+
if diff.is_rational_function(x):
|
| 114 |
+
coeff, sep = S.Zero, S.Zero
|
| 115 |
+
|
| 116 |
+
terms = apart(diff, x, full=full)
|
| 117 |
+
if terms.has(RootSum):
|
| 118 |
+
terms = terms.doit()
|
| 119 |
+
|
| 120 |
+
for t in Add.make_args(terms):
|
| 121 |
+
num, den = t.as_numer_denom()
|
| 122 |
+
if not den.has(x):
|
| 123 |
+
sep += t
|
| 124 |
+
else:
|
| 125 |
+
if isinstance(den, Mul):
|
| 126 |
+
# m*(n*x - a)**j -> (n*x - a)**j
|
| 127 |
+
ind = den.as_independent(x)
|
| 128 |
+
den = ind[1]
|
| 129 |
+
num /= ind[0]
|
| 130 |
+
|
| 131 |
+
# (n*x - a)**j -> (x - b)
|
| 132 |
+
den, j = den.as_base_exp()
|
| 133 |
+
a, xterm = den.as_coeff_add(x)
|
| 134 |
+
|
| 135 |
+
# term -> m/x**n
|
| 136 |
+
if not a:
|
| 137 |
+
sep += t
|
| 138 |
+
continue
|
| 139 |
+
|
| 140 |
+
xc = xterm[0].coeff(x)
|
| 141 |
+
a /= -xc
|
| 142 |
+
num /= xc**j
|
| 143 |
+
|
| 144 |
+
ak = ((-1)**j * num *
|
| 145 |
+
binomial(j + k - 1, k).rewrite(factorial) /
|
| 146 |
+
a**(j + k))
|
| 147 |
+
coeff += ak
|
| 148 |
+
|
| 149 |
+
# Hacky, better way?
|
| 150 |
+
if coeff.is_zero:
|
| 151 |
+
return None
|
| 152 |
+
if (coeff.has(x) or coeff.has(zoo) or coeff.has(oo) or
|
| 153 |
+
coeff.has(nan)):
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
for j in range(i):
|
| 157 |
+
coeff = (coeff / (k + j + 1))
|
| 158 |
+
sep = integrate(sep, x)
|
| 159 |
+
sep += (ds.pop() - sep).limit(x, 0) # constant of integration
|
| 160 |
+
return (coeff.subs(k, k - i), sep, i)
|
| 161 |
+
|
| 162 |
+
else:
|
| 163 |
+
ds.append(diff)
|
| 164 |
+
|
| 165 |
+
return None
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def rational_independent(terms, x):
|
| 169 |
+
"""
|
| 170 |
+
Returns a list of all the rationally independent terms.
|
| 171 |
+
|
| 172 |
+
Examples
|
| 173 |
+
========
|
| 174 |
+
|
| 175 |
+
>>> from sympy import sin, cos
|
| 176 |
+
>>> from sympy.series.formal import rational_independent
|
| 177 |
+
>>> from sympy.abc import x
|
| 178 |
+
|
| 179 |
+
>>> rational_independent([cos(x), sin(x)], x)
|
| 180 |
+
[cos(x), sin(x)]
|
| 181 |
+
>>> rational_independent([x**2, sin(x), x*sin(x), x**3], x)
|
| 182 |
+
[x**3 + x**2, x*sin(x) + sin(x)]
|
| 183 |
+
"""
|
| 184 |
+
if not terms:
|
| 185 |
+
return []
|
| 186 |
+
|
| 187 |
+
ind = terms[0:1]
|
| 188 |
+
|
| 189 |
+
for t in terms[1:]:
|
| 190 |
+
n = t.as_independent(x)[1]
|
| 191 |
+
for i, term in enumerate(ind):
|
| 192 |
+
d = term.as_independent(x)[1]
|
| 193 |
+
q = (n / d).cancel()
|
| 194 |
+
if q.is_rational_function(x):
|
| 195 |
+
ind[i] += t
|
| 196 |
+
break
|
| 197 |
+
else:
|
| 198 |
+
ind.append(t)
|
| 199 |
+
return ind
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def simpleDE(f, x, g, order=4):
|
| 203 |
+
r"""
|
| 204 |
+
Generates simple DE.
|
| 205 |
+
|
| 206 |
+
Explanation
|
| 207 |
+
===========
|
| 208 |
+
|
| 209 |
+
DE is of the form
|
| 210 |
+
|
| 211 |
+
.. math::
|
| 212 |
+
f^k(x) + \sum\limits_{j=0}^{k-1} A_j f^j(x) = 0
|
| 213 |
+
|
| 214 |
+
where :math:`A_j` should be rational function in x.
|
| 215 |
+
|
| 216 |
+
Generates DE's upto order 4 (default). DE's can also have free parameters.
|
| 217 |
+
|
| 218 |
+
By increasing order, higher order DE's can be found.
|
| 219 |
+
|
| 220 |
+
Yields a tuple of (DE, order).
|
| 221 |
+
"""
|
| 222 |
+
from sympy.solvers.solveset import linsolve
|
| 223 |
+
|
| 224 |
+
a = symbols('a:%d' % (order))
|
| 225 |
+
|
| 226 |
+
def _makeDE(k):
|
| 227 |
+
eq = f.diff(x, k) + Add(*[a[i]*f.diff(x, i) for i in range(0, k)])
|
| 228 |
+
DE = g(x).diff(x, k) + Add(*[a[i]*g(x).diff(x, i) for i in range(0, k)])
|
| 229 |
+
return eq, DE
|
| 230 |
+
|
| 231 |
+
found = False
|
| 232 |
+
for k in range(1, order + 1):
|
| 233 |
+
eq, DE = _makeDE(k)
|
| 234 |
+
eq = eq.expand()
|
| 235 |
+
terms = eq.as_ordered_terms()
|
| 236 |
+
ind = rational_independent(terms, x)
|
| 237 |
+
if found or len(ind) == k:
|
| 238 |
+
sol = dict(zip(a, (i for s in linsolve(ind, a[:k]) for i in s)))
|
| 239 |
+
if sol:
|
| 240 |
+
found = True
|
| 241 |
+
DE = DE.subs(sol)
|
| 242 |
+
DE = DE.as_numer_denom()[0]
|
| 243 |
+
DE = DE.factor().as_coeff_mul(Derivative)[1][0]
|
| 244 |
+
yield DE.collect(Derivative(g(x))), k
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def exp_re(DE, r, k):
|
| 248 |
+
"""Converts a DE with constant coefficients (explike) into a RE.
|
| 249 |
+
|
| 250 |
+
Explanation
|
| 251 |
+
===========
|
| 252 |
+
|
| 253 |
+
Performs the substitution:
|
| 254 |
+
|
| 255 |
+
.. math::
|
| 256 |
+
f^j(x) \\to r(k + j)
|
| 257 |
+
|
| 258 |
+
Normalises the terms so that lowest order of a term is always r(k).
|
| 259 |
+
|
| 260 |
+
Examples
|
| 261 |
+
========
|
| 262 |
+
|
| 263 |
+
>>> from sympy import Function, Derivative
|
| 264 |
+
>>> from sympy.series.formal import exp_re
|
| 265 |
+
>>> from sympy.abc import x, k
|
| 266 |
+
>>> f, r = Function('f'), Function('r')
|
| 267 |
+
|
| 268 |
+
>>> exp_re(-f(x) + Derivative(f(x)), r, k)
|
| 269 |
+
-r(k) + r(k + 1)
|
| 270 |
+
>>> exp_re(Derivative(f(x), x) + Derivative(f(x), (x, 2)), r, k)
|
| 271 |
+
r(k) + r(k + 1)
|
| 272 |
+
|
| 273 |
+
See Also
|
| 274 |
+
========
|
| 275 |
+
|
| 276 |
+
sympy.series.formal.hyper_re
|
| 277 |
+
"""
|
| 278 |
+
RE = S.Zero
|
| 279 |
+
|
| 280 |
+
g = DE.atoms(Function).pop()
|
| 281 |
+
|
| 282 |
+
mini = None
|
| 283 |
+
for t in Add.make_args(DE):
|
| 284 |
+
coeff, d = t.as_independent(g)
|
| 285 |
+
if isinstance(d, Derivative):
|
| 286 |
+
j = d.derivative_count
|
| 287 |
+
else:
|
| 288 |
+
j = 0
|
| 289 |
+
if mini is None or j < mini:
|
| 290 |
+
mini = j
|
| 291 |
+
RE += coeff * r(k + j)
|
| 292 |
+
if mini:
|
| 293 |
+
RE = RE.subs(k, k - mini)
|
| 294 |
+
return RE
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def hyper_re(DE, r, k):
|
| 298 |
+
"""
|
| 299 |
+
Converts a DE into a RE.
|
| 300 |
+
|
| 301 |
+
Explanation
|
| 302 |
+
===========
|
| 303 |
+
|
| 304 |
+
Performs the substitution:
|
| 305 |
+
|
| 306 |
+
.. math::
|
| 307 |
+
x^l f^j(x) \\to (k + 1 - l)_j . a_{k + j - l}
|
| 308 |
+
|
| 309 |
+
Normalises the terms so that lowest order of a term is always r(k).
|
| 310 |
+
|
| 311 |
+
Examples
|
| 312 |
+
========
|
| 313 |
+
|
| 314 |
+
>>> from sympy import Function, Derivative
|
| 315 |
+
>>> from sympy.series.formal import hyper_re
|
| 316 |
+
>>> from sympy.abc import x, k
|
| 317 |
+
>>> f, r = Function('f'), Function('r')
|
| 318 |
+
|
| 319 |
+
>>> hyper_re(-f(x) + Derivative(f(x)), r, k)
|
| 320 |
+
(k + 1)*r(k + 1) - r(k)
|
| 321 |
+
>>> hyper_re(-x*f(x) + Derivative(f(x), (x, 2)), r, k)
|
| 322 |
+
(k + 2)*(k + 3)*r(k + 3) - r(k)
|
| 323 |
+
|
| 324 |
+
See Also
|
| 325 |
+
========
|
| 326 |
+
|
| 327 |
+
sympy.series.formal.exp_re
|
| 328 |
+
"""
|
| 329 |
+
RE = S.Zero
|
| 330 |
+
|
| 331 |
+
g = DE.atoms(Function).pop()
|
| 332 |
+
x = g.atoms(Symbol).pop()
|
| 333 |
+
|
| 334 |
+
mini = None
|
| 335 |
+
for t in Add.make_args(DE.expand()):
|
| 336 |
+
coeff, d = t.as_independent(g)
|
| 337 |
+
c, v = coeff.as_independent(x)
|
| 338 |
+
l = v.as_coeff_exponent(x)[1]
|
| 339 |
+
if isinstance(d, Derivative):
|
| 340 |
+
j = d.derivative_count
|
| 341 |
+
else:
|
| 342 |
+
j = 0
|
| 343 |
+
RE += c * rf(k + 1 - l, j) * r(k + j - l)
|
| 344 |
+
if mini is None or j - l < mini:
|
| 345 |
+
mini = j - l
|
| 346 |
+
|
| 347 |
+
RE = RE.subs(k, k - mini)
|
| 348 |
+
|
| 349 |
+
m = Wild('m')
|
| 350 |
+
return RE.collect(r(k + m))
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _transformation_a(f, x, P, Q, k, m, shift):
|
| 354 |
+
f *= x**(-shift)
|
| 355 |
+
P = P.subs(k, k + shift)
|
| 356 |
+
Q = Q.subs(k, k + shift)
|
| 357 |
+
return f, P, Q, m
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def _transformation_c(f, x, P, Q, k, m, scale):
|
| 361 |
+
f = f.subs(x, x**scale)
|
| 362 |
+
P = P.subs(k, k / scale)
|
| 363 |
+
Q = Q.subs(k, k / scale)
|
| 364 |
+
m *= scale
|
| 365 |
+
return f, P, Q, m
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _transformation_e(f, x, P, Q, k, m):
|
| 369 |
+
f = f.diff(x)
|
| 370 |
+
P = P.subs(k, k + 1) * (k + m + 1)
|
| 371 |
+
Q = Q.subs(k, k + 1) * (k + 1)
|
| 372 |
+
return f, P, Q, m
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _apply_shift(sol, shift):
|
| 376 |
+
return [(res, cond + shift) for res, cond in sol]
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _apply_scale(sol, scale):
|
| 380 |
+
return [(res, cond / scale) for res, cond in sol]
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _apply_integrate(sol, x, k):
|
| 384 |
+
return [(res / ((cond + 1)*(cond.as_coeff_Add()[1].coeff(k))), cond + 1)
|
| 385 |
+
for res, cond in sol]
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _compute_formula(f, x, P, Q, k, m, k_max):
|
| 389 |
+
"""Computes the formula for f."""
|
| 390 |
+
from sympy.polys import roots
|
| 391 |
+
|
| 392 |
+
sol = []
|
| 393 |
+
for i in range(k_max + 1, k_max + m + 1):
|
| 394 |
+
if (i < 0) == True:
|
| 395 |
+
continue
|
| 396 |
+
r = f.diff(x, i).limit(x, 0) / factorial(i)
|
| 397 |
+
if r.is_zero:
|
| 398 |
+
continue
|
| 399 |
+
|
| 400 |
+
kterm = m*k + i
|
| 401 |
+
res = r
|
| 402 |
+
|
| 403 |
+
p = P.subs(k, kterm)
|
| 404 |
+
q = Q.subs(k, kterm)
|
| 405 |
+
c1 = p.subs(k, 1/k).leadterm(k)[0]
|
| 406 |
+
c2 = q.subs(k, 1/k).leadterm(k)[0]
|
| 407 |
+
res *= (-c1 / c2)**k
|
| 408 |
+
|
| 409 |
+
res *= Mul(*[rf(-r, k)**mul for r, mul in roots(p, k).items()])
|
| 410 |
+
res /= Mul(*[rf(-r, k)**mul for r, mul in roots(q, k).items()])
|
| 411 |
+
|
| 412 |
+
sol.append((res, kterm))
|
| 413 |
+
|
| 414 |
+
return sol
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def _rsolve_hypergeometric(f, x, P, Q, k, m):
|
| 418 |
+
"""
|
| 419 |
+
Recursive wrapper to rsolve_hypergeometric.
|
| 420 |
+
|
| 421 |
+
Explanation
|
| 422 |
+
===========
|
| 423 |
+
|
| 424 |
+
Returns a Tuple of (formula, series independent terms,
|
| 425 |
+
maximum power of x in independent terms) if successful
|
| 426 |
+
otherwise ``None``.
|
| 427 |
+
|
| 428 |
+
See :func:`rsolve_hypergeometric` for details.
|
| 429 |
+
"""
|
| 430 |
+
from sympy.polys import lcm, roots
|
| 431 |
+
from sympy.integrals import integrate
|
| 432 |
+
|
| 433 |
+
# transformation - c
|
| 434 |
+
proots, qroots = roots(P, k), roots(Q, k)
|
| 435 |
+
all_roots = dict(proots)
|
| 436 |
+
all_roots.update(qroots)
|
| 437 |
+
scale = lcm([r.as_numer_denom()[1] for r, t in all_roots.items()
|
| 438 |
+
if r.is_rational])
|
| 439 |
+
f, P, Q, m = _transformation_c(f, x, P, Q, k, m, scale)
|
| 440 |
+
|
| 441 |
+
# transformation - a
|
| 442 |
+
qroots = roots(Q, k)
|
| 443 |
+
if qroots:
|
| 444 |
+
k_min = Min(*qroots.keys())
|
| 445 |
+
else:
|
| 446 |
+
k_min = S.Zero
|
| 447 |
+
shift = k_min + m
|
| 448 |
+
f, P, Q, m = _transformation_a(f, x, P, Q, k, m, shift)
|
| 449 |
+
|
| 450 |
+
l = (x*f).limit(x, 0)
|
| 451 |
+
if not isinstance(l, Limit) and l != 0: # Ideally should only be l != 0
|
| 452 |
+
return None
|
| 453 |
+
|
| 454 |
+
qroots = roots(Q, k)
|
| 455 |
+
if qroots:
|
| 456 |
+
k_max = Max(*qroots.keys())
|
| 457 |
+
else:
|
| 458 |
+
k_max = S.Zero
|
| 459 |
+
|
| 460 |
+
ind, mp = S.Zero, -oo
|
| 461 |
+
for i in range(k_max + m + 1):
|
| 462 |
+
r = f.diff(x, i).limit(x, 0) / factorial(i)
|
| 463 |
+
if r.is_finite is False:
|
| 464 |
+
old_f = f
|
| 465 |
+
f, P, Q, m = _transformation_a(f, x, P, Q, k, m, i)
|
| 466 |
+
f, P, Q, m = _transformation_e(f, x, P, Q, k, m)
|
| 467 |
+
sol, ind, mp = _rsolve_hypergeometric(f, x, P, Q, k, m)
|
| 468 |
+
sol = _apply_integrate(sol, x, k)
|
| 469 |
+
sol = _apply_shift(sol, i)
|
| 470 |
+
ind = integrate(ind, x)
|
| 471 |
+
ind += (old_f - ind).limit(x, 0) # constant of integration
|
| 472 |
+
mp += 1
|
| 473 |
+
return sol, ind, mp
|
| 474 |
+
elif r:
|
| 475 |
+
ind += r*x**(i + shift)
|
| 476 |
+
pow_x = Rational((i + shift), scale)
|
| 477 |
+
if pow_x > mp:
|
| 478 |
+
mp = pow_x # maximum power of x
|
| 479 |
+
ind = ind.subs(x, x**(1/scale))
|
| 480 |
+
|
| 481 |
+
sol = _compute_formula(f, x, P, Q, k, m, k_max)
|
| 482 |
+
sol = _apply_shift(sol, shift)
|
| 483 |
+
sol = _apply_scale(sol, scale)
|
| 484 |
+
|
| 485 |
+
return sol, ind, mp
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def rsolve_hypergeometric(f, x, P, Q, k, m):
|
| 489 |
+
"""
|
| 490 |
+
Solves RE of hypergeometric type.
|
| 491 |
+
|
| 492 |
+
Explanation
|
| 493 |
+
===========
|
| 494 |
+
|
| 495 |
+
Attempts to solve RE of the form
|
| 496 |
+
|
| 497 |
+
Q(k)*a(k + m) - P(k)*a(k)
|
| 498 |
+
|
| 499 |
+
Transformations that preserve Hypergeometric type:
|
| 500 |
+
|
| 501 |
+
a. x**n*f(x): b(k + m) = R(k - n)*b(k)
|
| 502 |
+
b. f(A*x): b(k + m) = A**m*R(k)*b(k)
|
| 503 |
+
c. f(x**n): b(k + n*m) = R(k/n)*b(k)
|
| 504 |
+
d. f(x**(1/m)): b(k + 1) = R(k*m)*b(k)
|
| 505 |
+
e. f'(x): b(k + m) = ((k + m + 1)/(k + 1))*R(k + 1)*b(k)
|
| 506 |
+
|
| 507 |
+
Some of these transformations have been used to solve the RE.
|
| 508 |
+
|
| 509 |
+
Returns
|
| 510 |
+
=======
|
| 511 |
+
|
| 512 |
+
formula : Expr
|
| 513 |
+
ind : Expr
|
| 514 |
+
Independent terms.
|
| 515 |
+
order : int
|
| 516 |
+
|
| 517 |
+
Examples
|
| 518 |
+
========
|
| 519 |
+
|
| 520 |
+
>>> from sympy import exp, ln, S
|
| 521 |
+
>>> from sympy.series.formal import rsolve_hypergeometric as rh
|
| 522 |
+
>>> from sympy.abc import x, k
|
| 523 |
+
|
| 524 |
+
>>> rh(exp(x), x, -S.One, (k + 1), k, 1)
|
| 525 |
+
(Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
|
| 526 |
+
|
| 527 |
+
>>> rh(ln(1 + x), x, k**2, k*(k + 1), k, 1)
|
| 528 |
+
(Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
|
| 529 |
+
Eq(Mod(k, 1), 0)), (0, True)), x, 2)
|
| 530 |
+
|
| 531 |
+
References
|
| 532 |
+
==========
|
| 533 |
+
|
| 534 |
+
.. [1] Formal Power Series - Dominik Gruntz, Wolfram Koepf
|
| 535 |
+
.. [2] Power Series in Computer Algebra - Wolfram Koepf
|
| 536 |
+
"""
|
| 537 |
+
result = _rsolve_hypergeometric(f, x, P, Q, k, m)
|
| 538 |
+
|
| 539 |
+
if result is None:
|
| 540 |
+
return None
|
| 541 |
+
|
| 542 |
+
sol_list, ind, mp = result
|
| 543 |
+
|
| 544 |
+
sol_dict = defaultdict(lambda: S.Zero)
|
| 545 |
+
for res, cond in sol_list:
|
| 546 |
+
j, mk = cond.as_coeff_Add()
|
| 547 |
+
c = mk.coeff(k)
|
| 548 |
+
|
| 549 |
+
if j.is_integer is False:
|
| 550 |
+
res *= x**frac(j)
|
| 551 |
+
j = floor(j)
|
| 552 |
+
|
| 553 |
+
res = res.subs(k, (k - j) / c)
|
| 554 |
+
cond = Eq(k % c, j % c)
|
| 555 |
+
sol_dict[cond] += res # Group together formula for same conditions
|
| 556 |
+
|
| 557 |
+
sol = []
|
| 558 |
+
for cond, res in sol_dict.items():
|
| 559 |
+
sol.append((res, cond))
|
| 560 |
+
sol.append((S.Zero, True))
|
| 561 |
+
sol = Piecewise(*sol)
|
| 562 |
+
|
| 563 |
+
if mp is -oo:
|
| 564 |
+
s = S.Zero
|
| 565 |
+
elif mp.is_integer is False:
|
| 566 |
+
s = ceiling(mp)
|
| 567 |
+
else:
|
| 568 |
+
s = mp + 1
|
| 569 |
+
|
| 570 |
+
# save all the terms of
|
| 571 |
+
# form 1/x**k in ind
|
| 572 |
+
if s < 0:
|
| 573 |
+
ind += sum(sequence(sol * x**k, (k, s, -1)))
|
| 574 |
+
s = S.Zero
|
| 575 |
+
|
| 576 |
+
return (sol, ind, s)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def _solve_hyper_RE(f, x, RE, g, k):
|
| 580 |
+
"""See docstring of :func:`rsolve_hypergeometric` for details."""
|
| 581 |
+
terms = Add.make_args(RE)
|
| 582 |
+
|
| 583 |
+
if len(terms) == 2:
|
| 584 |
+
gs = list(RE.atoms(Function))
|
| 585 |
+
P, Q = map(RE.coeff, gs)
|
| 586 |
+
m = gs[1].args[0] - gs[0].args[0]
|
| 587 |
+
if m < 0:
|
| 588 |
+
P, Q = Q, P
|
| 589 |
+
m = abs(m)
|
| 590 |
+
return rsolve_hypergeometric(f, x, P, Q, k, m)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _solve_explike_DE(f, x, DE, g, k):
|
| 594 |
+
"""Solves DE with constant coefficients."""
|
| 595 |
+
from sympy.solvers import rsolve
|
| 596 |
+
|
| 597 |
+
for t in Add.make_args(DE):
|
| 598 |
+
coeff, d = t.as_independent(g)
|
| 599 |
+
if coeff.free_symbols:
|
| 600 |
+
return
|
| 601 |
+
|
| 602 |
+
RE = exp_re(DE, g, k)
|
| 603 |
+
|
| 604 |
+
init = {}
|
| 605 |
+
for i in range(len(Add.make_args(RE))):
|
| 606 |
+
if i:
|
| 607 |
+
f = f.diff(x)
|
| 608 |
+
init[g(k).subs(k, i)] = f.limit(x, 0)
|
| 609 |
+
|
| 610 |
+
sol = rsolve(RE, g(k), init)
|
| 611 |
+
|
| 612 |
+
if sol:
|
| 613 |
+
return (sol / factorial(k), S.Zero, S.Zero)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _solve_simple(f, x, DE, g, k):
|
| 617 |
+
"""Converts DE into RE and solves using :func:`rsolve`."""
|
| 618 |
+
from sympy.solvers import rsolve
|
| 619 |
+
|
| 620 |
+
RE = hyper_re(DE, g, k)
|
| 621 |
+
|
| 622 |
+
init = {}
|
| 623 |
+
for i in range(len(Add.make_args(RE))):
|
| 624 |
+
if i:
|
| 625 |
+
f = f.diff(x)
|
| 626 |
+
init[g(k).subs(k, i)] = f.limit(x, 0) / factorial(i)
|
| 627 |
+
|
| 628 |
+
sol = rsolve(RE, g(k), init)
|
| 629 |
+
|
| 630 |
+
if sol:
|
| 631 |
+
return (sol, S.Zero, S.Zero)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def _transform_explike_DE(DE, g, x, order, syms):
|
| 635 |
+
"""Converts DE with free parameters into DE with constant coefficients."""
|
| 636 |
+
from sympy.solvers.solveset import linsolve
|
| 637 |
+
|
| 638 |
+
eq = []
|
| 639 |
+
highest_coeff = DE.coeff(Derivative(g(x), x, order))
|
| 640 |
+
for i in range(order):
|
| 641 |
+
coeff = DE.coeff(Derivative(g(x), x, i))
|
| 642 |
+
coeff = (coeff / highest_coeff).expand().collect(x)
|
| 643 |
+
for t in Add.make_args(coeff):
|
| 644 |
+
eq.append(t)
|
| 645 |
+
temp = []
|
| 646 |
+
for e in eq:
|
| 647 |
+
if e.has(x):
|
| 648 |
+
break
|
| 649 |
+
elif e.has(Symbol):
|
| 650 |
+
temp.append(e)
|
| 651 |
+
else:
|
| 652 |
+
eq = temp
|
| 653 |
+
if eq:
|
| 654 |
+
sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
|
| 655 |
+
if sol:
|
| 656 |
+
DE = DE.subs(sol)
|
| 657 |
+
DE = DE.factor().as_coeff_mul(Derivative)[1][0]
|
| 658 |
+
DE = DE.collect(Derivative(g(x)))
|
| 659 |
+
return DE
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def _transform_DE_RE(DE, g, k, order, syms):
|
| 663 |
+
"""Converts DE with free parameters into RE of hypergeometric type."""
|
| 664 |
+
from sympy.solvers.solveset import linsolve
|
| 665 |
+
|
| 666 |
+
RE = hyper_re(DE, g, k)
|
| 667 |
+
|
| 668 |
+
eq = []
|
| 669 |
+
for i in range(1, order):
|
| 670 |
+
coeff = RE.coeff(g(k + i))
|
| 671 |
+
eq.append(coeff)
|
| 672 |
+
sol = dict(zip(syms, (i for s in linsolve(eq, list(syms)) for i in s)))
|
| 673 |
+
if sol:
|
| 674 |
+
m = Wild('m')
|
| 675 |
+
RE = RE.subs(sol)
|
| 676 |
+
RE = RE.factor().as_numer_denom()[0].collect(g(k + m))
|
| 677 |
+
RE = RE.as_coeff_mul(g)[1][0]
|
| 678 |
+
for i in range(order): # smallest order should be g(k)
|
| 679 |
+
if RE.coeff(g(k + i)) and i:
|
| 680 |
+
RE = RE.subs(k, k - i)
|
| 681 |
+
break
|
| 682 |
+
return RE
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def solve_de(f, x, DE, order, g, k):
|
| 686 |
+
"""
|
| 687 |
+
Solves the DE.
|
| 688 |
+
|
| 689 |
+
Explanation
|
| 690 |
+
===========
|
| 691 |
+
|
| 692 |
+
Tries to solve DE by either converting into a RE containing two terms or
|
| 693 |
+
converting into a DE having constant coefficients.
|
| 694 |
+
|
| 695 |
+
Returns
|
| 696 |
+
=======
|
| 697 |
+
|
| 698 |
+
formula : Expr
|
| 699 |
+
ind : Expr
|
| 700 |
+
Independent terms.
|
| 701 |
+
order : int
|
| 702 |
+
|
| 703 |
+
Examples
|
| 704 |
+
========
|
| 705 |
+
|
| 706 |
+
>>> from sympy import Derivative as D, Function
|
| 707 |
+
>>> from sympy import exp, ln
|
| 708 |
+
>>> from sympy.series.formal import solve_de
|
| 709 |
+
>>> from sympy.abc import x, k
|
| 710 |
+
>>> f = Function('f')
|
| 711 |
+
|
| 712 |
+
>>> solve_de(exp(x), x, D(f(x), x) - f(x), 1, f, k)
|
| 713 |
+
(Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
|
| 714 |
+
|
| 715 |
+
>>> solve_de(ln(1 + x), x, (x + 1)*D(f(x), x, 2) + D(f(x)), 2, f, k)
|
| 716 |
+
(Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
|
| 717 |
+
Eq(Mod(k, 1), 0)), (0, True)), x, 2)
|
| 718 |
+
"""
|
| 719 |
+
sol = None
|
| 720 |
+
syms = DE.free_symbols.difference({g, x})
|
| 721 |
+
|
| 722 |
+
if syms:
|
| 723 |
+
RE = _transform_DE_RE(DE, g, k, order, syms)
|
| 724 |
+
else:
|
| 725 |
+
RE = hyper_re(DE, g, k)
|
| 726 |
+
if not RE.free_symbols.difference({k}):
|
| 727 |
+
sol = _solve_hyper_RE(f, x, RE, g, k)
|
| 728 |
+
|
| 729 |
+
if sol:
|
| 730 |
+
return sol
|
| 731 |
+
|
| 732 |
+
if syms:
|
| 733 |
+
DE = _transform_explike_DE(DE, g, x, order, syms)
|
| 734 |
+
if not DE.free_symbols.difference({x}):
|
| 735 |
+
sol = _solve_explike_DE(f, x, DE, g, k)
|
| 736 |
+
|
| 737 |
+
if sol:
|
| 738 |
+
return sol
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def hyper_algorithm(f, x, k, order=4):
|
| 742 |
+
"""
|
| 743 |
+
Hypergeometric algorithm for computing Formal Power Series.
|
| 744 |
+
|
| 745 |
+
Explanation
|
| 746 |
+
===========
|
| 747 |
+
|
| 748 |
+
Steps:
|
| 749 |
+
* Generates DE
|
| 750 |
+
* Convert the DE into RE
|
| 751 |
+
* Solves the RE
|
| 752 |
+
|
| 753 |
+
Examples
|
| 754 |
+
========
|
| 755 |
+
|
| 756 |
+
>>> from sympy import exp, ln
|
| 757 |
+
>>> from sympy.series.formal import hyper_algorithm
|
| 758 |
+
|
| 759 |
+
>>> from sympy.abc import x, k
|
| 760 |
+
|
| 761 |
+
>>> hyper_algorithm(exp(x), x, k)
|
| 762 |
+
(Piecewise((1/factorial(k), Eq(Mod(k, 1), 0)), (0, True)), 1, 1)
|
| 763 |
+
|
| 764 |
+
>>> hyper_algorithm(ln(1 + x), x, k)
|
| 765 |
+
(Piecewise(((-1)**(k - 1)*factorial(k - 1)/RisingFactorial(2, k - 1),
|
| 766 |
+
Eq(Mod(k, 1), 0)), (0, True)), x, 2)
|
| 767 |
+
|
| 768 |
+
See Also
|
| 769 |
+
========
|
| 770 |
+
|
| 771 |
+
sympy.series.formal.simpleDE
|
| 772 |
+
sympy.series.formal.solve_de
|
| 773 |
+
"""
|
| 774 |
+
g = Function('g')
|
| 775 |
+
|
| 776 |
+
des = [] # list of DE's
|
| 777 |
+
sol = None
|
| 778 |
+
for DE, i in simpleDE(f, x, g, order):
|
| 779 |
+
if DE is not None:
|
| 780 |
+
sol = solve_de(f, x, DE, i, g, k)
|
| 781 |
+
if sol:
|
| 782 |
+
return sol
|
| 783 |
+
if not DE.free_symbols.difference({x}):
|
| 784 |
+
des.append(DE)
|
| 785 |
+
|
| 786 |
+
# If nothing works
|
| 787 |
+
# Try plain rsolve
|
| 788 |
+
for DE in des:
|
| 789 |
+
sol = _solve_simple(f, x, DE, g, k)
|
| 790 |
+
if sol:
|
| 791 |
+
return sol
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def _compute_fps(f, x, x0, dir, hyper, order, rational, full):
|
| 795 |
+
"""Recursive wrapper to compute fps.
|
| 796 |
+
|
| 797 |
+
See :func:`compute_fps` for details.
|
| 798 |
+
"""
|
| 799 |
+
if x0 in [S.Infinity, S.NegativeInfinity]:
|
| 800 |
+
dir = S.One if x0 is S.Infinity else -S.One
|
| 801 |
+
temp = f.subs(x, 1/x)
|
| 802 |
+
result = _compute_fps(temp, x, 0, dir, hyper, order, rational, full)
|
| 803 |
+
if result is None:
|
| 804 |
+
return None
|
| 805 |
+
return (result[0], result[1].subs(x, 1/x), result[2].subs(x, 1/x))
|
| 806 |
+
elif x0 or dir == -S.One:
|
| 807 |
+
if dir == -S.One:
|
| 808 |
+
rep = -x + x0
|
| 809 |
+
rep2 = -x
|
| 810 |
+
rep2b = x0
|
| 811 |
+
else:
|
| 812 |
+
rep = x + x0
|
| 813 |
+
rep2 = x
|
| 814 |
+
rep2b = -x0
|
| 815 |
+
temp = f.subs(x, rep)
|
| 816 |
+
result = _compute_fps(temp, x, 0, S.One, hyper, order, rational, full)
|
| 817 |
+
if result is None:
|
| 818 |
+
return None
|
| 819 |
+
return (result[0], result[1].subs(x, rep2 + rep2b),
|
| 820 |
+
result[2].subs(x, rep2 + rep2b))
|
| 821 |
+
|
| 822 |
+
if f.is_polynomial(x):
|
| 823 |
+
k = Dummy('k')
|
| 824 |
+
ak = sequence(Coeff(f, x, k), (k, 1, oo))
|
| 825 |
+
xk = sequence(x**k, (k, 0, oo))
|
| 826 |
+
ind = f.coeff(x, 0)
|
| 827 |
+
return ak, xk, ind
|
| 828 |
+
|
| 829 |
+
# Break instances of Add
|
| 830 |
+
# this allows application of different
|
| 831 |
+
# algorithms on different terms increasing the
|
| 832 |
+
# range of admissible functions.
|
| 833 |
+
if isinstance(f, Add):
|
| 834 |
+
result = False
|
| 835 |
+
ak = sequence(S.Zero, (0, oo))
|
| 836 |
+
ind, xk = S.Zero, None
|
| 837 |
+
for t in Add.make_args(f):
|
| 838 |
+
res = _compute_fps(t, x, 0, S.One, hyper, order, rational, full)
|
| 839 |
+
if res:
|
| 840 |
+
if not result:
|
| 841 |
+
result = True
|
| 842 |
+
xk = res[1]
|
| 843 |
+
if res[0].start > ak.start:
|
| 844 |
+
seq = ak
|
| 845 |
+
s, f = ak.start, res[0].start
|
| 846 |
+
else:
|
| 847 |
+
seq = res[0]
|
| 848 |
+
s, f = res[0].start, ak.start
|
| 849 |
+
save = Add(*[z[0]*z[1] for z in zip(seq[0:(f - s)], xk[s:f])])
|
| 850 |
+
ak += res[0]
|
| 851 |
+
ind += res[2] + save
|
| 852 |
+
else:
|
| 853 |
+
ind += t
|
| 854 |
+
if result:
|
| 855 |
+
return ak, xk, ind
|
| 856 |
+
return None
|
| 857 |
+
|
| 858 |
+
# The symbolic term - symb, if present, is being separated from the function
|
| 859 |
+
# Otherwise symb is being set to S.One
|
| 860 |
+
syms = f.free_symbols.difference({x})
|
| 861 |
+
(f, symb) = expand(f).as_independent(*syms)
|
| 862 |
+
|
| 863 |
+
result = None
|
| 864 |
+
|
| 865 |
+
# from here on it's x0=0 and dir=1 handling
|
| 866 |
+
k = Dummy('k')
|
| 867 |
+
if rational:
|
| 868 |
+
result = rational_algorithm(f, x, k, order, full)
|
| 869 |
+
|
| 870 |
+
if result is None and hyper:
|
| 871 |
+
result = hyper_algorithm(f, x, k, order)
|
| 872 |
+
|
| 873 |
+
if result is None:
|
| 874 |
+
return None
|
| 875 |
+
|
| 876 |
+
from sympy.simplify.powsimp import powsimp
|
| 877 |
+
if symb.is_zero:
|
| 878 |
+
symb = S.One
|
| 879 |
+
else:
|
| 880 |
+
symb = powsimp(symb)
|
| 881 |
+
ak = sequence(result[0], (k, result[2], oo))
|
| 882 |
+
xk_formula = powsimp(x**k * symb)
|
| 883 |
+
xk = sequence(xk_formula, (k, 0, oo))
|
| 884 |
+
ind = powsimp(result[1] * symb)
|
| 885 |
+
|
| 886 |
+
return ak, xk, ind
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def compute_fps(f, x, x0=0, dir=1, hyper=True, order=4, rational=True,
|
| 890 |
+
full=False):
|
| 891 |
+
"""
|
| 892 |
+
Computes the formula for Formal Power Series of a function.
|
| 893 |
+
|
| 894 |
+
Explanation
|
| 895 |
+
===========
|
| 896 |
+
|
| 897 |
+
Tries to compute the formula by applying the following techniques
|
| 898 |
+
(in order):
|
| 899 |
+
|
| 900 |
+
* rational_algorithm
|
| 901 |
+
* Hypergeometric algorithm
|
| 902 |
+
|
| 903 |
+
Parameters
|
| 904 |
+
==========
|
| 905 |
+
|
| 906 |
+
x : Symbol
|
| 907 |
+
x0 : number, optional
|
| 908 |
+
Point to perform series expansion about. Default is 0.
|
| 909 |
+
dir : {1, -1, '+', '-'}, optional
|
| 910 |
+
If dir is 1 or '+' the series is calculated from the right and
|
| 911 |
+
for -1 or '-' the series is calculated from the left. For smooth
|
| 912 |
+
functions this flag will not alter the results. Default is 1.
|
| 913 |
+
hyper : {True, False}, optional
|
| 914 |
+
Set hyper to False to skip the hypergeometric algorithm.
|
| 915 |
+
By default it is set to False.
|
| 916 |
+
order : int, optional
|
| 917 |
+
Order of the derivative of ``f``, Default is 4.
|
| 918 |
+
rational : {True, False}, optional
|
| 919 |
+
Set rational to False to skip rational algorithm. By default it is set
|
| 920 |
+
to True.
|
| 921 |
+
full : {True, False}, optional
|
| 922 |
+
Set full to True to increase the range of rational algorithm.
|
| 923 |
+
See :func:`rational_algorithm` for details. By default it is set to
|
| 924 |
+
False.
|
| 925 |
+
|
| 926 |
+
Returns
|
| 927 |
+
=======
|
| 928 |
+
|
| 929 |
+
ak : sequence
|
| 930 |
+
Sequence of coefficients.
|
| 931 |
+
xk : sequence
|
| 932 |
+
Sequence of powers of x.
|
| 933 |
+
ind : Expr
|
| 934 |
+
Independent terms.
|
| 935 |
+
mul : Pow
|
| 936 |
+
Common terms.
|
| 937 |
+
|
| 938 |
+
See Also
|
| 939 |
+
========
|
| 940 |
+
|
| 941 |
+
sympy.series.formal.rational_algorithm
|
| 942 |
+
sympy.series.formal.hyper_algorithm
|
| 943 |
+
"""
|
| 944 |
+
f = sympify(f)
|
| 945 |
+
x = sympify(x)
|
| 946 |
+
|
| 947 |
+
if not f.has(x):
|
| 948 |
+
return None
|
| 949 |
+
|
| 950 |
+
x0 = sympify(x0)
|
| 951 |
+
|
| 952 |
+
if dir == '+':
|
| 953 |
+
dir = S.One
|
| 954 |
+
elif dir == '-':
|
| 955 |
+
dir = -S.One
|
| 956 |
+
elif dir not in [S.One, -S.One]:
|
| 957 |
+
raise ValueError("Dir must be '+' or '-'")
|
| 958 |
+
else:
|
| 959 |
+
dir = sympify(dir)
|
| 960 |
+
|
| 961 |
+
return _compute_fps(f, x, x0, dir, hyper, order, rational, full)
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
class Coeff(Function):
|
| 965 |
+
"""
|
| 966 |
+
Coeff(p, x, n) represents the nth coefficient of the polynomial p in x
|
| 967 |
+
"""
|
| 968 |
+
@classmethod
|
| 969 |
+
def eval(cls, p, x, n):
|
| 970 |
+
if p.is_polynomial(x) and n.is_integer:
|
| 971 |
+
return p.coeff(x, n)
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
class FormalPowerSeries(SeriesBase):
|
| 975 |
+
"""
|
| 976 |
+
Represents Formal Power Series of a function.
|
| 977 |
+
|
| 978 |
+
Explanation
|
| 979 |
+
===========
|
| 980 |
+
|
| 981 |
+
No computation is performed. This class should only to be used to represent
|
| 982 |
+
a series. No checks are performed.
|
| 983 |
+
|
| 984 |
+
For computing a series use :func:`fps`.
|
| 985 |
+
|
| 986 |
+
See Also
|
| 987 |
+
========
|
| 988 |
+
|
| 989 |
+
sympy.series.formal.fps
|
| 990 |
+
"""
|
| 991 |
+
def __new__(cls, *args):
|
| 992 |
+
args = map(sympify, args)
|
| 993 |
+
return Expr.__new__(cls, *args)
|
| 994 |
+
|
| 995 |
+
def __init__(self, *args):
|
| 996 |
+
ak = args[4][0]
|
| 997 |
+
k = ak.variables[0]
|
| 998 |
+
self.ak_seq = sequence(ak.formula, (k, 1, oo))
|
| 999 |
+
self.fact_seq = sequence(factorial(k), (k, 1, oo))
|
| 1000 |
+
self.bell_coeff_seq = self.ak_seq * self.fact_seq
|
| 1001 |
+
self.sign_seq = sequence((-1, 1), (k, 1, oo))
|
| 1002 |
+
|
| 1003 |
+
@property
|
| 1004 |
+
def function(self):
|
| 1005 |
+
return self.args[0]
|
| 1006 |
+
|
| 1007 |
+
@property
|
| 1008 |
+
def x(self):
|
| 1009 |
+
return self.args[1]
|
| 1010 |
+
|
| 1011 |
+
@property
|
| 1012 |
+
def x0(self):
|
| 1013 |
+
return self.args[2]
|
| 1014 |
+
|
| 1015 |
+
@property
|
| 1016 |
+
def dir(self):
|
| 1017 |
+
return self.args[3]
|
| 1018 |
+
|
| 1019 |
+
@property
|
| 1020 |
+
def ak(self):
|
| 1021 |
+
return self.args[4][0]
|
| 1022 |
+
|
| 1023 |
+
@property
|
| 1024 |
+
def xk(self):
|
| 1025 |
+
return self.args[4][1]
|
| 1026 |
+
|
| 1027 |
+
@property
|
| 1028 |
+
def ind(self):
|
| 1029 |
+
return self.args[4][2]
|
| 1030 |
+
|
| 1031 |
+
@property
|
| 1032 |
+
def interval(self):
|
| 1033 |
+
return Interval(0, oo)
|
| 1034 |
+
|
| 1035 |
+
@property
|
| 1036 |
+
def start(self):
|
| 1037 |
+
return self.interval.inf
|
| 1038 |
+
|
| 1039 |
+
@property
|
| 1040 |
+
def stop(self):
|
| 1041 |
+
return self.interval.sup
|
| 1042 |
+
|
| 1043 |
+
@property
|
| 1044 |
+
def length(self):
|
| 1045 |
+
return oo
|
| 1046 |
+
|
| 1047 |
+
@property
|
| 1048 |
+
def infinite(self):
|
| 1049 |
+
"""Returns an infinite representation of the series"""
|
| 1050 |
+
from sympy.concrete import Sum
|
| 1051 |
+
ak, xk = self.ak, self.xk
|
| 1052 |
+
k = ak.variables[0]
|
| 1053 |
+
inf_sum = Sum(ak.formula * xk.formula, (k, ak.start, ak.stop))
|
| 1054 |
+
|
| 1055 |
+
return self.ind + inf_sum
|
| 1056 |
+
|
| 1057 |
+
def _get_pow_x(self, term):
|
| 1058 |
+
"""Returns the power of x in a term."""
|
| 1059 |
+
xterm, pow_x = term.as_independent(self.x)[1].as_base_exp()
|
| 1060 |
+
if not xterm.has(self.x):
|
| 1061 |
+
return S.Zero
|
| 1062 |
+
return pow_x
|
| 1063 |
+
|
| 1064 |
+
def polynomial(self, n=6):
|
| 1065 |
+
"""
|
| 1066 |
+
Truncated series as polynomial.
|
| 1067 |
+
|
| 1068 |
+
Explanation
|
| 1069 |
+
===========
|
| 1070 |
+
|
| 1071 |
+
Returns series expansion of ``f`` upto order ``O(x**n)``
|
| 1072 |
+
as a polynomial(without ``O`` term).
|
| 1073 |
+
"""
|
| 1074 |
+
terms = []
|
| 1075 |
+
sym = self.free_symbols
|
| 1076 |
+
for i, t in enumerate(self):
|
| 1077 |
+
xp = self._get_pow_x(t)
|
| 1078 |
+
if xp.has(*sym):
|
| 1079 |
+
xp = xp.as_coeff_add(*sym)[0]
|
| 1080 |
+
if xp >= n:
|
| 1081 |
+
break
|
| 1082 |
+
elif xp.is_integer is True and i == n + 1:
|
| 1083 |
+
break
|
| 1084 |
+
elif t is not S.Zero:
|
| 1085 |
+
terms.append(t)
|
| 1086 |
+
|
| 1087 |
+
return Add(*terms)
|
| 1088 |
+
|
| 1089 |
+
def truncate(self, n=6):
|
| 1090 |
+
"""
|
| 1091 |
+
Truncated series.
|
| 1092 |
+
|
| 1093 |
+
Explanation
|
| 1094 |
+
===========
|
| 1095 |
+
|
| 1096 |
+
Returns truncated series expansion of f upto
|
| 1097 |
+
order ``O(x**n)``.
|
| 1098 |
+
|
| 1099 |
+
If n is ``None``, returns an infinite iterator.
|
| 1100 |
+
"""
|
| 1101 |
+
if n is None:
|
| 1102 |
+
return iter(self)
|
| 1103 |
+
|
| 1104 |
+
x, x0 = self.x, self.x0
|
| 1105 |
+
pt_xk = self.xk.coeff(n)
|
| 1106 |
+
if x0 is S.NegativeInfinity:
|
| 1107 |
+
x0 = S.Infinity
|
| 1108 |
+
|
| 1109 |
+
return self.polynomial(n) + Order(pt_xk, (x, x0))
|
| 1110 |
+
|
| 1111 |
+
def zero_coeff(self):
|
| 1112 |
+
return self._eval_term(0)
|
| 1113 |
+
|
| 1114 |
+
def _eval_term(self, pt):
|
| 1115 |
+
try:
|
| 1116 |
+
pt_xk = self.xk.coeff(pt)
|
| 1117 |
+
pt_ak = self.ak.coeff(pt).simplify() # Simplify the coefficients
|
| 1118 |
+
except IndexError:
|
| 1119 |
+
term = S.Zero
|
| 1120 |
+
else:
|
| 1121 |
+
term = (pt_ak * pt_xk)
|
| 1122 |
+
|
| 1123 |
+
if self.ind:
|
| 1124 |
+
ind = S.Zero
|
| 1125 |
+
sym = self.free_symbols
|
| 1126 |
+
for t in Add.make_args(self.ind):
|
| 1127 |
+
pow_x = self._get_pow_x(t)
|
| 1128 |
+
if pow_x.has(*sym):
|
| 1129 |
+
pow_x = pow_x.as_coeff_add(*sym)[0]
|
| 1130 |
+
if pt == 0 and pow_x < 1:
|
| 1131 |
+
ind += t
|
| 1132 |
+
elif pow_x >= pt and pow_x < pt + 1:
|
| 1133 |
+
ind += t
|
| 1134 |
+
term += ind
|
| 1135 |
+
|
| 1136 |
+
return term.collect(self.x)
|
| 1137 |
+
|
| 1138 |
+
def _eval_subs(self, old, new):
|
| 1139 |
+
x = self.x
|
| 1140 |
+
if old.has(x):
|
| 1141 |
+
return self
|
| 1142 |
+
|
| 1143 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 1144 |
+
for t in self:
|
| 1145 |
+
if t is not S.Zero:
|
| 1146 |
+
return t
|
| 1147 |
+
|
| 1148 |
+
def _eval_derivative(self, x):
|
| 1149 |
+
f = self.function.diff(x)
|
| 1150 |
+
ind = self.ind.diff(x)
|
| 1151 |
+
|
| 1152 |
+
pow_xk = self._get_pow_x(self.xk.formula)
|
| 1153 |
+
ak = self.ak
|
| 1154 |
+
k = ak.variables[0]
|
| 1155 |
+
if ak.formula.has(x):
|
| 1156 |
+
form = []
|
| 1157 |
+
for e, c in ak.formula.args:
|
| 1158 |
+
temp = S.Zero
|
| 1159 |
+
for t in Add.make_args(e):
|
| 1160 |
+
pow_x = self._get_pow_x(t)
|
| 1161 |
+
temp += t * (pow_xk + pow_x)
|
| 1162 |
+
form.append((temp, c))
|
| 1163 |
+
form = Piecewise(*form)
|
| 1164 |
+
ak = sequence(form.subs(k, k + 1), (k, ak.start - 1, ak.stop))
|
| 1165 |
+
else:
|
| 1166 |
+
ak = sequence((ak.formula * pow_xk).subs(k, k + 1),
|
| 1167 |
+
(k, ak.start - 1, ak.stop))
|
| 1168 |
+
|
| 1169 |
+
return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
|
| 1170 |
+
|
| 1171 |
+
def integrate(self, x=None, **kwargs):
|
| 1172 |
+
"""
|
| 1173 |
+
Integrate Formal Power Series.
|
| 1174 |
+
|
| 1175 |
+
Examples
|
| 1176 |
+
========
|
| 1177 |
+
|
| 1178 |
+
>>> from sympy import fps, sin, integrate
|
| 1179 |
+
>>> from sympy.abc import x
|
| 1180 |
+
>>> f = fps(sin(x))
|
| 1181 |
+
>>> f.integrate(x).truncate()
|
| 1182 |
+
-1 + x**2/2 - x**4/24 + O(x**6)
|
| 1183 |
+
>>> integrate(f, (x, 0, 1))
|
| 1184 |
+
1 - cos(1)
|
| 1185 |
+
"""
|
| 1186 |
+
from sympy.integrals import integrate
|
| 1187 |
+
|
| 1188 |
+
if x is None:
|
| 1189 |
+
x = self.x
|
| 1190 |
+
elif iterable(x):
|
| 1191 |
+
return integrate(self.function, x)
|
| 1192 |
+
|
| 1193 |
+
f = integrate(self.function, x)
|
| 1194 |
+
ind = integrate(self.ind, x)
|
| 1195 |
+
ind += (f - ind).limit(x, 0) # constant of integration
|
| 1196 |
+
|
| 1197 |
+
pow_xk = self._get_pow_x(self.xk.formula)
|
| 1198 |
+
ak = self.ak
|
| 1199 |
+
k = ak.variables[0]
|
| 1200 |
+
if ak.formula.has(x):
|
| 1201 |
+
form = []
|
| 1202 |
+
for e, c in ak.formula.args:
|
| 1203 |
+
temp = S.Zero
|
| 1204 |
+
for t in Add.make_args(e):
|
| 1205 |
+
pow_x = self._get_pow_x(t)
|
| 1206 |
+
temp += t / (pow_xk + pow_x + 1)
|
| 1207 |
+
form.append((temp, c))
|
| 1208 |
+
form = Piecewise(*form)
|
| 1209 |
+
ak = sequence(form.subs(k, k - 1), (k, ak.start + 1, ak.stop))
|
| 1210 |
+
else:
|
| 1211 |
+
ak = sequence((ak.formula / (pow_xk + 1)).subs(k, k - 1),
|
| 1212 |
+
(k, ak.start + 1, ak.stop))
|
| 1213 |
+
|
| 1214 |
+
return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
|
| 1215 |
+
|
| 1216 |
+
def product(self, other, x=None, n=6):
|
| 1217 |
+
"""
|
| 1218 |
+
Multiplies two Formal Power Series, using discrete convolution and
|
| 1219 |
+
return the truncated terms upto specified order.
|
| 1220 |
+
|
| 1221 |
+
Parameters
|
| 1222 |
+
==========
|
| 1223 |
+
|
| 1224 |
+
n : Number, optional
|
| 1225 |
+
Specifies the order of the term up to which the polynomial should
|
| 1226 |
+
be truncated.
|
| 1227 |
+
|
| 1228 |
+
Examples
|
| 1229 |
+
========
|
| 1230 |
+
|
| 1231 |
+
>>> from sympy import fps, sin, exp
|
| 1232 |
+
>>> from sympy.abc import x
|
| 1233 |
+
>>> f1 = fps(sin(x))
|
| 1234 |
+
>>> f2 = fps(exp(x))
|
| 1235 |
+
|
| 1236 |
+
>>> f1.product(f2, x).truncate(4)
|
| 1237 |
+
x + x**2 + x**3/3 + O(x**4)
|
| 1238 |
+
|
| 1239 |
+
See Also
|
| 1240 |
+
========
|
| 1241 |
+
|
| 1242 |
+
sympy.discrete.convolutions
|
| 1243 |
+
sympy.series.formal.FormalPowerSeriesProduct
|
| 1244 |
+
|
| 1245 |
+
"""
|
| 1246 |
+
|
| 1247 |
+
if n is None:
|
| 1248 |
+
return iter(self)
|
| 1249 |
+
|
| 1250 |
+
other = sympify(other)
|
| 1251 |
+
|
| 1252 |
+
if not isinstance(other, FormalPowerSeries):
|
| 1253 |
+
raise ValueError("Both series should be an instance of FormalPowerSeries"
|
| 1254 |
+
" class.")
|
| 1255 |
+
|
| 1256 |
+
if self.dir != other.dir:
|
| 1257 |
+
raise ValueError("Both series should be calculated from the"
|
| 1258 |
+
" same direction.")
|
| 1259 |
+
elif self.x0 != other.x0:
|
| 1260 |
+
raise ValueError("Both series should be calculated about the"
|
| 1261 |
+
" same point.")
|
| 1262 |
+
|
| 1263 |
+
elif self.x != other.x:
|
| 1264 |
+
raise ValueError("Both series should have the same symbol.")
|
| 1265 |
+
|
| 1266 |
+
return FormalPowerSeriesProduct(self, other)
|
| 1267 |
+
|
| 1268 |
+
def coeff_bell(self, n):
|
| 1269 |
+
r"""
|
| 1270 |
+
self.coeff_bell(n) returns a sequence of Bell polynomials of the second kind.
|
| 1271 |
+
Note that ``n`` should be a integer.
|
| 1272 |
+
|
| 1273 |
+
The second kind of Bell polynomials (are sometimes called "partial" Bell
|
| 1274 |
+
polynomials or incomplete Bell polynomials) are defined as
|
| 1275 |
+
|
| 1276 |
+
.. math::
|
| 1277 |
+
B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
|
| 1278 |
+
\sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
|
| 1279 |
+
\frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
|
| 1280 |
+
\left(\frac{x_1}{1!} \right)^{j_1}
|
| 1281 |
+
\left(\frac{x_2}{2!} \right)^{j_2} \dotsb
|
| 1282 |
+
\left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.
|
| 1283 |
+
|
| 1284 |
+
* ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
|
| 1285 |
+
`B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.
|
| 1286 |
+
|
| 1287 |
+
See Also
|
| 1288 |
+
========
|
| 1289 |
+
|
| 1290 |
+
sympy.functions.combinatorial.numbers.bell
|
| 1291 |
+
|
| 1292 |
+
"""
|
| 1293 |
+
|
| 1294 |
+
inner_coeffs = [bell(n, j, tuple(self.bell_coeff_seq[:n-j+1])) for j in range(1, n+1)]
|
| 1295 |
+
|
| 1296 |
+
k = Dummy('k')
|
| 1297 |
+
return sequence(tuple(inner_coeffs), (k, 1, oo))
|
| 1298 |
+
|
| 1299 |
+
def compose(self, other, x=None, n=6):
|
| 1300 |
+
r"""
|
| 1301 |
+
Returns the truncated terms of the formal power series of the composed function,
|
| 1302 |
+
up to specified ``n``.
|
| 1303 |
+
|
| 1304 |
+
Explanation
|
| 1305 |
+
===========
|
| 1306 |
+
|
| 1307 |
+
If ``f`` and ``g`` are two formal power series of two different functions,
|
| 1308 |
+
then the coefficient sequence ``ak`` of the composed formal power series `fp`
|
| 1309 |
+
will be as follows.
|
| 1310 |
+
|
| 1311 |
+
.. math::
|
| 1312 |
+
\sum\limits_{k=0}^{n} b_k B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})
|
| 1313 |
+
|
| 1314 |
+
Parameters
|
| 1315 |
+
==========
|
| 1316 |
+
|
| 1317 |
+
n : Number, optional
|
| 1318 |
+
Specifies the order of the term up to which the polynomial should
|
| 1319 |
+
be truncated.
|
| 1320 |
+
|
| 1321 |
+
Examples
|
| 1322 |
+
========
|
| 1323 |
+
|
| 1324 |
+
>>> from sympy import fps, sin, exp
|
| 1325 |
+
>>> from sympy.abc import x
|
| 1326 |
+
>>> f1 = fps(exp(x))
|
| 1327 |
+
>>> f2 = fps(sin(x))
|
| 1328 |
+
|
| 1329 |
+
>>> f1.compose(f2, x).truncate()
|
| 1330 |
+
1 + x + x**2/2 - x**4/8 - x**5/15 + O(x**6)
|
| 1331 |
+
|
| 1332 |
+
>>> f1.compose(f2, x).truncate(8)
|
| 1333 |
+
1 + x + x**2/2 - x**4/8 - x**5/15 - x**6/240 + x**7/90 + O(x**8)
|
| 1334 |
+
|
| 1335 |
+
See Also
|
| 1336 |
+
========
|
| 1337 |
+
|
| 1338 |
+
sympy.functions.combinatorial.numbers.bell
|
| 1339 |
+
sympy.series.formal.FormalPowerSeriesCompose
|
| 1340 |
+
|
| 1341 |
+
References
|
| 1342 |
+
==========
|
| 1343 |
+
|
| 1344 |
+
.. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974.
|
| 1345 |
+
|
| 1346 |
+
"""
|
| 1347 |
+
|
| 1348 |
+
if n is None:
|
| 1349 |
+
return iter(self)
|
| 1350 |
+
|
| 1351 |
+
other = sympify(other)
|
| 1352 |
+
|
| 1353 |
+
if not isinstance(other, FormalPowerSeries):
|
| 1354 |
+
raise ValueError("Both series should be an instance of FormalPowerSeries"
|
| 1355 |
+
" class.")
|
| 1356 |
+
|
| 1357 |
+
if self.dir != other.dir:
|
| 1358 |
+
raise ValueError("Both series should be calculated from the"
|
| 1359 |
+
" same direction.")
|
| 1360 |
+
elif self.x0 != other.x0:
|
| 1361 |
+
raise ValueError("Both series should be calculated about the"
|
| 1362 |
+
" same point.")
|
| 1363 |
+
|
| 1364 |
+
elif self.x != other.x:
|
| 1365 |
+
raise ValueError("Both series should have the same symbol.")
|
| 1366 |
+
|
| 1367 |
+
if other._eval_term(0).as_coeff_mul(other.x)[0] is not S.Zero:
|
| 1368 |
+
raise ValueError("The formal power series of the inner function should not have any "
|
| 1369 |
+
"constant coefficient term.")
|
| 1370 |
+
|
| 1371 |
+
return FormalPowerSeriesCompose(self, other)
|
| 1372 |
+
|
| 1373 |
+
def inverse(self, x=None, n=6):
|
| 1374 |
+
r"""
|
| 1375 |
+
Returns the truncated terms of the inverse of the formal power series,
|
| 1376 |
+
up to specified ``n``.
|
| 1377 |
+
|
| 1378 |
+
Explanation
|
| 1379 |
+
===========
|
| 1380 |
+
|
| 1381 |
+
If ``f`` and ``g`` are two formal power series of two different functions,
|
| 1382 |
+
then the coefficient sequence ``ak`` of the composed formal power series ``fp``
|
| 1383 |
+
will be as follows.
|
| 1384 |
+
|
| 1385 |
+
.. math::
|
| 1386 |
+
\sum\limits_{k=0}^{n} (-1)^{k} x_0^{-k-1} B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})
|
| 1387 |
+
|
| 1388 |
+
Parameters
|
| 1389 |
+
==========
|
| 1390 |
+
|
| 1391 |
+
n : Number, optional
|
| 1392 |
+
Specifies the order of the term up to which the polynomial should
|
| 1393 |
+
be truncated.
|
| 1394 |
+
|
| 1395 |
+
Examples
|
| 1396 |
+
========
|
| 1397 |
+
|
| 1398 |
+
>>> from sympy import fps, exp, cos
|
| 1399 |
+
>>> from sympy.abc import x
|
| 1400 |
+
>>> f1 = fps(exp(x))
|
| 1401 |
+
>>> f2 = fps(cos(x))
|
| 1402 |
+
|
| 1403 |
+
>>> f1.inverse(x).truncate()
|
| 1404 |
+
1 - x + x**2/2 - x**3/6 + x**4/24 - x**5/120 + O(x**6)
|
| 1405 |
+
|
| 1406 |
+
>>> f2.inverse(x).truncate(8)
|
| 1407 |
+
1 + x**2/2 + 5*x**4/24 + 61*x**6/720 + O(x**8)
|
| 1408 |
+
|
| 1409 |
+
See Also
|
| 1410 |
+
========
|
| 1411 |
+
|
| 1412 |
+
sympy.functions.combinatorial.numbers.bell
|
| 1413 |
+
sympy.series.formal.FormalPowerSeriesInverse
|
| 1414 |
+
|
| 1415 |
+
References
|
| 1416 |
+
==========
|
| 1417 |
+
|
| 1418 |
+
.. [1] Comtet, Louis: Advanced combinatorics; the art of finite and infinite expansions. Reidel, 1974.
|
| 1419 |
+
|
| 1420 |
+
"""
|
| 1421 |
+
|
| 1422 |
+
if n is None:
|
| 1423 |
+
return iter(self)
|
| 1424 |
+
|
| 1425 |
+
if self._eval_term(0).is_zero:
|
| 1426 |
+
raise ValueError("Constant coefficient should exist for an inverse of a formal"
|
| 1427 |
+
" power series to exist.")
|
| 1428 |
+
|
| 1429 |
+
return FormalPowerSeriesInverse(self)
|
| 1430 |
+
|
| 1431 |
+
def __add__(self, other):
|
| 1432 |
+
other = sympify(other)
|
| 1433 |
+
|
| 1434 |
+
if isinstance(other, FormalPowerSeries):
|
| 1435 |
+
if self.dir != other.dir:
|
| 1436 |
+
raise ValueError("Both series should be calculated from the"
|
| 1437 |
+
" same direction.")
|
| 1438 |
+
elif self.x0 != other.x0:
|
| 1439 |
+
raise ValueError("Both series should be calculated about the"
|
| 1440 |
+
" same point.")
|
| 1441 |
+
|
| 1442 |
+
x, y = self.x, other.x
|
| 1443 |
+
f = self.function + other.function.subs(y, x)
|
| 1444 |
+
|
| 1445 |
+
if self.x not in f.free_symbols:
|
| 1446 |
+
return f
|
| 1447 |
+
|
| 1448 |
+
ak = self.ak + other.ak
|
| 1449 |
+
if self.ak.start > other.ak.start:
|
| 1450 |
+
seq = other.ak
|
| 1451 |
+
s, e = other.ak.start, self.ak.start
|
| 1452 |
+
else:
|
| 1453 |
+
seq = self.ak
|
| 1454 |
+
s, e = self.ak.start, other.ak.start
|
| 1455 |
+
save = Add(*[z[0]*z[1] for z in zip(seq[0:(e - s)], self.xk[s:e])])
|
| 1456 |
+
ind = self.ind + other.ind + save
|
| 1457 |
+
|
| 1458 |
+
return self.func(f, x, self.x0, self.dir, (ak, self.xk, ind))
|
| 1459 |
+
|
| 1460 |
+
elif not other.has(self.x):
|
| 1461 |
+
f = self.function + other
|
| 1462 |
+
ind = self.ind + other
|
| 1463 |
+
|
| 1464 |
+
return self.func(f, self.x, self.x0, self.dir,
|
| 1465 |
+
(self.ak, self.xk, ind))
|
| 1466 |
+
|
| 1467 |
+
return Add(self, other)
|
| 1468 |
+
|
| 1469 |
+
def __radd__(self, other):
|
| 1470 |
+
return self.__add__(other)
|
| 1471 |
+
|
| 1472 |
+
def __neg__(self):
|
| 1473 |
+
return self.func(-self.function, self.x, self.x0, self.dir,
|
| 1474 |
+
(-self.ak, self.xk, -self.ind))
|
| 1475 |
+
|
| 1476 |
+
def __sub__(self, other):
|
| 1477 |
+
return self.__add__(-other)
|
| 1478 |
+
|
| 1479 |
+
def __rsub__(self, other):
|
| 1480 |
+
return (-self).__add__(other)
|
| 1481 |
+
|
| 1482 |
+
def __mul__(self, other):
|
| 1483 |
+
other = sympify(other)
|
| 1484 |
+
|
| 1485 |
+
if other.has(self.x):
|
| 1486 |
+
return Mul(self, other)
|
| 1487 |
+
|
| 1488 |
+
f = self.function * other
|
| 1489 |
+
ak = self.ak.coeff_mul(other)
|
| 1490 |
+
ind = self.ind * other
|
| 1491 |
+
|
| 1492 |
+
return self.func(f, self.x, self.x0, self.dir, (ak, self.xk, ind))
|
| 1493 |
+
|
| 1494 |
+
def __rmul__(self, other):
|
| 1495 |
+
return self.__mul__(other)
|
| 1496 |
+
|
| 1497 |
+
|
| 1498 |
+
class FiniteFormalPowerSeries(FormalPowerSeries):
|
| 1499 |
+
"""Base Class for Product, Compose and Inverse classes"""
|
| 1500 |
+
|
| 1501 |
+
def __init__(self, *args):
|
| 1502 |
+
pass
|
| 1503 |
+
|
| 1504 |
+
@property
|
| 1505 |
+
def ffps(self):
|
| 1506 |
+
return self.args[0]
|
| 1507 |
+
|
| 1508 |
+
@property
|
| 1509 |
+
def gfps(self):
|
| 1510 |
+
return self.args[1]
|
| 1511 |
+
|
| 1512 |
+
@property
|
| 1513 |
+
def f(self):
|
| 1514 |
+
return self.ffps.function
|
| 1515 |
+
|
| 1516 |
+
@property
|
| 1517 |
+
def g(self):
|
| 1518 |
+
return self.gfps.function
|
| 1519 |
+
|
| 1520 |
+
@property
|
| 1521 |
+
def infinite(self):
|
| 1522 |
+
raise NotImplementedError("No infinite version for an object of"
|
| 1523 |
+
" FiniteFormalPowerSeries class.")
|
| 1524 |
+
|
| 1525 |
+
def _eval_terms(self, n):
|
| 1526 |
+
raise NotImplementedError("(%s)._eval_terms()" % self)
|
| 1527 |
+
|
| 1528 |
+
def _eval_term(self, pt):
|
| 1529 |
+
raise NotImplementedError("By the current logic, one can get terms"
|
| 1530 |
+
"upto a certain order, instead of getting term by term.")
|
| 1531 |
+
|
| 1532 |
+
def polynomial(self, n):
|
| 1533 |
+
return self._eval_terms(n)
|
| 1534 |
+
|
| 1535 |
+
def truncate(self, n=6):
|
| 1536 |
+
ffps = self.ffps
|
| 1537 |
+
pt_xk = ffps.xk.coeff(n)
|
| 1538 |
+
x, x0 = ffps.x, ffps.x0
|
| 1539 |
+
|
| 1540 |
+
return self.polynomial(n) + Order(pt_xk, (x, x0))
|
| 1541 |
+
|
| 1542 |
+
def _eval_derivative(self, x):
|
| 1543 |
+
raise NotImplementedError
|
| 1544 |
+
|
| 1545 |
+
def integrate(self, x):
|
| 1546 |
+
raise NotImplementedError
|
| 1547 |
+
|
| 1548 |
+
|
| 1549 |
+
class FormalPowerSeriesProduct(FiniteFormalPowerSeries):
|
| 1550 |
+
"""Represents the product of two formal power series of two functions.
|
| 1551 |
+
|
| 1552 |
+
Explanation
|
| 1553 |
+
===========
|
| 1554 |
+
|
| 1555 |
+
No computation is performed. Terms are calculated using a term by term logic,
|
| 1556 |
+
instead of a point by point logic.
|
| 1557 |
+
|
| 1558 |
+
There are two differences between a :obj:`FormalPowerSeries` object and a
|
| 1559 |
+
:obj:`FormalPowerSeriesProduct` object. The first argument contains the two
|
| 1560 |
+
functions involved in the product. Also, the coefficient sequence contains
|
| 1561 |
+
both the coefficient sequence of the formal power series of the involved functions.
|
| 1562 |
+
|
| 1563 |
+
See Also
|
| 1564 |
+
========
|
| 1565 |
+
|
| 1566 |
+
sympy.series.formal.FormalPowerSeries
|
| 1567 |
+
sympy.series.formal.FiniteFormalPowerSeries
|
| 1568 |
+
|
| 1569 |
+
"""
|
| 1570 |
+
|
| 1571 |
+
def __init__(self, *args):
|
| 1572 |
+
ffps, gfps = self.ffps, self.gfps
|
| 1573 |
+
|
| 1574 |
+
k = ffps.ak.variables[0]
|
| 1575 |
+
self.coeff1 = sequence(ffps.ak.formula, (k, 0, oo))
|
| 1576 |
+
|
| 1577 |
+
k = gfps.ak.variables[0]
|
| 1578 |
+
self.coeff2 = sequence(gfps.ak.formula, (k, 0, oo))
|
| 1579 |
+
|
| 1580 |
+
@property
|
| 1581 |
+
def function(self):
|
| 1582 |
+
"""Function of the product of two formal power series."""
|
| 1583 |
+
return self.f * self.g
|
| 1584 |
+
|
| 1585 |
+
def _eval_terms(self, n):
|
| 1586 |
+
"""
|
| 1587 |
+
Returns the first ``n`` terms of the product formal power series.
|
| 1588 |
+
Term by term logic is implemented here.
|
| 1589 |
+
|
| 1590 |
+
Examples
|
| 1591 |
+
========
|
| 1592 |
+
|
| 1593 |
+
>>> from sympy import fps, sin, exp
|
| 1594 |
+
>>> from sympy.abc import x
|
| 1595 |
+
>>> f1 = fps(sin(x))
|
| 1596 |
+
>>> f2 = fps(exp(x))
|
| 1597 |
+
>>> fprod = f1.product(f2, x)
|
| 1598 |
+
|
| 1599 |
+
>>> fprod._eval_terms(4)
|
| 1600 |
+
x**3/3 + x**2 + x
|
| 1601 |
+
|
| 1602 |
+
See Also
|
| 1603 |
+
========
|
| 1604 |
+
|
| 1605 |
+
sympy.series.formal.FormalPowerSeries.product
|
| 1606 |
+
|
| 1607 |
+
"""
|
| 1608 |
+
coeff1, coeff2 = self.coeff1, self.coeff2
|
| 1609 |
+
|
| 1610 |
+
aks = convolution(coeff1[:n], coeff2[:n])
|
| 1611 |
+
|
| 1612 |
+
terms = []
|
| 1613 |
+
for i in range(0, n):
|
| 1614 |
+
terms.append(aks[i] * self.ffps.xk.coeff(i))
|
| 1615 |
+
|
| 1616 |
+
return Add(*terms)
|
| 1617 |
+
|
| 1618 |
+
|
| 1619 |
+
class FormalPowerSeriesCompose(FiniteFormalPowerSeries):
|
| 1620 |
+
"""
|
| 1621 |
+
Represents the composed formal power series of two functions.
|
| 1622 |
+
|
| 1623 |
+
Explanation
|
| 1624 |
+
===========
|
| 1625 |
+
|
| 1626 |
+
No computation is performed. Terms are calculated using a term by term logic,
|
| 1627 |
+
instead of a point by point logic.
|
| 1628 |
+
|
| 1629 |
+
There are two differences between a :obj:`FormalPowerSeries` object and a
|
| 1630 |
+
:obj:`FormalPowerSeriesCompose` object. The first argument contains the outer
|
| 1631 |
+
function and the inner function involved in the omposition. Also, the
|
| 1632 |
+
coefficient sequence contains the generic sequence which is to be multiplied
|
| 1633 |
+
by a custom ``bell_seq`` finite sequence. The finite terms will then be added up to
|
| 1634 |
+
get the final terms.
|
| 1635 |
+
|
| 1636 |
+
See Also
|
| 1637 |
+
========
|
| 1638 |
+
|
| 1639 |
+
sympy.series.formal.FormalPowerSeries
|
| 1640 |
+
sympy.series.formal.FiniteFormalPowerSeries
|
| 1641 |
+
|
| 1642 |
+
"""
|
| 1643 |
+
|
| 1644 |
+
@property
|
| 1645 |
+
def function(self):
|
| 1646 |
+
"""Function for the composed formal power series."""
|
| 1647 |
+
f, g, x = self.f, self.g, self.ffps.x
|
| 1648 |
+
return f.subs(x, g)
|
| 1649 |
+
|
| 1650 |
+
def _eval_terms(self, n):
|
| 1651 |
+
"""
|
| 1652 |
+
Returns the first `n` terms of the composed formal power series.
|
| 1653 |
+
Term by term logic is implemented here.
|
| 1654 |
+
|
| 1655 |
+
Explanation
|
| 1656 |
+
===========
|
| 1657 |
+
|
| 1658 |
+
The coefficient sequence of the :obj:`FormalPowerSeriesCompose` object is the generic sequence.
|
| 1659 |
+
It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
|
| 1660 |
+
the final terms for the polynomial.
|
| 1661 |
+
|
| 1662 |
+
Examples
|
| 1663 |
+
========
|
| 1664 |
+
|
| 1665 |
+
>>> from sympy import fps, sin, exp
|
| 1666 |
+
>>> from sympy.abc import x
|
| 1667 |
+
>>> f1 = fps(exp(x))
|
| 1668 |
+
>>> f2 = fps(sin(x))
|
| 1669 |
+
>>> fcomp = f1.compose(f2, x)
|
| 1670 |
+
|
| 1671 |
+
>>> fcomp._eval_terms(6)
|
| 1672 |
+
-x**5/15 - x**4/8 + x**2/2 + x + 1
|
| 1673 |
+
|
| 1674 |
+
>>> fcomp._eval_terms(8)
|
| 1675 |
+
x**7/90 - x**6/240 - x**5/15 - x**4/8 + x**2/2 + x + 1
|
| 1676 |
+
|
| 1677 |
+
See Also
|
| 1678 |
+
========
|
| 1679 |
+
|
| 1680 |
+
sympy.series.formal.FormalPowerSeries.compose
|
| 1681 |
+
sympy.series.formal.FormalPowerSeries.coeff_bell
|
| 1682 |
+
|
| 1683 |
+
"""
|
| 1684 |
+
|
| 1685 |
+
ffps, gfps = self.ffps, self.gfps
|
| 1686 |
+
terms = [ffps.zero_coeff()]
|
| 1687 |
+
|
| 1688 |
+
for i in range(1, n):
|
| 1689 |
+
bell_seq = gfps.coeff_bell(i)
|
| 1690 |
+
seq = (ffps.bell_coeff_seq * bell_seq)
|
| 1691 |
+
terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
|
| 1692 |
+
|
| 1693 |
+
return Add(*terms)
|
| 1694 |
+
|
| 1695 |
+
|
| 1696 |
+
class FormalPowerSeriesInverse(FiniteFormalPowerSeries):
|
| 1697 |
+
"""
|
| 1698 |
+
Represents the Inverse of a formal power series.
|
| 1699 |
+
|
| 1700 |
+
Explanation
|
| 1701 |
+
===========
|
| 1702 |
+
|
| 1703 |
+
No computation is performed. Terms are calculated using a term by term logic,
|
| 1704 |
+
instead of a point by point logic.
|
| 1705 |
+
|
| 1706 |
+
There is a single difference between a :obj:`FormalPowerSeries` object and a
|
| 1707 |
+
:obj:`FormalPowerSeriesInverse` object. The coefficient sequence contains the
|
| 1708 |
+
generic sequence which is to be multiplied by a custom ``bell_seq`` finite sequence.
|
| 1709 |
+
The finite terms will then be added up to get the final terms.
|
| 1710 |
+
|
| 1711 |
+
See Also
|
| 1712 |
+
========
|
| 1713 |
+
|
| 1714 |
+
sympy.series.formal.FormalPowerSeries
|
| 1715 |
+
sympy.series.formal.FiniteFormalPowerSeries
|
| 1716 |
+
|
| 1717 |
+
"""
|
| 1718 |
+
def __init__(self, *args):
|
| 1719 |
+
ffps = self.ffps
|
| 1720 |
+
k = ffps.xk.variables[0]
|
| 1721 |
+
|
| 1722 |
+
inv = ffps.zero_coeff()
|
| 1723 |
+
inv_seq = sequence(inv ** (-(k + 1)), (k, 1, oo))
|
| 1724 |
+
self.aux_seq = ffps.sign_seq * ffps.fact_seq * inv_seq
|
| 1725 |
+
|
| 1726 |
+
@property
|
| 1727 |
+
def function(self):
|
| 1728 |
+
"""Function for the inverse of a formal power series."""
|
| 1729 |
+
f = self.f
|
| 1730 |
+
return 1 / f
|
| 1731 |
+
|
| 1732 |
+
@property
|
| 1733 |
+
def g(self):
|
| 1734 |
+
raise ValueError("Only one function is considered while performing"
|
| 1735 |
+
"inverse of a formal power series.")
|
| 1736 |
+
|
| 1737 |
+
@property
|
| 1738 |
+
def gfps(self):
|
| 1739 |
+
raise ValueError("Only one function is considered while performing"
|
| 1740 |
+
"inverse of a formal power series.")
|
| 1741 |
+
|
| 1742 |
+
def _eval_terms(self, n):
|
| 1743 |
+
"""
|
| 1744 |
+
Returns the first ``n`` terms of the composed formal power series.
|
| 1745 |
+
Term by term logic is implemented here.
|
| 1746 |
+
|
| 1747 |
+
Explanation
|
| 1748 |
+
===========
|
| 1749 |
+
|
| 1750 |
+
The coefficient sequence of the `FormalPowerSeriesInverse` object is the generic sequence.
|
| 1751 |
+
It is multiplied by ``bell_seq`` to get a sequence, whose terms are added up to get
|
| 1752 |
+
the final terms for the polynomial.
|
| 1753 |
+
|
| 1754 |
+
Examples
|
| 1755 |
+
========
|
| 1756 |
+
|
| 1757 |
+
>>> from sympy import fps, exp, cos
|
| 1758 |
+
>>> from sympy.abc import x
|
| 1759 |
+
>>> f1 = fps(exp(x))
|
| 1760 |
+
>>> f2 = fps(cos(x))
|
| 1761 |
+
>>> finv1, finv2 = f1.inverse(), f2.inverse()
|
| 1762 |
+
|
| 1763 |
+
>>> finv1._eval_terms(6)
|
| 1764 |
+
-x**5/120 + x**4/24 - x**3/6 + x**2/2 - x + 1
|
| 1765 |
+
|
| 1766 |
+
>>> finv2._eval_terms(8)
|
| 1767 |
+
61*x**6/720 + 5*x**4/24 + x**2/2 + 1
|
| 1768 |
+
|
| 1769 |
+
See Also
|
| 1770 |
+
========
|
| 1771 |
+
|
| 1772 |
+
sympy.series.formal.FormalPowerSeries.inverse
|
| 1773 |
+
sympy.series.formal.FormalPowerSeries.coeff_bell
|
| 1774 |
+
|
| 1775 |
+
"""
|
| 1776 |
+
ffps = self.ffps
|
| 1777 |
+
terms = [ffps.zero_coeff()]
|
| 1778 |
+
|
| 1779 |
+
for i in range(1, n):
|
| 1780 |
+
bell_seq = ffps.coeff_bell(i)
|
| 1781 |
+
seq = (self.aux_seq * bell_seq)
|
| 1782 |
+
terms.append(Add(*(seq[:i])) / ffps.fact_seq[i-1] * ffps.xk.coeff(i))
|
| 1783 |
+
|
| 1784 |
+
return Add(*terms)
|
| 1785 |
+
|
| 1786 |
+
|
| 1787 |
+
def fps(f, x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False):
|
| 1788 |
+
"""
|
| 1789 |
+
Generates Formal Power Series of ``f``.
|
| 1790 |
+
|
| 1791 |
+
Explanation
|
| 1792 |
+
===========
|
| 1793 |
+
|
| 1794 |
+
Returns the formal series expansion of ``f`` around ``x = x0``
|
| 1795 |
+
with respect to ``x`` in the form of a ``FormalPowerSeries`` object.
|
| 1796 |
+
|
| 1797 |
+
Formal Power Series is represented using an explicit formula
|
| 1798 |
+
computed using different algorithms.
|
| 1799 |
+
|
| 1800 |
+
See :func:`compute_fps` for the more details regarding the computation
|
| 1801 |
+
of formula.
|
| 1802 |
+
|
| 1803 |
+
Parameters
|
| 1804 |
+
==========
|
| 1805 |
+
|
| 1806 |
+
x : Symbol, optional
|
| 1807 |
+
If x is None and ``f`` is univariate, the univariate symbols will be
|
| 1808 |
+
supplied, otherwise an error will be raised.
|
| 1809 |
+
x0 : number, optional
|
| 1810 |
+
Point to perform series expansion about. Default is 0.
|
| 1811 |
+
dir : {1, -1, '+', '-'}, optional
|
| 1812 |
+
If dir is 1 or '+' the series is calculated from the right and
|
| 1813 |
+
for -1 or '-' the series is calculated from the left. For smooth
|
| 1814 |
+
functions this flag will not alter the results. Default is 1.
|
| 1815 |
+
hyper : {True, False}, optional
|
| 1816 |
+
Set hyper to False to skip the hypergeometric algorithm.
|
| 1817 |
+
By default it is set to False.
|
| 1818 |
+
order : int, optional
|
| 1819 |
+
Order of the derivative of ``f``, Default is 4.
|
| 1820 |
+
rational : {True, False}, optional
|
| 1821 |
+
Set rational to False to skip rational algorithm. By default it is set
|
| 1822 |
+
to True.
|
| 1823 |
+
full : {True, False}, optional
|
| 1824 |
+
Set full to True to increase the range of rational algorithm.
|
| 1825 |
+
See :func:`rational_algorithm` for details. By default it is set to
|
| 1826 |
+
False.
|
| 1827 |
+
|
| 1828 |
+
Examples
|
| 1829 |
+
========
|
| 1830 |
+
|
| 1831 |
+
>>> from sympy import fps, ln, atan, sin
|
| 1832 |
+
>>> from sympy.abc import x, n
|
| 1833 |
+
|
| 1834 |
+
Rational Functions
|
| 1835 |
+
|
| 1836 |
+
>>> fps(ln(1 + x)).truncate()
|
| 1837 |
+
x - x**2/2 + x**3/3 - x**4/4 + x**5/5 + O(x**6)
|
| 1838 |
+
|
| 1839 |
+
>>> fps(atan(x), full=True).truncate()
|
| 1840 |
+
x - x**3/3 + x**5/5 + O(x**6)
|
| 1841 |
+
|
| 1842 |
+
Symbolic Functions
|
| 1843 |
+
|
| 1844 |
+
>>> fps(x**n*sin(x**2), x).truncate(8)
|
| 1845 |
+
-x**(n + 6)/6 + x**(n + 2) + O(x**(n + 8))
|
| 1846 |
+
|
| 1847 |
+
See Also
|
| 1848 |
+
========
|
| 1849 |
+
|
| 1850 |
+
sympy.series.formal.FormalPowerSeries
|
| 1851 |
+
sympy.series.formal.compute_fps
|
| 1852 |
+
"""
|
| 1853 |
+
f = sympify(f)
|
| 1854 |
+
|
| 1855 |
+
if x is None:
|
| 1856 |
+
free = f.free_symbols
|
| 1857 |
+
if len(free) == 1:
|
| 1858 |
+
x = free.pop()
|
| 1859 |
+
elif not free:
|
| 1860 |
+
return f
|
| 1861 |
+
else:
|
| 1862 |
+
raise NotImplementedError("multivariate formal power series")
|
| 1863 |
+
|
| 1864 |
+
result = compute_fps(f, x, x0, dir, hyper, order, rational, full)
|
| 1865 |
+
|
| 1866 |
+
if result is None:
|
| 1867 |
+
return f
|
| 1868 |
+
|
| 1869 |
+
return FormalPowerSeries(f, x, x0, dir, result)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/fourier.py
ADDED
|
@@ -0,0 +1,811 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
from sympy.core.expr import Expr
|
| 6 |
+
from sympy.core.add import Add
|
| 7 |
+
from sympy.core.containers import Tuple
|
| 8 |
+
from sympy.core.singleton import S
|
| 9 |
+
from sympy.core.symbol import Dummy, Symbol
|
| 10 |
+
from sympy.core.sympify import sympify
|
| 11 |
+
from sympy.functions.elementary.trigonometric import sin, cos, sinc
|
| 12 |
+
from sympy.series.series_class import SeriesBase
|
| 13 |
+
from sympy.series.sequences import SeqFormula
|
| 14 |
+
from sympy.sets.sets import Interval
|
| 15 |
+
from sympy.utilities.iterables import is_sequence
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__doctest_requires__ = {('fourier_series',): ['matplotlib']}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def fourier_cos_seq(func, limits, n):
|
| 22 |
+
"""Returns the cos sequence in a Fourier series"""
|
| 23 |
+
from sympy.integrals import integrate
|
| 24 |
+
x, L = limits[0], limits[2] - limits[1]
|
| 25 |
+
cos_term = cos(2*n*pi*x / L)
|
| 26 |
+
formula = 2 * cos_term * integrate(func * cos_term, limits) / L
|
| 27 |
+
a0 = formula.subs(n, S.Zero) / 2
|
| 28 |
+
return a0, SeqFormula(2 * cos_term * integrate(func * cos_term, limits)
|
| 29 |
+
/ L, (n, 1, oo))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def fourier_sin_seq(func, limits, n):
|
| 33 |
+
"""Returns the sin sequence in a Fourier series"""
|
| 34 |
+
from sympy.integrals import integrate
|
| 35 |
+
x, L = limits[0], limits[2] - limits[1]
|
| 36 |
+
sin_term = sin(2*n*pi*x / L)
|
| 37 |
+
return SeqFormula(2 * sin_term * integrate(func * sin_term, limits)
|
| 38 |
+
/ L, (n, 1, oo))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _process_limits(func, limits):
|
| 42 |
+
"""
|
| 43 |
+
Limits should be of the form (x, start, stop).
|
| 44 |
+
x should be a symbol. Both start and stop should be bounded.
|
| 45 |
+
|
| 46 |
+
Explanation
|
| 47 |
+
===========
|
| 48 |
+
|
| 49 |
+
* If x is not given, x is determined from func.
|
| 50 |
+
* If limits is None. Limit of the form (x, -pi, pi) is returned.
|
| 51 |
+
|
| 52 |
+
Examples
|
| 53 |
+
========
|
| 54 |
+
|
| 55 |
+
>>> from sympy.series.fourier import _process_limits as pari
|
| 56 |
+
>>> from sympy.abc import x
|
| 57 |
+
>>> pari(x**2, (x, -2, 2))
|
| 58 |
+
(x, -2, 2)
|
| 59 |
+
>>> pari(x**2, (-2, 2))
|
| 60 |
+
(x, -2, 2)
|
| 61 |
+
>>> pari(x**2, None)
|
| 62 |
+
(x, -pi, pi)
|
| 63 |
+
"""
|
| 64 |
+
def _find_x(func):
|
| 65 |
+
free = func.free_symbols
|
| 66 |
+
if len(free) == 1:
|
| 67 |
+
return free.pop()
|
| 68 |
+
elif not free:
|
| 69 |
+
return Dummy('k')
|
| 70 |
+
else:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
" specify dummy variables for %s. If the function contains"
|
| 73 |
+
" more than one free symbol, a dummy variable should be"
|
| 74 |
+
" supplied explicitly e.g. FourierSeries(m*n**2, (n, -pi, pi))"
|
| 75 |
+
% func)
|
| 76 |
+
|
| 77 |
+
x, start, stop = None, None, None
|
| 78 |
+
if limits is None:
|
| 79 |
+
x, start, stop = _find_x(func), -pi, pi
|
| 80 |
+
if is_sequence(limits, Tuple):
|
| 81 |
+
if len(limits) == 3:
|
| 82 |
+
x, start, stop = limits
|
| 83 |
+
elif len(limits) == 2:
|
| 84 |
+
x = _find_x(func)
|
| 85 |
+
start, stop = limits
|
| 86 |
+
|
| 87 |
+
if not isinstance(x, Symbol) or start is None or stop is None:
|
| 88 |
+
raise ValueError('Invalid limits given: %s' % str(limits))
|
| 89 |
+
|
| 90 |
+
unbounded = [S.NegativeInfinity, S.Infinity]
|
| 91 |
+
if start in unbounded or stop in unbounded:
|
| 92 |
+
raise ValueError("Both the start and end value should be bounded")
|
| 93 |
+
|
| 94 |
+
return sympify((x, start, stop))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def finite_check(f, x, L):
|
| 98 |
+
|
| 99 |
+
def check_fx(exprs, x):
|
| 100 |
+
return x not in exprs.free_symbols
|
| 101 |
+
|
| 102 |
+
def check_sincos(_expr, x, L):
|
| 103 |
+
if isinstance(_expr, (sin, cos)):
|
| 104 |
+
sincos_args = _expr.args[0]
|
| 105 |
+
|
| 106 |
+
if sincos_args.match(a*(pi/L)*x + b) is not None:
|
| 107 |
+
return True
|
| 108 |
+
else:
|
| 109 |
+
return False
|
| 110 |
+
|
| 111 |
+
from sympy.simplify.fu import TR2, TR1, sincos_to_sum
|
| 112 |
+
_expr = sincos_to_sum(TR2(TR1(f)))
|
| 113 |
+
add_coeff = _expr.as_coeff_add()
|
| 114 |
+
|
| 115 |
+
a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k != S.Zero, ])
|
| 116 |
+
b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
|
| 117 |
+
|
| 118 |
+
for s in add_coeff[1]:
|
| 119 |
+
mul_coeffs = s.as_coeff_mul()[1]
|
| 120 |
+
for t in mul_coeffs:
|
| 121 |
+
if not (check_fx(t, x) or check_sincos(t, x, L)):
|
| 122 |
+
return False, f
|
| 123 |
+
|
| 124 |
+
return True, _expr
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class FourierSeries(SeriesBase):
|
| 128 |
+
r"""Represents Fourier sine/cosine series.
|
| 129 |
+
|
| 130 |
+
Explanation
|
| 131 |
+
===========
|
| 132 |
+
|
| 133 |
+
This class only represents a fourier series.
|
| 134 |
+
No computation is performed.
|
| 135 |
+
|
| 136 |
+
For how to compute Fourier series, see the :func:`fourier_series`
|
| 137 |
+
docstring.
|
| 138 |
+
|
| 139 |
+
See Also
|
| 140 |
+
========
|
| 141 |
+
|
| 142 |
+
sympy.series.fourier.fourier_series
|
| 143 |
+
"""
|
| 144 |
+
def __new__(cls, *args):
|
| 145 |
+
args = map(sympify, args)
|
| 146 |
+
return Expr.__new__(cls, *args)
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def function(self):
|
| 150 |
+
return self.args[0]
|
| 151 |
+
|
| 152 |
+
@property
|
| 153 |
+
def x(self):
|
| 154 |
+
return self.args[1][0]
|
| 155 |
+
|
| 156 |
+
@property
|
| 157 |
+
def period(self):
|
| 158 |
+
return (self.args[1][1], self.args[1][2])
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def a0(self):
|
| 162 |
+
return self.args[2][0]
|
| 163 |
+
|
| 164 |
+
@property
|
| 165 |
+
def an(self):
|
| 166 |
+
return self.args[2][1]
|
| 167 |
+
|
| 168 |
+
@property
|
| 169 |
+
def bn(self):
|
| 170 |
+
return self.args[2][2]
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def interval(self):
|
| 174 |
+
return Interval(0, oo)
|
| 175 |
+
|
| 176 |
+
@property
|
| 177 |
+
def start(self):
|
| 178 |
+
return self.interval.inf
|
| 179 |
+
|
| 180 |
+
@property
|
| 181 |
+
def stop(self):
|
| 182 |
+
return self.interval.sup
|
| 183 |
+
|
| 184 |
+
@property
|
| 185 |
+
def length(self):
|
| 186 |
+
return oo
|
| 187 |
+
|
| 188 |
+
@property
|
| 189 |
+
def L(self):
|
| 190 |
+
return abs(self.period[1] - self.period[0]) / 2
|
| 191 |
+
|
| 192 |
+
def _eval_subs(self, old, new):
|
| 193 |
+
x = self.x
|
| 194 |
+
if old.has(x):
|
| 195 |
+
return self
|
| 196 |
+
|
| 197 |
+
def truncate(self, n=3):
|
| 198 |
+
"""
|
| 199 |
+
Return the first n nonzero terms of the series.
|
| 200 |
+
|
| 201 |
+
If ``n`` is None return an iterator.
|
| 202 |
+
|
| 203 |
+
Parameters
|
| 204 |
+
==========
|
| 205 |
+
|
| 206 |
+
n : int or None
|
| 207 |
+
Amount of non-zero terms in approximation or None.
|
| 208 |
+
|
| 209 |
+
Returns
|
| 210 |
+
=======
|
| 211 |
+
|
| 212 |
+
Expr or iterator :
|
| 213 |
+
Approximation of function expanded into Fourier series.
|
| 214 |
+
|
| 215 |
+
Examples
|
| 216 |
+
========
|
| 217 |
+
|
| 218 |
+
>>> from sympy import fourier_series, pi
|
| 219 |
+
>>> from sympy.abc import x
|
| 220 |
+
>>> s = fourier_series(x, (x, -pi, pi))
|
| 221 |
+
>>> s.truncate(4)
|
| 222 |
+
2*sin(x) - sin(2*x) + 2*sin(3*x)/3 - sin(4*x)/2
|
| 223 |
+
|
| 224 |
+
See Also
|
| 225 |
+
========
|
| 226 |
+
|
| 227 |
+
sympy.series.fourier.FourierSeries.sigma_approximation
|
| 228 |
+
"""
|
| 229 |
+
if n is None:
|
| 230 |
+
return iter(self)
|
| 231 |
+
|
| 232 |
+
terms = []
|
| 233 |
+
for t in self:
|
| 234 |
+
if len(terms) == n:
|
| 235 |
+
break
|
| 236 |
+
if t is not S.Zero:
|
| 237 |
+
terms.append(t)
|
| 238 |
+
|
| 239 |
+
return Add(*terms)
|
| 240 |
+
|
| 241 |
+
def sigma_approximation(self, n=3):
|
| 242 |
+
r"""
|
| 243 |
+
Return :math:`\sigma`-approximation of Fourier series with respect
|
| 244 |
+
to order n.
|
| 245 |
+
|
| 246 |
+
Explanation
|
| 247 |
+
===========
|
| 248 |
+
|
| 249 |
+
Sigma approximation adjusts a Fourier summation to eliminate the Gibbs
|
| 250 |
+
phenomenon which would otherwise occur at discontinuities.
|
| 251 |
+
A sigma-approximated summation for a Fourier series of a T-periodical
|
| 252 |
+
function can be written as
|
| 253 |
+
|
| 254 |
+
.. math::
|
| 255 |
+
s(\theta) = \frac{1}{2} a_0 + \sum _{k=1}^{m-1}
|
| 256 |
+
\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr) \cdot
|
| 257 |
+
\left[ a_k \cos \Bigl( \frac{2\pi k}{T} \theta \Bigr)
|
| 258 |
+
+ b_k \sin \Bigl( \frac{2\pi k}{T} \theta \Bigr) \right],
|
| 259 |
+
|
| 260 |
+
where :math:`a_0, a_k, b_k, k=1,\ldots,{m-1}` are standard Fourier
|
| 261 |
+
series coefficients and
|
| 262 |
+
:math:`\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr)` is a Lanczos
|
| 263 |
+
:math:`\sigma` factor (expressed in terms of normalized
|
| 264 |
+
:math:`\operatorname{sinc}` function).
|
| 265 |
+
|
| 266 |
+
Parameters
|
| 267 |
+
==========
|
| 268 |
+
|
| 269 |
+
n : int
|
| 270 |
+
Highest order of the terms taken into account in approximation.
|
| 271 |
+
|
| 272 |
+
Returns
|
| 273 |
+
=======
|
| 274 |
+
|
| 275 |
+
Expr :
|
| 276 |
+
Sigma approximation of function expanded into Fourier series.
|
| 277 |
+
|
| 278 |
+
Examples
|
| 279 |
+
========
|
| 280 |
+
|
| 281 |
+
>>> from sympy import fourier_series, pi
|
| 282 |
+
>>> from sympy.abc import x
|
| 283 |
+
>>> s = fourier_series(x, (x, -pi, pi))
|
| 284 |
+
>>> s.sigma_approximation(4)
|
| 285 |
+
2*sin(x)*sinc(pi/4) - 2*sin(2*x)/pi + 2*sin(3*x)*sinc(3*pi/4)/3
|
| 286 |
+
|
| 287 |
+
See Also
|
| 288 |
+
========
|
| 289 |
+
|
| 290 |
+
sympy.series.fourier.FourierSeries.truncate
|
| 291 |
+
|
| 292 |
+
Notes
|
| 293 |
+
=====
|
| 294 |
+
|
| 295 |
+
The behaviour of
|
| 296 |
+
:meth:`~sympy.series.fourier.FourierSeries.sigma_approximation`
|
| 297 |
+
is different from :meth:`~sympy.series.fourier.FourierSeries.truncate`
|
| 298 |
+
- it takes all nonzero terms of degree smaller than n, rather than
|
| 299 |
+
first n nonzero ones.
|
| 300 |
+
|
| 301 |
+
References
|
| 302 |
+
==========
|
| 303 |
+
|
| 304 |
+
.. [1] https://en.wikipedia.org/wiki/Gibbs_phenomenon
|
| 305 |
+
.. [2] https://en.wikipedia.org/wiki/Sigma_approximation
|
| 306 |
+
"""
|
| 307 |
+
terms = [sinc(pi * i / n) * t for i, t in enumerate(self[:n])
|
| 308 |
+
if t is not S.Zero]
|
| 309 |
+
return Add(*terms)
|
| 310 |
+
|
| 311 |
+
def shift(self, s):
|
| 312 |
+
"""
|
| 313 |
+
Shift the function by a term independent of x.
|
| 314 |
+
|
| 315 |
+
Explanation
|
| 316 |
+
===========
|
| 317 |
+
|
| 318 |
+
f(x) -> f(x) + s
|
| 319 |
+
|
| 320 |
+
This is fast, if Fourier series of f(x) is already
|
| 321 |
+
computed.
|
| 322 |
+
|
| 323 |
+
Examples
|
| 324 |
+
========
|
| 325 |
+
|
| 326 |
+
>>> from sympy import fourier_series, pi
|
| 327 |
+
>>> from sympy.abc import x
|
| 328 |
+
>>> s = fourier_series(x**2, (x, -pi, pi))
|
| 329 |
+
>>> s.shift(1).truncate()
|
| 330 |
+
-4*cos(x) + cos(2*x) + 1 + pi**2/3
|
| 331 |
+
"""
|
| 332 |
+
s, x = sympify(s), self.x
|
| 333 |
+
|
| 334 |
+
if x in s.free_symbols:
|
| 335 |
+
raise ValueError("'%s' should be independent of %s" % (s, x))
|
| 336 |
+
|
| 337 |
+
a0 = self.a0 + s
|
| 338 |
+
sfunc = self.function + s
|
| 339 |
+
|
| 340 |
+
return self.func(sfunc, self.args[1], (a0, self.an, self.bn))
|
| 341 |
+
|
| 342 |
+
def shiftx(self, s):
|
| 343 |
+
"""
|
| 344 |
+
Shift x by a term independent of x.
|
| 345 |
+
|
| 346 |
+
Explanation
|
| 347 |
+
===========
|
| 348 |
+
|
| 349 |
+
f(x) -> f(x + s)
|
| 350 |
+
|
| 351 |
+
This is fast, if Fourier series of f(x) is already
|
| 352 |
+
computed.
|
| 353 |
+
|
| 354 |
+
Examples
|
| 355 |
+
========
|
| 356 |
+
|
| 357 |
+
>>> from sympy import fourier_series, pi
|
| 358 |
+
>>> from sympy.abc import x
|
| 359 |
+
>>> s = fourier_series(x**2, (x, -pi, pi))
|
| 360 |
+
>>> s.shiftx(1).truncate()
|
| 361 |
+
-4*cos(x + 1) + cos(2*x + 2) + pi**2/3
|
| 362 |
+
"""
|
| 363 |
+
s, x = sympify(s), self.x
|
| 364 |
+
|
| 365 |
+
if x in s.free_symbols:
|
| 366 |
+
raise ValueError("'%s' should be independent of %s" % (s, x))
|
| 367 |
+
|
| 368 |
+
an = self.an.subs(x, x + s)
|
| 369 |
+
bn = self.bn.subs(x, x + s)
|
| 370 |
+
sfunc = self.function.subs(x, x + s)
|
| 371 |
+
|
| 372 |
+
return self.func(sfunc, self.args[1], (self.a0, an, bn))
|
| 373 |
+
|
| 374 |
+
def scale(self, s):
|
| 375 |
+
"""
|
| 376 |
+
Scale the function by a term independent of x.
|
| 377 |
+
|
| 378 |
+
Explanation
|
| 379 |
+
===========
|
| 380 |
+
|
| 381 |
+
f(x) -> s * f(x)
|
| 382 |
+
|
| 383 |
+
This is fast, if Fourier series of f(x) is already
|
| 384 |
+
computed.
|
| 385 |
+
|
| 386 |
+
Examples
|
| 387 |
+
========
|
| 388 |
+
|
| 389 |
+
>>> from sympy import fourier_series, pi
|
| 390 |
+
>>> from sympy.abc import x
|
| 391 |
+
>>> s = fourier_series(x**2, (x, -pi, pi))
|
| 392 |
+
>>> s.scale(2).truncate()
|
| 393 |
+
-8*cos(x) + 2*cos(2*x) + 2*pi**2/3
|
| 394 |
+
"""
|
| 395 |
+
s, x = sympify(s), self.x
|
| 396 |
+
|
| 397 |
+
if x in s.free_symbols:
|
| 398 |
+
raise ValueError("'%s' should be independent of %s" % (s, x))
|
| 399 |
+
|
| 400 |
+
an = self.an.coeff_mul(s)
|
| 401 |
+
bn = self.bn.coeff_mul(s)
|
| 402 |
+
a0 = self.a0 * s
|
| 403 |
+
sfunc = self.args[0] * s
|
| 404 |
+
|
| 405 |
+
return self.func(sfunc, self.args[1], (a0, an, bn))
|
| 406 |
+
|
| 407 |
+
def scalex(self, s):
|
| 408 |
+
"""
|
| 409 |
+
Scale x by a term independent of x.
|
| 410 |
+
|
| 411 |
+
Explanation
|
| 412 |
+
===========
|
| 413 |
+
|
| 414 |
+
f(x) -> f(s*x)
|
| 415 |
+
|
| 416 |
+
This is fast, if Fourier series of f(x) is already
|
| 417 |
+
computed.
|
| 418 |
+
|
| 419 |
+
Examples
|
| 420 |
+
========
|
| 421 |
+
|
| 422 |
+
>>> from sympy import fourier_series, pi
|
| 423 |
+
>>> from sympy.abc import x
|
| 424 |
+
>>> s = fourier_series(x**2, (x, -pi, pi))
|
| 425 |
+
>>> s.scalex(2).truncate()
|
| 426 |
+
-4*cos(2*x) + cos(4*x) + pi**2/3
|
| 427 |
+
"""
|
| 428 |
+
s, x = sympify(s), self.x
|
| 429 |
+
|
| 430 |
+
if x in s.free_symbols:
|
| 431 |
+
raise ValueError("'%s' should be independent of %s" % (s, x))
|
| 432 |
+
|
| 433 |
+
an = self.an.subs(x, x * s)
|
| 434 |
+
bn = self.bn.subs(x, x * s)
|
| 435 |
+
sfunc = self.function.subs(x, x * s)
|
| 436 |
+
|
| 437 |
+
return self.func(sfunc, self.args[1], (self.a0, an, bn))
|
| 438 |
+
|
| 439 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 440 |
+
for t in self:
|
| 441 |
+
if t is not S.Zero:
|
| 442 |
+
return t
|
| 443 |
+
|
| 444 |
+
def _eval_term(self, pt):
|
| 445 |
+
if pt == 0:
|
| 446 |
+
return self.a0
|
| 447 |
+
return self.an.coeff(pt) + self.bn.coeff(pt)
|
| 448 |
+
|
| 449 |
+
def __neg__(self):
|
| 450 |
+
return self.scale(-1)
|
| 451 |
+
|
| 452 |
+
def __add__(self, other):
|
| 453 |
+
if isinstance(other, FourierSeries):
|
| 454 |
+
if self.period != other.period:
|
| 455 |
+
raise ValueError("Both the series should have same periods")
|
| 456 |
+
|
| 457 |
+
x, y = self.x, other.x
|
| 458 |
+
function = self.function + other.function.subs(y, x)
|
| 459 |
+
|
| 460 |
+
if self.x not in function.free_symbols:
|
| 461 |
+
return function
|
| 462 |
+
|
| 463 |
+
an = self.an + other.an
|
| 464 |
+
bn = self.bn + other.bn
|
| 465 |
+
a0 = self.a0 + other.a0
|
| 466 |
+
|
| 467 |
+
return self.func(function, self.args[1], (a0, an, bn))
|
| 468 |
+
|
| 469 |
+
return Add(self, other)
|
| 470 |
+
|
| 471 |
+
def __sub__(self, other):
|
| 472 |
+
return self.__add__(-other)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
class FiniteFourierSeries(FourierSeries):
|
| 476 |
+
r"""Represents Finite Fourier sine/cosine series.
|
| 477 |
+
|
| 478 |
+
For how to compute Fourier series, see the :func:`fourier_series`
|
| 479 |
+
docstring.
|
| 480 |
+
|
| 481 |
+
Parameters
|
| 482 |
+
==========
|
| 483 |
+
|
| 484 |
+
f : Expr
|
| 485 |
+
Expression for finding fourier_series
|
| 486 |
+
|
| 487 |
+
limits : ( x, start, stop)
|
| 488 |
+
x is the independent variable for the expression f
|
| 489 |
+
(start, stop) is the period of the fourier series
|
| 490 |
+
|
| 491 |
+
exprs: (a0, an, bn) or Expr
|
| 492 |
+
a0 is the constant term a0 of the fourier series
|
| 493 |
+
an is a dictionary of coefficients of cos terms
|
| 494 |
+
an[k] = coefficient of cos(pi*(k/L)*x)
|
| 495 |
+
bn is a dictionary of coefficients of sin terms
|
| 496 |
+
bn[k] = coefficient of sin(pi*(k/L)*x)
|
| 497 |
+
|
| 498 |
+
or exprs can be an expression to be converted to fourier form
|
| 499 |
+
|
| 500 |
+
Methods
|
| 501 |
+
=======
|
| 502 |
+
|
| 503 |
+
This class is an extension of FourierSeries class.
|
| 504 |
+
Please refer to sympy.series.fourier.FourierSeries for
|
| 505 |
+
further information.
|
| 506 |
+
|
| 507 |
+
See Also
|
| 508 |
+
========
|
| 509 |
+
|
| 510 |
+
sympy.series.fourier.FourierSeries
|
| 511 |
+
sympy.series.fourier.fourier_series
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
def __new__(cls, f, limits, exprs):
|
| 515 |
+
f = sympify(f)
|
| 516 |
+
limits = sympify(limits)
|
| 517 |
+
exprs = sympify(exprs)
|
| 518 |
+
|
| 519 |
+
if not (isinstance(exprs, Tuple) and len(exprs) == 3): # exprs is not of form (a0, an, bn)
|
| 520 |
+
# Converts the expression to fourier form
|
| 521 |
+
c, e = exprs.as_coeff_add()
|
| 522 |
+
from sympy.simplify.fu import TR10
|
| 523 |
+
rexpr = c + Add(*[TR10(i) for i in e])
|
| 524 |
+
a0, exp_ls = rexpr.expand(trig=False, power_base=False, power_exp=False, log=False).as_coeff_add()
|
| 525 |
+
|
| 526 |
+
x = limits[0]
|
| 527 |
+
L = abs(limits[2] - limits[1]) / 2
|
| 528 |
+
|
| 529 |
+
a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k is not S.Zero, ])
|
| 530 |
+
b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
|
| 531 |
+
|
| 532 |
+
an = {}
|
| 533 |
+
bn = {}
|
| 534 |
+
|
| 535 |
+
# separates the coefficients of sin and cos terms in dictionaries an, and bn
|
| 536 |
+
for p in exp_ls:
|
| 537 |
+
t = p.match(b * cos(a * (pi / L) * x))
|
| 538 |
+
q = p.match(b * sin(a * (pi / L) * x))
|
| 539 |
+
if t:
|
| 540 |
+
an[t[a]] = t[b] + an.get(t[a], S.Zero)
|
| 541 |
+
elif q:
|
| 542 |
+
bn[q[a]] = q[b] + bn.get(q[a], S.Zero)
|
| 543 |
+
else:
|
| 544 |
+
a0 += p
|
| 545 |
+
|
| 546 |
+
exprs = Tuple(a0, an, bn)
|
| 547 |
+
|
| 548 |
+
return Expr.__new__(cls, f, limits, exprs)
|
| 549 |
+
|
| 550 |
+
@property
|
| 551 |
+
def interval(self):
|
| 552 |
+
_length = 1 if self.a0 else 0
|
| 553 |
+
_length += max(set(self.an.keys()).union(set(self.bn.keys()))) + 1
|
| 554 |
+
return Interval(0, _length)
|
| 555 |
+
|
| 556 |
+
@property
|
| 557 |
+
def length(self):
|
| 558 |
+
return self.stop - self.start
|
| 559 |
+
|
| 560 |
+
def shiftx(self, s):
|
| 561 |
+
s, x = sympify(s), self.x
|
| 562 |
+
|
| 563 |
+
if x in s.free_symbols:
|
| 564 |
+
raise ValueError("'%s' should be independent of %s" % (s, x))
|
| 565 |
+
|
| 566 |
+
_expr = self.truncate().subs(x, x + s)
|
| 567 |
+
sfunc = self.function.subs(x, x + s)
|
| 568 |
+
|
| 569 |
+
return self.func(sfunc, self.args[1], _expr)
|
| 570 |
+
|
| 571 |
+
def scale(self, s):
|
| 572 |
+
s, x = sympify(s), self.x
|
| 573 |
+
|
| 574 |
+
if x in s.free_symbols:
|
| 575 |
+
raise ValueError("'%s' should be independent of %s" % (s, x))
|
| 576 |
+
|
| 577 |
+
_expr = self.truncate() * s
|
| 578 |
+
sfunc = self.function * s
|
| 579 |
+
|
| 580 |
+
return self.func(sfunc, self.args[1], _expr)
|
| 581 |
+
|
| 582 |
+
def scalex(self, s):
|
| 583 |
+
s, x = sympify(s), self.x
|
| 584 |
+
|
| 585 |
+
if x in s.free_symbols:
|
| 586 |
+
raise ValueError("'%s' should be independent of %s" % (s, x))
|
| 587 |
+
|
| 588 |
+
_expr = self.truncate().subs(x, x * s)
|
| 589 |
+
sfunc = self.function.subs(x, x * s)
|
| 590 |
+
|
| 591 |
+
return self.func(sfunc, self.args[1], _expr)
|
| 592 |
+
|
| 593 |
+
def _eval_term(self, pt):
|
| 594 |
+
if pt == 0:
|
| 595 |
+
return self.a0
|
| 596 |
+
|
| 597 |
+
_term = self.an.get(pt, S.Zero) * cos(pt * (pi / self.L) * self.x) \
|
| 598 |
+
+ self.bn.get(pt, S.Zero) * sin(pt * (pi / self.L) * self.x)
|
| 599 |
+
return _term
|
| 600 |
+
|
| 601 |
+
def __add__(self, other):
|
| 602 |
+
if isinstance(other, FourierSeries):
|
| 603 |
+
return other.__add__(fourier_series(self.function, self.args[1],\
|
| 604 |
+
finite=False))
|
| 605 |
+
elif isinstance(other, FiniteFourierSeries):
|
| 606 |
+
if self.period != other.period:
|
| 607 |
+
raise ValueError("Both the series should have same periods")
|
| 608 |
+
|
| 609 |
+
x, y = self.x, other.x
|
| 610 |
+
function = self.function + other.function.subs(y, x)
|
| 611 |
+
|
| 612 |
+
if self.x not in function.free_symbols:
|
| 613 |
+
return function
|
| 614 |
+
|
| 615 |
+
return fourier_series(function, limits=self.args[1])
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def fourier_series(f, limits=None, finite=True):
|
| 619 |
+
r"""Computes the Fourier trigonometric series expansion.
|
| 620 |
+
|
| 621 |
+
Explanation
|
| 622 |
+
===========
|
| 623 |
+
|
| 624 |
+
Fourier trigonometric series of $f(x)$ over the interval $(a, b)$
|
| 625 |
+
is defined as:
|
| 626 |
+
|
| 627 |
+
.. math::
|
| 628 |
+
\frac{a_0}{2} + \sum_{n=1}^{\infty}
|
| 629 |
+
(a_n \cos(\frac{2n \pi x}{L}) + b_n \sin(\frac{2n \pi x}{L}))
|
| 630 |
+
|
| 631 |
+
where the coefficients are:
|
| 632 |
+
|
| 633 |
+
.. math::
|
| 634 |
+
L = b - a
|
| 635 |
+
|
| 636 |
+
.. math::
|
| 637 |
+
a_0 = \frac{2}{L} \int_{a}^{b}{f(x) dx}
|
| 638 |
+
|
| 639 |
+
.. math::
|
| 640 |
+
a_n = \frac{2}{L} \int_{a}^{b}{f(x) \cos(\frac{2n \pi x}{L}) dx}
|
| 641 |
+
|
| 642 |
+
.. math::
|
| 643 |
+
b_n = \frac{2}{L} \int_{a}^{b}{f(x) \sin(\frac{2n \pi x}{L}) dx}
|
| 644 |
+
|
| 645 |
+
The condition whether the function $f(x)$ given should be periodic
|
| 646 |
+
or not is more than necessary, because it is sufficient to consider
|
| 647 |
+
the series to be converging to $f(x)$ only in the given interval,
|
| 648 |
+
not throughout the whole real line.
|
| 649 |
+
|
| 650 |
+
This also brings a lot of ease for the computation because
|
| 651 |
+
you do not have to make $f(x)$ artificially periodic by
|
| 652 |
+
wrapping it with piecewise, modulo operations,
|
| 653 |
+
but you can shape the function to look like the desired periodic
|
| 654 |
+
function only in the interval $(a, b)$, and the computed series will
|
| 655 |
+
automatically become the series of the periodic version of $f(x)$.
|
| 656 |
+
|
| 657 |
+
This property is illustrated in the examples section below.
|
| 658 |
+
|
| 659 |
+
Parameters
|
| 660 |
+
==========
|
| 661 |
+
|
| 662 |
+
limits : (sym, start, end), optional
|
| 663 |
+
*sym* denotes the symbol the series is computed with respect to.
|
| 664 |
+
|
| 665 |
+
*start* and *end* denotes the start and the end of the interval
|
| 666 |
+
where the fourier series converges to the given function.
|
| 667 |
+
|
| 668 |
+
Default range is specified as $-\pi$ and $\pi$.
|
| 669 |
+
|
| 670 |
+
Returns
|
| 671 |
+
=======
|
| 672 |
+
|
| 673 |
+
FourierSeries
|
| 674 |
+
A symbolic object representing the Fourier trigonometric series.
|
| 675 |
+
|
| 676 |
+
Examples
|
| 677 |
+
========
|
| 678 |
+
|
| 679 |
+
Computing the Fourier series of $f(x) = x^2$:
|
| 680 |
+
|
| 681 |
+
>>> from sympy import fourier_series, pi
|
| 682 |
+
>>> from sympy.abc import x
|
| 683 |
+
>>> f = x**2
|
| 684 |
+
>>> s = fourier_series(f, (x, -pi, pi))
|
| 685 |
+
>>> s1 = s.truncate(n=3)
|
| 686 |
+
>>> s1
|
| 687 |
+
-4*cos(x) + cos(2*x) + pi**2/3
|
| 688 |
+
|
| 689 |
+
Shifting of the Fourier series:
|
| 690 |
+
|
| 691 |
+
>>> s.shift(1).truncate()
|
| 692 |
+
-4*cos(x) + cos(2*x) + 1 + pi**2/3
|
| 693 |
+
>>> s.shiftx(1).truncate()
|
| 694 |
+
-4*cos(x + 1) + cos(2*x + 2) + pi**2/3
|
| 695 |
+
|
| 696 |
+
Scaling of the Fourier series:
|
| 697 |
+
|
| 698 |
+
>>> s.scale(2).truncate()
|
| 699 |
+
-8*cos(x) + 2*cos(2*x) + 2*pi**2/3
|
| 700 |
+
>>> s.scalex(2).truncate()
|
| 701 |
+
-4*cos(2*x) + cos(4*x) + pi**2/3
|
| 702 |
+
|
| 703 |
+
Computing the Fourier series of $f(x) = x$:
|
| 704 |
+
|
| 705 |
+
This illustrates how truncating to the higher order gives better
|
| 706 |
+
convergence.
|
| 707 |
+
|
| 708 |
+
.. plot::
|
| 709 |
+
:context: reset
|
| 710 |
+
:format: doctest
|
| 711 |
+
:include-source: True
|
| 712 |
+
|
| 713 |
+
>>> from sympy import fourier_series, pi, plot
|
| 714 |
+
>>> from sympy.abc import x
|
| 715 |
+
>>> f = x
|
| 716 |
+
>>> s = fourier_series(f, (x, -pi, pi))
|
| 717 |
+
>>> s1 = s.truncate(n = 3)
|
| 718 |
+
>>> s2 = s.truncate(n = 5)
|
| 719 |
+
>>> s3 = s.truncate(n = 7)
|
| 720 |
+
>>> p = plot(f, s1, s2, s3, (x, -pi, pi), show=False, legend=True)
|
| 721 |
+
|
| 722 |
+
>>> p[0].line_color = (0, 0, 0)
|
| 723 |
+
>>> p[0].label = 'x'
|
| 724 |
+
>>> p[1].line_color = (0.7, 0.7, 0.7)
|
| 725 |
+
>>> p[1].label = 'n=3'
|
| 726 |
+
>>> p[2].line_color = (0.5, 0.5, 0.5)
|
| 727 |
+
>>> p[2].label = 'n=5'
|
| 728 |
+
>>> p[3].line_color = (0.3, 0.3, 0.3)
|
| 729 |
+
>>> p[3].label = 'n=7'
|
| 730 |
+
|
| 731 |
+
>>> p.show()
|
| 732 |
+
|
| 733 |
+
This illustrates how the series converges to different sawtooth
|
| 734 |
+
waves if the different ranges are specified.
|
| 735 |
+
|
| 736 |
+
.. plot::
|
| 737 |
+
:context: close-figs
|
| 738 |
+
:format: doctest
|
| 739 |
+
:include-source: True
|
| 740 |
+
|
| 741 |
+
>>> s1 = fourier_series(x, (x, -1, 1)).truncate(10)
|
| 742 |
+
>>> s2 = fourier_series(x, (x, -pi, pi)).truncate(10)
|
| 743 |
+
>>> s3 = fourier_series(x, (x, 0, 1)).truncate(10)
|
| 744 |
+
>>> p = plot(x, s1, s2, s3, (x, -5, 5), show=False, legend=True)
|
| 745 |
+
|
| 746 |
+
>>> p[0].line_color = (0, 0, 0)
|
| 747 |
+
>>> p[0].label = 'x'
|
| 748 |
+
>>> p[1].line_color = (0.7, 0.7, 0.7)
|
| 749 |
+
>>> p[1].label = '[-1, 1]'
|
| 750 |
+
>>> p[2].line_color = (0.5, 0.5, 0.5)
|
| 751 |
+
>>> p[2].label = '[-pi, pi]'
|
| 752 |
+
>>> p[3].line_color = (0.3, 0.3, 0.3)
|
| 753 |
+
>>> p[3].label = '[0, 1]'
|
| 754 |
+
|
| 755 |
+
>>> p.show()
|
| 756 |
+
|
| 757 |
+
Notes
|
| 758 |
+
=====
|
| 759 |
+
|
| 760 |
+
Computing Fourier series can be slow
|
| 761 |
+
due to the integration required in computing
|
| 762 |
+
an, bn.
|
| 763 |
+
|
| 764 |
+
It is faster to compute Fourier series of a function
|
| 765 |
+
by using shifting and scaling on an already
|
| 766 |
+
computed Fourier series rather than computing
|
| 767 |
+
again.
|
| 768 |
+
|
| 769 |
+
e.g. If the Fourier series of ``x**2`` is known
|
| 770 |
+
the Fourier series of ``x**2 - 1`` can be found by shifting by ``-1``.
|
| 771 |
+
|
| 772 |
+
See Also
|
| 773 |
+
========
|
| 774 |
+
|
| 775 |
+
sympy.series.fourier.FourierSeries
|
| 776 |
+
|
| 777 |
+
References
|
| 778 |
+
==========
|
| 779 |
+
|
| 780 |
+
.. [1] https://mathworld.wolfram.com/FourierSeries.html
|
| 781 |
+
"""
|
| 782 |
+
f = sympify(f)
|
| 783 |
+
|
| 784 |
+
limits = _process_limits(f, limits)
|
| 785 |
+
x = limits[0]
|
| 786 |
+
|
| 787 |
+
if x not in f.free_symbols:
|
| 788 |
+
return f
|
| 789 |
+
|
| 790 |
+
if finite:
|
| 791 |
+
L = abs(limits[2] - limits[1]) / 2
|
| 792 |
+
is_finite, res_f = finite_check(f, x, L)
|
| 793 |
+
if is_finite:
|
| 794 |
+
return FiniteFourierSeries(f, limits, res_f)
|
| 795 |
+
|
| 796 |
+
n = Dummy('n')
|
| 797 |
+
center = (limits[1] + limits[2]) / 2
|
| 798 |
+
if center.is_zero:
|
| 799 |
+
neg_f = f.subs(x, -x)
|
| 800 |
+
if f == neg_f:
|
| 801 |
+
a0, an = fourier_cos_seq(f, limits, n)
|
| 802 |
+
bn = SeqFormula(0, (1, oo))
|
| 803 |
+
return FourierSeries(f, limits, (a0, an, bn))
|
| 804 |
+
elif f == -neg_f:
|
| 805 |
+
a0 = S.Zero
|
| 806 |
+
an = SeqFormula(0, (1, oo))
|
| 807 |
+
bn = fourier_sin_seq(f, limits, n)
|
| 808 |
+
return FourierSeries(f, limits, (a0, an, bn))
|
| 809 |
+
a0, an = fourier_cos_seq(f, limits, n)
|
| 810 |
+
bn = fourier_sin_seq(f, limits, n)
|
| 811 |
+
return FourierSeries(f, limits, (a0, an, bn))
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/gruntz.py
ADDED
|
@@ -0,0 +1,739 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Limits
|
| 3 |
+
======
|
| 4 |
+
|
| 5 |
+
Implemented according to the PhD thesis
|
| 6 |
+
https://www.cybertester.com/data/gruntz.pdf, which contains very thorough
|
| 7 |
+
descriptions of the algorithm including many examples. We summarize here
|
| 8 |
+
the gist of it.
|
| 9 |
+
|
| 10 |
+
All functions are sorted according to how rapidly varying they are at
|
| 11 |
+
infinity using the following rules. Any two functions f and g can be
|
| 12 |
+
compared using the properties of L:
|
| 13 |
+
|
| 14 |
+
L=lim log|f(x)| / log|g(x)| (for x -> oo)
|
| 15 |
+
|
| 16 |
+
We define >, < ~ according to::
|
| 17 |
+
|
| 18 |
+
1. f > g .... L=+-oo
|
| 19 |
+
|
| 20 |
+
we say that:
|
| 21 |
+
- f is greater than any power of g
|
| 22 |
+
- f is more rapidly varying than g
|
| 23 |
+
- f goes to infinity/zero faster than g
|
| 24 |
+
|
| 25 |
+
2. f < g .... L=0
|
| 26 |
+
|
| 27 |
+
we say that:
|
| 28 |
+
- f is lower than any power of g
|
| 29 |
+
|
| 30 |
+
3. f ~ g .... L!=0, +-oo
|
| 31 |
+
|
| 32 |
+
we say that:
|
| 33 |
+
- both f and g are bounded from above and below by suitable integral
|
| 34 |
+
powers of the other
|
| 35 |
+
|
| 36 |
+
Examples
|
| 37 |
+
========
|
| 38 |
+
::
|
| 39 |
+
2 < x < exp(x) < exp(x**2) < exp(exp(x))
|
| 40 |
+
2 ~ 3 ~ -5
|
| 41 |
+
x ~ x**2 ~ x**3 ~ 1/x ~ x**m ~ -x
|
| 42 |
+
exp(x) ~ exp(-x) ~ exp(2x) ~ exp(x)**2 ~ exp(x+exp(-x))
|
| 43 |
+
f ~ 1/f
|
| 44 |
+
|
| 45 |
+
So we can divide all the functions into comparability classes (x and x^2
|
| 46 |
+
belong to one class, exp(x) and exp(-x) belong to some other class). In
|
| 47 |
+
principle, we could compare any two functions, but in our algorithm, we
|
| 48 |
+
do not compare anything below the class 2~3~-5 (for example log(x) is
|
| 49 |
+
below this), so we set 2~3~-5 as the lowest comparability class.
|
| 50 |
+
|
| 51 |
+
Given the function f, we find the list of most rapidly varying (mrv set)
|
| 52 |
+
subexpressions of it. This list belongs to the same comparability class.
|
| 53 |
+
Let's say it is {exp(x), exp(2x)}. Using the rule f ~ 1/f we find an
|
| 54 |
+
element "w" (either from the list or a new one) from the same
|
| 55 |
+
comparability class which goes to zero at infinity. In our example we
|
| 56 |
+
set w=exp(-x) (but we could also set w=exp(-2x) or w=exp(-3x) ...). We
|
| 57 |
+
rewrite the mrv set using w, in our case {1/w, 1/w^2}, and substitute it
|
| 58 |
+
into f. Then we expand f into a series in w::
|
| 59 |
+
|
| 60 |
+
f = c0*w^e0 + c1*w^e1 + ... + O(w^en), where e0<e1<...<en, c0!=0
|
| 61 |
+
|
| 62 |
+
but for x->oo, lim f = lim c0*w^e0, because all the other terms go to zero,
|
| 63 |
+
because w goes to zero faster than the ci and ei. So::
|
| 64 |
+
|
| 65 |
+
for e0>0, lim f = 0
|
| 66 |
+
for e0<0, lim f = +-oo (the sign depends on the sign of c0)
|
| 67 |
+
for e0=0, lim f = lim c0
|
| 68 |
+
|
| 69 |
+
We need to recursively compute limits at several places of the algorithm, but
|
| 70 |
+
as is shown in the PhD thesis, it always finishes.
|
| 71 |
+
|
| 72 |
+
Important functions from the implementation:
|
| 73 |
+
|
| 74 |
+
compare(a, b, x) compares "a" and "b" by computing the limit L.
|
| 75 |
+
mrv(e, x) returns list of most rapidly varying (mrv) subexpressions of "e"
|
| 76 |
+
rewrite(e, Omega, x, wsym) rewrites "e" in terms of w
|
| 77 |
+
leadterm(f, x) returns the lowest power term in the series of f
|
| 78 |
+
mrv_leadterm(e, x) returns the lead term (c0, e0) for e
|
| 79 |
+
limitinf(e, x) computes lim e (for x->oo)
|
| 80 |
+
limit(e, z, z0) computes any limit by converting it to the case x->oo
|
| 81 |
+
|
| 82 |
+
All the functions are really simple and straightforward except
|
| 83 |
+
rewrite(), which is the most difficult/complex part of the algorithm.
|
| 84 |
+
When the algorithm fails, the bugs are usually in the series expansion
|
| 85 |
+
(i.e. in SymPy) or in rewrite.
|
| 86 |
+
|
| 87 |
+
This code is almost exact rewrite of the Maple code inside the Gruntz
|
| 88 |
+
thesis.
|
| 89 |
+
|
| 90 |
+
Debugging
|
| 91 |
+
---------
|
| 92 |
+
|
| 93 |
+
Because the gruntz algorithm is highly recursive, it's difficult to
|
| 94 |
+
figure out what went wrong inside a debugger. Instead, turn on nice
|
| 95 |
+
debug prints by defining the environment variable SYMPY_DEBUG. For
|
| 96 |
+
example:
|
| 97 |
+
|
| 98 |
+
[user@localhost]: SYMPY_DEBUG=True ./bin/isympy
|
| 99 |
+
|
| 100 |
+
In [1]: limit(sin(x)/x, x, 0)
|
| 101 |
+
limitinf(_x*sin(1/_x), _x) = 1
|
| 102 |
+
+-mrv_leadterm(_x*sin(1/_x), _x) = (1, 0)
|
| 103 |
+
| +-mrv(_x*sin(1/_x), _x) = set([_x])
|
| 104 |
+
| | +-mrv(_x, _x) = set([_x])
|
| 105 |
+
| | +-mrv(sin(1/_x), _x) = set([_x])
|
| 106 |
+
| | +-mrv(1/_x, _x) = set([_x])
|
| 107 |
+
| | +-mrv(_x, _x) = set([_x])
|
| 108 |
+
| +-mrv_leadterm(exp(_x)*sin(exp(-_x)), _x, set([exp(_x)])) = (1, 0)
|
| 109 |
+
| +-rewrite(exp(_x)*sin(exp(-_x)), set([exp(_x)]), _x, _w) = (1/_w*sin(_w), -_x)
|
| 110 |
+
| +-sign(_x, _x) = 1
|
| 111 |
+
| +-mrv_leadterm(1, _x) = (1, 0)
|
| 112 |
+
+-sign(0, _x) = 0
|
| 113 |
+
+-limitinf(1, _x) = 1
|
| 114 |
+
|
| 115 |
+
And check manually which line is wrong. Then go to the source code and
|
| 116 |
+
debug this function to figure out the exact problem.
|
| 117 |
+
|
| 118 |
+
"""
|
| 119 |
+
from functools import reduce
|
| 120 |
+
|
| 121 |
+
from sympy.core import Basic, S, Mul, PoleError, expand_mul
|
| 122 |
+
from sympy.core.cache import cacheit
|
| 123 |
+
from sympy.core.intfunc import ilcm
|
| 124 |
+
from sympy.core.numbers import I, oo
|
| 125 |
+
from sympy.core.symbol import Dummy, Wild
|
| 126 |
+
from sympy.core.traversal import bottom_up
|
| 127 |
+
|
| 128 |
+
from sympy.functions import log, exp, sign as _sign
|
| 129 |
+
from sympy.series.order import Order
|
| 130 |
+
from sympy.utilities.exceptions import SymPyDeprecationWarning
|
| 131 |
+
from sympy.utilities.misc import debug_decorator as debug
|
| 132 |
+
from sympy.utilities.timeutils import timethis
|
| 133 |
+
|
| 134 |
+
timeit = timethis('gruntz')
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def compare(a, b, x):
|
| 138 |
+
"""Returns "<" if a<b, "=" for a == b, ">" for a>b"""
|
| 139 |
+
# log(exp(...)) must always be simplified here for termination
|
| 140 |
+
la, lb = log(a), log(b)
|
| 141 |
+
if isinstance(a, Basic) and (isinstance(a, exp) or (a.is_Pow and a.base == S.Exp1)):
|
| 142 |
+
la = a.exp
|
| 143 |
+
if isinstance(b, Basic) and (isinstance(b, exp) or (b.is_Pow and b.base == S.Exp1)):
|
| 144 |
+
lb = b.exp
|
| 145 |
+
|
| 146 |
+
c = limitinf(la/lb, x)
|
| 147 |
+
if c == 0:
|
| 148 |
+
return "<"
|
| 149 |
+
elif c.is_infinite:
|
| 150 |
+
return ">"
|
| 151 |
+
else:
|
| 152 |
+
return "="
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class SubsSet(dict):
|
| 156 |
+
"""
|
| 157 |
+
Stores (expr, dummy) pairs, and how to rewrite expr-s.
|
| 158 |
+
|
| 159 |
+
Explanation
|
| 160 |
+
===========
|
| 161 |
+
|
| 162 |
+
The gruntz algorithm needs to rewrite certain expressions in term of a new
|
| 163 |
+
variable w. We cannot use subs, because it is just too smart for us. For
|
| 164 |
+
example::
|
| 165 |
+
|
| 166 |
+
> Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))]
|
| 167 |
+
> O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w]
|
| 168 |
+
> e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p))
|
| 169 |
+
> e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1])
|
| 170 |
+
-1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p))
|
| 171 |
+
|
| 172 |
+
is really not what we want!
|
| 173 |
+
|
| 174 |
+
So we do it the hard way and keep track of all the things we potentially
|
| 175 |
+
want to substitute by dummy variables. Consider the expression::
|
| 176 |
+
|
| 177 |
+
exp(x - exp(-x)) + exp(x) + x.
|
| 178 |
+
|
| 179 |
+
The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}.
|
| 180 |
+
We introduce corresponding dummy variables d1, d2, d3 and rewrite::
|
| 181 |
+
|
| 182 |
+
d3 + d1 + x.
|
| 183 |
+
|
| 184 |
+
This class first of all keeps track of the mapping expr->variable, i.e.
|
| 185 |
+
will at this stage be a dictionary::
|
| 186 |
+
|
| 187 |
+
{exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}.
|
| 188 |
+
|
| 189 |
+
[It turns out to be more convenient this way round.]
|
| 190 |
+
But sometimes expressions in the mrv set have other expressions from the
|
| 191 |
+
mrv set as subexpressions, and we need to keep track of that as well. In
|
| 192 |
+
this case, d3 is really exp(x - d2), so rewrites at this stage is::
|
| 193 |
+
|
| 194 |
+
{d3: exp(x-d2)}.
|
| 195 |
+
|
| 196 |
+
The function rewrite uses all this information to correctly rewrite our
|
| 197 |
+
expression in terms of w. In this case w can be chosen to be exp(-x),
|
| 198 |
+
i.e. d2. The correct rewriting then is::
|
| 199 |
+
|
| 200 |
+
exp(-w)/w + 1/w + x.
|
| 201 |
+
"""
|
| 202 |
+
def __init__(self):
|
| 203 |
+
self.rewrites = {}
|
| 204 |
+
|
| 205 |
+
def __repr__(self):
|
| 206 |
+
return super().__repr__() + ', ' + self.rewrites.__repr__()
|
| 207 |
+
|
| 208 |
+
def __getitem__(self, key):
|
| 209 |
+
if key not in self:
|
| 210 |
+
self[key] = Dummy()
|
| 211 |
+
return dict.__getitem__(self, key)
|
| 212 |
+
|
| 213 |
+
def do_subs(self, e):
|
| 214 |
+
"""Substitute the variables with expressions"""
|
| 215 |
+
for expr, var in self.items():
|
| 216 |
+
e = e.xreplace({var: expr})
|
| 217 |
+
return e
|
| 218 |
+
|
| 219 |
+
def meets(self, s2):
|
| 220 |
+
"""Tell whether or not self and s2 have non-empty intersection"""
|
| 221 |
+
return set(self.keys()).intersection(list(s2.keys())) != set()
|
| 222 |
+
|
| 223 |
+
def union(self, s2, exps=None):
|
| 224 |
+
"""Compute the union of self and s2, adjusting exps"""
|
| 225 |
+
res = self.copy()
|
| 226 |
+
tr = {}
|
| 227 |
+
for expr, var in s2.items():
|
| 228 |
+
if expr in self:
|
| 229 |
+
if exps:
|
| 230 |
+
exps = exps.xreplace({var: res[expr]})
|
| 231 |
+
tr[var] = res[expr]
|
| 232 |
+
else:
|
| 233 |
+
res[expr] = var
|
| 234 |
+
for var, rewr in s2.rewrites.items():
|
| 235 |
+
res.rewrites[var] = rewr.xreplace(tr)
|
| 236 |
+
return res, exps
|
| 237 |
+
|
| 238 |
+
def copy(self):
|
| 239 |
+
"""Create a shallow copy of SubsSet"""
|
| 240 |
+
r = SubsSet()
|
| 241 |
+
r.rewrites = self.rewrites.copy()
|
| 242 |
+
for expr, var in self.items():
|
| 243 |
+
r[expr] = var
|
| 244 |
+
return r
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
@debug
|
| 248 |
+
def mrv(e, x):
|
| 249 |
+
"""Returns a SubsSet of most rapidly varying (mrv) subexpressions of 'e',
|
| 250 |
+
and e rewritten in terms of these"""
|
| 251 |
+
from sympy.simplify.powsimp import powsimp
|
| 252 |
+
e = powsimp(e, deep=True, combine='exp')
|
| 253 |
+
if not isinstance(e, Basic):
|
| 254 |
+
raise TypeError("e should be an instance of Basic")
|
| 255 |
+
if not e.has(x):
|
| 256 |
+
return SubsSet(), e
|
| 257 |
+
elif e == x:
|
| 258 |
+
s = SubsSet()
|
| 259 |
+
return s, s[x]
|
| 260 |
+
elif e.is_Mul or e.is_Add:
|
| 261 |
+
i, d = e.as_independent(x) # throw away x-independent terms
|
| 262 |
+
if d.func != e.func:
|
| 263 |
+
s, expr = mrv(d, x)
|
| 264 |
+
return s, e.func(i, expr)
|
| 265 |
+
a, b = d.as_two_terms()
|
| 266 |
+
s1, e1 = mrv(a, x)
|
| 267 |
+
s2, e2 = mrv(b, x)
|
| 268 |
+
return mrv_max1(s1, s2, e.func(i, e1, e2), x)
|
| 269 |
+
elif e.is_Pow and e.base != S.Exp1:
|
| 270 |
+
e1 = S.One
|
| 271 |
+
while e.is_Pow:
|
| 272 |
+
b1 = e.base
|
| 273 |
+
e1 *= e.exp
|
| 274 |
+
e = b1
|
| 275 |
+
if b1 == 1:
|
| 276 |
+
return SubsSet(), b1
|
| 277 |
+
if e1.has(x):
|
| 278 |
+
if limitinf(b1, x) is S.One:
|
| 279 |
+
if limitinf(e1, x).is_infinite is False:
|
| 280 |
+
return mrv(exp(e1*(b1 - 1)), x)
|
| 281 |
+
return mrv(exp(e1*log(b1)), x)
|
| 282 |
+
else:
|
| 283 |
+
s, expr = mrv(b1, x)
|
| 284 |
+
return s, expr**e1
|
| 285 |
+
elif isinstance(e, log):
|
| 286 |
+
s, expr = mrv(e.args[0], x)
|
| 287 |
+
return s, log(expr)
|
| 288 |
+
elif isinstance(e, exp) or (e.is_Pow and e.base == S.Exp1):
|
| 289 |
+
# We know from the theory of this algorithm that exp(log(...)) may always
|
| 290 |
+
# be simplified here, and doing so is vital for termination.
|
| 291 |
+
if isinstance(e.exp, log):
|
| 292 |
+
return mrv(e.exp.args[0], x)
|
| 293 |
+
# if a product has an infinite factor the result will be
|
| 294 |
+
# infinite if there is no zero, otherwise NaN; here, we
|
| 295 |
+
# consider the result infinite if any factor is infinite
|
| 296 |
+
li = limitinf(e.exp, x)
|
| 297 |
+
if any(_.is_infinite for _ in Mul.make_args(li)):
|
| 298 |
+
s1 = SubsSet()
|
| 299 |
+
e1 = s1[e]
|
| 300 |
+
s2, e2 = mrv(e.exp, x)
|
| 301 |
+
su = s1.union(s2)[0]
|
| 302 |
+
su.rewrites[e1] = exp(e2)
|
| 303 |
+
return mrv_max3(s1, e1, s2, exp(e2), su, e1, x)
|
| 304 |
+
else:
|
| 305 |
+
s, expr = mrv(e.exp, x)
|
| 306 |
+
return s, exp(expr)
|
| 307 |
+
elif e.is_Function:
|
| 308 |
+
l = [mrv(a, x) for a in e.args]
|
| 309 |
+
l2 = [s for (s, _) in l if s != SubsSet()]
|
| 310 |
+
if len(l2) != 1:
|
| 311 |
+
# e.g. something like BesselJ(x, x)
|
| 312 |
+
raise NotImplementedError("MRV set computation for functions in"
|
| 313 |
+
" several variables not implemented.")
|
| 314 |
+
s, ss = l2[0], SubsSet()
|
| 315 |
+
args = [ss.do_subs(x[1]) for x in l]
|
| 316 |
+
return s, e.func(*args)
|
| 317 |
+
elif e.is_Derivative:
|
| 318 |
+
raise NotImplementedError("MRV set computation for derivatives"
|
| 319 |
+
" not implemented yet.")
|
| 320 |
+
raise NotImplementedError(
|
| 321 |
+
"Don't know how to calculate the mrv of '%s'" % e)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def mrv_max3(f, expsf, g, expsg, union, expsboth, x):
|
| 325 |
+
"""
|
| 326 |
+
Computes the maximum of two sets of expressions f and g, which
|
| 327 |
+
are in the same comparability class, i.e. max() compares (two elements of)
|
| 328 |
+
f and g and returns either (f, expsf) [if f is larger], (g, expsg)
|
| 329 |
+
[if g is larger] or (union, expsboth) [if f, g are of the same class].
|
| 330 |
+
"""
|
| 331 |
+
if not isinstance(f, SubsSet):
|
| 332 |
+
raise TypeError("f should be an instance of SubsSet")
|
| 333 |
+
if not isinstance(g, SubsSet):
|
| 334 |
+
raise TypeError("g should be an instance of SubsSet")
|
| 335 |
+
if f == SubsSet():
|
| 336 |
+
return g, expsg
|
| 337 |
+
elif g == SubsSet():
|
| 338 |
+
return f, expsf
|
| 339 |
+
elif f.meets(g):
|
| 340 |
+
return union, expsboth
|
| 341 |
+
|
| 342 |
+
c = compare(list(f.keys())[0], list(g.keys())[0], x)
|
| 343 |
+
if c == ">":
|
| 344 |
+
return f, expsf
|
| 345 |
+
elif c == "<":
|
| 346 |
+
return g, expsg
|
| 347 |
+
else:
|
| 348 |
+
if c != "=":
|
| 349 |
+
raise ValueError("c should be =")
|
| 350 |
+
return union, expsboth
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def mrv_max1(f, g, exps, x):
|
| 354 |
+
"""Computes the maximum of two sets of expressions f and g, which
|
| 355 |
+
are in the same comparability class, i.e. mrv_max1() compares (two elements of)
|
| 356 |
+
f and g and returns the set, which is in the higher comparability class
|
| 357 |
+
of the union of both, if they have the same order of variation.
|
| 358 |
+
Also returns exps, with the appropriate substitutions made.
|
| 359 |
+
"""
|
| 360 |
+
u, b = f.union(g, exps)
|
| 361 |
+
return mrv_max3(f, g.do_subs(exps), g, f.do_subs(exps),
|
| 362 |
+
u, b, x)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
@debug
|
| 366 |
+
@cacheit
|
| 367 |
+
@timeit
|
| 368 |
+
def sign(e, x):
|
| 369 |
+
"""
|
| 370 |
+
Returns a sign of an expression e(x) for x->oo.
|
| 371 |
+
|
| 372 |
+
::
|
| 373 |
+
|
| 374 |
+
e > 0 for x sufficiently large ... 1
|
| 375 |
+
e == 0 for x sufficiently large ... 0
|
| 376 |
+
e < 0 for x sufficiently large ... -1
|
| 377 |
+
|
| 378 |
+
The result of this function is currently undefined if e changes sign
|
| 379 |
+
arbitrarily often for arbitrarily large x (e.g. sin(x)).
|
| 380 |
+
|
| 381 |
+
Note that this returns zero only if e is *constantly* zero
|
| 382 |
+
for x sufficiently large. [If e is constant, of course, this is just
|
| 383 |
+
the same thing as the sign of e.]
|
| 384 |
+
"""
|
| 385 |
+
if not isinstance(e, Basic):
|
| 386 |
+
raise TypeError("e should be an instance of Basic")
|
| 387 |
+
|
| 388 |
+
if e.is_positive:
|
| 389 |
+
return 1
|
| 390 |
+
elif e.is_negative:
|
| 391 |
+
return -1
|
| 392 |
+
elif e.is_zero:
|
| 393 |
+
return 0
|
| 394 |
+
|
| 395 |
+
elif not e.has(x):
|
| 396 |
+
from sympy.simplify import logcombine
|
| 397 |
+
e = logcombine(e)
|
| 398 |
+
return _sign(e)
|
| 399 |
+
elif e == x:
|
| 400 |
+
return 1
|
| 401 |
+
elif e.is_Mul:
|
| 402 |
+
a, b = e.as_two_terms()
|
| 403 |
+
sa = sign(a, x)
|
| 404 |
+
if not sa:
|
| 405 |
+
return 0
|
| 406 |
+
return sa * sign(b, x)
|
| 407 |
+
elif isinstance(e, exp):
|
| 408 |
+
return 1
|
| 409 |
+
elif e.is_Pow:
|
| 410 |
+
if e.base == S.Exp1:
|
| 411 |
+
return 1
|
| 412 |
+
s = sign(e.base, x)
|
| 413 |
+
if s == 1:
|
| 414 |
+
return 1
|
| 415 |
+
if e.exp.is_Integer:
|
| 416 |
+
return s**e.exp
|
| 417 |
+
elif isinstance(e, log):
|
| 418 |
+
return sign(e.args[0] - 1, x)
|
| 419 |
+
|
| 420 |
+
# if all else fails, do it the hard way
|
| 421 |
+
c0, e0 = mrv_leadterm(e, x)
|
| 422 |
+
return sign(c0, x)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
@debug
|
| 426 |
+
@timeit
|
| 427 |
+
@cacheit
|
| 428 |
+
def limitinf(e, x):
|
| 429 |
+
"""Limit e(x) for x-> oo."""
|
| 430 |
+
# rewrite e in terms of tractable functions only
|
| 431 |
+
|
| 432 |
+
old = e
|
| 433 |
+
if not e.has(x):
|
| 434 |
+
return e # e is a constant
|
| 435 |
+
from sympy.simplify.powsimp import powdenest
|
| 436 |
+
from sympy.calculus.util import AccumBounds
|
| 437 |
+
if e.has(Order):
|
| 438 |
+
e = e.expand().removeO()
|
| 439 |
+
if not x.is_positive or x.is_integer:
|
| 440 |
+
# We make sure that x.is_positive is True and x.is_integer is None
|
| 441 |
+
# so we get all the correct mathematical behavior from the expression.
|
| 442 |
+
# We need a fresh variable.
|
| 443 |
+
p = Dummy('p', positive=True)
|
| 444 |
+
e = e.subs(x, p)
|
| 445 |
+
x = p
|
| 446 |
+
e = e.rewrite('tractable', deep=True, limitvar=x)
|
| 447 |
+
e = powdenest(e)
|
| 448 |
+
if isinstance(e, AccumBounds):
|
| 449 |
+
if mrv_leadterm(e.min, x) != mrv_leadterm(e.max, x):
|
| 450 |
+
raise NotImplementedError
|
| 451 |
+
c0, e0 = mrv_leadterm(e.min, x)
|
| 452 |
+
else:
|
| 453 |
+
c0, e0 = mrv_leadterm(e, x)
|
| 454 |
+
sig = sign(e0, x)
|
| 455 |
+
if sig == 1:
|
| 456 |
+
return S.Zero # e0>0: lim f = 0
|
| 457 |
+
elif sig == -1: # e0<0: lim f = +-oo (the sign depends on the sign of c0)
|
| 458 |
+
if c0.match(I*Wild("a", exclude=[I])):
|
| 459 |
+
return c0*oo
|
| 460 |
+
s = sign(c0, x)
|
| 461 |
+
# the leading term shouldn't be 0:
|
| 462 |
+
if s == 0:
|
| 463 |
+
raise ValueError("Leading term should not be 0")
|
| 464 |
+
return s*oo
|
| 465 |
+
elif sig == 0:
|
| 466 |
+
if c0 == old:
|
| 467 |
+
c0 = c0.cancel()
|
| 468 |
+
return limitinf(c0, x) # e0=0: lim f = lim c0
|
| 469 |
+
else:
|
| 470 |
+
raise ValueError("{} could not be evaluated".format(sig))
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def moveup2(s, x):
|
| 474 |
+
r = SubsSet()
|
| 475 |
+
for expr, var in s.items():
|
| 476 |
+
r[expr.xreplace({x: exp(x)})] = var
|
| 477 |
+
for var, expr in s.rewrites.items():
|
| 478 |
+
r.rewrites[var] = s.rewrites[var].xreplace({x: exp(x)})
|
| 479 |
+
return r
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def moveup(l, x):
|
| 483 |
+
return [e.xreplace({x: exp(x)}) for e in l]
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
@debug
|
| 487 |
+
@timeit
|
| 488 |
+
def calculate_series(e, x, logx=None):
|
| 489 |
+
""" Calculates at least one term of the series of ``e`` in ``x``.
|
| 490 |
+
|
| 491 |
+
This is a place that fails most often, so it is in its own function.
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
SymPyDeprecationWarning(
|
| 495 |
+
feature="calculate_series",
|
| 496 |
+
useinstead="series() with suitable n, or as_leading_term",
|
| 497 |
+
issue=21838,
|
| 498 |
+
deprecated_since_version="1.12"
|
| 499 |
+
).warn()
|
| 500 |
+
|
| 501 |
+
from sympy.simplify.powsimp import powdenest
|
| 502 |
+
|
| 503 |
+
for t in e.lseries(x, logx=logx):
|
| 504 |
+
# bottom_up function is required for a specific case - when e is
|
| 505 |
+
# -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p)
|
| 506 |
+
t = bottom_up(t, lambda w:
|
| 507 |
+
getattr(w, 'normal', lambda: w)())
|
| 508 |
+
# And the expression
|
| 509 |
+
# `(-sin(1/x) + sin((x + exp(x))*exp(-x)/x))*exp(x)`
|
| 510 |
+
# from the first test of test_gruntz_eval_special needs to
|
| 511 |
+
# be expanded. But other forms need to be have at least
|
| 512 |
+
# factor_terms applied. `factor` accomplishes both and is
|
| 513 |
+
# faster than using `factor_terms` for the gruntz suite. It
|
| 514 |
+
# does not appear that use of `cancel` is necessary.
|
| 515 |
+
# t = cancel(t, expand=False)
|
| 516 |
+
t = t.factor()
|
| 517 |
+
|
| 518 |
+
if t.has(exp) and t.has(log):
|
| 519 |
+
t = powdenest(t)
|
| 520 |
+
|
| 521 |
+
if not t.is_zero:
|
| 522 |
+
break
|
| 523 |
+
|
| 524 |
+
return t
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
@debug
|
| 528 |
+
@timeit
|
| 529 |
+
@cacheit
|
| 530 |
+
def mrv_leadterm(e, x):
|
| 531 |
+
"""Returns (c0, e0) for e."""
|
| 532 |
+
Omega = SubsSet()
|
| 533 |
+
if not e.has(x):
|
| 534 |
+
return (e, S.Zero)
|
| 535 |
+
if Omega == SubsSet():
|
| 536 |
+
Omega, exps = mrv(e, x)
|
| 537 |
+
if not Omega:
|
| 538 |
+
# e really does not depend on x after simplification
|
| 539 |
+
return exps, S.Zero
|
| 540 |
+
if x in Omega:
|
| 541 |
+
# move the whole omega up (exponentiate each term):
|
| 542 |
+
Omega_up = moveup2(Omega, x)
|
| 543 |
+
exps_up = moveup([exps], x)[0]
|
| 544 |
+
# NOTE: there is no need to move this down!
|
| 545 |
+
Omega = Omega_up
|
| 546 |
+
exps = exps_up
|
| 547 |
+
#
|
| 548 |
+
# The positive dummy, w, is used here so log(w*2) etc. will expand;
|
| 549 |
+
# a unique dummy is needed in this algorithm
|
| 550 |
+
#
|
| 551 |
+
# For limits of complex functions, the algorithm would have to be
|
| 552 |
+
# improved, or just find limits of Re and Im components separately.
|
| 553 |
+
#
|
| 554 |
+
w = Dummy("w", positive=True)
|
| 555 |
+
f, logw = rewrite(exps, Omega, x, w)
|
| 556 |
+
try:
|
| 557 |
+
lt = f.leadterm(w, logx=logw)
|
| 558 |
+
except (NotImplementedError, PoleError, ValueError):
|
| 559 |
+
n0 = 1
|
| 560 |
+
_series = Order(1)
|
| 561 |
+
incr = S.One
|
| 562 |
+
while _series.is_Order:
|
| 563 |
+
_series = f._eval_nseries(w, n=n0+incr, logx=logw)
|
| 564 |
+
incr *= 2
|
| 565 |
+
series = _series.expand().removeO()
|
| 566 |
+
try:
|
| 567 |
+
lt = series.leadterm(w, logx=logw)
|
| 568 |
+
except (NotImplementedError, PoleError, ValueError):
|
| 569 |
+
lt = f.as_coeff_exponent(w)
|
| 570 |
+
if lt[0].has(w):
|
| 571 |
+
base = f.as_base_exp()[0].as_coeff_exponent(w)
|
| 572 |
+
ex = f.as_base_exp()[1]
|
| 573 |
+
lt = (base[0]**ex, base[1]*ex)
|
| 574 |
+
return (lt[0].subs(log(w), logw), lt[1])
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def build_expression_tree(Omega, rewrites):
|
| 578 |
+
r""" Helper function for rewrite.
|
| 579 |
+
|
| 580 |
+
We need to sort Omega (mrv set) so that we replace an expression before
|
| 581 |
+
we replace any expression in terms of which it has to be rewritten::
|
| 582 |
+
|
| 583 |
+
e1 ---> e2 ---> e3
|
| 584 |
+
\
|
| 585 |
+
-> e4
|
| 586 |
+
|
| 587 |
+
Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
|
| 588 |
+
To do this we assemble the nodes into a tree, and sort them by height.
|
| 589 |
+
|
| 590 |
+
This function builds the tree, rewrites then sorts the nodes.
|
| 591 |
+
"""
|
| 592 |
+
class Node:
|
| 593 |
+
def __init__(self):
|
| 594 |
+
self.before = []
|
| 595 |
+
self.expr = None
|
| 596 |
+
self.var = None
|
| 597 |
+
def ht(self):
|
| 598 |
+
return reduce(lambda x, y: x + y,
|
| 599 |
+
[x.ht() for x in self.before], 1)
|
| 600 |
+
nodes = {}
|
| 601 |
+
for expr, v in Omega:
|
| 602 |
+
n = Node()
|
| 603 |
+
n.var = v
|
| 604 |
+
n.expr = expr
|
| 605 |
+
nodes[v] = n
|
| 606 |
+
for _, v in Omega:
|
| 607 |
+
if v in rewrites:
|
| 608 |
+
n = nodes[v]
|
| 609 |
+
r = rewrites[v]
|
| 610 |
+
for _, v2 in Omega:
|
| 611 |
+
if r.has(v2):
|
| 612 |
+
n.before.append(nodes[v2])
|
| 613 |
+
|
| 614 |
+
return nodes
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
@debug
|
| 618 |
+
@timeit
|
| 619 |
+
def rewrite(e, Omega, x, wsym):
|
| 620 |
+
"""e(x) ... the function
|
| 621 |
+
Omega ... the mrv set
|
| 622 |
+
wsym ... the symbol which is going to be used for w
|
| 623 |
+
|
| 624 |
+
Returns the rewritten e in terms of w and log(w). See test_rewrite1()
|
| 625 |
+
for examples and correct results.
|
| 626 |
+
"""
|
| 627 |
+
|
| 628 |
+
from sympy import AccumBounds
|
| 629 |
+
if not isinstance(Omega, SubsSet):
|
| 630 |
+
raise TypeError("Omega should be an instance of SubsSet")
|
| 631 |
+
if len(Omega) == 0:
|
| 632 |
+
raise ValueError("Length cannot be 0")
|
| 633 |
+
# all items in Omega must be exponentials
|
| 634 |
+
for t in Omega.keys():
|
| 635 |
+
if not isinstance(t, exp):
|
| 636 |
+
raise ValueError("Value should be exp")
|
| 637 |
+
rewrites = Omega.rewrites
|
| 638 |
+
Omega = list(Omega.items())
|
| 639 |
+
|
| 640 |
+
nodes = build_expression_tree(Omega, rewrites)
|
| 641 |
+
Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True)
|
| 642 |
+
|
| 643 |
+
# make sure we know the sign of each exp() term; after the loop,
|
| 644 |
+
# g is going to be the "w" - the simplest one in the mrv set
|
| 645 |
+
for g, _ in Omega:
|
| 646 |
+
sig = sign(g.exp, x)
|
| 647 |
+
if sig != 1 and sig != -1 and not sig.has(AccumBounds):
|
| 648 |
+
raise NotImplementedError('Result depends on the sign of %s' % sig)
|
| 649 |
+
if sig == 1:
|
| 650 |
+
wsym = 1/wsym # if g goes to oo, substitute 1/w
|
| 651 |
+
# O2 is a list, which results by rewriting each item in Omega using "w"
|
| 652 |
+
O2 = []
|
| 653 |
+
denominators = []
|
| 654 |
+
for f, var in Omega:
|
| 655 |
+
c = limitinf(f.exp/g.exp, x)
|
| 656 |
+
if c.is_Rational:
|
| 657 |
+
denominators.append(c.q)
|
| 658 |
+
arg = f.exp
|
| 659 |
+
if var in rewrites:
|
| 660 |
+
if not isinstance(rewrites[var], exp):
|
| 661 |
+
raise ValueError("Value should be exp")
|
| 662 |
+
arg = rewrites[var].args[0]
|
| 663 |
+
O2.append((var, exp((arg - c*g.exp).expand())*wsym**c))
|
| 664 |
+
|
| 665 |
+
# Remember that Omega contains subexpressions of "e". So now we find
|
| 666 |
+
# them in "e" and substitute them for our rewriting, stored in O2
|
| 667 |
+
|
| 668 |
+
# the following powsimp is necessary to automatically combine exponentials,
|
| 669 |
+
# so that the .xreplace() below succeeds:
|
| 670 |
+
# TODO this should not be necessary
|
| 671 |
+
from sympy.simplify.powsimp import powsimp
|
| 672 |
+
f = powsimp(e, deep=True, combine='exp')
|
| 673 |
+
for a, b in O2:
|
| 674 |
+
f = f.xreplace({a: b})
|
| 675 |
+
|
| 676 |
+
for _, var in Omega:
|
| 677 |
+
assert not f.has(var)
|
| 678 |
+
|
| 679 |
+
# finally compute the logarithm of w (logw).
|
| 680 |
+
logw = g.exp
|
| 681 |
+
if sig == 1:
|
| 682 |
+
logw = -logw # log(w)->log(1/w)=-log(w)
|
| 683 |
+
|
| 684 |
+
# Some parts of SymPy have difficulty computing series expansions with
|
| 685 |
+
# non-integral exponents. The following heuristic improves the situation:
|
| 686 |
+
exponent = reduce(ilcm, denominators, 1)
|
| 687 |
+
f = f.subs({wsym: wsym**exponent})
|
| 688 |
+
logw /= exponent
|
| 689 |
+
|
| 690 |
+
# bottom_up function is required for a specific case - when f is
|
| 691 |
+
# -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p). No current simplification
|
| 692 |
+
# methods reduce this to 0 while not expanding polynomials.
|
| 693 |
+
f = bottom_up(f, lambda w: getattr(w, 'normal', lambda: w)())
|
| 694 |
+
f = expand_mul(f)
|
| 695 |
+
|
| 696 |
+
return f, logw
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
def gruntz(e, z, z0, dir="+"):
|
| 700 |
+
"""
|
| 701 |
+
Compute the limit of e(z) at the point z0 using the Gruntz algorithm.
|
| 702 |
+
|
| 703 |
+
Explanation
|
| 704 |
+
===========
|
| 705 |
+
|
| 706 |
+
``z0`` can be any expression, including oo and -oo.
|
| 707 |
+
|
| 708 |
+
For ``dir="+"`` (default) it calculates the limit from the right
|
| 709 |
+
(z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
|
| 710 |
+
(oo or -oo), the dir argument does not matter.
|
| 711 |
+
|
| 712 |
+
This algorithm is fully described in the module docstring in the gruntz.py
|
| 713 |
+
file. It relies heavily on the series expansion. Most frequently, gruntz()
|
| 714 |
+
is only used if the faster limit() function (which uses heuristics) fails.
|
| 715 |
+
"""
|
| 716 |
+
if not z.is_symbol:
|
| 717 |
+
raise NotImplementedError("Second argument must be a Symbol")
|
| 718 |
+
|
| 719 |
+
# convert all limits to the limit z->oo; sign of z is handled in limitinf
|
| 720 |
+
r = None
|
| 721 |
+
if z0 in (oo, I*oo):
|
| 722 |
+
e0 = e
|
| 723 |
+
elif z0 in (-oo, -I*oo):
|
| 724 |
+
e0 = e.subs(z, -z)
|
| 725 |
+
else:
|
| 726 |
+
if str(dir) == "-":
|
| 727 |
+
e0 = e.subs(z, z0 - 1/z)
|
| 728 |
+
elif str(dir) == "+":
|
| 729 |
+
e0 = e.subs(z, z0 + 1/z)
|
| 730 |
+
else:
|
| 731 |
+
raise NotImplementedError("dir must be '+' or '-'")
|
| 732 |
+
|
| 733 |
+
r = limitinf(e0, z)
|
| 734 |
+
|
| 735 |
+
# This is a bit of a heuristic for nice results... we always rewrite
|
| 736 |
+
# tractable functions in terms of familiar intractable ones.
|
| 737 |
+
# It might be nicer to rewrite the exactly to what they were initially,
|
| 738 |
+
# but that would take some work to implement.
|
| 739 |
+
return r.rewrite('intractable', deep=True)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/kauers.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def finite_diff(expression, variable, increment=1):
|
| 2 |
+
"""
|
| 3 |
+
Takes as input a polynomial expression and the variable used to construct
|
| 4 |
+
it and returns the difference between function's value when the input is
|
| 5 |
+
incremented to 1 and the original function value. If you want an increment
|
| 6 |
+
other than one supply it as a third argument.
|
| 7 |
+
|
| 8 |
+
Examples
|
| 9 |
+
========
|
| 10 |
+
|
| 11 |
+
>>> from sympy.abc import x, y, z
|
| 12 |
+
>>> from sympy.series.kauers import finite_diff
|
| 13 |
+
>>> finite_diff(x**2, x)
|
| 14 |
+
2*x + 1
|
| 15 |
+
>>> finite_diff(y**3 + 2*y**2 + 3*y + 4, y)
|
| 16 |
+
3*y**2 + 7*y + 6
|
| 17 |
+
>>> finite_diff(x**2 + 3*x + 8, x, 2)
|
| 18 |
+
4*x + 10
|
| 19 |
+
>>> finite_diff(z**3 + 8*z, z, 3)
|
| 20 |
+
9*z**2 + 27*z + 51
|
| 21 |
+
"""
|
| 22 |
+
expression = expression.expand()
|
| 23 |
+
expression2 = expression.subs(variable, variable + increment)
|
| 24 |
+
expression2 = expression2.expand()
|
| 25 |
+
return expression2 - expression
|
| 26 |
+
|
| 27 |
+
def finite_diff_kauers(sum):
|
| 28 |
+
"""
|
| 29 |
+
Takes as input a Sum instance and returns the difference between the sum
|
| 30 |
+
with the upper index incremented by 1 and the original sum. For example,
|
| 31 |
+
if S(n) is a sum, then finite_diff_kauers will return S(n + 1) - S(n).
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
========
|
| 35 |
+
|
| 36 |
+
>>> from sympy.series.kauers import finite_diff_kauers
|
| 37 |
+
>>> from sympy import Sum
|
| 38 |
+
>>> from sympy.abc import x, y, m, n, k
|
| 39 |
+
>>> finite_diff_kauers(Sum(k, (k, 1, n)))
|
| 40 |
+
n + 1
|
| 41 |
+
>>> finite_diff_kauers(Sum(1/k, (k, 1, n)))
|
| 42 |
+
1/(n + 1)
|
| 43 |
+
>>> finite_diff_kauers(Sum((x*y**2), (x, 1, n), (y, 1, m)))
|
| 44 |
+
(m + 1)**2*(n + 1)
|
| 45 |
+
>>> finite_diff_kauers(Sum((x*y), (x, 1, m), (y, 1, n)))
|
| 46 |
+
(m + 1)*(n + 1)
|
| 47 |
+
"""
|
| 48 |
+
function = sum.function
|
| 49 |
+
for l in sum.limits:
|
| 50 |
+
function = function.subs(l[0], l[- 1] + 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.calculus.accumulationbounds import AccumBounds
|
| 2 |
+
from sympy.core import S, Symbol, Add, sympify, Expr, PoleError, Mul
|
| 3 |
+
from sympy.core.exprtools import factor_terms
|
| 4 |
+
from sympy.core.numbers import Float, _illegal
|
| 5 |
+
from sympy.functions.combinatorial.factorials import factorial
|
| 6 |
+
from sympy.functions.elementary.complexes import (Abs, sign, arg, re)
|
| 7 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 8 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 9 |
+
from sympy.polys import PolynomialError, factor
|
| 10 |
+
from sympy.series.order import Order
|
| 11 |
+
from .gruntz import gruntz
|
| 12 |
+
|
| 13 |
+
def limit(e, z, z0, dir="+"):
|
| 14 |
+
"""Computes the limit of ``e(z)`` at the point ``z0``.
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
==========
|
| 18 |
+
|
| 19 |
+
e : expression, the limit of which is to be taken
|
| 20 |
+
|
| 21 |
+
z : symbol representing the variable in the limit.
|
| 22 |
+
Other symbols are treated as constants. Multivariate limits
|
| 23 |
+
are not supported.
|
| 24 |
+
|
| 25 |
+
z0 : the value toward which ``z`` tends. Can be any expression,
|
| 26 |
+
including ``oo`` and ``-oo``.
|
| 27 |
+
|
| 28 |
+
dir : string, optional (default: "+")
|
| 29 |
+
The limit is bi-directional if ``dir="+-"``, from the right
|
| 30 |
+
(z->z0+) if ``dir="+"``, and from the left (z->z0-) if
|
| 31 |
+
``dir="-"``. For infinite ``z0`` (``oo`` or ``-oo``), the ``dir``
|
| 32 |
+
argument is determined from the direction of the infinity
|
| 33 |
+
(i.e., ``dir="-"`` for ``oo``).
|
| 34 |
+
|
| 35 |
+
Examples
|
| 36 |
+
========
|
| 37 |
+
|
| 38 |
+
>>> from sympy import limit, sin, oo
|
| 39 |
+
>>> from sympy.abc import x
|
| 40 |
+
>>> limit(sin(x)/x, x, 0)
|
| 41 |
+
1
|
| 42 |
+
>>> limit(1/x, x, 0) # default dir='+'
|
| 43 |
+
oo
|
| 44 |
+
>>> limit(1/x, x, 0, dir="-")
|
| 45 |
+
-oo
|
| 46 |
+
>>> limit(1/x, x, 0, dir='+-')
|
| 47 |
+
zoo
|
| 48 |
+
>>> limit(1/x, x, oo)
|
| 49 |
+
0
|
| 50 |
+
|
| 51 |
+
Notes
|
| 52 |
+
=====
|
| 53 |
+
|
| 54 |
+
First we try some heuristics for easy and frequent cases like "x", "1/x",
|
| 55 |
+
"x**2" and similar, so that it's fast. For all other cases, we use the
|
| 56 |
+
Gruntz algorithm (see the gruntz() function).
|
| 57 |
+
|
| 58 |
+
See Also
|
| 59 |
+
========
|
| 60 |
+
|
| 61 |
+
limit_seq : returns the limit of a sequence.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
return Limit(e, z, z0, dir).doit(deep=False)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def heuristics(e, z, z0, dir):
|
| 68 |
+
"""Computes the limit of an expression term-wise.
|
| 69 |
+
Parameters are the same as for the ``limit`` function.
|
| 70 |
+
Works with the arguments of expression ``e`` one by one, computing
|
| 71 |
+
the limit of each and then combining the results. This approach
|
| 72 |
+
works only for simple limits, but it is fast.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
rv = None
|
| 76 |
+
if z0 is S.Infinity:
|
| 77 |
+
rv = limit(e.subs(z, 1/z), z, S.Zero, "+")
|
| 78 |
+
if isinstance(rv, Limit):
|
| 79 |
+
return
|
| 80 |
+
elif e.is_Mul or e.is_Add or e.is_Pow or e.is_Function:
|
| 81 |
+
r = []
|
| 82 |
+
from sympy.simplify.simplify import together
|
| 83 |
+
for a in e.args:
|
| 84 |
+
l = limit(a, z, z0, dir)
|
| 85 |
+
if l.has(S.Infinity) and l.is_finite is None:
|
| 86 |
+
if isinstance(e, Add):
|
| 87 |
+
m = factor_terms(e)
|
| 88 |
+
if not isinstance(m, Mul): # try together
|
| 89 |
+
m = together(m)
|
| 90 |
+
if not isinstance(m, Mul): # try factor if the previous methods failed
|
| 91 |
+
m = factor(e)
|
| 92 |
+
if isinstance(m, Mul):
|
| 93 |
+
return heuristics(m, z, z0, dir)
|
| 94 |
+
return
|
| 95 |
+
return
|
| 96 |
+
elif isinstance(l, Limit):
|
| 97 |
+
return
|
| 98 |
+
elif l is S.NaN:
|
| 99 |
+
return
|
| 100 |
+
else:
|
| 101 |
+
r.append(l)
|
| 102 |
+
if r:
|
| 103 |
+
rv = e.func(*r)
|
| 104 |
+
if rv is S.NaN and e.is_Mul and any(isinstance(rr, AccumBounds) for rr in r):
|
| 105 |
+
r2 = []
|
| 106 |
+
e2 = []
|
| 107 |
+
for ii, rval in enumerate(r):
|
| 108 |
+
if isinstance(rval, AccumBounds):
|
| 109 |
+
r2.append(rval)
|
| 110 |
+
else:
|
| 111 |
+
e2.append(e.args[ii])
|
| 112 |
+
|
| 113 |
+
if len(e2) > 0:
|
| 114 |
+
e3 = Mul(*e2).simplify()
|
| 115 |
+
l = limit(e3, z, z0, dir)
|
| 116 |
+
rv = l * Mul(*r2)
|
| 117 |
+
|
| 118 |
+
if rv is S.NaN:
|
| 119 |
+
try:
|
| 120 |
+
from sympy.simplify.ratsimp import ratsimp
|
| 121 |
+
rat_e = ratsimp(e)
|
| 122 |
+
except PolynomialError:
|
| 123 |
+
return
|
| 124 |
+
if rat_e is S.NaN or rat_e == e:
|
| 125 |
+
return
|
| 126 |
+
return limit(rat_e, z, z0, dir)
|
| 127 |
+
return rv
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class Limit(Expr):
|
| 131 |
+
"""Represents an unevaluated limit.
|
| 132 |
+
|
| 133 |
+
Examples
|
| 134 |
+
========
|
| 135 |
+
|
| 136 |
+
>>> from sympy import Limit, sin
|
| 137 |
+
>>> from sympy.abc import x
|
| 138 |
+
>>> Limit(sin(x)/x, x, 0)
|
| 139 |
+
Limit(sin(x)/x, x, 0, dir='+')
|
| 140 |
+
>>> Limit(1/x, x, 0, dir="-")
|
| 141 |
+
Limit(1/x, x, 0, dir='-')
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
def __new__(cls, e, z, z0, dir="+"):
|
| 146 |
+
e = sympify(e)
|
| 147 |
+
z = sympify(z)
|
| 148 |
+
z0 = sympify(z0)
|
| 149 |
+
|
| 150 |
+
if z0 in (S.Infinity, S.ImaginaryUnit*S.Infinity):
|
| 151 |
+
dir = "-"
|
| 152 |
+
elif z0 in (S.NegativeInfinity, S.ImaginaryUnit*S.NegativeInfinity):
|
| 153 |
+
dir = "+"
|
| 154 |
+
|
| 155 |
+
if(z0.has(z)):
|
| 156 |
+
raise NotImplementedError("Limits approaching a variable point are"
|
| 157 |
+
" not supported (%s -> %s)" % (z, z0))
|
| 158 |
+
if isinstance(dir, str):
|
| 159 |
+
dir = Symbol(dir)
|
| 160 |
+
elif not isinstance(dir, Symbol):
|
| 161 |
+
raise TypeError("direction must be of type basestring or "
|
| 162 |
+
"Symbol, not %s" % type(dir))
|
| 163 |
+
if str(dir) not in ('+', '-', '+-'):
|
| 164 |
+
raise ValueError("direction must be one of '+', '-' "
|
| 165 |
+
"or '+-', not %s" % dir)
|
| 166 |
+
|
| 167 |
+
obj = Expr.__new__(cls)
|
| 168 |
+
obj._args = (e, z, z0, dir)
|
| 169 |
+
return obj
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def free_symbols(self):
|
| 174 |
+
e = self.args[0]
|
| 175 |
+
isyms = e.free_symbols
|
| 176 |
+
isyms.difference_update(self.args[1].free_symbols)
|
| 177 |
+
isyms.update(self.args[2].free_symbols)
|
| 178 |
+
return isyms
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def pow_heuristics(self, e):
|
| 182 |
+
_, z, z0, _ = self.args
|
| 183 |
+
b1, e1 = e.base, e.exp
|
| 184 |
+
if not b1.has(z):
|
| 185 |
+
res = limit(e1*log(b1), z, z0)
|
| 186 |
+
return exp(res)
|
| 187 |
+
|
| 188 |
+
ex_lim = limit(e1, z, z0)
|
| 189 |
+
base_lim = limit(b1, z, z0)
|
| 190 |
+
|
| 191 |
+
if base_lim is S.One:
|
| 192 |
+
if ex_lim in (S.Infinity, S.NegativeInfinity):
|
| 193 |
+
res = limit(e1*(b1 - 1), z, z0)
|
| 194 |
+
return exp(res)
|
| 195 |
+
if base_lim is S.NegativeInfinity and ex_lim is S.Infinity:
|
| 196 |
+
return S.ComplexInfinity
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def doit(self, **hints):
|
| 200 |
+
"""Evaluates the limit.
|
| 201 |
+
|
| 202 |
+
Parameters
|
| 203 |
+
==========
|
| 204 |
+
|
| 205 |
+
deep : bool, optional (default: True)
|
| 206 |
+
Invoke the ``doit`` method of the expressions involved before
|
| 207 |
+
taking the limit.
|
| 208 |
+
|
| 209 |
+
hints : optional keyword arguments
|
| 210 |
+
To be passed to ``doit`` methods; only used if deep is True.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
e, z, z0, dir = self.args
|
| 214 |
+
|
| 215 |
+
if str(dir) == '+-':
|
| 216 |
+
r = limit(e, z, z0, dir='+')
|
| 217 |
+
l = limit(e, z, z0, dir='-')
|
| 218 |
+
if isinstance(r, Limit) and isinstance(l, Limit):
|
| 219 |
+
if r.args[0] == l.args[0]:
|
| 220 |
+
return self
|
| 221 |
+
if r == l:
|
| 222 |
+
return l
|
| 223 |
+
if r.is_infinite and l.is_infinite:
|
| 224 |
+
return S.ComplexInfinity
|
| 225 |
+
raise ValueError("The limit does not exist since "
|
| 226 |
+
"left hand limit = %s and right hand limit = %s"
|
| 227 |
+
% (l, r))
|
| 228 |
+
|
| 229 |
+
if z0 is S.ComplexInfinity:
|
| 230 |
+
raise NotImplementedError("Limits at complex "
|
| 231 |
+
"infinity are not implemented")
|
| 232 |
+
|
| 233 |
+
if z0.is_infinite:
|
| 234 |
+
cdir = sign(z0)
|
| 235 |
+
cdir = cdir/abs(cdir)
|
| 236 |
+
e = e.subs(z, cdir*z)
|
| 237 |
+
dir = "-"
|
| 238 |
+
z0 = S.Infinity
|
| 239 |
+
|
| 240 |
+
if hints.get('deep', True):
|
| 241 |
+
e = e.doit(**hints)
|
| 242 |
+
z = z.doit(**hints)
|
| 243 |
+
z0 = z0.doit(**hints)
|
| 244 |
+
|
| 245 |
+
if e == z:
|
| 246 |
+
return z0
|
| 247 |
+
|
| 248 |
+
if not e.has(z):
|
| 249 |
+
return e
|
| 250 |
+
|
| 251 |
+
if z0 is S.NaN:
|
| 252 |
+
return S.NaN
|
| 253 |
+
|
| 254 |
+
if e.has(*_illegal):
|
| 255 |
+
return self
|
| 256 |
+
|
| 257 |
+
if e.is_Order:
|
| 258 |
+
return Order(limit(e.expr, z, z0), *e.args[1:])
|
| 259 |
+
|
| 260 |
+
cdir = 0
|
| 261 |
+
if str(dir) == "+":
|
| 262 |
+
cdir = 1
|
| 263 |
+
elif str(dir) == "-":
|
| 264 |
+
cdir = -1
|
| 265 |
+
|
| 266 |
+
def set_signs(expr):
|
| 267 |
+
if not expr.args:
|
| 268 |
+
return expr
|
| 269 |
+
newargs = tuple(set_signs(arg) for arg in expr.args)
|
| 270 |
+
if newargs != expr.args:
|
| 271 |
+
expr = expr.func(*newargs)
|
| 272 |
+
abs_flag = isinstance(expr, Abs)
|
| 273 |
+
arg_flag = isinstance(expr, arg)
|
| 274 |
+
sign_flag = isinstance(expr, sign)
|
| 275 |
+
if abs_flag or sign_flag or arg_flag:
|
| 276 |
+
sig = limit(expr.args[0], z, z0, dir)
|
| 277 |
+
if sig.is_zero:
|
| 278 |
+
sig = limit(1/expr.args[0], z, z0, dir)
|
| 279 |
+
if sig.is_extended_real:
|
| 280 |
+
if (sig < 0) == True:
|
| 281 |
+
return (-expr.args[0] if abs_flag else
|
| 282 |
+
S.NegativeOne if sign_flag else S.Pi)
|
| 283 |
+
elif (sig > 0) == True:
|
| 284 |
+
return (expr.args[0] if abs_flag else
|
| 285 |
+
S.One if sign_flag else S.Zero)
|
| 286 |
+
return expr
|
| 287 |
+
|
| 288 |
+
if e.has(Float):
|
| 289 |
+
# Convert floats like 0.5 to exact SymPy numbers like S.Half, to
|
| 290 |
+
# prevent rounding errors which can lead to unexpected execution
|
| 291 |
+
# of conditional blocks that work on comparisons
|
| 292 |
+
# Also see comments in https://github.com/sympy/sympy/issues/19453
|
| 293 |
+
from sympy.simplify.simplify import nsimplify
|
| 294 |
+
e = nsimplify(e)
|
| 295 |
+
e = set_signs(e)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
if e.is_meromorphic(z, z0):
|
| 299 |
+
if z0 is S.Infinity:
|
| 300 |
+
newe = e.subs(z, 1/z)
|
| 301 |
+
# cdir changes sign as oo- should become 0+
|
| 302 |
+
cdir = -cdir
|
| 303 |
+
else:
|
| 304 |
+
newe = e.subs(z, z + z0)
|
| 305 |
+
try:
|
| 306 |
+
coeff, ex = newe.leadterm(z, cdir=cdir)
|
| 307 |
+
except ValueError:
|
| 308 |
+
pass
|
| 309 |
+
else:
|
| 310 |
+
if ex > 0:
|
| 311 |
+
return S.Zero
|
| 312 |
+
elif ex == 0:
|
| 313 |
+
return coeff
|
| 314 |
+
if cdir == 1 or not(int(ex) & 1):
|
| 315 |
+
return S.Infinity*sign(coeff)
|
| 316 |
+
elif cdir == -1:
|
| 317 |
+
return S.NegativeInfinity*sign(coeff)
|
| 318 |
+
else:
|
| 319 |
+
return S.ComplexInfinity
|
| 320 |
+
|
| 321 |
+
if z0 is S.Infinity:
|
| 322 |
+
if e.is_Mul:
|
| 323 |
+
e = factor_terms(e)
|
| 324 |
+
newe = e.subs(z, 1/z)
|
| 325 |
+
# cdir changes sign as oo- should become 0+
|
| 326 |
+
cdir = -cdir
|
| 327 |
+
else:
|
| 328 |
+
newe = e.subs(z, z + z0)
|
| 329 |
+
try:
|
| 330 |
+
coeff, ex = newe.leadterm(z, cdir=cdir)
|
| 331 |
+
except (ValueError, NotImplementedError, PoleError):
|
| 332 |
+
# The NotImplementedError catching is for custom functions
|
| 333 |
+
from sympy.simplify.powsimp import powsimp
|
| 334 |
+
e = powsimp(e)
|
| 335 |
+
if e.is_Pow:
|
| 336 |
+
r = self.pow_heuristics(e)
|
| 337 |
+
if r is not None:
|
| 338 |
+
return r
|
| 339 |
+
try:
|
| 340 |
+
coeff = newe.as_leading_term(z, cdir=cdir)
|
| 341 |
+
if coeff != newe and (coeff.has(exp) or coeff.has(S.Exp1)):
|
| 342 |
+
return gruntz(coeff, z, 0, "-" if re(cdir).is_negative else "+")
|
| 343 |
+
except (ValueError, NotImplementedError, PoleError):
|
| 344 |
+
pass
|
| 345 |
+
else:
|
| 346 |
+
if isinstance(coeff, AccumBounds) and ex == S.Zero:
|
| 347 |
+
return coeff
|
| 348 |
+
if coeff.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN):
|
| 349 |
+
return self
|
| 350 |
+
if not coeff.has(z):
|
| 351 |
+
if ex.is_positive:
|
| 352 |
+
return S.Zero
|
| 353 |
+
elif ex == 0:
|
| 354 |
+
return coeff
|
| 355 |
+
elif ex.is_negative:
|
| 356 |
+
if cdir == 1:
|
| 357 |
+
return S.Infinity*sign(coeff)
|
| 358 |
+
elif cdir == -1:
|
| 359 |
+
return S.NegativeInfinity*sign(coeff)*S.NegativeOne**(S.One + ex)
|
| 360 |
+
else:
|
| 361 |
+
return S.ComplexInfinity
|
| 362 |
+
else:
|
| 363 |
+
raise NotImplementedError("Not sure of sign of %s" % ex)
|
| 364 |
+
|
| 365 |
+
# gruntz fails on factorials but works with the gamma function
|
| 366 |
+
# If no factorial term is present, e should remain unchanged.
|
| 367 |
+
# factorial is defined to be zero for negative inputs (which
|
| 368 |
+
# differs from gamma) so only rewrite for positive z0.
|
| 369 |
+
if z0.is_extended_positive:
|
| 370 |
+
e = e.rewrite(factorial, gamma)
|
| 371 |
+
|
| 372 |
+
l = None
|
| 373 |
+
|
| 374 |
+
try:
|
| 375 |
+
r = gruntz(e, z, z0, dir)
|
| 376 |
+
if r is S.NaN or l is S.NaN:
|
| 377 |
+
raise PoleError()
|
| 378 |
+
except (PoleError, ValueError):
|
| 379 |
+
if l is not None:
|
| 380 |
+
raise
|
| 381 |
+
r = heuristics(e, z, z0, dir)
|
| 382 |
+
if r is None:
|
| 383 |
+
return self
|
| 384 |
+
|
| 385 |
+
return r
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/limitseq.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Limits of sequences"""
|
| 2 |
+
|
| 3 |
+
from sympy.calculus.accumulationbounds import AccumulationBounds
|
| 4 |
+
from sympy.core.add import Add
|
| 5 |
+
from sympy.core.function import PoleError
|
| 6 |
+
from sympy.core.power import Pow
|
| 7 |
+
from sympy.core.singleton import S
|
| 8 |
+
from sympy.core.symbol import Dummy
|
| 9 |
+
from sympy.core.sympify import sympify
|
| 10 |
+
from sympy.functions.combinatorial.numbers import fibonacci
|
| 11 |
+
from sympy.functions.combinatorial.factorials import factorial, subfactorial
|
| 12 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 13 |
+
from sympy.functions.elementary.complexes import Abs
|
| 14 |
+
from sympy.functions.elementary.miscellaneous import Max, Min
|
| 15 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
| 16 |
+
from sympy.series.limits import Limit
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def difference_delta(expr, n=None, step=1):
|
| 20 |
+
"""Difference Operator.
|
| 21 |
+
|
| 22 |
+
Explanation
|
| 23 |
+
===========
|
| 24 |
+
|
| 25 |
+
Discrete analog of differential operator. Given a sequence x[n],
|
| 26 |
+
returns the sequence x[n + step] - x[n].
|
| 27 |
+
|
| 28 |
+
Examples
|
| 29 |
+
========
|
| 30 |
+
|
| 31 |
+
>>> from sympy import difference_delta as dd
|
| 32 |
+
>>> from sympy.abc import n
|
| 33 |
+
>>> dd(n*(n + 1), n)
|
| 34 |
+
2*n + 2
|
| 35 |
+
>>> dd(n*(n + 1), n, 2)
|
| 36 |
+
4*n + 6
|
| 37 |
+
|
| 38 |
+
References
|
| 39 |
+
==========
|
| 40 |
+
|
| 41 |
+
.. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html
|
| 42 |
+
"""
|
| 43 |
+
expr = sympify(expr)
|
| 44 |
+
|
| 45 |
+
if n is None:
|
| 46 |
+
f = expr.free_symbols
|
| 47 |
+
if len(f) == 1:
|
| 48 |
+
n = f.pop()
|
| 49 |
+
elif len(f) == 0:
|
| 50 |
+
return S.Zero
|
| 51 |
+
else:
|
| 52 |
+
raise ValueError("Since there is more than one variable in the"
|
| 53 |
+
" expression, a variable must be supplied to"
|
| 54 |
+
" take the difference of %s" % expr)
|
| 55 |
+
step = sympify(step)
|
| 56 |
+
if step.is_number is False or step.is_finite is False:
|
| 57 |
+
raise ValueError("Step should be a finite number.")
|
| 58 |
+
|
| 59 |
+
if hasattr(expr, '_eval_difference_delta'):
|
| 60 |
+
result = expr._eval_difference_delta(n, step)
|
| 61 |
+
if result:
|
| 62 |
+
return result
|
| 63 |
+
|
| 64 |
+
return expr.subs(n, n + step) - expr
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def dominant(expr, n):
|
| 68 |
+
"""Finds the dominant term in a sum, that is a term that dominates
|
| 69 |
+
every other term.
|
| 70 |
+
|
| 71 |
+
Explanation
|
| 72 |
+
===========
|
| 73 |
+
|
| 74 |
+
If limit(a/b, n, oo) is oo then a dominates b.
|
| 75 |
+
If limit(a/b, n, oo) is 0 then b dominates a.
|
| 76 |
+
Otherwise, a and b are comparable.
|
| 77 |
+
|
| 78 |
+
If there is no unique dominant term, then returns ``None``.
|
| 79 |
+
|
| 80 |
+
Examples
|
| 81 |
+
========
|
| 82 |
+
|
| 83 |
+
>>> from sympy import Sum
|
| 84 |
+
>>> from sympy.series.limitseq import dominant
|
| 85 |
+
>>> from sympy.abc import n, k
|
| 86 |
+
>>> dominant(5*n**3 + 4*n**2 + n + 1, n)
|
| 87 |
+
5*n**3
|
| 88 |
+
>>> dominant(2**n + Sum(k, (k, 0, n)), n)
|
| 89 |
+
2**n
|
| 90 |
+
|
| 91 |
+
See Also
|
| 92 |
+
========
|
| 93 |
+
|
| 94 |
+
sympy.series.limitseq.dominant
|
| 95 |
+
"""
|
| 96 |
+
terms = Add.make_args(expr.expand(func=True))
|
| 97 |
+
term0 = terms[-1]
|
| 98 |
+
comp = [term0] # comparable terms
|
| 99 |
+
for t in terms[:-1]:
|
| 100 |
+
r = term0/t
|
| 101 |
+
e = r.gammasimp()
|
| 102 |
+
if e == r:
|
| 103 |
+
e = r.factor()
|
| 104 |
+
l = limit_seq(e, n)
|
| 105 |
+
if l is None:
|
| 106 |
+
return None
|
| 107 |
+
elif l.is_zero:
|
| 108 |
+
term0 = t
|
| 109 |
+
comp = [term0]
|
| 110 |
+
elif l not in [S.Infinity, S.NegativeInfinity]:
|
| 111 |
+
comp.append(t)
|
| 112 |
+
if len(comp) > 1:
|
| 113 |
+
return None
|
| 114 |
+
return term0
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _limit_inf(expr, n):
|
| 118 |
+
try:
|
| 119 |
+
return Limit(expr, n, S.Infinity).doit(deep=False)
|
| 120 |
+
except (NotImplementedError, PoleError):
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _limit_seq(expr, n, trials):
|
| 125 |
+
from sympy.concrete.summations import Sum
|
| 126 |
+
|
| 127 |
+
for i in range(trials):
|
| 128 |
+
if not expr.has(Sum):
|
| 129 |
+
result = _limit_inf(expr, n)
|
| 130 |
+
if result is not None:
|
| 131 |
+
return result
|
| 132 |
+
|
| 133 |
+
num, den = expr.as_numer_denom()
|
| 134 |
+
if not den.has(n) or not num.has(n):
|
| 135 |
+
result = _limit_inf(expr.doit(), n)
|
| 136 |
+
if result is not None:
|
| 137 |
+
return result
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
num, den = (difference_delta(t.expand(), n) for t in [num, den])
|
| 141 |
+
expr = (num / den).gammasimp()
|
| 142 |
+
|
| 143 |
+
if not expr.has(Sum):
|
| 144 |
+
result = _limit_inf(expr, n)
|
| 145 |
+
if result is not None:
|
| 146 |
+
return result
|
| 147 |
+
|
| 148 |
+
num, den = expr.as_numer_denom()
|
| 149 |
+
|
| 150 |
+
num = dominant(num, n)
|
| 151 |
+
if num is None:
|
| 152 |
+
return None
|
| 153 |
+
|
| 154 |
+
den = dominant(den, n)
|
| 155 |
+
if den is None:
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
expr = (num / den).gammasimp()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def limit_seq(expr, n=None, trials=5):
|
| 162 |
+
"""Finds the limit of a sequence as index ``n`` tends to infinity.
|
| 163 |
+
|
| 164 |
+
Parameters
|
| 165 |
+
==========
|
| 166 |
+
|
| 167 |
+
expr : Expr
|
| 168 |
+
SymPy expression for the ``n-th`` term of the sequence
|
| 169 |
+
n : Symbol, optional
|
| 170 |
+
The index of the sequence, an integer that tends to positive
|
| 171 |
+
infinity. If None, inferred from the expression unless it has
|
| 172 |
+
multiple symbols.
|
| 173 |
+
trials: int, optional
|
| 174 |
+
The algorithm is highly recursive. ``trials`` is a safeguard from
|
| 175 |
+
infinite recursion in case the limit is not easily computed by the
|
| 176 |
+
algorithm. Try increasing ``trials`` if the algorithm returns ``None``.
|
| 177 |
+
|
| 178 |
+
Admissible Terms
|
| 179 |
+
================
|
| 180 |
+
|
| 181 |
+
The algorithm is designed for sequences built from rational functions,
|
| 182 |
+
indefinite sums, and indefinite products over an indeterminate n. Terms of
|
| 183 |
+
alternating sign are also allowed, but more complex oscillatory behavior is
|
| 184 |
+
not supported.
|
| 185 |
+
|
| 186 |
+
Examples
|
| 187 |
+
========
|
| 188 |
+
|
| 189 |
+
>>> from sympy import limit_seq, Sum, binomial
|
| 190 |
+
>>> from sympy.abc import n, k, m
|
| 191 |
+
>>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n)
|
| 192 |
+
5/3
|
| 193 |
+
>>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n)
|
| 194 |
+
3/4
|
| 195 |
+
>>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n)
|
| 196 |
+
4
|
| 197 |
+
|
| 198 |
+
See Also
|
| 199 |
+
========
|
| 200 |
+
|
| 201 |
+
sympy.series.limitseq.dominant
|
| 202 |
+
|
| 203 |
+
References
|
| 204 |
+
==========
|
| 205 |
+
|
| 206 |
+
.. [1] Computing Limits of Sequences - Manuel Kauers
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
from sympy.concrete.summations import Sum
|
| 210 |
+
if n is None:
|
| 211 |
+
free = expr.free_symbols
|
| 212 |
+
if len(free) == 1:
|
| 213 |
+
n = free.pop()
|
| 214 |
+
elif not free:
|
| 215 |
+
return expr
|
| 216 |
+
else:
|
| 217 |
+
raise ValueError("Expression has more than one variable. "
|
| 218 |
+
"Please specify a variable.")
|
| 219 |
+
elif n not in expr.free_symbols:
|
| 220 |
+
return expr
|
| 221 |
+
|
| 222 |
+
expr = expr.rewrite(fibonacci, S.GoldenRatio)
|
| 223 |
+
expr = expr.rewrite(factorial, subfactorial, gamma)
|
| 224 |
+
n_ = Dummy("n", integer=True, positive=True)
|
| 225 |
+
n1 = Dummy("n", odd=True, positive=True)
|
| 226 |
+
n2 = Dummy("n", even=True, positive=True)
|
| 227 |
+
|
| 228 |
+
# If there is a negative term raised to a power involving n, or a
|
| 229 |
+
# trigonometric function, then consider even and odd n separately.
|
| 230 |
+
powers = (p.as_base_exp() for p in expr.atoms(Pow))
|
| 231 |
+
if (any(b.is_negative and e.has(n) for b, e in powers) or
|
| 232 |
+
expr.has(cos, sin)):
|
| 233 |
+
L1 = _limit_seq(expr.xreplace({n: n1}), n1, trials)
|
| 234 |
+
if L1 is not None:
|
| 235 |
+
L2 = _limit_seq(expr.xreplace({n: n2}), n2, trials)
|
| 236 |
+
if L1 != L2:
|
| 237 |
+
if L1.is_comparable and L2.is_comparable:
|
| 238 |
+
return AccumulationBounds(Min(L1, L2), Max(L1, L2))
|
| 239 |
+
else:
|
| 240 |
+
return None
|
| 241 |
+
else:
|
| 242 |
+
L1 = _limit_seq(expr.xreplace({n: n_}), n_, trials)
|
| 243 |
+
if L1 is not None:
|
| 244 |
+
return L1
|
| 245 |
+
else:
|
| 246 |
+
if expr.is_Add:
|
| 247 |
+
limits = [limit_seq(term, n, trials) for term in expr.args]
|
| 248 |
+
if any(result is None for result in limits):
|
| 249 |
+
return None
|
| 250 |
+
else:
|
| 251 |
+
return Add(*limits)
|
| 252 |
+
# Maybe the absolute value is easier to deal with (though not if
|
| 253 |
+
# it has a Sum). If it tends to 0, the limit is 0.
|
| 254 |
+
elif not expr.has(Sum):
|
| 255 |
+
lim = _limit_seq(Abs(expr.xreplace({n: n_})), n_, trials)
|
| 256 |
+
if lim is not None and lim.is_zero:
|
| 257 |
+
return S.Zero
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/order.py
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import S, sympify, Expr, Dummy, Add, Mul
|
| 2 |
+
from sympy.core.cache import cacheit
|
| 3 |
+
from sympy.core.containers import Tuple
|
| 4 |
+
from sympy.core.function import Function, PoleError, expand_power_base, expand_log
|
| 5 |
+
from sympy.core.sorting import default_sort_key
|
| 6 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 7 |
+
from sympy.sets.sets import Complement
|
| 8 |
+
from sympy.utilities.iterables import uniq, is_sequence
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Order(Expr):
|
| 12 |
+
r""" Represents the limiting behavior of some function.
|
| 13 |
+
|
| 14 |
+
Explanation
|
| 15 |
+
===========
|
| 16 |
+
|
| 17 |
+
The order of a function characterizes the function based on the limiting
|
| 18 |
+
behavior of the function as it goes to some limit. Only taking the limit
|
| 19 |
+
point to be a number is currently supported. This is expressed in
|
| 20 |
+
big O notation [1]_.
|
| 21 |
+
|
| 22 |
+
The formal definition for the order of a function `g(x)` about a point `a`
|
| 23 |
+
is such that `g(x) = O(f(x))` as `x \rightarrow a` if and only if there
|
| 24 |
+
exists a `\delta > 0` and an `M > 0` such that `|g(x)| \leq M|f(x)|` for
|
| 25 |
+
`|x-a| < \delta`. This is equivalent to `\limsup_{x \rightarrow a}
|
| 26 |
+
|g(x)/f(x)| < \infty`.
|
| 27 |
+
|
| 28 |
+
Let's illustrate it on the following example by taking the expansion of
|
| 29 |
+
`\sin(x)` about 0:
|
| 30 |
+
|
| 31 |
+
.. math ::
|
| 32 |
+
\sin(x) = x - x^3/3! + O(x^5)
|
| 33 |
+
|
| 34 |
+
where in this case `O(x^5) = x^5/5! - x^7/7! + \cdots`. By the definition
|
| 35 |
+
of `O`, there is a `\delta > 0` and an `M` such that:
|
| 36 |
+
|
| 37 |
+
.. math ::
|
| 38 |
+
|x^5/5! - x^7/7! + ....| <= M|x^5| \text{ for } |x| < \delta
|
| 39 |
+
|
| 40 |
+
or by the alternate definition:
|
| 41 |
+
|
| 42 |
+
.. math ::
|
| 43 |
+
\lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| < \infty
|
| 44 |
+
|
| 45 |
+
which surely is true, because
|
| 46 |
+
|
| 47 |
+
.. math ::
|
| 48 |
+
\lim_{x \rightarrow 0} | (x^5/5! - x^7/7! + ....) / x^5| = 1/5!
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
As it is usually used, the order of a function can be intuitively thought
|
| 52 |
+
of representing all terms of powers greater than the one specified. For
|
| 53 |
+
example, `O(x^3)` corresponds to any terms proportional to `x^3,
|
| 54 |
+
x^4,\ldots` and any higher power. For a polynomial, this leaves terms
|
| 55 |
+
proportional to `x^2`, `x` and constants.
|
| 56 |
+
|
| 57 |
+
Examples
|
| 58 |
+
========
|
| 59 |
+
|
| 60 |
+
>>> from sympy import O, oo, cos, pi
|
| 61 |
+
>>> from sympy.abc import x, y
|
| 62 |
+
|
| 63 |
+
>>> O(x + x**2)
|
| 64 |
+
O(x)
|
| 65 |
+
>>> O(x + x**2, (x, 0))
|
| 66 |
+
O(x)
|
| 67 |
+
>>> O(x + x**2, (x, oo))
|
| 68 |
+
O(x**2, (x, oo))
|
| 69 |
+
|
| 70 |
+
>>> O(1 + x*y)
|
| 71 |
+
O(1, x, y)
|
| 72 |
+
>>> O(1 + x*y, (x, 0), (y, 0))
|
| 73 |
+
O(1, x, y)
|
| 74 |
+
>>> O(1 + x*y, (x, oo), (y, oo))
|
| 75 |
+
O(x*y, (x, oo), (y, oo))
|
| 76 |
+
|
| 77 |
+
>>> O(1) in O(1, x)
|
| 78 |
+
True
|
| 79 |
+
>>> O(1, x) in O(1)
|
| 80 |
+
False
|
| 81 |
+
>>> O(x) in O(1, x)
|
| 82 |
+
True
|
| 83 |
+
>>> O(x**2) in O(x)
|
| 84 |
+
True
|
| 85 |
+
|
| 86 |
+
>>> O(x)*x
|
| 87 |
+
O(x**2)
|
| 88 |
+
>>> O(x) - O(x)
|
| 89 |
+
O(x)
|
| 90 |
+
>>> O(cos(x))
|
| 91 |
+
O(1)
|
| 92 |
+
>>> O(cos(x), (x, pi/2))
|
| 93 |
+
O(x - pi/2, (x, pi/2))
|
| 94 |
+
|
| 95 |
+
References
|
| 96 |
+
==========
|
| 97 |
+
|
| 98 |
+
.. [1] `Big O notation <https://en.wikipedia.org/wiki/Big_O_notation>`_
|
| 99 |
+
|
| 100 |
+
Notes
|
| 101 |
+
=====
|
| 102 |
+
|
| 103 |
+
In ``O(f(x), x)`` the expression ``f(x)`` is assumed to have a leading
|
| 104 |
+
term. ``O(f(x), x)`` is automatically transformed to
|
| 105 |
+
``O(f(x).as_leading_term(x),x)``.
|
| 106 |
+
|
| 107 |
+
``O(expr*f(x), x)`` is ``O(f(x), x)``
|
| 108 |
+
|
| 109 |
+
``O(expr, x)`` is ``O(1)``
|
| 110 |
+
|
| 111 |
+
``O(0, x)`` is 0.
|
| 112 |
+
|
| 113 |
+
Multivariate O is also supported:
|
| 114 |
+
|
| 115 |
+
``O(f(x, y), x, y)`` is transformed to
|
| 116 |
+
``O(f(x, y).as_leading_term(x,y).as_leading_term(y), x, y)``
|
| 117 |
+
|
| 118 |
+
In the multivariate case, it is assumed the limits w.r.t. the various
|
| 119 |
+
symbols commute.
|
| 120 |
+
|
| 121 |
+
If no symbols are passed then all symbols in the expression are used
|
| 122 |
+
and the limit point is assumed to be zero.
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
is_Order = True
|
| 127 |
+
|
| 128 |
+
__slots__ = ()
|
| 129 |
+
|
| 130 |
+
@cacheit
|
| 131 |
+
def __new__(cls, expr, *args, **kwargs):
|
| 132 |
+
expr = sympify(expr)
|
| 133 |
+
|
| 134 |
+
if not args:
|
| 135 |
+
if expr.is_Order:
|
| 136 |
+
variables = expr.variables
|
| 137 |
+
point = expr.point
|
| 138 |
+
else:
|
| 139 |
+
variables = list(expr.free_symbols)
|
| 140 |
+
point = [S.Zero]*len(variables)
|
| 141 |
+
else:
|
| 142 |
+
args = list(args if is_sequence(args) else [args])
|
| 143 |
+
variables, point = [], []
|
| 144 |
+
if is_sequence(args[0]):
|
| 145 |
+
for a in args:
|
| 146 |
+
v, p = list(map(sympify, a))
|
| 147 |
+
variables.append(v)
|
| 148 |
+
point.append(p)
|
| 149 |
+
else:
|
| 150 |
+
variables = list(map(sympify, args))
|
| 151 |
+
point = [S.Zero]*len(variables)
|
| 152 |
+
|
| 153 |
+
if not all(v.is_symbol for v in variables):
|
| 154 |
+
raise TypeError('Variables are not symbols, got %s' % variables)
|
| 155 |
+
|
| 156 |
+
if len(list(uniq(variables))) != len(variables):
|
| 157 |
+
raise ValueError('Variables are supposed to be unique symbols, got %s' % variables)
|
| 158 |
+
|
| 159 |
+
if expr.is_Order:
|
| 160 |
+
expr_vp = dict(expr.args[1:])
|
| 161 |
+
new_vp = dict(expr_vp)
|
| 162 |
+
vp = dict(zip(variables, point))
|
| 163 |
+
for v, p in vp.items():
|
| 164 |
+
if v in new_vp.keys():
|
| 165 |
+
if p != new_vp[v]:
|
| 166 |
+
raise NotImplementedError(
|
| 167 |
+
"Mixing Order at different points is not supported.")
|
| 168 |
+
else:
|
| 169 |
+
new_vp[v] = p
|
| 170 |
+
if set(expr_vp.keys()) == set(new_vp.keys()):
|
| 171 |
+
return expr
|
| 172 |
+
else:
|
| 173 |
+
variables = list(new_vp.keys())
|
| 174 |
+
point = [new_vp[v] for v in variables]
|
| 175 |
+
|
| 176 |
+
if expr is S.NaN:
|
| 177 |
+
return S.NaN
|
| 178 |
+
|
| 179 |
+
if any(x in p.free_symbols for x in variables for p in point):
|
| 180 |
+
raise ValueError('Got %s as a point.' % point)
|
| 181 |
+
|
| 182 |
+
if variables:
|
| 183 |
+
if any(p != point[0] for p in point):
|
| 184 |
+
raise NotImplementedError(
|
| 185 |
+
"Multivariable orders at different points are not supported.")
|
| 186 |
+
if point[0] in (S.Infinity, S.Infinity*S.ImaginaryUnit):
|
| 187 |
+
s = {k: 1/Dummy() for k in variables}
|
| 188 |
+
rs = {1/v: 1/k for k, v in s.items()}
|
| 189 |
+
ps = [S.Zero for p in point]
|
| 190 |
+
elif point[0] in (S.NegativeInfinity, S.NegativeInfinity*S.ImaginaryUnit):
|
| 191 |
+
s = {k: -1/Dummy() for k in variables}
|
| 192 |
+
rs = {-1/v: -1/k for k, v in s.items()}
|
| 193 |
+
ps = [S.Zero for p in point]
|
| 194 |
+
elif point[0] is not S.Zero:
|
| 195 |
+
s = {k: Dummy() + point[0] for k in variables}
|
| 196 |
+
rs = {(v - point[0]).together(): k - point[0] for k, v in s.items()}
|
| 197 |
+
ps = [S.Zero for p in point]
|
| 198 |
+
else:
|
| 199 |
+
s = ()
|
| 200 |
+
rs = ()
|
| 201 |
+
ps = list(point)
|
| 202 |
+
|
| 203 |
+
expr = expr.subs(s)
|
| 204 |
+
|
| 205 |
+
if expr.is_Add:
|
| 206 |
+
expr = expr.factor()
|
| 207 |
+
|
| 208 |
+
if s:
|
| 209 |
+
args = tuple([r[0] for r in rs.items()])
|
| 210 |
+
else:
|
| 211 |
+
args = tuple(variables)
|
| 212 |
+
|
| 213 |
+
if len(variables) > 1:
|
| 214 |
+
# XXX: better way? We need this expand() to
|
| 215 |
+
# workaround e.g: expr = x*(x + y).
|
| 216 |
+
# (x*(x + y)).as_leading_term(x, y) currently returns
|
| 217 |
+
# x*y (wrong order term!). That's why we want to deal with
|
| 218 |
+
# expand()'ed expr (handled in "if expr.is_Add" branch below).
|
| 219 |
+
expr = expr.expand()
|
| 220 |
+
|
| 221 |
+
old_expr = None
|
| 222 |
+
while old_expr != expr:
|
| 223 |
+
old_expr = expr
|
| 224 |
+
if expr.is_Add:
|
| 225 |
+
lst = expr.extract_leading_order(args)
|
| 226 |
+
expr = Add(*[f.expr for (e, f) in lst])
|
| 227 |
+
|
| 228 |
+
elif expr:
|
| 229 |
+
try:
|
| 230 |
+
expr = expr.as_leading_term(*args)
|
| 231 |
+
except PoleError:
|
| 232 |
+
if isinstance(expr, Function) or\
|
| 233 |
+
all(isinstance(arg, Function) for arg in expr.args):
|
| 234 |
+
# It is not possible to simplify an expression
|
| 235 |
+
# containing only functions (which raise error on
|
| 236 |
+
# call to leading term) further
|
| 237 |
+
pass
|
| 238 |
+
else:
|
| 239 |
+
orders = []
|
| 240 |
+
pts = tuple(zip(args, ps))
|
| 241 |
+
for arg in expr.args:
|
| 242 |
+
try:
|
| 243 |
+
lt = arg.as_leading_term(*args)
|
| 244 |
+
except PoleError:
|
| 245 |
+
lt = arg
|
| 246 |
+
if lt not in args:
|
| 247 |
+
order = Order(lt)
|
| 248 |
+
else:
|
| 249 |
+
order = Order(lt, *pts)
|
| 250 |
+
orders.append(order)
|
| 251 |
+
if expr.is_Add:
|
| 252 |
+
new_expr = Order(Add(*orders), *pts)
|
| 253 |
+
if new_expr.is_Add:
|
| 254 |
+
new_expr = Order(Add(*[a.expr for a in new_expr.args]), *pts)
|
| 255 |
+
expr = new_expr.expr
|
| 256 |
+
elif expr.is_Mul:
|
| 257 |
+
expr = Mul(*[a.expr for a in orders])
|
| 258 |
+
elif expr.is_Pow:
|
| 259 |
+
e = expr.exp
|
| 260 |
+
b = expr.base
|
| 261 |
+
expr = exp(e * log(b))
|
| 262 |
+
|
| 263 |
+
# It would probably be better to handle this somewhere
|
| 264 |
+
# else. This is needed for a testcase in which there is a
|
| 265 |
+
# symbol with the assumptions zero=True.
|
| 266 |
+
if expr.is_zero:
|
| 267 |
+
expr = S.Zero
|
| 268 |
+
else:
|
| 269 |
+
expr = expr.as_independent(*args, as_Add=False)[1]
|
| 270 |
+
|
| 271 |
+
expr = expand_power_base(expr)
|
| 272 |
+
expr = expand_log(expr)
|
| 273 |
+
|
| 274 |
+
if len(args) == 1:
|
| 275 |
+
# The definition of O(f(x)) symbol explicitly stated that
|
| 276 |
+
# the argument of f(x) is irrelevant. That's why we can
|
| 277 |
+
# combine some power exponents (only "on top" of the
|
| 278 |
+
# expression tree for f(x)), e.g.:
|
| 279 |
+
# x**p * (-x)**q -> x**(p+q) for real p, q.
|
| 280 |
+
x = args[0]
|
| 281 |
+
margs = list(Mul.make_args(
|
| 282 |
+
expr.as_independent(x, as_Add=False)[1]))
|
| 283 |
+
|
| 284 |
+
for i, t in enumerate(margs):
|
| 285 |
+
if t.is_Pow:
|
| 286 |
+
b, q = t.args
|
| 287 |
+
if b in (x, -x) and q.is_real and not q.has(x):
|
| 288 |
+
margs[i] = x**q
|
| 289 |
+
elif b.is_Pow and not b.exp.has(x):
|
| 290 |
+
b, r = b.args
|
| 291 |
+
if b in (x, -x) and r.is_real:
|
| 292 |
+
margs[i] = x**(r*q)
|
| 293 |
+
elif b.is_Mul and b.args[0] is S.NegativeOne:
|
| 294 |
+
b = -b
|
| 295 |
+
if b.is_Pow and not b.exp.has(x):
|
| 296 |
+
b, r = b.args
|
| 297 |
+
if b in (x, -x) and r.is_real:
|
| 298 |
+
margs[i] = x**(r*q)
|
| 299 |
+
|
| 300 |
+
expr = Mul(*margs)
|
| 301 |
+
|
| 302 |
+
expr = expr.subs(rs)
|
| 303 |
+
|
| 304 |
+
if expr.is_Order:
|
| 305 |
+
expr = expr.expr
|
| 306 |
+
|
| 307 |
+
if not expr.has(*variables) and not expr.is_zero:
|
| 308 |
+
expr = S.One
|
| 309 |
+
|
| 310 |
+
# create Order instance:
|
| 311 |
+
vp = dict(zip(variables, point))
|
| 312 |
+
variables.sort(key=default_sort_key)
|
| 313 |
+
point = [vp[v] for v in variables]
|
| 314 |
+
args = (expr,) + Tuple(*zip(variables, point))
|
| 315 |
+
obj = Expr.__new__(cls, *args)
|
| 316 |
+
return obj
|
| 317 |
+
|
| 318 |
+
def _eval_nseries(self, x, n, logx, cdir=0):
|
| 319 |
+
return self
|
| 320 |
+
|
| 321 |
+
@property
|
| 322 |
+
def expr(self):
|
| 323 |
+
return self.args[0]
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
def variables(self):
|
| 327 |
+
if self.args[1:]:
|
| 328 |
+
return tuple(x[0] for x in self.args[1:])
|
| 329 |
+
else:
|
| 330 |
+
return ()
|
| 331 |
+
|
| 332 |
+
@property
|
| 333 |
+
def point(self):
|
| 334 |
+
if self.args[1:]:
|
| 335 |
+
return tuple(x[1] for x in self.args[1:])
|
| 336 |
+
else:
|
| 337 |
+
return ()
|
| 338 |
+
|
| 339 |
+
@property
|
| 340 |
+
def free_symbols(self):
|
| 341 |
+
return self.expr.free_symbols | set(self.variables)
|
| 342 |
+
|
| 343 |
+
def _eval_power(b, e):
|
| 344 |
+
if e.is_Number and e.is_nonnegative:
|
| 345 |
+
return b.func(b.expr ** e, *b.args[1:])
|
| 346 |
+
if e == O(1):
|
| 347 |
+
return b
|
| 348 |
+
return
|
| 349 |
+
|
| 350 |
+
def as_expr_variables(self, order_symbols):
|
| 351 |
+
if order_symbols is None:
|
| 352 |
+
order_symbols = self.args[1:]
|
| 353 |
+
else:
|
| 354 |
+
if (not all(o[1] == order_symbols[0][1] for o in order_symbols) and
|
| 355 |
+
not all(p == self.point[0] for p in self.point)): # pragma: no cover
|
| 356 |
+
raise NotImplementedError('Order at points other than 0 '
|
| 357 |
+
'or oo not supported, got %s as a point.' % self.point)
|
| 358 |
+
if order_symbols and order_symbols[0][1] != self.point[0]:
|
| 359 |
+
raise NotImplementedError(
|
| 360 |
+
"Multiplying Order at different points is not supported.")
|
| 361 |
+
order_symbols = dict(order_symbols)
|
| 362 |
+
for s, p in dict(self.args[1:]).items():
|
| 363 |
+
if s not in order_symbols.keys():
|
| 364 |
+
order_symbols[s] = p
|
| 365 |
+
order_symbols = sorted(order_symbols.items(), key=lambda x: default_sort_key(x[0]))
|
| 366 |
+
return self.expr, tuple(order_symbols)
|
| 367 |
+
|
| 368 |
+
def removeO(self):
|
| 369 |
+
return S.Zero
|
| 370 |
+
|
| 371 |
+
def getO(self):
|
| 372 |
+
return self
|
| 373 |
+
|
| 374 |
+
@cacheit
|
| 375 |
+
def contains(self, expr):
|
| 376 |
+
r"""
|
| 377 |
+
Return True if expr belongs to Order(self.expr, \*self.variables).
|
| 378 |
+
Return False if self belongs to expr.
|
| 379 |
+
Return None if the inclusion relation cannot be determined
|
| 380 |
+
(e.g. when self and expr have different symbols).
|
| 381 |
+
"""
|
| 382 |
+
expr = sympify(expr)
|
| 383 |
+
if expr.is_zero:
|
| 384 |
+
return True
|
| 385 |
+
if expr is S.NaN:
|
| 386 |
+
return False
|
| 387 |
+
point = self.point[0] if self.point else S.Zero
|
| 388 |
+
if expr.is_Order:
|
| 389 |
+
if (any(p != point for p in expr.point) or
|
| 390 |
+
any(p != point for p in self.point)):
|
| 391 |
+
return None
|
| 392 |
+
if expr.expr == self.expr:
|
| 393 |
+
# O(1) + O(1), O(1) + O(1, x), etc.
|
| 394 |
+
return all(x in self.args[1:] for x in expr.args[1:])
|
| 395 |
+
if expr.expr.is_Add:
|
| 396 |
+
return all(self.contains(x) for x in expr.expr.args)
|
| 397 |
+
if self.expr.is_Add and point.is_zero:
|
| 398 |
+
return any(self.func(x, *self.args[1:]).contains(expr)
|
| 399 |
+
for x in self.expr.args)
|
| 400 |
+
if self.variables and expr.variables:
|
| 401 |
+
common_symbols = tuple(
|
| 402 |
+
[s for s in self.variables if s in expr.variables])
|
| 403 |
+
elif self.variables:
|
| 404 |
+
common_symbols = self.variables
|
| 405 |
+
else:
|
| 406 |
+
common_symbols = expr.variables
|
| 407 |
+
if not common_symbols:
|
| 408 |
+
return None
|
| 409 |
+
if (self.expr.is_Pow and len(self.variables) == 1
|
| 410 |
+
and self.variables == expr.variables):
|
| 411 |
+
symbol = self.variables[0]
|
| 412 |
+
other = expr.expr.as_independent(symbol, as_Add=False)[1]
|
| 413 |
+
if (other.is_Pow and other.base == symbol and
|
| 414 |
+
self.expr.base == symbol):
|
| 415 |
+
if point.is_zero:
|
| 416 |
+
rv = (self.expr.exp - other.exp).is_nonpositive
|
| 417 |
+
if point.is_infinite:
|
| 418 |
+
rv = (self.expr.exp - other.exp).is_nonnegative
|
| 419 |
+
if rv is not None:
|
| 420 |
+
return rv
|
| 421 |
+
|
| 422 |
+
from sympy.simplify.powsimp import powsimp
|
| 423 |
+
r = None
|
| 424 |
+
ratio = self.expr/expr.expr
|
| 425 |
+
ratio = powsimp(ratio, deep=True, combine='exp')
|
| 426 |
+
for s in common_symbols:
|
| 427 |
+
from sympy.series.limits import Limit
|
| 428 |
+
l = Limit(ratio, s, point).doit(heuristics=False)
|
| 429 |
+
if not isinstance(l, Limit):
|
| 430 |
+
l = l != 0
|
| 431 |
+
else:
|
| 432 |
+
l = None
|
| 433 |
+
if r is None:
|
| 434 |
+
r = l
|
| 435 |
+
else:
|
| 436 |
+
if r != l:
|
| 437 |
+
return
|
| 438 |
+
return r
|
| 439 |
+
|
| 440 |
+
if self.expr.is_Pow and len(self.variables) == 1:
|
| 441 |
+
symbol = self.variables[0]
|
| 442 |
+
other = expr.as_independent(symbol, as_Add=False)[1]
|
| 443 |
+
if (other.is_Pow and other.base == symbol and
|
| 444 |
+
self.expr.base == symbol):
|
| 445 |
+
if point.is_zero:
|
| 446 |
+
rv = (self.expr.exp - other.exp).is_nonpositive
|
| 447 |
+
if point.is_infinite:
|
| 448 |
+
rv = (self.expr.exp - other.exp).is_nonnegative
|
| 449 |
+
if rv is not None:
|
| 450 |
+
return rv
|
| 451 |
+
|
| 452 |
+
obj = self.func(expr, *self.args[1:])
|
| 453 |
+
return self.contains(obj)
|
| 454 |
+
|
| 455 |
+
def __contains__(self, other):
|
| 456 |
+
result = self.contains(other)
|
| 457 |
+
if result is None:
|
| 458 |
+
raise TypeError('contains did not evaluate to a bool')
|
| 459 |
+
return result
|
| 460 |
+
|
| 461 |
+
def _eval_subs(self, old, new):
|
| 462 |
+
if old in self.variables:
|
| 463 |
+
newexpr = self.expr.subs(old, new)
|
| 464 |
+
i = self.variables.index(old)
|
| 465 |
+
newvars = list(self.variables)
|
| 466 |
+
newpt = list(self.point)
|
| 467 |
+
if new.is_symbol:
|
| 468 |
+
newvars[i] = new
|
| 469 |
+
else:
|
| 470 |
+
syms = new.free_symbols
|
| 471 |
+
if len(syms) == 1 or old in syms:
|
| 472 |
+
if old in syms:
|
| 473 |
+
var = self.variables[i]
|
| 474 |
+
else:
|
| 475 |
+
var = syms.pop()
|
| 476 |
+
# First, try to substitute self.point in the "new"
|
| 477 |
+
# expr to see if this is a fixed point.
|
| 478 |
+
# E.g. O(y).subs(y, sin(x))
|
| 479 |
+
point = new.subs(var, self.point[i])
|
| 480 |
+
if point != self.point[i]:
|
| 481 |
+
from sympy.solvers.solveset import solveset
|
| 482 |
+
d = Dummy()
|
| 483 |
+
sol = solveset(old - new.subs(var, d), d)
|
| 484 |
+
if isinstance(sol, Complement):
|
| 485 |
+
e1 = sol.args[0]
|
| 486 |
+
e2 = sol.args[1]
|
| 487 |
+
sol = set(e1) - set(e2)
|
| 488 |
+
res = [dict(zip((d, ), sol))]
|
| 489 |
+
point = d.subs(res[0]).limit(old, self.point[i])
|
| 490 |
+
newvars[i] = var
|
| 491 |
+
newpt[i] = point
|
| 492 |
+
elif old not in syms:
|
| 493 |
+
del newvars[i], newpt[i]
|
| 494 |
+
if not syms and new == self.point[i]:
|
| 495 |
+
newvars.extend(syms)
|
| 496 |
+
newpt.extend([S.Zero]*len(syms))
|
| 497 |
+
else:
|
| 498 |
+
return
|
| 499 |
+
return Order(newexpr, *zip(newvars, newpt))
|
| 500 |
+
|
| 501 |
+
def _eval_conjugate(self):
|
| 502 |
+
expr = self.expr._eval_conjugate()
|
| 503 |
+
if expr is not None:
|
| 504 |
+
return self.func(expr, *self.args[1:])
|
| 505 |
+
|
| 506 |
+
def _eval_derivative(self, x):
|
| 507 |
+
return self.func(self.expr.diff(x), *self.args[1:]) or self
|
| 508 |
+
|
| 509 |
+
def _eval_transpose(self):
|
| 510 |
+
expr = self.expr._eval_transpose()
|
| 511 |
+
if expr is not None:
|
| 512 |
+
return self.func(expr, *self.args[1:])
|
| 513 |
+
|
| 514 |
+
def __neg__(self):
|
| 515 |
+
return self
|
| 516 |
+
|
| 517 |
+
O = Order
|
evalkit_internvl/lib/python3.10/site-packages/sympy/series/residues.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module implements the Residue function and related tools for working
|
| 3 |
+
with residues.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from sympy.core.mul import Mul
|
| 7 |
+
from sympy.core.singleton import S
|
| 8 |
+
from sympy.core.sympify import sympify
|
| 9 |
+
from sympy.utilities.timeutils import timethis
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@timethis('residue')
|
| 13 |
+
def residue(expr, x, x0):
|
| 14 |
+
"""
|
| 15 |
+
Finds the residue of ``expr`` at the point x=x0.
|
| 16 |
+
|
| 17 |
+
The residue is defined as the coefficient of ``1/(x-x0)`` in the power series
|
| 18 |
+
expansion about ``x=x0``.
|
| 19 |
+
|
| 20 |
+
Examples
|
| 21 |
+
========
|
| 22 |
+
|
| 23 |
+
>>> from sympy import Symbol, residue, sin
|
| 24 |
+
>>> x = Symbol("x")
|
| 25 |
+
>>> residue(1/x, x, 0)
|
| 26 |
+
1
|
| 27 |
+
>>> residue(1/x**2, x, 0)
|
| 28 |
+
0
|
| 29 |
+
>>> residue(2/sin(x), x, 0)
|
| 30 |
+
2
|
| 31 |
+
|
| 32 |
+
This function is essential for the Residue Theorem [1].
|
| 33 |
+
|
| 34 |
+
References
|
| 35 |
+
==========
|
| 36 |
+
|
| 37 |
+
.. [1] https://en.wikipedia.org/wiki/Residue_theorem
|
| 38 |
+
"""
|
| 39 |
+
# The current implementation uses series expansion to
|
| 40 |
+
# calculate it. A more general implementation is explained in
|
| 41 |
+
# the section 5.6 of the Bronstein's book {M. Bronstein:
|
| 42 |
+
# Symbolic Integration I, Springer Verlag (2005)}. For purely
|
| 43 |
+
# rational functions, the algorithm is much easier. See
|
| 44 |
+
# sections 2.4, 2.5, and 2.7 (this section actually gives an
|
| 45 |
+
# algorithm for computing any Laurent series coefficient for
|
| 46 |
+
# a rational function). The theory in section 2.4 will help to
|
| 47 |
+
# understand why the resultant works in the general algorithm.
|
| 48 |
+
# For the definition of a resultant, see section 1.4 (and any
|
| 49 |
+
# previous sections for more review).
|
| 50 |
+
|
| 51 |
+
from sympy.series.order import Order
|
| 52 |
+
from sympy.simplify.radsimp import collect
|
| 53 |
+
expr = sympify(expr)
|
| 54 |
+
if x0 != 0:
|
| 55 |
+
expr = expr.subs(x, x + x0)
|
| 56 |
+
for n in (0, 1, 2, 4, 8, 16, 32):
|
| 57 |
+
s = expr.nseries(x, n=n)
|
| 58 |
+
if not s.has(Order) or s.getn() >= 0:
|
| 59 |
+
break
|
| 60 |
+
s = collect(s.removeO(), x)
|
| 61 |
+
if s.is_Add:
|
| 62 |
+
args = s.args
|
| 63 |
+
else:
|
| 64 |
+
args = [s]
|
| 65 |
+
res = S.Zero
|
| 66 |
+
for arg in args:
|
| 67 |
+
c, m = arg.as_coeff_mul(x)
|
| 68 |
+
m = Mul(*m)
|
| 69 |
+
if not (m in (S.One, x) or (m.is_Pow and m.exp.is_Integer)):
|
| 70 |
+
raise NotImplementedError('term of unexpected form: %s' % m)
|
| 71 |
+
if m == 1/x:
|
| 72 |
+
res += c
|
| 73 |
+
return res
|