ZTWHHH commited on
Commit
b63149a
·
verified ·
1 Parent(s): b078d5c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llava_next/lib/python3.10/site-packages/regex/__init__.py +3 -0
  2. llava_next/lib/python3.10/site-packages/regex/_regex_core.py +0 -0
  3. llava_next/lib/python3.10/site-packages/regex/regex.py +746 -0
  4. llava_next/lib/python3.10/site-packages/regex/test_regex.py +0 -0
  5. llava_next/lib/python3.10/site-packages/setproctitle/__pycache__/__init__.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/setproctitle/_setproctitle.cpython-310-x86_64-linux-gnu.so +0 -0
  7. llava_next/lib/python3.10/site-packages/setproctitle/py.typed +0 -0
  8. llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/INSTALLER +1 -0
  9. llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/LICENSE +0 -0
  10. llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/METADATA +520 -0
  11. llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/NOTICE +456 -0
  12. llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/REQUESTED +0 -0
  13. llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/WHEEL +5 -0
  14. llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/INSTALLER +1 -0
  15. llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/RECORD +88 -0
  16. llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/REQUESTED +0 -0
  17. llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/WHEEL +8 -0
  18. llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/top_level.txt +1 -0
  19. parrot/lib/python3.10/site-packages/sympy/integrals/__init__.py +45 -0
  20. parrot/lib/python3.10/site-packages/sympy/integrals/integrals.py +1640 -0
  21. parrot/lib/python3.10/site-packages/sympy/integrals/meijerint.py +2191 -0
  22. parrot/lib/python3.10/site-packages/sympy/integrals/rationaltools.py +429 -0
  23. parrot/lib/python3.10/site-packages/sympy/integrals/singularityfunctions.py +63 -0
  24. parrot/lib/python3.10/site-packages/sympy/integrals/tests/__init__.py +0 -0
  25. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_deltafunctions.py +79 -0
  26. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_failing_integrals.py +277 -0
  27. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_heurisch.py +419 -0
  28. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_intpoly.py +627 -0
  29. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_laplace.py +769 -0
  30. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_lineintegrals.py +13 -0
  31. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_risch.py +763 -0
  32. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_singularityfunctions.py +22 -0
  33. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_transforms.py +636 -0
  34. parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_trigonometry.py +98 -0
  35. parrot/lib/python3.10/site-packages/sympy/integrals/transforms.py +1590 -0
  36. parrot/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest2.cpython-310.pyc +0 -0
  37. parrot/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest8.cpython-310.pyc +0 -0
  38. parrot/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/__init__.cpython-310.pyc +0 -0
  39. parrot/lib/python3.10/site-packages/sympy/parsing/fortran/fortran_parser.py +347 -0
  40. parrot/lib/python3.10/site-packages/sympy/strategies/__init__.py +50 -0
  41. parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/__init__.cpython-310.pyc +0 -0
  42. parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/rl.cpython-310.pyc +0 -0
  43. parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/tools.cpython-310.pyc +0 -0
  44. parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/traverse.cpython-310.pyc +0 -0
  45. parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/tree.cpython-310.pyc +0 -0
  46. parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/util.cpython-310.pyc +0 -0
  47. parrot/lib/python3.10/site-packages/sympy/strategies/branch/__init__.py +14 -0
  48. parrot/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/__init__.cpython-310.pyc +0 -0
  49. parrot/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/core.cpython-310.pyc +0 -0
  50. parrot/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/tools.cpython-310.pyc +0 -0
llava_next/lib/python3.10/site-packages/regex/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .regex import *
2
+ from . import regex
3
+ __all__ = regex.__all__
llava_next/lib/python3.10/site-packages/regex/_regex_core.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/regex/regex.py ADDED
@@ -0,0 +1,746 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # Secret Labs' Regular Expression Engine
3
+ #
4
+ # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved.
5
+ #
6
+ # This version of the SRE library can be redistributed under CNRI's
7
+ # Python 1.6 license. For any other use, please contact Secret Labs
8
+ # AB (info@pythonware.com).
9
+ #
10
+ # Portions of this engine have been developed in cooperation with
11
+ # CNRI. Hewlett-Packard provided funding for 1.6 integration and
12
+ # other compatibility work.
13
+ #
14
+ # 2010-01-16 mrab Python front-end re-written and extended
15
+
16
+ r"""Support for regular expressions (RE).
17
+
18
+ This module provides regular expression matching operations similar to those
19
+ found in Perl. It supports both 8-bit and Unicode strings; both the pattern and
20
+ the strings being processed can contain null bytes and characters outside the
21
+ US ASCII range.
22
+
23
+ Regular expressions can contain both special and ordinary characters. Most
24
+ ordinary characters, like "A", "a", or "0", are the simplest regular
25
+ expressions; they simply match themselves. You can concatenate ordinary
26
+ characters, so last matches the string 'last'.
27
+
28
+ There are a few differences between the old (legacy) behaviour and the new
29
+ (enhanced) behaviour, which are indicated by VERSION0 or VERSION1.
30
+
31
+ The special characters are:
32
+ "." Matches any character except a newline.
33
+ "^" Matches the start of the string.
34
+ "$" Matches the end of the string or just before the
35
+ newline at the end of the string.
36
+ "*" Matches 0 or more (greedy) repetitions of the preceding
37
+ RE. Greedy means that it will match as many repetitions
38
+ as possible.
39
+ "+" Matches 1 or more (greedy) repetitions of the preceding
40
+ RE.
41
+ "?" Matches 0 or 1 (greedy) of the preceding RE.
42
+ *?,+?,?? Non-greedy versions of the previous three special
43
+ characters.
44
+ *+,++,?+ Possessive versions of the previous three special
45
+ characters.
46
+ {m,n} Matches from m to n repetitions of the preceding RE.
47
+ {m,n}? Non-greedy version of the above.
48
+ {m,n}+ Possessive version of the above.
49
+ {...} Fuzzy matching constraints.
50
+ "\\" Either escapes special characters or signals a special
51
+ sequence.
52
+ [...] Indicates a set of characters. A "^" as the first
53
+ character indicates a complementing set.
54
+ "|" A|B, creates an RE that will match either A or B.
55
+ (...) Matches the RE inside the parentheses. The contents are
56
+ captured and can be retrieved or matched later in the
57
+ string.
58
+ (?flags-flags) VERSION1: Sets/clears the flags for the remainder of
59
+ the group or pattern; VERSION0: Sets the flags for the
60
+ entire pattern.
61
+ (?:...) Non-capturing version of regular parentheses.
62
+ (?>...) Atomic non-capturing version of regular parentheses.
63
+ (?flags-flags:...) Non-capturing version of regular parentheses with local
64
+ flags.
65
+ (?P<name>...) The substring matched by the group is accessible by
66
+ name.
67
+ (?<name>...) The substring matched by the group is accessible by
68
+ name.
69
+ (?P=name) Matches the text matched earlier by the group named
70
+ name.
71
+ (?#...) A comment; ignored.
72
+ (?=...) Matches if ... matches next, but doesn't consume the
73
+ string.
74
+ (?!...) Matches if ... doesn't match next.
75
+ (?<=...) Matches if preceded by ....
76
+ (?<!...) Matches if not preceded by ....
77
+ (?(id)yes|no) Matches yes pattern if group id matched, the (optional)
78
+ no pattern otherwise.
79
+ (?(DEFINE)...) If there's no group called "DEFINE", then ... will be
80
+ ignored, but any group definitions will be available.
81
+ (?|...|...) (?|A|B), creates an RE that will match either A or B,
82
+ but reuses capture group numbers across the
83
+ alternatives.
84
+ (*FAIL) Forces matching to fail, which means immediate
85
+ backtracking.
86
+ (*F) Abbreviation for (*FAIL).
87
+ (*PRUNE) Discards the current backtracking information. Its
88
+ effect doesn't extend outside an atomic group or a
89
+ lookaround.
90
+ (*SKIP) Similar to (*PRUNE), except that it also sets where in
91
+ the text the next attempt at matching the entire
92
+ pattern will start. Its effect doesn't extend outside
93
+ an atomic group or a lookaround.
94
+
95
+ The fuzzy matching constraints are: "i" to permit insertions, "d" to permit
96
+ deletions, "s" to permit substitutions, "e" to permit any of these. Limits are
97
+ optional with "<=" and "<". If any type of error is provided then any type not
98
+ provided is not permitted.
99
+
100
+ A cost equation may be provided.
101
+
102
+ Examples:
103
+ (?:fuzzy){i<=2}
104
+ (?:fuzzy){i<=1,s<=2,d<=1,1i+1s+1d<3}
105
+
106
+ VERSION1: Set operators are supported, and a set can include nested sets. The
107
+ set operators, in order of increasing precedence, are:
108
+ || Set union ("x||y" means "x or y").
109
+ ~~ (double tilde) Symmetric set difference ("x~~y" means "x or y, but not
110
+ both").
111
+ && Set intersection ("x&&y" means "x and y").
112
+ -- (double dash) Set difference ("x--y" means "x but not y").
113
+
114
+ Implicit union, ie, simple juxtaposition like in [ab], has the highest
115
+ precedence.
116
+
117
+ VERSION0 and VERSION1:
118
+ The special sequences consist of "\\" and a character from the list below. If
119
+ the ordinary character is not on the list, then the resulting RE will match the
120
+ second character.
121
+ \number Matches the contents of the group of the same number if
122
+ number is no more than 2 digits, otherwise the character
123
+ with the 3-digit octal code.
124
+ \a Matches the bell character.
125
+ \A Matches only at the start of the string.
126
+ \b Matches the empty string, but only at the start or end of a
127
+ word.
128
+ \B Matches the empty string, but not at the start or end of a
129
+ word.
130
+ \d Matches any decimal digit; equivalent to the set [0-9] when
131
+ matching a bytestring or a Unicode string with the ASCII
132
+ flag, or the whole range of Unicode digits when matching a
133
+ Unicode string.
134
+ \D Matches any non-digit character; equivalent to [^\d].
135
+ \f Matches the formfeed character.
136
+ \g<name> Matches the text matched by the group named name.
137
+ \G Matches the empty string, but only at the position where
138
+ the search started.
139
+ \h Matches horizontal whitespace.
140
+ \K Keeps only what follows for the entire match.
141
+ \L<name> Named list. The list is provided as a keyword argument.
142
+ \m Matches the empty string, but only at the start of a word.
143
+ \M Matches the empty string, but only at the end of a word.
144
+ \n Matches the newline character.
145
+ \N{name} Matches the named character.
146
+ \p{name=value} Matches the character if its property has the specified
147
+ value.
148
+ \P{name=value} Matches the character if its property hasn't the specified
149
+ value.
150
+ \r Matches the carriage-return character.
151
+ \s Matches any whitespace character; equivalent to
152
+ [ \t\n\r\f\v].
153
+ \S Matches any non-whitespace character; equivalent to [^\s].
154
+ \t Matches the tab character.
155
+ \uXXXX Matches the Unicode codepoint with 4-digit hex code XXXX.
156
+ \UXXXXXXXX Matches the Unicode codepoint with 8-digit hex code
157
+ XXXXXXXX.
158
+ \v Matches the vertical tab character.
159
+ \w Matches any alphanumeric character; equivalent to
160
+ [a-zA-Z0-9_] when matching a bytestring or a Unicode string
161
+ with the ASCII flag, or the whole range of Unicode
162
+ alphanumeric characters (letters plus digits plus
163
+ underscore) when matching a Unicode string. With LOCALE, it
164
+ will match the set [0-9_] plus characters defined as
165
+ letters for the current locale.
166
+ \W Matches the complement of \w; equivalent to [^\w].
167
+ \xXX Matches the character with 2-digit hex code XX.
168
+ \X Matches a grapheme.
169
+ \Z Matches only at the end of the string.
170
+ \\ Matches a literal backslash.
171
+
172
+ This module exports the following functions:
173
+ match Match a regular expression pattern at the beginning of a string.
174
+ fullmatch Match a regular expression pattern against all of a string.
175
+ search Search a string for the presence of a pattern.
176
+ sub Substitute occurrences of a pattern found in a string using a
177
+ template string.
178
+ subf Substitute occurrences of a pattern found in a string using a
179
+ format string.
180
+ subn Same as sub, but also return the number of substitutions made.
181
+ subfn Same as subf, but also return the number of substitutions made.
182
+ split Split a string by the occurrences of a pattern. VERSION1: will
183
+ split at zero-width match; VERSION0: won't split at zero-width
184
+ match.
185
+ splititer Return an iterator yielding the parts of a split string.
186
+ findall Find all occurrences of a pattern in a string.
187
+ finditer Return an iterator yielding a match object for each match.
188
+ compile Compile a pattern into a Pattern object.
189
+ purge Clear the regular expression cache.
190
+ escape Backslash all non-alphanumerics or special characters in a
191
+ string.
192
+
193
+ Most of the functions support a concurrent parameter: if True, the GIL will be
194
+ released during matching, allowing other Python threads to run concurrently. If
195
+ the string changes during matching, the behaviour is undefined. This parameter
196
+ is not needed when working on the builtin (immutable) string classes.
197
+
198
+ Some of the functions in this module take flags as optional parameters. Most of
199
+ these flags can also be set within an RE:
200
+ A a ASCII Make \w, \W, \b, \B, \d, and \D match the
201
+ corresponding ASCII character categories. Default
202
+ when matching a bytestring.
203
+ B b BESTMATCH Find the best fuzzy match (default is first).
204
+ D DEBUG Print the parsed pattern.
205
+ E e ENHANCEMATCH Attempt to improve the fit after finding the first
206
+ fuzzy match.
207
+ F f FULLCASE Use full case-folding when performing
208
+ case-insensitive matching in Unicode.
209
+ I i IGNORECASE Perform case-insensitive matching.
210
+ L L LOCALE Make \w, \W, \b, \B, \d, and \D dependent on the
211
+ current locale. (One byte per character only.)
212
+ M m MULTILINE "^" matches the beginning of lines (after a newline)
213
+ as well as the string. "$" matches the end of lines
214
+ (before a newline) as well as the end of the string.
215
+ P p POSIX Perform POSIX-standard matching (leftmost longest).
216
+ R r REVERSE Searches backwards.
217
+ S s DOTALL "." matches any character at all, including the
218
+ newline.
219
+ U u UNICODE Make \w, \W, \b, \B, \d, and \D dependent on the
220
+ Unicode locale. Default when matching a Unicode
221
+ string.
222
+ V0 V0 VERSION0 Turn on the old legacy behaviour.
223
+ V1 V1 VERSION1 Turn on the new enhanced behaviour. This flag
224
+ includes the FULLCASE flag.
225
+ W w WORD Make \b and \B work with default Unicode word breaks
226
+ and make ".", "^" and "$" work with Unicode line
227
+ breaks.
228
+ X x VERBOSE Ignore whitespace and comments for nicer looking REs.
229
+
230
+ This module also defines an exception 'error'.
231
+
232
+ """
233
+
234
+ # Public symbols.
235
+ __all__ = ["cache_all", "compile", "DEFAULT_VERSION", "escape", "findall",
236
+ "finditer", "fullmatch", "match", "purge", "search", "split", "splititer",
237
+ "sub", "subf", "subfn", "subn", "template", "Scanner", "A", "ASCII", "B",
238
+ "BESTMATCH", "D", "DEBUG", "E", "ENHANCEMATCH", "S", "DOTALL", "F",
239
+ "FULLCASE", "I", "IGNORECASE", "L", "LOCALE", "M", "MULTILINE", "P", "POSIX",
240
+ "R", "REVERSE", "T", "TEMPLATE", "U", "UNICODE", "V0", "VERSION0", "V1",
241
+ "VERSION1", "X", "VERBOSE", "W", "WORD", "error", "Regex", "__version__",
242
+ "__doc__", "RegexFlag"]
243
+
244
+ __version__ = "2.5.148"
245
+
246
+ # --------------------------------------------------------------------
247
+ # Public interface.
248
+
249
+ def match(pattern, string, flags=0, pos=None, endpos=None, partial=False,
250
+ concurrent=None, timeout=None, ignore_unused=False, **kwargs):
251
+ """Try to apply the pattern at the start of the string, returning a match
252
+ object, or None if no match was found."""
253
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
254
+ return pat.match(string, pos, endpos, concurrent, partial, timeout)
255
+
256
+ def fullmatch(pattern, string, flags=0, pos=None, endpos=None, partial=False,
257
+ concurrent=None, timeout=None, ignore_unused=False, **kwargs):
258
+ """Try to apply the pattern against all of the string, returning a match
259
+ object, or None if no match was found."""
260
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
261
+ return pat.fullmatch(string, pos, endpos, concurrent, partial, timeout)
262
+
263
+ def search(pattern, string, flags=0, pos=None, endpos=None, partial=False,
264
+ concurrent=None, timeout=None, ignore_unused=False, **kwargs):
265
+ """Search through string looking for a match to the pattern, returning a
266
+ match object, or None if no match was found."""
267
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
268
+ return pat.search(string, pos, endpos, concurrent, partial, timeout)
269
+
270
+ def sub(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
271
+ concurrent=None, timeout=None, ignore_unused=False, **kwargs):
272
+ """Return the string obtained by replacing the leftmost (or rightmost with a
273
+ reverse pattern) non-overlapping occurrences of the pattern in string by the
274
+ replacement repl. repl can be either a string or a callable; if a string,
275
+ backslash escapes in it are processed; if a callable, it's passed the match
276
+ object and must return a replacement string to be used."""
277
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
278
+ return pat.sub(repl, string, count, pos, endpos, concurrent, timeout)
279
+
280
+ def subf(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
281
+ concurrent=None, timeout=None, ignore_unused=False, **kwargs):
282
+ """Return the string obtained by replacing the leftmost (or rightmost with a
283
+ reverse pattern) non-overlapping occurrences of the pattern in string by the
284
+ replacement format. format can be either a string or a callable; if a string,
285
+ it's treated as a format string; if a callable, it's passed the match object
286
+ and must return a replacement string to be used."""
287
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
288
+ return pat.subf(format, string, count, pos, endpos, concurrent, timeout)
289
+
290
+ def subn(pattern, repl, string, count=0, flags=0, pos=None, endpos=None,
291
+ concurrent=None, timeout=None, ignore_unused=False, **kwargs):
292
+ """Return a 2-tuple containing (new_string, number). new_string is the string
293
+ obtained by replacing the leftmost (or rightmost with a reverse pattern)
294
+ non-overlapping occurrences of the pattern in the source string by the
295
+ replacement repl. number is the number of substitutions that were made. repl
296
+ can be either a string or a callable; if a string, backslash escapes in it
297
+ are processed; if a callable, it's passed the match object and must return a
298
+ replacement string to be used."""
299
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
300
+ return pat.subn(repl, string, count, pos, endpos, concurrent, timeout)
301
+
302
+ def subfn(pattern, format, string, count=0, flags=0, pos=None, endpos=None,
303
+ concurrent=None, timeout=None, ignore_unused=False, **kwargs):
304
+ """Return a 2-tuple containing (new_string, number). new_string is the string
305
+ obtained by replacing the leftmost (or rightmost with a reverse pattern)
306
+ non-overlapping occurrences of the pattern in the source string by the
307
+ replacement format. number is the number of substitutions that were made. format
308
+ can be either a string or a callable; if a string, it's treated as a format
309
+ string; if a callable, it's passed the match object and must return a
310
+ replacement string to be used."""
311
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
312
+ return pat.subfn(format, string, count, pos, endpos, concurrent, timeout)
313
+
314
+ def split(pattern, string, maxsplit=0, flags=0, concurrent=None, timeout=None,
315
+ ignore_unused=False, **kwargs):
316
+ """Split the source string by the occurrences of the pattern, returning a
317
+ list containing the resulting substrings. If capturing parentheses are used
318
+ in pattern, then the text of all groups in the pattern are also returned as
319
+ part of the resulting list. If maxsplit is nonzero, at most maxsplit splits
320
+ occur, and the remainder of the string is returned as the final element of
321
+ the list."""
322
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
323
+ return pat.split(string, maxsplit, concurrent, timeout)
324
+
325
+ def splititer(pattern, string, maxsplit=0, flags=0, concurrent=None,
326
+ timeout=None, ignore_unused=False, **kwargs):
327
+ "Return an iterator yielding the parts of a split string."
328
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
329
+ return pat.splititer(string, maxsplit, concurrent, timeout)
330
+
331
+ def findall(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
332
+ concurrent=None, timeout=None, ignore_unused=False, **kwargs):
333
+ """Return a list of all matches in the string. The matches may be overlapped
334
+ if overlapped is True. If one or more groups are present in the pattern,
335
+ return a list of groups; this will be a list of tuples if the pattern has
336
+ more than one group. Empty matches are included in the result."""
337
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
338
+ return pat.findall(string, pos, endpos, overlapped, concurrent, timeout)
339
+
340
+ def finditer(pattern, string, flags=0, pos=None, endpos=None, overlapped=False,
341
+ partial=False, concurrent=None, timeout=None, ignore_unused=False, **kwargs):
342
+ """Return an iterator over all matches in the string. The matches may be
343
+ overlapped if overlapped is True. For each match, the iterator returns a
344
+ match object. Empty matches are included in the result."""
345
+ pat = _compile(pattern, flags, ignore_unused, kwargs, True)
346
+ return pat.finditer(string, pos, endpos, overlapped, concurrent, partial,
347
+ timeout)
348
+
349
+ def compile(pattern, flags=0, ignore_unused=False, cache_pattern=None, **kwargs):
350
+ "Compile a regular expression pattern, returning a pattern object."
351
+ if cache_pattern is None:
352
+ cache_pattern = _cache_all
353
+ return _compile(pattern, flags, ignore_unused, kwargs, cache_pattern)
354
+
355
+ def purge():
356
+ "Clear the regular expression cache"
357
+ _cache.clear()
358
+ _locale_sensitive.clear()
359
+
360
+ # Whether to cache all patterns.
361
+ _cache_all = True
362
+
363
+ def cache_all(value=True):
364
+ """Sets whether to cache all patterns, even those are compiled explicitly.
365
+ Passing None has no effect, but returns the current setting."""
366
+ global _cache_all
367
+
368
+ if value is None:
369
+ return _cache_all
370
+
371
+ _cache_all = value
372
+
373
+ def template(pattern, flags=0):
374
+ "Compile a template pattern, returning a pattern object."
375
+ return _compile(pattern, flags | TEMPLATE, False, {}, False)
376
+
377
+ def escape(pattern, special_only=True, literal_spaces=False):
378
+ """Escape a string for use as a literal in a pattern. If special_only is
379
+ True, escape only special characters, else escape all non-alphanumeric
380
+ characters. If literal_spaces is True, don't escape spaces."""
381
+ # Convert it to Unicode.
382
+ if isinstance(pattern, bytes):
383
+ p = pattern.decode("latin-1")
384
+ else:
385
+ p = pattern
386
+
387
+ s = []
388
+ if special_only:
389
+ for c in p:
390
+ if c == " " and literal_spaces:
391
+ s.append(c)
392
+ elif c in _METACHARS or c.isspace():
393
+ s.append("\\")
394
+ s.append(c)
395
+ else:
396
+ s.append(c)
397
+ else:
398
+ for c in p:
399
+ if c == " " and literal_spaces:
400
+ s.append(c)
401
+ elif c in _ALNUM:
402
+ s.append(c)
403
+ else:
404
+ s.append("\\")
405
+ s.append(c)
406
+
407
+ r = "".join(s)
408
+ # Convert it back to bytes if necessary.
409
+ if isinstance(pattern, bytes):
410
+ r = r.encode("latin-1")
411
+
412
+ return r
413
+
414
+ # --------------------------------------------------------------------
415
+ # Internals.
416
+
417
+ import regex._regex_core as _regex_core
418
+ import regex._regex as _regex
419
+ from threading import RLock as _RLock
420
+ from locale import getpreferredencoding as _getpreferredencoding
421
+ from regex._regex_core import *
422
+ from regex._regex_core import (_ALL_VERSIONS, _ALL_ENCODINGS, _FirstSetError,
423
+ _UnscopedFlagSet, _check_group_features, _compile_firstset,
424
+ _compile_replacement, _flatten_code, _fold_case, _get_required_string,
425
+ _parse_pattern, _shrink_cache)
426
+ from regex._regex_core import (ALNUM as _ALNUM, Info as _Info, OP as _OP, Source
427
+ as _Source, Fuzzy as _Fuzzy)
428
+
429
+ # Version 0 is the old behaviour, compatible with the original 're' module.
430
+ # Version 1 is the new behaviour, which differs slightly.
431
+
432
+ DEFAULT_VERSION = VERSION0
433
+
434
+ _METACHARS = frozenset("()[]{}?*+|^$\\.-#&~")
435
+
436
+ _regex_core.DEFAULT_VERSION = DEFAULT_VERSION
437
+
438
+ # Caches for the patterns and replacements.
439
+ _cache = {}
440
+ _cache_lock = _RLock()
441
+ _named_args = {}
442
+ _replacement_cache = {}
443
+ _locale_sensitive = {}
444
+
445
+ # Maximum size of the cache.
446
+ _MAXCACHE = 500
447
+ _MAXREPCACHE = 500
448
+
449
+ def _compile(pattern, flags, ignore_unused, kwargs, cache_it):
450
+ "Compiles a regular expression to a PatternObject."
451
+
452
+ global DEFAULT_VERSION
453
+ try:
454
+ from regex import DEFAULT_VERSION
455
+ except ImportError:
456
+ pass
457
+
458
+ # We won't bother to cache the pattern if we're debugging.
459
+ if (flags & DEBUG) != 0:
460
+ cache_it = False
461
+
462
+ # What locale is this pattern using?
463
+ locale_key = (type(pattern), pattern)
464
+ if _locale_sensitive.get(locale_key, True) or (flags & LOCALE) != 0:
465
+ # This pattern is, or might be, locale-sensitive.
466
+ pattern_locale = _getpreferredencoding()
467
+ else:
468
+ # This pattern is definitely not locale-sensitive.
469
+ pattern_locale = None
470
+
471
+ def complain_unused_args():
472
+ if ignore_unused:
473
+ return
474
+
475
+ # Complain about any unused keyword arguments, possibly resulting from a typo.
476
+ unused_kwargs = set(kwargs) - {k for k, v in args_needed}
477
+ if unused_kwargs:
478
+ any_one = next(iter(unused_kwargs))
479
+ raise ValueError('unused keyword argument {!a}'.format(any_one))
480
+
481
+ if cache_it:
482
+ try:
483
+ # Do we know what keyword arguments are needed?
484
+ args_key = pattern, type(pattern), flags
485
+ args_needed = _named_args[args_key]
486
+
487
+ # Are we being provided with its required keyword arguments?
488
+ args_supplied = set()
489
+ if args_needed:
490
+ for k, v in args_needed:
491
+ try:
492
+ args_supplied.add((k, frozenset(kwargs[k])))
493
+ except KeyError:
494
+ raise error("missing named list: {!r}".format(k))
495
+
496
+ complain_unused_args()
497
+
498
+ args_supplied = frozenset(args_supplied)
499
+
500
+ # Have we already seen this regular expression and named list?
501
+ pattern_key = (pattern, type(pattern), flags, args_supplied,
502
+ DEFAULT_VERSION, pattern_locale)
503
+ return _cache[pattern_key]
504
+ except KeyError:
505
+ # It's a new pattern, or new named list for a known pattern.
506
+ pass
507
+
508
+ # Guess the encoding from the class of the pattern string.
509
+ if isinstance(pattern, str):
510
+ guess_encoding = UNICODE
511
+ elif isinstance(pattern, bytes):
512
+ guess_encoding = ASCII
513
+ elif isinstance(pattern, Pattern):
514
+ if flags:
515
+ raise ValueError("cannot process flags argument with a compiled pattern")
516
+
517
+ return pattern
518
+ else:
519
+ raise TypeError("first argument must be a string or compiled pattern")
520
+
521
+ # Set the default version in the core code in case it has been changed.
522
+ _regex_core.DEFAULT_VERSION = DEFAULT_VERSION
523
+
524
+ global_flags = flags
525
+
526
+ while True:
527
+ caught_exception = None
528
+ try:
529
+ source = _Source(pattern)
530
+ info = _Info(global_flags, source.char_type, kwargs)
531
+ info.guess_encoding = guess_encoding
532
+ source.ignore_space = bool(info.flags & VERBOSE)
533
+ parsed = _parse_pattern(source, info)
534
+ break
535
+ except _UnscopedFlagSet:
536
+ # Remember the global flags for the next attempt.
537
+ global_flags = info.global_flags
538
+ except error as e:
539
+ caught_exception = e
540
+
541
+ if caught_exception:
542
+ raise error(caught_exception.msg, caught_exception.pattern,
543
+ caught_exception.pos)
544
+
545
+ if not source.at_end():
546
+ raise error("unbalanced parenthesis", pattern, source.pos)
547
+
548
+ # Check the global flags for conflicts.
549
+ version = (info.flags & _ALL_VERSIONS) or DEFAULT_VERSION
550
+ if version not in (0, VERSION0, VERSION1):
551
+ raise ValueError("VERSION0 and VERSION1 flags are mutually incompatible")
552
+
553
+ if (info.flags & _ALL_ENCODINGS) not in (0, ASCII, LOCALE, UNICODE):
554
+ raise ValueError("ASCII, LOCALE and UNICODE flags are mutually incompatible")
555
+
556
+ if isinstance(pattern, bytes) and (info.flags & UNICODE):
557
+ raise ValueError("cannot use UNICODE flag with a bytes pattern")
558
+
559
+ if not (info.flags & _ALL_ENCODINGS):
560
+ if isinstance(pattern, str):
561
+ info.flags |= UNICODE
562
+ else:
563
+ info.flags |= ASCII
564
+
565
+ reverse = bool(info.flags & REVERSE)
566
+ fuzzy = isinstance(parsed, _Fuzzy)
567
+
568
+ # Remember whether this pattern as an inline locale flag.
569
+ _locale_sensitive[locale_key] = info.inline_locale
570
+
571
+ # Fix the group references.
572
+ caught_exception = None
573
+ try:
574
+ parsed.fix_groups(pattern, reverse, False)
575
+ except error as e:
576
+ caught_exception = e
577
+
578
+ if caught_exception:
579
+ raise error(caught_exception.msg, caught_exception.pattern,
580
+ caught_exception.pos)
581
+
582
+ # Should we print the parsed pattern?
583
+ if flags & DEBUG:
584
+ parsed.dump(indent=0, reverse=reverse)
585
+
586
+ # Optimise the parsed pattern.
587
+ parsed = parsed.optimise(info, reverse)
588
+ parsed = parsed.pack_characters(info)
589
+
590
+ # Get the required string.
591
+ req_offset, req_chars, req_flags = _get_required_string(parsed, info.flags)
592
+
593
+ # Build the named lists.
594
+ named_lists = {}
595
+ named_list_indexes = [None] * len(info.named_lists_used)
596
+ args_needed = set()
597
+ for key, index in info.named_lists_used.items():
598
+ name, case_flags = key
599
+ values = frozenset(kwargs[name])
600
+ if case_flags:
601
+ items = frozenset(_fold_case(info, v) for v in values)
602
+ else:
603
+ items = values
604
+ named_lists[name] = values
605
+ named_list_indexes[index] = items
606
+ args_needed.add((name, values))
607
+
608
+ complain_unused_args()
609
+
610
+ # Check the features of the groups.
611
+ _check_group_features(info, parsed)
612
+
613
+ # Compile the parsed pattern. The result is a list of tuples.
614
+ code = parsed.compile(reverse)
615
+
616
+ # Is there a group call to the pattern as a whole?
617
+ key = (0, reverse, fuzzy)
618
+ ref = info.call_refs.get(key)
619
+ if ref is not None:
620
+ code = [(_OP.CALL_REF, ref)] + code + [(_OP.END, )]
621
+
622
+ # Add the final 'success' opcode.
623
+ code += [(_OP.SUCCESS, )]
624
+
625
+ # Compile the additional copies of the groups that we need.
626
+ for group, rev, fuz in info.additional_groups:
627
+ code += group.compile(rev, fuz)
628
+
629
+ # Flatten the code into a list of ints.
630
+ code = _flatten_code(code)
631
+
632
+ if not parsed.has_simple_start():
633
+ # Get the first set, if possible.
634
+ try:
635
+ fs_code = _compile_firstset(info, parsed.get_firstset(reverse))
636
+ fs_code = _flatten_code(fs_code)
637
+ code = fs_code + code
638
+ except _FirstSetError:
639
+ pass
640
+
641
+ # The named capture groups.
642
+ index_group = dict((v, n) for n, v in info.group_index.items())
643
+
644
+ # Create the PatternObject.
645
+ #
646
+ # Local flags like IGNORECASE affect the code generation, but aren't needed
647
+ # by the PatternObject itself. Conversely, global flags like LOCALE _don't_
648
+ # affect the code generation but _are_ needed by the PatternObject.
649
+ compiled_pattern = _regex.compile(pattern, info.flags | version, code,
650
+ info.group_index, index_group, named_lists, named_list_indexes,
651
+ req_offset, req_chars, req_flags, info.group_count)
652
+
653
+ # Do we need to reduce the size of the cache?
654
+ if len(_cache) >= _MAXCACHE:
655
+ with _cache_lock:
656
+ _shrink_cache(_cache, _named_args, _locale_sensitive, _MAXCACHE)
657
+
658
+ if cache_it:
659
+ if (info.flags & LOCALE) == 0:
660
+ pattern_locale = None
661
+
662
+ args_needed = frozenset(args_needed)
663
+
664
+ # Store this regular expression and named list.
665
+ pattern_key = (pattern, type(pattern), flags, args_needed,
666
+ DEFAULT_VERSION, pattern_locale)
667
+ _cache[pattern_key] = compiled_pattern
668
+
669
+ # Store what keyword arguments are needed.
670
+ _named_args[args_key] = args_needed
671
+
672
+ return compiled_pattern
673
+
674
+ def _compile_replacement_helper(pattern, template):
675
+ "Compiles a replacement template."
676
+ # This function is called by the _regex module.
677
+
678
+ # Have we seen this before?
679
+ key = pattern.pattern, pattern.flags, template
680
+ compiled = _replacement_cache.get(key)
681
+ if compiled is not None:
682
+ return compiled
683
+
684
+ if len(_replacement_cache) >= _MAXREPCACHE:
685
+ _replacement_cache.clear()
686
+
687
+ is_unicode = isinstance(template, str)
688
+ source = _Source(template)
689
+ if is_unicode:
690
+ def make_string(char_codes):
691
+ return "".join(chr(c) for c in char_codes)
692
+ else:
693
+ def make_string(char_codes):
694
+ return bytes(char_codes)
695
+
696
+ compiled = []
697
+ literal = []
698
+ while True:
699
+ ch = source.get()
700
+ if not ch:
701
+ break
702
+ if ch == "\\":
703
+ # '_compile_replacement' will return either an int group reference
704
+ # or a string literal. It returns items (plural) in order to handle
705
+ # a 2-character literal (an invalid escape sequence).
706
+ is_group, items = _compile_replacement(source, pattern, is_unicode)
707
+ if is_group:
708
+ # It's a group, so first flush the literal.
709
+ if literal:
710
+ compiled.append(make_string(literal))
711
+ literal = []
712
+ compiled.extend(items)
713
+ else:
714
+ literal.extend(items)
715
+ else:
716
+ literal.append(ord(ch))
717
+
718
+ # Flush the literal.
719
+ if literal:
720
+ compiled.append(make_string(literal))
721
+
722
+ _replacement_cache[key] = compiled
723
+
724
+ return compiled
725
+
726
+ # We define Pattern here after all the support objects have been defined.
727
+ _pat = _compile('', 0, False, {}, False)
728
+ Pattern = type(_pat)
729
+ Match = type(_pat.match(''))
730
+ del _pat
731
+
732
+ # Make Pattern public for typing annotations.
733
+ __all__.append("Pattern")
734
+ __all__.append("Match")
735
+
736
+ # We'll define an alias for the 'compile' function so that the repr of a
737
+ # pattern object is eval-able.
738
+ Regex = compile
739
+
740
+ # Register myself for pickling.
741
+ import copyreg as _copy_reg
742
+
743
+ def _pickle(pattern):
744
+ return _regex.compile, pattern._pickled_data
745
+
746
+ _copy_reg.pickle(Pattern, _pickle)
llava_next/lib/python3.10/site-packages/regex/test_regex.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/setproctitle/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.32 kB). View file
 
llava_next/lib/python3.10/site-packages/setproctitle/_setproctitle.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (68.8 kB). View file
 
llava_next/lib/python3.10/site-packages/setproctitle/py.typed ADDED
File without changes
llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/LICENSE ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/METADATA ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: torch
3
+ Version: 2.1.2
4
+ Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration
5
+ Home-page: https://pytorch.org/
6
+ Author: PyTorch Team
7
+ Author-email: packages@pytorch.org
8
+ License: BSD-3
9
+ Download-URL: https://github.com/pytorch/pytorch/tags
10
+ Keywords: pytorch,machine learning
11
+ Platform: UNKNOWN
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Education
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: BSD License
17
+ Classifier: Topic :: Scientific/Engineering
18
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Programming Language :: C++
24
+ Classifier: Programming Language :: Python :: 3
25
+ Classifier: Programming Language :: Python :: 3.8
26
+ Classifier: Programming Language :: Python :: 3.9
27
+ Classifier: Programming Language :: Python :: 3.10
28
+ Requires-Python: >=3.8.0
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ License-File: NOTICE
32
+ Requires-Dist: filelock
33
+ Requires-Dist: typing-extensions
34
+ Requires-Dist: sympy
35
+ Requires-Dist: networkx
36
+ Requires-Dist: jinja2
37
+ Requires-Dist: fsspec
38
+ Requires-Dist: nvidia-cuda-nvrtc-cu12 (==12.1.105) ; platform_system == "Linux" and platform_machine == "x86_64"
39
+ Requires-Dist: nvidia-cuda-runtime-cu12 (==12.1.105) ; platform_system == "Linux" and platform_machine == "x86_64"
40
+ Requires-Dist: nvidia-cuda-cupti-cu12 (==12.1.105) ; platform_system == "Linux" and platform_machine == "x86_64"
41
+ Requires-Dist: nvidia-cudnn-cu12 (==8.9.2.26) ; platform_system == "Linux" and platform_machine == "x86_64"
42
+ Requires-Dist: nvidia-cublas-cu12 (==12.1.3.1) ; platform_system == "Linux" and platform_machine == "x86_64"
43
+ Requires-Dist: nvidia-cufft-cu12 (==11.0.2.54) ; platform_system == "Linux" and platform_machine == "x86_64"
44
+ Requires-Dist: nvidia-curand-cu12 (==10.3.2.106) ; platform_system == "Linux" and platform_machine == "x86_64"
45
+ Requires-Dist: nvidia-cusolver-cu12 (==11.4.5.107) ; platform_system == "Linux" and platform_machine == "x86_64"
46
+ Requires-Dist: nvidia-cusparse-cu12 (==12.1.0.106) ; platform_system == "Linux" and platform_machine == "x86_64"
47
+ Requires-Dist: nvidia-nccl-cu12 (==2.18.1) ; platform_system == "Linux" and platform_machine == "x86_64"
48
+ Requires-Dist: nvidia-nvtx-cu12 (==12.1.105) ; platform_system == "Linux" and platform_machine == "x86_64"
49
+ Requires-Dist: triton (==2.1.0) ; platform_system == "Linux" and platform_machine == "x86_64"
50
+ Provides-Extra: dynamo
51
+ Requires-Dist: jinja2 ; extra == 'dynamo'
52
+ Provides-Extra: opt-einsum
53
+ Requires-Dist: opt-einsum (>=3.3) ; extra == 'opt-einsum'
54
+
55
+ ![PyTorch Logo](https://github.com/pytorch/pytorch/blob/main/docs/source/_static/img/pytorch-logo-dark.png)
56
+
57
+ --------------------------------------------------------------------------------
58
+
59
+ PyTorch is a Python package that provides two high-level features:
60
+ - Tensor computation (like NumPy) with strong GPU acceleration
61
+ - Deep neural networks built on a tape-based autograd system
62
+
63
+ You can reuse your favorite Python packages such as NumPy, SciPy, and Cython to extend PyTorch when needed.
64
+
65
+ Our trunk health (Continuous Integration signals) can be found at [hud.pytorch.org](https://hud.pytorch.org/ci/pytorch/pytorch/main).
66
+
67
+ <!-- toc -->
68
+
69
+ - [More About PyTorch](#more-about-pytorch)
70
+ - [A GPU-Ready Tensor Library](#a-gpu-ready-tensor-library)
71
+ - [Dynamic Neural Networks: Tape-Based Autograd](#dynamic-neural-networks-tape-based-autograd)
72
+ - [Python First](#python-first)
73
+ - [Imperative Experiences](#imperative-experiences)
74
+ - [Fast and Lean](#fast-and-lean)
75
+ - [Extensions Without Pain](#extensions-without-pain)
76
+ - [Installation](#installation)
77
+ - [Binaries](#binaries)
78
+ - [NVIDIA Jetson Platforms](#nvidia-jetson-platforms)
79
+ - [From Source](#from-source)
80
+ - [Prerequisites](#prerequisites)
81
+ - [Install Dependencies](#install-dependencies)
82
+ - [Get the PyTorch Source](#get-the-pytorch-source)
83
+ - [Install PyTorch](#install-pytorch)
84
+ - [Adjust Build Options (Optional)](#adjust-build-options-optional)
85
+ - [Docker Image](#docker-image)
86
+ - [Using pre-built images](#using-pre-built-images)
87
+ - [Building the image yourself](#building-the-image-yourself)
88
+ - [Building the Documentation](#building-the-documentation)
89
+ - [Previous Versions](#previous-versions)
90
+ - [Getting Started](#getting-started)
91
+ - [Resources](#resources)
92
+ - [Communication](#communication)
93
+ - [Releases and Contributing](#releases-and-contributing)
94
+ - [The Team](#the-team)
95
+ - [License](#license)
96
+
97
+ <!-- tocstop -->
98
+
99
+ ## More About PyTorch
100
+
101
+ [Learn the basics of PyTorch](https://pytorch.org/tutorials/beginner/basics/intro.html)
102
+
103
+ At a granular level, PyTorch is a library that consists of the following components:
104
+
105
+ | Component | Description |
106
+ | ---- | --- |
107
+ | [**torch**](https://pytorch.org/docs/stable/torch.html) | A Tensor library like NumPy, with strong GPU support |
108
+ | [**torch.autograd**](https://pytorch.org/docs/stable/autograd.html) | A tape-based automatic differentiation library that supports all differentiable Tensor operations in torch |
109
+ | [**torch.jit**](https://pytorch.org/docs/stable/jit.html) | A compilation stack (TorchScript) to create serializable and optimizable models from PyTorch code |
110
+ | [**torch.nn**](https://pytorch.org/docs/stable/nn.html) | A neural networks library deeply integrated with autograd designed for maximum flexibility |
111
+ | [**torch.multiprocessing**](https://pytorch.org/docs/stable/multiprocessing.html) | Python multiprocessing, but with magical memory sharing of torch Tensors across processes. Useful for data loading and Hogwild training |
112
+ | [**torch.utils**](https://pytorch.org/docs/stable/data.html) | DataLoader and other utility functions for convenience |
113
+
114
+ Usually, PyTorch is used either as:
115
+
116
+ - A replacement for NumPy to use the power of GPUs.
117
+ - A deep learning research platform that provides maximum flexibility and speed.
118
+
119
+ Elaborating Further:
120
+
121
+ ### A GPU-Ready Tensor Library
122
+
123
+ If you use NumPy, then you have used Tensors (a.k.a. ndarray).
124
+
125
+ ![Tensor illustration](./docs/source/_static/img/tensor_illustration.png)
126
+
127
+ PyTorch provides Tensors that can live either on the CPU or the GPU and accelerates the
128
+ computation by a huge amount.
129
+
130
+ We provide a wide variety of tensor routines to accelerate and fit your scientific computation needs
131
+ such as slicing, indexing, mathematical operations, linear algebra, reductions.
132
+ And they are fast!
133
+
134
+ ### Dynamic Neural Networks: Tape-Based Autograd
135
+
136
+ PyTorch has a unique way of building neural networks: using and replaying a tape recorder.
137
+
138
+ Most frameworks such as TensorFlow, Theano, Caffe, and CNTK have a static view of the world.
139
+ One has to build a neural network and reuse the same structure again and again.
140
+ Changing the way the network behaves means that one has to start from scratch.
141
+
142
+ With PyTorch, we use a technique called reverse-mode auto-differentiation, which allows you to
143
+ change the way your network behaves arbitrarily with zero lag or overhead. Our inspiration comes
144
+ from several research papers on this topic, as well as current and past work such as
145
+ [torch-autograd](https://github.com/twitter/torch-autograd),
146
+ [autograd](https://github.com/HIPS/autograd),
147
+ [Chainer](https://chainer.org), etc.
148
+
149
+ While this technique is not unique to PyTorch, it's one of the fastest implementations of it to date.
150
+ You get the best of speed and flexibility for your crazy research.
151
+
152
+ ![Dynamic graph](https://github.com/pytorch/pytorch/blob/main/docs/source/_static/img/dynamic_graph.gif)
153
+
154
+ ### Python First
155
+
156
+ PyTorch is not a Python binding into a monolithic C++ framework.
157
+ It is built to be deeply integrated into Python.
158
+ You can use it naturally like you would use [NumPy](https://www.numpy.org/) / [SciPy](https://www.scipy.org/) / [scikit-learn](https://scikit-learn.org) etc.
159
+ You can write your new neural network layers in Python itself, using your favorite libraries
160
+ and use packages such as [Cython](https://cython.org/) and [Numba](http://numba.pydata.org/).
161
+ Our goal is to not reinvent the wheel where appropriate.
162
+
163
+ ### Imperative Experiences
164
+
165
+ PyTorch is designed to be intuitive, linear in thought, and easy to use.
166
+ When you execute a line of code, it gets executed. There isn't an asynchronous view of the world.
167
+ When you drop into a debugger or receive error messages and stack traces, understanding them is straightforward.
168
+ The stack trace points to exactly where your code was defined.
169
+ We hope you never spend hours debugging your code because of bad stack traces or asynchronous and opaque execution engines.
170
+
171
+ ### Fast and Lean
172
+
173
+ PyTorch has minimal framework overhead. We integrate acceleration libraries
174
+ such as [Intel MKL](https://software.intel.com/mkl) and NVIDIA ([cuDNN](https://developer.nvidia.com/cudnn), [NCCL](https://developer.nvidia.com/nccl)) to maximize speed.
175
+ At the core, its CPU and GPU Tensor and neural network backends
176
+ are mature and have been tested for years.
177
+
178
+ Hence, PyTorch is quite fast — whether you run small or large neural networks.
179
+
180
+ The memory usage in PyTorch is extremely efficient compared to Torch or some of the alternatives.
181
+ We've written custom memory allocators for the GPU to make sure that
182
+ your deep learning models are maximally memory efficient.
183
+ This enables you to train bigger deep learning models than before.
184
+
185
+ ### Extensions Without Pain
186
+
187
+ Writing new neural network modules, or interfacing with PyTorch's Tensor API was designed to be straightforward
188
+ and with minimal abstractions.
189
+
190
+ You can write new neural network layers in Python using the torch API
191
+ [or your favorite NumPy-based libraries such as SciPy](https://pytorch.org/tutorials/advanced/numpy_extensions_tutorial.html).
192
+
193
+ If you want to write your layers in C/C++, we provide a convenient extension API that is efficient and with minimal boilerplate.
194
+ No wrapper code needs to be written. You can see [a tutorial here](https://pytorch.org/tutorials/advanced/cpp_extension.html) and [an example here](https://github.com/pytorch/extension-cpp).
195
+
196
+
197
+ ## Installation
198
+
199
+ ### Binaries
200
+ Commands to install binaries via Conda or pip wheels are on our website: [https://pytorch.org/get-started/locally/](https://pytorch.org/get-started/locally/)
201
+
202
+
203
+ #### NVIDIA Jetson Platforms
204
+
205
+ Python wheels for NVIDIA's Jetson Nano, Jetson TX1/TX2, Jetson Xavier NX/AGX, and Jetson AGX Orin are provided [here](https://forums.developer.nvidia.com/t/pytorch-for-jetson-version-1-10-now-available/72048) and the L4T container is published [here](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/l4t-pytorch)
206
+
207
+ They require JetPack 4.2 and above, and [@dusty-nv](https://github.com/dusty-nv) and [@ptrblck](https://github.com/ptrblck) are maintaining them.
208
+
209
+
210
+ ### From Source
211
+
212
+ #### Prerequisites
213
+ If you are installing from source, you will need:
214
+ - Python 3.8 or later (for Linux, Python 3.8.1+ is needed)
215
+ - A compiler that fully supports C++17, such as clang or gcc (especially for aarch64, gcc 9.4.0 or newer is required)
216
+
217
+ We highly recommend installing an [Anaconda](https://www.anaconda.com/download) environment. You will get a high-quality BLAS library (MKL) and you get controlled dependency versions regardless of your Linux distro.
218
+
219
+ If you want to compile with CUDA support, [select a supported version of CUDA from our support matrix](https://pytorch.org/get-started/locally/), then install the following:
220
+ - [NVIDIA CUDA](https://developer.nvidia.com/cuda-downloads)
221
+ - [NVIDIA cuDNN](https://developer.nvidia.com/cudnn) v7 or above
222
+ - [Compiler](https://gist.github.com/ax3l/9489132) compatible with CUDA
223
+
224
+ Note: You could refer to the [cuDNN Support Matrix](https://docs.nvidia.com/deeplearning/cudnn/pdf/cuDNN-Support-Matrix.pdf) for cuDNN versions with the various supported CUDA, CUDA driver and NVIDIA hardware
225
+
226
+ If you want to disable CUDA support, export the environment variable `USE_CUDA=0`.
227
+ Other potentially useful environment variables may be found in `setup.py`.
228
+
229
+ If you are building for NVIDIA's Jetson platforms (Jetson Nano, TX1, TX2, AGX Xavier), Instructions to install PyTorch for Jetson Nano are [available here](https://devtalk.nvidia.com/default/topic/1049071/jetson-nano/pytorch-for-jetson-nano/)
230
+
231
+ If you want to compile with ROCm support, install
232
+ - [AMD ROCm](https://rocm.docs.amd.com/en/latest/deploy/linux/quick_start.html) 4.0 and above installation
233
+ - ROCm is currently supported only for Linux systems.
234
+
235
+ If you want to disable ROCm support, export the environment variable `USE_ROCM=0`.
236
+ Other potentially useful environment variables may be found in `setup.py`.
237
+
238
+ #### Install Dependencies
239
+
240
+ **Common**
241
+
242
+ ```bash
243
+ conda install cmake ninja
244
+ # Run this command from the PyTorch directory after cloning the source code using the “Get the PyTorch Source“ section below
245
+ pip install -r requirements.txt
246
+ ```
247
+
248
+ **On Linux**
249
+
250
+ ```bash
251
+ conda install mkl mkl-include
252
+ # CUDA only: Add LAPACK support for the GPU if needed
253
+ conda install -c pytorch magma-cuda110 # or the magma-cuda* that matches your CUDA version from https://anaconda.org/pytorch/repo
254
+
255
+ # (optional) If using torch.compile with inductor/triton, install the matching version of triton
256
+ # Run from the pytorch directory after cloning
257
+ make triton
258
+ ```
259
+
260
+ **On MacOS**
261
+
262
+ ```bash
263
+ # Add this package on intel x86 processor machines only
264
+ conda install mkl mkl-include
265
+ # Add these packages if torch.distributed is needed
266
+ conda install pkg-config libuv
267
+ ```
268
+
269
+ **On Windows**
270
+
271
+ ```bash
272
+ conda install mkl mkl-include
273
+ # Add these packages if torch.distributed is needed.
274
+ # Distributed package support on Windows is a prototype feature and is subject to changes.
275
+ conda install -c conda-forge libuv=1.39
276
+ ```
277
+
278
+ #### Get the PyTorch Source
279
+ ```bash
280
+ git clone --recursive https://github.com/pytorch/pytorch
281
+ cd pytorch
282
+ # if you are updating an existing checkout
283
+ git submodule sync
284
+ git submodule update --init --recursive
285
+ ```
286
+
287
+ #### Install PyTorch
288
+ **On Linux**
289
+
290
+ If you would like to compile PyTorch with [new C++ ABI](https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_dual_abi.html) enabled, then first run this command:
291
+ ```bash
292
+ export _GLIBCXX_USE_CXX11_ABI=1
293
+ ```
294
+
295
+ If you're compiling for AMD ROCm then first run this command:
296
+ ```bash
297
+ # Only run this if you're compiling for ROCm
298
+ python tools/amd_build/build_amd.py
299
+ ```
300
+
301
+ Install PyTorch
302
+ ```bash
303
+ export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
304
+ python setup.py develop
305
+ ```
306
+
307
+ > _Aside:_ If you are using [Anaconda](https://www.anaconda.com/distribution/#download-section), you may experience an error caused by the linker:
308
+ >
309
+ > ```plaintext
310
+ > build/temp.linux-x86_64-3.7/torch/csrc/stub.o: file not recognized: file format not recognized
311
+ > collect2: error: ld returned 1 exit status
312
+ > error: command 'g++' failed with exit status 1
313
+ > ```
314
+ >
315
+ > This is caused by `ld` from the Conda environment shadowing the system `ld`. You should use a newer version of Python that fixes this issue. The recommended Python version is 3.8.1+.
316
+
317
+ **On macOS**
318
+
319
+ ```bash
320
+ python3 setup.py develop
321
+ ```
322
+
323
+ **On Windows**
324
+
325
+ Choose Correct Visual Studio Version.
326
+
327
+ PyTorch CI uses Visual C++ BuildTools, which come with Visual Studio Enterprise,
328
+ Professional, or Community Editions. You can also install the build tools from
329
+ https://visualstudio.microsoft.com/visual-cpp-build-tools/. The build tools *do not*
330
+ come with Visual Studio Code by default.
331
+
332
+ If you want to build legacy python code, please refer to [Building on legacy code and CUDA](https://github.com/pytorch/pytorch/blob/main/CONTRIBUTING.md#building-on-legacy-code-and-cuda)
333
+
334
+ **CPU-only builds**
335
+
336
+ In this mode PyTorch computations will run on your CPU, not your GPU
337
+
338
+ ```cmd
339
+ conda activate
340
+ python setup.py develop
341
+ ```
342
+
343
+ Note on OpenMP: The desired OpenMP implementation is Intel OpenMP (iomp). In order to link against iomp, you'll need to manually download the library and set up the building environment by tweaking `CMAKE_INCLUDE_PATH` and `LIB`. The instruction [here](https://github.com/pytorch/pytorch/blob/main/docs/source/notes/windows.rst#building-from-source) is an example for setting up both MKL and Intel OpenMP. Without these configurations for CMake, Microsoft Visual C OpenMP runtime (vcomp) will be used.
344
+
345
+ **CUDA based build**
346
+
347
+ In this mode PyTorch computations will leverage your GPU via CUDA for faster number crunching
348
+
349
+ [NVTX](https://docs.nvidia.com/gameworks/content/gameworkslibrary/nvtx/nvidia_tools_extension_library_nvtx.htm) is needed to build Pytorch with CUDA.
350
+ NVTX is a part of CUDA distributive, where it is called "Nsight Compute". To install it onto an already installed CUDA run CUDA installation once again and check the corresponding checkbox.
351
+ Make sure that CUDA with Nsight Compute is installed after Visual Studio.
352
+
353
+ Currently, VS 2017 / 2019, and Ninja are supported as the generator of CMake. If `ninja.exe` is detected in `PATH`, then Ninja will be used as the default generator, otherwise, it will use VS 2017 / 2019.
354
+ <br/> If Ninja is selected as the generator, the latest MSVC will get selected as the underlying toolchain.
355
+
356
+ Additional libraries such as
357
+ [Magma](https://developer.nvidia.com/magma), [oneDNN, a.k.a. MKLDNN or DNNL](https://github.com/oneapi-src/oneDNN), and [Sccache](https://github.com/mozilla/sccache) are often needed. Please refer to the [installation-helper](https://github.com/pytorch/pytorch/tree/main/.ci/pytorch/win-test-helpers/installation-helpers) to install them.
358
+
359
+ You can refer to the [build_pytorch.bat](https://github.com/pytorch/pytorch/blob/main/.ci/pytorch/win-test-helpers/build_pytorch.bat) script for some other environment variables configurations
360
+
361
+
362
+ ```cmd
363
+ cmd
364
+
365
+ :: Set the environment variables after you have downloaded and unzipped the mkl package,
366
+ :: else CMake would throw an error as `Could NOT find OpenMP`.
367
+ set CMAKE_INCLUDE_PATH={Your directory}\mkl\include
368
+ set LIB={Your directory}\mkl\lib;%LIB%
369
+
370
+ :: Read the content in the previous section carefully before you proceed.
371
+ :: [Optional] If you want to override the underlying toolset used by Ninja and Visual Studio with CUDA, please run the following script block.
372
+ :: "Visual Studio 2019 Developer Command Prompt" will be run automatically.
373
+ :: Make sure you have CMake >= 3.12 before you do this when you use the Visual Studio generator.
374
+ set CMAKE_GENERATOR_TOOLSET_VERSION=14.27
375
+ set DISTUTILS_USE_SDK=1
376
+ for /f "usebackq tokens=*" %i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -version [15^,17^) -products * -latest -property installationPath`) do call "%i\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%CMAKE_GENERATOR_TOOLSET_VERSION%
377
+
378
+ :: [Optional] If you want to override the CUDA host compiler
379
+ set CUDAHOSTCXX=C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\bin\HostX64\x64\cl.exe
380
+
381
+ python setup.py develop
382
+
383
+ ```
384
+
385
+ ##### Adjust Build Options (Optional)
386
+
387
+ You can adjust the configuration of cmake variables optionally (without building first), by doing
388
+ the following. For example, adjusting the pre-detected directories for CuDNN or BLAS can be done
389
+ with such a step.
390
+
391
+ On Linux
392
+ ```bash
393
+ export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
394
+ python setup.py build --cmake-only
395
+ ccmake build # or cmake-gui build
396
+ ```
397
+
398
+ On macOS
399
+ ```bash
400
+ export CMAKE_PREFIX_PATH=${CONDA_PREFIX:-"$(dirname $(which conda))/../"}
401
+ MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ python setup.py build --cmake-only
402
+ ccmake build # or cmake-gui build
403
+ ```
404
+
405
+ ### Docker Image
406
+
407
+ #### Using pre-built images
408
+
409
+ You can also pull a pre-built docker image from Docker Hub and run with docker v19.03+
410
+
411
+ ```bash
412
+ docker run --gpus all --rm -ti --ipc=host pytorch/pytorch:latest
413
+ ```
414
+
415
+ Please note that PyTorch uses shared memory to share data between processes, so if torch multiprocessing is used (e.g.
416
+ for multithreaded data loaders) the default shared memory segment size that container runs with is not enough, and you
417
+ should increase shared memory size either with `--ipc=host` or `--shm-size` command line options to `nvidia-docker run`.
418
+
419
+ #### Building the image yourself
420
+
421
+ **NOTE:** Must be built with a docker version > 18.06
422
+
423
+ The `Dockerfile` is supplied to build images with CUDA 11.1 support and cuDNN v8.
424
+ You can pass `PYTHON_VERSION=x.y` make variable to specify which Python version is to be used by Miniconda, or leave it
425
+ unset to use the default.
426
+
427
+ ```bash
428
+ make -f docker.Makefile
429
+ # images are tagged as docker.io/${your_docker_username}/pytorch
430
+ ```
431
+
432
+ You can also pass the `CMAKE_VARS="..."` environment variable to specify additional CMake variables to be passed to CMake during the build.
433
+ See [setup.py](./setup.py) for the list of available variables.
434
+
435
+ ```bash
436
+ CMAKE_VARS="BUILD_CAFFE2=ON BUILD_CAFFE2_OPS=ON" make -f docker.Makefile
437
+ ```
438
+
439
+ ### Building the Documentation
440
+
441
+ To build documentation in various formats, you will need [Sphinx](http://www.sphinx-doc.org) and the
442
+ readthedocs theme.
443
+
444
+ ```bash
445
+ cd docs/
446
+ pip install -r requirements.txt
447
+ ```
448
+ You can then build the documentation by running `make <format>` from the
449
+ `docs/` folder. Run `make` to get a list of all available output formats.
450
+
451
+ If you get a katex error run `npm install katex`. If it persists, try
452
+ `npm install -g katex`
453
+
454
+ > Note: if you installed `nodejs` with a different package manager (e.g.,
455
+ `conda`) then `npm` will probably install a version of `katex` that is not
456
+ compatible with your version of `nodejs` and doc builds will fail.
457
+ A combination of versions that is known to work is `node@6.13.1` and
458
+ `katex@0.13.18`. To install the latter with `npm` you can run
459
+ ```npm install -g katex@0.13.18```
460
+
461
+ ### Previous Versions
462
+
463
+ Installation instructions and binaries for previous PyTorch versions may be found
464
+ on [our website](https://pytorch.org/previous-versions).
465
+
466
+
467
+ ## Getting Started
468
+
469
+ Three-pointers to get you started:
470
+ - [Tutorials: get you started with understanding and using PyTorch](https://pytorch.org/tutorials/)
471
+ - [Examples: easy to understand PyTorch code across all domains](https://github.com/pytorch/examples)
472
+ - [The API Reference](https://pytorch.org/docs/)
473
+ - [Glossary](https://github.com/pytorch/pytorch/blob/main/GLOSSARY.md)
474
+
475
+ ## Resources
476
+
477
+ * [PyTorch.org](https://pytorch.org/)
478
+ * [PyTorch Tutorials](https://pytorch.org/tutorials/)
479
+ * [PyTorch Examples](https://github.com/pytorch/examples)
480
+ * [PyTorch Models](https://pytorch.org/hub/)
481
+ * [Intro to Deep Learning with PyTorch from Udacity](https://www.udacity.com/course/deep-learning-pytorch--ud188)
482
+ * [Intro to Machine Learning with PyTorch from Udacity](https://www.udacity.com/course/intro-to-machine-learning-nanodegree--nd229)
483
+ * [Deep Neural Networks with PyTorch from Coursera](https://www.coursera.org/learn/deep-neural-networks-with-pytorch)
484
+ * [PyTorch Twitter](https://twitter.com/PyTorch)
485
+ * [PyTorch Blog](https://pytorch.org/blog/)
486
+ * [PyTorch YouTube](https://www.youtube.com/channel/UCWXI5YeOsh03QvJ59PMaXFw)
487
+
488
+ ## Communication
489
+ * Forums: Discuss implementations, research, etc. https://discuss.pytorch.org
490
+ * GitHub Issues: Bug reports, feature requests, install issues, RFCs, thoughts, etc.
491
+ * Slack: The [PyTorch Slack](https://pytorch.slack.com/) hosts a primary audience of moderate to experienced PyTorch users and developers for general chat, online discussions, collaboration, etc. If you are a beginner looking for help, the primary medium is [PyTorch Forums](https://discuss.pytorch.org). If you need a slack invite, please fill this form: https://goo.gl/forms/PP1AGvNHpSaJP8to1
492
+ * Newsletter: No-noise, a one-way email newsletter with important announcements about PyTorch. You can sign-up here: https://eepurl.com/cbG0rv
493
+ * Facebook Page: Important announcements about PyTorch. https://www.facebook.com/pytorch
494
+ * For brand guidelines, please visit our website at [pytorch.org](https://pytorch.org/)
495
+
496
+ ## Releases and Contributing
497
+
498
+ Typically, PyTorch has three minor releases a year. Please let us know if you encounter a bug by [filing an issue](https://github.com/pytorch/pytorch/issues).
499
+
500
+ We appreciate all contributions. If you are planning to contribute back bug-fixes, please do so without any further discussion.
501
+
502
+ If you plan to contribute new features, utility functions, or extensions to the core, please first open an issue and discuss the feature with us.
503
+ Sending a PR without discussion might end up resulting in a rejected PR because we might be taking the core in a different direction than you might be aware of.
504
+
505
+ To learn more about making a contribution to Pytorch, please see our [Contribution page](CONTRIBUTING.md). For more information about PyTorch releases, see [Release page](RELEASE.md).
506
+
507
+ ## The Team
508
+
509
+ PyTorch is a community-driven project with several skillful engineers and researchers contributing to it.
510
+
511
+ PyTorch is currently maintained by [Soumith Chintala](http://soumith.ch), [Gregory Chanan](https://github.com/gchanan), [Dmytro Dzhulgakov](https://github.com/dzhulgakov), [Edward Yang](https://github.com/ezyang), and [Nikita Shulga](https://github.com/malfet) with major contributions coming from hundreds of talented individuals in various forms and means.
512
+ A non-exhaustive but growing list needs to mention: Trevor Killeen, Sasank Chilamkurthy, Sergey Zagoruyko, Adam Lerer, Francisco Massa, Alykhan Tejani, Luca Antiga, Alban Desmaison, Andreas Koepf, James Bradbury, Zeming Lin, Yuandong Tian, Guillaume Lample, Marat Dukhan, Natalia Gimelshein, Christian Sarofeen, Martin Raison, Edward Yang, Zachary Devito.
513
+
514
+ Note: This project is unrelated to [hughperkins/pytorch](https://github.com/hughperkins/pytorch) with the same name. Hugh is a valuable contributor to the Torch community and has helped with many things Torch and PyTorch.
515
+
516
+ ## License
517
+
518
+ PyTorch has a BSD-style license, as found in the [LICENSE](LICENSE) file.
519
+
520
+
llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/NOTICE ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ =======================================================================
2
+ Software under third_party
3
+ =======================================================================
4
+ Software libraries under third_party are provided as github submodule
5
+ links, and their content is not part of the Caffe2 codebase. Their
6
+ licences can be found under the respective software repositories.
7
+
8
+ =======================================================================
9
+ Earlier BSD License
10
+ =======================================================================
11
+ Early development of Caffe2 in 2015 and early 2016 is licensed under the
12
+ BSD license. The license is attached below:
13
+
14
+ All contributions by Facebook:
15
+ Copyright (c) 2016 Facebook Inc.
16
+
17
+ All contributions by Google:
18
+ Copyright (c) 2015 Google Inc.
19
+ All rights reserved.
20
+
21
+ All contributions by Yangqing Jia:
22
+ Copyright (c) 2015 Yangqing Jia
23
+ All rights reserved.
24
+
25
+ All contributions by Kakao Brain:
26
+ Copyright 2019-2020 Kakao Brain
27
+
28
+ All other contributions:
29
+ Copyright(c) 2015, 2016 the respective contributors
30
+ All rights reserved.
31
+
32
+ Redistribution and use in source and binary forms, with or without
33
+ modification, are permitted provided that the following conditions are met:
34
+
35
+ 1. Redistributions of source code must retain the above copyright notice, this
36
+ list of conditions and the following disclaimer.
37
+ 2. Redistributions in binary form must reproduce the above copyright notice,
38
+ this list of conditions and the following disclaimer in the documentation
39
+ and/or other materials provided with the distribution.
40
+
41
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
42
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
43
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
44
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
45
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
46
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
48
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
49
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
50
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
51
+
52
+
53
+ =======================================================================
54
+ Caffe's BSD License
55
+ =======================================================================
56
+ Some parts of the caffe2 code is derived from the original Caffe code, which is
57
+ created by Yangqing Jia and is now a BSD-licensed open-source project. The Caffe
58
+ license is as follows:
59
+
60
+ COPYRIGHT
61
+
62
+ All contributions by the University of California:
63
+ Copyright (c) 2014, The Regents of the University of California (Regents)
64
+ All rights reserved.
65
+
66
+ All other contributions:
67
+ Copyright (c) 2014, the respective contributors
68
+ All rights reserved.
69
+
70
+ Caffe uses a shared copyright model: each contributor holds copyright over
71
+ their contributions to Caffe. The project versioning records all such
72
+ contribution and copyright details. If a contributor wants to further mark
73
+ their specific copyright on a particular contribution, they should indicate
74
+ their copyright solely in the commit message of the change when it is
75
+ committed.
76
+
77
+ LICENSE
78
+
79
+ Redistribution and use in source and binary forms, with or without
80
+ modification, are permitted provided that the following conditions are met:
81
+
82
+ 1. Redistributions of source code must retain the above copyright notice, this
83
+ list of conditions and the following disclaimer.
84
+ 2. Redistributions in binary form must reproduce the above copyright notice,
85
+ this list of conditions and the following disclaimer in the documentation
86
+ and/or other materials provided with the distribution.
87
+
88
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
89
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
90
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
91
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
92
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
93
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
94
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
95
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
96
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
97
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
98
+
99
+ CONTRIBUTION AGREEMENT
100
+
101
+ By contributing to the BVLC/caffe repository through pull-request, comment,
102
+ or otherwise, the contributor releases their content to the
103
+ license and copyright terms herein.
104
+
105
+ =======================================================================
106
+ Caffe2's Apache License
107
+ =======================================================================
108
+
109
+ This repo contains Caffe2 code, which was previously licensed under
110
+ Apache License Version 2.0:
111
+
112
+ Apache License
113
+ Version 2.0, January 2004
114
+ http://www.apache.org/licenses/
115
+
116
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
117
+
118
+ 1. Definitions.
119
+
120
+ "License" shall mean the terms and conditions for use, reproduction,
121
+ and distribution as defined by Sections 1 through 9 of this document.
122
+
123
+ "Licensor" shall mean the copyright owner or entity authorized by
124
+ the copyright owner that is granting the License.
125
+
126
+ "Legal Entity" shall mean the union of the acting entity and all
127
+ other entities that control, are controlled by, or are under common
128
+ control with that entity. For the purposes of this definition,
129
+ "control" means (i) the power, direct or indirect, to cause the
130
+ direction or management of such entity, whether by contract or
131
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
132
+ outstanding shares, or (iii) beneficial ownership of such entity.
133
+
134
+ "You" (or "Your") shall mean an individual or Legal Entity
135
+ exercising permissions granted by this License.
136
+
137
+ "Source" form shall mean the preferred form for making modifications,
138
+ including but not limited to software source code, documentation
139
+ source, and configuration files.
140
+
141
+ "Object" form shall mean any form resulting from mechanical
142
+ transformation or translation of a Source form, including but
143
+ not limited to compiled object code, generated documentation,
144
+ and conversions to other media types.
145
+
146
+ "Work" shall mean the work of authorship, whether in Source or
147
+ Object form, made available under the License, as indicated by a
148
+ copyright notice that is included in or attached to the work
149
+ (an example is provided in the Appendix below).
150
+
151
+ "Derivative Works" shall mean any work, whether in Source or Object
152
+ form, that is based on (or derived from) the Work and for which the
153
+ editorial revisions, annotations, elaborations, or other modifications
154
+ represent, as a whole, an original work of authorship. For the purposes
155
+ of this License, Derivative Works shall not include works that remain
156
+ separable from, or merely link (or bind by name) to the interfaces of,
157
+ the Work and Derivative Works thereof.
158
+
159
+ "Contribution" shall mean any work of authorship, including
160
+ the original version of the Work and any modifications or additions
161
+ to that Work or Derivative Works thereof, that is intentionally
162
+ submitted to Licensor for inclusion in the Work by the copyright owner
163
+ or by an individual or Legal Entity authorized to submit on behalf of
164
+ the copyright owner. For the purposes of this definition, "submitted"
165
+ means any form of electronic, verbal, or written communication sent
166
+ to the Licensor or its representatives, including but not limited to
167
+ communication on electronic mailing lists, source code control systems,
168
+ and issue tracking systems that are managed by, or on behalf of, the
169
+ Licensor for the purpose of discussing and improving the Work, but
170
+ excluding communication that is conspicuously marked or otherwise
171
+ designated in writing by the copyright owner as "Not a Contribution."
172
+
173
+ "Contributor" shall mean Licensor and any individual or Legal Entity
174
+ on behalf of whom a Contribution has been received by Licensor and
175
+ subsequently incorporated within the Work.
176
+
177
+ 2. Grant of Copyright License. Subject to the terms and conditions of
178
+ this License, each Contributor hereby grants to You a perpetual,
179
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
180
+ copyright license to reproduce, prepare Derivative Works of,
181
+ publicly display, publicly perform, sublicense, and distribute the
182
+ Work and such Derivative Works in Source or Object form.
183
+
184
+ 3. Grant of Patent License. Subject to the terms and conditions of
185
+ this License, each Contributor hereby grants to You a perpetual,
186
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
187
+ (except as stated in this section) patent license to make, have made,
188
+ use, offer to sell, sell, import, and otherwise transfer the Work,
189
+ where such license applies only to those patent claims licensable
190
+ by such Contributor that are necessarily infringed by their
191
+ Contribution(s) alone or by combination of their Contribution(s)
192
+ with the Work to which such Contribution(s) was submitted. If You
193
+ institute patent litigation against any entity (including a
194
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
195
+ or a Contribution incorporated within the Work constitutes direct
196
+ or contributory patent infringement, then any patent licenses
197
+ granted to You under this License for that Work shall terminate
198
+ as of the date such litigation is filed.
199
+
200
+ 4. Redistribution. You may reproduce and distribute copies of the
201
+ Work or Derivative Works thereof in any medium, with or without
202
+ modifications, and in Source or Object form, provided that You
203
+ meet the following conditions:
204
+
205
+ (a) You must give any other recipients of the Work or
206
+ Derivative Works a copy of this License; and
207
+
208
+ (b) You must cause any modified files to carry prominent notices
209
+ stating that You changed the files; and
210
+
211
+ (c) You must retain, in the Source form of any Derivative Works
212
+ that You distribute, all copyright, patent, trademark, and
213
+ attribution notices from the Source form of the Work,
214
+ excluding those notices that do not pertain to any part of
215
+ the Derivative Works; and
216
+
217
+ (d) If the Work includes a "NOTICE" text file as part of its
218
+ distribution, then any Derivative Works that You distribute must
219
+ include a readable copy of the attribution notices contained
220
+ within such NOTICE file, excluding those notices that do not
221
+ pertain to any part of the Derivative Works, in at least one
222
+ of the following places: within a NOTICE text file distributed
223
+ as part of the Derivative Works; within the Source form or
224
+ documentation, if provided along with the Derivative Works; or,
225
+ within a display generated by the Derivative Works, if and
226
+ wherever such third-party notices normally appear. The contents
227
+ of the NOTICE file are for informational purposes only and
228
+ do not modify the License. You may add Your own attribution
229
+ notices within Derivative Works that You distribute, alongside
230
+ or as an addendum to the NOTICE text from the Work, provided
231
+ that such additional attribution notices cannot be construed
232
+ as modifying the License.
233
+
234
+ You may add Your own copyright statement to Your modifications and
235
+ may provide additional or different license terms and conditions
236
+ for use, reproduction, or distribution of Your modifications, or
237
+ for any such Derivative Works as a whole, provided Your use,
238
+ reproduction, and distribution of the Work otherwise complies with
239
+ the conditions stated in this License.
240
+
241
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
242
+ any Contribution intentionally submitted for inclusion in the Work
243
+ by You to the Licensor shall be under the terms and conditions of
244
+ this License, without any additional terms or conditions.
245
+ Notwithstanding the above, nothing herein shall supersede or modify
246
+ the terms of any separate license agreement you may have executed
247
+ with Licensor regarding such Contributions.
248
+
249
+ 6. Trademarks. This License does not grant permission to use the trade
250
+ names, trademarks, service marks, or product names of the Licensor,
251
+ except as required for reasonable and customary use in describing the
252
+ origin of the Work and reproducing the content of the NOTICE file.
253
+
254
+ 7. Disclaimer of Warranty. Unless required by applicable law or
255
+ agreed to in writing, Licensor provides the Work (and each
256
+ Contributor provides its Contributions) on an "AS IS" BASIS,
257
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
258
+ implied, including, without limitation, any warranties or conditions
259
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
260
+ PARTICULAR PURPOSE. You are solely responsible for determining the
261
+ appropriateness of using or redistributing the Work and assume any
262
+ risks associated with Your exercise of permissions under this License.
263
+
264
+ 8. Limitation of Liability. In no event and under no legal theory,
265
+ whether in tort (including negligence), contract, or otherwise,
266
+ unless required by applicable law (such as deliberate and grossly
267
+ negligent acts) or agreed to in writing, shall any Contributor be
268
+ liable to You for damages, including any direct, indirect, special,
269
+ incidental, or consequential damages of any character arising as a
270
+ result of this License or out of the use or inability to use the
271
+ Work (including but not limited to damages for loss of goodwill,
272
+ work stoppage, computer failure or malfunction, or any and all
273
+ other commercial damages or losses), even if such Contributor
274
+ has been advised of the possibility of such damages.
275
+
276
+ 9. Accepting Warranty or Additional Liability. While redistributing
277
+ the Work or Derivative Works thereof, You may choose to offer,
278
+ and charge a fee for, acceptance of support, warranty, indemnity,
279
+ or other liability obligations and/or rights consistent with this
280
+ License. However, in accepting such obligations, You may act only
281
+ on Your own behalf and on Your sole responsibility, not on behalf
282
+ of any other Contributor, and only if You agree to indemnify,
283
+ defend, and hold each Contributor harmless for any liability
284
+ incurred by, or claims asserted against, such Contributor by reason
285
+ of your accepting any such warranty or additional liability.
286
+
287
+ =======================================================================
288
+ Cephes's 3-Clause BSD License
289
+ =======================================================================
290
+
291
+ Code derived from implementations in the Cephes Math Library should mention
292
+ its derivation and reference the following license:
293
+
294
+ 3-Clause BSD License for the Cephes Math Library
295
+ Copyright (c) 2018, Steven Moshier
296
+ All rights reserved.
297
+
298
+ Redistribution and use in source and binary forms, with or without
299
+ modification, are permitted provided that the following conditions are met:
300
+
301
+ * Redistributions of source code must retain the above copyright
302
+ notice, this list of conditions and the following disclaimer.
303
+
304
+ * Redistributions in binary form must reproduce the above copyright
305
+ notice, this list of conditions and the following disclaimer in the
306
+ documentation and/or other materials provided with the distribution.
307
+
308
+ * Neither the name of the nor the
309
+ names of its contributors may be used to endorse or promote products
310
+ derived from this software without specific prior written permission.
311
+
312
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
313
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
314
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
315
+ DISCLAIMED. IN NO EVENT SHALL Steven Moshier BE LIABLE FOR ANY
316
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
317
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
318
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
319
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
320
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
321
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
322
+
323
+
324
+ =======================================================================
325
+ SciPy's 3-Clause BSD License
326
+ =======================================================================
327
+
328
+ Code derived from implementations in SciPy should mention its derivation
329
+ and reference the following license:
330
+
331
+ Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers.
332
+ All rights reserved.
333
+
334
+ Redistribution and use in source and binary forms, with or without
335
+ modification, are permitted provided that the following conditions
336
+ are met:
337
+
338
+ 1. Redistributions of source code must retain the above copyright
339
+ notice, this list of conditions and the following disclaimer.
340
+
341
+ 2. Redistributions in binary form must reproduce the above
342
+ copyright notice, this list of conditions and the following
343
+ disclaimer in the documentation and/or other materials provided
344
+ with the distribution.
345
+
346
+ 3. Neither the name of the copyright holder nor the names of its
347
+ contributors may be used to endorse or promote products derived
348
+ from this software without specific prior written permission.
349
+
350
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
351
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
352
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
353
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
354
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
355
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
356
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
357
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
358
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
359
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
360
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
361
+
362
+ =======================================================================
363
+ Boost's 1.0 Software License
364
+ =======================================================================
365
+
366
+ Code derived from implementations in Boost 1.0 should mention its
367
+ derivation and reference the following license:
368
+
369
+ Boost Software License - Version 1.0 - August 17th, 2003
370
+
371
+ Permission is hereby granted, free of charge, to any person or organization
372
+ obtaining a copy of the software and accompanying documentation covered by
373
+ this license (the "Software") to use, reproduce, display, distribute,
374
+ execute, and transmit the Software, and to prepare derivative works of the
375
+ Software, and to permit third-parties to whom the Software is furnished to
376
+ do so, all subject to the following:
377
+
378
+ The copyright notices in the Software and this entire statement, including
379
+ the above license grant, this restriction and the following disclaimer,
380
+ must be included in all copies of the Software, in whole or in part, and
381
+ all derivative works of the Software, unless such copies or derivative
382
+ works are solely in the form of machine-executable object code generated by
383
+ a source language processor.
384
+
385
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
386
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
387
+ FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
388
+ SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
389
+ FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
390
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
391
+ DEALINGS IN THE SOFTWARE.
392
+
393
+ END OF TERMS AND CONDITIONS
394
+
395
+ APPENDIX: How to apply the Apache License to your work.
396
+
397
+ To apply the Apache License to your work, attach the following
398
+ boilerplate notice, with the fields enclosed by brackets "[]"
399
+ replaced with your own identifying information. (Don't include
400
+ the brackets!) The text should be enclosed in the appropriate
401
+ comment syntax for the file format. We also recommend that a
402
+ file or class name and description of purpose be included on the
403
+ same "printed page" as the copyright notice for easier
404
+ identification within third-party archives.
405
+
406
+ Copyright [yyyy] [name of copyright owner]
407
+
408
+ Licensed under the Apache License, Version 2.0 (the "License");
409
+ you may not use this file except in compliance with the License.
410
+ You may obtain a copy of the License at
411
+
412
+ http://www.apache.org/licenses/LICENSE-2.0
413
+
414
+ Unless required by applicable law or agreed to in writing, software
415
+ distributed under the License is distributed on an "AS IS" BASIS,
416
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
417
+ See the License for the specific language governing permissions and
418
+ limitations under the License.
419
+
420
+ =======================================================================
421
+ PILLOW-SIMD Software License
422
+ =======================================================================
423
+
424
+ Code derived from implementations in PILLOW-SIMD should mention its derivation
425
+ and reference the following license:
426
+
427
+ The Python Imaging Library (PIL) is
428
+
429
+ Copyright © 1997-2011 by Secret Labs AB
430
+ Copyright © 1995-2011 by Fredrik Lundh
431
+
432
+ Pillow is the friendly PIL fork. It is
433
+
434
+ Copyright © 2010-2022 by Alex Clark and contributors
435
+
436
+ Like PIL, Pillow is licensed under the open source HPND License:
437
+
438
+ By obtaining, using, and/or copying this software and/or its associated
439
+ documentation, you agree that you have read, understood, and will comply
440
+ with the following terms and conditions:
441
+
442
+ Permission to use, copy, modify, and distribute this software and its
443
+ associated documentation for any purpose and without fee is hereby granted,
444
+ provided that the above copyright notice appears in all copies, and that
445
+ both that copyright notice and this permission notice appear in supporting
446
+ documentation, and that the name of Secret Labs AB or the author not be
447
+ used in advertising or publicity pertaining to distribution of the software
448
+ without specific, written prior permission.
449
+
450
+ SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
451
+ SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
452
+ IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,
453
+ INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
454
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
455
+ OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
456
+ PERFORMANCE OF THIS SOFTWARE.
llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/REQUESTED ADDED
File without changes
llava_next/lib/python3.10/site-packages/torch-2.1.2.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.34.2)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-linux_x86_64
5
+
llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/RECORD ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ websockets-11.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ websockets-11.0.3.dist-info/LICENSE,sha256=PWoMBQ2L7FL6utUC5F-yW9ArytvXDeo01Ee2oP9Obag,1514
3
+ websockets-11.0.3.dist-info/METADATA,sha256=p679f2CwWdb-87gsrSEpFWqlue5gFCyNJbYqCucVpmg,6619
4
+ websockets-11.0.3.dist-info/RECORD,,
5
+ websockets-11.0.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ websockets-11.0.3.dist-info/WHEEL,sha256=24QVFBJBvF4a1ZC352AVuqHCJgY3xUfAV-_i6gkjtuc,225
7
+ websockets-11.0.3.dist-info/top_level.txt,sha256=CMpdKklxKsvZgCgyltxUWOHibZXZ1uYIVpca9xsQ8Hk,11
8
+ websockets/__init__.py,sha256=kezN0NeaLAYBNP8eNgIadwCf-X4qAuQjdqXVrdLm5AM,3426
9
+ websockets/__main__.py,sha256=8Dtga-XePHQ4jqgMMuXHT8XRH_hSvs8bEZ7-v49vTKg,4744
10
+ websockets/__pycache__/__init__.cpython-310.pyc,,
11
+ websockets/__pycache__/__main__.cpython-310.pyc,,
12
+ websockets/__pycache__/auth.cpython-310.pyc,,
13
+ websockets/__pycache__/client.cpython-310.pyc,,
14
+ websockets/__pycache__/connection.cpython-310.pyc,,
15
+ websockets/__pycache__/datastructures.cpython-310.pyc,,
16
+ websockets/__pycache__/exceptions.cpython-310.pyc,,
17
+ websockets/__pycache__/frames.cpython-310.pyc,,
18
+ websockets/__pycache__/headers.cpython-310.pyc,,
19
+ websockets/__pycache__/http.cpython-310.pyc,,
20
+ websockets/__pycache__/http11.cpython-310.pyc,,
21
+ websockets/__pycache__/imports.cpython-310.pyc,,
22
+ websockets/__pycache__/protocol.cpython-310.pyc,,
23
+ websockets/__pycache__/server.cpython-310.pyc,,
24
+ websockets/__pycache__/streams.cpython-310.pyc,,
25
+ websockets/__pycache__/typing.cpython-310.pyc,,
26
+ websockets/__pycache__/uri.cpython-310.pyc,,
27
+ websockets/__pycache__/utils.cpython-310.pyc,,
28
+ websockets/__pycache__/version.cpython-310.pyc,,
29
+ websockets/auth.py,sha256=VObSo1Q61jh0XFXpeL6-1ir0OXlqA8OJjoChsB_01k8,139
30
+ websockets/client.py,sha256=dfEJWRlGLaSfssMr3Lss-02n-IVosorFMD6Ub9JAI3E,12418
31
+ websockets/connection.py,sha256=UivBmLaKmEOGpL1bU8uwh1PXIqMFiOUTVRi_gM7w5Rg,333
32
+ websockets/datastructures.py,sha256=pcT7RdCI6ZfYddHWMcwPR-1A89GRpj26xgdtmZsRgiA,5738
33
+ websockets/exceptions.py,sha256=DUzr1GdPO6FDAl9C5Wb3IhjSYSomVbvWo_NTM46zWm4,10143
34
+ websockets/extensions/__init__.py,sha256=QkZsxaJVllVSp1uhdD5uPGibdbx_091GrVVfS5LXcpw,98
35
+ websockets/extensions/__pycache__/__init__.cpython-310.pyc,,
36
+ websockets/extensions/__pycache__/base.cpython-310.pyc,,
37
+ websockets/extensions/__pycache__/permessage_deflate.cpython-310.pyc,,
38
+ websockets/extensions/base.py,sha256=5shEU7lqmsLC7-y3OCWih1VdS_wOImmZwuAaEKl9kDU,3271
39
+ websockets/extensions/permessage_deflate.py,sha256=bPFOAyTUDU7IIJyCGnWfr5yZF_J8dhCwJWt7jWuYM6c,24782
40
+ websockets/frames.py,sha256=jSHawlqpEDrVcnGrKDawlINoelU9Hg5Wb0p4B_3SEl0,12537
41
+ websockets/headers.py,sha256=RYryH2zqB_2Y02BTF2KsQFfYxAM6-Kh-A3Dv_32opAA,16120
42
+ websockets/http.py,sha256=HR_IIij3xpoKkiLzGp4h5_NkVr2a8ZeCqGUopo6U4Rs,644
43
+ websockets/http11.py,sha256=QcZ7u-UYbO98xQXrUz43qgaBXk-AyoQBHJBR0J9qYRE,12565
44
+ websockets/imports.py,sha256=SXXs0glid-UHcwla5yjR72DIbGeUTrS9VFagPvPvRNY,2790
45
+ websockets/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
46
+ websockets/legacy/__pycache__/__init__.cpython-310.pyc,,
47
+ websockets/legacy/__pycache__/async_timeout.cpython-310.pyc,,
48
+ websockets/legacy/__pycache__/auth.cpython-310.pyc,,
49
+ websockets/legacy/__pycache__/client.cpython-310.pyc,,
50
+ websockets/legacy/__pycache__/compatibility.cpython-310.pyc,,
51
+ websockets/legacy/__pycache__/framing.cpython-310.pyc,,
52
+ websockets/legacy/__pycache__/handshake.cpython-310.pyc,,
53
+ websockets/legacy/__pycache__/http.cpython-310.pyc,,
54
+ websockets/legacy/__pycache__/protocol.cpython-310.pyc,,
55
+ websockets/legacy/__pycache__/server.cpython-310.pyc,,
56
+ websockets/legacy/async_timeout.py,sha256=nHW_nJYnxtuprwPduZMTl789KAymwmv0ukLbzm2Z8yU,8540
57
+ websockets/legacy/auth.py,sha256=WP68nZ1KAS0YCfNRyYG2M6LrNmT6xa430YnAjoeAP3g,6287
58
+ websockets/legacy/client.py,sha256=cEa1xlsuUhJk9T0RKdRSWeYm8WGV2M7M8JZeqwp2tpE,26555
59
+ websockets/legacy/compatibility.py,sha256=HRmodUeop_0hT7TG8_qIZrXmfGYDFioSmg3jCoPs0Ow,758
60
+ websockets/legacy/framing.py,sha256=M4J6ZPRK-zNqY_UgPQ4Qppc4R64aSMftO7FR_0VpG-Q,4998
61
+ websockets/legacy/handshake.py,sha256=RggPKl-w8oFJZQYZR0IdIOTrsz040pYp0Gu4L_D7_4U,5479
62
+ websockets/legacy/http.py,sha256=qmrM7pa0kuuJIroMVahBAH8_ZVqkD91YhwVux_xpfeI,6938
63
+ websockets/legacy/protocol.py,sha256=W_et77gFzuJ4IWtoROWt45v_Nx4Auq552HrQPakdGps,63339
64
+ websockets/legacy/server.py,sha256=BjiJELoOfY7KspN9RpqquxIMVDgQZw4IFQscHdH82lM,45232
65
+ websockets/protocol.py,sha256=sKb7pl8k5TFTBwZPB9_kBzvBaxSzR9ExHTPrgUbW6lU,23822
66
+ websockets/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
67
+ websockets/server.py,sha256=uYaKhW6y01WCSegDVAwKhFv__OAhG6_-lwbLIBXq0lw,20857
68
+ websockets/speedups.c,sha256=ghPq-NF35VLVNkMv0uFDIruNpVISyW-qvoZgPpE65qw,5834
69
+ websockets/speedups.cpython-310-x86_64-linux-gnu.so,sha256=tFuYvXgP4zHqpDcekn8lGpbSHaMwApSUvtfoH-TDtAs,33736
70
+ websockets/streams.py,sha256=8nv62HYyS74t_JSWGie4SoYAz8-jMcQacaHnD0RkK90,4038
71
+ websockets/sync/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
72
+ websockets/sync/__pycache__/__init__.cpython-310.pyc,,
73
+ websockets/sync/__pycache__/client.cpython-310.pyc,,
74
+ websockets/sync/__pycache__/compatibility.cpython-310.pyc,,
75
+ websockets/sync/__pycache__/connection.cpython-310.pyc,,
76
+ websockets/sync/__pycache__/messages.cpython-310.pyc,,
77
+ websockets/sync/__pycache__/server.cpython-310.pyc,,
78
+ websockets/sync/__pycache__/utils.cpython-310.pyc,,
79
+ websockets/sync/client.py,sha256=-9we3AHtE25pcT6EHGQ0oIyGzfYs18AzLpyDn4RLi94,11265
80
+ websockets/sync/compatibility.py,sha256=1k-EUGSz-tpDdj4c65uIgbzpET5ZRWdQtRTPbZ8kFvI,555
81
+ websockets/sync/connection.py,sha256=3Fe1BRNr4AdXs5j8UAdrSODomnfNrI460T0nTyn_2N0,29284
82
+ websockets/sync/messages.py,sha256=pTcWhwD-uwA0l4a26_xgPHgP8pjRYk5xrX5Vhq-JuCo,9484
83
+ websockets/sync/server.py,sha256=Wi306IkixafVw0JqeFEXUE7WWgIU_Go_FG3UQ9bz0HA,18661
84
+ websockets/sync/utils.py,sha256=yUDxjeM4yVeXOZ_Go4ajgTUDOy-0rEWkjcR_RZDqcYY,1151
85
+ websockets/typing.py,sha256=yx0SxSmil5JfG4fUtj-dgyR1UcW5wwmvgqtEOmcJxm4,1384
86
+ websockets/uri.py,sha256=oymYUo7bX8LofYzXpT3UqTZfkCt2y4s680Xr-qw88qk,3215
87
+ websockets/utils.py,sha256=QBhgbXn9ZvvLEzj-X8-zSHWVMkUqc6Wm-_HBjga5RNM,1150
88
+ websockets/version.py,sha256=1txnm49P_pXG7EmoPowwuhzYwUJVkR1iaD-ZTyLuvrc,2723
llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/REQUESTED ADDED
File without changes
llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/WHEEL ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.40.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_5_x86_64
5
+ Tag: cp310-cp310-manylinux1_x86_64
6
+ Tag: cp310-cp310-manylinux_2_17_x86_64
7
+ Tag: cp310-cp310-manylinux2014_x86_64
8
+
llava_next/lib/python3.10/site-packages/websockets-11.0.3.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ websockets
parrot/lib/python3.10/site-packages/sympy/integrals/__init__.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Integration functions that integrate a SymPy expression.
2
+
3
+ Examples
4
+ ========
5
+
6
+ >>> from sympy import integrate, sin
7
+ >>> from sympy.abc import x
8
+ >>> integrate(1/x,x)
9
+ log(x)
10
+ >>> integrate(sin(x),x)
11
+ -cos(x)
12
+ """
13
+ from .integrals import integrate, Integral, line_integrate
14
+ from .transforms import (mellin_transform, inverse_mellin_transform,
15
+ MellinTransform, InverseMellinTransform,
16
+ laplace_transform, inverse_laplace_transform,
17
+ laplace_correspondence, laplace_initial_conds,
18
+ LaplaceTransform, InverseLaplaceTransform,
19
+ fourier_transform, inverse_fourier_transform,
20
+ FourierTransform, InverseFourierTransform,
21
+ sine_transform, inverse_sine_transform,
22
+ SineTransform, InverseSineTransform,
23
+ cosine_transform, inverse_cosine_transform,
24
+ CosineTransform, InverseCosineTransform,
25
+ hankel_transform, inverse_hankel_transform,
26
+ HankelTransform, InverseHankelTransform)
27
+ from .singularityfunctions import singularityintegrate
28
+
29
+ __all__ = [
30
+ 'integrate', 'Integral', 'line_integrate',
31
+
32
+ 'mellin_transform', 'inverse_mellin_transform', 'MellinTransform',
33
+ 'InverseMellinTransform', 'laplace_transform',
34
+ 'inverse_laplace_transform', 'LaplaceTransform',
35
+ 'laplace_correspondence', 'laplace_initial_conds',
36
+ 'InverseLaplaceTransform', 'fourier_transform',
37
+ 'inverse_fourier_transform', 'FourierTransform',
38
+ 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform',
39
+ 'SineTransform', 'InverseSineTransform', 'cosine_transform',
40
+ 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform',
41
+ 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform',
42
+ 'InverseHankelTransform',
43
+
44
+ 'singularityintegrate',
45
+ ]
parrot/lib/python3.10/site-packages/sympy/integrals/integrals.py ADDED
@@ -0,0 +1,1640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple as tTuple
2
+
3
+ from sympy.concrete.expr_with_limits import AddWithLimits
4
+ from sympy.core.add import Add
5
+ from sympy.core.basic import Basic
6
+ from sympy.core.containers import Tuple
7
+ from sympy.core.expr import Expr
8
+ from sympy.core.exprtools import factor_terms
9
+ from sympy.core.function import diff
10
+ from sympy.core.logic import fuzzy_bool
11
+ from sympy.core.mul import Mul
12
+ from sympy.core.numbers import oo, pi
13
+ from sympy.core.relational import Ne
14
+ from sympy.core.singleton import S
15
+ from sympy.core.symbol import (Dummy, Symbol, Wild)
16
+ from sympy.core.sympify import sympify
17
+ from sympy.functions import Piecewise, sqrt, piecewise_fold, tan, cot, atan
18
+ from sympy.functions.elementary.exponential import log
19
+ from sympy.functions.elementary.integers import floor
20
+ from sympy.functions.elementary.complexes import Abs, sign
21
+ from sympy.functions.elementary.miscellaneous import Min, Max
22
+ from sympy.functions.special.singularity_functions import Heaviside
23
+ from .rationaltools import ratint
24
+ from sympy.matrices import MatrixBase
25
+ from sympy.polys import Poly, PolynomialError
26
+ from sympy.series.formal import FormalPowerSeries
27
+ from sympy.series.limits import limit
28
+ from sympy.series.order import Order
29
+ from sympy.tensor.functions import shape
30
+ from sympy.utilities.exceptions import sympy_deprecation_warning
31
+ from sympy.utilities.iterables import is_sequence
32
+ from sympy.utilities.misc import filldedent
33
+
34
+
35
+ class Integral(AddWithLimits):
36
+ """Represents unevaluated integral."""
37
+
38
+ __slots__ = ()
39
+
40
+ args: tTuple[Expr, Tuple]
41
+
42
+ def __new__(cls, function, *symbols, **assumptions):
43
+ """Create an unevaluated integral.
44
+
45
+ Explanation
46
+ ===========
47
+
48
+ Arguments are an integrand followed by one or more limits.
49
+
50
+ If no limits are given and there is only one free symbol in the
51
+ expression, that symbol will be used, otherwise an error will be
52
+ raised.
53
+
54
+ >>> from sympy import Integral
55
+ >>> from sympy.abc import x, y
56
+ >>> Integral(x)
57
+ Integral(x, x)
58
+ >>> Integral(y)
59
+ Integral(y, y)
60
+
61
+ When limits are provided, they are interpreted as follows (using
62
+ ``x`` as though it were the variable of integration):
63
+
64
+ (x,) or x - indefinite integral
65
+ (x, a) - "evaluate at" integral is an abstract antiderivative
66
+ (x, a, b) - definite integral
67
+
68
+ The ``as_dummy`` method can be used to see which symbols cannot be
69
+ targeted by subs: those with a prepended underscore cannot be
70
+ changed with ``subs``. (Also, the integration variables themselves --
71
+ the first element of a limit -- can never be changed by subs.)
72
+
73
+ >>> i = Integral(x, x)
74
+ >>> at = Integral(x, (x, x))
75
+ >>> i.as_dummy()
76
+ Integral(x, x)
77
+ >>> at.as_dummy()
78
+ Integral(_0, (_0, x))
79
+
80
+ """
81
+
82
+ #This will help other classes define their own definitions
83
+ #of behaviour with Integral.
84
+ if hasattr(function, '_eval_Integral'):
85
+ return function._eval_Integral(*symbols, **assumptions)
86
+
87
+ if isinstance(function, Poly):
88
+ sympy_deprecation_warning(
89
+ """
90
+ integrate(Poly) and Integral(Poly) are deprecated. Instead,
91
+ use the Poly.integrate() method, or convert the Poly to an
92
+ Expr first with the Poly.as_expr() method.
93
+ """,
94
+ deprecated_since_version="1.6",
95
+ active_deprecations_target="deprecated-integrate-poly")
96
+
97
+ obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
98
+ return obj
99
+
100
+ def __getnewargs__(self):
101
+ return (self.function,) + tuple([tuple(xab) for xab in self.limits])
102
+
103
+ @property
104
+ def free_symbols(self):
105
+ """
106
+ This method returns the symbols that will exist when the
107
+ integral is evaluated. This is useful if one is trying to
108
+ determine whether an integral depends on a certain
109
+ symbol or not.
110
+
111
+ Examples
112
+ ========
113
+
114
+ >>> from sympy import Integral
115
+ >>> from sympy.abc import x, y
116
+ >>> Integral(x, (x, y, 1)).free_symbols
117
+ {y}
118
+
119
+ See Also
120
+ ========
121
+
122
+ sympy.concrete.expr_with_limits.ExprWithLimits.function
123
+ sympy.concrete.expr_with_limits.ExprWithLimits.limits
124
+ sympy.concrete.expr_with_limits.ExprWithLimits.variables
125
+ """
126
+ return super().free_symbols
127
+
128
+ def _eval_is_zero(self):
129
+ # This is a very naive and quick test, not intended to do the integral to
130
+ # answer whether it is zero or not, e.g. Integral(sin(x), (x, 0, 2*pi))
131
+ # is zero but this routine should return None for that case. But, like
132
+ # Mul, there are trivial situations for which the integral will be
133
+ # zero so we check for those.
134
+ if self.function.is_zero:
135
+ return True
136
+ got_none = False
137
+ for l in self.limits:
138
+ if len(l) == 3:
139
+ z = (l[1] == l[2]) or (l[1] - l[2]).is_zero
140
+ if z:
141
+ return True
142
+ elif z is None:
143
+ got_none = True
144
+ free = self.function.free_symbols
145
+ for xab in self.limits:
146
+ if len(xab) == 1:
147
+ free.add(xab[0])
148
+ continue
149
+ if len(xab) == 2 and xab[0] not in free:
150
+ if xab[1].is_zero:
151
+ return True
152
+ elif xab[1].is_zero is None:
153
+ got_none = True
154
+ # take integration symbol out of free since it will be replaced
155
+ # with the free symbols in the limits
156
+ free.discard(xab[0])
157
+ # add in the new symbols
158
+ for i in xab[1:]:
159
+ free.update(i.free_symbols)
160
+ if self.function.is_zero is False and got_none is False:
161
+ return False
162
+
163
+ def transform(self, x, u):
164
+ r"""
165
+ Performs a change of variables from `x` to `u` using the relationship
166
+ given by `x` and `u` which will define the transformations `f` and `F`
167
+ (which are inverses of each other) as follows:
168
+
169
+ 1) If `x` is a Symbol (which is a variable of integration) then `u`
170
+ will be interpreted as some function, f(u), with inverse F(u).
171
+ This, in effect, just makes the substitution of x with f(x).
172
+
173
+ 2) If `u` is a Symbol then `x` will be interpreted as some function,
174
+ F(x), with inverse f(u). This is commonly referred to as
175
+ u-substitution.
176
+
177
+ Once f and F have been identified, the transformation is made as
178
+ follows:
179
+
180
+ .. math:: \int_a^b x \mathrm{d}x \rightarrow \int_{F(a)}^{F(b)} f(x)
181
+ \frac{\mathrm{d}}{\mathrm{d}x}
182
+
183
+ where `F(x)` is the inverse of `f(x)` and the limits and integrand have
184
+ been corrected so as to retain the same value after integration.
185
+
186
+ Notes
187
+ =====
188
+
189
+ The mappings, F(x) or f(u), must lead to a unique integral. Linear
190
+ or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will
191
+ always work; quadratic expressions like ``x**2 - 1`` are acceptable
192
+ as long as the resulting integrand does not depend on the sign of
193
+ the solutions (see examples).
194
+
195
+ The integral will be returned unchanged if ``x`` is not a variable of
196
+ integration.
197
+
198
+ ``x`` must be (or contain) only one of of the integration variables. If
199
+ ``u`` has more than one free symbol then it should be sent as a tuple
200
+ (``u``, ``uvar``) where ``uvar`` identifies which variable is replacing
201
+ the integration variable.
202
+ XXX can it contain another integration variable?
203
+
204
+ Examples
205
+ ========
206
+
207
+ >>> from sympy.abc import a, x, u
208
+ >>> from sympy import Integral, cos, sqrt
209
+
210
+ >>> i = Integral(x*cos(x**2 - 1), (x, 0, 1))
211
+
212
+ transform can change the variable of integration
213
+
214
+ >>> i.transform(x, u)
215
+ Integral(u*cos(u**2 - 1), (u, 0, 1))
216
+
217
+ transform can perform u-substitution as long as a unique
218
+ integrand is obtained:
219
+
220
+ >>> ui = i.transform(x**2 - 1, u)
221
+ >>> ui
222
+ Integral(cos(u)/2, (u, -1, 0))
223
+
224
+ This attempt fails because x = +/-sqrt(u + 1) and the
225
+ sign does not cancel out of the integrand:
226
+
227
+ >>> Integral(cos(x**2 - 1), (x, 0, 1)).transform(x**2 - 1, u)
228
+ Traceback (most recent call last):
229
+ ...
230
+ ValueError:
231
+ The mapping between F(x) and f(u) did not give a unique integrand.
232
+
233
+ transform can do a substitution. Here, the previous
234
+ result is transformed back into the original expression
235
+ using "u-substitution":
236
+
237
+ >>> ui.transform(sqrt(u + 1), x) == i
238
+ True
239
+
240
+ We can accomplish the same with a regular substitution:
241
+
242
+ >>> ui.transform(u, x**2 - 1) == i
243
+ True
244
+
245
+ If the `x` does not contain a symbol of integration then
246
+ the integral will be returned unchanged. Integral `i` does
247
+ not have an integration variable `a` so no change is made:
248
+
249
+ >>> i.transform(a, x) == i
250
+ True
251
+
252
+ When `u` has more than one free symbol the symbol that is
253
+ replacing `x` must be identified by passing `u` as a tuple:
254
+
255
+ >>> Integral(x, (x, 0, 1)).transform(x, (u + a, u))
256
+ Integral(a + u, (u, -a, 1 - a))
257
+ >>> Integral(x, (x, 0, 1)).transform(x, (u + a, a))
258
+ Integral(a + u, (a, -u, 1 - u))
259
+
260
+ See Also
261
+ ========
262
+
263
+ sympy.concrete.expr_with_limits.ExprWithLimits.variables : Lists the integration variables
264
+ as_dummy : Replace integration variables with dummy ones
265
+ """
266
+ d = Dummy('d')
267
+
268
+ xfree = x.free_symbols.intersection(self.variables)
269
+ if len(xfree) > 1:
270
+ raise ValueError(
271
+ 'F(x) can only contain one of: %s' % self.variables)
272
+ xvar = xfree.pop() if xfree else d
273
+
274
+ if xvar not in self.variables:
275
+ return self
276
+
277
+ u = sympify(u)
278
+ if isinstance(u, Expr):
279
+ ufree = u.free_symbols
280
+ if len(ufree) == 0:
281
+ raise ValueError(filldedent('''
282
+ f(u) cannot be a constant'''))
283
+ if len(ufree) > 1:
284
+ raise ValueError(filldedent('''
285
+ When f(u) has more than one free symbol, the one replacing x
286
+ must be identified: pass f(u) as (f(u), u)'''))
287
+ uvar = ufree.pop()
288
+ else:
289
+ u, uvar = u
290
+ if uvar not in u.free_symbols:
291
+ raise ValueError(filldedent('''
292
+ Expecting a tuple (expr, symbol) where symbol identified
293
+ a free symbol in expr, but symbol is not in expr's free
294
+ symbols.'''))
295
+ if not isinstance(uvar, Symbol):
296
+ # This probably never evaluates to True
297
+ raise ValueError(filldedent('''
298
+ Expecting a tuple (expr, symbol) but didn't get
299
+ a symbol; got %s''' % uvar))
300
+
301
+ if x.is_Symbol and u.is_Symbol:
302
+ return self.xreplace({x: u})
303
+
304
+ if not x.is_Symbol and not u.is_Symbol:
305
+ raise ValueError('either x or u must be a symbol')
306
+
307
+ if uvar == xvar:
308
+ return self.transform(x, (u.subs(uvar, d), d)).xreplace({d: uvar})
309
+
310
+ if uvar in self.limits:
311
+ raise ValueError(filldedent('''
312
+ u must contain the same variable as in x
313
+ or a variable that is not already an integration variable'''))
314
+
315
+ from sympy.solvers.solvers import solve
316
+ if not x.is_Symbol:
317
+ F = [x.subs(xvar, d)]
318
+ soln = solve(u - x, xvar, check=False)
319
+ if not soln:
320
+ raise ValueError('no solution for solve(F(x) - f(u), x)')
321
+ f = [fi.subs(uvar, d) for fi in soln]
322
+ else:
323
+ f = [u.subs(uvar, d)]
324
+ from sympy.simplify.simplify import posify
325
+ pdiff, reps = posify(u - x)
326
+ puvar = uvar.subs([(v, k) for k, v in reps.items()])
327
+ soln = [s.subs(reps) for s in solve(pdiff, puvar)]
328
+ if not soln:
329
+ raise ValueError('no solution for solve(F(x) - f(u), u)')
330
+ F = [fi.subs(xvar, d) for fi in soln]
331
+
332
+ newfuncs = {(self.function.subs(xvar, fi)*fi.diff(d)
333
+ ).subs(d, uvar) for fi in f}
334
+ if len(newfuncs) > 1:
335
+ raise ValueError(filldedent('''
336
+ The mapping between F(x) and f(u) did not give
337
+ a unique integrand.'''))
338
+ newfunc = newfuncs.pop()
339
+
340
+ def _calc_limit_1(F, a, b):
341
+ """
342
+ replace d with a, using subs if possible, otherwise limit
343
+ where sign of b is considered
344
+ """
345
+ wok = F.subs(d, a)
346
+ if wok is S.NaN or wok.is_finite is False and a.is_finite:
347
+ return limit(sign(b)*F, d, a)
348
+ return wok
349
+
350
+ def _calc_limit(a, b):
351
+ """
352
+ replace d with a, using subs if possible, otherwise limit
353
+ where sign of b is considered
354
+ """
355
+ avals = list({_calc_limit_1(Fi, a, b) for Fi in F})
356
+ if len(avals) > 1:
357
+ raise ValueError(filldedent('''
358
+ The mapping between F(x) and f(u) did not
359
+ give a unique limit.'''))
360
+ return avals[0]
361
+
362
+ newlimits = []
363
+ for xab in self.limits:
364
+ sym = xab[0]
365
+ if sym == xvar:
366
+ if len(xab) == 3:
367
+ a, b = xab[1:]
368
+ a, b = _calc_limit(a, b), _calc_limit(b, a)
369
+ if fuzzy_bool(a - b > 0):
370
+ a, b = b, a
371
+ newfunc = -newfunc
372
+ newlimits.append((uvar, a, b))
373
+ elif len(xab) == 2:
374
+ a = _calc_limit(xab[1], 1)
375
+ newlimits.append((uvar, a))
376
+ else:
377
+ newlimits.append(uvar)
378
+ else:
379
+ newlimits.append(xab)
380
+
381
+ return self.func(newfunc, *newlimits)
382
+
383
+ def doit(self, **hints):
384
+ """
385
+ Perform the integration using any hints given.
386
+
387
+ Examples
388
+ ========
389
+
390
+ >>> from sympy import Piecewise, S
391
+ >>> from sympy.abc import x, t
392
+ >>> p = x**2 + Piecewise((0, x/t < 0), (1, True))
393
+ >>> p.integrate((t, S(4)/5, 1), (x, -1, 1))
394
+ 1/3
395
+
396
+ See Also
397
+ ========
398
+
399
+ sympy.integrals.trigonometry.trigintegrate
400
+ sympy.integrals.heurisch.heurisch
401
+ sympy.integrals.rationaltools.ratint
402
+ as_sum : Approximate the integral using a sum
403
+ """
404
+ if not hints.get('integrals', True):
405
+ return self
406
+
407
+ deep = hints.get('deep', True)
408
+ meijerg = hints.get('meijerg', None)
409
+ conds = hints.get('conds', 'piecewise')
410
+ risch = hints.get('risch', None)
411
+ heurisch = hints.get('heurisch', None)
412
+ manual = hints.get('manual', None)
413
+ if len(list(filter(None, (manual, meijerg, risch, heurisch)))) > 1:
414
+ raise ValueError("At most one of manual, meijerg, risch, heurisch can be True")
415
+ elif manual:
416
+ meijerg = risch = heurisch = False
417
+ elif meijerg:
418
+ manual = risch = heurisch = False
419
+ elif risch:
420
+ manual = meijerg = heurisch = False
421
+ elif heurisch:
422
+ manual = meijerg = risch = False
423
+ eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual, "heurisch": heurisch,
424
+ "conds": conds}
425
+
426
+ if conds not in ('separate', 'piecewise', 'none'):
427
+ raise ValueError('conds must be one of "separate", "piecewise", '
428
+ '"none", got: %s' % conds)
429
+
430
+ if risch and any(len(xab) > 1 for xab in self.limits):
431
+ raise ValueError('risch=True is only allowed for indefinite integrals.')
432
+
433
+ # check for the trivial zero
434
+ if self.is_zero:
435
+ return S.Zero
436
+
437
+ # hacks to handle integrals of
438
+ # nested summations
439
+ from sympy.concrete.summations import Sum
440
+ if isinstance(self.function, Sum):
441
+ if any(v in self.function.limits[0] for v in self.variables):
442
+ raise ValueError('Limit of the sum cannot be an integration variable.')
443
+ if any(l.is_infinite for l in self.function.limits[0][1:]):
444
+ return self
445
+ _i = self
446
+ _sum = self.function
447
+ return _sum.func(_i.func(_sum.function, *_i.limits).doit(), *_sum.limits).doit()
448
+
449
+ # now compute and check the function
450
+ function = self.function
451
+
452
+ # hack to use a consistent Heaviside(x, 1/2)
453
+ function = function.replace(
454
+ lambda x: isinstance(x, Heaviside) and x.args[1]*2 != 1,
455
+ lambda x: Heaviside(x.args[0]))
456
+
457
+ if deep:
458
+ function = function.doit(**hints)
459
+ if function.is_zero:
460
+ return S.Zero
461
+
462
+ # hacks to handle special cases
463
+ if isinstance(function, MatrixBase):
464
+ return function.applyfunc(
465
+ lambda f: self.func(f, *self.limits).doit(**hints))
466
+
467
+ if isinstance(function, FormalPowerSeries):
468
+ if len(self.limits) > 1:
469
+ raise NotImplementedError
470
+ xab = self.limits[0]
471
+ if len(xab) > 1:
472
+ return function.integrate(xab, **eval_kwargs)
473
+ else:
474
+ return function.integrate(xab[0], **eval_kwargs)
475
+
476
+ # There is no trivial answer and special handling
477
+ # is done so continue
478
+
479
+ # first make sure any definite limits have integration
480
+ # variables with matching assumptions
481
+ reps = {}
482
+ for xab in self.limits:
483
+ if len(xab) != 3:
484
+ # it makes sense to just make
485
+ # all x real but in practice with the
486
+ # current state of integration...this
487
+ # doesn't work out well
488
+ # x = xab[0]
489
+ # if x not in reps and not x.is_real:
490
+ # reps[x] = Dummy(real=True)
491
+ continue
492
+ x, a, b = xab
493
+ l = (a, b)
494
+ if all(i.is_nonnegative for i in l) and not x.is_nonnegative:
495
+ d = Dummy(positive=True)
496
+ elif all(i.is_nonpositive for i in l) and not x.is_nonpositive:
497
+ d = Dummy(negative=True)
498
+ elif all(i.is_real for i in l) and not x.is_real:
499
+ d = Dummy(real=True)
500
+ else:
501
+ d = None
502
+ if d:
503
+ reps[x] = d
504
+ if reps:
505
+ undo = {v: k for k, v in reps.items()}
506
+ did = self.xreplace(reps).doit(**hints)
507
+ if isinstance(did, tuple): # when separate=True
508
+ did = tuple([i.xreplace(undo) for i in did])
509
+ else:
510
+ did = did.xreplace(undo)
511
+ return did
512
+
513
+ # continue with existing assumptions
514
+ undone_limits = []
515
+ # ulj = free symbols of any undone limits' upper and lower limits
516
+ ulj = set()
517
+ for xab in self.limits:
518
+ # compute uli, the free symbols in the
519
+ # Upper and Lower limits of limit I
520
+ if len(xab) == 1:
521
+ uli = set(xab[:1])
522
+ elif len(xab) == 2:
523
+ uli = xab[1].free_symbols
524
+ elif len(xab) == 3:
525
+ uli = xab[1].free_symbols.union(xab[2].free_symbols)
526
+ # this integral can be done as long as there is no blocking
527
+ # limit that has been undone. An undone limit is blocking if
528
+ # it contains an integration variable that is in this limit's
529
+ # upper or lower free symbols or vice versa
530
+ if xab[0] in ulj or any(v[0] in uli for v in undone_limits):
531
+ undone_limits.append(xab)
532
+ ulj.update(uli)
533
+ function = self.func(*([function] + [xab]))
534
+ factored_function = function.factor()
535
+ if not isinstance(factored_function, Integral):
536
+ function = factored_function
537
+ continue
538
+
539
+ if function.has(Abs, sign) and (
540
+ (len(xab) < 3 and all(x.is_extended_real for x in xab)) or
541
+ (len(xab) == 3 and all(x.is_extended_real and not x.is_infinite for
542
+ x in xab[1:]))):
543
+ # some improper integrals are better off with Abs
544
+ xr = Dummy("xr", real=True)
545
+ function = (function.xreplace({xab[0]: xr})
546
+ .rewrite(Piecewise).xreplace({xr: xab[0]}))
547
+ elif function.has(Min, Max):
548
+ function = function.rewrite(Piecewise)
549
+ if (function.has(Piecewise) and
550
+ not isinstance(function, Piecewise)):
551
+ function = piecewise_fold(function)
552
+ if isinstance(function, Piecewise):
553
+ if len(xab) == 1:
554
+ antideriv = function._eval_integral(xab[0],
555
+ **eval_kwargs)
556
+ else:
557
+ antideriv = self._eval_integral(
558
+ function, xab[0], **eval_kwargs)
559
+ else:
560
+ # There are a number of tradeoffs in using the
561
+ # Meijer G method. It can sometimes be a lot faster
562
+ # than other methods, and sometimes slower. And
563
+ # there are certain types of integrals for which it
564
+ # is more likely to work than others. These
565
+ # heuristics are incorporated in deciding what
566
+ # integration methods to try, in what order. See the
567
+ # integrate() docstring for details.
568
+ def try_meijerg(function, xab):
569
+ ret = None
570
+ if len(xab) == 3 and meijerg is not False:
571
+ x, a, b = xab
572
+ try:
573
+ res = meijerint_definite(function, x, a, b)
574
+ except NotImplementedError:
575
+ _debug('NotImplementedError '
576
+ 'from meijerint_definite')
577
+ res = None
578
+ if res is not None:
579
+ f, cond = res
580
+ if conds == 'piecewise':
581
+ u = self.func(function, (x, a, b))
582
+ # if Piecewise modifies cond too
583
+ # much it may not be recognized by
584
+ # _condsimp pattern matching so just
585
+ # turn off all evaluation
586
+ return Piecewise((f, cond), (u, True),
587
+ evaluate=False)
588
+ elif conds == 'separate':
589
+ if len(self.limits) != 1:
590
+ raise ValueError(filldedent('''
591
+ conds=separate not supported in
592
+ multiple integrals'''))
593
+ ret = f, cond
594
+ else:
595
+ ret = f
596
+ return ret
597
+
598
+ meijerg1 = meijerg
599
+ if (meijerg is not False and
600
+ len(xab) == 3 and xab[1].is_extended_real and xab[2].is_extended_real
601
+ and not function.is_Poly and
602
+ (xab[1].has(oo, -oo) or xab[2].has(oo, -oo))):
603
+ ret = try_meijerg(function, xab)
604
+ if ret is not None:
605
+ function = ret
606
+ continue
607
+ meijerg1 = False
608
+ # If the special meijerg code did not succeed in
609
+ # finding a definite integral, then the code using
610
+ # meijerint_indefinite will not either (it might
611
+ # find an antiderivative, but the answer is likely
612
+ # to be nonsensical). Thus if we are requested to
613
+ # only use Meijer G-function methods, we give up at
614
+ # this stage. Otherwise we just disable G-function
615
+ # methods.
616
+ if meijerg1 is False and meijerg is True:
617
+ antideriv = None
618
+ else:
619
+ antideriv = self._eval_integral(
620
+ function, xab[0], **eval_kwargs)
621
+ if antideriv is None and meijerg is True:
622
+ ret = try_meijerg(function, xab)
623
+ if ret is not None:
624
+ function = ret
625
+ continue
626
+
627
+ final = hints.get('final', True)
628
+ # dotit may be iterated but floor terms making atan and acot
629
+ # continuous should only be added in the final round
630
+ if (final and not isinstance(antideriv, Integral) and
631
+ antideriv is not None):
632
+ for atan_term in antideriv.atoms(atan):
633
+ atan_arg = atan_term.args[0]
634
+ # Checking `atan_arg` to be linear combination of `tan` or `cot`
635
+ for tan_part in atan_arg.atoms(tan):
636
+ x1 = Dummy('x1')
637
+ tan_exp1 = atan_arg.subs(tan_part, x1)
638
+ # The coefficient of `tan` should be constant
639
+ coeff = tan_exp1.diff(x1)
640
+ if x1 not in coeff.free_symbols:
641
+ a = tan_part.args[0]
642
+ antideriv = antideriv.subs(atan_term, Add(atan_term,
643
+ sign(coeff)*pi*floor((a-pi/2)/pi)))
644
+ for cot_part in atan_arg.atoms(cot):
645
+ x1 = Dummy('x1')
646
+ cot_exp1 = atan_arg.subs(cot_part, x1)
647
+ # The coefficient of `cot` should be constant
648
+ coeff = cot_exp1.diff(x1)
649
+ if x1 not in coeff.free_symbols:
650
+ a = cot_part.args[0]
651
+ antideriv = antideriv.subs(atan_term, Add(atan_term,
652
+ sign(coeff)*pi*floor((a)/pi)))
653
+
654
+ if antideriv is None:
655
+ undone_limits.append(xab)
656
+ function = self.func(*([function] + [xab])).factor()
657
+ factored_function = function.factor()
658
+ if not isinstance(factored_function, Integral):
659
+ function = factored_function
660
+ continue
661
+ else:
662
+ if len(xab) == 1:
663
+ function = antideriv
664
+ else:
665
+ if len(xab) == 3:
666
+ x, a, b = xab
667
+ elif len(xab) == 2:
668
+ x, b = xab
669
+ a = None
670
+ else:
671
+ raise NotImplementedError
672
+
673
+ if deep:
674
+ if isinstance(a, Basic):
675
+ a = a.doit(**hints)
676
+ if isinstance(b, Basic):
677
+ b = b.doit(**hints)
678
+
679
+ if antideriv.is_Poly:
680
+ gens = list(antideriv.gens)
681
+ gens.remove(x)
682
+
683
+ antideriv = antideriv.as_expr()
684
+
685
+ function = antideriv._eval_interval(x, a, b)
686
+ function = Poly(function, *gens)
687
+ else:
688
+ def is_indef_int(g, x):
689
+ return (isinstance(g, Integral) and
690
+ any(i == (x,) for i in g.limits))
691
+
692
+ def eval_factored(f, x, a, b):
693
+ # _eval_interval for integrals with
694
+ # (constant) factors
695
+ # a single indefinite integral is assumed
696
+ args = []
697
+ for g in Mul.make_args(f):
698
+ if is_indef_int(g, x):
699
+ args.append(g._eval_interval(x, a, b))
700
+ else:
701
+ args.append(g)
702
+ return Mul(*args)
703
+
704
+ integrals, others, piecewises = [], [], []
705
+ for f in Add.make_args(antideriv):
706
+ if any(is_indef_int(g, x)
707
+ for g in Mul.make_args(f)):
708
+ integrals.append(f)
709
+ elif any(isinstance(g, Piecewise)
710
+ for g in Mul.make_args(f)):
711
+ piecewises.append(piecewise_fold(f))
712
+ else:
713
+ others.append(f)
714
+ uneval = Add(*[eval_factored(f, x, a, b)
715
+ for f in integrals])
716
+ try:
717
+ evalued = Add(*others)._eval_interval(x, a, b)
718
+ evalued_pw = piecewise_fold(Add(*piecewises))._eval_interval(x, a, b)
719
+ function = uneval + evalued + evalued_pw
720
+ except NotImplementedError:
721
+ # This can happen if _eval_interval depends in a
722
+ # complicated way on limits that cannot be computed
723
+ undone_limits.append(xab)
724
+ function = self.func(*([function] + [xab]))
725
+ factored_function = function.factor()
726
+ if not isinstance(factored_function, Integral):
727
+ function = factored_function
728
+ return function
729
+
730
+ def _eval_derivative(self, sym):
731
+ """Evaluate the derivative of the current Integral object by
732
+ differentiating under the integral sign [1], using the Fundamental
733
+ Theorem of Calculus [2] when possible.
734
+
735
+ Explanation
736
+ ===========
737
+
738
+ Whenever an Integral is encountered that is equivalent to zero or
739
+ has an integrand that is independent of the variable of integration
740
+ those integrals are performed. All others are returned as Integral
741
+ instances which can be resolved with doit() (provided they are integrable).
742
+
743
+ References
744
+ ==========
745
+
746
+ .. [1] https://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign
747
+ .. [2] https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus
748
+
749
+ Examples
750
+ ========
751
+
752
+ >>> from sympy import Integral
753
+ >>> from sympy.abc import x, y
754
+ >>> i = Integral(x + y, y, (y, 1, x))
755
+ >>> i.diff(x)
756
+ Integral(x + y, (y, x)) + Integral(1, y, (y, 1, x))
757
+ >>> i.doit().diff(x) == i.diff(x).doit()
758
+ True
759
+ >>> i.diff(y)
760
+ 0
761
+
762
+ The previous must be true since there is no y in the evaluated integral:
763
+
764
+ >>> i.free_symbols
765
+ {x}
766
+ >>> i.doit()
767
+ 2*x**3/3 - x/2 - 1/6
768
+
769
+ """
770
+
771
+ # differentiate under the integral sign; we do not
772
+ # check for regularity conditions (TODO), see issue 4215
773
+
774
+ # get limits and the function
775
+ f, limits = self.function, list(self.limits)
776
+
777
+ # the order matters if variables of integration appear in the limits
778
+ # so work our way in from the outside to the inside.
779
+ limit = limits.pop(-1)
780
+ if len(limit) == 3:
781
+ x, a, b = limit
782
+ elif len(limit) == 2:
783
+ x, b = limit
784
+ a = None
785
+ else:
786
+ a = b = None
787
+ x = limit[0]
788
+
789
+ if limits: # f is the argument to an integral
790
+ f = self.func(f, *tuple(limits))
791
+
792
+ # assemble the pieces
793
+ def _do(f, ab):
794
+ dab_dsym = diff(ab, sym)
795
+ if not dab_dsym:
796
+ return S.Zero
797
+ if isinstance(f, Integral):
798
+ limits = [(x, x) if (len(l) == 1 and l[0] == x) else l
799
+ for l in f.limits]
800
+ f = self.func(f.function, *limits)
801
+ return f.subs(x, ab)*dab_dsym
802
+
803
+ rv = S.Zero
804
+ if b is not None:
805
+ rv += _do(f, b)
806
+ if a is not None:
807
+ rv -= _do(f, a)
808
+ if len(limit) == 1 and sym == x:
809
+ # the dummy variable *is* also the real-world variable
810
+ arg = f
811
+ rv += arg
812
+ else:
813
+ # the dummy variable might match sym but it's
814
+ # only a dummy and the actual variable is determined
815
+ # by the limits, so mask off the variable of integration
816
+ # while differentiating
817
+ u = Dummy('u')
818
+ arg = f.subs(x, u).diff(sym).subs(u, x)
819
+ if arg:
820
+ rv += self.func(arg, (x, a, b))
821
+ return rv
822
+
823
+ def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None,
824
+ heurisch=None, conds='piecewise',final=None):
825
+ """
826
+ Calculate the anti-derivative to the function f(x).
827
+
828
+ Explanation
829
+ ===========
830
+
831
+ The following algorithms are applied (roughly in this order):
832
+
833
+ 1. Simple heuristics (based on pattern matching and integral table):
834
+
835
+ - most frequently used functions (e.g. polynomials, products of
836
+ trig functions)
837
+
838
+ 2. Integration of rational functions:
839
+
840
+ - A complete algorithm for integrating rational functions is
841
+ implemented (the Lazard-Rioboo-Trager algorithm). The algorithm
842
+ also uses the partial fraction decomposition algorithm
843
+ implemented in apart() as a preprocessor to make this process
844
+ faster. Note that the integral of a rational function is always
845
+ elementary, but in general, it may include a RootSum.
846
+
847
+ 3. Full Risch algorithm:
848
+
849
+ - The Risch algorithm is a complete decision
850
+ procedure for integrating elementary functions, which means that
851
+ given any elementary function, it will either compute an
852
+ elementary antiderivative, or else prove that none exists.
853
+ Currently, part of transcendental case is implemented, meaning
854
+ elementary integrals containing exponentials, logarithms, and
855
+ (soon!) trigonometric functions can be computed. The algebraic
856
+ case, e.g., functions containing roots, is much more difficult
857
+ and is not implemented yet.
858
+
859
+ - If the routine fails (because the integrand is not elementary, or
860
+ because a case is not implemented yet), it continues on to the
861
+ next algorithms below. If the routine proves that the integrals
862
+ is nonelementary, it still moves on to the algorithms below,
863
+ because we might be able to find a closed-form solution in terms
864
+ of special functions. If risch=True, however, it will stop here.
865
+
866
+ 4. The Meijer G-Function algorithm:
867
+
868
+ - This algorithm works by first rewriting the integrand in terms of
869
+ very general Meijer G-Function (meijerg in SymPy), integrating
870
+ it, and then rewriting the result back, if possible. This
871
+ algorithm is particularly powerful for definite integrals (which
872
+ is actually part of a different method of Integral), since it can
873
+ compute closed-form solutions of definite integrals even when no
874
+ closed-form indefinite integral exists. But it also is capable
875
+ of computing many indefinite integrals as well.
876
+
877
+ - Another advantage of this method is that it can use some results
878
+ about the Meijer G-Function to give a result in terms of a
879
+ Piecewise expression, which allows to express conditionally
880
+ convergent integrals.
881
+
882
+ - Setting meijerg=True will cause integrate() to use only this
883
+ method.
884
+
885
+ 5. The "manual integration" algorithm:
886
+
887
+ - This algorithm tries to mimic how a person would find an
888
+ antiderivative by hand, for example by looking for a
889
+ substitution or applying integration by parts. This algorithm
890
+ does not handle as many integrands but can return results in a
891
+ more familiar form.
892
+
893
+ - Sometimes this algorithm can evaluate parts of an integral; in
894
+ this case integrate() will try to evaluate the rest of the
895
+ integrand using the other methods here.
896
+
897
+ - Setting manual=True will cause integrate() to use only this
898
+ method.
899
+
900
+ 6. The Heuristic Risch algorithm:
901
+
902
+ - This is a heuristic version of the Risch algorithm, meaning that
903
+ it is not deterministic. This is tried as a last resort because
904
+ it can be very slow. It is still used because not enough of the
905
+ full Risch algorithm is implemented, so that there are still some
906
+ integrals that can only be computed using this method. The goal
907
+ is to implement enough of the Risch and Meijer G-function methods
908
+ so that this can be deleted.
909
+
910
+ Setting heurisch=True will cause integrate() to use only this
911
+ method. Set heurisch=False to not use it.
912
+
913
+ """
914
+
915
+ from sympy.integrals.risch import risch_integrate, NonElementaryIntegral
916
+ from sympy.integrals.manualintegrate import manualintegrate
917
+
918
+ if risch:
919
+ try:
920
+ return risch_integrate(f, x, conds=conds)
921
+ except NotImplementedError:
922
+ return None
923
+
924
+ if manual:
925
+ try:
926
+ result = manualintegrate(f, x)
927
+ if result is not None and result.func != Integral:
928
+ return result
929
+ except (ValueError, PolynomialError):
930
+ pass
931
+
932
+ eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual,
933
+ "heurisch": heurisch, "conds": conds}
934
+
935
+ # if it is a poly(x) then let the polynomial integrate itself (fast)
936
+ #
937
+ # It is important to make this check first, otherwise the other code
938
+ # will return a SymPy expression instead of a Polynomial.
939
+ #
940
+ # see Polynomial for details.
941
+ if isinstance(f, Poly) and not (manual or meijerg or risch):
942
+ # Note: this is deprecated, but the deprecation warning is already
943
+ # issued in the Integral constructor.
944
+ return f.integrate(x)
945
+
946
+ # Piecewise antiderivatives need to call special integrate.
947
+ if isinstance(f, Piecewise):
948
+ return f.piecewise_integrate(x, **eval_kwargs)
949
+
950
+ # let's cut it short if `f` does not depend on `x`; if
951
+ # x is only a dummy, that will be handled below
952
+ if not f.has(x):
953
+ return f*x
954
+
955
+ # try to convert to poly(x) and then integrate if successful (fast)
956
+ poly = f.as_poly(x)
957
+ if poly is not None and not (manual or meijerg or risch):
958
+ return poly.integrate().as_expr()
959
+
960
+ if risch is not False:
961
+ try:
962
+ result, i = risch_integrate(f, x, separate_integral=True,
963
+ conds=conds)
964
+ except NotImplementedError:
965
+ pass
966
+ else:
967
+ if i:
968
+ # There was a nonelementary integral. Try integrating it.
969
+
970
+ # if no part of the NonElementaryIntegral is integrated by
971
+ # the Risch algorithm, then use the original function to
972
+ # integrate, instead of re-written one
973
+ if result == 0:
974
+ return NonElementaryIntegral(f, x).doit(risch=False)
975
+ else:
976
+ return result + i.doit(risch=False)
977
+ else:
978
+ return result
979
+
980
+ # since Integral(f=g1+g2+...) == Integral(g1) + Integral(g2) + ...
981
+ # we are going to handle Add terms separately,
982
+ # if `f` is not Add -- we only have one term
983
+
984
+ # Note that in general, this is a bad idea, because Integral(g1) +
985
+ # Integral(g2) might not be computable, even if Integral(g1 + g2) is.
986
+ # For example, Integral(x**x + x**x*log(x)). But many heuristics only
987
+ # work term-wise. So we compute this step last, after trying
988
+ # risch_integrate. We also try risch_integrate again in this loop,
989
+ # because maybe the integral is a sum of an elementary part and a
990
+ # nonelementary part (like erf(x) + exp(x)). risch_integrate() is
991
+ # quite fast, so this is acceptable.
992
+ from sympy.simplify.fu import sincos_to_sum
993
+ parts = []
994
+ args = Add.make_args(f)
995
+ for g in args:
996
+ coeff, g = g.as_independent(x)
997
+
998
+ # g(x) = const
999
+ if g is S.One and not meijerg:
1000
+ parts.append(coeff*x)
1001
+ continue
1002
+
1003
+ # g(x) = expr + O(x**n)
1004
+ order_term = g.getO()
1005
+
1006
+ if order_term is not None:
1007
+ h = self._eval_integral(g.removeO(), x, **eval_kwargs)
1008
+
1009
+ if h is not None:
1010
+ h_order_expr = self._eval_integral(order_term.expr, x, **eval_kwargs)
1011
+
1012
+ if h_order_expr is not None:
1013
+ h_order_term = order_term.func(
1014
+ h_order_expr, *order_term.variables)
1015
+ parts.append(coeff*(h + h_order_term))
1016
+ continue
1017
+
1018
+ # NOTE: if there is O(x**n) and we fail to integrate then
1019
+ # there is no point in trying other methods because they
1020
+ # will fail, too.
1021
+ return None
1022
+
1023
+ # c
1024
+ # g(x) = (a*x+b)
1025
+ if g.is_Pow and not g.exp.has(x) and not meijerg:
1026
+ a = Wild('a', exclude=[x])
1027
+ b = Wild('b', exclude=[x])
1028
+
1029
+ M = g.base.match(a*x + b)
1030
+
1031
+ if M is not None:
1032
+ if g.exp == -1:
1033
+ h = log(g.base)
1034
+ elif conds != 'piecewise':
1035
+ h = g.base**(g.exp + 1) / (g.exp + 1)
1036
+ else:
1037
+ h1 = log(g.base)
1038
+ h2 = g.base**(g.exp + 1) / (g.exp + 1)
1039
+ h = Piecewise((h2, Ne(g.exp, -1)), (h1, True))
1040
+
1041
+ parts.append(coeff * h / M[a])
1042
+ continue
1043
+
1044
+ # poly(x)
1045
+ # g(x) = -------
1046
+ # poly(x)
1047
+ if g.is_rational_function(x) and not (manual or meijerg or risch):
1048
+ parts.append(coeff * ratint(g, x))
1049
+ continue
1050
+
1051
+ if not (manual or meijerg or risch):
1052
+ # g(x) = Mul(trig)
1053
+ h = trigintegrate(g, x, conds=conds)
1054
+ if h is not None:
1055
+ parts.append(coeff * h)
1056
+ continue
1057
+
1058
+ # g(x) has at least a DiracDelta term
1059
+ h = deltaintegrate(g, x)
1060
+ if h is not None:
1061
+ parts.append(coeff * h)
1062
+ continue
1063
+
1064
+ from .singularityfunctions import singularityintegrate
1065
+ # g(x) has at least a Singularity Function term
1066
+ h = singularityintegrate(g, x)
1067
+ if h is not None:
1068
+ parts.append(coeff * h)
1069
+ continue
1070
+
1071
+ # Try risch again.
1072
+ if risch is not False:
1073
+ try:
1074
+ h, i = risch_integrate(g, x,
1075
+ separate_integral=True, conds=conds)
1076
+ except NotImplementedError:
1077
+ h = None
1078
+ else:
1079
+ if i:
1080
+ h = h + i.doit(risch=False)
1081
+
1082
+ parts.append(coeff*h)
1083
+ continue
1084
+
1085
+ # fall back to heurisch
1086
+ if heurisch is not False:
1087
+ from sympy.integrals.heurisch import (heurisch as heurisch_,
1088
+ heurisch_wrapper)
1089
+ try:
1090
+ if conds == 'piecewise':
1091
+ h = heurisch_wrapper(g, x, hints=[])
1092
+ else:
1093
+ h = heurisch_(g, x, hints=[])
1094
+ except PolynomialError:
1095
+ # XXX: this exception means there is a bug in the
1096
+ # implementation of heuristic Risch integration
1097
+ # algorithm.
1098
+ h = None
1099
+ else:
1100
+ h = None
1101
+
1102
+ if meijerg is not False and h is None:
1103
+ # rewrite using G functions
1104
+ try:
1105
+ h = meijerint_indefinite(g, x)
1106
+ except NotImplementedError:
1107
+ _debug('NotImplementedError from meijerint_definite')
1108
+ if h is not None:
1109
+ parts.append(coeff * h)
1110
+ continue
1111
+
1112
+ if h is None and manual is not False:
1113
+ try:
1114
+ result = manualintegrate(g, x)
1115
+ if result is not None and not isinstance(result, Integral):
1116
+ if result.has(Integral) and not manual:
1117
+ # Try to have other algorithms do the integrals
1118
+ # manualintegrate can't handle,
1119
+ # unless we were asked to use manual only.
1120
+ # Keep the rest of eval_kwargs in case another
1121
+ # method was set to False already
1122
+ new_eval_kwargs = eval_kwargs
1123
+ new_eval_kwargs["manual"] = False
1124
+ new_eval_kwargs["final"] = False
1125
+ result = result.func(*[
1126
+ arg.doit(**new_eval_kwargs) if
1127
+ arg.has(Integral) else arg
1128
+ for arg in result.args
1129
+ ]).expand(multinomial=False,
1130
+ log=False,
1131
+ power_exp=False,
1132
+ power_base=False)
1133
+ if not result.has(Integral):
1134
+ parts.append(coeff * result)
1135
+ continue
1136
+ except (ValueError, PolynomialError):
1137
+ # can't handle some SymPy expressions
1138
+ pass
1139
+
1140
+ # if we failed maybe it was because we had
1141
+ # a product that could have been expanded,
1142
+ # so let's try an expansion of the whole
1143
+ # thing before giving up; we don't try this
1144
+ # at the outset because there are things
1145
+ # that cannot be solved unless they are
1146
+ # NOT expanded e.g., x**x*(1+log(x)). There
1147
+ # should probably be a checker somewhere in this
1148
+ # routine to look for such cases and try to do
1149
+ # collection on the expressions if they are already
1150
+ # in an expanded form
1151
+ if not h and len(args) == 1:
1152
+ f = sincos_to_sum(f).expand(mul=True, deep=False)
1153
+ if f.is_Add:
1154
+ # Note: risch will be identical on the expanded
1155
+ # expression, but maybe it will be able to pick out parts,
1156
+ # like x*(exp(x) + erf(x)).
1157
+ return self._eval_integral(f, x, **eval_kwargs)
1158
+
1159
+ if h is not None:
1160
+ parts.append(coeff * h)
1161
+ else:
1162
+ return None
1163
+
1164
+ return Add(*parts)
1165
+
1166
+ def _eval_lseries(self, x, logx=None, cdir=0):
1167
+ expr = self.as_dummy()
1168
+ symb = x
1169
+ for l in expr.limits:
1170
+ if x in l[1:]:
1171
+ symb = l[0]
1172
+ break
1173
+ for term in expr.function.lseries(symb, logx):
1174
+ yield integrate(term, *expr.limits)
1175
+
1176
+ def _eval_nseries(self, x, n, logx=None, cdir=0):
1177
+ symb = x
1178
+ for l in self.limits:
1179
+ if x in l[1:]:
1180
+ symb = l[0]
1181
+ break
1182
+ terms, order = self.function.nseries(
1183
+ x=symb, n=n, logx=logx).as_coeff_add(Order)
1184
+ order = [o.subs(symb, x) for o in order]
1185
+ return integrate(terms, *self.limits) + Add(*order)*x
1186
+
1187
+ def _eval_as_leading_term(self, x, logx=None, cdir=0):
1188
+ series_gen = self.args[0].lseries(x)
1189
+ for leading_term in series_gen:
1190
+ if leading_term != 0:
1191
+ break
1192
+ return integrate(leading_term, *self.args[1:])
1193
+
1194
+ def _eval_simplify(self, **kwargs):
1195
+ expr = factor_terms(self)
1196
+ if isinstance(expr, Integral):
1197
+ from sympy.simplify.simplify import simplify
1198
+ return expr.func(*[simplify(i, **kwargs) for i in expr.args])
1199
+ return expr.simplify(**kwargs)
1200
+
1201
+ def as_sum(self, n=None, method="midpoint", evaluate=True):
1202
+ """
1203
+ Approximates a definite integral by a sum.
1204
+
1205
+ Parameters
1206
+ ==========
1207
+
1208
+ n :
1209
+ The number of subintervals to use, optional.
1210
+ method :
1211
+ One of: 'left', 'right', 'midpoint', 'trapezoid'.
1212
+ evaluate : bool
1213
+ If False, returns an unevaluated Sum expression. The default
1214
+ is True, evaluate the sum.
1215
+
1216
+ Notes
1217
+ =====
1218
+
1219
+ These methods of approximate integration are described in [1].
1220
+
1221
+ Examples
1222
+ ========
1223
+
1224
+ >>> from sympy import Integral, sin, sqrt
1225
+ >>> from sympy.abc import x, n
1226
+ >>> e = Integral(sin(x), (x, 3, 7))
1227
+ >>> e
1228
+ Integral(sin(x), (x, 3, 7))
1229
+
1230
+ For demonstration purposes, this interval will only be split into 2
1231
+ regions, bounded by [3, 5] and [5, 7].
1232
+
1233
+ The left-hand rule uses function evaluations at the left of each
1234
+ interval:
1235
+
1236
+ >>> e.as_sum(2, 'left')
1237
+ 2*sin(5) + 2*sin(3)
1238
+
1239
+ The midpoint rule uses evaluations at the center of each interval:
1240
+
1241
+ >>> e.as_sum(2, 'midpoint')
1242
+ 2*sin(4) + 2*sin(6)
1243
+
1244
+ The right-hand rule uses function evaluations at the right of each
1245
+ interval:
1246
+
1247
+ >>> e.as_sum(2, 'right')
1248
+ 2*sin(5) + 2*sin(7)
1249
+
1250
+ The trapezoid rule uses function evaluations on both sides of the
1251
+ intervals. This is equivalent to taking the average of the left and
1252
+ right hand rule results:
1253
+
1254
+ >>> s = e.as_sum(2, 'trapezoid')
1255
+ >>> s
1256
+ 2*sin(5) + sin(3) + sin(7)
1257
+ >>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == s
1258
+ True
1259
+
1260
+ Here, the discontinuity at x = 0 can be avoided by using the
1261
+ midpoint or right-hand method:
1262
+
1263
+ >>> e = Integral(1/sqrt(x), (x, 0, 1))
1264
+ >>> e.as_sum(5).n(4)
1265
+ 1.730
1266
+ >>> e.as_sum(10).n(4)
1267
+ 1.809
1268
+ >>> e.doit().n(4) # the actual value is 2
1269
+ 2.000
1270
+
1271
+ The left- or trapezoid method will encounter the discontinuity and
1272
+ return infinity:
1273
+
1274
+ >>> e.as_sum(5, 'left')
1275
+ zoo
1276
+
1277
+ The number of intervals can be symbolic. If omitted, a dummy symbol
1278
+ will be used for it.
1279
+
1280
+ >>> e = Integral(x**2, (x, 0, 2))
1281
+ >>> e.as_sum(n, 'right').expand()
1282
+ 8/3 + 4/n + 4/(3*n**2)
1283
+
1284
+ This shows that the midpoint rule is more accurate, as its error
1285
+ term decays as the square of n:
1286
+
1287
+ >>> e.as_sum(method='midpoint').expand()
1288
+ 8/3 - 2/(3*_n**2)
1289
+
1290
+ A symbolic sum is returned with evaluate=False:
1291
+
1292
+ >>> e.as_sum(n, 'midpoint', evaluate=False)
1293
+ 2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n
1294
+
1295
+ See Also
1296
+ ========
1297
+
1298
+ Integral.doit : Perform the integration using any hints
1299
+
1300
+ References
1301
+ ==========
1302
+
1303
+ .. [1] https://en.wikipedia.org/wiki/Riemann_sum#Riemann_summation_methods
1304
+ """
1305
+
1306
+ from sympy.concrete.summations import Sum
1307
+ limits = self.limits
1308
+ if len(limits) > 1:
1309
+ raise NotImplementedError(
1310
+ "Multidimensional midpoint rule not implemented yet")
1311
+ else:
1312
+ limit = limits[0]
1313
+ if (len(limit) != 3 or limit[1].is_finite is False or
1314
+ limit[2].is_finite is False):
1315
+ raise ValueError("Expecting a definite integral over "
1316
+ "a finite interval.")
1317
+ if n is None:
1318
+ n = Dummy('n', integer=True, positive=True)
1319
+ else:
1320
+ n = sympify(n)
1321
+ if (n.is_positive is False or n.is_integer is False or
1322
+ n.is_finite is False):
1323
+ raise ValueError("n must be a positive integer, got %s" % n)
1324
+ x, a, b = limit
1325
+ dx = (b - a)/n
1326
+ k = Dummy('k', integer=True, positive=True)
1327
+ f = self.function
1328
+
1329
+ if method == "left":
1330
+ result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))
1331
+ elif method == "right":
1332
+ result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))
1333
+ elif method == "midpoint":
1334
+ result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))
1335
+ elif method == "trapezoid":
1336
+ result = dx*((f.subs(x, a) + f.subs(x, b))/2 +
1337
+ Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))
1338
+ else:
1339
+ raise ValueError("Unknown method %s" % method)
1340
+ return result.doit() if evaluate else result
1341
+
1342
+ def principal_value(self, **kwargs):
1343
+ """
1344
+ Compute the Cauchy Principal Value of the definite integral of a real function in the given interval
1345
+ on the real axis.
1346
+
1347
+ Explanation
1348
+ ===========
1349
+
1350
+ In mathematics, the Cauchy principal value, is a method for assigning values to certain improper
1351
+ integrals which would otherwise be undefined.
1352
+
1353
+ Examples
1354
+ ========
1355
+
1356
+ >>> from sympy import Integral, oo
1357
+ >>> from sympy.abc import x
1358
+ >>> Integral(x+1, (x, -oo, oo)).principal_value()
1359
+ oo
1360
+ >>> f = 1 / (x**3)
1361
+ >>> Integral(f, (x, -oo, oo)).principal_value()
1362
+ 0
1363
+ >>> Integral(f, (x, -10, 10)).principal_value()
1364
+ 0
1365
+ >>> Integral(f, (x, -10, oo)).principal_value() + Integral(f, (x, -oo, 10)).principal_value()
1366
+ 0
1367
+
1368
+ References
1369
+ ==========
1370
+
1371
+ .. [1] https://en.wikipedia.org/wiki/Cauchy_principal_value
1372
+ .. [2] https://mathworld.wolfram.com/CauchyPrincipalValue.html
1373
+ """
1374
+ if len(self.limits) != 1 or len(list(self.limits[0])) != 3:
1375
+ raise ValueError("You need to insert a variable, lower_limit, and upper_limit correctly to calculate "
1376
+ "cauchy's principal value")
1377
+ x, a, b = self.limits[0]
1378
+ if not (a.is_comparable and b.is_comparable and a <= b):
1379
+ raise ValueError("The lower_limit must be smaller than or equal to the upper_limit to calculate "
1380
+ "cauchy's principal value. Also, a and b need to be comparable.")
1381
+ if a == b:
1382
+ return S.Zero
1383
+
1384
+ from sympy.calculus.singularities import singularities
1385
+
1386
+ r = Dummy('r')
1387
+ f = self.function
1388
+ singularities_list = [s for s in singularities(f, x) if s.is_comparable and a <= s <= b]
1389
+ for i in singularities_list:
1390
+ if i in (a, b):
1391
+ raise ValueError(
1392
+ 'The principal value is not defined in the given interval due to singularity at %d.' % (i))
1393
+ F = integrate(f, x, **kwargs)
1394
+ if F.has(Integral):
1395
+ return self
1396
+ if a is -oo and b is oo:
1397
+ I = limit(F - F.subs(x, -x), x, oo)
1398
+ else:
1399
+ I = limit(F, x, b, '-') - limit(F, x, a, '+')
1400
+ for s in singularities_list:
1401
+ I += limit(((F.subs(x, s - r)) - F.subs(x, s + r)), r, 0, '+')
1402
+ return I
1403
+
1404
+
1405
+
1406
+ def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs):
1407
+ """integrate(f, var, ...)
1408
+
1409
+ .. deprecated:: 1.6
1410
+
1411
+ Using ``integrate()`` with :class:`~.Poly` is deprecated. Use
1412
+ :meth:`.Poly.integrate` instead. See :ref:`deprecated-integrate-poly`.
1413
+
1414
+ Explanation
1415
+ ===========
1416
+
1417
+ Compute definite or indefinite integral of one or more variables
1418
+ using Risch-Norman algorithm and table lookup. This procedure is
1419
+ able to handle elementary algebraic and transcendental functions
1420
+ and also a huge class of special functions, including Airy,
1421
+ Bessel, Whittaker and Lambert.
1422
+
1423
+ var can be:
1424
+
1425
+ - a symbol -- indefinite integration
1426
+ - a tuple (symbol, a) -- indefinite integration with result
1427
+ given with ``a`` replacing ``symbol``
1428
+ - a tuple (symbol, a, b) -- definite integration
1429
+
1430
+ Several variables can be specified, in which case the result is
1431
+ multiple integration. (If var is omitted and the integrand is
1432
+ univariate, the indefinite integral in that variable will be performed.)
1433
+
1434
+ Indefinite integrals are returned without terms that are independent
1435
+ of the integration variables. (see examples)
1436
+
1437
+ Definite improper integrals often entail delicate convergence
1438
+ conditions. Pass conds='piecewise', 'separate' or 'none' to have
1439
+ these returned, respectively, as a Piecewise function, as a separate
1440
+ result (i.e. result will be a tuple), or not at all (default is
1441
+ 'piecewise').
1442
+
1443
+ **Strategy**
1444
+
1445
+ SymPy uses various approaches to definite integration. One method is to
1446
+ find an antiderivative for the integrand, and then use the fundamental
1447
+ theorem of calculus. Various functions are implemented to integrate
1448
+ polynomial, rational and trigonometric functions, and integrands
1449
+ containing DiracDelta terms.
1450
+
1451
+ SymPy also implements the part of the Risch algorithm, which is a decision
1452
+ procedure for integrating elementary functions, i.e., the algorithm can
1453
+ either find an elementary antiderivative, or prove that one does not
1454
+ exist. There is also a (very successful, albeit somewhat slow) general
1455
+ implementation of the heuristic Risch algorithm. This algorithm will
1456
+ eventually be phased out as more of the full Risch algorithm is
1457
+ implemented. See the docstring of Integral._eval_integral() for more
1458
+ details on computing the antiderivative using algebraic methods.
1459
+
1460
+ The option risch=True can be used to use only the (full) Risch algorithm.
1461
+ This is useful if you want to know if an elementary function has an
1462
+ elementary antiderivative. If the indefinite Integral returned by this
1463
+ function is an instance of NonElementaryIntegral, that means that the
1464
+ Risch algorithm has proven that integral to be non-elementary. Note that
1465
+ by default, additional methods (such as the Meijer G method outlined
1466
+ below) are tried on these integrals, as they may be expressible in terms
1467
+ of special functions, so if you only care about elementary answers, use
1468
+ risch=True. Also note that an unevaluated Integral returned by this
1469
+ function is not necessarily a NonElementaryIntegral, even with risch=True,
1470
+ as it may just be an indication that the particular part of the Risch
1471
+ algorithm needed to integrate that function is not yet implemented.
1472
+
1473
+ Another family of strategies comes from re-writing the integrand in
1474
+ terms of so-called Meijer G-functions. Indefinite integrals of a
1475
+ single G-function can always be computed, and the definite integral
1476
+ of a product of two G-functions can be computed from zero to
1477
+ infinity. Various strategies are implemented to rewrite integrands
1478
+ as G-functions, and use this information to compute integrals (see
1479
+ the ``meijerint`` module).
1480
+
1481
+ The option manual=True can be used to use only an algorithm that tries
1482
+ to mimic integration by hand. This algorithm does not handle as many
1483
+ integrands as the other algorithms implemented but may return results in
1484
+ a more familiar form. The ``manualintegrate`` module has functions that
1485
+ return the steps used (see the module docstring for more information).
1486
+
1487
+ In general, the algebraic methods work best for computing
1488
+ antiderivatives of (possibly complicated) combinations of elementary
1489
+ functions. The G-function methods work best for computing definite
1490
+ integrals from zero to infinity of moderately complicated
1491
+ combinations of special functions, or indefinite integrals of very
1492
+ simple combinations of special functions.
1493
+
1494
+ The strategy employed by the integration code is as follows:
1495
+
1496
+ - If computing a definite integral, and both limits are real,
1497
+ and at least one limit is +- oo, try the G-function method of
1498
+ definite integration first.
1499
+
1500
+ - Try to find an antiderivative, using all available methods, ordered
1501
+ by performance (that is try fastest method first, slowest last; in
1502
+ particular polynomial integration is tried first, Meijer
1503
+ G-functions second to last, and heuristic Risch last).
1504
+
1505
+ - If still not successful, try G-functions irrespective of the
1506
+ limits.
1507
+
1508
+ The option meijerg=True, False, None can be used to, respectively:
1509
+ always use G-function methods and no others, never use G-function
1510
+ methods, or use all available methods (in order as described above).
1511
+ It defaults to None.
1512
+
1513
+ Examples
1514
+ ========
1515
+
1516
+ >>> from sympy import integrate, log, exp, oo
1517
+ >>> from sympy.abc import a, x, y
1518
+
1519
+ >>> integrate(x*y, x)
1520
+ x**2*y/2
1521
+
1522
+ >>> integrate(log(x), x)
1523
+ x*log(x) - x
1524
+
1525
+ >>> integrate(log(x), (x, 1, a))
1526
+ a*log(a) - a + 1
1527
+
1528
+ >>> integrate(x)
1529
+ x**2/2
1530
+
1531
+ Terms that are independent of x are dropped by indefinite integration:
1532
+
1533
+ >>> from sympy import sqrt
1534
+ >>> integrate(sqrt(1 + x), (x, 0, x))
1535
+ 2*(x + 1)**(3/2)/3 - 2/3
1536
+ >>> integrate(sqrt(1 + x), x)
1537
+ 2*(x + 1)**(3/2)/3
1538
+
1539
+ >>> integrate(x*y)
1540
+ Traceback (most recent call last):
1541
+ ...
1542
+ ValueError: specify integration variables to integrate x*y
1543
+
1544
+ Note that ``integrate(x)`` syntax is meant only for convenience
1545
+ in interactive sessions and should be avoided in library code.
1546
+
1547
+ >>> integrate(x**a*exp(-x), (x, 0, oo)) # same as conds='piecewise'
1548
+ Piecewise((gamma(a + 1), re(a) > -1),
1549
+ (Integral(x**a*exp(-x), (x, 0, oo)), True))
1550
+
1551
+ >>> integrate(x**a*exp(-x), (x, 0, oo), conds='none')
1552
+ gamma(a + 1)
1553
+
1554
+ >>> integrate(x**a*exp(-x), (x, 0, oo), conds='separate')
1555
+ (gamma(a + 1), re(a) > -1)
1556
+
1557
+ See Also
1558
+ ========
1559
+
1560
+ Integral, Integral.doit
1561
+
1562
+ """
1563
+ doit_flags = {
1564
+ 'deep': False,
1565
+ 'meijerg': meijerg,
1566
+ 'conds': conds,
1567
+ 'risch': risch,
1568
+ 'heurisch': heurisch,
1569
+ 'manual': manual
1570
+ }
1571
+ integral = Integral(*args, **kwargs)
1572
+
1573
+ if isinstance(integral, Integral):
1574
+ return integral.doit(**doit_flags)
1575
+ else:
1576
+ new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
1577
+ for a in integral.args]
1578
+ return integral.func(*new_args)
1579
+
1580
+
1581
+ def line_integrate(field, curve, vars):
1582
+ """line_integrate(field, Curve, variables)
1583
+
1584
+ Compute the line integral.
1585
+
1586
+ Examples
1587
+ ========
1588
+
1589
+ >>> from sympy import Curve, line_integrate, E, ln
1590
+ >>> from sympy.abc import x, y, t
1591
+ >>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2)))
1592
+ >>> line_integrate(x + y, C, [x, y])
1593
+ 3*sqrt(2)
1594
+
1595
+ See Also
1596
+ ========
1597
+
1598
+ sympy.integrals.integrals.integrate, Integral
1599
+ """
1600
+ from sympy.geometry import Curve
1601
+ F = sympify(field)
1602
+ if not F:
1603
+ raise ValueError(
1604
+ "Expecting function specifying field as first argument.")
1605
+ if not isinstance(curve, Curve):
1606
+ raise ValueError("Expecting Curve entity as second argument.")
1607
+ if not is_sequence(vars):
1608
+ raise ValueError("Expecting ordered iterable for variables.")
1609
+ if len(curve.functions) != len(vars):
1610
+ raise ValueError("Field variable size does not match curve dimension.")
1611
+
1612
+ if curve.parameter in vars:
1613
+ raise ValueError("Curve parameter clashes with field parameters.")
1614
+
1615
+ # Calculate derivatives for line parameter functions
1616
+ # F(r) -> F(r(t)) and finally F(r(t)*r'(t))
1617
+ Ft = F
1618
+ dldt = 0
1619
+ for i, var in enumerate(vars):
1620
+ _f = curve.functions[i]
1621
+ _dn = diff(_f, curve.parameter)
1622
+ # ...arc length
1623
+ dldt = dldt + (_dn * _dn)
1624
+ Ft = Ft.subs(var, _f)
1625
+ Ft = Ft * sqrt(dldt)
1626
+
1627
+ integral = Integral(Ft, curve.limits).doit(deep=False)
1628
+ return integral
1629
+
1630
+
1631
+ ### Property function dispatching ###
1632
+
1633
+ @shape.register(Integral)
1634
+ def _(expr):
1635
+ return shape(expr.function)
1636
+
1637
+ # Delayed imports
1638
+ from .deltafunctions import deltaintegrate
1639
+ from .meijerint import meijerint_definite, meijerint_indefinite, _debug
1640
+ from .trigonometry import trigintegrate
parrot/lib/python3.10/site-packages/sympy/integrals/meijerint.py ADDED
@@ -0,0 +1,2191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Integrate functions by rewriting them as Meijer G-functions.
3
+
4
+ There are three user-visible functions that can be used by other parts of the
5
+ sympy library to solve various integration problems:
6
+
7
+ - meijerint_indefinite
8
+ - meijerint_definite
9
+ - meijerint_inversion
10
+
11
+ They can be used to compute, respectively, indefinite integrals, definite
12
+ integrals over intervals of the real line, and inverse laplace-type integrals
13
+ (from c-I*oo to c+I*oo). See the respective docstrings for details.
14
+
15
+ The main references for this are:
16
+
17
+ [L] Luke, Y. L. (1969), The Special Functions and Their Approximations,
18
+ Volume 1
19
+
20
+ [R] Kelly B. Roach. Meijer G Function Representations.
21
+ In: Proceedings of the 1997 International Symposium on Symbolic and
22
+ Algebraic Computation, pages 205-211, New York, 1997. ACM.
23
+
24
+ [P] A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990).
25
+ Integrals and Series: More Special Functions, Vol. 3,.
26
+ Gordon and Breach Science Publisher
27
+ """
28
+
29
+ from __future__ import annotations
30
+ import itertools
31
+
32
+ from sympy import SYMPY_DEBUG
33
+ from sympy.core import S, Expr
34
+ from sympy.core.add import Add
35
+ from sympy.core.basic import Basic
36
+ from sympy.core.cache import cacheit
37
+ from sympy.core.containers import Tuple
38
+ from sympy.core.exprtools import factor_terms
39
+ from sympy.core.function import (expand, expand_mul, expand_power_base,
40
+ expand_trig, Function)
41
+ from sympy.core.mul import Mul
42
+ from sympy.core.intfunc import ilcm
43
+ from sympy.core.numbers import Rational, pi
44
+ from sympy.core.relational import Eq, Ne, _canonical_coeff
45
+ from sympy.core.sorting import default_sort_key, ordered
46
+ from sympy.core.symbol import Dummy, symbols, Wild, Symbol
47
+ from sympy.core.sympify import sympify
48
+ from sympy.functions.combinatorial.factorials import factorial
49
+ from sympy.functions.elementary.complexes import (re, im, arg, Abs, sign,
50
+ unpolarify, polarify, polar_lift, principal_branch, unbranched_argument,
51
+ periodic_argument)
52
+ from sympy.functions.elementary.exponential import exp, exp_polar, log
53
+ from sympy.functions.elementary.integers import ceiling
54
+ from sympy.functions.elementary.hyperbolic import (cosh, sinh,
55
+ _rewrite_hyperbolics_as_exp, HyperbolicFunction)
56
+ from sympy.functions.elementary.miscellaneous import sqrt
57
+ from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold
58
+ from sympy.functions.elementary.trigonometric import (cos, sin, sinc,
59
+ TrigonometricFunction)
60
+ from sympy.functions.special.bessel import besselj, bessely, besseli, besselk
61
+ from sympy.functions.special.delta_functions import DiracDelta, Heaviside
62
+ from sympy.functions.special.elliptic_integrals import elliptic_k, elliptic_e
63
+ from sympy.functions.special.error_functions import (erf, erfc, erfi, Ei,
64
+ expint, Si, Ci, Shi, Chi, fresnels, fresnelc)
65
+ from sympy.functions.special.gamma_functions import gamma
66
+ from sympy.functions.special.hyper import hyper, meijerg
67
+ from sympy.functions.special.singularity_functions import SingularityFunction
68
+ from .integrals import Integral
69
+ from sympy.logic.boolalg import And, Or, BooleanAtom, Not, BooleanFunction
70
+ from sympy.polys import cancel, factor
71
+ from sympy.utilities.iterables import multiset_partitions
72
+ from sympy.utilities.misc import debug as _debug
73
+ from sympy.utilities.misc import debugf as _debugf
74
+
75
+ # keep this at top for easy reference
76
+ z = Dummy('z')
77
+
78
+
79
+ def _has(res, *f):
80
+ # return True if res has f; in the case of Piecewise
81
+ # only return True if *all* pieces have f
82
+ res = piecewise_fold(res)
83
+ if getattr(res, 'is_Piecewise', False):
84
+ return all(_has(i, *f) for i in res.args)
85
+ return res.has(*f)
86
+
87
+
88
+ def _create_lookup_table(table):
89
+ """ Add formulae for the function -> meijerg lookup table. """
90
+ def wild(n):
91
+ return Wild(n, exclude=[z])
92
+ p, q, a, b, c = list(map(wild, 'pqabc'))
93
+ n = Wild('n', properties=[lambda x: x.is_Integer and x > 0])
94
+ t = p*z**q
95
+
96
+ def add(formula, an, ap, bm, bq, arg=t, fac=S.One, cond=True, hint=True):
97
+ table.setdefault(_mytype(formula, z), []).append((formula,
98
+ [(fac, meijerg(an, ap, bm, bq, arg))], cond, hint))
99
+
100
+ def addi(formula, inst, cond, hint=True):
101
+ table.setdefault(
102
+ _mytype(formula, z), []).append((formula, inst, cond, hint))
103
+
104
+ def constant(a):
105
+ return [(a, meijerg([1], [], [], [0], z)),
106
+ (a, meijerg([], [1], [0], [], z))]
107
+ table[()] = [(a, constant(a), True, True)]
108
+
109
+ # [P], Section 8.
110
+ class IsNonPositiveInteger(Function):
111
+
112
+ @classmethod
113
+ def eval(cls, arg):
114
+ arg = unpolarify(arg)
115
+ if arg.is_Integer is True:
116
+ return arg <= 0
117
+
118
+ # Section 8.4.2
119
+ # TODO this needs more polar_lift (c/f entry for exp)
120
+ add(Heaviside(t - b)*(t - b)**(a - 1), [a], [], [], [0], t/b,
121
+ gamma(a)*b**(a - 1), And(b > 0))
122
+ add(Heaviside(b - t)*(b - t)**(a - 1), [], [a], [0], [], t/b,
123
+ gamma(a)*b**(a - 1), And(b > 0))
124
+ add(Heaviside(z - (b/p)**(1/q))*(t - b)**(a - 1), [a], [], [], [0], t/b,
125
+ gamma(a)*b**(a - 1), And(b > 0))
126
+ add(Heaviside((b/p)**(1/q) - z)*(b - t)**(a - 1), [], [a], [0], [], t/b,
127
+ gamma(a)*b**(a - 1), And(b > 0))
128
+ add((b + t)**(-a), [1 - a], [], [0], [], t/b, b**(-a)/gamma(a),
129
+ hint=Not(IsNonPositiveInteger(a)))
130
+ add(Abs(b - t)**(-a), [1 - a], [(1 - a)/2], [0], [(1 - a)/2], t/b,
131
+ 2*sin(pi*a/2)*gamma(1 - a)*Abs(b)**(-a), re(a) < 1)
132
+ add((t**a - b**a)/(t - b), [0, a], [], [0, a], [], t/b,
133
+ b**(a - 1)*sin(a*pi)/pi)
134
+
135
+ # 12
136
+ def A1(r, sign, nu):
137
+ return pi**Rational(-1, 2)*(-sign*nu/2)**(1 - 2*r)
138
+
139
+ def tmpadd(r, sgn):
140
+ # XXX the a**2 is bad for matching
141
+ add((sqrt(a**2 + t) + sgn*a)**b/(a**2 + t)**r,
142
+ [(1 + b)/2, 1 - 2*r + b/2], [],
143
+ [(b - sgn*b)/2], [(b + sgn*b)/2], t/a**2,
144
+ a**(b - 2*r)*A1(r, sgn, b))
145
+ tmpadd(0, 1)
146
+ tmpadd(0, -1)
147
+ tmpadd(S.Half, 1)
148
+ tmpadd(S.Half, -1)
149
+
150
+ # 13
151
+ def tmpadd(r, sgn):
152
+ add((sqrt(a + p*z**q) + sgn*sqrt(p)*z**(q/2))**b/(a + p*z**q)**r,
153
+ [1 - r + sgn*b/2], [1 - r - sgn*b/2], [0, S.Half], [],
154
+ p*z**q/a, a**(b/2 - r)*A1(r, sgn, b))
155
+ tmpadd(0, 1)
156
+ tmpadd(0, -1)
157
+ tmpadd(S.Half, 1)
158
+ tmpadd(S.Half, -1)
159
+ # (those after look obscure)
160
+
161
+ # Section 8.4.3
162
+ add(exp(polar_lift(-1)*t), [], [], [0], [])
163
+
164
+ # TODO can do sin^n, sinh^n by expansion ... where?
165
+ # 8.4.4 (hyperbolic functions)
166
+ add(sinh(t), [], [1], [S.Half], [1, 0], t**2/4, pi**Rational(3, 2))
167
+ add(cosh(t), [], [S.Half], [0], [S.Half, S.Half], t**2/4, pi**Rational(3, 2))
168
+
169
+ # Section 8.4.5
170
+ # TODO can do t + a. but can also do by expansion... (XXX not really)
171
+ add(sin(t), [], [], [S.Half], [0], t**2/4, sqrt(pi))
172
+ add(cos(t), [], [], [0], [S.Half], t**2/4, sqrt(pi))
173
+
174
+ # Section 8.4.6 (sinc function)
175
+ add(sinc(t), [], [], [0], [Rational(-1, 2)], t**2/4, sqrt(pi)/2)
176
+
177
+ # Section 8.5.5
178
+ def make_log1(subs):
179
+ N = subs[n]
180
+ return [(S.NegativeOne**N*factorial(N),
181
+ meijerg([], [1]*(N + 1), [0]*(N + 1), [], t))]
182
+
183
+ def make_log2(subs):
184
+ N = subs[n]
185
+ return [(factorial(N),
186
+ meijerg([1]*(N + 1), [], [], [0]*(N + 1), t))]
187
+ # TODO these only hold for positive p, and can be made more general
188
+ # but who uses log(x)*Heaviside(a-x) anyway ...
189
+ # TODO also it would be nice to derive them recursively ...
190
+ addi(log(t)**n*Heaviside(1 - t), make_log1, True)
191
+ addi(log(t)**n*Heaviside(t - 1), make_log2, True)
192
+
193
+ def make_log3(subs):
194
+ return make_log1(subs) + make_log2(subs)
195
+ addi(log(t)**n, make_log3, True)
196
+ addi(log(t + a),
197
+ constant(log(a)) + [(S.One, meijerg([1, 1], [], [1], [0], t/a))],
198
+ True)
199
+ addi(log(Abs(t - a)), constant(log(Abs(a))) +
200
+ [(pi, meijerg([1, 1], [S.Half], [1], [0, S.Half], t/a))],
201
+ True)
202
+ # TODO log(x)/(x+a) and log(x)/(x-1) can also be done. should they
203
+ # be derivable?
204
+ # TODO further formulae in this section seem obscure
205
+
206
+ # Sections 8.4.9-10
207
+ # TODO
208
+
209
+ # Section 8.4.11
210
+ addi(Ei(t),
211
+ constant(-S.ImaginaryUnit*pi) + [(S.NegativeOne, meijerg([], [1], [0, 0], [],
212
+ t*polar_lift(-1)))],
213
+ True)
214
+
215
+ # Section 8.4.12
216
+ add(Si(t), [1], [], [S.Half], [0, 0], t**2/4, sqrt(pi)/2)
217
+ add(Ci(t), [], [1], [0, 0], [S.Half], t**2/4, -sqrt(pi)/2)
218
+
219
+ # Section 8.4.13
220
+ add(Shi(t), [S.Half], [], [0], [Rational(-1, 2), Rational(-1, 2)], polar_lift(-1)*t**2/4,
221
+ t*sqrt(pi)/4)
222
+ add(Chi(t), [], [S.Half, 1], [0, 0], [S.Half, S.Half], t**2/4, -
223
+ pi**S('3/2')/2)
224
+
225
+ # generalized exponential integral
226
+ add(expint(a, t), [], [a], [a - 1, 0], [], t)
227
+
228
+ # Section 8.4.14
229
+ add(erf(t), [1], [], [S.Half], [0], t**2, 1/sqrt(pi))
230
+ # TODO exp(-x)*erf(I*x) does not work
231
+ add(erfc(t), [], [1], [0, S.Half], [], t**2, 1/sqrt(pi))
232
+ # This formula for erfi(z) yields a wrong(?) minus sign
233
+ #add(erfi(t), [1], [], [S.Half], [0], -t**2, I/sqrt(pi))
234
+ add(erfi(t), [S.Half], [], [0], [Rational(-1, 2)], -t**2, t/sqrt(pi))
235
+
236
+ # Fresnel Integrals
237
+ add(fresnels(t), [1], [], [Rational(3, 4)], [0, Rational(1, 4)], pi**2*t**4/16, S.Half)
238
+ add(fresnelc(t), [1], [], [Rational(1, 4)], [0, Rational(3, 4)], pi**2*t**4/16, S.Half)
239
+
240
+ ##### bessel-type functions #####
241
+ # Section 8.4.19
242
+ add(besselj(a, t), [], [], [a/2], [-a/2], t**2/4)
243
+
244
+ # all of the following are derivable
245
+ #add(sin(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [(1+a)/2],
246
+ # [-a/2, a/2, (1-a)/2], t**2, 1/sqrt(2))
247
+ #add(cos(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [a/2],
248
+ # [-a/2, (1+a)/2, (1-a)/2], t**2, 1/sqrt(2))
249
+ #add(besselj(a, t)**2, [S.Half], [], [a], [-a, 0], t**2, 1/sqrt(pi))
250
+ #add(besselj(a, t)*besselj(b, t), [0, S.Half], [], [(a + b)/2],
251
+ # [-(a+b)/2, (a - b)/2, (b - a)/2], t**2, 1/sqrt(pi))
252
+
253
+ # Section 8.4.20
254
+ add(bessely(a, t), [], [-(a + 1)/2], [a/2, -a/2], [-(a + 1)/2], t**2/4)
255
+
256
+ # TODO all of the following should be derivable
257
+ #add(sin(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(1 - a - 1)/2],
258
+ # [(1 + a)/2, (1 - a)/2], [(1 - a - 1)/2, (1 - 1 - a)/2, (1 - 1 + a)/2],
259
+ # t**2, 1/sqrt(2))
260
+ #add(cos(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(0 - a - 1)/2],
261
+ # [(0 + a)/2, (0 - a)/2], [(0 - a - 1)/2, (1 - 0 - a)/2, (1 - 0 + a)/2],
262
+ # t**2, 1/sqrt(2))
263
+ #add(besselj(a, t)*bessely(b, t), [0, S.Half], [(a - b - 1)/2],
264
+ # [(a + b)/2, (a - b)/2], [(a - b - 1)/2, -(a + b)/2, (b - a)/2],
265
+ # t**2, 1/sqrt(pi))
266
+ #addi(bessely(a, t)**2,
267
+ # [(2/sqrt(pi), meijerg([], [S.Half, S.Half - a], [0, a, -a],
268
+ # [S.Half - a], t**2)),
269
+ # (1/sqrt(pi), meijerg([S.Half], [], [a], [-a, 0], t**2))],
270
+ # True)
271
+ #addi(bessely(a, t)*bessely(b, t),
272
+ # [(2/sqrt(pi), meijerg([], [0, S.Half, (1 - a - b)/2],
273
+ # [(a + b)/2, (a - b)/2, (b - a)/2, -(a + b)/2],
274
+ # [(1 - a - b)/2], t**2)),
275
+ # (1/sqrt(pi), meijerg([0, S.Half], [], [(a + b)/2],
276
+ # [-(a + b)/2, (a - b)/2, (b - a)/2], t**2))],
277
+ # True)
278
+
279
+ # Section 8.4.21 ?
280
+ # Section 8.4.22
281
+ add(besseli(a, t), [], [(1 + a)/2], [a/2], [-a/2, (1 + a)/2], t**2/4, pi)
282
+ # TODO many more formulas. should all be derivable
283
+
284
+ # Section 8.4.23
285
+ add(besselk(a, t), [], [], [a/2, -a/2], [], t**2/4, S.Half)
286
+ # TODO many more formulas. should all be derivable
287
+
288
+ # Complete elliptic integrals K(z) and E(z)
289
+ add(elliptic_k(t), [S.Half, S.Half], [], [0], [0], -t, S.Half)
290
+ add(elliptic_e(t), [S.Half, 3*S.Half], [], [0], [0], -t, Rational(-1, 2)/2)
291
+
292
+
293
+ ####################################################################
294
+ # First some helper functions.
295
+ ####################################################################
296
+
297
+ from sympy.utilities.timeutils import timethis
298
+ timeit = timethis('meijerg')
299
+
300
+
301
+ def _mytype(f: Basic, x: Symbol) -> tuple[type[Basic], ...]:
302
+ """ Create a hashable entity describing the type of f. """
303
+ def key(x: type[Basic]) -> tuple[int, int, str]:
304
+ return x.class_key()
305
+
306
+ if x not in f.free_symbols:
307
+ return ()
308
+ elif f.is_Function:
309
+ return type(f),
310
+ return tuple(sorted((t for a in f.args for t in _mytype(a, x)), key=key))
311
+
312
+
313
+ class _CoeffExpValueError(ValueError):
314
+ """
315
+ Exception raised by _get_coeff_exp, for internal use only.
316
+ """
317
+ pass
318
+
319
+
320
+ def _get_coeff_exp(expr, x):
321
+ """
322
+ When expr is known to be of the form c*x**b, with c and/or b possibly 1,
323
+ return c, b.
324
+
325
+ Examples
326
+ ========
327
+
328
+ >>> from sympy.abc import x, a, b
329
+ >>> from sympy.integrals.meijerint import _get_coeff_exp
330
+ >>> _get_coeff_exp(a*x**b, x)
331
+ (a, b)
332
+ >>> _get_coeff_exp(x, x)
333
+ (1, 1)
334
+ >>> _get_coeff_exp(2*x, x)
335
+ (2, 1)
336
+ >>> _get_coeff_exp(x**3, x)
337
+ (1, 3)
338
+ """
339
+ from sympy.simplify import powsimp
340
+ (c, m) = expand_power_base(powsimp(expr)).as_coeff_mul(x)
341
+ if not m:
342
+ return c, S.Zero
343
+ [m] = m
344
+ if m.is_Pow:
345
+ if m.base != x:
346
+ raise _CoeffExpValueError('expr not of form a*x**b')
347
+ return c, m.exp
348
+ elif m == x:
349
+ return c, S.One
350
+ else:
351
+ raise _CoeffExpValueError('expr not of form a*x**b: %s' % expr)
352
+
353
+
354
+ def _exponents(expr, x):
355
+ """
356
+ Find the exponents of ``x`` (not including zero) in ``expr``.
357
+
358
+ Examples
359
+ ========
360
+
361
+ >>> from sympy.integrals.meijerint import _exponents
362
+ >>> from sympy.abc import x, y
363
+ >>> from sympy import sin
364
+ >>> _exponents(x, x)
365
+ {1}
366
+ >>> _exponents(x**2, x)
367
+ {2}
368
+ >>> _exponents(x**2 + x, x)
369
+ {1, 2}
370
+ >>> _exponents(x**3*sin(x + x**y) + 1/x, x)
371
+ {-1, 1, 3, y}
372
+ """
373
+ def _exponents_(expr, x, res):
374
+ if expr == x:
375
+ res.update([1])
376
+ return
377
+ if expr.is_Pow and expr.base == x:
378
+ res.update([expr.exp])
379
+ return
380
+ for argument in expr.args:
381
+ _exponents_(argument, x, res)
382
+ res = set()
383
+ _exponents_(expr, x, res)
384
+ return res
385
+
386
+
387
+ def _functions(expr, x):
388
+ """ Find the types of functions in expr, to estimate the complexity. """
389
+ return {e.func for e in expr.atoms(Function) if x in e.free_symbols}
390
+
391
+
392
+ def _find_splitting_points(expr, x):
393
+ """
394
+ Find numbers a such that a linear substitution x -> x + a would
395
+ (hopefully) simplify expr.
396
+
397
+ Examples
398
+ ========
399
+
400
+ >>> from sympy.integrals.meijerint import _find_splitting_points as fsp
401
+ >>> from sympy import sin
402
+ >>> from sympy.abc import x
403
+ >>> fsp(x, x)
404
+ {0}
405
+ >>> fsp((x-1)**3, x)
406
+ {1}
407
+ >>> fsp(sin(x+3)*x, x)
408
+ {-3, 0}
409
+ """
410
+ p, q = [Wild(n, exclude=[x]) for n in 'pq']
411
+
412
+ def compute_innermost(expr, res):
413
+ if not isinstance(expr, Expr):
414
+ return
415
+ m = expr.match(p*x + q)
416
+ if m and m[p] != 0:
417
+ res.add(-m[q]/m[p])
418
+ return
419
+ if expr.is_Atom:
420
+ return
421
+ for argument in expr.args:
422
+ compute_innermost(argument, res)
423
+ innermost = set()
424
+ compute_innermost(expr, innermost)
425
+ return innermost
426
+
427
+
428
+ def _split_mul(f, x):
429
+ """
430
+ Split expression ``f`` into fac, po, g, where fac is a constant factor,
431
+ po = x**s for some s independent of s, and g is "the rest".
432
+
433
+ Examples
434
+ ========
435
+
436
+ >>> from sympy.integrals.meijerint import _split_mul
437
+ >>> from sympy import sin
438
+ >>> from sympy.abc import s, x
439
+ >>> _split_mul((3*x)**s*sin(x**2)*x, x)
440
+ (3**s, x*x**s, sin(x**2))
441
+ """
442
+ fac = S.One
443
+ po = S.One
444
+ g = S.One
445
+ f = expand_power_base(f)
446
+
447
+ args = Mul.make_args(f)
448
+ for a in args:
449
+ if a == x:
450
+ po *= x
451
+ elif x not in a.free_symbols:
452
+ fac *= a
453
+ else:
454
+ if a.is_Pow and x not in a.exp.free_symbols:
455
+ c, t = a.base.as_coeff_mul(x)
456
+ if t != (x,):
457
+ c, t = expand_mul(a.base).as_coeff_mul(x)
458
+ if t == (x,):
459
+ po *= x**a.exp
460
+ fac *= unpolarify(polarify(c**a.exp, subs=False))
461
+ continue
462
+ g *= a
463
+
464
+ return fac, po, g
465
+
466
+
467
+ def _mul_args(f):
468
+ """
469
+ Return a list ``L`` such that ``Mul(*L) == f``.
470
+
471
+ If ``f`` is not a ``Mul`` or ``Pow``, ``L=[f]``.
472
+ If ``f=g**n`` for an integer ``n``, ``L=[g]*n``.
473
+ If ``f`` is a ``Mul``, ``L`` comes from applying ``_mul_args`` to all factors of ``f``.
474
+ """
475
+ args = Mul.make_args(f)
476
+ gs = []
477
+ for g in args:
478
+ if g.is_Pow and g.exp.is_Integer:
479
+ n = g.exp
480
+ base = g.base
481
+ if n < 0:
482
+ n = -n
483
+ base = 1/base
484
+ gs += [base]*n
485
+ else:
486
+ gs.append(g)
487
+ return gs
488
+
489
+
490
+ def _mul_as_two_parts(f):
491
+ """
492
+ Find all the ways to split ``f`` into a product of two terms.
493
+ Return None on failure.
494
+
495
+ Explanation
496
+ ===========
497
+
498
+ Although the order is canonical from multiset_partitions, this is
499
+ not necessarily the best order to process the terms. For example,
500
+ if the case of len(gs) == 2 is removed and multiset is allowed to
501
+ sort the terms, some tests fail.
502
+
503
+ Examples
504
+ ========
505
+
506
+ >>> from sympy.integrals.meijerint import _mul_as_two_parts
507
+ >>> from sympy import sin, exp, ordered
508
+ >>> from sympy.abc import x
509
+ >>> list(ordered(_mul_as_two_parts(x*sin(x)*exp(x))))
510
+ [(x, exp(x)*sin(x)), (x*exp(x), sin(x)), (x*sin(x), exp(x))]
511
+ """
512
+
513
+ gs = _mul_args(f)
514
+ if len(gs) < 2:
515
+ return None
516
+ if len(gs) == 2:
517
+ return [tuple(gs)]
518
+ return [(Mul(*x), Mul(*y)) for (x, y) in multiset_partitions(gs, 2)]
519
+
520
+
521
+ def _inflate_g(g, n):
522
+ """ Return C, h such that h is a G function of argument z**n and
523
+ g = C*h. """
524
+ # TODO should this be a method of meijerg?
525
+ # See: [L, page 150, equation (5)]
526
+ def inflate(params, n):
527
+ """ (a1, .., ak) -> (a1/n, (a1+1)/n, ..., (ak + n-1)/n) """
528
+ return [(a + i)/n for a, i in itertools.product(params, range(n))]
529
+ v = S(len(g.ap) - len(g.bq))
530
+ C = n**(1 + g.nu + v/2)
531
+ C /= (2*pi)**((n - 1)*g.delta)
532
+ return C, meijerg(inflate(g.an, n), inflate(g.aother, n),
533
+ inflate(g.bm, n), inflate(g.bother, n),
534
+ g.argument**n * n**(n*v))
535
+
536
+
537
+ def _flip_g(g):
538
+ """ Turn the G function into one of inverse argument
539
+ (i.e. G(1/x) -> G'(x)) """
540
+ # See [L], section 5.2
541
+ def tr(l):
542
+ return [1 - a for a in l]
543
+ return meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), 1/g.argument)
544
+
545
+
546
+ def _inflate_fox_h(g, a):
547
+ r"""
548
+ Let d denote the integrand in the definition of the G function ``g``.
549
+ Consider the function H which is defined in the same way, but with
550
+ integrand d/Gamma(a*s) (contour conventions as usual).
551
+
552
+ If ``a`` is rational, the function H can be written as C*G, for a constant C
553
+ and a G-function G.
554
+
555
+ This function returns C, G.
556
+ """
557
+ if a < 0:
558
+ return _inflate_fox_h(_flip_g(g), -a)
559
+ p = S(a.p)
560
+ q = S(a.q)
561
+ # We use the substitution s->qs, i.e. inflate g by q. We are left with an
562
+ # extra factor of Gamma(p*s), for which we use Gauss' multiplication
563
+ # theorem.
564
+ D, g = _inflate_g(g, q)
565
+ z = g.argument
566
+ D /= (2*pi)**((1 - p)/2)*p**Rational(-1, 2)
567
+ z /= p**p
568
+ bs = [(n + 1)/p for n in range(p)]
569
+ return D, meijerg(g.an, g.aother, g.bm, list(g.bother) + bs, z)
570
+
571
+ _dummies: dict[tuple[str, str], Dummy] = {}
572
+
573
+
574
+ def _dummy(name, token, expr, **kwargs):
575
+ """
576
+ Return a dummy. This will return the same dummy if the same token+name is
577
+ requested more than once, and it is not already in expr.
578
+ This is for being cache-friendly.
579
+ """
580
+ d = _dummy_(name, token, **kwargs)
581
+ if d in expr.free_symbols:
582
+ return Dummy(name, **kwargs)
583
+ return d
584
+
585
+
586
+ def _dummy_(name, token, **kwargs):
587
+ """
588
+ Return a dummy associated to name and token. Same effect as declaring
589
+ it globally.
590
+ """
591
+ global _dummies
592
+ if not (name, token) in _dummies:
593
+ _dummies[(name, token)] = Dummy(name, **kwargs)
594
+ return _dummies[(name, token)]
595
+
596
+
597
+ def _is_analytic(f, x):
598
+ """ Check if f(x), when expressed using G functions on the positive reals,
599
+ will in fact agree with the G functions almost everywhere """
600
+ return not any(x in expr.free_symbols for expr in f.atoms(Heaviside, Abs))
601
+
602
+
603
+ def _condsimp(cond, first=True):
604
+ """
605
+ Do naive simplifications on ``cond``.
606
+
607
+ Explanation
608
+ ===========
609
+
610
+ Note that this routine is completely ad-hoc, simplification rules being
611
+ added as need arises rather than following any logical pattern.
612
+
613
+ Examples
614
+ ========
615
+
616
+ >>> from sympy.integrals.meijerint import _condsimp as simp
617
+ >>> from sympy import Or, Eq
618
+ >>> from sympy.abc import x, y
619
+ >>> simp(Or(x < y, Eq(x, y)))
620
+ x <= y
621
+ """
622
+ if first:
623
+ cond = cond.replace(lambda _: _.is_Relational, _canonical_coeff)
624
+ first = False
625
+ if not isinstance(cond, BooleanFunction):
626
+ return cond
627
+ p, q, r = symbols('p q r', cls=Wild)
628
+ # transforms tests use 0, 4, 5 and 11-14
629
+ # meijer tests use 0, 2, 11, 14
630
+ # joint_rv uses 6, 7
631
+ rules = [
632
+ (Or(p < q, Eq(p, q)), p <= q), # 0
633
+ # The next two obviously are instances of a general pattern, but it is
634
+ # easier to spell out the few cases we care about.
635
+ (And(Abs(arg(p)) <= pi, Abs(arg(p) - 2*pi) <= pi),
636
+ Eq(arg(p) - pi, 0)), # 1
637
+ (And(Abs(2*arg(p) + pi) <= pi, Abs(2*arg(p) - pi) <= pi),
638
+ Eq(arg(p), 0)), # 2
639
+ (And(Abs(2*arg(p) + pi) < pi, Abs(2*arg(p) - pi) <= pi),
640
+ S.false), # 3
641
+ (And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) <= pi/2),
642
+ Eq(arg(p), 0)), # 4
643
+ (And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) < pi/2),
644
+ S.false), # 5
645
+ (And(Abs(arg(p**2/2 + 1)) < pi, Ne(Abs(arg(p**2/2 + 1)), pi)),
646
+ S.true), # 6
647
+ (Or(Abs(arg(p**2/2 + 1)) < pi, Ne(1/(p**2/2 + 1), 0)),
648
+ S.true), # 7
649
+ (And(Abs(unbranched_argument(p)) <= pi,
650
+ Abs(unbranched_argument(exp_polar(-2*pi*S.ImaginaryUnit)*p)) <= pi),
651
+ Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi)*p), 0)), # 8
652
+ (And(Abs(unbranched_argument(p)) <= pi/2,
653
+ Abs(unbranched_argument(exp_polar(-pi*S.ImaginaryUnit)*p)) <= pi/2),
654
+ Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi/2)*p), 0)), # 9
655
+ (Or(p <= q, And(p < q, r)), p <= q), # 10
656
+ (Ne(p**2, 1) & (p**2 > 1), p**2 > 1), # 11
657
+ (Ne(1/p, 1) & (cos(Abs(arg(p)))*Abs(p) > 1), Abs(p) > 1), # 12
658
+ (Ne(p, 2) & (cos(Abs(arg(p)))*Abs(p) > 2), Abs(p) > 2), # 13
659
+ ((Abs(arg(p)) < pi/2) & (cos(Abs(arg(p)))*sqrt(Abs(p**2)) > 1), p**2 > 1), # 14
660
+ ]
661
+ cond = cond.func(*[_condsimp(_, first) for _ in cond.args])
662
+ change = True
663
+ while change:
664
+ change = False
665
+ for irule, (fro, to) in enumerate(rules):
666
+ if fro.func != cond.func:
667
+ continue
668
+ for n, arg1 in enumerate(cond.args):
669
+ if r in fro.args[0].free_symbols:
670
+ m = arg1.match(fro.args[1])
671
+ num = 1
672
+ else:
673
+ num = 0
674
+ m = arg1.match(fro.args[0])
675
+ if not m:
676
+ continue
677
+ otherargs = [x.subs(m) for x in fro.args[:num] + fro.args[num + 1:]]
678
+ otherlist = [n]
679
+ for arg2 in otherargs:
680
+ for k, arg3 in enumerate(cond.args):
681
+ if k in otherlist:
682
+ continue
683
+ if arg2 == arg3:
684
+ otherlist += [k]
685
+ break
686
+ if isinstance(arg3, And) and arg2.args[1] == r and \
687
+ isinstance(arg2, And) and arg2.args[0] in arg3.args:
688
+ otherlist += [k]
689
+ break
690
+ if isinstance(arg3, And) and arg2.args[0] == r and \
691
+ isinstance(arg2, And) and arg2.args[1] in arg3.args:
692
+ otherlist += [k]
693
+ break
694
+ if len(otherlist) != len(otherargs) + 1:
695
+ continue
696
+ newargs = [arg_ for (k, arg_) in enumerate(cond.args)
697
+ if k not in otherlist] + [to.subs(m)]
698
+ if SYMPY_DEBUG:
699
+ if irule not in (0, 2, 4, 5, 6, 7, 11, 12, 13, 14):
700
+ print('used new rule:', irule)
701
+ cond = cond.func(*newargs)
702
+ change = True
703
+ break
704
+
705
+ # final tweak
706
+ def rel_touchup(rel):
707
+ if rel.rel_op != '==' or rel.rhs != 0:
708
+ return rel
709
+
710
+ # handle Eq(*, 0)
711
+ LHS = rel.lhs
712
+ m = LHS.match(arg(p)**q)
713
+ if not m:
714
+ m = LHS.match(unbranched_argument(polar_lift(p)**q))
715
+ if not m:
716
+ if isinstance(LHS, periodic_argument) and not LHS.args[0].is_polar \
717
+ and LHS.args[1] is S.Infinity:
718
+ return (LHS.args[0] > 0)
719
+ return rel
720
+ return (m[p] > 0)
721
+ cond = cond.replace(lambda _: _.is_Relational, rel_touchup)
722
+ if SYMPY_DEBUG:
723
+ print('_condsimp: ', cond)
724
+ return cond
725
+
726
+ def _eval_cond(cond):
727
+ """ Re-evaluate the conditions. """
728
+ if isinstance(cond, bool):
729
+ return cond
730
+ return _condsimp(cond.doit())
731
+
732
+ ####################################################################
733
+ # Now the "backbone" functions to do actual integration.
734
+ ####################################################################
735
+
736
+
737
+ def _my_principal_branch(expr, period, full_pb=False):
738
+ """ Bring expr nearer to its principal branch by removing superfluous
739
+ factors.
740
+ This function does *not* guarantee to yield the principal branch,
741
+ to avoid introducing opaque principal_branch() objects,
742
+ unless full_pb=True. """
743
+ res = principal_branch(expr, period)
744
+ if not full_pb:
745
+ res = res.replace(principal_branch, lambda x, y: x)
746
+ return res
747
+
748
+
749
+ def _rewrite_saxena_1(fac, po, g, x):
750
+ """
751
+ Rewrite the integral fac*po*g dx, from zero to infinity, as
752
+ integral fac*G, where G has argument a*x. Note po=x**s.
753
+ Return fac, G.
754
+ """
755
+ _, s = _get_coeff_exp(po, x)
756
+ a, b = _get_coeff_exp(g.argument, x)
757
+ period = g.get_period()
758
+ a = _my_principal_branch(a, period)
759
+
760
+ # We substitute t = x**b.
761
+ C = fac/(Abs(b)*a**((s + 1)/b - 1))
762
+ # Absorb a factor of (at)**((1 + s)/b - 1).
763
+
764
+ def tr(l):
765
+ return [a + (1 + s)/b - 1 for a in l]
766
+ return C, meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother),
767
+ a*x)
768
+
769
+
770
+ def _check_antecedents_1(g, x, helper=False):
771
+ r"""
772
+ Return a condition under which the mellin transform of g exists.
773
+ Any power of x has already been absorbed into the G function,
774
+ so this is just $\int_0^\infty g\, dx$.
775
+
776
+ See [L, section 5.6.1]. (Note that s=1.)
777
+
778
+ If ``helper`` is True, only check if the MT exists at infinity, i.e. if
779
+ $\int_1^\infty g\, dx$ exists.
780
+ """
781
+ # NOTE if you update these conditions, please update the documentation as well
782
+ delta = g.delta
783
+ eta, _ = _get_coeff_exp(g.argument, x)
784
+ m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)])
785
+
786
+ if p > q:
787
+ def tr(l):
788
+ return [1 - x for x in l]
789
+ return _check_antecedents_1(meijerg(tr(g.bm), tr(g.bother),
790
+ tr(g.an), tr(g.aother), x/eta),
791
+ x)
792
+
793
+ tmp = [-re(b) < 1 for b in g.bm] + [1 < 1 - re(a) for a in g.an]
794
+ cond_3 = And(*tmp)
795
+
796
+ tmp += [-re(b) < 1 for b in g.bother]
797
+ tmp += [1 < 1 - re(a) for a in g.aother]
798
+ cond_3_star = And(*tmp)
799
+
800
+ cond_4 = (-re(g.nu) + (q + 1 - p)/2 > q - p)
801
+
802
+ def debug(*msg):
803
+ _debug(*msg)
804
+
805
+ def debugf(string, arg):
806
+ _debugf(string, arg)
807
+
808
+ debug('Checking antecedents for 1 function:')
809
+ debugf(' delta=%s, eta=%s, m=%s, n=%s, p=%s, q=%s',
810
+ (delta, eta, m, n, p, q))
811
+ debugf(' ap = %s, %s', (list(g.an), list(g.aother)))
812
+ debugf(' bq = %s, %s', (list(g.bm), list(g.bother)))
813
+ debugf(' cond_3=%s, cond_3*=%s, cond_4=%s', (cond_3, cond_3_star, cond_4))
814
+
815
+ conds = []
816
+
817
+ # case 1
818
+ case1 = []
819
+ tmp1 = [1 <= n, p < q, 1 <= m]
820
+ tmp2 = [1 <= p, 1 <= m, Eq(q, p + 1), Not(And(Eq(n, 0), Eq(m, p + 1)))]
821
+ tmp3 = [1 <= p, Eq(q, p)]
822
+ for k in range(ceiling(delta/2) + 1):
823
+ tmp3 += [Ne(Abs(unbranched_argument(eta)), (delta - 2*k)*pi)]
824
+ tmp = [delta > 0, Abs(unbranched_argument(eta)) < delta*pi]
825
+ extra = [Ne(eta, 0), cond_3]
826
+ if helper:
827
+ extra = []
828
+ for t in [tmp1, tmp2, tmp3]:
829
+ case1 += [And(*(t + tmp + extra))]
830
+ conds += case1
831
+ debug(' case 1:', case1)
832
+
833
+ # case 2
834
+ extra = [cond_3]
835
+ if helper:
836
+ extra = []
837
+ case2 = [And(Eq(n, 0), p + 1 <= m, m <= q,
838
+ Abs(unbranched_argument(eta)) < delta*pi, *extra)]
839
+ conds += case2
840
+ debug(' case 2:', case2)
841
+
842
+ # case 3
843
+ extra = [cond_3, cond_4]
844
+ if helper:
845
+ extra = []
846
+ case3 = [And(p < q, 1 <= m, delta > 0, Eq(Abs(unbranched_argument(eta)), delta*pi),
847
+ *extra)]
848
+ case3 += [And(p <= q - 2, Eq(delta, 0), Eq(Abs(unbranched_argument(eta)), 0), *extra)]
849
+ conds += case3
850
+ debug(' case 3:', case3)
851
+
852
+ # TODO altered cases 4-7
853
+
854
+ # extra case from wofram functions site:
855
+ # (reproduced verbatim from Prudnikov, section 2.24.2)
856
+ # https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/01/
857
+ case_extra = []
858
+ case_extra += [Eq(p, q), Eq(delta, 0), Eq(unbranched_argument(eta), 0), Ne(eta, 0)]
859
+ if not helper:
860
+ case_extra += [cond_3]
861
+ s = []
862
+ for a, b in zip(g.ap, g.bq):
863
+ s += [b - a]
864
+ case_extra += [re(Add(*s)) < 0]
865
+ case_extra = And(*case_extra)
866
+ conds += [case_extra]
867
+ debug(' extra case:', [case_extra])
868
+
869
+ case_extra_2 = [And(delta > 0, Abs(unbranched_argument(eta)) < delta*pi)]
870
+ if not helper:
871
+ case_extra_2 += [cond_3]
872
+ case_extra_2 = And(*case_extra_2)
873
+ conds += [case_extra_2]
874
+ debug(' second extra case:', [case_extra_2])
875
+
876
+ # TODO This leaves only one case from the three listed by Prudnikov.
877
+ # Investigate if these indeed cover everything; if so, remove the rest.
878
+
879
+ return Or(*conds)
880
+
881
+
882
+ def _int0oo_1(g, x):
883
+ r"""
884
+ Evaluate $\int_0^\infty g\, dx$ using G functions,
885
+ assuming the necessary conditions are fulfilled.
886
+
887
+ Examples
888
+ ========
889
+
890
+ >>> from sympy.abc import a, b, c, d, x, y
891
+ >>> from sympy import meijerg
892
+ >>> from sympy.integrals.meijerint import _int0oo_1
893
+ >>> _int0oo_1(meijerg([a], [b], [c], [d], x*y), x)
894
+ gamma(-a)*gamma(c + 1)/(y*gamma(-d)*gamma(b + 1))
895
+ """
896
+ from sympy.simplify import gammasimp
897
+ # See [L, section 5.6.1]. Note that s=1.
898
+ eta, _ = _get_coeff_exp(g.argument, x)
899
+ res = 1/eta
900
+ # XXX TODO we should reduce order first
901
+ for b in g.bm:
902
+ res *= gamma(b + 1)
903
+ for a in g.an:
904
+ res *= gamma(1 - a - 1)
905
+ for b in g.bother:
906
+ res /= gamma(1 - b - 1)
907
+ for a in g.aother:
908
+ res /= gamma(a + 1)
909
+ return gammasimp(unpolarify(res))
910
+
911
+
912
+ def _rewrite_saxena(fac, po, g1, g2, x, full_pb=False):
913
+ """
914
+ Rewrite the integral ``fac*po*g1*g2`` from 0 to oo in terms of G
915
+ functions with argument ``c*x``.
916
+
917
+ Explanation
918
+ ===========
919
+
920
+ Return C, f1, f2 such that integral C f1 f2 from 0 to infinity equals
921
+ integral fac ``po``, ``g1``, ``g2`` from 0 to infinity.
922
+
923
+ Examples
924
+ ========
925
+
926
+ >>> from sympy.integrals.meijerint import _rewrite_saxena
927
+ >>> from sympy.abc import s, t, m
928
+ >>> from sympy import meijerg
929
+ >>> g1 = meijerg([], [], [0], [], s*t)
930
+ >>> g2 = meijerg([], [], [m/2], [-m/2], t**2/4)
931
+ >>> r = _rewrite_saxena(1, t**0, g1, g2, t)
932
+ >>> r[0]
933
+ s/(4*sqrt(pi))
934
+ >>> r[1]
935
+ meijerg(((), ()), ((-1/2, 0), ()), s**2*t/4)
936
+ >>> r[2]
937
+ meijerg(((), ()), ((m/2,), (-m/2,)), t/4)
938
+ """
939
+ def pb(g):
940
+ a, b = _get_coeff_exp(g.argument, x)
941
+ per = g.get_period()
942
+ return meijerg(g.an, g.aother, g.bm, g.bother,
943
+ _my_principal_branch(a, per, full_pb)*x**b)
944
+
945
+ _, s = _get_coeff_exp(po, x)
946
+ _, b1 = _get_coeff_exp(g1.argument, x)
947
+ _, b2 = _get_coeff_exp(g2.argument, x)
948
+ if (b1 < 0) == True:
949
+ b1 = -b1
950
+ g1 = _flip_g(g1)
951
+ if (b2 < 0) == True:
952
+ b2 = -b2
953
+ g2 = _flip_g(g2)
954
+ if not b1.is_Rational or not b2.is_Rational:
955
+ return
956
+ m1, n1 = b1.p, b1.q
957
+ m2, n2 = b2.p, b2.q
958
+ tau = ilcm(m1*n2, m2*n1)
959
+ r1 = tau//(m1*n2)
960
+ r2 = tau//(m2*n1)
961
+
962
+ C1, g1 = _inflate_g(g1, r1)
963
+ C2, g2 = _inflate_g(g2, r2)
964
+ g1 = pb(g1)
965
+ g2 = pb(g2)
966
+
967
+ fac *= C1*C2
968
+ a1, b = _get_coeff_exp(g1.argument, x)
969
+ a2, _ = _get_coeff_exp(g2.argument, x)
970
+
971
+ # arbitrarily tack on the x**s part to g1
972
+ # TODO should we try both?
973
+ exp = (s + 1)/b - 1
974
+ fac = fac/(Abs(b) * a1**exp)
975
+
976
+ def tr(l):
977
+ return [a + exp for a in l]
978
+ g1 = meijerg(tr(g1.an), tr(g1.aother), tr(g1.bm), tr(g1.bother), a1*x)
979
+ g2 = meijerg(g2.an, g2.aother, g2.bm, g2.bother, a2*x)
980
+
981
+ from sympy.simplify import powdenest
982
+ return powdenest(fac, polar=True), g1, g2
983
+
984
+
985
+ def _check_antecedents(g1, g2, x):
986
+ """ Return a condition under which the integral theorem applies. """
987
+ # Yes, this is madness.
988
+ # XXX TODO this is a testing *nightmare*
989
+ # NOTE if you update these conditions, please update the documentation as well
990
+
991
+ # The following conditions are found in
992
+ # [P], Section 2.24.1
993
+ #
994
+ # They are also reproduced (verbatim!) at
995
+ # https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/
996
+ #
997
+ # Note: k=l=r=alpha=1
998
+ sigma, _ = _get_coeff_exp(g1.argument, x)
999
+ omega, _ = _get_coeff_exp(g2.argument, x)
1000
+ s, t, u, v = S([len(g1.bm), len(g1.an), len(g1.ap), len(g1.bq)])
1001
+ m, n, p, q = S([len(g2.bm), len(g2.an), len(g2.ap), len(g2.bq)])
1002
+ bstar = s + t - (u + v)/2
1003
+ cstar = m + n - (p + q)/2
1004
+ rho = g1.nu + (u - v)/2 + 1
1005
+ mu = g2.nu + (p - q)/2 + 1
1006
+ phi = q - p - (v - u)
1007
+ eta = 1 - (v - u) - mu - rho
1008
+ psi = (pi*(q - m - n) + Abs(unbranched_argument(omega)))/(q - p)
1009
+ theta = (pi*(v - s - t) + Abs(unbranched_argument(sigma)))/(v - u)
1010
+
1011
+ _debug('Checking antecedents:')
1012
+ _debugf(' sigma=%s, s=%s, t=%s, u=%s, v=%s, b*=%s, rho=%s',
1013
+ (sigma, s, t, u, v, bstar, rho))
1014
+ _debugf(' omega=%s, m=%s, n=%s, p=%s, q=%s, c*=%s, mu=%s,',
1015
+ (omega, m, n, p, q, cstar, mu))
1016
+ _debugf(' phi=%s, eta=%s, psi=%s, theta=%s', (phi, eta, psi, theta))
1017
+
1018
+ def _c1():
1019
+ for g in [g1, g2]:
1020
+ for i, j in itertools.product(g.an, g.bm):
1021
+ diff = i - j
1022
+ if diff.is_integer and diff.is_positive:
1023
+ return False
1024
+ return True
1025
+ c1 = _c1()
1026
+ c2 = And(*[re(1 + i + j) > 0 for i in g1.bm for j in g2.bm])
1027
+ c3 = And(*[re(1 + i + j) < 1 + 1 for i in g1.an for j in g2.an])
1028
+ c4 = And(*[(p - q)*re(1 + i - 1) - re(mu) > Rational(-3, 2) for i in g1.an])
1029
+ c5 = And(*[(p - q)*re(1 + i) - re(mu) > Rational(-3, 2) for i in g1.bm])
1030
+ c6 = And(*[(u - v)*re(1 + i - 1) - re(rho) > Rational(-3, 2) for i in g2.an])
1031
+ c7 = And(*[(u - v)*re(1 + i) - re(rho) > Rational(-3, 2) for i in g2.bm])
1032
+ c8 = (Abs(phi) + 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu -
1033
+ 1)*(v - u)) > 0)
1034
+ c9 = (Abs(phi) - 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu -
1035
+ 1)*(v - u)) > 0)
1036
+ c10 = (Abs(unbranched_argument(sigma)) < bstar*pi)
1037
+ c11 = Eq(Abs(unbranched_argument(sigma)), bstar*pi)
1038
+ c12 = (Abs(unbranched_argument(omega)) < cstar*pi)
1039
+ c13 = Eq(Abs(unbranched_argument(omega)), cstar*pi)
1040
+
1041
+ # The following condition is *not* implemented as stated on the wolfram
1042
+ # function site. In the book of Prudnikov there is an additional part
1043
+ # (the And involving re()). However, I only have this book in russian, and
1044
+ # I don't read any russian. The following condition is what other people
1045
+ # have told me it means.
1046
+ # Worryingly, it is different from the condition implemented in REDUCE.
1047
+ # The REDUCE implementation:
1048
+ # https://reduce-algebra.svn.sourceforge.net/svnroot/reduce-algebra/trunk/packages/defint/definta.red
1049
+ # (search for tst14)
1050
+ # The Wolfram alpha version:
1051
+ # https://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/03/0014/
1052
+ z0 = exp(-(bstar + cstar)*pi*S.ImaginaryUnit)
1053
+ zos = unpolarify(z0*omega/sigma)
1054
+ zso = unpolarify(z0*sigma/omega)
1055
+ if zos == 1/zso:
1056
+ c14 = And(Eq(phi, 0), bstar + cstar <= 1,
1057
+ Or(Ne(zos, 1), re(mu + rho + v - u) < 1,
1058
+ re(mu + rho + q - p) < 1))
1059
+ else:
1060
+ def _cond(z):
1061
+ '''Returns True if abs(arg(1-z)) < pi, avoiding arg(0).
1062
+
1063
+ Explanation
1064
+ ===========
1065
+
1066
+ If ``z`` is 1 then arg is NaN. This raises a
1067
+ TypeError on `NaN < pi`. Previously this gave `False` so
1068
+ this behavior has been hardcoded here but someone should
1069
+ check if this NaN is more serious! This NaN is triggered by
1070
+ test_meijerint() in test_meijerint.py:
1071
+ `meijerint_definite(exp(x), x, 0, I)`
1072
+ '''
1073
+ return z != 1 and Abs(arg(1 - z)) < pi
1074
+
1075
+ c14 = And(Eq(phi, 0), bstar - 1 + cstar <= 0,
1076
+ Or(And(Ne(zos, 1), _cond(zos)),
1077
+ And(re(mu + rho + v - u) < 1, Eq(zos, 1))))
1078
+
1079
+ c14_alt = And(Eq(phi, 0), cstar - 1 + bstar <= 0,
1080
+ Or(And(Ne(zso, 1), _cond(zso)),
1081
+ And(re(mu + rho + q - p) < 1, Eq(zso, 1))))
1082
+
1083
+ # Since r=k=l=1, in our case there is c14_alt which is the same as calling
1084
+ # us with (g1, g2) = (g2, g1). The conditions below enumerate all cases
1085
+ # (i.e. we don't have to try arguments reversed by hand), and indeed try
1086
+ # all symmetric cases. (i.e. whenever there is a condition involving c14,
1087
+ # there is also a dual condition which is exactly what we would get when g1,
1088
+ # g2 were interchanged, *but c14 was unaltered*).
1089
+ # Hence the following seems correct:
1090
+ c14 = Or(c14, c14_alt)
1091
+
1092
+ '''
1093
+ When `c15` is NaN (e.g. from `psi` being NaN as happens during
1094
+ 'test_issue_4992' and/or `theta` is NaN as in 'test_issue_6253',
1095
+ both in `test_integrals.py`) the comparison to 0 formerly gave False
1096
+ whereas now an error is raised. To keep the old behavior, the value
1097
+ of NaN is replaced with False but perhaps a closer look at this condition
1098
+ should be made: XXX how should conditions leading to c15=NaN be handled?
1099
+ '''
1100
+ try:
1101
+ lambda_c = (q - p)*Abs(omega)**(1/(q - p))*cos(psi) \
1102
+ + (v - u)*Abs(sigma)**(1/(v - u))*cos(theta)
1103
+ # the TypeError might be raised here, e.g. if lambda_c is NaN
1104
+ if _eval_cond(lambda_c > 0) != False:
1105
+ c15 = (lambda_c > 0)
1106
+ else:
1107
+ def lambda_s0(c1, c2):
1108
+ return c1*(q - p)*Abs(omega)**(1/(q - p))*sin(psi) \
1109
+ + c2*(v - u)*Abs(sigma)**(1/(v - u))*sin(theta)
1110
+ lambda_s = Piecewise(
1111
+ ((lambda_s0(+1, +1)*lambda_s0(-1, -1)),
1112
+ And(Eq(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))),
1113
+ (lambda_s0(sign(unbranched_argument(omega)), +1)*lambda_s0(sign(unbranched_argument(omega)), -1),
1114
+ And(Eq(unbranched_argument(sigma), 0), Ne(unbranched_argument(omega), 0))),
1115
+ (lambda_s0(+1, sign(unbranched_argument(sigma)))*lambda_s0(-1, sign(unbranched_argument(sigma))),
1116
+ And(Ne(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))),
1117
+ (lambda_s0(sign(unbranched_argument(omega)), sign(unbranched_argument(sigma))), True))
1118
+ tmp = [lambda_c > 0,
1119
+ And(Eq(lambda_c, 0), Ne(lambda_s, 0), re(eta) > -1),
1120
+ And(Eq(lambda_c, 0), Eq(lambda_s, 0), re(eta) > 0)]
1121
+ c15 = Or(*tmp)
1122
+ except TypeError:
1123
+ c15 = False
1124
+ for cond, i in [(c1, 1), (c2, 2), (c3, 3), (c4, 4), (c5, 5), (c6, 6),
1125
+ (c7, 7), (c8, 8), (c9, 9), (c10, 10), (c11, 11),
1126
+ (c12, 12), (c13, 13), (c14, 14), (c15, 15)]:
1127
+ _debugf(' c%s: %s', (i, cond))
1128
+
1129
+ # We will return Or(*conds)
1130
+ conds = []
1131
+
1132
+ def pr(count):
1133
+ _debugf(' case %s: %s', (count, conds[-1]))
1134
+ conds += [And(m*n*s*t != 0, bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10,
1135
+ c12)] # 1
1136
+ pr(1)
1137
+ conds += [And(Eq(u, v), Eq(bstar, 0), cstar.is_positive is True, sigma.is_positive is True, re(rho) < 1,
1138
+ c1, c2, c3, c12)] # 2
1139
+ pr(2)
1140
+ conds += [And(Eq(p, q), Eq(cstar, 0), bstar.is_positive is True, omega.is_positive is True, re(mu) < 1,
1141
+ c1, c2, c3, c10)] # 3
1142
+ pr(3)
1143
+ conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0),
1144
+ sigma.is_positive is True, omega.is_positive is True, re(mu) < 1, re(rho) < 1,
1145
+ Ne(sigma, omega), c1, c2, c3)] # 4
1146
+ pr(4)
1147
+ conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0),
1148
+ sigma.is_positive is True, omega.is_positive is True, re(mu + rho) < 1,
1149
+ Ne(omega, sigma), c1, c2, c3)] # 5
1150
+ pr(5)
1151
+ conds += [And(p > q, s.is_positive is True, bstar.is_positive is True, cstar >= 0,
1152
+ c1, c2, c3, c5, c10, c13)] # 6
1153
+ pr(6)
1154
+ conds += [And(p < q, t.is_positive is True, bstar.is_positive is True, cstar >= 0,
1155
+ c1, c2, c3, c4, c10, c13)] # 7
1156
+ pr(7)
1157
+ conds += [And(u > v, m.is_positive is True, cstar.is_positive is True, bstar >= 0,
1158
+ c1, c2, c3, c7, c11, c12)] # 8
1159
+ pr(8)
1160
+ conds += [And(u < v, n.is_positive is True, cstar.is_positive is True, bstar >= 0,
1161
+ c1, c2, c3, c6, c11, c12)] # 9
1162
+ pr(9)
1163
+ conds += [And(p > q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True,
1164
+ re(rho) < 1, c1, c2, c3, c5, c13)] # 10
1165
+ pr(10)
1166
+ conds += [And(p < q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True,
1167
+ re(rho) < 1, c1, c2, c3, c4, c13)] # 11
1168
+ pr(11)
1169
+ conds += [And(Eq(p, q), u > v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True,
1170
+ re(mu) < 1, c1, c2, c3, c7, c11)] # 12
1171
+ pr(12)
1172
+ conds += [And(Eq(p, q), u < v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True,
1173
+ re(mu) < 1, c1, c2, c3, c6, c11)] # 13
1174
+ pr(13)
1175
+ conds += [And(p < q, u > v, bstar >= 0, cstar >= 0,
1176
+ c1, c2, c3, c4, c7, c11, c13)] # 14
1177
+ pr(14)
1178
+ conds += [And(p > q, u < v, bstar >= 0, cstar >= 0,
1179
+ c1, c2, c3, c5, c6, c11, c13)] # 15
1180
+ pr(15)
1181
+ conds += [And(p > q, u > v, bstar >= 0, cstar >= 0,
1182
+ c1, c2, c3, c5, c7, c8, c11, c13, c14)] # 16
1183
+ pr(16)
1184
+ conds += [And(p < q, u < v, bstar >= 0, cstar >= 0,
1185
+ c1, c2, c3, c4, c6, c9, c11, c13, c14)] # 17
1186
+ pr(17)
1187
+ conds += [And(Eq(t, 0), s.is_positive is True, bstar.is_positive is True, phi.is_positive is True, c1, c2, c10)] # 18
1188
+ pr(18)
1189
+ conds += [And(Eq(s, 0), t.is_positive is True, bstar.is_positive is True, phi.is_negative is True, c1, c3, c10)] # 19
1190
+ pr(19)
1191
+ conds += [And(Eq(n, 0), m.is_positive is True, cstar.is_positive is True, phi.is_negative is True, c1, c2, c12)] # 20
1192
+ pr(20)
1193
+ conds += [And(Eq(m, 0), n.is_positive is True, cstar.is_positive is True, phi.is_positive is True, c1, c3, c12)] # 21
1194
+ pr(21)
1195
+ conds += [And(Eq(s*t, 0), bstar.is_positive is True, cstar.is_positive is True,
1196
+ c1, c2, c3, c10, c12)] # 22
1197
+ pr(22)
1198
+ conds += [And(Eq(m*n, 0), bstar.is_positive is True, cstar.is_positive is True,
1199
+ c1, c2, c3, c10, c12)] # 23
1200
+ pr(23)
1201
+
1202
+ # The following case is from [Luke1969]. As far as I can tell, it is *not*
1203
+ # covered by Prudnikov's.
1204
+ # Let G1 and G2 be the two G-functions. Suppose the integral exists from
1205
+ # 0 to a > 0 (this is easy the easy part), that G1 is exponential decay at
1206
+ # infinity, and that the mellin transform of G2 exists.
1207
+ # Then the integral exists.
1208
+ mt1_exists = _check_antecedents_1(g1, x, helper=True)
1209
+ mt2_exists = _check_antecedents_1(g2, x, helper=True)
1210
+ conds += [And(mt2_exists, Eq(t, 0), u < s, bstar.is_positive is True, c10, c1, c2, c3)]
1211
+ pr('E1')
1212
+ conds += [And(mt2_exists, Eq(s, 0), v < t, bstar.is_positive is True, c10, c1, c2, c3)]
1213
+ pr('E2')
1214
+ conds += [And(mt1_exists, Eq(n, 0), p < m, cstar.is_positive is True, c12, c1, c2, c3)]
1215
+ pr('E3')
1216
+ conds += [And(mt1_exists, Eq(m, 0), q < n, cstar.is_positive is True, c12, c1, c2, c3)]
1217
+ pr('E4')
1218
+
1219
+ # Let's short-circuit if this worked ...
1220
+ # the rest is corner-cases and terrible to read.
1221
+ r = Or(*conds)
1222
+ if _eval_cond(r) != False:
1223
+ return r
1224
+
1225
+ conds += [And(m + n > p, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar.is_negative is True,
1226
+ Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi,
1227
+ c1, c2, c10, c14, c15)] # 24
1228
+ pr(24)
1229
+ conds += [And(m + n > q, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar.is_negative is True,
1230
+ Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi,
1231
+ c1, c3, c10, c14, c15)] # 25
1232
+ pr(25)
1233
+ conds += [And(Eq(p, q - 1), Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True,
1234
+ cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
1235
+ c1, c2, c10, c14, c15)] # 26
1236
+ pr(26)
1237
+ conds += [And(Eq(p, q + 1), Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True,
1238
+ cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
1239
+ c1, c3, c10, c14, c15)] # 27
1240
+ pr(27)
1241
+ conds += [And(p < q - 1, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True,
1242
+ cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)),
1243
+ Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi,
1244
+ c1, c2, c10, c14, c15)] # 28
1245
+ pr(28)
1246
+ conds += [And(
1247
+ p > q + 1, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar >= 0,
1248
+ cstar*pi < Abs(unbranched_argument(omega)),
1249
+ Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi,
1250
+ c1, c3, c10, c14, c15)] # 29
1251
+ pr(29)
1252
+ conds += [And(Eq(n, 0), Eq(phi, 0), s + t > 0, m.is_positive is True, cstar.is_positive is True, bstar.is_negative is True,
1253
+ Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi,
1254
+ c1, c2, c12, c14, c15)] # 30
1255
+ pr(30)
1256
+ conds += [And(Eq(m, 0), Eq(phi, 0), s + t > v, n.is_positive is True, cstar.is_positive is True, bstar.is_negative is True,
1257
+ Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi,
1258
+ c1, c3, c12, c14, c15)] # 31
1259
+ pr(31)
1260
+ conds += [And(Eq(n, 0), Eq(phi, 0), Eq(u, v - 1), m.is_positive is True, cstar.is_positive is True,
1261
+ bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)),
1262
+ Abs(unbranched_argument(sigma)) < (bstar + 1)*pi,
1263
+ c1, c2, c12, c14, c15)] # 32
1264
+ pr(32)
1265
+ conds += [And(Eq(m, 0), Eq(phi, 0), Eq(u, v + 1), n.is_positive is True, cstar.is_positive is True,
1266
+ bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)),
1267
+ Abs(unbranched_argument(sigma)) < (bstar + 1)*pi,
1268
+ c1, c3, c12, c14, c15)] # 33
1269
+ pr(33)
1270
+ conds += [And(
1271
+ Eq(n, 0), Eq(phi, 0), u < v - 1, m.is_positive is True, cstar.is_positive is True, bstar >= 0,
1272
+ bstar*pi < Abs(unbranched_argument(sigma)),
1273
+ Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi,
1274
+ c1, c2, c12, c14, c15)] # 34
1275
+ pr(34)
1276
+ conds += [And(
1277
+ Eq(m, 0), Eq(phi, 0), u > v + 1, n.is_positive is True, cstar.is_positive is True, bstar >= 0,
1278
+ bstar*pi < Abs(unbranched_argument(sigma)),
1279
+ Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi,
1280
+ c1, c3, c12, c14, c15)] # 35
1281
+ pr(35)
1282
+
1283
+ return Or(*conds)
1284
+
1285
+ # NOTE An alternative, but as far as I can tell weaker, set of conditions
1286
+ # can be found in [L, section 5.6.2].
1287
+
1288
+
1289
+ def _int0oo(g1, g2, x):
1290
+ """
1291
+ Express integral from zero to infinity g1*g2 using a G function,
1292
+ assuming the necessary conditions are fulfilled.
1293
+
1294
+ Examples
1295
+ ========
1296
+
1297
+ >>> from sympy.integrals.meijerint import _int0oo
1298
+ >>> from sympy.abc import s, t, m
1299
+ >>> from sympy import meijerg, S
1300
+ >>> g1 = meijerg([], [], [-S(1)/2, 0], [], s**2*t/4)
1301
+ >>> g2 = meijerg([], [], [m/2], [-m/2], t/4)
1302
+ >>> _int0oo(g1, g2, t)
1303
+ 4*meijerg(((0, 1/2), ()), ((m/2,), (-m/2,)), s**(-2))/s**2
1304
+ """
1305
+ # See: [L, section 5.6.2, equation (1)]
1306
+ eta, _ = _get_coeff_exp(g1.argument, x)
1307
+ omega, _ = _get_coeff_exp(g2.argument, x)
1308
+
1309
+ def neg(l):
1310
+ return [-x for x in l]
1311
+ a1 = neg(g1.bm) + list(g2.an)
1312
+ a2 = list(g2.aother) + neg(g1.bother)
1313
+ b1 = neg(g1.an) + list(g2.bm)
1314
+ b2 = list(g2.bother) + neg(g1.aother)
1315
+ return meijerg(a1, a2, b1, b2, omega/eta)/eta
1316
+
1317
+
1318
+ def _rewrite_inversion(fac, po, g, x):
1319
+ """ Absorb ``po`` == x**s into g. """
1320
+ _, s = _get_coeff_exp(po, x)
1321
+ a, b = _get_coeff_exp(g.argument, x)
1322
+
1323
+ def tr(l):
1324
+ return [t + s/b for t in l]
1325
+ from sympy.simplify import powdenest
1326
+ return (powdenest(fac/a**(s/b), polar=True),
1327
+ meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), g.argument))
1328
+
1329
+
1330
+ def _check_antecedents_inversion(g, x):
1331
+ """ Check antecedents for the laplace inversion integral. """
1332
+ _debug('Checking antecedents for inversion:')
1333
+ z = g.argument
1334
+ _, e = _get_coeff_exp(z, x)
1335
+ if e < 0:
1336
+ _debug(' Flipping G.')
1337
+ # We want to assume that argument gets large as |x| -> oo
1338
+ return _check_antecedents_inversion(_flip_g(g), x)
1339
+
1340
+ def statement_half(a, b, c, z, plus):
1341
+ coeff, exponent = _get_coeff_exp(z, x)
1342
+ a *= exponent
1343
+ b *= coeff**c
1344
+ c *= exponent
1345
+ conds = []
1346
+ wp = b*exp(S.ImaginaryUnit*re(c)*pi/2)
1347
+ wm = b*exp(-S.ImaginaryUnit*re(c)*pi/2)
1348
+ if plus:
1349
+ w = wp
1350
+ else:
1351
+ w = wm
1352
+ conds += [And(Or(Eq(b, 0), re(c) <= 0), re(a) <= -1)]
1353
+ conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) < 0)]
1354
+ conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) <= 0,
1355
+ re(a) <= -1)]
1356
+ return Or(*conds)
1357
+
1358
+ def statement(a, b, c, z):
1359
+ """ Provide a convergence statement for z**a * exp(b*z**c),
1360
+ c/f sphinx docs. """
1361
+ return And(statement_half(a, b, c, z, True),
1362
+ statement_half(a, b, c, z, False))
1363
+
1364
+ # Notations from [L], section 5.7-10
1365
+ m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)])
1366
+ tau = m + n - p
1367
+ nu = q - m - n
1368
+ rho = (tau - nu)/2
1369
+ sigma = q - p
1370
+ if sigma == 1:
1371
+ epsilon = S.Half
1372
+ elif sigma > 1:
1373
+ epsilon = 1
1374
+ else:
1375
+ epsilon = S.NaN
1376
+ theta = ((1 - sigma)/2 + Add(*g.bq) - Add(*g.ap))/sigma
1377
+ delta = g.delta
1378
+ _debugf(' m=%s, n=%s, p=%s, q=%s, tau=%s, nu=%s, rho=%s, sigma=%s',
1379
+ (m, n, p, q, tau, nu, rho, sigma))
1380
+ _debugf(' epsilon=%s, theta=%s, delta=%s', (epsilon, theta, delta))
1381
+
1382
+ # First check if the computation is valid.
1383
+ if not (g.delta >= e/2 or (p >= 1 and p >= q)):
1384
+ _debug(' Computation not valid for these parameters.')
1385
+ return False
1386
+
1387
+ # Now check if the inversion integral exists.
1388
+
1389
+ # Test "condition A"
1390
+ for a, b in itertools.product(g.an, g.bm):
1391
+ if (a - b).is_integer and a > b:
1392
+ _debug(' Not a valid G function.')
1393
+ return False
1394
+
1395
+ # There are two cases. If p >= q, we can directly use a slater expansion
1396
+ # like [L], 5.2 (11). Note in particular that the asymptotics of such an
1397
+ # expansion even hold when some of the parameters differ by integers, i.e.
1398
+ # the formula itself would not be valid! (b/c G functions are cts. in their
1399
+ # parameters)
1400
+ # When p < q, we need to use the theorems of [L], 5.10.
1401
+
1402
+ if p >= q:
1403
+ _debug(' Using asymptotic Slater expansion.')
1404
+ return And(*[statement(a - 1, 0, 0, z) for a in g.an])
1405
+
1406
+ def E(z):
1407
+ return And(*[statement(a - 1, 0, 0, z) for a in g.an])
1408
+
1409
+ def H(z):
1410
+ return statement(theta, -sigma, 1/sigma, z)
1411
+
1412
+ def Hp(z):
1413
+ return statement_half(theta, -sigma, 1/sigma, z, True)
1414
+
1415
+ def Hm(z):
1416
+ return statement_half(theta, -sigma, 1/sigma, z, False)
1417
+
1418
+ # [L], section 5.10
1419
+ conds = []
1420
+ # Theorem 1 -- p < q from test above
1421
+ conds += [And(1 <= n, 1 <= m, rho*pi - delta >= pi/2, delta > 0,
1422
+ E(z*exp(S.ImaginaryUnit*pi*(nu + 1))))]
1423
+ # Theorem 2, statements (2) and (3)
1424
+ conds += [And(p + 1 <= m, m + 1 <= q, delta > 0, delta < pi/2, n == 0,
1425
+ (m - p + 1)*pi - delta >= pi/2,
1426
+ Hp(z*exp(S.ImaginaryUnit*pi*(q - m))),
1427
+ Hm(z*exp(-S.ImaginaryUnit*pi*(q - m))))]
1428
+ # Theorem 2, statement (5) -- p < q from test above
1429
+ conds += [And(m == q, n == 0, delta > 0,
1430
+ (sigma + epsilon)*pi - delta >= pi/2, H(z))]
1431
+ # Theorem 3, statements (6) and (7)
1432
+ conds += [And(Or(And(p <= q - 2, 1 <= tau, tau <= sigma/2),
1433
+ And(p + 1 <= m + n, m + n <= (p + q)/2)),
1434
+ delta > 0, delta < pi/2, (tau + 1)*pi - delta >= pi/2,
1435
+ Hp(z*exp(S.ImaginaryUnit*pi*nu)),
1436
+ Hm(z*exp(-S.ImaginaryUnit*pi*nu)))]
1437
+ # Theorem 4, statements (10) and (11) -- p < q from test above
1438
+ conds += [And(1 <= m, rho > 0, delta > 0, delta + rho*pi < pi/2,
1439
+ (tau + epsilon)*pi - delta >= pi/2,
1440
+ Hp(z*exp(S.ImaginaryUnit*pi*nu)),
1441
+ Hm(z*exp(-S.ImaginaryUnit*pi*nu)))]
1442
+ # Trivial case
1443
+ conds += [m == 0]
1444
+
1445
+ # TODO
1446
+ # Theorem 5 is quite general
1447
+ # Theorem 6 contains special cases for q=p+1
1448
+
1449
+ return Or(*conds)
1450
+
1451
+
1452
+ def _int_inversion(g, x, t):
1453
+ """
1454
+ Compute the laplace inversion integral, assuming the formula applies.
1455
+ """
1456
+ b, a = _get_coeff_exp(g.argument, x)
1457
+ C, g = _inflate_fox_h(meijerg(g.an, g.aother, g.bm, g.bother, b/t**a), -a)
1458
+ return C/t*g
1459
+
1460
+
1461
+ ####################################################################
1462
+ # Finally, the real meat.
1463
+ ####################################################################
1464
+
1465
+ _lookup_table = None
1466
+
1467
+
1468
+ @cacheit
1469
+ @timeit
1470
+ def _rewrite_single(f, x, recursive=True):
1471
+ """
1472
+ Try to rewrite f as a sum of single G functions of the form
1473
+ C*x**s*G(a*x**b), where b is a rational number and C is independent of x.
1474
+ We guarantee that result.argument.as_coeff_mul(x) returns (a, (x**b,))
1475
+ or (a, ()).
1476
+ Returns a list of tuples (C, s, G) and a condition cond.
1477
+ Returns None on failure.
1478
+ """
1479
+ from .transforms import (mellin_transform, inverse_mellin_transform,
1480
+ IntegralTransformError, MellinTransformStripError)
1481
+
1482
+ global _lookup_table
1483
+ if not _lookup_table:
1484
+ _lookup_table = {}
1485
+ _create_lookup_table(_lookup_table)
1486
+
1487
+ if isinstance(f, meijerg):
1488
+ coeff, m = factor(f.argument, x).as_coeff_mul(x)
1489
+ if len(m) > 1:
1490
+ return None
1491
+ m = m[0]
1492
+ if m.is_Pow:
1493
+ if m.base != x or not m.exp.is_Rational:
1494
+ return None
1495
+ elif m != x:
1496
+ return None
1497
+ return [(1, 0, meijerg(f.an, f.aother, f.bm, f.bother, coeff*m))], True
1498
+
1499
+ f_ = f
1500
+ f = f.subs(x, z)
1501
+ t = _mytype(f, z)
1502
+ if t in _lookup_table:
1503
+ l = _lookup_table[t]
1504
+ for formula, terms, cond, hint in l:
1505
+ subs = f.match(formula, old=True)
1506
+ if subs:
1507
+ subs_ = {}
1508
+ for fro, to in subs.items():
1509
+ subs_[fro] = unpolarify(polarify(to, lift=True),
1510
+ exponents_only=True)
1511
+ subs = subs_
1512
+ if not isinstance(hint, bool):
1513
+ hint = hint.subs(subs)
1514
+ if hint == False:
1515
+ continue
1516
+ if not isinstance(cond, (bool, BooleanAtom)):
1517
+ cond = unpolarify(cond.subs(subs))
1518
+ if _eval_cond(cond) == False:
1519
+ continue
1520
+ if not isinstance(terms, list):
1521
+ terms = terms(subs)
1522
+ res = []
1523
+ for fac, g in terms:
1524
+ r1 = _get_coeff_exp(unpolarify(fac.subs(subs).subs(z, x),
1525
+ exponents_only=True), x)
1526
+ try:
1527
+ g = g.subs(subs).subs(z, x)
1528
+ except ValueError:
1529
+ continue
1530
+ # NOTE these substitutions can in principle introduce oo,
1531
+ # zoo and other absurdities. It shouldn't matter,
1532
+ # but better be safe.
1533
+ if Tuple(*(r1 + (g,))).has(S.Infinity, S.ComplexInfinity, S.NegativeInfinity):
1534
+ continue
1535
+ g = meijerg(g.an, g.aother, g.bm, g.bother,
1536
+ unpolarify(g.argument, exponents_only=True))
1537
+ res.append(r1 + (g,))
1538
+ if res:
1539
+ return res, cond
1540
+
1541
+ # try recursive mellin transform
1542
+ if not recursive:
1543
+ return None
1544
+ _debug('Trying recursive Mellin transform method.')
1545
+
1546
+ def my_imt(F, s, x, strip):
1547
+ """ Calling simplify() all the time is slow and not helpful, since
1548
+ most of the time it only factors things in a way that has to be
1549
+ un-done anyway. But sometimes it can remove apparent poles. """
1550
+ # XXX should this be in inverse_mellin_transform?
1551
+ try:
1552
+ return inverse_mellin_transform(F, s, x, strip,
1553
+ as_meijerg=True, needeval=True)
1554
+ except MellinTransformStripError:
1555
+ from sympy.simplify import simplify
1556
+ return inverse_mellin_transform(
1557
+ simplify(cancel(expand(F))), s, x, strip,
1558
+ as_meijerg=True, needeval=True)
1559
+ f = f_
1560
+ s = _dummy('s', 'rewrite-single', f)
1561
+ # to avoid infinite recursion, we have to force the two g functions case
1562
+
1563
+ def my_integrator(f, x):
1564
+ r = _meijerint_definite_4(f, x, only_double=True)
1565
+ if r is not None:
1566
+ from sympy.simplify import hyperexpand
1567
+ res, cond = r
1568
+ res = _my_unpolarify(hyperexpand(res, rewrite='nonrepsmall'))
1569
+ return Piecewise((res, cond),
1570
+ (Integral(f, (x, S.Zero, S.Infinity)), True))
1571
+ return Integral(f, (x, S.Zero, S.Infinity))
1572
+ try:
1573
+ F, strip, _ = mellin_transform(f, x, s, integrator=my_integrator,
1574
+ simplify=False, needeval=True)
1575
+ g = my_imt(F, s, x, strip)
1576
+ except IntegralTransformError:
1577
+ g = None
1578
+ if g is None:
1579
+ # We try to find an expression by analytic continuation.
1580
+ # (also if the dummy is already in the expression, there is no point in
1581
+ # putting in another one)
1582
+ a = _dummy_('a', 'rewrite-single')
1583
+ if a not in f.free_symbols and _is_analytic(f, x):
1584
+ try:
1585
+ F, strip, _ = mellin_transform(f.subs(x, a*x), x, s,
1586
+ integrator=my_integrator,
1587
+ needeval=True, simplify=False)
1588
+ g = my_imt(F, s, x, strip).subs(a, 1)
1589
+ except IntegralTransformError:
1590
+ g = None
1591
+ if g is None or g.has(S.Infinity, S.NaN, S.ComplexInfinity):
1592
+ _debug('Recursive Mellin transform failed.')
1593
+ return None
1594
+ args = Add.make_args(g)
1595
+ res = []
1596
+ for f in args:
1597
+ c, m = f.as_coeff_mul(x)
1598
+ if len(m) > 1:
1599
+ raise NotImplementedError('Unexpected form...')
1600
+ g = m[0]
1601
+ a, b = _get_coeff_exp(g.argument, x)
1602
+ res += [(c, 0, meijerg(g.an, g.aother, g.bm, g.bother,
1603
+ unpolarify(polarify(
1604
+ a, lift=True), exponents_only=True)
1605
+ *x**b))]
1606
+ _debug('Recursive Mellin transform worked:', g)
1607
+ return res, True
1608
+
1609
+
1610
+ def _rewrite1(f, x, recursive=True):
1611
+ """
1612
+ Try to rewrite ``f`` using a (sum of) single G functions with argument a*x**b.
1613
+ Return fac, po, g such that f = fac*po*g, fac is independent of ``x``.
1614
+ and po = x**s.
1615
+ Here g is a result from _rewrite_single.
1616
+ Return None on failure.
1617
+ """
1618
+ fac, po, g = _split_mul(f, x)
1619
+ g = _rewrite_single(g, x, recursive)
1620
+ if g:
1621
+ return fac, po, g[0], g[1]
1622
+
1623
+
1624
+ def _rewrite2(f, x):
1625
+ """
1626
+ Try to rewrite ``f`` as a product of two G functions of arguments a*x**b.
1627
+ Return fac, po, g1, g2 such that f = fac*po*g1*g2, where fac is
1628
+ independent of x and po is x**s.
1629
+ Here g1 and g2 are results of _rewrite_single.
1630
+ Returns None on failure.
1631
+ """
1632
+ fac, po, g = _split_mul(f, x)
1633
+ if any(_rewrite_single(expr, x, False) is None for expr in _mul_args(g)):
1634
+ return None
1635
+ l = _mul_as_two_parts(g)
1636
+ if not l:
1637
+ return None
1638
+ l = list(ordered(l, [
1639
+ lambda p: max(len(_exponents(p[0], x)), len(_exponents(p[1], x))),
1640
+ lambda p: max(len(_functions(p[0], x)), len(_functions(p[1], x))),
1641
+ lambda p: max(len(_find_splitting_points(p[0], x)),
1642
+ len(_find_splitting_points(p[1], x)))]))
1643
+
1644
+ for recursive, (fac1, fac2) in itertools.product((False, True), l):
1645
+ g1 = _rewrite_single(fac1, x, recursive)
1646
+ g2 = _rewrite_single(fac2, x, recursive)
1647
+ if g1 and g2:
1648
+ cond = And(g1[1], g2[1])
1649
+ if cond != False:
1650
+ return fac, po, g1[0], g2[0], cond
1651
+
1652
+
1653
+ def meijerint_indefinite(f, x):
1654
+ """
1655
+ Compute an indefinite integral of ``f`` by rewriting it as a G function.
1656
+
1657
+ Examples
1658
+ ========
1659
+
1660
+ >>> from sympy.integrals.meijerint import meijerint_indefinite
1661
+ >>> from sympy import sin
1662
+ >>> from sympy.abc import x
1663
+ >>> meijerint_indefinite(sin(x), x)
1664
+ -cos(x)
1665
+ """
1666
+ f = sympify(f)
1667
+ results = []
1668
+ for a in sorted(_find_splitting_points(f, x) | {S.Zero}, key=default_sort_key):
1669
+ res = _meijerint_indefinite_1(f.subs(x, x + a), x)
1670
+ if not res:
1671
+ continue
1672
+ res = res.subs(x, x - a)
1673
+ if _has(res, hyper, meijerg):
1674
+ results.append(res)
1675
+ else:
1676
+ return res
1677
+ if f.has(HyperbolicFunction):
1678
+ _debug('Try rewriting hyperbolics in terms of exp.')
1679
+ rv = meijerint_indefinite(
1680
+ _rewrite_hyperbolics_as_exp(f), x)
1681
+ if rv:
1682
+ if not isinstance(rv, list):
1683
+ from sympy.simplify.radsimp import collect
1684
+ return collect(factor_terms(rv), rv.atoms(exp))
1685
+ results.extend(rv)
1686
+ if results:
1687
+ return next(ordered(results))
1688
+
1689
+
1690
+ def _meijerint_indefinite_1(f, x):
1691
+ """ Helper that does not attempt any substitution. """
1692
+ _debug('Trying to compute the indefinite integral of', f, 'wrt', x)
1693
+ from sympy.simplify import hyperexpand, powdenest
1694
+
1695
+ gs = _rewrite1(f, x)
1696
+ if gs is None:
1697
+ # Note: the code that calls us will do expand() and try again
1698
+ return None
1699
+
1700
+ fac, po, gl, cond = gs
1701
+ _debug(' could rewrite:', gs)
1702
+ res = S.Zero
1703
+ for C, s, g in gl:
1704
+ a, b = _get_coeff_exp(g.argument, x)
1705
+ _, c = _get_coeff_exp(po, x)
1706
+ c += s
1707
+
1708
+ # we do a substitution t=a*x**b, get integrand fac*t**rho*g
1709
+ fac_ = fac * C * x**(1 + c) / b
1710
+ rho = (c + 1)/b
1711
+
1712
+ # we now use t**rho*G(params, t) = G(params + rho, t)
1713
+ # [L, page 150, equation (4)]
1714
+ # and integral G(params, t) dt = G(1, params+1, 0, t)
1715
+ # (or a similar expression with 1 and 0 exchanged ... pick the one
1716
+ # which yields a well-defined function)
1717
+ # [R, section 5]
1718
+ # (Note that this dummy will immediately go away again, so we
1719
+ # can safely pass S.One for ``expr``.)
1720
+ t = _dummy('t', 'meijerint-indefinite', S.One)
1721
+
1722
+ def tr(p):
1723
+ return [a + rho for a in p]
1724
+ if any(b.is_integer and (b <= 0) == True for b in tr(g.bm)):
1725
+ r = -meijerg(
1726
+ list(g.an), list(g.aother) + [1-rho], list(g.bm) + [-rho], list(g.bother), t)
1727
+ else:
1728
+ r = meijerg(
1729
+ list(g.an) + [1-rho], list(g.aother), list(g.bm), list(g.bother) + [-rho], t)
1730
+ # The antiderivative is most often expected to be defined
1731
+ # in the neighborhood of x = 0.
1732
+ if b.is_extended_nonnegative and not f.subs(x, 0).has(S.NaN, S.ComplexInfinity):
1733
+ place = 0 # Assume we can expand at zero
1734
+ else:
1735
+ place = None
1736
+ r = hyperexpand(r.subs(t, a*x**b), place=place)
1737
+
1738
+ # now substitute back
1739
+ # Note: we really do want the powers of x to combine.
1740
+ res += powdenest(fac_*r, polar=True)
1741
+
1742
+ def _clean(res):
1743
+ """This multiplies out superfluous powers of x we created, and chops off
1744
+ constants:
1745
+
1746
+ >> _clean(x*(exp(x)/x - 1/x) + 3)
1747
+ exp(x)
1748
+
1749
+ cancel is used before mul_expand since it is possible for an
1750
+ expression to have an additive constant that does not become isolated
1751
+ with simple expansion. Such a situation was identified in issue 6369:
1752
+
1753
+ Examples
1754
+ ========
1755
+
1756
+ >>> from sympy import sqrt, cancel
1757
+ >>> from sympy.abc import x
1758
+ >>> a = sqrt(2*x + 1)
1759
+ >>> bad = (3*x*a**5 + 2*x - a**5 + 1)/a**2
1760
+ >>> bad.expand().as_independent(x)[0]
1761
+ 0
1762
+ >>> cancel(bad).expand().as_independent(x)[0]
1763
+ 1
1764
+ """
1765
+ res = expand_mul(cancel(res), deep=False)
1766
+ return Add._from_args(res.as_coeff_add(x)[1])
1767
+
1768
+ res = piecewise_fold(res, evaluate=None)
1769
+ if res.is_Piecewise:
1770
+ newargs = []
1771
+ for e, c in res.args:
1772
+ e = _my_unpolarify(_clean(e))
1773
+ newargs += [(e, c)]
1774
+ res = Piecewise(*newargs, evaluate=False)
1775
+ else:
1776
+ res = _my_unpolarify(_clean(res))
1777
+ return Piecewise((res, _my_unpolarify(cond)), (Integral(f, x), True))
1778
+
1779
+
1780
+ @timeit
1781
+ def meijerint_definite(f, x, a, b):
1782
+ """
1783
+ Integrate ``f`` over the interval [``a``, ``b``], by rewriting it as a product
1784
+ of two G functions, or as a single G function.
1785
+
1786
+ Return res, cond, where cond are convergence conditions.
1787
+
1788
+ Examples
1789
+ ========
1790
+
1791
+ >>> from sympy.integrals.meijerint import meijerint_definite
1792
+ >>> from sympy import exp, oo
1793
+ >>> from sympy.abc import x
1794
+ >>> meijerint_definite(exp(-x**2), x, -oo, oo)
1795
+ (sqrt(pi), True)
1796
+
1797
+ This function is implemented as a succession of functions
1798
+ meijerint_definite, _meijerint_definite_2, _meijerint_definite_3,
1799
+ _meijerint_definite_4. Each function in the list calls the next one
1800
+ (presumably) several times. This means that calling meijerint_definite
1801
+ can be very costly.
1802
+ """
1803
+ # This consists of three steps:
1804
+ # 1) Change the integration limits to 0, oo
1805
+ # 2) Rewrite in terms of G functions
1806
+ # 3) Evaluate the integral
1807
+ #
1808
+ # There are usually several ways of doing this, and we want to try all.
1809
+ # This function does (1), calls _meijerint_definite_2 for step (2).
1810
+ _debugf('Integrating %s wrt %s from %s to %s.', (f, x, a, b))
1811
+ f = sympify(f)
1812
+ if f.has(DiracDelta):
1813
+ _debug('Integrand has DiracDelta terms - giving up.')
1814
+ return None
1815
+
1816
+ if f.has(SingularityFunction):
1817
+ _debug('Integrand has Singularity Function terms - giving up.')
1818
+ return None
1819
+
1820
+ f_, x_, a_, b_ = f, x, a, b
1821
+
1822
+ # Let's use a dummy in case any of the boundaries has x.
1823
+ d = Dummy('x')
1824
+ f = f.subs(x, d)
1825
+ x = d
1826
+
1827
+ if a == b:
1828
+ return (S.Zero, True)
1829
+
1830
+ results = []
1831
+ if a is S.NegativeInfinity and b is not S.Infinity:
1832
+ return meijerint_definite(f.subs(x, -x), x, -b, -a)
1833
+
1834
+ elif a is S.NegativeInfinity:
1835
+ # Integrating -oo to oo. We need to find a place to split the integral.
1836
+ _debug(' Integrating -oo to +oo.')
1837
+ innermost = _find_splitting_points(f, x)
1838
+ _debug(' Sensible splitting points:', innermost)
1839
+ for c in sorted(innermost, key=default_sort_key, reverse=True) + [S.Zero]:
1840
+ _debug(' Trying to split at', c)
1841
+ if not c.is_extended_real:
1842
+ _debug(' Non-real splitting point.')
1843
+ continue
1844
+ res1 = _meijerint_definite_2(f.subs(x, x + c), x)
1845
+ if res1 is None:
1846
+ _debug(' But could not compute first integral.')
1847
+ continue
1848
+ res2 = _meijerint_definite_2(f.subs(x, c - x), x)
1849
+ if res2 is None:
1850
+ _debug(' But could not compute second integral.')
1851
+ continue
1852
+ res1, cond1 = res1
1853
+ res2, cond2 = res2
1854
+ cond = _condsimp(And(cond1, cond2))
1855
+ if cond == False:
1856
+ _debug(' But combined condition is always false.')
1857
+ continue
1858
+ res = res1 + res2
1859
+ return res, cond
1860
+
1861
+ elif a is S.Infinity:
1862
+ res = meijerint_definite(f, x, b, S.Infinity)
1863
+ return -res[0], res[1]
1864
+
1865
+ elif (a, b) == (S.Zero, S.Infinity):
1866
+ # This is a common case - try it directly first.
1867
+ res = _meijerint_definite_2(f, x)
1868
+ if res:
1869
+ if _has(res[0], meijerg):
1870
+ results.append(res)
1871
+ else:
1872
+ return res
1873
+
1874
+ else:
1875
+ if b is S.Infinity:
1876
+ for split in _find_splitting_points(f, x):
1877
+ if (a - split >= 0) == True:
1878
+ _debugf('Trying x -> x + %s', split)
1879
+ res = _meijerint_definite_2(f.subs(x, x + split)
1880
+ *Heaviside(x + split - a), x)
1881
+ if res:
1882
+ if _has(res[0], meijerg):
1883
+ results.append(res)
1884
+ else:
1885
+ return res
1886
+
1887
+ f = f.subs(x, x + a)
1888
+ b = b - a
1889
+ a = 0
1890
+ if b is not S.Infinity:
1891
+ phi = exp(S.ImaginaryUnit*arg(b))
1892
+ b = Abs(b)
1893
+ f = f.subs(x, phi*x)
1894
+ f *= Heaviside(b - x)*phi
1895
+ b = S.Infinity
1896
+
1897
+ _debug('Changed limits to', a, b)
1898
+ _debug('Changed function to', f)
1899
+ res = _meijerint_definite_2(f, x)
1900
+ if res:
1901
+ if _has(res[0], meijerg):
1902
+ results.append(res)
1903
+ else:
1904
+ return res
1905
+ if f_.has(HyperbolicFunction):
1906
+ _debug('Try rewriting hyperbolics in terms of exp.')
1907
+ rv = meijerint_definite(
1908
+ _rewrite_hyperbolics_as_exp(f_), x_, a_, b_)
1909
+ if rv:
1910
+ if not isinstance(rv, list):
1911
+ from sympy.simplify.radsimp import collect
1912
+ rv = (collect(factor_terms(rv[0]), rv[0].atoms(exp)),) + rv[1:]
1913
+ return rv
1914
+ results.extend(rv)
1915
+ if results:
1916
+ return next(ordered(results))
1917
+
1918
+
1919
+ def _guess_expansion(f, x):
1920
+ """ Try to guess sensible rewritings for integrand f(x). """
1921
+ res = [(f, 'original integrand')]
1922
+
1923
+ orig = res[-1][0]
1924
+ saw = {orig}
1925
+ expanded = expand_mul(orig)
1926
+ if expanded not in saw:
1927
+ res += [(expanded, 'expand_mul')]
1928
+ saw.add(expanded)
1929
+
1930
+ expanded = expand(orig)
1931
+ if expanded not in saw:
1932
+ res += [(expanded, 'expand')]
1933
+ saw.add(expanded)
1934
+
1935
+ if orig.has(TrigonometricFunction, HyperbolicFunction):
1936
+ expanded = expand_mul(expand_trig(orig))
1937
+ if expanded not in saw:
1938
+ res += [(expanded, 'expand_trig, expand_mul')]
1939
+ saw.add(expanded)
1940
+
1941
+ if orig.has(cos, sin):
1942
+ from sympy.simplify.fu import sincos_to_sum
1943
+ reduced = sincos_to_sum(orig)
1944
+ if reduced not in saw:
1945
+ res += [(reduced, 'trig power reduction')]
1946
+ saw.add(reduced)
1947
+
1948
+ return res
1949
+
1950
+
1951
+ def _meijerint_definite_2(f, x):
1952
+ """
1953
+ Try to integrate f dx from zero to infinity.
1954
+
1955
+ The body of this function computes various 'simplifications'
1956
+ f1, f2, ... of f (e.g. by calling expand_mul(), trigexpand()
1957
+ - see _guess_expansion) and calls _meijerint_definite_3 with each of
1958
+ these in succession.
1959
+ If _meijerint_definite_3 succeeds with any of the simplified functions,
1960
+ returns this result.
1961
+ """
1962
+ # This function does preparation for (2), calls
1963
+ # _meijerint_definite_3 for (2) and (3) combined.
1964
+
1965
+ # use a positive dummy - we integrate from 0 to oo
1966
+ # XXX if a nonnegative symbol is used there will be test failures
1967
+ dummy = _dummy('x', 'meijerint-definite2', f, positive=True)
1968
+ f = f.subs(x, dummy)
1969
+ x = dummy
1970
+
1971
+ if f == 0:
1972
+ return S.Zero, True
1973
+
1974
+ for g, explanation in _guess_expansion(f, x):
1975
+ _debug('Trying', explanation)
1976
+ res = _meijerint_definite_3(g, x)
1977
+ if res:
1978
+ return res
1979
+
1980
+
1981
+ def _meijerint_definite_3(f, x):
1982
+ """
1983
+ Try to integrate f dx from zero to infinity.
1984
+
1985
+ This function calls _meijerint_definite_4 to try to compute the
1986
+ integral. If this fails, it tries using linearity.
1987
+ """
1988
+ res = _meijerint_definite_4(f, x)
1989
+ if res and res[1] != False:
1990
+ return res
1991
+ if f.is_Add:
1992
+ _debug('Expanding and evaluating all terms.')
1993
+ ress = [_meijerint_definite_4(g, x) for g in f.args]
1994
+ if all(r is not None for r in ress):
1995
+ conds = []
1996
+ res = S.Zero
1997
+ for r, c in ress:
1998
+ res += r
1999
+ conds += [c]
2000
+ c = And(*conds)
2001
+ if c != False:
2002
+ return res, c
2003
+
2004
+
2005
+ def _my_unpolarify(f):
2006
+ return _eval_cond(unpolarify(f))
2007
+
2008
+
2009
+ @timeit
2010
+ def _meijerint_definite_4(f, x, only_double=False):
2011
+ """
2012
+ Try to integrate f dx from zero to infinity.
2013
+
2014
+ Explanation
2015
+ ===========
2016
+
2017
+ This function tries to apply the integration theorems found in literature,
2018
+ i.e. it tries to rewrite f as either one or a product of two G-functions.
2019
+
2020
+ The parameter ``only_double`` is used internally in the recursive algorithm
2021
+ to disable trying to rewrite f as a single G-function.
2022
+ """
2023
+ from sympy.simplify import hyperexpand
2024
+ # This function does (2) and (3)
2025
+ _debug('Integrating', f)
2026
+ # Try single G function.
2027
+ if not only_double:
2028
+ gs = _rewrite1(f, x, recursive=False)
2029
+ if gs is not None:
2030
+ fac, po, g, cond = gs
2031
+ _debug('Could rewrite as single G function:', fac, po, g)
2032
+ res = S.Zero
2033
+ for C, s, f in g:
2034
+ if C == 0:
2035
+ continue
2036
+ C, f = _rewrite_saxena_1(fac*C, po*x**s, f, x)
2037
+ res += C*_int0oo_1(f, x)
2038
+ cond = And(cond, _check_antecedents_1(f, x))
2039
+ if cond == False:
2040
+ break
2041
+ cond = _my_unpolarify(cond)
2042
+ if cond == False:
2043
+ _debug('But cond is always False.')
2044
+ else:
2045
+ _debug('Result before branch substitutions is:', res)
2046
+ return _my_unpolarify(hyperexpand(res)), cond
2047
+
2048
+ # Try two G functions.
2049
+ gs = _rewrite2(f, x)
2050
+ if gs is not None:
2051
+ for full_pb in [False, True]:
2052
+ fac, po, g1, g2, cond = gs
2053
+ _debug('Could rewrite as two G functions:', fac, po, g1, g2)
2054
+ res = S.Zero
2055
+ for C1, s1, f1 in g1:
2056
+ for C2, s2, f2 in g2:
2057
+ r = _rewrite_saxena(fac*C1*C2, po*x**(s1 + s2),
2058
+ f1, f2, x, full_pb)
2059
+ if r is None:
2060
+ _debug('Non-rational exponents.')
2061
+ return
2062
+ C, f1_, f2_ = r
2063
+ _debug('Saxena subst for yielded:', C, f1_, f2_)
2064
+ cond = And(cond, _check_antecedents(f1_, f2_, x))
2065
+ if cond == False:
2066
+ break
2067
+ res += C*_int0oo(f1_, f2_, x)
2068
+ else:
2069
+ continue
2070
+ break
2071
+ cond = _my_unpolarify(cond)
2072
+ if cond == False:
2073
+ _debugf('But cond is always False (full_pb=%s).', full_pb)
2074
+ else:
2075
+ _debugf('Result before branch substitutions is: %s', (res, ))
2076
+ if only_double:
2077
+ return res, cond
2078
+ return _my_unpolarify(hyperexpand(res)), cond
2079
+
2080
+
2081
+ def meijerint_inversion(f, x, t):
2082
+ r"""
2083
+ Compute the inverse laplace transform
2084
+ $\int_{c+i\infty}^{c-i\infty} f(x) e^{tx}\, dx$,
2085
+ for real c larger than the real part of all singularities of ``f``.
2086
+
2087
+ Note that ``t`` is always assumed real and positive.
2088
+
2089
+ Return None if the integral does not exist or could not be evaluated.
2090
+
2091
+ Examples
2092
+ ========
2093
+
2094
+ >>> from sympy.abc import x, t
2095
+ >>> from sympy.integrals.meijerint import meijerint_inversion
2096
+ >>> meijerint_inversion(1/x, x, t)
2097
+ Heaviside(t)
2098
+ """
2099
+ f_ = f
2100
+ t_ = t
2101
+ t = Dummy('t', polar=True) # We don't want sqrt(t**2) = abs(t) etc
2102
+ f = f.subs(t_, t)
2103
+ _debug('Laplace-inverting', f)
2104
+ if not _is_analytic(f, x):
2105
+ _debug('But expression is not analytic.')
2106
+ return None
2107
+ # Exponentials correspond to shifts; we filter them out and then
2108
+ # shift the result later. If we are given an Add this will not
2109
+ # work, but the calling code will take care of that.
2110
+ shift = S.Zero
2111
+
2112
+ if f.is_Mul:
2113
+ args = list(f.args)
2114
+ elif isinstance(f, exp):
2115
+ args = [f]
2116
+ else:
2117
+ args = None
2118
+
2119
+ if args:
2120
+ newargs = []
2121
+ exponentials = []
2122
+ while args:
2123
+ arg = args.pop()
2124
+ if isinstance(arg, exp):
2125
+ arg2 = expand(arg)
2126
+ if arg2.is_Mul:
2127
+ args += arg2.args
2128
+ continue
2129
+ try:
2130
+ a, b = _get_coeff_exp(arg.args[0], x)
2131
+ except _CoeffExpValueError:
2132
+ b = 0
2133
+ if b == 1:
2134
+ exponentials.append(a)
2135
+ else:
2136
+ newargs.append(arg)
2137
+ elif arg.is_Pow:
2138
+ arg2 = expand(arg)
2139
+ if arg2.is_Mul:
2140
+ args += arg2.args
2141
+ continue
2142
+ if x not in arg.base.free_symbols:
2143
+ try:
2144
+ a, b = _get_coeff_exp(arg.exp, x)
2145
+ except _CoeffExpValueError:
2146
+ b = 0
2147
+ if b == 1:
2148
+ exponentials.append(a*log(arg.base))
2149
+ newargs.append(arg)
2150
+ else:
2151
+ newargs.append(arg)
2152
+ shift = Add(*exponentials)
2153
+ f = Mul(*newargs)
2154
+
2155
+ if x not in f.free_symbols:
2156
+ _debug('Expression consists of constant and exp shift:', f, shift)
2157
+ cond = Eq(im(shift), 0)
2158
+ if cond == False:
2159
+ _debug('but shift is nonreal, cannot be a Laplace transform')
2160
+ return None
2161
+ res = f*DiracDelta(t + shift)
2162
+ _debug('Result is a delta function, possibly conditional:', res, cond)
2163
+ # cond is True or Eq
2164
+ return Piecewise((res.subs(t, t_), cond))
2165
+
2166
+ gs = _rewrite1(f, x)
2167
+ if gs is not None:
2168
+ fac, po, g, cond = gs
2169
+ _debug('Could rewrite as single G function:', fac, po, g)
2170
+ res = S.Zero
2171
+ for C, s, f in g:
2172
+ C, f = _rewrite_inversion(fac*C, po*x**s, f, x)
2173
+ res += C*_int_inversion(f, x, t)
2174
+ cond = And(cond, _check_antecedents_inversion(f, x))
2175
+ if cond == False:
2176
+ break
2177
+ cond = _my_unpolarify(cond)
2178
+ if cond == False:
2179
+ _debug('But cond is always False.')
2180
+ else:
2181
+ _debug('Result before branch substitution:', res)
2182
+ from sympy.simplify import hyperexpand
2183
+ res = _my_unpolarify(hyperexpand(res))
2184
+ if not res.has(Heaviside):
2185
+ res *= Heaviside(t)
2186
+ res = res.subs(t, t + shift)
2187
+ if not isinstance(cond, bool):
2188
+ cond = cond.subs(t, t + shift)
2189
+ from .transforms import InverseLaplaceTransform
2190
+ return Piecewise((res.subs(t, t_), cond),
2191
+ (InverseLaplaceTransform(f_.subs(t, t_), x, t_, None), True))
parrot/lib/python3.10/site-packages/sympy/integrals/rationaltools.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module implements tools for integrating rational functions. """
2
+
3
+ from sympy.core.function import Lambda
4
+ from sympy.core.numbers import I
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import (Dummy, Symbol, symbols)
7
+ from sympy.functions.elementary.exponential import log
8
+ from sympy.functions.elementary.trigonometric import atan
9
+ from sympy.polys.polyroots import roots
10
+ from sympy.polys.polytools import cancel
11
+ from sympy.polys.rootoftools import RootSum
12
+ from sympy.polys import Poly, resultant, ZZ
13
+
14
+
15
+ def ratint(f, x, **flags):
16
+ """
17
+ Performs indefinite integration of rational functions.
18
+
19
+ Explanation
20
+ ===========
21
+
22
+ Given a field :math:`K` and a rational function :math:`f = p/q`,
23
+ where :math:`p` and :math:`q` are polynomials in :math:`K[x]`,
24
+ returns a function :math:`g` such that :math:`f = g'`.
25
+
26
+ Examples
27
+ ========
28
+
29
+ >>> from sympy.integrals.rationaltools import ratint
30
+ >>> from sympy.abc import x
31
+
32
+ >>> ratint(36/(x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2), x)
33
+ (12*x + 6)/(x**2 - 1) + 4*log(x - 2) - 4*log(x + 1)
34
+
35
+ References
36
+ ==========
37
+
38
+ .. [1] M. Bronstein, Symbolic Integration I: Transcendental
39
+ Functions, Second Edition, Springer-Verlag, 2005, pp. 35-70
40
+
41
+ See Also
42
+ ========
43
+
44
+ sympy.integrals.integrals.Integral.doit
45
+ sympy.integrals.rationaltools.ratint_logpart
46
+ sympy.integrals.rationaltools.ratint_ratpart
47
+
48
+ """
49
+ if isinstance(f, tuple):
50
+ p, q = f
51
+ else:
52
+ p, q = f.as_numer_denom()
53
+
54
+ p, q = Poly(p, x, composite=False, field=True), Poly(q, x, composite=False, field=True)
55
+
56
+ coeff, p, q = p.cancel(q)
57
+ poly, p = p.div(q)
58
+
59
+ result = poly.integrate(x).as_expr()
60
+
61
+ if p.is_zero:
62
+ return coeff*result
63
+
64
+ g, h = ratint_ratpart(p, q, x)
65
+
66
+ P, Q = h.as_numer_denom()
67
+
68
+ P = Poly(P, x)
69
+ Q = Poly(Q, x)
70
+
71
+ q, r = P.div(Q)
72
+
73
+ result += g + q.integrate(x).as_expr()
74
+
75
+ if not r.is_zero:
76
+ symbol = flags.get('symbol', 't')
77
+
78
+ if not isinstance(symbol, Symbol):
79
+ t = Dummy(symbol)
80
+ else:
81
+ t = symbol.as_dummy()
82
+
83
+ L = ratint_logpart(r, Q, x, t)
84
+
85
+ real = flags.get('real')
86
+
87
+ if real is None:
88
+ if isinstance(f, tuple):
89
+ p, q = f
90
+ atoms = p.atoms() | q.atoms()
91
+ else:
92
+ atoms = f.atoms()
93
+
94
+ for elt in atoms - {x}:
95
+ if not elt.is_extended_real:
96
+ real = False
97
+ break
98
+ else:
99
+ real = True
100
+
101
+ eps = S.Zero
102
+
103
+ if not real:
104
+ for h, q in L:
105
+ _, h = h.primitive()
106
+ eps += RootSum(
107
+ q, Lambda(t, t*log(h.as_expr())), quadratic=True)
108
+ else:
109
+ for h, q in L:
110
+ _, h = h.primitive()
111
+ R = log_to_real(h, q, x, t)
112
+
113
+ if R is not None:
114
+ eps += R
115
+ else:
116
+ eps += RootSum(
117
+ q, Lambda(t, t*log(h.as_expr())), quadratic=True)
118
+
119
+ result += eps
120
+
121
+ return coeff*result
122
+
123
+
124
+ def ratint_ratpart(f, g, x):
125
+ """
126
+ Horowitz-Ostrogradsky algorithm.
127
+
128
+ Explanation
129
+ ===========
130
+
131
+ Given a field K and polynomials f and g in K[x], such that f and g
132
+ are coprime and deg(f) < deg(g), returns fractions A and B in K(x),
133
+ such that f/g = A' + B and B has square-free denominator.
134
+
135
+ Examples
136
+ ========
137
+
138
+ >>> from sympy.integrals.rationaltools import ratint_ratpart
139
+ >>> from sympy.abc import x, y
140
+ >>> from sympy import Poly
141
+ >>> ratint_ratpart(Poly(1, x, domain='ZZ'),
142
+ ... Poly(x + 1, x, domain='ZZ'), x)
143
+ (0, 1/(x + 1))
144
+ >>> ratint_ratpart(Poly(1, x, domain='EX'),
145
+ ... Poly(x**2 + y**2, x, domain='EX'), x)
146
+ (0, 1/(x**2 + y**2))
147
+ >>> ratint_ratpart(Poly(36, x, domain='ZZ'),
148
+ ... Poly(x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2, x, domain='ZZ'), x)
149
+ ((12*x + 6)/(x**2 - 1), 12/(x**2 - x - 2))
150
+
151
+ See Also
152
+ ========
153
+
154
+ ratint, ratint_logpart
155
+ """
156
+ from sympy.solvers.solvers import solve
157
+
158
+ f = Poly(f, x)
159
+ g = Poly(g, x)
160
+
161
+ u, v, _ = g.cofactors(g.diff())
162
+
163
+ n = u.degree()
164
+ m = v.degree()
165
+
166
+ A_coeffs = [ Dummy('a' + str(n - i)) for i in range(0, n) ]
167
+ B_coeffs = [ Dummy('b' + str(m - i)) for i in range(0, m) ]
168
+
169
+ C_coeffs = A_coeffs + B_coeffs
170
+
171
+ A = Poly(A_coeffs, x, domain=ZZ[C_coeffs])
172
+ B = Poly(B_coeffs, x, domain=ZZ[C_coeffs])
173
+
174
+ H = f - A.diff()*v + A*(u.diff()*v).quo(u) - B*u
175
+
176
+ result = solve(H.coeffs(), C_coeffs)
177
+
178
+ A = A.as_expr().subs(result)
179
+ B = B.as_expr().subs(result)
180
+
181
+ rat_part = cancel(A/u.as_expr(), x)
182
+ log_part = cancel(B/v.as_expr(), x)
183
+
184
+ return rat_part, log_part
185
+
186
+
187
+ def ratint_logpart(f, g, x, t=None):
188
+ r"""
189
+ Lazard-Rioboo-Trager algorithm.
190
+
191
+ Explanation
192
+ ===========
193
+
194
+ Given a field K and polynomials f and g in K[x], such that f and g
195
+ are coprime, deg(f) < deg(g) and g is square-free, returns a list
196
+ of tuples (s_i, q_i) of polynomials, for i = 1..n, such that s_i
197
+ in K[t, x] and q_i in K[t], and::
198
+
199
+ ___ ___
200
+ d f d \ ` \ `
201
+ -- - = -- ) ) a log(s_i(a, x))
202
+ dx g dx /__, /__,
203
+ i=1..n a | q_i(a) = 0
204
+
205
+ Examples
206
+ ========
207
+
208
+ >>> from sympy.integrals.rationaltools import ratint_logpart
209
+ >>> from sympy.abc import x
210
+ >>> from sympy import Poly
211
+ >>> ratint_logpart(Poly(1, x, domain='ZZ'),
212
+ ... Poly(x**2 + x + 1, x, domain='ZZ'), x)
213
+ [(Poly(x + 3*_t/2 + 1/2, x, domain='QQ[_t]'),
214
+ ...Poly(3*_t**2 + 1, _t, domain='ZZ'))]
215
+ >>> ratint_logpart(Poly(12, x, domain='ZZ'),
216
+ ... Poly(x**2 - x - 2, x, domain='ZZ'), x)
217
+ [(Poly(x - 3*_t/8 - 1/2, x, domain='QQ[_t]'),
218
+ ...Poly(-_t**2 + 16, _t, domain='ZZ'))]
219
+
220
+ See Also
221
+ ========
222
+
223
+ ratint, ratint_ratpart
224
+ """
225
+ f, g = Poly(f, x), Poly(g, x)
226
+
227
+ t = t or Dummy('t')
228
+ a, b = g, f - g.diff()*Poly(t, x)
229
+
230
+ res, R = resultant(a, b, includePRS=True)
231
+ res = Poly(res, t, composite=False)
232
+
233
+ assert res, "BUG: resultant(%s, %s) cannot be zero" % (a, b)
234
+
235
+ R_map, H = {}, []
236
+
237
+ for r in R:
238
+ R_map[r.degree()] = r
239
+
240
+ def _include_sign(c, sqf):
241
+ if c.is_extended_real and (c < 0) == True:
242
+ h, k = sqf[0]
243
+ c_poly = c.as_poly(h.gens)
244
+ sqf[0] = h*c_poly, k
245
+
246
+ C, res_sqf = res.sqf_list()
247
+ _include_sign(C, res_sqf)
248
+
249
+ for q, i in res_sqf:
250
+ _, q = q.primitive()
251
+
252
+ if g.degree() == i:
253
+ H.append((g, q))
254
+ else:
255
+ h = R_map[i]
256
+ h_lc = Poly(h.LC(), t, field=True)
257
+
258
+ c, h_lc_sqf = h_lc.sqf_list(all=True)
259
+ _include_sign(c, h_lc_sqf)
260
+
261
+ for a, j in h_lc_sqf:
262
+ h = h.quo(Poly(a.gcd(q)**j, x))
263
+
264
+ inv, coeffs = h_lc.invert(q), [S.One]
265
+
266
+ for coeff in h.coeffs()[1:]:
267
+ coeff = coeff.as_poly(inv.gens)
268
+ T = (inv*coeff).rem(q)
269
+ coeffs.append(T.as_expr())
270
+
271
+ h = Poly(dict(list(zip(h.monoms(), coeffs))), x)
272
+
273
+ H.append((h, q))
274
+
275
+ return H
276
+
277
+
278
+ def log_to_atan(f, g):
279
+ """
280
+ Convert complex logarithms to real arctangents.
281
+
282
+ Explanation
283
+ ===========
284
+
285
+ Given a real field K and polynomials f and g in K[x], with g != 0,
286
+ returns a sum h of arctangents of polynomials in K[x], such that:
287
+
288
+ dh d f + I g
289
+ -- = -- I log( ------- )
290
+ dx dx f - I g
291
+
292
+ Examples
293
+ ========
294
+
295
+ >>> from sympy.integrals.rationaltools import log_to_atan
296
+ >>> from sympy.abc import x
297
+ >>> from sympy import Poly, sqrt, S
298
+ >>> log_to_atan(Poly(x, x, domain='ZZ'), Poly(1, x, domain='ZZ'))
299
+ 2*atan(x)
300
+ >>> log_to_atan(Poly(x + S(1)/2, x, domain='QQ'),
301
+ ... Poly(sqrt(3)/2, x, domain='EX'))
302
+ 2*atan(2*sqrt(3)*x/3 + sqrt(3)/3)
303
+
304
+ See Also
305
+ ========
306
+
307
+ log_to_real
308
+ """
309
+ if f.degree() < g.degree():
310
+ f, g = -g, f
311
+
312
+ f = f.to_field()
313
+ g = g.to_field()
314
+
315
+ p, q = f.div(g)
316
+
317
+ if q.is_zero:
318
+ return 2*atan(p.as_expr())
319
+ else:
320
+ s, t, h = g.gcdex(-f)
321
+ u = (f*s + g*t).quo(h)
322
+ A = 2*atan(u.as_expr())
323
+
324
+ return A + log_to_atan(s, t)
325
+
326
+
327
+ def log_to_real(h, q, x, t):
328
+ r"""
329
+ Convert complex logarithms to real functions.
330
+
331
+ Explanation
332
+ ===========
333
+
334
+ Given real field K and polynomials h in K[t,x] and q in K[t],
335
+ returns real function f such that:
336
+ ___
337
+ df d \ `
338
+ -- = -- ) a log(h(a, x))
339
+ dx dx /__,
340
+ a | q(a) = 0
341
+
342
+ Examples
343
+ ========
344
+
345
+ >>> from sympy.integrals.rationaltools import log_to_real
346
+ >>> from sympy.abc import x, y
347
+ >>> from sympy import Poly, S
348
+ >>> log_to_real(Poly(x + 3*y/2 + S(1)/2, x, domain='QQ[y]'),
349
+ ... Poly(3*y**2 + 1, y, domain='ZZ'), x, y)
350
+ 2*sqrt(3)*atan(2*sqrt(3)*x/3 + sqrt(3)/3)/3
351
+ >>> log_to_real(Poly(x**2 - 1, x, domain='ZZ'),
352
+ ... Poly(-2*y + 1, y, domain='ZZ'), x, y)
353
+ log(x**2 - 1)/2
354
+
355
+ See Also
356
+ ========
357
+
358
+ log_to_atan
359
+ """
360
+ from sympy.simplify.radsimp import collect
361
+ u, v = symbols('u,v', cls=Dummy)
362
+
363
+ H = h.as_expr().xreplace({t: u + I*v}).expand()
364
+ Q = q.as_expr().xreplace({t: u + I*v}).expand()
365
+
366
+ H_map = collect(H, I, evaluate=False)
367
+ Q_map = collect(Q, I, evaluate=False)
368
+
369
+ a, b = H_map.get(S.One, S.Zero), H_map.get(I, S.Zero)
370
+ c, d = Q_map.get(S.One, S.Zero), Q_map.get(I, S.Zero)
371
+
372
+ R = Poly(resultant(c, d, v), u)
373
+
374
+ R_u = roots(R, filter='R')
375
+
376
+ if len(R_u) != R.count_roots():
377
+ return None
378
+
379
+ result = S.Zero
380
+
381
+ for r_u in R_u.keys():
382
+ C = Poly(c.xreplace({u: r_u}), v)
383
+ if not C:
384
+ # t was split into real and imaginary parts
385
+ # and denom Q(u, v) = c + I*d. We just found
386
+ # that c(r_u) is 0 so the roots are in d
387
+ C = Poly(d.xreplace({u: r_u}), v)
388
+ # we were going to reject roots from C that
389
+ # did not set d to zero, but since we are now
390
+ # using C = d and c is already 0, there is
391
+ # nothing to check
392
+ d = S.Zero
393
+
394
+ R_v = roots(C, filter='R')
395
+
396
+ if len(R_v) != C.count_roots():
397
+ return None
398
+
399
+ R_v_paired = [] # take one from each pair of conjugate roots
400
+ for r_v in R_v:
401
+ if r_v not in R_v_paired and -r_v not in R_v_paired:
402
+ if r_v.is_negative or r_v.could_extract_minus_sign():
403
+ R_v_paired.append(-r_v)
404
+ elif not r_v.is_zero:
405
+ R_v_paired.append(r_v)
406
+
407
+ for r_v in R_v_paired:
408
+
409
+ D = d.xreplace({u: r_u, v: r_v})
410
+
411
+ if D.evalf(chop=True) != 0:
412
+ continue
413
+
414
+ A = Poly(a.xreplace({u: r_u, v: r_v}), x)
415
+ B = Poly(b.xreplace({u: r_u, v: r_v}), x)
416
+
417
+ AB = (A**2 + B**2).as_expr()
418
+
419
+ result += r_u*log(AB) + r_v*log_to_atan(A, B)
420
+
421
+ R_q = roots(q, filter='R')
422
+
423
+ if len(R_q) != q.count_roots():
424
+ return None
425
+
426
+ for r in R_q.keys():
427
+ result += r*log(h.as_expr().subs(t, r))
428
+
429
+ return result
parrot/lib/python3.10/site-packages/sympy/integrals/singularityfunctions.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.functions import SingularityFunction, DiracDelta
2
+ from sympy.integrals import integrate
3
+
4
+
5
+ def singularityintegrate(f, x):
6
+ """
7
+ This function handles the indefinite integrations of Singularity functions.
8
+ The ``integrate`` function calls this function internally whenever an
9
+ instance of SingularityFunction is passed as argument.
10
+
11
+ Explanation
12
+ ===========
13
+
14
+ The idea for integration is the following:
15
+
16
+ - If we are dealing with a SingularityFunction expression,
17
+ i.e. ``SingularityFunction(x, a, n)``, we just return
18
+ ``SingularityFunction(x, a, n + 1)/(n + 1)`` if ``n >= 0`` and
19
+ ``SingularityFunction(x, a, n + 1)`` if ``n < 0``.
20
+
21
+ - If the node is a multiplication or power node having a
22
+ SingularityFunction term we rewrite the whole expression in terms of
23
+ Heaviside and DiracDelta and then integrate the output. Lastly, we
24
+ rewrite the output of integration back in terms of SingularityFunction.
25
+
26
+ - If none of the above case arises, we return None.
27
+
28
+ Examples
29
+ ========
30
+
31
+ >>> from sympy.integrals.singularityfunctions import singularityintegrate
32
+ >>> from sympy import SingularityFunction, symbols, Function
33
+ >>> x, a, n, y = symbols('x a n y')
34
+ >>> f = Function('f')
35
+ >>> singularityintegrate(SingularityFunction(x, a, 3), x)
36
+ SingularityFunction(x, a, 4)/4
37
+ >>> singularityintegrate(5*SingularityFunction(x, 5, -2), x)
38
+ 5*SingularityFunction(x, 5, -1)
39
+ >>> singularityintegrate(6*SingularityFunction(x, 5, -1), x)
40
+ 6*SingularityFunction(x, 5, 0)
41
+ >>> singularityintegrate(x*SingularityFunction(x, 0, -1), x)
42
+ 0
43
+ >>> singularityintegrate(SingularityFunction(x, 1, -1) * f(x), x)
44
+ f(1)*SingularityFunction(x, 1, 0)
45
+
46
+ """
47
+
48
+ if not f.has(SingularityFunction):
49
+ return None
50
+
51
+ if isinstance(f, SingularityFunction):
52
+ x, a, n = f.args
53
+ if n.is_positive or n.is_zero:
54
+ return SingularityFunction(x, a, n + 1)/(n + 1)
55
+ elif n in (-1, -2, -3, -4):
56
+ return SingularityFunction(x, a, n + 1)
57
+
58
+ if f.is_Mul or f.is_Pow:
59
+
60
+ expr = f.rewrite(DiracDelta)
61
+ expr = integrate(expr, x)
62
+ return expr.rewrite(SingularityFunction)
63
+ return None
parrot/lib/python3.10/site-packages/sympy/integrals/tests/__init__.py ADDED
File without changes
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_deltafunctions.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import Function
2
+ from sympy.core.numbers import (Rational, pi)
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import symbols
5
+ from sympy.functions.elementary.trigonometric import (cos, sin)
6
+ from sympy.functions.special.delta_functions import (DiracDelta, Heaviside)
7
+ from sympy.integrals.deltafunctions import change_mul, deltaintegrate
8
+
9
+ f = Function("f")
10
+ x_1, x_2, x, y, z = symbols("x_1 x_2 x y z")
11
+
12
+
13
+ def test_change_mul():
14
+ assert change_mul(x, x) == (None, None)
15
+ assert change_mul(x*y, x) == (None, None)
16
+ assert change_mul(x*y*DiracDelta(x), x) == (DiracDelta(x), x*y)
17
+ assert change_mul(x*y*DiracDelta(x)*DiracDelta(y), x) == \
18
+ (DiracDelta(x), x*y*DiracDelta(y))
19
+ assert change_mul(DiracDelta(x)**2, x) == \
20
+ (DiracDelta(x), DiracDelta(x))
21
+ assert change_mul(y*DiracDelta(x)**2, x) == \
22
+ (DiracDelta(x), y*DiracDelta(x))
23
+
24
+
25
+ def test_deltaintegrate():
26
+ assert deltaintegrate(x, x) is None
27
+ assert deltaintegrate(x + DiracDelta(x), x) is None
28
+ assert deltaintegrate(DiracDelta(x, 0), x) == Heaviside(x)
29
+ for n in range(10):
30
+ assert deltaintegrate(DiracDelta(x, n + 1), x) == DiracDelta(x, n)
31
+ assert deltaintegrate(DiracDelta(x), x) == Heaviside(x)
32
+ assert deltaintegrate(DiracDelta(-x), x) == Heaviside(x)
33
+ assert deltaintegrate(DiracDelta(x - y), x) == Heaviside(x - y)
34
+ assert deltaintegrate(DiracDelta(y - x), x) == Heaviside(x - y)
35
+
36
+ assert deltaintegrate(x*DiracDelta(x), x) == 0
37
+ assert deltaintegrate((x - y)*DiracDelta(x - y), x) == 0
38
+
39
+ assert deltaintegrate(DiracDelta(x)**2, x) == DiracDelta(0)*Heaviside(x)
40
+ assert deltaintegrate(y*DiracDelta(x)**2, x) == \
41
+ y*DiracDelta(0)*Heaviside(x)
42
+ assert deltaintegrate(DiracDelta(x, 1), x) == DiracDelta(x, 0)
43
+ assert deltaintegrate(y*DiracDelta(x, 1), x) == y*DiracDelta(x, 0)
44
+ assert deltaintegrate(DiracDelta(x, 1)**2, x) == -DiracDelta(0, 2)*Heaviside(x)
45
+ assert deltaintegrate(y*DiracDelta(x, 1)**2, x) == -y*DiracDelta(0, 2)*Heaviside(x)
46
+
47
+
48
+ assert deltaintegrate(DiracDelta(x) * f(x), x) == f(0) * Heaviside(x)
49
+ assert deltaintegrate(DiracDelta(-x) * f(x), x) == f(0) * Heaviside(x)
50
+ assert deltaintegrate(DiracDelta(x - 1) * f(x), x) == f(1) * Heaviside(x - 1)
51
+ assert deltaintegrate(DiracDelta(1 - x) * f(x), x) == f(1) * Heaviside(x - 1)
52
+ assert deltaintegrate(DiracDelta(x**2 + x - 2), x) == \
53
+ Heaviside(x - 1)/3 + Heaviside(x + 2)/3
54
+
55
+ p = cos(x)*(DiracDelta(x) + DiracDelta(x**2 - 1))*sin(x)*(x - pi)
56
+ assert deltaintegrate(p, x) - (-pi*(cos(1)*Heaviside(-1 + x)*sin(1)/2 - \
57
+ cos(1)*Heaviside(1 + x)*sin(1)/2) + \
58
+ cos(1)*Heaviside(1 + x)*sin(1)/2 + \
59
+ cos(1)*Heaviside(-1 + x)*sin(1)/2) == 0
60
+
61
+ p = x_2*DiracDelta(x - x_2)*DiracDelta(x_2 - x_1)
62
+ assert deltaintegrate(p, x_2) == x*DiracDelta(x - x_1)*Heaviside(x_2 - x)
63
+
64
+ p = x*y**2*z*DiracDelta(y - x)*DiracDelta(y - z)*DiracDelta(x - z)
65
+ assert deltaintegrate(p, y) == x**3*z*DiracDelta(x - z)**2*Heaviside(y - x)
66
+ assert deltaintegrate((x + 1)*DiracDelta(2*x), x) == S.Half * Heaviside(x)
67
+ assert deltaintegrate((x + 1)*DiracDelta(x*Rational(2, 3) + Rational(4, 9)), x) == \
68
+ S.Half * Heaviside(x + Rational(2, 3))
69
+
70
+ a, b, c = symbols('a b c', commutative=False)
71
+ assert deltaintegrate(DiracDelta(x - y)*f(x - b)*f(x - a), x) == \
72
+ f(y - b)*f(y - a)*Heaviside(x - y)
73
+
74
+ p = f(x - a)*DiracDelta(x - y)*f(x - c)*f(x - b)
75
+ assert deltaintegrate(p, x) == f(y - a)*f(y - c)*f(y - b)*Heaviside(x - y)
76
+
77
+ p = DiracDelta(x - z)*f(x - b)*f(x - a)*DiracDelta(x - y)
78
+ assert deltaintegrate(p, x) == DiracDelta(y - z)*f(y - b)*f(y - a) * \
79
+ Heaviside(x - y)
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_failing_integrals.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A collection of failing integrals from the issues.
2
+
3
+ from sympy.core.numbers import (I, Rational, oo, pi)
4
+ from sympy.core.singleton import S
5
+ from sympy.core.symbol import symbols
6
+ from sympy.functions.elementary.complexes import sign
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.hyperbolic import (sech, sinh)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.piecewise import Piecewise
11
+ from sympy.functions.elementary.trigonometric import (acos, atan, cos, sin, tan)
12
+ from sympy.functions.special.delta_functions import DiracDelta
13
+ from sympy.functions.special.gamma_functions import gamma
14
+ from sympy.integrals.integrals import (Integral, integrate)
15
+ from sympy.simplify.fu import fu
16
+
17
+
18
+ from sympy.testing.pytest import XFAIL, slow, tooslow
19
+
20
+ from sympy.abc import x, k, c, y, b, h, a, m, z, n, t
21
+
22
+
23
+ @tooslow
24
+ @XFAIL
25
+ def test_issue_3880():
26
+ # integrate_hyperexponential(Poly(t*2*(1 - t0**2)*t0*(x**3 + x**2), t), Poly((1 + t0**2)**2*2*(x**2 + x + 1), t), [Poly(1, x), Poly(1 + t0**2, t0), Poly(t, t)], [x, t0, t], [exp, tan])
27
+ assert not integrate(exp(x)*cos(2*x)*sin(2*x) * (x**3 + x**2)/(2*(x**2 + x + 1)), x).has(Integral)
28
+
29
+
30
+ def test_issue_4212_real():
31
+ xr = symbols('xr', real=True)
32
+ negabsx = Piecewise((-xr, xr < 0), (xr, True))
33
+ assert integrate(sign(xr), xr) == negabsx
34
+
35
+
36
+ @XFAIL
37
+ def test_issue_4212():
38
+ # XXX: Maybe this should be expected to fail without real assumptions on x.
39
+ # As a complex function sign(x) is not analytic and so there is no complex
40
+ # function whose complex derivative is sign(x). With real assumptions this
41
+ # works (see test_issue_4212_real above).
42
+ assert not integrate(sign(x), x).has(Integral)
43
+
44
+
45
+ def test_issue_4511():
46
+ # This works, but gives a slightly over-complicated answer.
47
+ f = integrate(cos(x)**2 / (1 - sin(x)), x)
48
+ assert fu(f) == x - cos(x) - 1
49
+ assert f == ((x*tan(x/2)**2 + x - 2)/(tan(x/2)**2 + 1)).expand()
50
+
51
+
52
+ def test_integrate_DiracDelta_no_meijerg():
53
+ assert integrate(integrate(integrate(
54
+ DiracDelta(x - y - z), (z, 0, oo)), (y, 0, 1), meijerg=False), (x, 0, 1)) == S.Half
55
+
56
+
57
+ @XFAIL
58
+ def test_integrate_DiracDelta_fails():
59
+ # issue 6427
60
+ # works without meijerg. See test_integrate_DiracDelta_no_meijerg above.
61
+ assert integrate(integrate(integrate(
62
+ DiracDelta(x - y - z), (z, 0, oo)), (y, 0, 1)), (x, 0, 1)) == S.Half
63
+
64
+
65
+ @XFAIL
66
+ @slow
67
+ def test_issue_4525():
68
+ # Warning: takes a long time
69
+ assert not integrate((x**m * (1 - x)**n * (a + b*x + c*x**2))/(1 + x**2), (x, 0, 1)).has(Integral)
70
+
71
+
72
+ @XFAIL
73
+ @tooslow
74
+ def test_issue_4540():
75
+ # Note, this integral is probably nonelementary
76
+ assert not integrate(
77
+ (sin(1/x) - x*exp(x)) /
78
+ ((-sin(1/x) + x*exp(x))*x + x*sin(1/x)), x).has(Integral)
79
+
80
+
81
+ @XFAIL
82
+ @slow
83
+ def test_issue_4891():
84
+ # Requires the hypergeometric function.
85
+ assert not integrate(cos(x)**y, x).has(Integral)
86
+
87
+
88
+ @XFAIL
89
+ @slow
90
+ def test_issue_1796a():
91
+ assert not integrate(exp(2*b*x)*exp(-a*x**2), x).has(Integral)
92
+
93
+
94
+ @XFAIL
95
+ def test_issue_4895b():
96
+ assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, -oo, 0)).has(Integral)
97
+
98
+
99
+ @XFAIL
100
+ def test_issue_4895c():
101
+ assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, -oo, oo)).has(Integral)
102
+
103
+
104
+ @XFAIL
105
+ def test_issue_4895d():
106
+ assert not integrate(exp(2*b*x)*exp(-a*x**2), (x, 0, oo)).has(Integral)
107
+
108
+
109
+ @XFAIL
110
+ @slow
111
+ def test_issue_4941():
112
+ assert not integrate(sqrt(1 + sinh(x/20)**2), (x, -25, 25)).has(Integral)
113
+
114
+
115
+ @XFAIL
116
+ def test_issue_4992():
117
+ # Nonelementary integral. Requires hypergeometric/Meijer-G handling.
118
+ assert not integrate(log(x) * x**(k - 1) * exp(-x) / gamma(k), (x, 0, oo)).has(Integral)
119
+
120
+
121
+ @XFAIL
122
+ def test_issue_16396a():
123
+ i = integrate(1/(1+sqrt(tan(x))), (x, pi/3, pi/6))
124
+ assert not i.has(Integral)
125
+
126
+
127
+ @XFAIL
128
+ def test_issue_16396b():
129
+ i = integrate(x*sin(x)/(1+cos(x)**2), (x, 0, pi))
130
+ assert not i.has(Integral)
131
+
132
+
133
+ @XFAIL
134
+ def test_issue_16046():
135
+ assert integrate(exp(exp(I*x)), [x, 0, 2*pi]) == 2*pi
136
+
137
+
138
+ @XFAIL
139
+ def test_issue_15925a():
140
+ assert not integrate(sqrt((1+sin(x))**2+(cos(x))**2), (x, -pi/2, pi/2)).has(Integral)
141
+
142
+
143
+ def test_issue_15925b():
144
+ f = sqrt((-12*cos(x)**2*sin(x))**2+(12*cos(x)*sin(x)**2)**2)
145
+ assert integrate(f, (x, 0, pi/6)) == Rational(3, 2)
146
+
147
+
148
+ @XFAIL
149
+ def test_issue_15925b_manual():
150
+ assert not integrate(sqrt((-12*cos(x)**2*sin(x))**2+(12*cos(x)*sin(x)**2)**2),
151
+ (x, 0, pi/6), manual=True).has(Integral)
152
+
153
+
154
+ @XFAIL
155
+ @tooslow
156
+ def test_issue_15227():
157
+ i = integrate(log(1-x)*log((1+x)**2)/x, (x, 0, 1))
158
+ assert not i.has(Integral)
159
+ # assert i == -5*zeta(3)/4
160
+
161
+
162
+ @XFAIL
163
+ @slow
164
+ def test_issue_14716():
165
+ i = integrate(log(x + 5)*cos(pi*x),(x, S.Half, 1))
166
+ assert not i.has(Integral)
167
+ # Mathematica can not solve it either, but
168
+ # integrate(log(x + 5)*cos(pi*x),(x, S.Half, 1)).transform(x, y - 5).doit()
169
+ # works
170
+ # assert i == -log(Rational(11, 2))/pi - Si(pi*Rational(11, 2))/pi + Si(6*pi)/pi
171
+
172
+
173
+ @XFAIL
174
+ def test_issue_14709a():
175
+ i = integrate(x*acos(1 - 2*x/h), (x, 0, h))
176
+ assert not i.has(Integral)
177
+ # assert i == 5*h**2*pi/16
178
+
179
+
180
+ @slow
181
+ @XFAIL
182
+ def test_issue_14398():
183
+ assert not integrate(exp(x**2)*cos(x), x).has(Integral)
184
+
185
+
186
+ @XFAIL
187
+ def test_issue_14074():
188
+ i = integrate(log(sin(x)), (x, 0, pi/2))
189
+ assert not i.has(Integral)
190
+ # assert i == -pi*log(2)/2
191
+
192
+
193
+ @XFAIL
194
+ @slow
195
+ def test_issue_14078b():
196
+ i = integrate((atan(4*x)-atan(2*x))/x, (x, 0, oo))
197
+ assert not i.has(Integral)
198
+ # assert i == pi*log(2)/2
199
+
200
+
201
+ @XFAIL
202
+ def test_issue_13792():
203
+ i = integrate(log(1/x) / (1 - x), (x, 0, 1))
204
+ assert not i.has(Integral)
205
+ # assert i in [polylog(2, -exp_polar(I*pi)), pi**2/6]
206
+
207
+
208
+ @XFAIL
209
+ def test_issue_11845a():
210
+ assert not integrate(exp(y - x**3), (x, 0, 1)).has(Integral)
211
+
212
+
213
+ @XFAIL
214
+ def test_issue_11845b():
215
+ assert not integrate(exp(-y - x**3), (x, 0, 1)).has(Integral)
216
+
217
+
218
+ @XFAIL
219
+ def test_issue_11813():
220
+ assert not integrate((a - x)**Rational(-1, 2)*x, (x, 0, a)).has(Integral)
221
+
222
+
223
+ @XFAIL
224
+ def test_issue_11254c():
225
+ assert not integrate(sech(x)**2, (x, 0, 1)).has(Integral)
226
+
227
+
228
+ @XFAIL
229
+ def test_issue_10584():
230
+ assert not integrate(sqrt(x**2 + 1/x**2), x).has(Integral)
231
+
232
+
233
+ @XFAIL
234
+ def test_issue_9101():
235
+ assert not integrate(log(x + sqrt(x**2 + y**2 + z**2)), z).has(Integral)
236
+
237
+
238
+ @XFAIL
239
+ def test_issue_7147():
240
+ assert not integrate(x/sqrt(a*x**2 + b*x + c)**3, x).has(Integral)
241
+
242
+
243
+ @XFAIL
244
+ def test_issue_7109():
245
+ assert not integrate(sqrt(a**2/(a**2 - x**2)), x).has(Integral)
246
+
247
+
248
+ @XFAIL
249
+ def test_integrate_Piecewise_rational_over_reals():
250
+ f = Piecewise(
251
+ (0, t - 478.515625*pi < 0),
252
+ (13.2075145209219*pi/(0.000871222*t + 0.995)**2, t - 478.515625*pi >= 0))
253
+
254
+ assert abs((integrate(f, (t, 0, oo)) - 15235.9375*pi).evalf()) <= 1e-7
255
+
256
+
257
+ @XFAIL
258
+ def test_issue_4311_slow():
259
+ # Not slow when bypassing heurish
260
+ assert not integrate(x*abs(9-x**2), x).has(Integral)
261
+
262
+ @XFAIL
263
+ def test_issue_20370():
264
+ a = symbols('a', positive=True)
265
+ assert integrate((1 + a * cos(x))**-1, (x, 0, 2 * pi)) == (2 * pi / sqrt(1 - a**2))
266
+
267
+
268
+ @XFAIL
269
+ def test_polylog():
270
+ # log(1/x)*log(x+1)-polylog(2, -x)
271
+ assert not integrate(log(1/x)/(x + 1), x).has(Integral)
272
+
273
+
274
+ @XFAIL
275
+ def test_polylog_manual():
276
+ # Make sure _parts_rule does not go into an infinite loop here
277
+ assert not integrate(log(1/x)/(x + 1), x, manual=True).has(Integral)
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_heurisch.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.add import Add
3
+ from sympy.core.function import (Derivative, Function, diff)
4
+ from sympy.core.numbers import (I, Rational, pi)
5
+ from sympy.core.relational import Eq, Ne
6
+ from sympy.core.symbol import (Symbol, symbols)
7
+ from sympy.functions.elementary.exponential import (LambertW, exp, log)
8
+ from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, tanh)
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.functions.elementary.piecewise import Piecewise
11
+ from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, tan)
12
+ from sympy.functions.special.bessel import (besselj, besselk, bessely, jn)
13
+ from sympy.functions.special.error_functions import erf
14
+ from sympy.integrals.integrals import Integral
15
+ from sympy.logic.boolalg import And
16
+ from sympy.matrices import Matrix
17
+ from sympy.simplify.ratsimp import ratsimp
18
+ from sympy.simplify.simplify import simplify
19
+ from sympy.integrals.heurisch import components, heurisch, heurisch_wrapper
20
+ from sympy.testing.pytest import XFAIL, slow
21
+ from sympy.integrals.integrals import integrate
22
+ from sympy import S
23
+
24
+ x, y, z, nu = symbols('x,y,z,nu')
25
+ f = Function('f')
26
+
27
+
28
+ def test_components():
29
+ assert components(x*y, x) == {x}
30
+ assert components(1/(x + y), x) == {x}
31
+ assert components(sin(x), x) == {sin(x), x}
32
+ assert components(sin(x)*sqrt(log(x)), x) == \
33
+ {log(x), sin(x), sqrt(log(x)), x}
34
+ assert components(x*sin(exp(x)*y), x) == \
35
+ {sin(y*exp(x)), x, exp(x)}
36
+ assert components(x**Rational(17, 54)/sqrt(sin(x)), x) == \
37
+ {sin(x), x**Rational(1, 54), sqrt(sin(x)), x}
38
+
39
+ assert components(f(x), x) == \
40
+ {x, f(x)}
41
+ assert components(Derivative(f(x), x), x) == \
42
+ {x, f(x), Derivative(f(x), x)}
43
+ assert components(f(x)*diff(f(x), x), x) == \
44
+ {x, f(x), Derivative(f(x), x), Derivative(f(x), x)}
45
+
46
+
47
+ def test_issue_10680():
48
+ assert isinstance(integrate(x**log(x**log(x**log(x))),x), Integral)
49
+
50
+
51
+ def test_issue_21166():
52
+ assert integrate(sin(x/sqrt(abs(x))), (x, -1, 1)) == 0
53
+
54
+
55
+ def test_heurisch_polynomials():
56
+ assert heurisch(1, x) == x
57
+ assert heurisch(x, x) == x**2/2
58
+ assert heurisch(x**17, x) == x**18/18
59
+ # For coverage
60
+ assert heurisch_wrapper(y, x) == y*x
61
+
62
+
63
+ def test_heurisch_fractions():
64
+ assert heurisch(1/x, x) == log(x)
65
+ assert heurisch(1/(2 + x), x) == log(x + 2)
66
+ assert heurisch(1/(x + sin(y)), x) == log(x + sin(y))
67
+
68
+ # Up to a constant, where C = pi*I*Rational(5, 12), Mathematica gives identical
69
+ # result in the first case. The difference is because SymPy changes
70
+ # signs of expressions without any care.
71
+ # XXX ^ ^ ^ is this still correct?
72
+ assert heurisch(5*x**5/(
73
+ 2*x**6 - 5), x) in [5*log(2*x**6 - 5) / 12, 5*log(-2*x**6 + 5) / 12]
74
+ assert heurisch(5*x**5/(2*x**6 + 5), x) == 5*log(2*x**6 + 5) / 12
75
+
76
+ assert heurisch(1/x**2, x) == -1/x
77
+ assert heurisch(-1/x**5, x) == 1/(4*x**4)
78
+
79
+
80
+ def test_heurisch_log():
81
+ assert heurisch(log(x), x) == x*log(x) - x
82
+ assert heurisch(log(3*x), x) == -x + x*log(3) + x*log(x)
83
+ assert heurisch(log(x**2), x) in [x*log(x**2) - 2*x, 2*x*log(x) - 2*x]
84
+
85
+
86
+ def test_heurisch_exp():
87
+ assert heurisch(exp(x), x) == exp(x)
88
+ assert heurisch(exp(-x), x) == -exp(-x)
89
+ assert heurisch(exp(17*x), x) == exp(17*x) / 17
90
+ assert heurisch(x*exp(x), x) == x*exp(x) - exp(x)
91
+ assert heurisch(x*exp(x**2), x) == exp(x**2) / 2
92
+
93
+ assert heurisch(exp(-x**2), x) is None
94
+
95
+ assert heurisch(2**x, x) == 2**x/log(2)
96
+ assert heurisch(x*2**x, x) == x*2**x/log(2) - 2**x*log(2)**(-2)
97
+
98
+ assert heurisch(Integral(x**z*y, (y, 1, 2), (z, 2, 3)).function, x) == (x*x**z*y)/(z+1)
99
+ assert heurisch(Sum(x**z, (z, 1, 2)).function, z) == x**z/log(x)
100
+
101
+ # https://github.com/sympy/sympy/issues/23707
102
+ anti = -exp(z)/(sqrt(x - y)*exp(z*sqrt(x - y)) - exp(z*sqrt(x - y)))
103
+ assert heurisch(exp(z)*exp(-z*sqrt(x - y)), z) == anti
104
+
105
+
106
+ def test_heurisch_trigonometric():
107
+ assert heurisch(sin(x), x) == -cos(x)
108
+ assert heurisch(pi*sin(x) + 1, x) == x - pi*cos(x)
109
+
110
+ assert heurisch(cos(x), x) == sin(x)
111
+ assert heurisch(tan(x), x) in [
112
+ log(1 + tan(x)**2)/2,
113
+ log(tan(x) + I) + I*x,
114
+ log(tan(x) - I) - I*x,
115
+ ]
116
+
117
+ assert heurisch(sin(x)*sin(y), x) == -cos(x)*sin(y)
118
+ assert heurisch(sin(x)*sin(y), y) == -cos(y)*sin(x)
119
+
120
+ # gives sin(x) in answer when run via setup.py and cos(x) when run via py.test
121
+ assert heurisch(sin(x)*cos(x), x) in [sin(x)**2 / 2, -cos(x)**2 / 2]
122
+ assert heurisch(cos(x)/sin(x), x) == log(sin(x))
123
+
124
+ assert heurisch(x*sin(7*x), x) == sin(7*x) / 49 - x*cos(7*x) / 7
125
+ assert heurisch(1/pi/4 * x**2*cos(x), x) == 1/pi/4*(x**2*sin(x) -
126
+ 2*sin(x) + 2*x*cos(x))
127
+
128
+ assert heurisch(acos(x/4) * asin(x/4), x) == 2*x - (sqrt(16 - x**2))*asin(x/4) \
129
+ + (sqrt(16 - x**2))*acos(x/4) + x*asin(x/4)*acos(x/4)
130
+
131
+ assert heurisch(sin(x)/(cos(x)**2+1), x) == -atan(cos(x)) #fixes issue 13723
132
+ assert heurisch(1/(cos(x)+2), x) == 2*sqrt(3)*atan(sqrt(3)*tan(x/2)/3)/3
133
+ assert heurisch(2*sin(x)*cos(x)/(sin(x)**4 + 1), x) == atan(sqrt(2)*sin(x)
134
+ - 1) - atan(sqrt(2)*sin(x) + 1)
135
+
136
+ assert heurisch(1/cosh(x), x) == 2*atan(tanh(x/2))
137
+
138
+
139
+ def test_heurisch_hyperbolic():
140
+ assert heurisch(sinh(x), x) == cosh(x)
141
+ assert heurisch(cosh(x), x) == sinh(x)
142
+
143
+ assert heurisch(x*sinh(x), x) == x*cosh(x) - sinh(x)
144
+ assert heurisch(x*cosh(x), x) == x*sinh(x) - cosh(x)
145
+
146
+ assert heurisch(
147
+ x*asinh(x/2), x) == x**2*asinh(x/2)/2 + asinh(x/2) - x*sqrt(4 + x**2)/4
148
+
149
+
150
+ def test_heurisch_mixed():
151
+ assert heurisch(sin(x)*exp(x), x) == exp(x)*sin(x)/2 - exp(x)*cos(x)/2
152
+ assert heurisch(sin(x/sqrt(-x)), x) == 2*x*cos(x/sqrt(-x))/sqrt(-x) - 2*sin(x/sqrt(-x))
153
+
154
+
155
+ def test_heurisch_radicals():
156
+ assert heurisch(1/sqrt(x), x) == 2*sqrt(x)
157
+ assert heurisch(1/sqrt(x)**3, x) == -2/sqrt(x)
158
+ assert heurisch(sqrt(x)**3, x) == 2*sqrt(x)**5/5
159
+
160
+ assert heurisch(sin(x)*sqrt(cos(x)), x) == -2*sqrt(cos(x))**3/3
161
+ y = Symbol('y')
162
+ assert heurisch(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \
163
+ 2*sqrt(x)*cos(y*sqrt(x))/y
164
+ assert heurisch_wrapper(sin(y*sqrt(x)), x) == Piecewise(
165
+ (-2*sqrt(x)*cos(sqrt(x)*y)/y + 2*sin(sqrt(x)*y)/y**2, Ne(y, 0)),
166
+ (0, True))
167
+ y = Symbol('y', positive=True)
168
+ assert heurisch_wrapper(sin(y*sqrt(x)), x) == 2/y**2*sin(y*sqrt(x)) - \
169
+ 2*sqrt(x)*cos(y*sqrt(x))/y
170
+
171
+
172
+ def test_heurisch_special():
173
+ assert heurisch(erf(x), x) == x*erf(x) + exp(-x**2)/sqrt(pi)
174
+ assert heurisch(exp(-x**2)*erf(x), x) == sqrt(pi)*erf(x)**2 / 4
175
+
176
+
177
+ def test_heurisch_symbolic_coeffs():
178
+ assert heurisch(1/(x + y), x) == log(x + y)
179
+ assert heurisch(1/(x + sqrt(2)), x) == log(x + sqrt(2))
180
+ assert simplify(diff(heurisch(log(x + y + z), y), y)) == log(x + y + z)
181
+
182
+
183
+ def test_heurisch_symbolic_coeffs_1130():
184
+ y = Symbol('y')
185
+ assert heurisch_wrapper(1/(x**2 + y), x) == Piecewise(
186
+ (log(x - sqrt(-y))/(2*sqrt(-y)) - log(x + sqrt(-y))/(2*sqrt(-y)),
187
+ Ne(y, 0)), (-1/x, True))
188
+ y = Symbol('y', positive=True)
189
+ assert heurisch_wrapper(1/(x**2 + y), x) == (atan(x/sqrt(y))/sqrt(y))
190
+
191
+
192
+ def test_heurisch_hacking():
193
+ assert heurisch(sqrt(1 + 7*x**2), x, hints=[]) == \
194
+ x*sqrt(1 + 7*x**2)/2 + sqrt(7)*asinh(sqrt(7)*x)/14
195
+ assert heurisch(sqrt(1 - 7*x**2), x, hints=[]) == \
196
+ x*sqrt(1 - 7*x**2)/2 + sqrt(7)*asin(sqrt(7)*x)/14
197
+
198
+ assert heurisch(1/sqrt(1 + 7*x**2), x, hints=[]) == \
199
+ sqrt(7)*asinh(sqrt(7)*x)/7
200
+ assert heurisch(1/sqrt(1 - 7*x**2), x, hints=[]) == \
201
+ sqrt(7)*asin(sqrt(7)*x)/7
202
+
203
+ assert heurisch(exp(-7*x**2), x, hints=[]) == \
204
+ sqrt(7*pi)*erf(sqrt(7)*x)/14
205
+
206
+ assert heurisch(1/sqrt(9 - 4*x**2), x, hints=[]) == \
207
+ asin(x*Rational(2, 3))/2
208
+
209
+ assert heurisch(1/sqrt(9 + 4*x**2), x, hints=[]) == \
210
+ asinh(x*Rational(2, 3))/2
211
+
212
+ assert heurisch(1/sqrt(3*x**2-4), x, hints=[]) == \
213
+ sqrt(3)*log(3*x + sqrt(3)*sqrt(3*x**2 - 4))/3
214
+
215
+
216
+ def test_heurisch_function():
217
+ assert heurisch(f(x), x) is None
218
+
219
+ @XFAIL
220
+ def test_heurisch_function_derivative():
221
+ # TODO: it looks like this used to work just by coincindence and
222
+ # thanks to sloppy implementation. Investigate why this used to
223
+ # work at all and if support for this can be restored.
224
+
225
+ df = diff(f(x), x)
226
+
227
+ assert heurisch(f(x)*df, x) == f(x)**2/2
228
+ assert heurisch(f(x)**2*df, x) == f(x)**3/3
229
+ assert heurisch(df/f(x), x) == log(f(x))
230
+
231
+
232
+ def test_heurisch_wrapper():
233
+ f = 1/(y + x)
234
+ assert heurisch_wrapper(f, x) == log(x + y)
235
+ f = 1/(y - x)
236
+ assert heurisch_wrapper(f, x) == -log(x - y)
237
+ f = 1/((y - x)*(y + x))
238
+ assert heurisch_wrapper(f, x) == Piecewise(
239
+ (-log(x - y)/(2*y) + log(x + y)/(2*y), Ne(y, 0)), (1/x, True))
240
+ # issue 6926
241
+ f = sqrt(x**2/((y - x)*(y + x)))
242
+ assert heurisch_wrapper(f, x) == x*sqrt(-x**2/(x**2 - y**2)) \
243
+ - y**2*sqrt(-x**2/(x**2 - y**2))/x
244
+
245
+
246
+ def test_issue_3609():
247
+ assert heurisch(1/(x * (1 + log(x)**2)), x) == atan(log(x))
248
+
249
+ ### These are examples from the Poor Man's Integrator
250
+ ### http://www-sop.inria.fr/cafe/Manuel.Bronstein/pmint/examples/
251
+
252
+
253
+ def test_pmint_rat():
254
+ # TODO: heurisch() is off by a constant: -3/4. Possibly different permutation
255
+ # would give the optimal result?
256
+
257
+ def drop_const(expr, x):
258
+ if expr.is_Add:
259
+ return Add(*[ arg for arg in expr.args if arg.has(x) ])
260
+ else:
261
+ return expr
262
+
263
+ f = (x**7 - 24*x**4 - 4*x**2 + 8*x - 8)/(x**8 + 6*x**6 + 12*x**4 + 8*x**2)
264
+ g = (4 + 8*x**2 + 6*x + 3*x**3)/(x**5 + 4*x**3 + 4*x) + log(x)
265
+
266
+ assert drop_const(ratsimp(heurisch(f, x)), x) == g
267
+
268
+
269
+ def test_pmint_trig():
270
+ f = (x - tan(x)) / tan(x)**2 + tan(x)
271
+ g = -x**2/2 - x/tan(x) + log(tan(x)**2 + 1)/2
272
+
273
+ assert heurisch(f, x) == g
274
+
275
+
276
+ def test_pmint_logexp():
277
+ f = (1 + x + x*exp(x))*(x + log(x) + exp(x) - 1)/(x + log(x) + exp(x))**2/x
278
+ g = log(x + exp(x) + log(x)) + 1/(x + exp(x) + log(x))
279
+
280
+ assert ratsimp(heurisch(f, x)) == g
281
+
282
+
283
+ def test_pmint_erf():
284
+ f = exp(-x**2)*erf(x)/(erf(x)**3 - erf(x)**2 - erf(x) + 1)
285
+ g = sqrt(pi)*log(erf(x) - 1)/8 - sqrt(pi)*log(erf(x) + 1)/8 - sqrt(pi)/(4*erf(x) - 4)
286
+
287
+ assert ratsimp(heurisch(f, x)) == g
288
+
289
+
290
+ def test_pmint_LambertW():
291
+ f = LambertW(x)
292
+ g = x*LambertW(x) - x + x/LambertW(x)
293
+
294
+ assert heurisch(f, x) == g
295
+
296
+
297
+ def test_pmint_besselj():
298
+ f = besselj(nu + 1, x)/besselj(nu, x)
299
+ g = nu*log(x) - log(besselj(nu, x))
300
+
301
+ assert heurisch(f, x) == g
302
+
303
+ f = (nu*besselj(nu, x) - x*besselj(nu + 1, x))/x
304
+ g = besselj(nu, x)
305
+
306
+ assert heurisch(f, x) == g
307
+
308
+ f = jn(nu + 1, x)/jn(nu, x)
309
+ g = nu*log(x) - log(jn(nu, x))
310
+
311
+ assert heurisch(f, x) == g
312
+
313
+
314
+ @slow
315
+ def test_pmint_bessel_products():
316
+ f = x*besselj(nu, x)*bessely(nu, 2*x)
317
+ g = -2*x*besselj(nu, x)*bessely(nu - 1, 2*x)/3 + x*besselj(nu - 1, x)*bessely(nu, 2*x)/3
318
+
319
+ assert heurisch(f, x) == g
320
+
321
+ f = x*besselj(nu, x)*besselk(nu, 2*x)
322
+ g = -2*x*besselj(nu, x)*besselk(nu - 1, 2*x)/5 - x*besselj(nu - 1, x)*besselk(nu, 2*x)/5
323
+
324
+ assert heurisch(f, x) == g
325
+
326
+
327
+ def test_pmint_WrightOmega():
328
+ def omega(x):
329
+ return LambertW(exp(x))
330
+
331
+ f = (1 + omega(x) * (2 + cos(omega(x)) * (x + omega(x))))/(1 + omega(x))/(x + omega(x))
332
+ g = log(x + LambertW(exp(x))) + sin(LambertW(exp(x)))
333
+
334
+ assert heurisch(f, x) == g
335
+
336
+
337
+ def test_RR():
338
+ # Make sure the algorithm does the right thing if the ring is RR. See
339
+ # issue 8685.
340
+ assert heurisch(sqrt(1 + 0.25*x**2), x, hints=[]) == \
341
+ 0.5*x*sqrt(0.25*x**2 + 1) + 1.0*asinh(0.5*x)
342
+
343
+ # TODO: convert the rest of PMINT tests:
344
+ # Airy functions
345
+ # f = (x - AiryAi(x)*AiryAi(1, x)) / (x**2 - AiryAi(x)**2)
346
+ # g = Rational(1,2)*ln(x + AiryAi(x)) + Rational(1,2)*ln(x - AiryAi(x))
347
+ # f = x**2 * AiryAi(x)
348
+ # g = -AiryAi(x) + AiryAi(1, x)*x
349
+ # Whittaker functions
350
+ # f = WhittakerW(mu + 1, nu, x) / (WhittakerW(mu, nu, x) * x)
351
+ # g = x/2 - mu*ln(x) - ln(WhittakerW(mu, nu, x))
352
+
353
+
354
+ def test_issue_22527():
355
+ t, R = symbols(r't R')
356
+ z = Function('z')(t)
357
+ def f(x):
358
+ return x/sqrt(R**2 - x**2)
359
+ Uz = integrate(f(z), z)
360
+ Ut = integrate(f(t), t)
361
+ assert Ut == Uz.subs(z, t)
362
+
363
+
364
+ def test_heurisch_complex_erf_issue_26338():
365
+ r = symbols('r', real=True)
366
+ a = exp(-r**2/(2*(2 - I)**2))
367
+ assert heurisch(a, r, hints=[]) is None # None, not a wrong soln
368
+ a = sqrt(pi)*erf((1 + I)/2)/2
369
+ assert integrate(exp(-I*r**2/2), (r, 0, 1)) == a - I*a
370
+
371
+ a = exp(-x**2/(2*(2 - I)**2))
372
+ assert heurisch(a, x, hints=[]) is None # None, not a wrong soln
373
+ a = exp(-r**2/(2*(2 - I)**2))
374
+ assert heurisch(a, r, hints=[]) is None
375
+ a = sqrt(pi)*erf((1 + I)/2)/2
376
+ assert integrate(exp(-I*x**2/2), (x, 0, 1)) == a - I*a
377
+
378
+
379
+ def test_issue_15498():
380
+ Z0 = Function('Z0')
381
+ k01, k10, t, s= symbols('k01 k10 t s', real=True, positive=True)
382
+ m = Matrix([[exp(-k10*t)]])
383
+ _83 = Rational(83, 100) # 0.83 works, too
384
+ [a, b, c, d, e, f, g] = [100, 0.5, _83, 50, 0.6, 2, 120]
385
+ AIF_btf = a*(d*e*(1 - exp(-(t - b)/e)) + f*g*(1 - exp(-(t - b)/g)))
386
+ AIF_atf = a*(d*e*exp(-(t - b)/e)*(exp((c - b)/e) - 1
387
+ ) + f*g*exp(-(t - b)/g)*(exp((c - b)/g) - 1))
388
+ AIF_sym = Piecewise((0, t < b), (AIF_btf, And(b <= t, t < c)), (AIF_atf, c <= t))
389
+ aif_eq = Eq(Z0(t), AIF_sym)
390
+ f_vec = Matrix([[k01*Z0(t)]])
391
+ integrand = m*m.subs(t, s)**-1*f_vec.subs(aif_eq.lhs, aif_eq.rhs).subs(t, s)
392
+ solution = integrate(integrand[0], (s, 0, t))
393
+ assert solution is not None # does not hang and takes less than 10 s
394
+
395
+
396
+ @slow
397
+ def test_heurisch_issue_26930():
398
+ integrand = x**Rational(4, 3)*log(x)
399
+ anti = 3*x**(S(7)/3)*log(x)/7 - 9*x**(S(7)/3)/49
400
+ assert heurisch(integrand, x) == anti
401
+ assert integrate(integrand, x) == anti
402
+ assert integrate(integrand, (x, 0, 1)) == -S(9)/49
403
+
404
+
405
+ def test_heurisch_issue_26922():
406
+
407
+ a, b, x = symbols("a, b, x", real=True, positive=True)
408
+ C = symbols("C", real=True)
409
+ i1 = -C*x*exp(-a*x**2 - sqrt(b)*x)
410
+ i2 = C*x*exp(-a*x**2 + sqrt(b)*x)
411
+ i = Integral(i1, x) + Integral(i2, x)
412
+ res = (
413
+ -C*exp(-a*x**2)*exp(sqrt(b)*x)/(2*a)
414
+ + C*exp(-a*x**2)*exp(-sqrt(b)*x)/(2*a)
415
+ + sqrt(pi)*C*sqrt(b)*exp(b/(4*a))*erf(sqrt(a)*x - sqrt(b)/(2*sqrt(a)))/(4*a**(S(3)/2))
416
+ + sqrt(pi)*C*sqrt(b)*exp(b/(4*a))*erf(sqrt(a)*x + sqrt(b)/(2*sqrt(a)))/(4*a**(S(3)/2))
417
+ )
418
+
419
+ assert i.doit(heurisch=False).expand() == res
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_intpoly.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.functions.elementary.complexes import Abs
2
+ from sympy.functions.elementary.miscellaneous import sqrt
3
+
4
+ from sympy.core import S, Rational
5
+
6
+ from sympy.integrals.intpoly import (decompose, best_origin, distance_to_side,
7
+ polytope_integrate, point_sort,
8
+ hyperplane_parameters, main_integrate3d,
9
+ main_integrate, polygon_integrate,
10
+ lineseg_integrate, integration_reduction,
11
+ integration_reduction_dynamic, is_vertex)
12
+
13
+ from sympy.geometry.line import Segment2D
14
+ from sympy.geometry.polygon import Polygon
15
+ from sympy.geometry.point import Point, Point2D
16
+ from sympy.abc import x, y, z
17
+
18
+ from sympy.testing.pytest import slow
19
+
20
+
21
+ def test_decompose():
22
+ assert decompose(x) == {1: x}
23
+ assert decompose(x**2) == {2: x**2}
24
+ assert decompose(x*y) == {2: x*y}
25
+ assert decompose(x + y) == {1: x + y}
26
+ assert decompose(x**2 + y) == {1: y, 2: x**2}
27
+ assert decompose(8*x**2 + 4*y + 7) == {0: 7, 1: 4*y, 2: 8*x**2}
28
+ assert decompose(x**2 + 3*y*x) == {2: x**2 + 3*x*y}
29
+ assert decompose(9*x**2 + y + 4*x + x**3 + y**2*x + 3) ==\
30
+ {0: 3, 1: 4*x + y, 2: 9*x**2, 3: x**3 + x*y**2}
31
+
32
+ assert decompose(x, True) == {x}
33
+ assert decompose(x ** 2, True) == {x**2}
34
+ assert decompose(x * y, True) == {x * y}
35
+ assert decompose(x + y, True) == {x, y}
36
+ assert decompose(x ** 2 + y, True) == {y, x ** 2}
37
+ assert decompose(8 * x ** 2 + 4 * y + 7, True) == {7, 4*y, 8*x**2}
38
+ assert decompose(x ** 2 + 3 * y * x, True) == {x ** 2, 3 * x * y}
39
+ assert decompose(9 * x ** 2 + y + 4 * x + x ** 3 + y ** 2 * x + 3, True) == \
40
+ {3, y, 4*x, 9*x**2, x*y**2, x**3}
41
+
42
+
43
+ def test_best_origin():
44
+ expr1 = y ** 2 * x ** 5 + y ** 5 * x ** 7 + 7 * x + x ** 12 + y ** 7 * x
45
+
46
+ l1 = Segment2D(Point(0, 3), Point(1, 1))
47
+ l2 = Segment2D(Point(S(3) / 2, 0), Point(S(3) / 2, 3))
48
+ l3 = Segment2D(Point(0, S(3) / 2), Point(3, S(3) / 2))
49
+ l4 = Segment2D(Point(0, 2), Point(2, 0))
50
+ l5 = Segment2D(Point(0, 2), Point(1, 1))
51
+ l6 = Segment2D(Point(2, 0), Point(1, 1))
52
+
53
+ assert best_origin((2, 1), 3, l1, expr1) == (0, 3)
54
+ # XXX: Should these return exact Rational output? Maybe best_origin should
55
+ # sympify its arguments...
56
+ assert best_origin((2, 0), 3, l2, x ** 7) == (1.5, 0)
57
+ assert best_origin((0, 2), 3, l3, x ** 7) == (0, 1.5)
58
+ assert best_origin((1, 1), 2, l4, x ** 7 * y ** 3) == (0, 2)
59
+ assert best_origin((1, 1), 2, l4, x ** 3 * y ** 7) == (2, 0)
60
+ assert best_origin((1, 1), 2, l5, x ** 2 * y ** 9) == (0, 2)
61
+ assert best_origin((1, 1), 2, l6, x ** 9 * y ** 2) == (2, 0)
62
+
63
+
64
+ @slow
65
+ def test_polytope_integrate():
66
+ # Convex 2-Polytopes
67
+ # Vertex representation
68
+ assert polytope_integrate(Polygon(Point(0, 0), Point(0, 2),
69
+ Point(4, 0)), 1) == 4
70
+ assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1),
71
+ Point(1, 1), Point(1, 0)), x * y) ==\
72
+ Rational(1, 4)
73
+ assert polytope_integrate(Polygon(Point(0, 3), Point(5, 3), Point(1, 1)),
74
+ 6*x**2 - 40*y) == Rational(-935, 3)
75
+
76
+ assert polytope_integrate(Polygon(Point(0, 0), Point(0, sqrt(3)),
77
+ Point(sqrt(3), sqrt(3)),
78
+ Point(sqrt(3), 0)), 1) == 3
79
+
80
+ hexagon = Polygon(Point(0, 0), Point(-sqrt(3) / 2, S.Half),
81
+ Point(-sqrt(3) / 2, S(3) / 2), Point(0, 2),
82
+ Point(sqrt(3) / 2, S(3) / 2), Point(sqrt(3) / 2, S.Half))
83
+
84
+ assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2
85
+
86
+ # Hyperplane representation
87
+ assert polytope_integrate([((-1, 0), 0), ((1, 2), 4),
88
+ ((0, -1), 0)], 1) == 4
89
+ assert polytope_integrate([((-1, 0), 0), ((0, 1), 1),
90
+ ((1, 0), 1), ((0, -1), 0)], x * y) == Rational(1, 4)
91
+ assert polytope_integrate([((0, 1), 3), ((1, -2), -1),
92
+ ((-2, -1), -3)], 6*x**2 - 40*y) == Rational(-935, 3)
93
+ assert polytope_integrate([((-1, 0), 0), ((0, sqrt(3)), 3),
94
+ ((sqrt(3), 0), 3), ((0, -1), 0)], 1) == 3
95
+
96
+ hexagon = [((Rational(-1, 2), -sqrt(3) / 2), 0),
97
+ ((-1, 0), sqrt(3) / 2),
98
+ ((Rational(-1, 2), sqrt(3) / 2), sqrt(3)),
99
+ ((S.Half, sqrt(3) / 2), sqrt(3)),
100
+ ((1, 0), sqrt(3) / 2),
101
+ ((S.Half, -sqrt(3) / 2), 0)]
102
+ assert polytope_integrate(hexagon, 1) == S(3*sqrt(3)) / 2
103
+
104
+ # Non-convex polytopes
105
+ # Vertex representation
106
+ assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1),
107
+ Point(1, 1), Point(0, 0),
108
+ Point(1, -1)), 1) == 3
109
+ assert polytope_integrate(Polygon(Point(-1, -1), Point(-1, 1),
110
+ Point(0, 0), Point(1, 1),
111
+ Point(1, -1), Point(0, 0)), 1) == 2
112
+ # Hyperplane representation
113
+ assert polytope_integrate([((-1, 0), 1), ((0, 1), 1), ((1, -1), 0),
114
+ ((1, 1), 0), ((0, -1), 1)], 1) == 3
115
+ assert polytope_integrate([((-1, 0), 1), ((1, 1), 0), ((-1, 1), 0),
116
+ ((1, 0), 1), ((-1, -1), 0),
117
+ ((1, -1), 0)], 1) == 2
118
+
119
+ # Tests for 2D polytopes mentioned in Chin et al(Page 10):
120
+ # http://dilbert.engr.ucdavis.edu/~suku/quadrature/cls-integration.pdf
121
+ fig1 = Polygon(Point(1.220, -0.827), Point(-1.490, -4.503),
122
+ Point(-3.766, -1.622), Point(-4.240, -0.091),
123
+ Point(-3.160, 4), Point(-0.981, 4.447),
124
+ Point(0.132, 4.027))
125
+ assert polytope_integrate(fig1, x**2 + x*y + y**2) ==\
126
+ S(2031627344735367)/(8*10**12)
127
+
128
+ fig2 = Polygon(Point(4.561, 2.317), Point(1.491, -1.315),
129
+ Point(-3.310, -3.164), Point(-4.845, -3.110),
130
+ Point(-4.569, 1.867))
131
+ assert polytope_integrate(fig2, x**2 + x*y + y**2) ==\
132
+ S(517091313866043)/(16*10**11)
133
+
134
+ fig3 = Polygon(Point(-2.740, -1.888), Point(-3.292, 4.233),
135
+ Point(-2.723, -0.697), Point(-0.643, -3.151))
136
+ assert polytope_integrate(fig3, x**2 + x*y + y**2) ==\
137
+ S(147449361647041)/(8*10**12)
138
+
139
+ fig4 = Polygon(Point(0.211, -4.622), Point(-2.684, 3.851),
140
+ Point(0.468, 4.879), Point(4.630, -1.325),
141
+ Point(-0.411, -1.044))
142
+ assert polytope_integrate(fig4, x**2 + x*y + y**2) ==\
143
+ S(180742845225803)/(10**12)
144
+
145
+ # Tests for many polynomials with maximum degree given(2D case).
146
+ tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
147
+ polys = []
148
+ expr1 = x**9*y + x**7*y**3 + 2*x**2*y**8
149
+ expr2 = x**6*y**4 + x**5*y**5 + 2*y**10
150
+ expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5
151
+ polys.extend((expr1, expr2, expr3))
152
+ result_dict = polytope_integrate(tri, polys, max_degree=10)
153
+ assert result_dict[expr1] == Rational(615780107, 594)
154
+ assert result_dict[expr2] == Rational(13062161, 27)
155
+ assert result_dict[expr3] == Rational(1946257153, 924)
156
+
157
+ tri = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
158
+ expr1 = x**7*y**1 + 2*x**2*y**6
159
+ expr2 = x**6*y**4 + x**5*y**5 + 2*y**10
160
+ expr3 = x**10 + x**9*y + x**8*y**2 + x**5*y**5
161
+ polys.extend((expr1, expr2, expr3))
162
+ assert polytope_integrate(tri, polys, max_degree=9) == \
163
+ {x**7*y + 2*x**2*y**6: Rational(489262, 9)}
164
+
165
+ # Tests when all integral of all monomials up to a max_degree is to be
166
+ # calculated.
167
+ assert polytope_integrate(Polygon(Point(0, 0), Point(0, 1),
168
+ Point(1, 1), Point(1, 0)),
169
+ max_degree=4) == {0: 0, 1: 1, x: S.Half,
170
+ x ** 2 * y ** 2: S.One / 9,
171
+ x ** 4: S.One / 5,
172
+ y ** 4: S.One / 5,
173
+ y: S.Half,
174
+ x * y ** 2: S.One / 6,
175
+ y ** 2: S.One / 3,
176
+ x ** 3: S.One / 4,
177
+ x ** 2 * y: S.One / 6,
178
+ x ** 3 * y: S.One / 8,
179
+ x * y: S.One / 4,
180
+ y ** 3: S.One / 4,
181
+ x ** 2: S.One / 3,
182
+ x * y ** 3: S.One / 8}
183
+
184
+ # Tests for 3D polytopes
185
+ cube1 = [[(0, 0, 0), (0, 6, 6), (6, 6, 6), (3, 6, 0),
186
+ (0, 6, 0), (6, 0, 6), (3, 0, 0), (0, 0, 6)],
187
+ [1, 2, 3, 4], [3, 2, 5, 6], [1, 7, 5, 2], [0, 6, 5, 7],
188
+ [1, 4, 0, 7], [0, 4, 3, 6]]
189
+ assert polytope_integrate(cube1, 1) == S(162)
190
+
191
+ # 3D Test cases in Chin et al(2015)
192
+ cube2 = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),
193
+ (5, 0, 5), (5, 5, 0), (5, 5, 5)],
194
+ [3, 7, 6, 2], [1, 5, 7, 3], [5, 4, 6, 7], [0, 4, 5, 1],
195
+ [2, 0, 1, 3], [2, 6, 4, 0]]
196
+
197
+ cube3 = [[(0, 0, 0), (5, 0, 0), (5, 4, 0), (3, 2, 0), (3, 5, 0),
198
+ (0, 5, 0), (0, 0, 5), (5, 0, 5), (5, 4, 5), (3, 2, 5),
199
+ (3, 5, 5), (0, 5, 5)],
200
+ [6, 11, 5, 0], [1, 7, 6, 0], [5, 4, 3, 2, 1, 0], [11, 10, 4, 5],
201
+ [10, 9, 3, 4], [9, 8, 2, 3], [8, 7, 1, 2], [7, 8, 9, 10, 11, 6]]
202
+
203
+ cube4 = [[(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1),
204
+ (S.One / 4, S.One / 4, S.One / 4)],
205
+ [0, 2, 1], [1, 3, 0], [4, 2, 3], [4, 3, 1],
206
+ [0, 1, 2], [2, 4, 1], [0, 3, 2]]
207
+
208
+ assert polytope_integrate(cube2, x ** 2 + y ** 2 + x * y + z ** 2) ==\
209
+ Rational(15625, 4)
210
+ assert polytope_integrate(cube3, x ** 2 + y ** 2 + x * y + z ** 2) ==\
211
+ S(33835) / 12
212
+ assert polytope_integrate(cube4, x ** 2 + y ** 2 + x * y + z ** 2) ==\
213
+ S(37) / 960
214
+
215
+ # Test cases from Mathematica's PolyhedronData library
216
+ octahedron = [[(S.NegativeOne / sqrt(2), 0, 0), (0, S.One / sqrt(2), 0),
217
+ (0, 0, S.NegativeOne / sqrt(2)), (0, 0, S.One / sqrt(2)),
218
+ (0, S.NegativeOne / sqrt(2), 0), (S.One / sqrt(2), 0, 0)],
219
+ [3, 4, 5], [3, 5, 1], [3, 1, 0], [3, 0, 4], [4, 0, 2],
220
+ [4, 2, 5], [2, 0, 1], [5, 2, 1]]
221
+
222
+ assert polytope_integrate(octahedron, 1) == sqrt(2) / 3
223
+
224
+ great_stellated_dodecahedron =\
225
+ [[(-0.32491969623290634095, 0, 0.42532540417601993887),
226
+ (0.32491969623290634095, 0, -0.42532540417601993887),
227
+ (-0.52573111211913359231, 0, 0.10040570794311363956),
228
+ (0.52573111211913359231, 0, -0.10040570794311363956),
229
+ (-0.10040570794311363956, -0.3090169943749474241, 0.42532540417601993887),
230
+ (-0.10040570794311363956, 0.30901699437494742410, 0.42532540417601993887),
231
+ (0.10040570794311363956, -0.3090169943749474241, -0.42532540417601993887),
232
+ (0.10040570794311363956, 0.30901699437494742410, -0.42532540417601993887),
233
+ (-0.16245984811645317047, -0.5, 0.10040570794311363956),
234
+ (-0.16245984811645317047, 0.5, 0.10040570794311363956),
235
+ (0.16245984811645317047, -0.5, -0.10040570794311363956),
236
+ (0.16245984811645317047, 0.5, -0.10040570794311363956),
237
+ (-0.42532540417601993887, -0.3090169943749474241, -0.10040570794311363956),
238
+ (-0.42532540417601993887, 0.30901699437494742410, -0.10040570794311363956),
239
+ (-0.26286555605956679615, 0.1909830056250525759, -0.42532540417601993887),
240
+ (-0.26286555605956679615, -0.1909830056250525759, -0.42532540417601993887),
241
+ (0.26286555605956679615, 0.1909830056250525759, 0.42532540417601993887),
242
+ (0.26286555605956679615, -0.1909830056250525759, 0.42532540417601993887),
243
+ (0.42532540417601993887, -0.3090169943749474241, 0.10040570794311363956),
244
+ (0.42532540417601993887, 0.30901699437494742410, 0.10040570794311363956)],
245
+ [12, 3, 0, 6, 16], [17, 7, 0, 3, 13],
246
+ [9, 6, 0, 7, 8], [18, 2, 1, 4, 14],
247
+ [15, 5, 1, 2, 19], [11, 4, 1, 5, 10],
248
+ [8, 19, 2, 18, 9], [10, 13, 3, 12, 11],
249
+ [16, 14, 4, 11, 12], [13, 10, 5, 15, 17],
250
+ [14, 16, 6, 9, 18], [19, 8, 7, 17, 15]]
251
+ # Actual volume is : 0.163118960624632
252
+ assert Abs(polytope_integrate(great_stellated_dodecahedron, 1) -\
253
+ 0.163118960624632) < 1e-12
254
+
255
+ expr = x **2 + y ** 2 + z ** 2
256
+ octahedron_five_compound = [[(0, -0.7071067811865475244, 0),
257
+ (0, 0.70710678118654752440, 0),
258
+ (0.1148764602736805918,
259
+ -0.35355339059327376220, -0.60150095500754567366),
260
+ (0.1148764602736805918, 0.35355339059327376220,
261
+ -0.60150095500754567366),
262
+ (0.18587401723009224507,
263
+ -0.57206140281768429760, 0.37174803446018449013),
264
+ (0.18587401723009224507, 0.57206140281768429760,
265
+ 0.37174803446018449013),
266
+ (0.30075047750377283683, -0.21850801222441053540,
267
+ 0.60150095500754567366),
268
+ (0.30075047750377283683, 0.21850801222441053540,
269
+ 0.60150095500754567366),
270
+ (0.48662449473386508189, -0.35355339059327376220,
271
+ -0.37174803446018449013),
272
+ (0.48662449473386508189, 0.35355339059327376220,
273
+ -0.37174803446018449013),
274
+ (-0.60150095500754567366, 0, -0.37174803446018449013),
275
+ (-0.30075047750377283683, -0.21850801222441053540,
276
+ -0.60150095500754567366),
277
+ (-0.30075047750377283683, 0.21850801222441053540,
278
+ -0.60150095500754567366),
279
+ (0.60150095500754567366, 0, 0.37174803446018449013),
280
+ (0.4156269377774534286, -0.57206140281768429760, 0),
281
+ (0.4156269377774534286, 0.57206140281768429760, 0),
282
+ (0.37174803446018449013, 0, -0.60150095500754567366),
283
+ (-0.4156269377774534286, -0.57206140281768429760, 0),
284
+ (-0.4156269377774534286, 0.57206140281768429760, 0),
285
+ (-0.67249851196395732696, -0.21850801222441053540, 0),
286
+ (-0.67249851196395732696, 0.21850801222441053540, 0),
287
+ (0.67249851196395732696, -0.21850801222441053540, 0),
288
+ (0.67249851196395732696, 0.21850801222441053540, 0),
289
+ (-0.37174803446018449013, 0, 0.60150095500754567366),
290
+ (-0.48662449473386508189, -0.35355339059327376220,
291
+ 0.37174803446018449013),
292
+ (-0.48662449473386508189, 0.35355339059327376220,
293
+ 0.37174803446018449013),
294
+ (-0.18587401723009224507, -0.57206140281768429760,
295
+ -0.37174803446018449013),
296
+ (-0.18587401723009224507, 0.57206140281768429760,
297
+ -0.37174803446018449013),
298
+ (-0.11487646027368059176, -0.35355339059327376220,
299
+ 0.60150095500754567366),
300
+ (-0.11487646027368059176, 0.35355339059327376220,
301
+ 0.60150095500754567366)],
302
+ [0, 10, 16], [23, 10, 0], [16, 13, 0],
303
+ [0, 13, 23], [16, 10, 1], [1, 10, 23],
304
+ [1, 13, 16], [23, 13, 1], [2, 4, 19],
305
+ [22, 4, 2], [2, 19, 27], [27, 22, 2],
306
+ [20, 5, 3], [3, 5, 21], [26, 20, 3],
307
+ [3, 21, 26], [29, 19, 4], [4, 22, 29],
308
+ [5, 20, 28], [28, 21, 5], [6, 8, 15],
309
+ [17, 8, 6], [6, 15, 25], [25, 17, 6],
310
+ [14, 9, 7], [7, 9, 18], [24, 14, 7],
311
+ [7, 18, 24], [8, 12, 15], [17, 12, 8],
312
+ [14, 11, 9], [9, 11, 18], [11, 14, 24],
313
+ [24, 18, 11], [25, 15, 12], [12, 17, 25],
314
+ [29, 27, 19], [20, 26, 28], [28, 26, 21],
315
+ [22, 27, 29]]
316
+ assert Abs(polytope_integrate(octahedron_five_compound, expr)) - 0.353553\
317
+ < 1e-6
318
+
319
+ cube_five_compound = [[(-0.1624598481164531631, -0.5, -0.6881909602355867691),
320
+ (-0.1624598481164531631, 0.5, -0.6881909602355867691),
321
+ (0.1624598481164531631, -0.5, 0.68819096023558676910),
322
+ (0.1624598481164531631, 0.5, 0.68819096023558676910),
323
+ (-0.52573111211913359231, 0, -0.6881909602355867691),
324
+ (0.52573111211913359231, 0, 0.68819096023558676910),
325
+ (-0.26286555605956679615, -0.8090169943749474241,
326
+ -0.1624598481164531631),
327
+ (-0.26286555605956679615, 0.8090169943749474241,
328
+ -0.1624598481164531631),
329
+ (0.26286555605956680301, -0.8090169943749474241,
330
+ 0.1624598481164531631),
331
+ (0.26286555605956680301, 0.8090169943749474241,
332
+ 0.1624598481164531631),
333
+ (-0.42532540417601993887, -0.3090169943749474241,
334
+ 0.68819096023558676910),
335
+ (-0.42532540417601993887, 0.30901699437494742410,
336
+ 0.68819096023558676910),
337
+ (0.42532540417601996609, -0.3090169943749474241,
338
+ -0.6881909602355867691),
339
+ (0.42532540417601996609, 0.30901699437494742410,
340
+ -0.6881909602355867691),
341
+ (-0.6881909602355867691, -0.5, 0.1624598481164531631),
342
+ (-0.6881909602355867691, 0.5, 0.1624598481164531631),
343
+ (0.68819096023558676910, -0.5, -0.1624598481164531631),
344
+ (0.68819096023558676910, 0.5, -0.1624598481164531631),
345
+ (-0.85065080835203998877, 0, -0.1624598481164531631),
346
+ (0.85065080835203993218, 0, 0.1624598481164531631)],
347
+ [18, 10, 3, 7], [13, 19, 8, 0], [18, 0, 8, 10],
348
+ [3, 19, 13, 7], [18, 7, 13, 0], [8, 19, 3, 10],
349
+ [6, 2, 11, 18], [1, 9, 19, 12], [11, 9, 1, 18],
350
+ [6, 12, 19, 2], [1, 12, 6, 18], [11, 2, 19, 9],
351
+ [4, 14, 11, 7], [17, 5, 8, 12], [4, 12, 8, 14],
352
+ [11, 5, 17, 7], [4, 7, 17, 12], [8, 5, 11, 14],
353
+ [6, 10, 15, 4], [13, 9, 5, 16], [15, 9, 13, 4],
354
+ [6, 16, 5, 10], [13, 16, 6, 4], [15, 10, 5, 9],
355
+ [14, 15, 1, 0], [16, 17, 3, 2], [14, 2, 3, 15],
356
+ [1, 17, 16, 0], [14, 0, 16, 2], [3, 17, 1, 15]]
357
+ assert Abs(polytope_integrate(cube_five_compound, expr) - 1.25) < 1e-12
358
+
359
+ echidnahedron = [[(0, 0, -2.4898982848827801995),
360
+ (0, 0, 2.4898982848827802734),
361
+ (0, -4.2360679774997896964, -2.4898982848827801995),
362
+ (0, -4.2360679774997896964, 2.4898982848827802734),
363
+ (0, 4.2360679774997896964, -2.4898982848827801995),
364
+ (0, 4.2360679774997896964, 2.4898982848827802734),
365
+ (-4.0287400534704067567, -1.3090169943749474241, -2.4898982848827801995),
366
+ (-4.0287400534704067567, -1.3090169943749474241, 2.4898982848827802734),
367
+ (-4.0287400534704067567, 1.3090169943749474241, -2.4898982848827801995),
368
+ (-4.0287400534704067567, 1.3090169943749474241, 2.4898982848827802734),
369
+ (4.0287400534704069747, -1.3090169943749474241, -2.4898982848827801995),
370
+ (4.0287400534704069747, -1.3090169943749474241, 2.4898982848827802734),
371
+ (4.0287400534704069747, 1.3090169943749474241, -2.4898982848827801995),
372
+ (4.0287400534704069747, 1.3090169943749474241, 2.4898982848827802734),
373
+ (-2.4898982848827801995, -3.4270509831248422723, -2.4898982848827801995),
374
+ (-2.4898982848827801995, -3.4270509831248422723, 2.4898982848827802734),
375
+ (-2.4898982848827801995, 3.4270509831248422723, -2.4898982848827801995),
376
+ (-2.4898982848827801995, 3.4270509831248422723, 2.4898982848827802734),
377
+ (2.4898982848827802734, -3.4270509831248422723, -2.4898982848827801995),
378
+ (2.4898982848827802734, -3.4270509831248422723, 2.4898982848827802734),
379
+ (2.4898982848827802734, 3.4270509831248422723, -2.4898982848827801995),
380
+ (2.4898982848827802734, 3.4270509831248422723, 2.4898982848827802734),
381
+ (-4.7169310137059934362, -0.8090169943749474241, -1.1135163644116066184),
382
+ (-4.7169310137059934362, 0.8090169943749474241, -1.1135163644116066184),
383
+ (4.7169310137059937438, -0.8090169943749474241, 1.11351636441160673519),
384
+ (4.7169310137059937438, 0.8090169943749474241, 1.11351636441160673519),
385
+ (-4.2916056095299737777, -2.1180339887498948482, 1.11351636441160673519),
386
+ (-4.2916056095299737777, 2.1180339887498948482, 1.11351636441160673519),
387
+ (4.2916056095299737777, -2.1180339887498948482, -1.1135163644116066184),
388
+ (4.2916056095299737777, 2.1180339887498948482, -1.1135163644116066184),
389
+ (-3.6034146492943870399, 0, -3.3405490932348205213),
390
+ (3.6034146492943870399, 0, 3.3405490932348202056),
391
+ (-3.3405490932348205213, -3.4270509831248422723, 1.11351636441160673519),
392
+ (-3.3405490932348205213, 3.4270509831248422723, 1.11351636441160673519),
393
+ (3.3405490932348202056, -3.4270509831248422723, -1.1135163644116066184),
394
+ (3.3405490932348202056, 3.4270509831248422723, -1.1135163644116066184),
395
+ (-2.9152236890588002395, -2.1180339887498948482, 3.3405490932348202056),
396
+ (-2.9152236890588002395, 2.1180339887498948482, 3.3405490932348202056),
397
+ (2.9152236890588002395, -2.1180339887498948482, -3.3405490932348205213),
398
+ (2.9152236890588002395, 2.1180339887498948482, -3.3405490932348205213),
399
+ (-2.2270327288232132368, 0, -1.1135163644116066184),
400
+ (-2.2270327288232132368, -4.2360679774997896964, -1.1135163644116066184),
401
+ (-2.2270327288232132368, 4.2360679774997896964, -1.1135163644116066184),
402
+ (2.2270327288232134704, 0, 1.11351636441160673519),
403
+ (2.2270327288232134704, -4.2360679774997896964, 1.11351636441160673519),
404
+ (2.2270327288232134704, 4.2360679774997896964, 1.11351636441160673519),
405
+ (-1.8017073246471935200, -1.3090169943749474241, 1.11351636441160673519),
406
+ (-1.8017073246471935200, 1.3090169943749474241, 1.11351636441160673519),
407
+ (1.8017073246471935043, -1.3090169943749474241, -1.1135163644116066184),
408
+ (1.8017073246471935043, 1.3090169943749474241, -1.1135163644116066184),
409
+ (-1.3763819204711735382, 0, -4.7169310137059934362),
410
+ (-1.3763819204711735382, 0, 0.26286555605956679615),
411
+ (1.37638192047117353821, 0, 4.7169310137059937438),
412
+ (1.37638192047117353821, 0, -0.26286555605956679615),
413
+ (-1.1135163644116066184, -3.4270509831248422723, -3.3405490932348205213),
414
+ (-1.1135163644116066184, -0.8090169943749474241, 4.7169310137059937438),
415
+ (-1.1135163644116066184, -0.8090169943749474241, -0.26286555605956679615),
416
+ (-1.1135163644116066184, 0.8090169943749474241, 4.7169310137059937438),
417
+ (-1.1135163644116066184, 0.8090169943749474241, -0.26286555605956679615),
418
+ (-1.1135163644116066184, 3.4270509831248422723, -3.3405490932348205213),
419
+ (1.11351636441160673519, -3.4270509831248422723, 3.3405490932348202056),
420
+ (1.11351636441160673519, -0.8090169943749474241, -4.7169310137059934362),
421
+ (1.11351636441160673519, -0.8090169943749474241, 0.26286555605956679615),
422
+ (1.11351636441160673519, 0.8090169943749474241, -4.7169310137059934362),
423
+ (1.11351636441160673519, 0.8090169943749474241, 0.26286555605956679615),
424
+ (1.11351636441160673519, 3.4270509831248422723, 3.3405490932348202056),
425
+ (-0.85065080835203998877, 0, 1.11351636441160673519),
426
+ (0.85065080835203993218, 0, -1.1135163644116066184),
427
+ (-0.6881909602355867691, -0.5, -1.1135163644116066184),
428
+ (-0.6881909602355867691, 0.5, -1.1135163644116066184),
429
+ (-0.6881909602355867691, -4.7360679774997896964, -1.1135163644116066184),
430
+ (-0.6881909602355867691, -2.1180339887498948482, -1.1135163644116066184),
431
+ (-0.6881909602355867691, 2.1180339887498948482, -1.1135163644116066184),
432
+ (-0.6881909602355867691, 4.7360679774997896964, -1.1135163644116066184),
433
+ (0.68819096023558676910, -0.5, 1.11351636441160673519),
434
+ (0.68819096023558676910, 0.5, 1.11351636441160673519),
435
+ (0.68819096023558676910, -4.7360679774997896964, 1.11351636441160673519),
436
+ (0.68819096023558676910, -2.1180339887498948482, 1.11351636441160673519),
437
+ (0.68819096023558676910, 2.1180339887498948482, 1.11351636441160673519),
438
+ (0.68819096023558676910, 4.7360679774997896964, 1.11351636441160673519),
439
+ (-0.42532540417601993887, -1.3090169943749474241, -4.7169310137059934362),
440
+ (-0.42532540417601993887, -1.3090169943749474241, 0.26286555605956679615),
441
+ (-0.42532540417601993887, 1.3090169943749474241, -4.7169310137059934362),
442
+ (-0.42532540417601993887, 1.3090169943749474241, 0.26286555605956679615),
443
+ (-0.26286555605956679615, -0.8090169943749474241, 1.11351636441160673519),
444
+ (-0.26286555605956679615, 0.8090169943749474241, 1.11351636441160673519),
445
+ (0.26286555605956679615, -0.8090169943749474241, -1.1135163644116066184),
446
+ (0.26286555605956679615, 0.8090169943749474241, -1.1135163644116066184),
447
+ (0.42532540417601996609, -1.3090169943749474241, 4.7169310137059937438),
448
+ (0.42532540417601996609, -1.3090169943749474241, -0.26286555605956679615),
449
+ (0.42532540417601996609, 1.3090169943749474241, 4.7169310137059937438),
450
+ (0.42532540417601996609, 1.3090169943749474241, -0.26286555605956679615)],
451
+ [9, 66, 47], [44, 62, 77], [20, 91, 49], [33, 47, 83],
452
+ [3, 77, 84], [12, 49, 53], [36, 84, 66], [28, 53, 62],
453
+ [73, 83, 91], [15, 84, 46], [25, 64, 43], [16, 58, 72],
454
+ [26, 46, 51], [11, 43, 74], [4, 72, 91], [60, 74, 84],
455
+ [35, 91, 64], [23, 51, 58], [19, 74, 77], [79, 83, 78],
456
+ [6, 56, 40], [76, 77, 81], [21, 78, 75], [8, 40, 58],
457
+ [31, 75, 74], [42, 58, 83], [41, 81, 56], [13, 75, 43],
458
+ [27, 51, 47], [2, 89, 71], [24, 43, 62], [17, 47, 85],
459
+ [14, 71, 56], [65, 85, 75], [22, 56, 51], [34, 62, 89],
460
+ [5, 85, 78], [32, 81, 46], [10, 53, 48], [45, 78, 64],
461
+ [7, 46, 66], [18, 48, 89], [37, 66, 85], [70, 89, 81],
462
+ [29, 64, 53], [88, 74, 1], [38, 67, 48], [42, 83, 72],
463
+ [57, 1, 85], [34, 48, 62], [59, 72, 87], [19, 62, 74],
464
+ [63, 87, 67], [17, 85, 83], [52, 75, 1], [39, 87, 49],
465
+ [22, 51, 40], [55, 1, 66], [29, 49, 64], [30, 40, 69],
466
+ [13, 64, 75], [82, 69, 87], [7, 66, 51], [90, 85, 1],
467
+ [59, 69, 72], [70, 81, 71], [88, 1, 84], [73, 72, 83],
468
+ [54, 71, 68], [5, 83, 85], [50, 68, 69], [3, 84, 81],
469
+ [57, 66, 1], [30, 68, 40], [28, 62, 48], [52, 1, 74],
470
+ [23, 40, 51], [38, 48, 86], [9, 51, 66], [80, 86, 68],
471
+ [11, 74, 62], [55, 84, 1], [54, 86, 71], [35, 64, 49],
472
+ [90, 1, 75], [41, 71, 81], [39, 49, 67], [15, 81, 84],
473
+ [61, 67, 86], [21, 75, 64], [24, 53, 43], [50, 69, 0],
474
+ [37, 85, 47], [31, 43, 75], [61, 0, 67], [27, 47, 58],
475
+ [10, 67, 53], [8, 58, 69], [90, 75, 85], [45, 91, 78],
476
+ [80, 68, 0], [36, 66, 46], [65, 78, 85], [63, 0, 87],
477
+ [32, 46, 56], [20, 87, 91], [14, 56, 68], [57, 85, 66],
478
+ [33, 58, 47], [61, 86, 0], [60, 84, 77], [37, 47, 66],
479
+ [82, 0, 69], [44, 77, 89], [16, 69, 58], [18, 89, 86],
480
+ [55, 66, 84], [26, 56, 46], [63, 67, 0], [31, 74, 43],
481
+ [36, 46, 84], [50, 0, 68], [25, 43, 53], [6, 68, 56],
482
+ [12, 53, 67], [88, 84, 74], [76, 89, 77], [82, 87, 0],
483
+ [65, 75, 78], [60, 77, 74], [80, 0, 86], [79, 78, 91],
484
+ [2, 86, 89], [4, 91, 87], [52, 74, 75], [21, 64, 78],
485
+ [18, 86, 48], [23, 58, 40], [5, 78, 83], [28, 48, 53],
486
+ [6, 40, 68], [25, 53, 64], [54, 68, 86], [33, 83, 58],
487
+ [17, 83, 47], [12, 67, 49], [41, 56, 71], [9, 47, 51],
488
+ [35, 49, 91], [2, 71, 86], [79, 91, 83], [38, 86, 67],
489
+ [26, 51, 56], [7, 51, 46], [4, 87, 72], [34, 89, 48],
490
+ [15, 46, 81], [42, 72, 58], [10, 48, 67], [27, 58, 51],
491
+ [39, 67, 87], [76, 81, 89], [3, 81, 77], [8, 69, 40],
492
+ [29, 53, 49], [19, 77, 62], [22, 40, 56], [20, 49, 87],
493
+ [32, 56, 81], [59, 87, 69], [24, 62, 53], [11, 62, 43],
494
+ [14, 68, 71], [73, 91, 72], [13, 43, 64], [70, 71, 89],
495
+ [16, 72, 69], [44, 89, 62], [30, 69, 68], [45, 64, 91]]
496
+ # Actual volume is : 51.405764746872634
497
+ assert Abs(polytope_integrate(echidnahedron, 1) - 51.4057647468726) < 1e-12
498
+ assert Abs(polytope_integrate(echidnahedron, expr) - 253.569603474519) <\
499
+ 1e-12
500
+
501
+ # Tests for many polynomials with maximum degree given(2D case).
502
+ assert polytope_integrate(cube2, [x**2, y*z], max_degree=2) == \
503
+ {y * z: 3125 / S(4), x ** 2: 3125 / S(3)}
504
+
505
+ assert polytope_integrate(cube2, max_degree=2) == \
506
+ {1: 125, x: 625 / S(2), x * z: 3125 / S(4), y: 625 / S(2),
507
+ y * z: 3125 / S(4), z ** 2: 3125 / S(3), y ** 2: 3125 / S(3),
508
+ z: 625 / S(2), x * y: 3125 / S(4), x ** 2: 3125 / S(3)}
509
+
510
+ def test_point_sort():
511
+ assert point_sort([Point(0, 0), Point(1, 0), Point(1, 1)]) == \
512
+ [Point2D(1, 1), Point2D(1, 0), Point2D(0, 0)]
513
+
514
+ fig6 = Polygon((0, 0), (1, 0), (1, 1))
515
+ assert polytope_integrate(fig6, x*y) == Rational(-1, 8)
516
+ assert polytope_integrate(fig6, x*y, clockwise = True) == Rational(1, 8)
517
+
518
+
519
+ def test_polytopes_intersecting_sides():
520
+ fig5 = Polygon(Point(-4.165, -0.832), Point(-3.668, 1.568),
521
+ Point(-3.266, 1.279), Point(-1.090, -2.080),
522
+ Point(3.313, -0.683), Point(3.033, -4.845),
523
+ Point(-4.395, 4.840), Point(-1.007, -3.328))
524
+ assert polytope_integrate(fig5, x**2 + x*y + y**2) ==\
525
+ S(1633405224899363)/(24*10**12)
526
+
527
+ fig6 = Polygon(Point(-3.018, -4.473), Point(-0.103, 2.378),
528
+ Point(-1.605, -2.308), Point(4.516, -0.771),
529
+ Point(4.203, 0.478))
530
+ assert polytope_integrate(fig6, x**2 + x*y + y**2) ==\
531
+ S(88161333955921)/(3*10**12)
532
+
533
+
534
+ def test_max_degree():
535
+ polygon = Polygon((0, 0), (0, 1), (1, 1), (1, 0))
536
+ polys = [1, x, y, x*y, x**2*y, x*y**2]
537
+ assert polytope_integrate(polygon, polys, max_degree=3) == \
538
+ {1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)}
539
+ assert polytope_integrate(polygon, polys, max_degree=2) == \
540
+ {1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4)}
541
+ assert polytope_integrate(polygon, polys, max_degree=1) == \
542
+ {1: 1, x: S.Half, y: S.Half}
543
+
544
+
545
+ def test_main_integrate3d():
546
+ cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
547
+ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\
548
+ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
549
+ [3, 1, 0, 2], [0, 4, 6, 2]]
550
+ vertices = cube[0]
551
+ faces = cube[1:]
552
+ hp_params = hyperplane_parameters(faces, vertices)
553
+ assert main_integrate3d(1, faces, vertices, hp_params) == -125
554
+ assert main_integrate3d(1, faces, vertices, hp_params, max_degree=1) == \
555
+ {1: -125, y: Rational(-625, 2), z: Rational(-625, 2), x: Rational(-625, 2)}
556
+
557
+
558
+ def test_main_integrate():
559
+ triangle = Polygon((0, 3), (5, 3), (1, 1))
560
+ facets = triangle.sides
561
+ hp_params = hyperplane_parameters(triangle)
562
+ assert main_integrate(x**2 + y**2, facets, hp_params) == Rational(325, 6)
563
+ assert main_integrate(x**2 + y**2, facets, hp_params, max_degree=1) == \
564
+ {0: 0, 1: 5, y: Rational(35, 3), x: 10}
565
+
566
+
567
+ def test_polygon_integrate():
568
+ cube = [[(0, 0, 0), (0, 0, 5), (0, 5, 0), (0, 5, 5), (5, 0, 0),\
569
+ (5, 0, 5), (5, 5, 0), (5, 5, 5)],\
570
+ [2, 6, 7, 3], [3, 7, 5, 1], [7, 6, 4, 5], [1, 5, 4, 0],\
571
+ [3, 1, 0, 2], [0, 4, 6, 2]]
572
+ facet = cube[1]
573
+ facets = cube[1:]
574
+ vertices = cube[0]
575
+ assert polygon_integrate(facet, [(0, 1, 0), 5], 0, facets, vertices, 1, 0) == -25
576
+
577
+
578
+ def test_distance_to_side():
579
+ point = (0, 0, 0)
580
+ assert distance_to_side(point, [(0, 0, 1), (0, 1, 0)], (1, 0, 0)) == -sqrt(2)/2
581
+
582
+
583
+ def test_lineseg_integrate():
584
+ polygon = [(0, 5, 0), (5, 5, 0), (5, 5, 5), (0, 5, 5)]
585
+ line_seg = [(0, 5, 0), (5, 5, 0)]
586
+ assert lineseg_integrate(polygon, 0, line_seg, 1, 0) == 5
587
+ assert lineseg_integrate(polygon, 0, line_seg, 0, 0) == 0
588
+
589
+
590
+ def test_integration_reduction():
591
+ triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
592
+ facets = triangle.sides
593
+ a, b = hyperplane_parameters(triangle)[0]
594
+ assert integration_reduction(facets, 0, a, b, 1, (x, y), 0) == 5
595
+ assert integration_reduction(facets, 0, a, b, 0, (x, y), 0) == 0
596
+
597
+
598
+ def test_integration_reduction_dynamic():
599
+ triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))
600
+ facets = triangle.sides
601
+ a, b = hyperplane_parameters(triangle)[0]
602
+ x0 = facets[0].points[0]
603
+ monomial_values = [[0, 0, 0, 0], [1, 0, 0, 5],\
604
+ [y, 0, 1, 15], [x, 1, 0, None]]
605
+
606
+ assert integration_reduction_dynamic(facets, 0, a, b, x, 1, (x, y), 1,\
607
+ 0, 1, x0, monomial_values, 3) == Rational(25, 2)
608
+ assert integration_reduction_dynamic(facets, 0, a, b, 0, 1, (x, y), 1,\
609
+ 0, 1, x0, monomial_values, 3) == 0
610
+
611
+
612
+ def test_is_vertex():
613
+ assert is_vertex(2) is False
614
+ assert is_vertex((2, 3)) is True
615
+ assert is_vertex(Point(2, 3)) is True
616
+ assert is_vertex((2, 3, 4)) is True
617
+ assert is_vertex((2, 3, 4, 5)) is False
618
+
619
+
620
+ def test_issue_19234():
621
+ polygon = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0))
622
+ polys = [ 1, x, y, x*y, x**2*y, x*y**2]
623
+ assert polytope_integrate(polygon, polys) == \
624
+ {1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y: Rational(1, 6), x*y**2: Rational(1, 6)}
625
+ polys = [ 1, x, y, x*y, 3 + x**2*y, x + x*y**2]
626
+ assert polytope_integrate(polygon, polys) == \
627
+ {1: 1, x: S.Half, y: S.Half, x*y: Rational(1, 4), x**2*y + 3: Rational(19, 6), x*y**2 + x: Rational(2, 3)}
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_laplace.py ADDED
@@ -0,0 +1,769 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.integrals.laplace import (
2
+ laplace_transform, inverse_laplace_transform,
3
+ LaplaceTransform, InverseLaplaceTransform,
4
+ _laplace_deep_collect, laplace_correspondence,
5
+ laplace_initial_conds)
6
+ from sympy.core.function import Function, expand_mul
7
+ from sympy.core import EulerGamma, Subs, Derivative, diff
8
+ from sympy.core.exprtools import factor_terms
9
+ from sympy.core.numbers import I, oo, pi
10
+ from sympy.core.relational import Eq
11
+ from sympy.core.singleton import S
12
+ from sympy.core.symbol import Symbol, symbols
13
+ from sympy.simplify.simplify import simplify
14
+ from sympy.functions.elementary.complexes import Abs, re
15
+ from sympy.functions.elementary.exponential import exp, log, exp_polar
16
+ from sympy.functions.elementary.hyperbolic import cosh, sinh, coth, asinh
17
+ from sympy.functions.elementary.miscellaneous import sqrt
18
+ from sympy.functions.elementary.piecewise import Piecewise
19
+ from sympy.functions.elementary.trigonometric import atan, cos, sin
20
+ from sympy.logic.boolalg import And
21
+ from sympy.functions.special.gamma_functions import (
22
+ lowergamma, gamma, uppergamma)
23
+ from sympy.functions.special.delta_functions import DiracDelta, Heaviside
24
+ from sympy.functions.special.singularity_functions import SingularityFunction
25
+ from sympy.functions.special.zeta_functions import lerchphi
26
+ from sympy.functions.special.error_functions import (
27
+ fresnelc, fresnels, erf, erfc, Ei, Ci, expint, E1)
28
+ from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
29
+ from sympy.testing.pytest import slow, warns_deprecated_sympy
30
+ from sympy.matrices import Matrix, eye
31
+ from sympy.abc import s
32
+
33
+
34
+ @slow
35
+ def test_laplace_transform():
36
+ LT = laplace_transform
37
+ ILT = inverse_laplace_transform
38
+ a, b, c = symbols('a, b, c', positive=True)
39
+ np = symbols('np', integer=True, positive=True)
40
+ t, w, x = symbols('t, w, x')
41
+ f = Function('f')
42
+ F = Function('F')
43
+ g = Function('g')
44
+ y = Function('y')
45
+ Y = Function('Y')
46
+
47
+ # Test helper functions
48
+ assert (
49
+ _laplace_deep_collect(exp((t+a)*(t+b)) +
50
+ besselj(2, exp((t+a)*(t+b)-t**2)), t) ==
51
+ exp(a*b + t**2 + t*(a + b)) + besselj(2, exp(a*b + t*(a + b))))
52
+ L = laplace_transform(diff(y(t), t, 3), t, s, noconds=True)
53
+ L = laplace_correspondence(L, {y: Y})
54
+ L = laplace_initial_conds(L, t, {y: [2, 4, 8, 16, 32]})
55
+ assert L == s**3*Y(s) - 2*s**2 - 4*s - 8
56
+ # Test whether `noconds=True` in `doit`:
57
+ assert (2*LaplaceTransform(exp(t), t, s) - 1).doit() == -1 + 2/(s - 1)
58
+ assert (LT(a*t+t**2+t**(S(5)/2), t, s) ==
59
+ (a/s**2 + 2/s**3 + 15*sqrt(pi)/(8*s**(S(7)/2)), 0, True))
60
+ assert LT(b/(t+a), t, s) == (-b*exp(-a*s)*Ei(-a*s), 0, True)
61
+ assert (LT(1/sqrt(t+a), t, s) ==
62
+ (sqrt(pi)*sqrt(1/s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True))
63
+ assert (LT(sqrt(t)/(t+a), t, s) ==
64
+ (-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
65
+ 0, True))
66
+ assert (LT((t+a)**(-S(3)/2), t, s) ==
67
+ (-2*sqrt(pi)*sqrt(s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + 2/sqrt(a),
68
+ 0, True))
69
+ assert (LT(t**(S(1)/2)*(t+a)**(-1), t, s) ==
70
+ (-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s),
71
+ 0, True))
72
+ assert (LT(1/(a*sqrt(t) + t**(3/2)), t, s) ==
73
+ (pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True))
74
+ assert (LT((t+a)**b, t, s) ==
75
+ (s**(-b - 1)*exp(-a*s)*uppergamma(b + 1, a*s), 0, True))
76
+ assert LT(t**5/(t+a), t, s) == (120*a**5*uppergamma(-5, a*s), 0, True)
77
+ assert LT(exp(t), t, s) == (1/(s - 1), 1, True)
78
+ assert LT(exp(2*t), t, s) == (1/(s - 2), 2, True)
79
+ assert LT(exp(a*t), t, s) == (1/(s - a), a, True)
80
+ assert LT(exp(a*(t-b)), t, s) == (exp(-a*b)/(-a + s), a, True)
81
+ assert LT(t*exp(-a*(t)), t, s) == ((a + s)**(-2), -a, True)
82
+ assert LT(t*exp(-a*(t-b)), t, s) == (exp(a*b)/(a + s)**2, -a, True)
83
+ assert LT(b*t*exp(-a*t), t, s) == (b/(a + s)**2, -a, True)
84
+ assert LT(exp(-a*exp(-t)), t, s) == (lowergamma(s, a)/a**s, 0, True)
85
+ assert LT(exp(-a*exp(t)), t, s) == (a**s*uppergamma(-s, a), 0, True)
86
+ assert (LT(t**(S(7)/4)*exp(-8*t)/gamma(S(11)/4), t, s) ==
87
+ ((s + 8)**(-S(11)/4), -8, True))
88
+ assert (LT(t**(S(3)/2)*exp(-8*t), t, s) ==
89
+ (3*sqrt(pi)/(4*(s + 8)**(S(5)/2)), -8, True))
90
+ assert LT(t**a*exp(-a*t), t, s) == ((a+s)**(-a-1)*gamma(a+1), -a, True)
91
+ assert (LT(b*exp(-a*t**2), t, s) ==
92
+ (sqrt(pi)*b*exp(s**2/(4*a))*erfc(s/(2*sqrt(a)))/(2*sqrt(a)),
93
+ 0, True))
94
+ assert (LT(exp(-2*t**2), t, s) ==
95
+ (sqrt(2)*sqrt(pi)*exp(s**2/8)*erfc(sqrt(2)*s/4)/4, 0, True))
96
+ assert (LT(b*exp(2*t**2), t, s) ==
97
+ (b*LaplaceTransform(exp(2*t**2), t, s), -oo, True))
98
+ assert (LT(t*exp(-a*t**2), t, s) ==
99
+ (1/(2*a) - s*erfc(s/(2*sqrt(a)))/(4*sqrt(pi)*a**(S(3)/2)),
100
+ 0, True))
101
+ assert (LT(exp(-a/t), t, s) ==
102
+ (2*sqrt(a)*sqrt(1/s)*besselk(1, 2*sqrt(a)*sqrt(s)), 0, True))
103
+ assert LT(sqrt(t)*exp(-a/t), t, s, simplify=True) == (
104
+ sqrt(pi)*(sqrt(a)*sqrt(s) + 1/S(2))*sqrt(s**(-3)) *
105
+ exp(-2*sqrt(a)*sqrt(s)), 0, True)
106
+ assert (LT(exp(-a/t)/sqrt(t), t, s) ==
107
+ (sqrt(pi)*sqrt(1/s)*exp(-2*sqrt(a)*sqrt(s)), 0, True))
108
+ assert (LT(exp(-a/t)/(t*sqrt(t)), t, s) ==
109
+ (sqrt(pi)*sqrt(1/a)*exp(-2*sqrt(a)*sqrt(s)), 0, True))
110
+ assert (
111
+ LT(exp(-2*sqrt(a*t)), t, s) ==
112
+ (1/s - sqrt(pi)*sqrt(a) * exp(a/s)*erfc(sqrt(a)*sqrt(1/s)) /
113
+ s**(S(3)/2), 0, True))
114
+ assert LT(exp(-2*sqrt(a*t))/sqrt(t), t, s) == (
115
+ exp(a/s)*erfc(sqrt(a) * sqrt(1/s))*(sqrt(pi)*sqrt(1/s)), 0, True)
116
+ assert (LT(t**4*exp(-2/t), t, s) ==
117
+ (8*sqrt(2)*(1/s)**(S(5)/2)*besselk(5, 2*sqrt(2)*sqrt(s)),
118
+ 0, True))
119
+ assert LT(sinh(a*t), t, s) == (a/(-a**2 + s**2), a, True)
120
+ assert (LT(b*sinh(a*t)**2, t, s) ==
121
+ (2*a**2*b/(-4*a**2*s + s**3), 2*a, True))
122
+ assert (LT(b*sinh(a*t)**2, t, s, simplify=True) ==
123
+ (2*a**2*b/(s*(-4*a**2 + s**2)), 2*a, True))
124
+ # The following line confirms that issue #21202 is solved
125
+ assert LT(cosh(2*t), t, s) == (s/(-4 + s**2), 2, True)
126
+ assert LT(cosh(a*t), t, s) == (s/(-a**2 + s**2), a, True)
127
+ assert (LT(cosh(a*t)**2, t, s, simplify=True) ==
128
+ ((2*a**2 - s**2)/(s*(4*a**2 - s**2)), 2*a, True))
129
+ assert (LT(sinh(x+3), x, s, simplify=True) ==
130
+ ((s*sinh(3) + cosh(3))/(s**2 - 1), 1, True))
131
+ L, _, _ = LT(42*sin(w*t+x)**2, t, s)
132
+ assert (
133
+ L -
134
+ 21*(s**2 + s*(-s*cos(2*x) + 2*w*sin(2*x)) +
135
+ 4*w**2)/(s*(s**2 + 4*w**2))).simplify() == 0
136
+ # The following line replaces the old test test_issue_7173()
137
+ assert LT(sinh(a*t)*cosh(a*t), t, s, simplify=True) == (a/(-4*a**2 + s**2),
138
+ 2*a, True)
139
+ assert LT(sinh(a*t)/t, t, s) == (log((a + s)/(-a + s))/2, a, True)
140
+ assert (LT(t**(-S(3)/2)*sinh(a*t), t, s) ==
141
+ (-sqrt(pi)*(sqrt(-a + s) - sqrt(a + s)), a, True))
142
+ assert (LT(sinh(2*sqrt(a*t)), t, s) ==
143
+ (sqrt(pi)*sqrt(a)*exp(a/s)/s**(S(3)/2), 0, True))
144
+ assert (LT(sqrt(t)*sinh(2*sqrt(a*t)), t, s, simplify=True) ==
145
+ ((-sqrt(a)*s**(S(5)/2) + sqrt(pi)*s**2*(2*a + s)*exp(a/s) *
146
+ erf(sqrt(a)*sqrt(1/s))/2)/s**(S(9)/2), 0, True))
147
+ assert (LT(sinh(2*sqrt(a*t))/sqrt(t), t, s) ==
148
+ (sqrt(pi)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/sqrt(s), 0, True))
149
+ assert (LT(sinh(sqrt(a*t))**2/sqrt(t), t, s) ==
150
+ (sqrt(pi)*(exp(a/s) - 1)/(2*sqrt(s)), 0, True))
151
+ assert (LT(t**(S(3)/7)*cosh(a*t), t, s) ==
152
+ (((a + s)**(-S(10)/7) + (-a+s)**(-S(10)/7))*gamma(S(10)/7)/2,
153
+ a, True))
154
+ assert (LT(cosh(2*sqrt(a*t)), t, s) ==
155
+ (sqrt(pi)*sqrt(a)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/s**(S(3)/2) +
156
+ 1/s, 0, True))
157
+ assert (LT(sqrt(t)*cosh(2*sqrt(a*t)), t, s) ==
158
+ (sqrt(pi)*(a + s/2)*exp(a/s)/s**(S(5)/2), 0, True))
159
+ assert (LT(cosh(2*sqrt(a*t))/sqrt(t), t, s) ==
160
+ (sqrt(pi)*exp(a/s)/sqrt(s), 0, True))
161
+ assert (LT(cosh(sqrt(a*t))**2/sqrt(t), t, s) ==
162
+ (sqrt(pi)*(exp(a/s) + 1)/(2*sqrt(s)), 0, True))
163
+ assert LT(log(t), t, s, simplify=True) == (
164
+ (-log(s) - EulerGamma)/s, 0, True)
165
+ assert (LT(-log(t/a), t, s, simplify=True) ==
166
+ ((log(a) + log(s) + EulerGamma)/s, 0, True))
167
+ assert LT(log(1+a*t), t, s) == (-exp(s/a)*Ei(-s/a)/s, 0, True)
168
+ assert (LT(log(t+a), t, s, simplify=True) ==
169
+ ((s*log(a) - exp(s/a)*Ei(-s/a))/s**2, 0, True))
170
+ assert (LT(log(t)/sqrt(t), t, s, simplify=True) ==
171
+ (sqrt(pi)*(-log(s) - log(4) - EulerGamma)/sqrt(s), 0, True))
172
+ assert (LT(t**(S(5)/2)*log(t), t, s, simplify=True) ==
173
+ (sqrt(pi)*(-15*log(s) - log(1073741824) - 15*EulerGamma + 46) /
174
+ (8*s**(S(7)/2)), 0, True))
175
+ assert (LT(t**3*log(t), t, s, noconds=True, simplify=True) -
176
+ 6*(-log(s) - S.EulerGamma + S(11)/6)/s**4).simplify() == S.Zero
177
+ assert (LT(log(t)**2, t, s, simplify=True) ==
178
+ (((log(s) + EulerGamma)**2 + pi**2/6)/s, 0, True))
179
+ assert (LT(exp(-a*t)*log(t), t, s, simplify=True) ==
180
+ ((-log(a + s) - EulerGamma)/(a + s), -a, True))
181
+ assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True)
182
+ assert (LT(Abs(sin(a*t)), t, s) ==
183
+ (a*coth(pi*s/(2*a))/(a**2 + s**2), 0, True))
184
+ assert LT(sin(a*t)/t, t, s) == (atan(a/s), 0, True)
185
+ assert LT(sin(a*t)**2/t, t, s) == (log(4*a**2/s**2 + 1)/4, 0, True)
186
+ assert (LT(sin(a*t)**2/t**2, t, s) ==
187
+ (a*atan(2*a/s) - s*log(4*a**2/s**2 + 1)/4, 0, True))
188
+ assert (LT(sin(2*sqrt(a*t)), t, s) ==
189
+ (sqrt(pi)*sqrt(a)*exp(-a/s)/s**(S(3)/2), 0, True))
190
+ assert LT(sin(2*sqrt(a*t))/t, t, s) == (pi*erf(sqrt(a)*sqrt(1/s)), 0, True)
191
+ assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True)
192
+ assert (LT(cos(a*t)**2, t, s) ==
193
+ ((2*a**2 + s**2)/(s*(4*a**2 + s**2)), 0, True))
194
+ assert (LT(sqrt(t)*cos(2*sqrt(a*t)), t, s, simplify=True) ==
195
+ (sqrt(pi)*(-a + s/2)*exp(-a/s)/s**(S(5)/2), 0, True))
196
+ assert (LT(cos(2*sqrt(a*t))/sqrt(t), t, s) ==
197
+ (sqrt(pi)*sqrt(1/s)*exp(-a/s), 0, True))
198
+ assert (LT(sin(a*t)*sin(b*t), t, s) ==
199
+ (2*a*b*s/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True))
200
+ assert (LT(cos(a*t)*sin(b*t), t, s) ==
201
+ (b*(-a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
202
+ 0, True))
203
+ assert (LT(cos(a*t)*cos(b*t), t, s) ==
204
+ (s*(a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)),
205
+ 0, True))
206
+ assert (LT(-a*t*cos(a*t) + sin(a*t), t, s, simplify=True) ==
207
+ (2*a**3/(a**4 + 2*a**2*s**2 + s**4), 0, True))
208
+ assert LT(c*exp(-b*t)*sin(a*t), t, s) == (a *
209
+ c/(a**2 + (b + s)**2), -b, True)
210
+ assert LT(c*exp(-b*t)*cos(a*t), t, s) == (c*(b + s)/(a**2 + (b + s)**2),
211
+ -b, True)
212
+ L, plane, cond = LT(cos(x + 3), x, s, simplify=True)
213
+ assert plane == 0
214
+ assert L - (s*cos(3) - sin(3))/(s**2 + 1) == 0
215
+ # Error functions (laplace7.pdf)
216
+ assert LT(erf(a*t), t, s) == (exp(s**2/(4*a**2))*erfc(s/(2*a))/s, 0, True)
217
+ assert LT(erf(sqrt(a*t)), t, s) == (sqrt(a)/(s*sqrt(a + s)), 0, True)
218
+ assert (LT(exp(a*t)*erf(sqrt(a*t)), t, s, simplify=True) ==
219
+ (-sqrt(a)/(sqrt(s)*(a - s)), a, True))
220
+ assert (LT(erf(sqrt(a/t)/2), t, s, simplify=True) ==
221
+ (1/s - exp(-sqrt(a)*sqrt(s))/s, 0, True))
222
+ assert (LT(erfc(sqrt(a*t)), t, s, simplify=True) ==
223
+ (-sqrt(a)/(s*sqrt(a + s)) + 1/s, -a, True))
224
+ assert (LT(exp(a*t)*erfc(sqrt(a*t)), t, s) ==
225
+ (1/(sqrt(a)*sqrt(s) + s), 0, True))
226
+ assert LT(erfc(sqrt(a/t)/2), t, s) == (exp(-sqrt(a)*sqrt(s))/s, 0, True)
227
+ # Bessel functions (laplace8.pdf)
228
+ assert LT(besselj(0, a*t), t, s) == (1/sqrt(a**2 + s**2), 0, True)
229
+ assert (LT(besselj(1, a*t), t, s, simplify=True) ==
230
+ (a/(a**2 + s**2 + s*sqrt(a**2 + s**2)), 0, True))
231
+ assert (LT(besselj(2, a*t), t, s, simplify=True) ==
232
+ (a**2/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))**2), 0, True))
233
+ assert (LT(t*besselj(0, a*t), t, s) ==
234
+ (s/(a**2 + s**2)**(S(3)/2), 0, True))
235
+ assert (LT(t*besselj(1, a*t), t, s) ==
236
+ (a/(a**2 + s**2)**(S(3)/2), 0, True))
237
+ assert (LT(t**2*besselj(2, a*t), t, s) ==
238
+ (3*a**2/(a**2 + s**2)**(S(5)/2), 0, True))
239
+ assert LT(besselj(0, 2*sqrt(a*t)), t, s) == (exp(-a/s)/s, 0, True)
240
+ assert (LT(t**(S(3)/2)*besselj(3, 2*sqrt(a*t)), t, s) ==
241
+ (a**(S(3)/2)*exp(-a/s)/s**4, 0, True))
242
+ assert (LT(besselj(0, a*sqrt(t**2+b*t)), t, s, simplify=True) ==
243
+ (exp(b*(s - sqrt(a**2 + s**2)))/sqrt(a**2 + s**2), 0, True))
244
+ assert LT(besseli(0, a*t), t, s) == (1/sqrt(-a**2 + s**2), a, True)
245
+ assert (LT(besseli(1, a*t), t, s, simplify=True) ==
246
+ (a/(-a**2 + s**2 + s*sqrt(-a**2 + s**2)), a, True))
247
+ assert (LT(besseli(2, a*t), t, s, simplify=True) ==
248
+ (a**2/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))**2), a, True))
249
+ assert LT(t*besseli(0, a*t), t, s) == (s/(-a**2 + s**2)**(S(3)/2), a, True)
250
+ assert LT(t*besseli(1, a*t), t, s) == (a/(-a**2 + s**2)**(S(3)/2), a, True)
251
+ assert (LT(t**2*besseli(2, a*t), t, s) ==
252
+ (3*a**2/(-a**2 + s**2)**(S(5)/2), a, True))
253
+ assert (LT(t**(S(3)/2)*besseli(3, 2*sqrt(a*t)), t, s) ==
254
+ (a**(S(3)/2)*exp(a/s)/s**4, 0, True))
255
+ assert (LT(bessely(0, a*t), t, s) ==
256
+ (-2*asinh(s/a)/(pi*sqrt(a**2 + s**2)), 0, True))
257
+ assert (LT(besselk(0, a*t), t, s) ==
258
+ (log((s + sqrt(-a**2 + s**2))/a)/sqrt(-a**2 + s**2), -a, True))
259
+ assert (LT(sin(a*t)**4, t, s, simplify=True) ==
260
+ (24*a**4/(s*(64*a**4 + 20*a**2*s**2 + s**4)), 0, True))
261
+ # Test general rules and unevaluated forms
262
+ # These all also test whether issue #7219 is solved.
263
+ assert LT(Heaviside(t-1)*cos(t-1), t, s) == (s*exp(-s)/(s**2 + 1), 0, True)
264
+ assert LT(a*f(t), t, w) == (a*LaplaceTransform(f(t), t, w), -oo, True)
265
+ assert (LT(a*Heaviside(t+1)*f(t+1), t, s) ==
266
+ (a*LaplaceTransform(f(t + 1), t, s), -oo, True))
267
+ assert (LT(a*Heaviside(t-1)*f(t-1), t, s) ==
268
+ (a*LaplaceTransform(f(t), t, s)*exp(-s), -oo, True))
269
+ assert (LT(b*f(t/a), t, s) ==
270
+ (a*b*LaplaceTransform(f(t), t, a*s), -oo, True))
271
+ assert LT(exp(-f(x)*t), t, s) == (1/(s + f(x)), -re(f(x)), True)
272
+ assert (LT(exp(-a*t)*f(t), t, s) ==
273
+ (LaplaceTransform(f(t), t, a + s), -oo, True))
274
+ assert (LT(exp(-a*t)*erfc(sqrt(b/t)/2), t, s) ==
275
+ (exp(-sqrt(b)*sqrt(a + s))/(a + s), -a, True))
276
+ assert (LT(sinh(a*t)*f(t), t, s) ==
277
+ (LaplaceTransform(f(t), t, -a + s)/2 -
278
+ LaplaceTransform(f(t), t, a + s)/2, -oo, True))
279
+ assert (LT(sinh(a*t)*t, t, s, simplify=True) ==
280
+ (2*a*s/(a**4 - 2*a**2*s**2 + s**4), a, True))
281
+ assert (LT(cosh(a*t)*f(t), t, s) ==
282
+ (LaplaceTransform(f(t), t, -a + s)/2 +
283
+ LaplaceTransform(f(t), t, a + s)/2, -oo, True))
284
+ assert (LT(cosh(a*t)*t, t, s, simplify=True) ==
285
+ (1/(2*(a + s)**2) + 1/(2*(a - s)**2), a, True))
286
+ assert (LT(sin(a*t)*f(t), t, s, simplify=True) ==
287
+ (I*(-LaplaceTransform(f(t), t, -I*a + s) +
288
+ LaplaceTransform(f(t), t, I*a + s))/2, -oo, True))
289
+ assert (LT(sin(f(t)), t, s) ==
290
+ (LaplaceTransform(sin(f(t)), t, s), -oo, True))
291
+ assert (LT(sin(a*t)*t, t, s, simplify=True) ==
292
+ (2*a*s/(a**4 + 2*a**2*s**2 + s**4), 0, True))
293
+ assert (LT(cos(a*t)*f(t), t, s) ==
294
+ (LaplaceTransform(f(t), t, -I*a + s)/2 +
295
+ LaplaceTransform(f(t), t, I*a + s)/2, -oo, True))
296
+ assert (LT(cos(a*t)*t, t, s, simplify=True) ==
297
+ ((-a**2 + s**2)/(a**4 + 2*a**2*s**2 + s**4), 0, True))
298
+ L, plane, _ = LT(sin(a*t+b)**2*f(t), t, s)
299
+ assert plane == -oo
300
+ assert (
301
+ -L + (
302
+ LaplaceTransform(f(t), t, s)/2 -
303
+ LaplaceTransform(f(t), t, -2*I*a + s)*exp(2*I*b)/4 -
304
+ LaplaceTransform(f(t), t, 2*I*a + s)*exp(-2*I*b)/4)) == 0
305
+ L = LT(sin(a*t+b)**2*f(t), t, s, noconds=True)
306
+ assert (
307
+ laplace_correspondence(L, {f: F}) ==
308
+ F(s)/2 - F(-2*I*a + s)*exp(2*I*b)/4 -
309
+ F(2*I*a + s)*exp(-2*I*b)/4)
310
+ L, plane, _ = LT(sin(a*t)**3*cosh(b*t), t, s)
311
+ assert plane == b
312
+ assert (
313
+ -L - 3*a/(8*(9*a**2 + b**2 + 2*b*s + s**2)) -
314
+ 3*a/(8*(9*a**2 + b**2 - 2*b*s + s**2)) +
315
+ 3*a/(8*(a**2 + b**2 + 2*b*s + s**2)) +
316
+ 3*a/(8*(a**2 + b**2 - 2*b*s + s**2))).simplify() == 0
317
+ assert (LT(t**2*exp(-t**2), t, s) ==
318
+ (sqrt(pi)*s**2*exp(s**2/4)*erfc(s/2)/8 - s/4 +
319
+ sqrt(pi)*exp(s**2/4)*erfc(s/2)/4, 0, True))
320
+ assert (LT((a*t**2 + b*t + c)*f(t), t, s) ==
321
+ (a*Derivative(LaplaceTransform(f(t), t, s), (s, 2)) -
322
+ b*Derivative(LaplaceTransform(f(t), t, s), s) +
323
+ c*LaplaceTransform(f(t), t, s), -oo, True))
324
+ assert (LT(t**np*g(t), t, s) ==
325
+ ((-1)**np*Derivative(LaplaceTransform(g(t), t, s), (s, np)),
326
+ -oo, True))
327
+ # The following tests check whether _piecewise_to_heaviside works:
328
+ x1 = Piecewise((0, t <= 0), (1, t <= 1), (0, True))
329
+ X1 = LT(x1, t, s)[0]
330
+ assert X1 == 1/s - exp(-s)/s
331
+ y1 = ILT(X1, s, t)
332
+ assert y1 == Heaviside(t) - Heaviside(t - 1)
333
+ x1 = Piecewise((0, t <= 0), (t, t <= 1), (2-t, t <= 2), (0, True))
334
+ X1 = LT(x1, t, s)[0].simplify()
335
+ assert X1 == (exp(2*s) - 2*exp(s) + 1)*exp(-2*s)/s**2
336
+ y1 = ILT(X1, s, t)
337
+ assert (
338
+ -y1 + t*Heaviside(t) + (t - 2)*Heaviside(t - 2) -
339
+ 2*(t - 1)*Heaviside(t - 1)).simplify() == 0
340
+ x1 = Piecewise((exp(t), t <= 0), (1, t <= 1), (exp(-(t)), True))
341
+ X1 = LT(x1, t, s)[0]
342
+ assert X1 == exp(-1)*exp(-s)/(s + 1) + 1/s - exp(-s)/s
343
+ y1 = ILT(X1, s, t)
344
+ assert y1 == (
345
+ exp(-1)*exp(1 - t)*Heaviside(t - 1) + Heaviside(t) - Heaviside(t - 1))
346
+ x1 = Piecewise((0, x <= 0), (1, x <= 1), (0, True))
347
+ X1 = LT(x1, t, s)[0]
348
+ assert X1 == Piecewise((0, x <= 0), (1, x <= 1), (0, True))/s
349
+ x1 = [
350
+ a*Piecewise((1, And(t > 1, t <= 3)), (2, True)),
351
+ a*Piecewise((1, And(t >= 1, t <= 3)), (2, True)),
352
+ a*Piecewise((1, And(t >= 1, t < 3)), (2, True)),
353
+ a*Piecewise((1, And(t > 1, t < 3)), (2, True))]
354
+ for x2 in x1:
355
+ assert LT(x2, t, s)[0].expand() == 2*a/s - a*exp(-s)/s + a*exp(-3*s)/s
356
+ assert (
357
+ LT(Piecewise((1, Eq(t, 1)), (2, True)), t, s)[0] ==
358
+ LaplaceTransform(Piecewise((1, Eq(t, 1)), (2, True)), t, s))
359
+ # The following lines test whether _laplace_transform successfully
360
+ # removes Heaviside(1) before processing espressions. It fails if
361
+ # Heaviside(t) remains because then meijerg functions will appear.
362
+ X1 = 1/sqrt(a*s**2-b)
363
+ x1 = ILT(X1, s, t)
364
+ Y1 = LT(x1, t, s)[0]
365
+ Z1 = (Y1**2/X1**2).simplify()
366
+ assert Z1 == 1
367
+ # The following two lines test whether issues #5813 and #7176 are solved.
368
+ assert (LT(diff(f(t), (t, 1)), t, s, noconds=True) ==
369
+ s*LaplaceTransform(f(t), t, s) - f(0))
370
+ assert (LT(diff(f(t), (t, 3)), t, s, noconds=True) ==
371
+ s**3*LaplaceTransform(f(t), t, s) - s**2*f(0) -
372
+ s*Subs(Derivative(f(t), t), t, 0) -
373
+ Subs(Derivative(f(t), (t, 2)), t, 0))
374
+ # Issue #7219
375
+ assert (LT(diff(f(x, t, w), t, 2), t, s) ==
376
+ (s**2*LaplaceTransform(f(x, t, w), t, s) - s*f(x, 0, w) -
377
+ Subs(Derivative(f(x, t, w), t), t, 0), -oo, True))
378
+ # Issue #23307
379
+ assert (LT(10*diff(f(t), (t, 1)), t, s, noconds=True) ==
380
+ 10*s*LaplaceTransform(f(t), t, s) - 10*f(0))
381
+ assert (LT(a*f(b*t)+g(c*t), t, s, noconds=True) ==
382
+ a*LaplaceTransform(f(t), t, s/b)/b +
383
+ LaplaceTransform(g(t), t, s/c)/c)
384
+ assert inverse_laplace_transform(
385
+ f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0)
386
+ assert (LT(f(t)*g(t), t, s, noconds=True) ==
387
+ LaplaceTransform(f(t)*g(t), t, s))
388
+ # Issue #24294
389
+ assert (LT(b*f(a*t), t, s, noconds=True) ==
390
+ b*LaplaceTransform(f(t), t, s/a)/a)
391
+ assert LT(3*exp(t)*Heaviside(t), t, s) == (3/(s - 1), 1, True)
392
+ assert (LT(2*sin(t)*Heaviside(t), t, s, simplify=True) ==
393
+ (2/(s**2 + 1), 0, True))
394
+ # Issue #25293
395
+ assert (
396
+ LT((1/(t-1))*sin(4*pi*(t-1))*DiracDelta(t-1) *
397
+ (Heaviside(t-1/4) - Heaviside(t-2)), t, s)[0] == 4*pi*exp(-s))
398
+ # additional basic tests from wikipedia
399
+ assert (LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) ==
400
+ ((c + s)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True))
401
+ assert (
402
+ LT((exp(2*t)-1)*exp(-b-t)*Heaviside(t)/2, t, s, noconds=True,
403
+ simplify=True) ==
404
+ exp(-b)/(s**2 - 1))
405
+ # DiracDelta function: standard cases
406
+ assert LT(DiracDelta(t), t, s) == (1, -oo, True)
407
+ assert LT(DiracDelta(a*t), t, s) == (1/a, -oo, True)
408
+ assert LT(DiracDelta(t/42), t, s) == (42, -oo, True)
409
+ assert LT(DiracDelta(t+42), t, s) == (0, -oo, True)
410
+ assert (LT(DiracDelta(t)+DiracDelta(t-42), t, s) ==
411
+ (1 + exp(-42*s), -oo, True))
412
+ assert (LT(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True) ==
413
+ (s/(a + s), -a, True))
414
+ assert (
415
+ LT(exp(-t)*(DiracDelta(t)+DiracDelta(t-42)), t, s, simplify=True) ==
416
+ (exp(-42*s - 42) + 1, -oo, True))
417
+ assert LT(f(t)*DiracDelta(t-42), t, s) == (f(42)*exp(-42*s), -oo, True)
418
+ assert LT(f(t)*DiracDelta(b*t-a), t, s) == (f(a/b)*exp(-a*s/b)/b,
419
+ -oo, True)
420
+ assert LT(f(t)*DiracDelta(b*t+a), t, s) == (0, -oo, True)
421
+ # SingularityFunction
422
+ assert LT(SingularityFunction(t, a, -1), t, s)[0] == exp(-a*s)
423
+ assert LT(SingularityFunction(t, a, 1), t, s)[0] == exp(-a*s)/s**2
424
+ assert LT(SingularityFunction(t, a, x), t, s)[0] == (
425
+ LaplaceTransform(SingularityFunction(t, a, x), t, s))
426
+ # Collection of cases that cannot be fully evaluated and/or would catch
427
+ # some common implementation errors
428
+ assert (LT(DiracDelta(t**2), t, s, noconds=True) ==
429
+ LaplaceTransform(DiracDelta(t**2), t, s))
430
+ assert LT(DiracDelta(t**2 - 1), t, s) == (exp(-s)/2, -oo, True)
431
+ assert LT(DiracDelta(t*(1 - t)), t, s) == (1 - exp(-s), -oo, True)
432
+ assert (LT((DiracDelta(t) + 1)*(DiracDelta(t - 1) + 1), t, s) ==
433
+ (LaplaceTransform(DiracDelta(t)*DiracDelta(t - 1), t, s) +
434
+ 1 + exp(-s) + 1/s, 0, True))
435
+ assert LT(DiracDelta(2*t-2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True)
436
+ assert LT(DiracDelta(-2*t+2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True)
437
+ # Heaviside tests
438
+ assert LT(Heaviside(t), t, s) == (1/s, 0, True)
439
+ assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True)
440
+ assert LT(Heaviside(t-1), t, s) == (exp(-s)/s, 0, True)
441
+ assert LT(Heaviside(2*t-4), t, s) == (exp(-2*s)/s, 0, True)
442
+ assert LT(Heaviside(2*t+4), t, s) == (1/s, 0, True)
443
+ assert (LT(Heaviside(-2*t+4), t, s, simplify=True) ==
444
+ (1/s - exp(-2*s)/s, 0, True))
445
+ assert (LT(g(t)*Heaviside(t - w), t, s) ==
446
+ (LaplaceTransform(g(t)*Heaviside(t - w), t, s), -oo, True))
447
+ assert (
448
+ LT(Heaviside(t-a)*g(t), t, s) ==
449
+ (LaplaceTransform(g(a + t), t, s)*exp(-a*s), -oo, True))
450
+ assert (
451
+ LT(Heaviside(t+a)*g(t), t, s) ==
452
+ (LaplaceTransform(g(t), t, s), -oo, True))
453
+ assert (
454
+ LT(Heaviside(-t+a)*g(t), t, s) ==
455
+ (LaplaceTransform(g(t), t, s) -
456
+ LaplaceTransform(g(a + t), t, s)*exp(-a*s), -oo, True))
457
+ assert (
458
+ LT(Heaviside(-t-a)*g(t), t, s) == (0, 0, True))
459
+ # Fresnel functions
460
+ assert (laplace_transform(fresnels(t), t, s, simplify=True) ==
461
+ ((-sin(s**2/(2*pi))*fresnels(s/pi) +
462
+ sqrt(2)*sin(s**2/(2*pi) + pi/4)/2 -
463
+ cos(s**2/(2*pi))*fresnelc(s/pi))/s, 0, True))
464
+ assert (laplace_transform(fresnelc(t), t, s, simplify=True) ==
465
+ ((sin(s**2/(2*pi))*fresnelc(s/pi) -
466
+ cos(s**2/(2*pi))*fresnels(s/pi) +
467
+ sqrt(2)*cos(s**2/(2*pi) + pi/4)/2)/s, 0, True))
468
+ # Matrix tests
469
+ Mt = Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]])
470
+ Ms = Matrix([[1/(s - 1), (s + 1)**(-2)],
471
+ [(s + 1)**(-2), 1/(s - 1)]])
472
+ # The default behaviour for Laplace transform of a Matrix returns a Matrix
473
+ # of Tuples and is deprecated:
474
+ with warns_deprecated_sympy():
475
+ Ms_conds = Matrix(
476
+ [[(1/(s - 1), 1, True), ((s + 1)**(-2), -1, True)],
477
+ [((s + 1)**(-2), -1, True), (1/(s - 1), 1, True)]])
478
+ with warns_deprecated_sympy():
479
+ assert LT(Mt, t, s) == Ms_conds
480
+ # The new behavior is to return a tuple of a Matrix and the convergence
481
+ # conditions for the matrix as a whole:
482
+ assert LT(Mt, t, s, legacy_matrix=False) == (Ms, 1, True)
483
+ # With noconds=True the transformed matrix is returned without conditions
484
+ # either way:
485
+ assert LT(Mt, t, s, noconds=True) == Ms
486
+ assert LT(Mt, t, s, legacy_matrix=False, noconds=True) == Ms
487
+
488
+
489
+ @slow
490
+ def test_inverse_laplace_transform():
491
+ s = symbols('s')
492
+ k, n, t = symbols('k, n, t', real=True)
493
+ a, b, c, d = symbols('a, b, c, d', positive=True)
494
+ f = Function('f')
495
+ F = Function('F')
496
+
497
+ def ILT(g):
498
+ return inverse_laplace_transform(g, s, t)
499
+
500
+ def ILTS(g):
501
+ return inverse_laplace_transform(g, s, t, simplify=True)
502
+
503
+ def ILTF(g):
504
+ return laplace_correspondence(
505
+ inverse_laplace_transform(g, s, t), {f: F})
506
+
507
+ # Tests for the rules in Bateman54.
508
+
509
+ # Section 4.1: Some of the Laplace transform rules can also be used well
510
+ # in the inverse transform.
511
+ assert ILTF(exp(-a*s)*F(s)) == f(-a + t)
512
+ assert ILTF(k*F(s-a)) == k*f(t)*exp(-a*t)
513
+ assert ILTF(diff(F(s), s, 3)) == -t**3*f(t)
514
+ assert ILTF(diff(F(s), s, 4)) == t**4*f(t)
515
+
516
+ # Section 5.1: Most rules are impractical for a computer algebra system.
517
+
518
+ # Section 5.2: Rational functions
519
+ assert ILT(2) == 2*DiracDelta(t)
520
+ assert ILT(1/s) == Heaviside(t)
521
+ assert ILT(1/s**2) == t*Heaviside(t)
522
+ assert ILT(1/s**5) == t**4*Heaviside(t)/24
523
+ assert ILT(1/s**n) == t**(n - 1)*Heaviside(t)/gamma(n)
524
+ assert ILT(a/(a + s)) == a*exp(-a*t)*Heaviside(t)
525
+ assert ILT(s/(a + s)) == -a*exp(-a*t)*Heaviside(t) + DiracDelta(t)
526
+ assert (ILT(b*s/(s+a)**2) ==
527
+ b*(-a*t*exp(-a*t)*Heaviside(t) + exp(-a*t)*Heaviside(t)))
528
+ assert (ILTS(c/((s+a)*(s+b))) ==
529
+ c*(exp(a*t) - exp(b*t))*exp(-t*(a + b))*Heaviside(t)/(a - b))
530
+ assert (ILTS(c*s/((s+a)*(s+b))) ==
531
+ c*(a*exp(b*t) - b*exp(a*t))*exp(-t*(a + b))*Heaviside(t)/(a - b))
532
+ assert ILTS(s/(a + s)**3) == t*(-a*t + 2)*exp(-a*t)*Heaviside(t)/2
533
+ assert ILTS(1/(s*(a + s)**3)) == (
534
+ -a**2*t**2 - 2*a*t + 2*exp(a*t) - 2)*exp(-a*t)*Heaviside(t)/(2*a**3)
535
+ assert ILT(1/(s*(a + s)**n)) == (
536
+ Heaviside(t)*lowergamma(n, a*t)/(a**n*gamma(n)))
537
+ assert ILT((s-a)**(-b)) == t**(b - 1)*exp(a*t)*Heaviside(t)/gamma(b)
538
+ assert ILT((a + s)**(-2)) == t*exp(-a*t)*Heaviside(t)
539
+ assert ILT((a + s)**(-5)) == t**4*exp(-a*t)*Heaviside(t)/24
540
+ assert ILT(s**2/(s**2 + 1)) == -sin(t)*Heaviside(t) + DiracDelta(t)
541
+ assert ILT(1 - 1/(s**2 + 1)) == -sin(t)*Heaviside(t) + DiracDelta(t)
542
+ assert ILT(a/(a**2 + s**2)) == sin(a*t)*Heaviside(t)
543
+ assert ILT(s/(s**2 + a**2)) == cos(a*t)*Heaviside(t)
544
+ assert ILT(b/(b**2 + (a + s)**2)) == exp(-a*t)*sin(b*t)*Heaviside(t)
545
+ assert (ILT(b*s/(b**2 + (a + s)**2)) ==
546
+ b*(-a*exp(-a*t)*sin(b*t)/b + exp(-a*t)*cos(b*t))*Heaviside(t))
547
+ assert ILT(1/(s**2*(s**2 + 1))) == t*Heaviside(t) - sin(t)*Heaviside(t)
548
+ assert (ILTS(c*s/(d**2*(s+a)**2+b**2)) ==
549
+ c*(-a*d*sin(b*t/d) + b*cos(b*t/d))*exp(-a*t)*Heaviside(t)/(b*d**2))
550
+ assert ILTS((b*s**2 + d)/(a**2 + s**2)**2) == (
551
+ 2*a**2*b*sin(a*t) + (a**2*b - d)*(a*t*cos(a*t) -
552
+ sin(a*t)))*Heaviside(t)/(2*a**3)
553
+ assert ILTS(b/(s**2-a**2)) == b*sinh(a*t)*Heaviside(t)/a
554
+ assert (ILT(b/(s**2-a**2)) ==
555
+ b*(exp(a*t)*Heaviside(t)/(2*a) - exp(-a*t)*Heaviside(t)/(2*a)))
556
+ assert ILTS(b*s/(s**2-a**2)) == b*cosh(a*t)*Heaviside(t)
557
+ assert (ILT(b/(s*(s+a))) ==
558
+ b*(Heaviside(t)/a - exp(-a*t)*Heaviside(t)/a))
559
+ # Issue #24424
560
+ assert (ILTS((s + 8)/((s + 2)*(s**2 + 2*s + 10))) ==
561
+ ((8*sin(3*t) - 9*cos(3*t))*exp(t) + 9)*exp(-2*t)*Heaviside(t)/15)
562
+ # Issue #8514; this is not important anymore, since this function
563
+ # is not solved by integration anymore
564
+ assert (ILT(1/(a*s**2+b*s+c)) ==
565
+ 2*exp(-b*t/(2*a))*sin(t*sqrt(4*a*c - b**2)/(2*a)) *
566
+ Heaviside(t)/sqrt(4*a*c - b**2))
567
+
568
+ # Section 5.3: Irrational algebraic functions
569
+ assert ( # (1)
570
+ ILT(1/sqrt(s)/(b*s-a)) ==
571
+ exp(a*t/b)*Heaviside(t)*erf(sqrt(a)*sqrt(t)/sqrt(b))/(sqrt(a)*sqrt(b)))
572
+ assert ( # (2)
573
+ ILT(1/sqrt(k*s)/(c*s-a)/s) ==
574
+ (-2*c*sqrt(t)/(sqrt(pi)*a) +
575
+ c**(S(3)/2)*exp(a*t/c)*erf(sqrt(a)*sqrt(t)/sqrt(c))/a**(S(3)/2)) *
576
+ Heaviside(t)/(c*sqrt(k)))
577
+ assert ( # (4)
578
+ ILT(1/(sqrt(c*s)+a)) == (-a*exp(a**2*t/c)*erfc(a*sqrt(t)/sqrt(c))/c +
579
+ 1/(sqrt(pi)*sqrt(c)*sqrt(t)))*Heaviside(t))
580
+ assert ( # (5)
581
+ ILT(a/s/(b*sqrt(s)+a)) ==
582
+ (-exp(a**2*t/b**2)*erfc(a*sqrt(t)/b) + 1)*Heaviside(t))
583
+ assert ( # (6)
584
+ ILT((a-b)*sqrt(s)/(sqrt(s)+sqrt(a))/(s-b)) ==
585
+ (sqrt(a)*sqrt(b)*exp(b*t)*erfc(sqrt(b)*sqrt(t)) +
586
+ a*exp(a*t)*erfc(sqrt(a)*sqrt(t)) - b*exp(b*t))*Heaviside(t))
587
+ assert ( # (7)
588
+ ILT(1/sqrt(s)/(sqrt(b*s)+a)) ==
589
+ exp(a**2*t/b)*Heaviside(t)*erfc(a*sqrt(t)/sqrt(b))/sqrt(b))
590
+ assert ( # (8)
591
+ ILT(a**2/(sqrt(s)+a)/s**(S(3)/2)) ==
592
+ (2*a*sqrt(t)/sqrt(pi) + exp(a**2*t)*erfc(a*sqrt(t)) - 1) *
593
+ Heaviside(t))
594
+ assert ( # (9)
595
+ ILT((a-b)*sqrt(b)/(s-b)/sqrt(s)/(sqrt(s)+sqrt(a))) ==
596
+ (sqrt(a)*exp(b*t)*erf(sqrt(b)*sqrt(t)) +
597
+ sqrt(b)*exp(a*t)*erfc(sqrt(a)*sqrt(t)) -
598
+ sqrt(b)*exp(b*t))*Heaviside(t))
599
+ assert ( # (10)
600
+ ILT(1/(sqrt(s)+sqrt(a))**2) ==
601
+ (-2*sqrt(a)*sqrt(t)/sqrt(pi) +
602
+ (-2*a*t + 1)*(erf(sqrt(a)*sqrt(t)) -
603
+ 1)*exp(a*t) + 1)*Heaviside(t))
604
+ assert ( # (11)
605
+ ILT(1/(sqrt(s)+sqrt(a))**2/s) ==
606
+ ((2*t - 1/a)*exp(a*t)*erfc(sqrt(a)*sqrt(t)) + 1/a -
607
+ 2*sqrt(t)/(sqrt(pi)*sqrt(a)))*Heaviside(t))
608
+ assert ( # (12)
609
+ ILT(1/(sqrt(s)+a)**2/sqrt(s)) ==
610
+ (-2*a*t*exp(a**2*t)*erfc(a*sqrt(t)) +
611
+ 2*sqrt(t)/sqrt(pi))*Heaviside(t))
612
+ assert ( # (13)
613
+ ILT(1/(sqrt(s)+a)**3) ==
614
+ (-a*t*(2*a**2*t + 3)*exp(a**2*t)*erfc(a*sqrt(t)) +
615
+ 2*sqrt(t)*(a**2*t + 1)/sqrt(pi))*Heaviside(t))
616
+ x = (
617
+ - ILT(sqrt(s)/(sqrt(s)+a)**3) +
618
+ 2*(sqrt(pi)*a**2*t*(-2*sqrt(pi)*erfc(a*sqrt(t)) +
619
+ 2*exp(-a**2*t)/(a*sqrt(t))) *
620
+ (-a**4*t**2 - 5*a**2*t/2 - S.Half) * exp(a**2*t)/2 +
621
+ sqrt(pi)*a*sqrt(t)*(a**2*t + 1)/2) *
622
+ Heaviside(t)/(pi*a**2*t)).simplify()
623
+ assert ( # (14)
624
+ x == 0)
625
+ x = (
626
+ - ILT(1/sqrt(s)/(sqrt(s)+a)**3) +
627
+ Heaviside(t)*(sqrt(t)*((2*a**2*t + 1) *
628
+ (sqrt(pi)*a*sqrt(t)*exp(a**2*t) *
629
+ erfc(a*sqrt(t)) - 1) + 1) /
630
+ (sqrt(pi)*a))).simplify()
631
+ assert ( # (15)
632
+ x == 0)
633
+ assert ( # (16)
634
+ factor_terms(ILT(3/(sqrt(s)+a)**4)) ==
635
+ 3*(-2*a**3*t**(S(5)/2)*(2*a**2*t + 5)/(3*sqrt(pi)) +
636
+ t*(4*a**4*t**2 + 12*a**2*t + 3)*exp(a**2*t) *
637
+ erfc(a*sqrt(t))/3)*Heaviside(t))
638
+ assert ( # (17)
639
+ ILT((sqrt(s)-a)/(s*(sqrt(s)+a))) ==
640
+ (2*exp(a**2*t)*erfc(a*sqrt(t))-1)*Heaviside(t))
641
+ assert ( # (18)
642
+ ILT((sqrt(s)-a)**2/(s*(sqrt(s)+a)**2)) == (
643
+ 1 + 8*a**2*t*exp(a**2*t)*erfc(a*sqrt(t)) -
644
+ 8/sqrt(pi)*a*sqrt(t))*Heaviside(t))
645
+ assert ( # (19)
646
+ ILT((sqrt(s)-a)**3/(s*(sqrt(s)+a)**3)) == Heaviside(t)*(
647
+ 2*(8*a**4*t**2+8*a**2*t+1)*exp(a**2*t) *
648
+ erfc(a*sqrt(t))-8/sqrt(pi)*a*sqrt(t)*(2*a**2*t+1)-1))
649
+ assert ( # (22)
650
+ ILT(sqrt(s+a)/(s+b)) == Heaviside(t)*(
651
+ exp(-a*t)/sqrt(t)/sqrt(pi) +
652
+ sqrt(a-b)*exp(-b*t)*erf(sqrt(a-b)*sqrt(t))))
653
+ assert ( # (23)
654
+ ILT(1/sqrt(s+b)/(s+a)) == Heaviside(t)*(
655
+ 1/sqrt(b-a)*exp(-a*t)*erf(sqrt(b-a)*sqrt(t))))
656
+ assert ( # (35)
657
+ ILT(1/sqrt(s**2+a**2)) == Heaviside(t)*(
658
+ besselj(0, a*t)))
659
+ assert ( # (44)
660
+ ILT(1/sqrt(s**2-a**2)) == Heaviside(t)*(
661
+ besseli(0, a*t)))
662
+
663
+ # Miscellaneous tests
664
+ # Can _inverse_laplace_time_shift deal with positive exponents?
665
+ assert (
666
+ - ILT((s**2*exp(2*s) + 4*exp(s) - 4)*exp(-2*s)/(s*(s**2 + 1))) +
667
+ cos(t)*Heaviside(t) + 4*cos(t - 2)*Heaviside(t - 2) -
668
+ 4*cos(t - 1)*Heaviside(t - 1) - 4*Heaviside(t - 2) +
669
+ 4*Heaviside(t - 1)).simplify() == 0
670
+
671
+
672
+ @slow
673
+ def test_inverse_laplace_transform_old():
674
+ from sympy.functions.special.delta_functions import DiracDelta
675
+ ILT = inverse_laplace_transform
676
+ a, b, c, d = symbols('a b c d', positive=True)
677
+ n, r = symbols('n, r', real=True)
678
+ t, z = symbols('t z')
679
+ f = Function('f')
680
+ F = Function('F')
681
+
682
+ def simp_hyp(expr):
683
+ return factor_terms(expand_mul(expr)).rewrite(sin)
684
+
685
+ L = ILT(F(s), s, t)
686
+ assert laplace_correspondence(L, {f: F}) == f(t)
687
+ assert ILT(exp(-a*s)/s, s, t) == Heaviside(-a + t)
688
+ assert ILT(exp(-a*s)/(b + s), s, t) == exp(-b*(-a + t))*Heaviside(-a + t)
689
+ assert (ILT((b + s)/(a**2 + (b + s)**2), s, t) ==
690
+ exp(-b*t)*cos(a*t)*Heaviside(t))
691
+ assert (ILT(exp(-a*s)/s**b, s, t) ==
692
+ (-a + t)**(b - 1)*Heaviside(-a + t)/gamma(b))
693
+ assert (ILT(exp(-a*s)/sqrt(s**2 + 1), s, t) ==
694
+ Heaviside(-a + t)*besselj(0, a - t))
695
+ assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
696
+ # TODO sinh/cosh shifted come out a mess. also delayed trig is a mess
697
+ # TODO should this simplify further?
698
+ assert (ILT(exp(-a*s)/s**b, s, t) ==
699
+ (t - a)**(b - 1)*Heaviside(t - a)/gamma(b))
700
+ assert (ILT(exp(-a*s)/sqrt(1 + s**2), s, t) ==
701
+ Heaviside(t - a)*besselj(0, a - t)) # note: besselj(0, x) is even
702
+ # XXX ILT turns these branch factor into trig functions ...
703
+ assert (
704
+ simplify(ILT(a**b*(s + sqrt(s**2 - a**2))**(-b)/sqrt(s**2 - a**2),
705
+ s, t).rewrite(exp)) ==
706
+ Heaviside(t)*besseli(b, a*t))
707
+ assert (
708
+ ILT(a**b*(s + sqrt(s**2 + a**2))**(-b)/sqrt(s**2 + a**2),
709
+ s, t, simplify=True).rewrite(exp) ==
710
+ Heaviside(t)*besselj(b, a*t))
711
+ assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t))
712
+ # TODO can we make erf(t) work?
713
+ assert (ILT((s * eye(2) - Matrix([[1, 0], [0, 2]])).inv(), s, t) ==
714
+ Matrix([[exp(t)*Heaviside(t), 0], [0, exp(2*t)*Heaviside(t)]]))
715
+ # Test time_diff rule
716
+ assert (ILT(s**42*f(s), s, t) ==
717
+ Derivative(InverseLaplaceTransform(f(s), s, t, None), (t, 42)))
718
+ assert ILT(cos(s), s, t) == InverseLaplaceTransform(cos(s), s, t, None)
719
+ # Rules for testing different DiracDelta cases
720
+ assert (ILT(2*exp(3*s) - 5*exp(-7*s), s, t) ==
721
+ 2*InverseLaplaceTransform(exp(3*s), s, t, None) -
722
+ 5*DiracDelta(t - 7))
723
+ a = cos(sin(7)/2)
724
+ assert ILT(a*exp(-3*s), s, t) == a*DiracDelta(t - 3)
725
+ assert ILT(exp(2*s), s, t) == InverseLaplaceTransform(exp(2*s), s, t, None)
726
+ r = Symbol('r', real=True)
727
+ assert ILT(exp(r*s), s, t) == InverseLaplaceTransform(exp(r*s), s, t, None)
728
+ # Rules for testing whether Heaviside(t) is treated properly in diff rule
729
+ assert ILT(s**2/(a**2 + s**2), s, t) == (
730
+ -a*sin(a*t)*Heaviside(t) + DiracDelta(t))
731
+ assert ILT(s**2*(f(s) + 1/(a**2 + s**2)), s, t) == (
732
+ -a*sin(a*t)*Heaviside(t) + DiracDelta(t) +
733
+ Derivative(InverseLaplaceTransform(f(s), s, t, None), (t, 2)))
734
+ # Rules from the previous test_inverse_laplace_transform_delta_cond():
735
+ assert (ILT(exp(r*s), s, t, noconds=False) ==
736
+ (InverseLaplaceTransform(exp(r*s), s, t, None), True))
737
+ # inversion does not exist: verify it doesn't evaluate to DiracDelta
738
+ for z in (Symbol('z', extended_real=False),
739
+ Symbol('z', imaginary=True, zero=False)):
740
+ f = ILT(exp(z*s), s, t, noconds=False)
741
+ f = f[0] if isinstance(f, tuple) else f
742
+ assert f.func != DiracDelta
743
+
744
+
745
+ @slow
746
+ def test_expint():
747
+ x = Symbol('x')
748
+ a = Symbol('a')
749
+ u = Symbol('u', polar=True)
750
+
751
+ # TODO LT of Si, Shi, Chi is a mess ...
752
+ assert laplace_transform(Ci(x), x, s) == (-log(1 + s**2)/2/s, 0, True)
753
+ assert (laplace_transform(expint(a, x), x, s, simplify=True) ==
754
+ (lerchphi(s*exp_polar(I*pi), 1, a), 0, re(a) > S.Zero))
755
+ assert (laplace_transform(expint(1, x), x, s, simplify=True) ==
756
+ (log(s + 1)/s, 0, True))
757
+ assert (laplace_transform(expint(2, x), x, s, simplify=True) ==
758
+ ((s - log(s + 1))/s**2, 0, True))
759
+ assert (inverse_laplace_transform(-log(1 + s**2)/2/s, s, u).expand() ==
760
+ Heaviside(u)*Ci(u))
761
+ assert (
762
+ inverse_laplace_transform(log(s + 1)/s, s, x,
763
+ simplify=True).rewrite(expint) ==
764
+ Heaviside(x)*E1(x))
765
+ assert (
766
+ inverse_laplace_transform(
767
+ (s - log(s + 1))/s**2, s, x,
768
+ simplify=True).rewrite(expint).expand() ==
769
+ (expint(2, x)*Heaviside(x)).rewrite(Ei).rewrite(expint).expand())
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_lineintegrals.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import E
2
+ from sympy.core.symbol import symbols
3
+ from sympy.functions.elementary.exponential import log
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.geometry.curve import Curve
6
+ from sympy.integrals.integrals import line_integrate
7
+
8
+ s, t, x, y, z = symbols('s,t,x,y,z')
9
+
10
+
11
+ def test_lineintegral():
12
+ c = Curve([E**t + 1, E**t - 1], (t, 0, log(2)))
13
+ assert line_integrate(x + y, c, [x, y]) == 3*sqrt(2)
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_risch.py ADDED
@@ -0,0 +1,763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Most of these tests come from the examples in Bronstein's book."""
2
+ from sympy.core.function import (Function, Lambda, diff, expand_log)
3
+ from sympy.core.numbers import (I, Rational, pi)
4
+ from sympy.core.relational import Ne
5
+ from sympy.core.singleton import S
6
+ from sympy.core.symbol import (Symbol, symbols)
7
+ from sympy.functions.elementary.exponential import (exp, log)
8
+ from sympy.functions.elementary.miscellaneous import sqrt
9
+ from sympy.functions.elementary.piecewise import Piecewise
10
+ from sympy.functions.elementary.trigonometric import (atan, sin, tan)
11
+ from sympy.polys.polytools import (Poly, cancel, factor)
12
+ from sympy.integrals.risch import (gcdex_diophantine, frac_in, as_poly_1t,
13
+ derivation, splitfactor, splitfactor_sqf, canonical_representation,
14
+ hermite_reduce, polynomial_reduce, residue_reduce, residue_reduce_to_basic,
15
+ integrate_primitive, integrate_hyperexponential_polynomial,
16
+ integrate_hyperexponential, integrate_hypertangent_polynomial,
17
+ integrate_nonlinear_no_specials, integer_powers, DifferentialExtension,
18
+ risch_integrate, DecrementLevel, NonElementaryIntegral, recognize_log_derivative,
19
+ recognize_derivative, laurent_series)
20
+ from sympy.testing.pytest import raises
21
+
22
+ from sympy.abc import x, t, nu, z, a, y
23
+ t0, t1, t2 = symbols('t:3')
24
+ i = Symbol('i')
25
+
26
+ def test_gcdex_diophantine():
27
+ assert gcdex_diophantine(Poly(x**4 - 2*x**3 - 6*x**2 + 12*x + 15),
28
+ Poly(x**3 + x**2 - 4*x - 4), Poly(x**2 - 1)) == \
29
+ (Poly((-x**2 + 4*x - 3)/5), Poly((x**3 - 7*x**2 + 16*x - 10)/5))
30
+ assert gcdex_diophantine(Poly(x**3 + 6*x + 7), Poly(x**2 + 3*x + 2), Poly(x + 1)) == \
31
+ (Poly(1/13, x, domain='QQ'), Poly(-1/13*x + 3/13, x, domain='QQ'))
32
+
33
+
34
+ def test_frac_in():
35
+ assert frac_in(Poly((x + 1)/x*t, t), x) == \
36
+ (Poly(t*x + t, x), Poly(x, x))
37
+ assert frac_in((x + 1)/x*t, x) == \
38
+ (Poly(t*x + t, x), Poly(x, x))
39
+ assert frac_in((Poly((x + 1)/x*t, t), Poly(t + 1, t)), x) == \
40
+ (Poly(t*x + t, x), Poly((1 + t)*x, x))
41
+ raises(ValueError, lambda: frac_in((x + 1)/log(x)*t, x))
42
+ assert frac_in(Poly((2 + 2*x + x*(1 + x))/(1 + x)**2, t), x, cancel=True) == \
43
+ (Poly(x + 2, x), Poly(x + 1, x))
44
+
45
+
46
+ def test_as_poly_1t():
47
+ assert as_poly_1t(2/t + t, t, z) in [
48
+ Poly(t + 2*z, t, z), Poly(t + 2*z, z, t)]
49
+ assert as_poly_1t(2/t + 3/t**2, t, z) in [
50
+ Poly(2*z + 3*z**2, t, z), Poly(2*z + 3*z**2, z, t)]
51
+ assert as_poly_1t(2/((exp(2) + 1)*t), t, z) in [
52
+ Poly(2/(exp(2) + 1)*z, t, z), Poly(2/(exp(2) + 1)*z, z, t)]
53
+ assert as_poly_1t(2/((exp(2) + 1)*t) + t, t, z) in [
54
+ Poly(t + 2/(exp(2) + 1)*z, t, z), Poly(t + 2/(exp(2) + 1)*z, z, t)]
55
+ assert as_poly_1t(S.Zero, t, z) == Poly(0, t, z)
56
+
57
+
58
+ def test_derivation():
59
+ p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 +
60
+ (2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t)
61
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t + 1/(2*x), t)]})
62
+ assert derivation(p, DE) == Poly(-20*x**4*t**6 + (2*x**3 + 16*x**4)*t**5 +
63
+ (21*x**2 + 12*x**3)*t**4 + (x*Rational(7, 2) - 25*x**2 - 12*x**3)*t**3 +
64
+ (-5 - x*Rational(15, 2) + 7*x**2)*t**2 - (3 - 8*x - 10*x**2 - 4*x**3)/(2*x)*t +
65
+ (1 - 4*x**2)/(2*x), t)
66
+ assert derivation(Poly(1, t), DE) == Poly(0, t)
67
+ assert derivation(Poly(t, t), DE) == DE.d
68
+ assert derivation(Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t), DE) == \
69
+ Poly(-2*t**3 - 4/x*t**2 - (5 - 2*x)/(2*x**2)*t - (1 - 2*x)/(2*x**3), t, domain='ZZ(x)')
70
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(t, t)]})
71
+ assert derivation(Poly(x*t*t1, t), DE) == Poly(t*t1 + x*t*t1 + t, t)
72
+ assert derivation(Poly(x*t*t1, t), DE, coefficientD=True) == \
73
+ Poly((1 + t1)*t, t)
74
+ DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
75
+ assert derivation(Poly(x, x), DE) == Poly(1, x)
76
+ # Test basic option
77
+ assert derivation((x + 1)/(x - 1), DE, basic=True) == -2/(1 - 2*x + x**2)
78
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
79
+ assert derivation((t + 1)/(t - 1), DE, basic=True) == -2*t/(1 - 2*t + t**2)
80
+ assert derivation(t + 1, DE, basic=True) == t
81
+
82
+
83
+ def test_splitfactor():
84
+ p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 +
85
+ (2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t, field=True)
86
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t + 1/(2*x), t)]})
87
+ assert splitfactor(p, DE) == (Poly(4*x**4*t**3 + (-8*x**3 - 4*x**4)*t**2 +
88
+ (4*x**2 + 8*x**3)*t - 4*x**2, t, domain='ZZ(x)'),
89
+ Poly(t**2 + 1/x*t + (1 - 2*x)/(4*x**2), t, domain='ZZ(x)'))
90
+ assert splitfactor(Poly(x, t), DE) == (Poly(x, t), Poly(1, t))
91
+ r = Poly(-4*x**4*z**2 + 4*x**6*z**2 - z*x**3 - 4*x**5*z**3 + 4*x**3*z**3 + x**4 + z*x**5 - x**6, t)
92
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
93
+ assert splitfactor(r, DE, coefficientD=True) == \
94
+ (Poly(x*z - x**2 - z*x**3 + x**4, t), Poly(-x**2 + 4*x**2*z**2, t))
95
+ assert splitfactor_sqf(r, DE, coefficientD=True) == \
96
+ (((Poly(x*z - x**2 - z*x**3 + x**4, t), 1),), ((Poly(-x**2 + 4*x**2*z**2, t), 1),))
97
+ assert splitfactor(Poly(0, t), DE) == (Poly(0, t), Poly(1, t))
98
+ assert splitfactor_sqf(Poly(0, t), DE) == (((Poly(0, t), 1),), ())
99
+
100
+
101
+ def test_canonical_representation():
102
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
103
+ assert canonical_representation(Poly(x - t, t), Poly(t**2, t), DE) == \
104
+ (Poly(0, t, domain='ZZ[x]'), (Poly(0, t, domain='QQ[x]'),
105
+ Poly(1, t, domain='ZZ')), (Poly(-t + x, t, domain='QQ[x]'),
106
+ Poly(t**2, t)))
107
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
108
+ assert canonical_representation(Poly(t**5 + t**3 + x**2*t + 1, t),
109
+ Poly((t**2 + 1)**3, t), DE) == \
110
+ (Poly(0, t, domain='ZZ[x]'), (Poly(t**5 + t**3 + x**2*t + 1, t, domain='QQ[x]'),
111
+ Poly(t**6 + 3*t**4 + 3*t**2 + 1, t, domain='QQ')),
112
+ (Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='QQ')))
113
+
114
+
115
+ def test_hermite_reduce():
116
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
117
+
118
+ assert hermite_reduce(Poly(x - t, t), Poly(t**2, t), DE) == \
119
+ ((Poly(-x, t, domain='QQ[x]'), Poly(t, t, domain='QQ[x]')),
120
+ (Poly(0, t, domain='QQ[x]'), Poly(1, t, domain='QQ[x]')),
121
+ (Poly(-x, t, domain='QQ[x]'), Poly(1, t, domain='QQ[x]')))
122
+
123
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)]})
124
+
125
+ assert hermite_reduce(
126
+ Poly(x**2*t**5 + x*t**4 - nu**2*t**3 - x*(x**2 + 1)*t**2 - (x**2 - nu**2)*t - x**5/4, t),
127
+ Poly(x**2*t**4 + x**2*(x**2 + 2)*t**2 + x**2 + x**4 + x**6/4, t), DE) == \
128
+ ((Poly(-x**2 - 4, t, domain='ZZ(x,nu)'), Poly(4*t**2 + 2*x**2 + 4, t, domain='ZZ(x,nu)')),
129
+ (Poly((-2*nu**2 - x**4)*t - (2*x**3 + 2*x), t, domain='ZZ(x,nu)'),
130
+ Poly(2*x**2*t**2 + x**4 + 2*x**2, t, domain='ZZ(x,nu)')),
131
+ (Poly(x*t + 1, t, domain='ZZ(x,nu)'), Poly(x, t, domain='ZZ(x,nu)')))
132
+
133
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
134
+
135
+ a = Poly((-2 + 3*x)*t**3 + (-1 + x)*t**2 + (-4*x + 2*x**2)*t + x**2, t)
136
+ d = Poly(x*t**6 - 4*x**2*t**5 + 6*x**3*t**4 - 4*x**4*t**3 + x**5*t**2, t)
137
+
138
+ assert hermite_reduce(a, d, DE) == \
139
+ ((Poly(3*t**2 + t + 3*x, t, domain='ZZ(x)'),
140
+ Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t, domain='ZZ(x)')),
141
+ (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
142
+ (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')))
143
+
144
+ assert hermite_reduce(
145
+ Poly(-t**2 + 2*t + 2, t, domain='ZZ(x)'),
146
+ Poly(-x*t**2 + 2*x*t - x, t, domain='ZZ(x)'), DE) == \
147
+ ((Poly(3, t, domain='ZZ(x)'), Poly(t - 1, t, domain='ZZ(x)')),
148
+ (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
149
+ (Poly(1, t, domain='ZZ(x)'), Poly(x, t, domain='ZZ(x)')))
150
+
151
+ assert hermite_reduce(
152
+ Poly(-x**2*t**6 + (-1 - 2*x**3 + x**4)*t**3 + (-3 - 3*x**4)*t**2 -
153
+ 2*x*t - x - 3*x**2, t, domain='ZZ(x)'),
154
+ Poly(x**4*t**6 - 2*x**2*t**3 + 1, t, domain='ZZ(x)'), DE) == \
155
+ ((Poly(x**3*t + x**4 + 1, t, domain='ZZ(x)'), Poly(x**3*t**3 - x, t, domain='ZZ(x)')),
156
+ (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
157
+ (Poly(-1, t, domain='ZZ(x)'), Poly(x**2, t, domain='ZZ(x)')))
158
+
159
+ assert hermite_reduce(
160
+ Poly((-2 + 3*x)*t**3 + (-1 + x)*t**2 + (-4*x + 2*x**2)*t + x**2, t),
161
+ Poly(x*t**6 - 4*x**2*t**5 + 6*x**3*t**4 - 4*x**4*t**3 + x**5*t**2, t), DE) == \
162
+ ((Poly(3*t**2 + t + 3*x, t, domain='ZZ(x)'),
163
+ Poly(3*t**4 - 9*x*t**3 + 9*x**2*t**2 - 3*x**3*t, t, domain='ZZ(x)')),
164
+ (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')),
165
+ (Poly(0, t, domain='ZZ(x)'), Poly(1, t, domain='ZZ(x)')))
166
+
167
+
168
+ def test_polynomial_reduce():
169
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
170
+ assert polynomial_reduce(Poly(1 + x*t + t**2, t), DE) == \
171
+ (Poly(t, t), Poly(x*t, t))
172
+ assert polynomial_reduce(Poly(0, t), DE) == \
173
+ (Poly(0, t), Poly(0, t))
174
+
175
+
176
+ def test_laurent_series():
177
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1, t)]})
178
+ a = Poly(36, t)
179
+ d = Poly((t - 2)*(t**2 - 1)**2, t)
180
+ F = Poly(t**2 - 1, t)
181
+ n = 2
182
+ assert laurent_series(a, d, F, n, DE) == \
183
+ (Poly(-3*t**3 + 3*t**2 - 6*t - 8, t), Poly(t**5 + t**4 - 2*t**3 - 2*t**2 + t + 1, t),
184
+ [Poly(-3*t**3 - 6*t**2, t, domain='QQ'), Poly(2*t**6 + 6*t**5 - 8*t**3, t, domain='QQ')])
185
+
186
+
187
+ def test_recognize_derivative():
188
+ DE = DifferentialExtension(extension={'D': [Poly(1, t)]})
189
+ a = Poly(36, t)
190
+ d = Poly((t - 2)*(t**2 - 1)**2, t)
191
+ assert recognize_derivative(a, d, DE) == False
192
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
193
+ a = Poly(2, t)
194
+ d = Poly(t**2 - 1, t)
195
+ assert recognize_derivative(a, d, DE) == False
196
+ assert recognize_derivative(Poly(x*t, t), Poly(1, t), DE) == True
197
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
198
+ assert recognize_derivative(Poly(t, t), Poly(1, t), DE) == True
199
+
200
+
201
+ def test_recognize_log_derivative():
202
+
203
+ a = Poly(2*x**2 + 4*x*t - 2*t - x**2*t, t)
204
+ d = Poly((2*x + t)*(t + x**2), t)
205
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
206
+ assert recognize_log_derivative(a, d, DE, z) == True
207
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)]})
208
+ assert recognize_log_derivative(Poly(t + 1, t), Poly(t + x, t), DE) == True
209
+ assert recognize_log_derivative(Poly(2, t), Poly(t**2 - 1, t), DE) == True
210
+ DE = DifferentialExtension(extension={'D': [Poly(1, x)]})
211
+ assert recognize_log_derivative(Poly(1, x), Poly(x**2 - 2, x), DE) == False
212
+ assert recognize_log_derivative(Poly(1, x), Poly(x**2 + x, x), DE) == True
213
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
214
+ assert recognize_log_derivative(Poly(1, t), Poly(t**2 - 2, t), DE) == False
215
+ assert recognize_log_derivative(Poly(1, t), Poly(t**2 + t, t), DE) == False
216
+
217
+
218
+ def test_residue_reduce():
219
+ a = Poly(2*t**2 - t - x**2, t)
220
+ d = Poly(t**3 - x**2*t, t)
221
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)], 'Tfuncs': [log]})
222
+ assert residue_reduce(a, d, DE, z, invert=False) == \
223
+ ([(Poly(z**2 - Rational(1, 4), z, domain='ZZ(x)'),
224
+ Poly((1 + 3*x*z - 6*z**2 - 2*x**2 + 4*x**2*z**2)*t - x*z + x**2 +
225
+ 2*x**2*z**2 - 2*z*x**3, t, domain='ZZ(z, x)'))], False)
226
+ assert residue_reduce(a, d, DE, z, invert=True) == \
227
+ ([(Poly(z**2 - Rational(1, 4), z, domain='ZZ(x)'), Poly(t + 2*x*z, t))], False)
228
+ assert residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t,), DE, z, invert=False) == \
229
+ ([(Poly(z**2 - 1, z, domain='QQ'), Poly(-2*z*t/x - 2/x, t, domain='ZZ(z,x)'))], True)
230
+ ans = residue_reduce(Poly(-2/x, t), Poly(t**2 - 1, t), DE, z, invert=True)
231
+ assert ans == ([(Poly(z**2 - 1, z, domain='QQ'), Poly(t + z, t))], True)
232
+ assert residue_reduce_to_basic(ans[0], DE, z) == -log(-1 + log(x)) + log(1 + log(x))
233
+
234
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - t/x - (1 - nu**2/x**2), t)]})
235
+ # TODO: Skip or make faster
236
+ assert residue_reduce(Poly((-2*nu**2 - x**4)/(2*x**2)*t - (1 + x**2)/x, t),
237
+ Poly(t**2 + 1 + x**2/2, t), DE, z) == \
238
+ ([(Poly(z + S.Half, z, domain='QQ'), Poly(t**2 + 1 + x**2/2, t,
239
+ domain='ZZ(x,nu)'))], True)
240
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t**2, t)]})
241
+ assert residue_reduce(Poly(-2*x*t + 1 - x**2, t),
242
+ Poly(t**2 + 2*x*t + 1 + x**2, t), DE, z) == \
243
+ ([(Poly(z**2 + Rational(1, 4), z), Poly(t + x + 2*z, t))], True)
244
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
245
+ assert residue_reduce(Poly(t, t), Poly(t + sqrt(2), t), DE, z) == \
246
+ ([(Poly(z - 1, z, domain='QQ'), Poly(t + sqrt(2), t))], True)
247
+
248
+
249
+ def test_integrate_hyperexponential():
250
+ # TODO: Add tests for integrate_hyperexponential() from the book
251
+ a = Poly((1 + 2*t1 + t1**2 + 2*t1**3)*t**2 + (1 + t1**2)*t + 1 + t1**2, t)
252
+ d = Poly(1, t)
253
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1 + t1**2, t1),
254
+ Poly(t*(1 + t1**2), t)], 'Tfuncs': [tan, Lambda(i, exp(tan(i)))]})
255
+ assert integrate_hyperexponential(a, d, DE) == \
256
+ (exp(2*tan(x))*tan(x) + exp(tan(x)), 1 + t1**2, True)
257
+ a = Poly((t1**3 + (x + 1)*t1**2 + t1 + x + 2)*t, t)
258
+ assert integrate_hyperexponential(a, d, DE) == \
259
+ ((x + tan(x))*exp(tan(x)), 0, True)
260
+
261
+ a = Poly(t, t)
262
+ d = Poly(1, t)
263
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(2*x*t, t)],
264
+ 'Tfuncs': [Lambda(i, exp(x**2))]})
265
+
266
+ assert integrate_hyperexponential(a, d, DE) == \
267
+ (0, NonElementaryIntegral(exp(x**2), x), False)
268
+
269
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'Tfuncs': [exp]})
270
+ assert integrate_hyperexponential(a, d, DE) == (exp(x), 0, True)
271
+
272
+ a = Poly(25*t**6 - 10*t**5 + 7*t**4 - 8*t**3 + 13*t**2 + 2*t - 1, t)
273
+ d = Poly(25*t**6 + 35*t**4 + 11*t**2 + 1, t)
274
+ assert integrate_hyperexponential(a, d, DE) == \
275
+ (-(11 - 10*exp(x))/(5 + 25*exp(2*x)) + log(1 + exp(2*x)), -1, True)
276
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(t0*t, t)],
277
+ 'Tfuncs': [exp, Lambda(i, exp(exp(i)))]})
278
+ assert integrate_hyperexponential(Poly(2*t0*t**2, t), Poly(1, t), DE) == (exp(2*exp(x)), 0, True)
279
+
280
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t0, t0), Poly(-t0*t, t)],
281
+ 'Tfuncs': [exp, Lambda(i, exp(-exp(i)))]})
282
+ assert integrate_hyperexponential(Poly(-27*exp(9) - 162*t0*exp(9) +
283
+ 27*x*t0*exp(9), t), Poly((36*exp(18) + x**2*exp(18) - 12*x*exp(18))*t, t), DE) == \
284
+ (27*exp(exp(x))/(-6*exp(9) + x*exp(9)), 0, True)
285
+
286
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)], 'Tfuncs': [exp]})
287
+ assert integrate_hyperexponential(Poly(x**2/2*t, t), Poly(1, t), DE) == \
288
+ ((2 - 2*x + x**2)*exp(x)/2, 0, True)
289
+ assert integrate_hyperexponential(Poly(1 + t, t), Poly(t, t), DE) == \
290
+ (-exp(-x), 1, True) # x - exp(-x)
291
+ assert integrate_hyperexponential(Poly(x, t), Poly(t + 1, t), DE) == \
292
+ (0, NonElementaryIntegral(x/(1 + exp(x)), x), False)
293
+
294
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0), Poly(2*x*t1, t1)],
295
+ 'Tfuncs': [log, Lambda(i, exp(i**2))]})
296
+
297
+ elem, nonelem, b = integrate_hyperexponential(Poly((8*x**7 - 12*x**5 + 6*x**3 - x)*t1**4 +
298
+ (8*t0*x**7 - 8*t0*x**6 - 4*t0*x**5 + 2*t0*x**3 + 2*t0*x**2 - t0*x +
299
+ 24*x**8 - 36*x**6 - 4*x**5 + 22*x**4 + 4*x**3 - 7*x**2 - x + 1)*t1**3
300
+ + (8*t0*x**8 - 4*t0*x**6 - 16*t0*x**5 - 2*t0*x**4 + 12*t0*x**3 +
301
+ t0*x**2 - 2*t0*x + 24*x**9 - 36*x**7 - 8*x**6 + 22*x**5 + 12*x**4 -
302
+ 7*x**3 - 6*x**2 + x + 1)*t1**2 + (8*t0*x**8 - 8*t0*x**6 - 16*t0*x**5 +
303
+ 6*t0*x**4 + 10*t0*x**3 - 2*t0*x**2 - t0*x + 8*x**10 - 12*x**8 - 4*x**7
304
+ + 2*x**6 + 12*x**5 + 3*x**4 - 9*x**3 - x**2 + 2*x)*t1 + 8*t0*x**7 -
305
+ 12*t0*x**6 - 4*t0*x**5 + 8*t0*x**4 - t0*x**2 - 4*x**7 + 4*x**6 +
306
+ 4*x**5 - 4*x**4 - x**3 + x**2, t1), Poly((8*x**7 - 12*x**5 + 6*x**3 -
307
+ x)*t1**4 + (24*x**8 + 8*x**7 - 36*x**6 - 12*x**5 + 18*x**4 + 6*x**3 -
308
+ 3*x**2 - x)*t1**3 + (24*x**9 + 24*x**8 - 36*x**7 - 36*x**6 + 18*x**5 +
309
+ 18*x**4 - 3*x**3 - 3*x**2)*t1**2 + (8*x**10 + 24*x**9 - 12*x**8 -
310
+ 36*x**7 + 6*x**6 + 18*x**5 - x**4 - 3*x**3)*t1 + 8*x**10 - 12*x**8 +
311
+ 6*x**6 - x**4, t1), DE)
312
+
313
+ assert factor(elem) == -((x - 1)*log(x)/((x + exp(x**2))*(2*x**2 - 1)))
314
+ assert (nonelem, b) == (NonElementaryIntegral(exp(x**2)/(exp(x**2) + 1), x), False)
315
+
316
+ def test_integrate_hyperexponential_polynomial():
317
+ # Without proper cancellation within integrate_hyperexponential_polynomial(),
318
+ # this will take a long time to complete, and will return a complicated
319
+ # expression
320
+ p = Poly((-28*x**11*t0 - 6*x**8*t0 + 6*x**9*t0 - 15*x**8*t0**2 +
321
+ 15*x**7*t0**2 + 84*x**10*t0**2 - 140*x**9*t0**3 - 20*x**6*t0**3 +
322
+ 20*x**7*t0**3 - 15*x**6*t0**4 + 15*x**5*t0**4 + 140*x**8*t0**4 -
323
+ 84*x**7*t0**5 - 6*x**4*t0**5 + 6*x**5*t0**5 + x**3*t0**6 - x**4*t0**6 +
324
+ 28*x**6*t0**6 - 4*x**5*t0**7 + x**9 - x**10 + 4*x**12)/(-8*x**11*t0 +
325
+ 28*x**10*t0**2 - 56*x**9*t0**3 + 70*x**8*t0**4 - 56*x**7*t0**5 +
326
+ 28*x**6*t0**6 - 8*x**5*t0**7 + x**4*t0**8 + x**12)*t1**2 +
327
+ (-28*x**11*t0 - 12*x**8*t0 + 12*x**9*t0 - 30*x**8*t0**2 +
328
+ 30*x**7*t0**2 + 84*x**10*t0**2 - 140*x**9*t0**3 - 40*x**6*t0**3 +
329
+ 40*x**7*t0**3 - 30*x**6*t0**4 + 30*x**5*t0**4 + 140*x**8*t0**4 -
330
+ 84*x**7*t0**5 - 12*x**4*t0**5 + 12*x**5*t0**5 - 2*x**4*t0**6 +
331
+ 2*x**3*t0**6 + 28*x**6*t0**6 - 4*x**5*t0**7 + 2*x**9 - 2*x**10 +
332
+ 4*x**12)/(-8*x**11*t0 + 28*x**10*t0**2 - 56*x**9*t0**3 +
333
+ 70*x**8*t0**4 - 56*x**7*t0**5 + 28*x**6*t0**6 - 8*x**5*t0**7 +
334
+ x**4*t0**8 + x**12)*t1 + (-2*x**2*t0 + 2*x**3*t0 + x*t0**2 -
335
+ x**2*t0**2 + x**3 - x**4)/(-4*x**5*t0 + 6*x**4*t0**2 - 4*x**3*t0**3 +
336
+ x**2*t0**4 + x**6), t1, z, expand=False)
337
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0), Poly(2*x*t1, t1)]})
338
+ assert integrate_hyperexponential_polynomial(p, DE, z) == (
339
+ Poly((x - t0)*t1**2 + (-2*t0 + 2*x)*t1, t1), Poly(-2*x*t0 + x**2 +
340
+ t0**2, t1), True)
341
+
342
+ DE = DifferentialExtension(extension={'D':[Poly(1, x), Poly(t0, t0)]})
343
+ assert integrate_hyperexponential_polynomial(Poly(0, t0), DE, z) == (
344
+ Poly(0, t0), Poly(1, t0), True)
345
+
346
+
347
+ def test_integrate_hyperexponential_returns_piecewise():
348
+ a, b = symbols('a b')
349
+ DE = DifferentialExtension(a**x, x)
350
+ assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
351
+ (exp(x*log(a))/log(a), Ne(log(a), 0)), (x, True)), 0, True)
352
+ DE = DifferentialExtension(a**(b*x), x)
353
+ assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
354
+ (exp(b*x*log(a))/(b*log(a)), Ne(b*log(a), 0)), (x, True)), 0, True)
355
+ DE = DifferentialExtension(exp(a*x), x)
356
+ assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
357
+ (exp(a*x)/a, Ne(a, 0)), (x, True)), 0, True)
358
+ DE = DifferentialExtension(x*exp(a*x), x)
359
+ assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
360
+ ((a*x - 1)*exp(a*x)/a**2, Ne(a**2, 0)), (x**2/2, True)), 0, True)
361
+ DE = DifferentialExtension(x**2*exp(a*x), x)
362
+ assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
363
+ ((x**2*a**2 - 2*a*x + 2)*exp(a*x)/a**3, Ne(a**3, 0)),
364
+ (x**3/3, True)), 0, True)
365
+ DE = DifferentialExtension(x**y + z, y)
366
+ assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
367
+ (exp(log(x)*y)/log(x), Ne(log(x), 0)), (y, True)), z, True)
368
+ DE = DifferentialExtension(x**y + z + x**(2*y), y)
369
+ assert integrate_hyperexponential(DE.fa, DE.fd, DE) == (Piecewise(
370
+ ((exp(2*log(x)*y)*log(x) +
371
+ 2*exp(log(x)*y)*log(x))/(2*log(x)**2), Ne(2*log(x)**2, 0)),
372
+ (2*y, True),
373
+ ), z, True)
374
+ # TODO: Add a test where two different parts of the extension use a
375
+ # Piecewise, like y**x + z**x.
376
+
377
+
378
+ def test_issue_13947():
379
+ a, t, s = symbols('a t s')
380
+ assert risch_integrate(2**(-pi)/(2**t + 1), t) == \
381
+ 2**(-pi)*t - 2**(-pi)*log(2**t + 1)/log(2)
382
+ assert risch_integrate(a**(t - s)/(a**t + 1), t) == \
383
+ exp(-s*log(a))*log(a**t + 1)/log(a)
384
+
385
+
386
+ def test_integrate_primitive():
387
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t)],
388
+ 'Tfuncs': [log]})
389
+ assert integrate_primitive(Poly(t, t), Poly(1, t), DE) == (x*log(x), -1, True)
390
+ assert integrate_primitive(Poly(x, t), Poly(t, t), DE) == (0, NonElementaryIntegral(x/log(x), x), False)
391
+
392
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x + 1), t2)],
393
+ 'Tfuncs': [log, Lambda(i, log(i + 1))]})
394
+ assert integrate_primitive(Poly(t1, t2), Poly(t2, t2), DE) == \
395
+ (0, NonElementaryIntegral(log(x)/log(1 + x), x), False)
396
+
397
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t1), Poly(1/(x*t1), t2)],
398
+ 'Tfuncs': [log, Lambda(i, log(log(i)))]})
399
+ assert integrate_primitive(Poly(t2, t2), Poly(t1, t2), DE) == \
400
+ (0, NonElementaryIntegral(log(log(x))/log(x), x), False)
401
+
402
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(1/x, t0)],
403
+ 'Tfuncs': [log]})
404
+ assert integrate_primitive(Poly(x**2*t0**3 + (3*x**2 + x)*t0**2 + (3*x**2
405
+ + 2*x)*t0 + x**2 + x, t0), Poly(x**2*t0**4 + 4*x**2*t0**3 + 6*x**2*t0**2 +
406
+ 4*x**2*t0 + x**2, t0), DE) == \
407
+ (-1/(log(x) + 1), NonElementaryIntegral(1/(log(x) + 1), x), False)
408
+
409
+ def test_integrate_hypertangent_polynomial():
410
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t**2 + 1, t)]})
411
+ assert integrate_hypertangent_polynomial(Poly(t**2 + x*t + 1, t), DE) == \
412
+ (Poly(t, t), Poly(x/2, t))
413
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(a*(t**2 + 1), t)]})
414
+ assert integrate_hypertangent_polynomial(Poly(t**5, t), DE) == \
415
+ (Poly(1/(4*a)*t**4 - 1/(2*a)*t**2, t), Poly(1/(2*a), t))
416
+
417
+
418
+ def test_integrate_nonlinear_no_specials():
419
+ a, d, = Poly(x**2*t**5 + x*t**4 - nu**2*t**3 - x*(x**2 + 1)*t**2 - (x**2 -
420
+ nu**2)*t - x**5/4, t), Poly(x**2*t**4 + x**2*(x**2 + 2)*t**2 + x**2 + x**4 + x**6/4, t)
421
+ # f(x) == phi_nu(x), the logarithmic derivative of J_v, the Bessel function,
422
+ # which has no specials (see Chapter 5, note 4 of Bronstein's book).
423
+ f = Function('phi_nu')
424
+ DE = DifferentialExtension(extension={'D': [Poly(1, x),
425
+ Poly(-t**2 - t/x - (1 - nu**2/x**2), t)], 'Tfuncs': [f]})
426
+ assert integrate_nonlinear_no_specials(a, d, DE) == \
427
+ (-log(1 + f(x)**2 + x**2/2)/2 + (- 4 - x**2)/(4 + 2*x**2 + 4*f(x)**2), True)
428
+ assert integrate_nonlinear_no_specials(Poly(t, t), Poly(1, t), DE) == \
429
+ (0, False)
430
+
431
+
432
+ def test_integer_powers():
433
+ assert integer_powers([x, x/2, x**2 + 1, x*Rational(2, 3)]) == [
434
+ (x/6, [(x, 6), (x/2, 3), (x*Rational(2, 3), 4)]),
435
+ (1 + x**2, [(1 + x**2, 1)])]
436
+
437
+
438
+ def test_DifferentialExtension_exp():
439
+ assert DifferentialExtension(exp(x) + exp(x**2), x)._important_attrs == \
440
+ (Poly(t1 + t0, t1), Poly(1, t1), [Poly(1, x,), Poly(t0, t0),
441
+ Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
442
+ Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
443
+ assert DifferentialExtension(exp(x) + exp(2*x), x)._important_attrs == \
444
+ (Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0, t0)], [x, t0],
445
+ [Lambda(i, exp(i))], [], [None, 'exp'], [None, x])
446
+ assert DifferentialExtension(exp(x) + exp(x/2), x)._important_attrs == \
447
+ (Poly(t0**2 + t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)],
448
+ [x, t0], [Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2])
449
+ assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2), x)._important_attrs == \
450
+ (Poly((1 + t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0),
451
+ Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
452
+ Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
453
+ assert DifferentialExtension(exp(x) + exp(x**2) + exp(x + x**2 + 1), x)._important_attrs == \
454
+ (Poly((1 + S.Exp1*t0)*t1 + t0, t1), Poly(1, t1), [Poly(1, x),
455
+ Poly(t0, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i)),
456
+ Lambda(i, exp(i**2))], [], [None, 'exp', 'exp'], [None, x, x**2])
457
+ assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2), x)._important_attrs == \
458
+ (Poly((t0 + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x),
459
+ Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1],
460
+ [Lambda(i, exp(i/2)), Lambda(i, exp(i**2))],
461
+ [(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'], [None, x/2, x**2])
462
+ assert DifferentialExtension(exp(x) + exp(x**2) + exp(x/2 + x**2 + 3), x)._important_attrs == \
463
+ (Poly((t0*exp(3) + 1)*t1 + t0**2, t1), Poly(1, t1), [Poly(1, x),
464
+ Poly(t0/2, t0), Poly(2*x*t1, t1)], [x, t0, t1], [Lambda(i, exp(i/2)),
465
+ Lambda(i, exp(i**2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp', 'exp'],
466
+ [None, x/2, x**2])
467
+ assert DifferentialExtension(sqrt(exp(x)), x)._important_attrs == \
468
+ (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0],
469
+ [Lambda(i, exp(i/2))], [(exp(x/2), sqrt(exp(x)))], [None, 'exp'], [None, x/2])
470
+
471
+ assert DifferentialExtension(exp(x/2), x)._important_attrs == \
472
+ (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(t0/2, t0)], [x, t0],
473
+ [Lambda(i, exp(i/2))], [], [None, 'exp'], [None, x/2])
474
+
475
+
476
+ def test_DifferentialExtension_log():
477
+ assert DifferentialExtension(log(x)*log(x + 1)*log(2*x**2 + 2*x), x)._important_attrs == \
478
+ (Poly(t0*t1**2 + (t0*log(2) + t0**2)*t1, t1), Poly(1, t1),
479
+ [Poly(1, x), Poly(1/x, t0),
480
+ Poly(1/(x + 1), t1, expand=False)], [x, t0, t1],
481
+ [Lambda(i, log(i)), Lambda(i, log(i + 1))], [], [None, 'log', 'log'],
482
+ [None, x, x + 1])
483
+ assert DifferentialExtension(x**x*log(x), x)._important_attrs == \
484
+ (Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0),
485
+ Poly((1 + t0)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)),
486
+ Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)], [None, 'log', 'exp'],
487
+ [None, x, t0*x])
488
+
489
+
490
+ def test_DifferentialExtension_symlog():
491
+ # See comment on test_risch_integrate below
492
+ assert DifferentialExtension(log(x**x), x)._important_attrs == \
493
+ (Poly(t0*x, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0), Poly((t0 +
494
+ 1)*t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i*t0))],
495
+ [(exp(x*log(x)), x**x)], [None, 'log', 'exp'], [None, x, t0*x])
496
+ assert DifferentialExtension(log(x**y), x)._important_attrs == \
497
+ (Poly(y*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
498
+ [Lambda(i, log(i))], [(y*log(x), log(x**y))], [None, 'log'],
499
+ [None, x])
500
+ assert DifferentialExtension(log(sqrt(x)), x)._important_attrs == \
501
+ (Poly(t0, t0), Poly(2, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
502
+ [Lambda(i, log(i))], [(log(x)/2, log(sqrt(x)))], [None, 'log'],
503
+ [None, x])
504
+
505
+
506
+ def test_DifferentialExtension_handle_first():
507
+ assert DifferentialExtension(exp(x)*log(x), x, handle_first='log')._important_attrs == \
508
+ (Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(1/x, t0),
509
+ Poly(t1, t1)], [x, t0, t1], [Lambda(i, log(i)), Lambda(i, exp(i))],
510
+ [], [None, 'log', 'exp'], [None, x, x])
511
+ assert DifferentialExtension(exp(x)*log(x), x, handle_first='exp')._important_attrs == \
512
+ (Poly(t0*t1, t1), Poly(1, t1), [Poly(1, x), Poly(t0, t0),
513
+ Poly(1/x, t1)], [x, t0, t1], [Lambda(i, exp(i)), Lambda(i, log(i))],
514
+ [], [None, 'exp', 'log'], [None, x, x])
515
+
516
+ # This one must have the log first, regardless of what we set it to
517
+ # (because the log is inside of the exponential: x**x == exp(x*log(x)))
518
+ assert DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x,
519
+ handle_first='exp')._important_attrs == \
520
+ DifferentialExtension(-x**x*log(x)**2 + x**x - x**x/x, x,
521
+ handle_first='log')._important_attrs == \
522
+ (Poly((-1 + x - x*t0**2)*t1, t1), Poly(x, t1),
523
+ [Poly(1, x), Poly(1/x, t0), Poly((1 + t0)*t1, t1)], [x, t0, t1],
524
+ [Lambda(i, log(i)), Lambda(i, exp(t0*i))], [(exp(x*log(x)), x**x)],
525
+ [None, 'log', 'exp'], [None, x, t0*x])
526
+
527
+
528
+ def test_DifferentialExtension_all_attrs():
529
+ # Test 'unimportant' attributes
530
+ DE = DifferentialExtension(exp(x)*log(x), x, handle_first='exp')
531
+ assert DE.f == exp(x)*log(x)
532
+ assert DE.newf == t0*t1
533
+ assert DE.x == x
534
+ assert DE.cases == ['base', 'exp', 'primitive']
535
+ assert DE.case == 'primitive'
536
+
537
+ assert DE.level == -1
538
+ assert DE.t == t1 == DE.T[DE.level]
539
+ assert DE.d == Poly(1/x, t1) == DE.D[DE.level]
540
+ raises(ValueError, lambda: DE.increment_level())
541
+ DE.decrement_level()
542
+ assert DE.level == -2
543
+ assert DE.t == t0 == DE.T[DE.level]
544
+ assert DE.d == Poly(t0, t0) == DE.D[DE.level]
545
+ assert DE.case == 'exp'
546
+ DE.decrement_level()
547
+ assert DE.level == -3
548
+ assert DE.t == x == DE.T[DE.level] == DE.x
549
+ assert DE.d == Poly(1, x) == DE.D[DE.level]
550
+ assert DE.case == 'base'
551
+ raises(ValueError, lambda: DE.decrement_level())
552
+ DE.increment_level()
553
+ DE.increment_level()
554
+ assert DE.level == -1
555
+ assert DE.t == t1 == DE.T[DE.level]
556
+ assert DE.d == Poly(1/x, t1) == DE.D[DE.level]
557
+ assert DE.case == 'primitive'
558
+
559
+ # Test methods
560
+ assert DE.indices('log') == [2]
561
+ assert DE.indices('exp') == [1]
562
+
563
+
564
+ def test_DifferentialExtension_extension_flag():
565
+ raises(ValueError, lambda: DifferentialExtension(extension={'T': [x, t]}))
566
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]})
567
+ assert DE._important_attrs == (None, None, [Poly(1, x), Poly(t, t)], [x, t],
568
+ None, None, None, None)
569
+ assert DE.d == Poly(t, t)
570
+ assert DE.t == t
571
+ assert DE.level == -1
572
+ assert DE.cases == ['base', 'exp']
573
+ assert DE.x == x
574
+ assert DE.case == 'exp'
575
+
576
+ DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)],
577
+ 'exts': [None, 'exp'], 'extargs': [None, x]})
578
+ assert DE._important_attrs == (None, None, [Poly(1, x), Poly(t, t)], [x, t],
579
+ None, None, [None, 'exp'], [None, x])
580
+ raises(ValueError, lambda: DifferentialExtension())
581
+
582
+
583
+ def test_DifferentialExtension_misc():
584
+ # Odd ends
585
+ assert DifferentialExtension(sin(y)*exp(x), x)._important_attrs == \
586
+ (Poly(sin(y)*t0, t0, domain='ZZ[sin(y)]'), Poly(1, t0, domain='ZZ'),
587
+ [Poly(1, x, domain='ZZ'), Poly(t0, t0, domain='ZZ')], [x, t0],
588
+ [Lambda(i, exp(i))], [], [None, 'exp'], [None, x])
589
+ raises(NotImplementedError, lambda: DifferentialExtension(sin(x), x))
590
+ assert DifferentialExtension(10**x, x)._important_attrs == \
591
+ (Poly(t0, t0), Poly(1, t0), [Poly(1, x), Poly(log(10)*t0, t0)], [x, t0],
592
+ [Lambda(i, exp(i*log(10)))], [(exp(x*log(10)), 10**x)], [None, 'exp'],
593
+ [None, x*log(10)])
594
+ assert DifferentialExtension(log(x) + log(x**2), x)._important_attrs in [
595
+ (Poly(3*t0, t0), Poly(2, t0), [Poly(1, x), Poly(2/x, t0)], [x, t0],
596
+ [Lambda(i, log(i**2))], [], [None, ], [], [1], [x**2]),
597
+ (Poly(3*t0, t0), Poly(1, t0), [Poly(1, x), Poly(1/x, t0)], [x, t0],
598
+ [Lambda(i, log(i))], [], [None, 'log'], [None, x])]
599
+ assert DifferentialExtension(S.Zero, x)._important_attrs == \
600
+ (Poly(0, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None])
601
+ assert DifferentialExtension(tan(atan(x).rewrite(log)), x)._important_attrs == \
602
+ (Poly(x, x), Poly(1, x), [Poly(1, x)], [x], [], [], [None], [None])
603
+
604
+
605
+ def test_DifferentialExtension_Rothstein():
606
+ # Rothstein's integral
607
+ f = (2581284541*exp(x) + 1757211400)/(39916800*exp(3*x) +
608
+ 119750400*exp(x)**2 + 119750400*exp(x) + 39916800)*exp(1/(exp(x) + 1) - 10*x)
609
+ assert DifferentialExtension(f, x)._important_attrs == \
610
+ (Poly((1757211400 + 2581284541*t0)*t1, t1), Poly(39916800 +
611
+ 119750400*t0 + 119750400*t0**2 + 39916800*t0**3, t1),
612
+ [Poly(1, x), Poly(t0, t0), Poly(-(10 + 21*t0 + 10*t0**2)/(1 + 2*t0 +
613
+ t0**2)*t1, t1, domain='ZZ(t0)')], [x, t0, t1],
614
+ [Lambda(i, exp(i)), Lambda(i, exp(1/(t0 + 1) - 10*i))], [],
615
+ [None, 'exp', 'exp'], [None, x, 1/(t0 + 1) - 10*x])
616
+
617
+
618
+ class _TestingException(Exception):
619
+ """Dummy Exception class for testing."""
620
+ pass
621
+
622
+
623
+ def test_DecrementLevel():
624
+ DE = DifferentialExtension(x*log(exp(x) + 1), x)
625
+ assert DE.level == -1
626
+ assert DE.t == t1
627
+ assert DE.d == Poly(t0/(t0 + 1), t1)
628
+ assert DE.case == 'primitive'
629
+
630
+ with DecrementLevel(DE):
631
+ assert DE.level == -2
632
+ assert DE.t == t0
633
+ assert DE.d == Poly(t0, t0)
634
+ assert DE.case == 'exp'
635
+
636
+ with DecrementLevel(DE):
637
+ assert DE.level == -3
638
+ assert DE.t == x
639
+ assert DE.d == Poly(1, x)
640
+ assert DE.case == 'base'
641
+
642
+ assert DE.level == -2
643
+ assert DE.t == t0
644
+ assert DE.d == Poly(t0, t0)
645
+ assert DE.case == 'exp'
646
+
647
+ assert DE.level == -1
648
+ assert DE.t == t1
649
+ assert DE.d == Poly(t0/(t0 + 1), t1)
650
+ assert DE.case == 'primitive'
651
+
652
+ # Test that __exit__ is called after an exception correctly
653
+ try:
654
+ with DecrementLevel(DE):
655
+ raise _TestingException
656
+ except _TestingException:
657
+ pass
658
+ else:
659
+ raise AssertionError("Did not raise.")
660
+
661
+ assert DE.level == -1
662
+ assert DE.t == t1
663
+ assert DE.d == Poly(t0/(t0 + 1), t1)
664
+ assert DE.case == 'primitive'
665
+
666
+
667
+ def test_risch_integrate():
668
+ assert risch_integrate(t0*exp(x), x) == t0*exp(x)
669
+ assert risch_integrate(sin(x), x, rewrite_complex=True) == -exp(I*x)/2 - exp(-I*x)/2
670
+
671
+ # From my GSoC writeup
672
+ assert risch_integrate((1 + 2*x**2 + x**4 + 2*x**3*exp(2*x**2))/
673
+ (x**4*exp(x**2) + 2*x**2*exp(x**2) + exp(x**2)), x) == \
674
+ NonElementaryIntegral(exp(-x**2), x) + exp(x**2)/(1 + x**2)
675
+
676
+
677
+ assert risch_integrate(0, x) == 0
678
+
679
+ # also tests prde_cancel()
680
+ e1 = log(x/exp(x) + 1)
681
+ ans1 = risch_integrate(e1, x)
682
+ assert ans1 == (x*log(x*exp(-x) + 1) + NonElementaryIntegral((x**2 - x)/(x + exp(x)), x))
683
+ assert cancel(diff(ans1, x) - e1) == 0
684
+
685
+ # also tests issue #10798
686
+ e2 = (log(-1/y)/2 - log(1/y)/2)/y - (log(1 - 1/y)/2 - log(1 + 1/y)/2)/y
687
+ ans2 = risch_integrate(e2, y)
688
+ assert ans2 == log(1/y)*log(1 - 1/y)/2 - log(1/y)*log(1 + 1/y)/2 + \
689
+ NonElementaryIntegral((I*pi*y**2 - 2*y*log(1/y) - I*pi)/(2*y**3 - 2*y), y)
690
+ assert expand_log(cancel(diff(ans2, y) - e2), force=True) == 0
691
+
692
+ # These are tested here in addition to in test_DifferentialExtension above
693
+ # (symlogs) to test that backsubs works correctly. The integrals should be
694
+ # written in terms of the original logarithms in the integrands.
695
+
696
+ # XXX: Unfortunately, making backsubs work on this one is a little
697
+ # trickier, because x**x is converted to exp(x*log(x)), and so log(x**x)
698
+ # is converted to x*log(x). (x**2*log(x)).subs(x*log(x), log(x**x)) is
699
+ # smart enough, the issue is that these splits happen at different places
700
+ # in the algorithm. Maybe a heuristic is in order
701
+ assert risch_integrate(log(x**x), x) == x**2*log(x)/2 - x**2/4
702
+
703
+ assert risch_integrate(log(x**y), x) == x*log(x**y) - x*y
704
+ assert risch_integrate(log(sqrt(x)), x) == x*log(sqrt(x)) - x/2
705
+
706
+
707
+ def test_risch_integrate_float():
708
+ assert risch_integrate((-60*exp(x) - 19.2*exp(4*x))*exp(4*x), x) == -2.4*exp(8*x) - 12.0*exp(5*x)
709
+
710
+
711
+ def test_NonElementaryIntegral():
712
+ assert isinstance(risch_integrate(exp(x**2), x), NonElementaryIntegral)
713
+ assert isinstance(risch_integrate(x**x*log(x), x), NonElementaryIntegral)
714
+ # Make sure methods of Integral still give back a NonElementaryIntegral
715
+ assert isinstance(NonElementaryIntegral(x**x*t0, x).subs(t0, log(x)), NonElementaryIntegral)
716
+
717
+
718
+ def test_xtothex():
719
+ a = risch_integrate(x**x, x)
720
+ assert a == NonElementaryIntegral(x**x, x)
721
+ assert isinstance(a, NonElementaryIntegral)
722
+
723
+
724
+ def test_DifferentialExtension_equality():
725
+ DE1 = DE2 = DifferentialExtension(log(x), x)
726
+ assert DE1 == DE2
727
+
728
+
729
+ def test_DifferentialExtension_printing():
730
+ DE = DifferentialExtension(exp(2*x**2) + log(exp(x**2) + 1), x)
731
+ assert repr(DE) == ("DifferentialExtension(dict([('f', exp(2*x**2) + log(exp(x**2) + 1)), "
732
+ "('x', x), ('T', [x, t0, t1]), ('D', [Poly(1, x, domain='ZZ'), Poly(2*x*t0, t0, domain='ZZ[x]'), "
733
+ "Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')]), ('fa', Poly(t1 + t0**2, t1, domain='ZZ[t0]')), "
734
+ "('fd', Poly(1, t1, domain='ZZ')), ('Tfuncs', [Lambda(i, exp(i**2)), Lambda(i, log(t0 + 1))]), "
735
+ "('backsubs', []), ('exts', [None, 'exp', 'log']), ('extargs', [None, x**2, t0 + 1]), "
736
+ "('cases', ['base', 'exp', 'primitive']), ('case', 'primitive'), ('t', t1), "
737
+ "('d', Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')), ('newf', t0**2 + t1), ('level', -1), "
738
+ "('dummy', False)]))")
739
+
740
+ assert str(DE) == ("DifferentialExtension({fa=Poly(t1 + t0**2, t1, domain='ZZ[t0]'), "
741
+ "fd=Poly(1, t1, domain='ZZ'), D=[Poly(1, x, domain='ZZ'), Poly(2*x*t0, t0, domain='ZZ[x]'), "
742
+ "Poly(2*t0*x/(t0 + 1), t1, domain='ZZ(x,t0)')]})")
743
+
744
+
745
+ def test_issue_23948():
746
+ f = (
747
+ ( (-2*x**5 + 28*x**4 - 144*x**3 + 324*x**2 - 270*x)*log(x)**2
748
+ +(-4*x**6 + 56*x**5 - 288*x**4 + 648*x**3 - 540*x**2)*log(x)
749
+ +(2*x**5 - 28*x**4 + 144*x**3 - 324*x**2 + 270*x)*exp(x)
750
+ +(2*x**5 - 28*x**4 + 144*x**3 - 324*x**2 + 270*x)*log(5)
751
+ -2*x**7 + 26*x**6 - 116*x**5 + 180*x**4 + 54*x**3 - 270*x**2
752
+ )*log(-log(x)**2 - 2*x*log(x) + exp(x) + log(5) - x**2 - x)**2
753
+ +( (4*x**5 - 44*x**4 + 168*x**3 - 216*x**2 - 108*x + 324)*log(x)
754
+ +(-2*x**5 + 24*x**4 - 108*x**3 + 216*x**2 - 162*x)*exp(x)
755
+ +4*x**6 - 42*x**5 + 144*x**4 - 108*x**3 - 324*x**2 + 486*x
756
+ )*log(-log(x)**2 - 2*x*log(x) + exp(x) + log(5) - x**2 - x)
757
+ )/(x*exp(x)**2*log(x)**2 + 2*x**2*exp(x)**2*log(x) - x*exp(x)**3
758
+ +(-x*log(5) + x**3 + x**2)*exp(x)**2)
759
+
760
+ F = ((x**4 - 12*x**3 + 54*x**2 - 108*x + 81)*exp(-2*x)
761
+ *log(-x**2 - 2*x*log(x) - x + exp(x) - log(x)**2 + log(5))**2)
762
+
763
+ assert risch_integrate(f, x) == F
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_singularityfunctions.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.integrals.singularityfunctions import singularityintegrate
2
+ from sympy.core.function import Function
3
+ from sympy.core.symbol import symbols
4
+ from sympy.functions.special.singularity_functions import SingularityFunction
5
+
6
+ x, a, n, y = symbols('x a n y')
7
+ f = Function('f')
8
+
9
+
10
+ def test_singularityintegrate():
11
+ assert singularityintegrate(x, x) is None
12
+ assert singularityintegrate(x + SingularityFunction(x, 9, 1), x) is None
13
+
14
+ assert 4*singularityintegrate(SingularityFunction(x, a, 3), x) == 4*SingularityFunction(x, a, 4)/4
15
+ assert singularityintegrate(5*SingularityFunction(x, 5, -2), x) == 5*SingularityFunction(x, 5, -1)
16
+ assert singularityintegrate(6*SingularityFunction(x, 5, -1), x) == 6*SingularityFunction(x, 5, 0)
17
+ assert singularityintegrate(x*SingularityFunction(x, 0, -1), x) == 0
18
+ assert singularityintegrate((x - 5)*SingularityFunction(x, 5, -1), x) == 0
19
+ assert singularityintegrate(SingularityFunction(x, 0, -1) * f(x), x) == f(0) * SingularityFunction(x, 0, 0)
20
+ assert singularityintegrate(SingularityFunction(x, 1, -1) * f(x), x) == f(1) * SingularityFunction(x, 1, 0)
21
+ assert singularityintegrate(y*SingularityFunction(x, 0, -1)**2, x) == \
22
+ y*SingularityFunction(0, 0, -1)*SingularityFunction(x, 0, 0)
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_transforms.py ADDED
@@ -0,0 +1,636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.integrals.transforms import (
2
+ mellin_transform, inverse_mellin_transform,
3
+ fourier_transform, inverse_fourier_transform,
4
+ sine_transform, inverse_sine_transform,
5
+ cosine_transform, inverse_cosine_transform,
6
+ hankel_transform, inverse_hankel_transform,
7
+ FourierTransform, SineTransform, CosineTransform, InverseFourierTransform,
8
+ InverseSineTransform, InverseCosineTransform, IntegralTransformError)
9
+ from sympy.integrals.laplace import (
10
+ laplace_transform, inverse_laplace_transform)
11
+ from sympy.core.function import Function, expand_mul
12
+ from sympy.core import EulerGamma
13
+ from sympy.core.numbers import I, Rational, oo, pi
14
+ from sympy.core.singleton import S
15
+ from sympy.core.symbol import Symbol, symbols
16
+ from sympy.functions.combinatorial.factorials import factorial
17
+ from sympy.functions.elementary.complexes import re, unpolarify
18
+ from sympy.functions.elementary.exponential import exp, exp_polar, log
19
+ from sympy.functions.elementary.miscellaneous import sqrt
20
+ from sympy.functions.elementary.trigonometric import atan, cos, sin, tan
21
+ from sympy.functions.special.bessel import besseli, besselj, besselk, bessely
22
+ from sympy.functions.special.delta_functions import Heaviside
23
+ from sympy.functions.special.error_functions import erf, expint
24
+ from sympy.functions.special.gamma_functions import gamma
25
+ from sympy.functions.special.hyper import meijerg
26
+ from sympy.simplify.gammasimp import gammasimp
27
+ from sympy.simplify.hyperexpand import hyperexpand
28
+ from sympy.simplify.trigsimp import trigsimp
29
+ from sympy.testing.pytest import XFAIL, slow, skip, raises
30
+ from sympy.abc import x, s, a, b, c, d
31
+
32
+
33
+ nu, beta, rho = symbols('nu beta rho')
34
+
35
+
36
+ def test_undefined_function():
37
+ from sympy.integrals.transforms import MellinTransform
38
+ f = Function('f')
39
+ assert mellin_transform(f(x), x, s) == MellinTransform(f(x), x, s)
40
+ assert mellin_transform(f(x) + exp(-x), x, s) == \
41
+ (MellinTransform(f(x), x, s) + gamma(s + 1)/s, (0, oo), True)
42
+
43
+
44
+ def test_free_symbols():
45
+ f = Function('f')
46
+ assert mellin_transform(f(x), x, s).free_symbols == {s}
47
+ assert mellin_transform(f(x)*a, x, s).free_symbols == {s, a}
48
+
49
+
50
+ def test_as_integral():
51
+ from sympy.integrals.integrals import Integral
52
+ f = Function('f')
53
+ assert mellin_transform(f(x), x, s).rewrite('Integral') == \
54
+ Integral(x**(s - 1)*f(x), (x, 0, oo))
55
+ assert fourier_transform(f(x), x, s).rewrite('Integral') == \
56
+ Integral(f(x)*exp(-2*I*pi*s*x), (x, -oo, oo))
57
+ assert laplace_transform(f(x), x, s, noconds=True).rewrite('Integral') == \
58
+ Integral(f(x)*exp(-s*x), (x, 0, oo))
59
+ assert str(2*pi*I*inverse_mellin_transform(f(s), s, x, (a, b)).rewrite('Integral')) \
60
+ == "Integral(f(s)/x**s, (s, _c - oo*I, _c + oo*I))"
61
+ assert str(2*pi*I*inverse_laplace_transform(f(s), s, x).rewrite('Integral')) == \
62
+ "Integral(f(s)*exp(s*x), (s, _c - oo*I, _c + oo*I))"
63
+ assert inverse_fourier_transform(f(s), s, x).rewrite('Integral') == \
64
+ Integral(f(s)*exp(2*I*pi*s*x), (s, -oo, oo))
65
+
66
+ # NOTE this is stuck in risch because meijerint cannot handle it
67
+
68
+
69
+ @slow
70
+ @XFAIL
71
+ def test_mellin_transform_fail():
72
+ skip("Risch takes forever.")
73
+
74
+ MT = mellin_transform
75
+
76
+ bpos = symbols('b', positive=True)
77
+ # bneg = symbols('b', negative=True)
78
+
79
+ expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
80
+ # TODO does not work with bneg, argument wrong. Needs changes to matching.
81
+ assert MT(expr.subs(b, -bpos), x, s) == \
82
+ ((-1)**(a + 1)*2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(a + s)
83
+ *gamma(1 - a - 2*s)/gamma(1 - s),
84
+ (-re(a), -re(a)/2 + S.Half), True)
85
+
86
+ expr = (sqrt(x + b**2) + b)**a
87
+ assert MT(expr.subs(b, -bpos), x, s) == \
88
+ (
89
+ 2**(a + 2*s)*a*bpos**(a + 2*s)*gamma(-a - 2*
90
+ s)*gamma(a + s)/gamma(-s + 1),
91
+ (-re(a), -re(a)/2), True)
92
+
93
+ # Test exponent 1:
94
+ assert MT(expr.subs({b: -bpos, a: 1}), x, s) == \
95
+ (-bpos**(2*s + 1)*gamma(s)*gamma(-s - S.Half)/(2*sqrt(pi)),
96
+ (-1, Rational(-1, 2)), True)
97
+
98
+
99
+ def test_mellin_transform():
100
+ from sympy.functions.elementary.miscellaneous import (Max, Min)
101
+ MT = mellin_transform
102
+
103
+ bpos = symbols('b', positive=True)
104
+
105
+ # 8.4.2
106
+ assert MT(x**nu*Heaviside(x - 1), x, s) == \
107
+ (-1/(nu + s), (-oo, -re(nu)), True)
108
+ assert MT(x**nu*Heaviside(1 - x), x, s) == \
109
+ (1/(nu + s), (-re(nu), oo), True)
110
+
111
+ assert MT((1 - x)**(beta - 1)*Heaviside(1 - x), x, s) == \
112
+ (gamma(beta)*gamma(s)/gamma(beta + s), (0, oo), re(beta) > 0)
113
+ assert MT((x - 1)**(beta - 1)*Heaviside(x - 1), x, s) == \
114
+ (gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
115
+ (-oo, 1 - re(beta)), re(beta) > 0)
116
+
117
+ assert MT((1 + x)**(-rho), x, s) == \
118
+ (gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True)
119
+
120
+ assert MT(abs(1 - x)**(-rho), x, s) == (
121
+ 2*sin(pi*rho/2)*gamma(1 - rho)*
122
+ cos(pi*(s - rho/2))*gamma(s)*gamma(rho-s)/pi,
123
+ (0, re(rho)), re(rho) < 1)
124
+ mt = MT((1 - x)**(beta - 1)*Heaviside(1 - x)
125
+ + a*(x - 1)**(beta - 1)*Heaviside(x - 1), x, s)
126
+ assert mt[1], mt[2] == ((0, -re(beta) + 1), re(beta) > 0)
127
+
128
+ assert MT((x**a - b**a)/(x - b), x, s)[0] == \
129
+ pi*b**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s)))
130
+ assert MT((x**a - bpos**a)/(x - bpos), x, s) == \
131
+ (pi*bpos**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))),
132
+ (Max(0, -re(a)), Min(1, 1 - re(a))), True)
133
+
134
+ expr = (sqrt(x + b**2) + b)**a
135
+ assert MT(expr.subs(b, bpos), x, s) == \
136
+ (-a*(2*bpos)**(a + 2*s)*gamma(s)*gamma(-a - 2*s)/gamma(-a - s + 1),
137
+ (0, -re(a)/2), True)
138
+
139
+ expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2)
140
+ assert MT(expr.subs(b, bpos), x, s) == \
141
+ (2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(s)
142
+ *gamma(1 - a - 2*s)/gamma(1 - a - s),
143
+ (0, -re(a)/2 + S.Half), True)
144
+
145
+ # 8.4.2
146
+ assert MT(exp(-x), x, s) == (gamma(s), (0, oo), True)
147
+ assert MT(exp(-1/x), x, s) == (gamma(-s), (-oo, 0), True)
148
+
149
+ # 8.4.5
150
+ assert MT(log(x)**4*Heaviside(1 - x), x, s) == (24/s**5, (0, oo), True)
151
+ assert MT(log(x)**3*Heaviside(x - 1), x, s) == (6/s**4, (-oo, 0), True)
152
+ assert MT(log(x + 1), x, s) == (pi/(s*sin(pi*s)), (-1, 0), True)
153
+ assert MT(log(1/x + 1), x, s) == (pi/(s*sin(pi*s)), (0, 1), True)
154
+ assert MT(log(abs(1 - x)), x, s) == (pi/(s*tan(pi*s)), (-1, 0), True)
155
+ assert MT(log(abs(1 - 1/x)), x, s) == (pi/(s*tan(pi*s)), (0, 1), True)
156
+
157
+ # 8.4.14
158
+ assert MT(erf(sqrt(x)), x, s) == \
159
+ (-gamma(s + S.Half)/(sqrt(pi)*s), (Rational(-1, 2), 0), True)
160
+
161
+
162
+ def test_mellin_transform2():
163
+ MT = mellin_transform
164
+ # TODO we cannot currently do these (needs summation of 3F2(-1))
165
+ # this also implies that they cannot be written as a single g-function
166
+ # (although this is possible)
167
+ mt = MT(log(x)/(x + 1), x, s)
168
+ assert mt[1:] == ((0, 1), True)
169
+ assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
170
+ mt = MT(log(x)**2/(x + 1), x, s)
171
+ assert mt[1:] == ((0, 1), True)
172
+ assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
173
+ mt = MT(log(x)/(x + 1)**2, x, s)
174
+ assert mt[1:] == ((0, 2), True)
175
+ assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg)
176
+
177
+
178
+ @slow
179
+ def test_mellin_transform_bessel():
180
+ from sympy.functions.elementary.miscellaneous import Max
181
+ MT = mellin_transform
182
+
183
+ # 8.4.19
184
+ assert MT(besselj(a, 2*sqrt(x)), x, s) == \
185
+ (gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, Rational(3, 4)), True)
186
+ assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
187
+ (2**a*gamma(-2*s + S.Half)*gamma(a/2 + s + S.Half)/(
188
+ gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), (
189
+ -re(a)/2 - S.Half, Rational(1, 4)), True)
190
+ assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \
191
+ (2**a*gamma(a/2 + s)*gamma(-2*s + S.Half)/(
192
+ gamma(-a/2 - s + S.Half)*gamma(a - 2*s + 1)), (
193
+ -re(a)/2, Rational(1, 4)), True)
194
+ assert MT(besselj(a, sqrt(x))**2, x, s) == \
195
+ (gamma(a + s)*gamma(S.Half - s)
196
+ / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
197
+ (-re(a), S.Half), True)
198
+ assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \
199
+ (gamma(s)*gamma(S.Half - s)
200
+ / (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)),
201
+ (0, S.Half), True)
202
+ # NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as
203
+ # I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large)
204
+ assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \
205
+ (gamma(1 - s)*gamma(a + s - S.Half)
206
+ / (sqrt(pi)*gamma(Rational(3, 2) - s)*gamma(a - s + S.Half)),
207
+ (S.Half - re(a), S.Half), True)
208
+ assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \
209
+ (4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s)
210
+ / (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2)
211
+ *gamma( 1 - s + (a + b)/2)),
212
+ (-(re(a) + re(b))/2, S.Half), True)
213
+ assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \
214
+ ((Max(re(a), -re(a)), S.Half), True)
215
+
216
+ # Section 8.4.20
217
+ assert MT(bessely(a, 2*sqrt(x)), x, s) == \
218
+ (-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi,
219
+ (Max(-re(a)/2, re(a)/2), Rational(3, 4)), True)
220
+ assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
221
+ (-4**s*sin(pi*(a/2 - s))*gamma(S.Half - 2*s)
222
+ * gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s)
223
+ / (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)),
224
+ (Max(-(re(a) + 1)/2, (re(a) - 1)/2), Rational(1, 4)), True)
225
+ assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \
226
+ (-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S.Half - 2*s)
227
+ / (sqrt(pi)*gamma(S.Half - s - a/2)*gamma(S.Half - s + a/2)),
228
+ (Max(-re(a)/2, re(a)/2), Rational(1, 4)), True)
229
+ assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \
230
+ (-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S.Half - s)
231
+ / (pi**S('3/2')*gamma(1 + a - s)),
232
+ (Max(-re(a), 0), S.Half), True)
233
+ assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \
234
+ (-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s)
235
+ * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s)
236
+ / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
237
+ (Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S.Half), True)
238
+ # NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x))
239
+ # are a mess (no matter what way you look at it ...)
240
+ assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \
241
+ ((Max(-re(a), 0, re(a)), S.Half), True)
242
+
243
+ # Section 8.4.22
244
+ # TODO we can't do any of these (delicate cancellation)
245
+
246
+ # Section 8.4.23
247
+ assert MT(besselk(a, 2*sqrt(x)), x, s) == \
248
+ (gamma(
249
+ s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True)
250
+ assert MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(
251
+ a, 2*sqrt(2*sqrt(x))), x, s) == (4**(-s)*gamma(2*s)*
252
+ gamma(a/2 + s)/(2*gamma(a/2 - s + 1)), (Max(0, -re(a)/2), oo), True)
253
+ # TODO bessely(a, x)*besselk(a, x) is a mess
254
+ assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
255
+ (gamma(s)*gamma(
256
+ a + s)*gamma(-s + S.Half)/(2*sqrt(pi)*gamma(a - s + 1)),
257
+ (Max(-re(a), 0), S.Half), True)
258
+ assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \
259
+ (2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \
260
+ gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \
261
+ gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \
262
+ re(a)/2 - re(b)/2), S.Half), True)
263
+
264
+ # TODO products of besselk are a mess
265
+
266
+ mt = MT(exp(-x/2)*besselk(a, x/2), x, s)
267
+ mt0 = gammasimp(trigsimp(gammasimp(mt[0].expand(func=True))))
268
+ assert mt0 == 2*pi**Rational(3, 2)*cos(pi*s)*gamma(S.Half - s)/(
269
+ (cos(2*pi*a) - cos(2*pi*s))*gamma(-a - s + 1)*gamma(a - s + 1))
270
+ assert mt[1:] == ((Max(-re(a), re(a)), oo), True)
271
+ # TODO exp(x/2)*besselk(a, x/2) [etc] cannot currently be done
272
+ # TODO various strange products of special orders
273
+
274
+
275
+ @slow
276
+ def test_expint():
277
+ from sympy.functions.elementary.miscellaneous import Max
278
+ from sympy.functions.special.error_functions import Ci, E1, Si
279
+ from sympy.simplify.simplify import simplify
280
+
281
+ aneg = Symbol('a', negative=True)
282
+ u = Symbol('u', polar=True)
283
+
284
+ assert mellin_transform(E1(x), x, s) == (gamma(s)/s, (0, oo), True)
285
+ assert inverse_mellin_transform(gamma(s)/s, s, x,
286
+ (0, oo)).rewrite(expint).expand() == E1(x)
287
+ assert mellin_transform(expint(a, x), x, s) == \
288
+ (gamma(s)/(a + s - 1), (Max(1 - re(a), 0), oo), True)
289
+ # XXX IMT has hickups with complicated strips ...
290
+ assert simplify(unpolarify(
291
+ inverse_mellin_transform(gamma(s)/(aneg + s - 1), s, x,
292
+ (1 - aneg, oo)).rewrite(expint).expand(func=True))) == \
293
+ expint(aneg, x)
294
+
295
+ assert mellin_transform(Si(x), x, s) == \
296
+ (-2**s*sqrt(pi)*gamma(s/2 + S.Half)/(
297
+ 2*s*gamma(-s/2 + 1)), (-1, 0), True)
298
+ assert inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)
299
+ /(2*s*gamma(-s/2 + 1)), s, x, (-1, 0)) \
300
+ == Si(x)
301
+
302
+ assert mellin_transform(Ci(sqrt(x)), x, s) == \
303
+ (-2**(2*s - 1)*sqrt(pi)*gamma(s)/(s*gamma(-s + S.Half)), (0, 1), True)
304
+ assert inverse_mellin_transform(
305
+ -4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S.Half)),
306
+ s, u, (0, 1)).expand() == Ci(sqrt(u))
307
+
308
+
309
+ @slow
310
+ def test_inverse_mellin_transform():
311
+ from sympy.core.function import expand
312
+ from sympy.functions.elementary.miscellaneous import (Max, Min)
313
+ from sympy.functions.elementary.trigonometric import cot
314
+ from sympy.simplify.powsimp import powsimp
315
+ from sympy.simplify.simplify import simplify
316
+ IMT = inverse_mellin_transform
317
+
318
+ assert IMT(gamma(s), s, x, (0, oo)) == exp(-x)
319
+ assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1/x)
320
+ assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \
321
+ (x**2 + 1)*Heaviside(1 - x)/(4*x)
322
+
323
+ # test passing "None"
324
+ assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \
325
+ -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
326
+ assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \
327
+ -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x)
328
+
329
+ # test expansion of sums
330
+ assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1)*exp(-x)/x
331
+
332
+ # test factorisation of polys
333
+ r = symbols('r', real=True)
334
+ assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo)
335
+ ).subs(x, r).rewrite(sin).simplify() \
336
+ == sin(r)*Heaviside(1 - exp(-r))
337
+
338
+ # test multiplicative substitution
339
+ _a, _b = symbols('a b', positive=True)
340
+ assert IMT(_b**(-s/_a)*factorial(s/_a)/s, s, x, (0, oo)) == exp(-_b*x**_a)
341
+ assert IMT(factorial(_a/_b + s/_b)/(_a + s), s, x, (-_a, oo)) == x**_a*exp(-x**_b)
342
+
343
+ def simp_pows(expr):
344
+ return simplify(powsimp(expand_mul(expr, deep=False), force=True)).replace(exp_polar, exp)
345
+
346
+ # Now test the inverses of all direct transforms tested above
347
+
348
+ # Section 8.4.2
349
+ nu = symbols('nu', real=True)
350
+ assert IMT(-1/(nu + s), s, x, (-oo, None)) == x**nu*Heaviside(x - 1)
351
+ assert IMT(1/(nu + s), s, x, (None, oo)) == x**nu*Heaviside(1 - x)
352
+ assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \
353
+ == (1 - x)**(beta - 1)*Heaviside(1 - x)
354
+ assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s),
355
+ s, x, (-oo, None))) \
356
+ == (x - 1)**(beta - 1)*Heaviside(x - 1)
357
+ assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \
358
+ == (1/(x + 1))**rho
359
+ assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c)
360
+ *gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi,
361
+ s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \
362
+ == (x**c - d**c)/(x - d)
363
+
364
+ assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s)
365
+ *gamma(-c/2 - s)/gamma(1 - c - s),
366
+ s, x, (0, -re(c)/2))) == \
367
+ (1 + sqrt(x + 1))**c
368
+ assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s)
369
+ /gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \
370
+ b**(a - 1)*(b**2*(sqrt(1 + x/b**2) + 1)**a + x*(sqrt(1 + x/b**2) + 1
371
+ )**(a - 1))/(b**2 + x)
372
+ assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s)
373
+ / gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \
374
+ b**c*(sqrt(1 + x/b**2) + 1)**c
375
+
376
+ # Section 8.4.5
377
+ assert IMT(24/s**5, s, x, (0, oo)) == log(x)**4*Heaviside(1 - x)
378
+ assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \
379
+ log(x)**3*Heaviside(x - 1)
380
+ assert IMT(pi/(s*sin(pi*s)), s, x, (-1, 0)) == log(x + 1)
381
+ assert IMT(pi/(s*sin(pi*s/2)), s, x, (-2, 0)) == log(x**2 + 1)
382
+ assert IMT(pi/(s*sin(2*pi*s)), s, x, (Rational(-1, 2), 0)) == log(sqrt(x) + 1)
383
+ assert IMT(pi/(s*sin(pi*s)), s, x, (0, 1)) == log(1 + 1/x)
384
+
385
+ # TODO
386
+ def mysimp(expr):
387
+ from sympy.core.function import expand
388
+ from sympy.simplify.powsimp import powsimp
389
+ from sympy.simplify.simplify import logcombine
390
+ return expand(
391
+ powsimp(logcombine(expr, force=True), force=True, deep=True),
392
+ force=True).replace(exp_polar, exp)
393
+
394
+ assert mysimp(mysimp(IMT(pi/(s*tan(pi*s)), s, x, (-1, 0)))) in [
395
+ log(1 - x)*Heaviside(1 - x) + log(x - 1)*Heaviside(x - 1),
396
+ log(x)*Heaviside(x - 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x +
397
+ 1)*Heaviside(-x + 1)]
398
+ # test passing cot
399
+ assert mysimp(IMT(pi*cot(pi*s)/s, s, x, (0, 1))) in [
400
+ log(1/x - 1)*Heaviside(1 - x) + log(1 - 1/x)*Heaviside(x - 1),
401
+ -log(x)*Heaviside(-x + 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x +
402
+ 1)*Heaviside(-x + 1), ]
403
+
404
+ # 8.4.14
405
+ assert IMT(-gamma(s + S.Half)/(sqrt(pi)*s), s, x, (Rational(-1, 2), 0)) == \
406
+ erf(sqrt(x))
407
+
408
+ # 8.4.19
409
+ assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, Rational(3, 4)))) \
410
+ == besselj(a, 2*sqrt(x))
411
+ assert simplify(IMT(2**a*gamma(S.Half - 2*s)*gamma(s + (a + 1)/2)
412
+ / (gamma(1 - s - a/2)*gamma(1 - 2*s + a)),
413
+ s, x, (-(re(a) + 1)/2, Rational(1, 4)))) == \
414
+ sin(sqrt(x))*besselj(a, sqrt(x))
415
+ assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S.Half - 2*s)
416
+ / (gamma(S.Half - s - a/2)*gamma(1 - 2*s + a)),
417
+ s, x, (-re(a)/2, Rational(1, 4)))) == \
418
+ cos(sqrt(x))*besselj(a, sqrt(x))
419
+ # TODO this comes out as an amazing mess, but simplifies nicely
420
+ assert simplify(IMT(gamma(a + s)*gamma(S.Half - s)
421
+ / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)),
422
+ s, x, (-re(a), S.Half))) == \
423
+ besselj(a, sqrt(x))**2
424
+ assert simplify(IMT(gamma(s)*gamma(S.Half - s)
425
+ / (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)),
426
+ s, x, (0, S.Half))) == \
427
+ besselj(-a, sqrt(x))*besselj(a, sqrt(x))
428
+ assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s)
429
+ / (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1)
430
+ *gamma(a/2 + b/2 - s + 1)),
431
+ s, x, (-(re(a) + re(b))/2, S.Half))) == \
432
+ besselj(a, sqrt(x))*besselj(b, sqrt(x))
433
+
434
+ # Section 8.4.20
435
+ # TODO this can be further simplified!
436
+ assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) *
437
+ gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) /
438
+ (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)),
439
+ s, x,
440
+ (Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S.Half))) == \
441
+ besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) -
442
+ besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b)
443
+ # TODO more
444
+
445
+ # for coverage
446
+
447
+ assert IMT(pi/cos(pi*s), s, x, (0, S.Half)) == sqrt(x)/(x + 1)
448
+
449
+
450
+ def test_fourier_transform():
451
+ from sympy.core.function import (expand, expand_complex, expand_trig)
452
+ from sympy.polys.polytools import factor
453
+ from sympy.simplify.simplify import simplify
454
+ FT = fourier_transform
455
+ IFT = inverse_fourier_transform
456
+
457
+ def simp(x):
458
+ return simplify(expand_trig(expand_complex(expand(x))))
459
+
460
+ def sinc(x):
461
+ return sin(pi*x)/(pi*x)
462
+ k = symbols('k', real=True)
463
+ f = Function("f")
464
+
465
+ # TODO for this to work with real a, need to expand abs(a*x) to abs(a)*abs(x)
466
+ a = symbols('a', positive=True)
467
+ b = symbols('b', positive=True)
468
+
469
+ posk = symbols('posk', positive=True)
470
+
471
+ # Test unevaluated form
472
+ assert fourier_transform(f(x), x, k) == FourierTransform(f(x), x, k)
473
+ assert inverse_fourier_transform(
474
+ f(k), k, x) == InverseFourierTransform(f(k), k, x)
475
+
476
+ # basic examples from wikipedia
477
+ assert simp(FT(Heaviside(1 - abs(2*a*x)), x, k)) == sinc(k/a)/a
478
+ # TODO IFT is a *mess*
479
+ assert simp(FT(Heaviside(1 - abs(a*x))*(1 - abs(a*x)), x, k)) == sinc(k/a)**2/a
480
+ # TODO IFT
481
+
482
+ assert factor(FT(exp(-a*x)*Heaviside(x), x, k), extension=I) == \
483
+ 1/(a + 2*pi*I*k)
484
+ # NOTE: the ift comes out in pieces
485
+ assert IFT(1/(a + 2*pi*I*x), x, posk,
486
+ noconds=False) == (exp(-a*posk), True)
487
+ assert IFT(1/(a + 2*pi*I*x), x, -posk,
488
+ noconds=False) == (0, True)
489
+ assert IFT(1/(a + 2*pi*I*x), x, symbols('k', negative=True),
490
+ noconds=False) == (0, True)
491
+ # TODO IFT without factoring comes out as meijer g
492
+
493
+ assert factor(FT(x*exp(-a*x)*Heaviside(x), x, k), extension=I) == \
494
+ 1/(a + 2*pi*I*k)**2
495
+ assert FT(exp(-a*x)*sin(b*x)*Heaviside(x), x, k) == \
496
+ b/(b**2 + (a + 2*I*pi*k)**2)
497
+
498
+ assert FT(exp(-a*x**2), x, k) == sqrt(pi)*exp(-pi**2*k**2/a)/sqrt(a)
499
+ assert IFT(sqrt(pi/a)*exp(-(pi*k)**2/a), k, x) == exp(-a*x**2)
500
+ assert FT(exp(-a*abs(x)), x, k) == 2*a/(a**2 + 4*pi**2*k**2)
501
+ # TODO IFT (comes out as meijer G)
502
+
503
+ # TODO besselj(n, x), n an integer > 0 actually can be done...
504
+
505
+ # TODO are there other common transforms (no distributions!)?
506
+
507
+
508
+ def test_sine_transform():
509
+ t = symbols("t")
510
+ w = symbols("w")
511
+ a = symbols("a")
512
+ f = Function("f")
513
+
514
+ # Test unevaluated form
515
+ assert sine_transform(f(t), t, w) == SineTransform(f(t), t, w)
516
+ assert inverse_sine_transform(
517
+ f(w), w, t) == InverseSineTransform(f(w), w, t)
518
+
519
+ assert sine_transform(1/sqrt(t), t, w) == 1/sqrt(w)
520
+ assert inverse_sine_transform(1/sqrt(w), w, t) == 1/sqrt(t)
521
+
522
+ assert sine_transform((1/sqrt(t))**3, t, w) == 2*sqrt(w)
523
+
524
+ assert sine_transform(t**(-a), t, w) == 2**(
525
+ -a + S.Half)*w**(a - 1)*gamma(-a/2 + 1)/gamma((a + 1)/2)
526
+ assert inverse_sine_transform(2**(-a + S(
527
+ 1)/2)*w**(a - 1)*gamma(-a/2 + 1)/gamma(a/2 + S.Half), w, t) == t**(-a)
528
+
529
+ assert sine_transform(
530
+ exp(-a*t), t, w) == sqrt(2)*w/(sqrt(pi)*(a**2 + w**2))
531
+ assert inverse_sine_transform(
532
+ sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t)
533
+
534
+ assert sine_transform(
535
+ log(t)/t, t, w) == sqrt(2)*sqrt(pi)*-(log(w**2) + 2*EulerGamma)/4
536
+
537
+ assert sine_transform(
538
+ t*exp(-a*t**2), t, w) == sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2))
539
+ assert inverse_sine_transform(
540
+ sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)), w, t) == t*exp(-a*t**2)
541
+
542
+
543
+ def test_cosine_transform():
544
+ from sympy.functions.special.error_functions import (Ci, Si)
545
+
546
+ t = symbols("t")
547
+ w = symbols("w")
548
+ a = symbols("a")
549
+ f = Function("f")
550
+
551
+ # Test unevaluated form
552
+ assert cosine_transform(f(t), t, w) == CosineTransform(f(t), t, w)
553
+ assert inverse_cosine_transform(
554
+ f(w), w, t) == InverseCosineTransform(f(w), w, t)
555
+
556
+ assert cosine_transform(1/sqrt(t), t, w) == 1/sqrt(w)
557
+ assert inverse_cosine_transform(1/sqrt(w), w, t) == 1/sqrt(t)
558
+
559
+ assert cosine_transform(1/(
560
+ a**2 + t**2), t, w) == sqrt(2)*sqrt(pi)*exp(-a*w)/(2*a)
561
+
562
+ assert cosine_transform(t**(
563
+ -a), t, w) == 2**(-a + S.Half)*w**(a - 1)*gamma((-a + 1)/2)/gamma(a/2)
564
+ assert inverse_cosine_transform(2**(-a + S(
565
+ 1)/2)*w**(a - 1)*gamma(-a/2 + S.Half)/gamma(a/2), w, t) == t**(-a)
566
+
567
+ assert cosine_transform(
568
+ exp(-a*t), t, w) == sqrt(2)*a/(sqrt(pi)*(a**2 + w**2))
569
+ assert inverse_cosine_transform(
570
+ sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t)
571
+
572
+ assert cosine_transform(exp(-a*sqrt(t))*cos(a*sqrt(
573
+ t)), t, w) == a*exp(-a**2/(2*w))/(2*w**Rational(3, 2))
574
+
575
+ assert cosine_transform(1/(a + t), t, w) == sqrt(2)*(
576
+ (-2*Si(a*w) + pi)*sin(a*w)/2 - cos(a*w)*Ci(a*w))/sqrt(pi)
577
+ assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half, 0), ()), (
578
+ (S.Half, 0, 0), (S.Half,)), a**2*w**2/4)/(2*pi), w, t) == 1/(a + t)
579
+
580
+ assert cosine_transform(1/sqrt(a**2 + t**2), t, w) == sqrt(2)*meijerg(
581
+ ((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi))
582
+ assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)), w, t) == 1/(t*sqrt(a**2/t**2 + 1))
583
+
584
+
585
+ def test_hankel_transform():
586
+ r = Symbol("r")
587
+ k = Symbol("k")
588
+ nu = Symbol("nu")
589
+ m = Symbol("m")
590
+ a = symbols("a")
591
+
592
+ assert hankel_transform(1/r, r, k, 0) == 1/k
593
+ assert inverse_hankel_transform(1/k, k, r, 0) == 1/r
594
+
595
+ assert hankel_transform(
596
+ 1/r**m, r, k, 0) == 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2)
597
+ assert inverse_hankel_transform(
598
+ 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2), k, r, 0) == r**(-m)
599
+
600
+ assert hankel_transform(1/r**m, r, k, nu) == (
601
+ 2*2**(-m)*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2))
602
+ assert inverse_hankel_transform(2**(-m + 1)*k**(
603
+ m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2), k, r, nu) == r**(-m)
604
+
605
+ assert hankel_transform(r**nu*exp(-a*r), r, k, nu) == \
606
+ 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S(
607
+ 3)/2)*gamma(nu + Rational(3, 2))/sqrt(pi)
608
+ assert inverse_hankel_transform(
609
+ 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - Rational(3, 2))*gamma(
610
+ nu + Rational(3, 2))/sqrt(pi), k, r, nu) == r**nu*exp(-a*r)
611
+
612
+
613
+ def test_issue_7181():
614
+ assert mellin_transform(1/(1 - x), x, s) != None
615
+
616
+
617
+ def test_issue_8882():
618
+ # This is the original test.
619
+ # from sympy import diff, Integral, integrate
620
+ # r = Symbol('r')
621
+ # psi = 1/r*sin(r)*exp(-(a0*r))
622
+ # h = -1/2*diff(psi, r, r) - 1/r*psi
623
+ # f = 4*pi*psi*h*r**2
624
+ # assert integrate(f, (r, -oo, 3), meijerg=True).has(Integral) == True
625
+
626
+ # To save time, only the critical part is included.
627
+ F = -a**(-s + 1)*(4 + 1/a**2)**(-s/2)*sqrt(1/a**2)*exp(-s*I*pi)* \
628
+ sin(s*atan(sqrt(1/a**2)/2))*gamma(s)
629
+ raises(IntegralTransformError, lambda:
630
+ inverse_mellin_transform(F, s, x, (-1, oo),
631
+ **{'as_meijerg': True, 'needeval': True}))
632
+
633
+
634
+ def test_issue_12591():
635
+ x, y = symbols("x y", real=True)
636
+ assert fourier_transform(exp(x), x, y) == FourierTransform(exp(x), x, y)
parrot/lib/python3.10/site-packages/sympy/integrals/tests/test_trigonometry.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Ne, Rational, Symbol
2
+ from sympy.functions import sin, cos, tan, csc, sec, cot, log, Piecewise
3
+ from sympy.integrals.trigonometry import trigintegrate
4
+
5
+ x = Symbol('x')
6
+
7
+
8
+ def test_trigintegrate_odd():
9
+ assert trigintegrate(Rational(1), x) == x
10
+ assert trigintegrate(x, x) is None
11
+ assert trigintegrate(x**2, x) is None
12
+
13
+ assert trigintegrate(sin(x), x) == -cos(x)
14
+ assert trigintegrate(cos(x), x) == sin(x)
15
+
16
+ assert trigintegrate(sin(3*x), x) == -cos(3*x)/3
17
+ assert trigintegrate(cos(3*x), x) == sin(3*x)/3
18
+
19
+ y = Symbol('y')
20
+ assert trigintegrate(sin(y*x), x) == Piecewise(
21
+ (-cos(y*x)/y, Ne(y, 0)), (0, True))
22
+ assert trigintegrate(cos(y*x), x) == Piecewise(
23
+ (sin(y*x)/y, Ne(y, 0)), (x, True))
24
+ assert trigintegrate(sin(y*x)**2, x) == Piecewise(
25
+ ((x*y/2 - sin(x*y)*cos(x*y)/2)/y, Ne(y, 0)), (0, True))
26
+ assert trigintegrate(sin(y*x)*cos(y*x), x) == Piecewise(
27
+ (sin(x*y)**2/(2*y), Ne(y, 0)), (0, True))
28
+ assert trigintegrate(cos(y*x)**2, x) == Piecewise(
29
+ ((x*y/2 + sin(x*y)*cos(x*y)/2)/y, Ne(y, 0)), (x, True))
30
+
31
+ y = Symbol('y', positive=True)
32
+ # TODO: remove conds='none' below. For this to work we would have to rule
33
+ # out (e.g. by trying solve) the condition y = 0, incompatible with
34
+ # y.is_positive being True.
35
+ assert trigintegrate(sin(y*x), x, conds='none') == -cos(y*x)/y
36
+ assert trigintegrate(cos(y*x), x, conds='none') == sin(y*x)/y
37
+
38
+ assert trigintegrate(sin(x)*cos(x), x) == sin(x)**2/2
39
+ assert trigintegrate(sin(x)*cos(x)**2, x) == -cos(x)**3/3
40
+ assert trigintegrate(sin(x)**2*cos(x), x) == sin(x)**3/3
41
+
42
+ # check if it selects right function to substitute,
43
+ # so the result is kept simple
44
+ assert trigintegrate(sin(x)**7 * cos(x), x) == sin(x)**8/8
45
+ assert trigintegrate(sin(x) * cos(x)**7, x) == -cos(x)**8/8
46
+
47
+ assert trigintegrate(sin(x)**7 * cos(x)**3, x) == \
48
+ -sin(x)**10/10 + sin(x)**8/8
49
+ assert trigintegrate(sin(x)**3 * cos(x)**7, x) == \
50
+ cos(x)**10/10 - cos(x)**8/8
51
+
52
+ # both n, m are odd and -ve, and not necessarily equal
53
+ assert trigintegrate(sin(x)**-1*cos(x)**-1, x) == \
54
+ -log(sin(x)**2 - 1)/2 + log(sin(x))
55
+
56
+
57
+ def test_trigintegrate_even():
58
+ assert trigintegrate(sin(x)**2, x) == x/2 - cos(x)*sin(x)/2
59
+ assert trigintegrate(cos(x)**2, x) == x/2 + cos(x)*sin(x)/2
60
+
61
+ assert trigintegrate(sin(3*x)**2, x) == x/2 - cos(3*x)*sin(3*x)/6
62
+ assert trigintegrate(cos(3*x)**2, x) == x/2 + cos(3*x)*sin(3*x)/6
63
+ assert trigintegrate(sin(x)**2 * cos(x)**2, x) == \
64
+ x/8 - sin(2*x)*cos(2*x)/16
65
+
66
+ assert trigintegrate(sin(x)**4 * cos(x)**2, x) == \
67
+ x/16 - sin(x) *cos(x)/16 - sin(x)**3*cos(x)/24 + \
68
+ sin(x)**5*cos(x)/6
69
+
70
+ assert trigintegrate(sin(x)**2 * cos(x)**4, x) == \
71
+ x/16 + cos(x) *sin(x)/16 + cos(x)**3*sin(x)/24 - \
72
+ cos(x)**5*sin(x)/6
73
+
74
+ assert trigintegrate(sin(x)**(-4), x) == -2*cos(x)/(3*sin(x)) \
75
+ - cos(x)/(3*sin(x)**3)
76
+
77
+ assert trigintegrate(cos(x)**(-6), x) == sin(x)/(5*cos(x)**5) \
78
+ + 4*sin(x)/(15*cos(x)**3) + 8*sin(x)/(15*cos(x))
79
+
80
+
81
+ def test_trigintegrate_mixed():
82
+ assert trigintegrate(sin(x)*sec(x), x) == -log(cos(x))
83
+ assert trigintegrate(sin(x)*csc(x), x) == x
84
+ assert trigintegrate(sin(x)*cot(x), x) == sin(x)
85
+
86
+ assert trigintegrate(cos(x)*sec(x), x) == x
87
+ assert trigintegrate(cos(x)*csc(x), x) == log(sin(x))
88
+ assert trigintegrate(cos(x)*tan(x), x) == -cos(x)
89
+ assert trigintegrate(cos(x)*cot(x), x) == log(cos(x) - 1)/2 \
90
+ - log(cos(x) + 1)/2 + cos(x)
91
+ assert trigintegrate(cot(x)*cos(x)**2, x) == log(sin(x)) - sin(x)**2/2
92
+
93
+
94
+ def test_trigintegrate_symbolic():
95
+ n = Symbol('n', integer=True)
96
+ assert trigintegrate(cos(x)**n, x) is None
97
+ assert trigintegrate(sin(x)**n, x) is None
98
+ assert trigintegrate(cot(x)**n, x) is None
parrot/lib/python3.10/site-packages/sympy/integrals/transforms.py ADDED
@@ -0,0 +1,1590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Integral Transforms """
2
+ from functools import reduce, wraps
3
+ from itertools import repeat
4
+ from sympy.core import S, pi
5
+ from sympy.core.add import Add
6
+ from sympy.core.function import (
7
+ AppliedUndef, count_ops, expand, expand_mul, Function)
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.intfunc import igcd, ilcm
10
+ from sympy.core.sorting import default_sort_key
11
+ from sympy.core.symbol import Dummy
12
+ from sympy.core.traversal import postorder_traversal
13
+ from sympy.functions.combinatorial.factorials import factorial, rf
14
+ from sympy.functions.elementary.complexes import re, arg, Abs
15
+ from sympy.functions.elementary.exponential import exp, exp_polar
16
+ from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh
17
+ from sympy.functions.elementary.integers import ceiling
18
+ from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
19
+ from sympy.functions.elementary.piecewise import piecewise_fold
20
+ from sympy.functions.elementary.trigonometric import cos, cot, sin, tan
21
+ from sympy.functions.special.bessel import besselj
22
+ from sympy.functions.special.delta_functions import Heaviside
23
+ from sympy.functions.special.gamma_functions import gamma
24
+ from sympy.functions.special.hyper import meijerg
25
+ from sympy.integrals import integrate, Integral
26
+ from sympy.integrals.meijerint import _dummy
27
+ from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And
28
+ from sympy.polys.polyroots import roots
29
+ from sympy.polys.polytools import factor, Poly
30
+ from sympy.polys.rootoftools import CRootOf
31
+ from sympy.utilities.iterables import iterable
32
+ from sympy.utilities.misc import debug
33
+
34
+
35
+ ##########################################################################
36
+ # Helpers / Utilities
37
+ ##########################################################################
38
+
39
+
40
+ class IntegralTransformError(NotImplementedError):
41
+ """
42
+ Exception raised in relation to problems computing transforms.
43
+
44
+ Explanation
45
+ ===========
46
+
47
+ This class is mostly used internally; if integrals cannot be computed
48
+ objects representing unevaluated transforms are usually returned.
49
+
50
+ The hint ``needeval=True`` can be used to disable returning transform
51
+ objects, and instead raise this exception if an integral cannot be
52
+ computed.
53
+ """
54
+ def __init__(self, transform, function, msg):
55
+ super().__init__(
56
+ "%s Transform could not be computed: %s." % (transform, msg))
57
+ self.function = function
58
+
59
+
60
+ class IntegralTransform(Function):
61
+ """
62
+ Base class for integral transforms.
63
+
64
+ Explanation
65
+ ===========
66
+
67
+ This class represents unevaluated transforms.
68
+
69
+ To implement a concrete transform, derive from this class and implement
70
+ the ``_compute_transform(f, x, s, **hints)`` and ``_as_integral(f, x, s)``
71
+ functions. If the transform cannot be computed, raise :obj:`IntegralTransformError`.
72
+
73
+ Also set ``cls._name``. For instance,
74
+
75
+ >>> from sympy import LaplaceTransform
76
+ >>> LaplaceTransform._name
77
+ 'Laplace'
78
+
79
+ Implement ``self._collapse_extra`` if your function returns more than just a
80
+ number and possibly a convergence condition.
81
+ """
82
+
83
+ @property
84
+ def function(self):
85
+ """ The function to be transformed. """
86
+ return self.args[0]
87
+
88
+ @property
89
+ def function_variable(self):
90
+ """ The dependent variable of the function to be transformed. """
91
+ return self.args[1]
92
+
93
+ @property
94
+ def transform_variable(self):
95
+ """ The independent transform variable. """
96
+ return self.args[2]
97
+
98
+ @property
99
+ def free_symbols(self):
100
+ """
101
+ This method returns the symbols that will exist when the transform
102
+ is evaluated.
103
+ """
104
+ return self.function.free_symbols.union({self.transform_variable}) \
105
+ - {self.function_variable}
106
+
107
+ def _compute_transform(self, f, x, s, **hints):
108
+ raise NotImplementedError
109
+
110
+ def _as_integral(self, f, x, s):
111
+ raise NotImplementedError
112
+
113
+ def _collapse_extra(self, extra):
114
+ cond = And(*extra)
115
+ if cond == False:
116
+ raise IntegralTransformError(self.__class__.name, None, '')
117
+ return cond
118
+
119
+ def _try_directly(self, **hints):
120
+ T = None
121
+ try_directly = not any(func.has(self.function_variable)
122
+ for func in self.function.atoms(AppliedUndef))
123
+ if try_directly:
124
+ try:
125
+ T = self._compute_transform(self.function,
126
+ self.function_variable, self.transform_variable, **hints)
127
+ except IntegralTransformError:
128
+ debug('[IT _try ] Caught IntegralTransformError, returns None')
129
+ T = None
130
+
131
+ fn = self.function
132
+ if not fn.is_Add:
133
+ fn = expand_mul(fn)
134
+ return fn, T
135
+
136
+ def doit(self, **hints):
137
+ """
138
+ Try to evaluate the transform in closed form.
139
+
140
+ Explanation
141
+ ===========
142
+
143
+ This general function handles linearity, but apart from that leaves
144
+ pretty much everything to _compute_transform.
145
+
146
+ Standard hints are the following:
147
+
148
+ - ``simplify``: whether or not to simplify the result
149
+ - ``noconds``: if True, do not return convergence conditions
150
+ - ``needeval``: if True, raise IntegralTransformError instead of
151
+ returning IntegralTransform objects
152
+
153
+ The default values of these hints depend on the concrete transform,
154
+ usually the default is
155
+ ``(simplify, noconds, needeval) = (True, False, False)``.
156
+ """
157
+ needeval = hints.pop('needeval', False)
158
+ simplify = hints.pop('simplify', True)
159
+ hints['simplify'] = simplify
160
+
161
+ fn, T = self._try_directly(**hints)
162
+
163
+ if T is not None:
164
+ return T
165
+
166
+ if fn.is_Add:
167
+ hints['needeval'] = needeval
168
+ res = [self.__class__(*([x] + list(self.args[1:]))).doit(**hints)
169
+ for x in fn.args]
170
+ extra = []
171
+ ress = []
172
+ for x in res:
173
+ if not isinstance(x, tuple):
174
+ x = [x]
175
+ ress.append(x[0])
176
+ if len(x) == 2:
177
+ # only a condition
178
+ extra.append(x[1])
179
+ elif len(x) > 2:
180
+ # some region parameters and a condition (Mellin, Laplace)
181
+ extra += [x[1:]]
182
+ if simplify==True:
183
+ res = Add(*ress).simplify()
184
+ else:
185
+ res = Add(*ress)
186
+ if not extra:
187
+ return res
188
+ try:
189
+ extra = self._collapse_extra(extra)
190
+ if iterable(extra):
191
+ return (res,) + tuple(extra)
192
+ else:
193
+ return (res, extra)
194
+ except IntegralTransformError:
195
+ pass
196
+
197
+ if needeval:
198
+ raise IntegralTransformError(
199
+ self.__class__._name, self.function, 'needeval')
200
+
201
+ # TODO handle derivatives etc
202
+
203
+ # pull out constant coefficients
204
+ coeff, rest = fn.as_coeff_mul(self.function_variable)
205
+ return coeff*self.__class__(*([Mul(*rest)] + list(self.args[1:])))
206
+
207
+ @property
208
+ def as_integral(self):
209
+ return self._as_integral(self.function, self.function_variable,
210
+ self.transform_variable)
211
+
212
+ def _eval_rewrite_as_Integral(self, *args, **kwargs):
213
+ return self.as_integral
214
+
215
+
216
+ def _simplify(expr, doit):
217
+ if doit:
218
+ from sympy.simplify import simplify
219
+ from sympy.simplify.powsimp import powdenest
220
+ return simplify(powdenest(piecewise_fold(expr), polar=True))
221
+ return expr
222
+
223
+
224
+ def _noconds_(default):
225
+ """
226
+ This is a decorator generator for dropping convergence conditions.
227
+
228
+ Explanation
229
+ ===========
230
+
231
+ Suppose you define a function ``transform(*args)`` which returns a tuple of
232
+ the form ``(result, cond1, cond2, ...)``.
233
+
234
+ Decorating it ``@_noconds_(default)`` will add a new keyword argument
235
+ ``noconds`` to it. If ``noconds=True``, the return value will be altered to
236
+ be only ``result``, whereas if ``noconds=False`` the return value will not
237
+ be altered.
238
+
239
+ The default value of the ``noconds`` keyword will be ``default`` (i.e. the
240
+ argument of this function).
241
+ """
242
+ def make_wrapper(func):
243
+ @wraps(func)
244
+ def wrapper(*args, noconds=default, **kwargs):
245
+ res = func(*args, **kwargs)
246
+ if noconds:
247
+ return res[0]
248
+ return res
249
+ return wrapper
250
+ return make_wrapper
251
+ _noconds = _noconds_(False)
252
+
253
+
254
+ ##########################################################################
255
+ # Mellin Transform
256
+ ##########################################################################
257
+
258
+ def _default_integrator(f, x):
259
+ return integrate(f, (x, S.Zero, S.Infinity))
260
+
261
+
262
+ @_noconds
263
+ def _mellin_transform(f, x, s_, integrator=_default_integrator, simplify=True):
264
+ """ Backend function to compute Mellin transforms. """
265
+ # We use a fresh dummy, because assumptions on s might drop conditions on
266
+ # convergence of the integral.
267
+ s = _dummy('s', 'mellin-transform', f)
268
+ F = integrator(x**(s - 1) * f, x)
269
+
270
+ if not F.has(Integral):
271
+ return _simplify(F.subs(s, s_), simplify), (S.NegativeInfinity, S.Infinity), S.true
272
+
273
+ if not F.is_Piecewise: # XXX can this work if integration gives continuous result now?
274
+ raise IntegralTransformError('Mellin', f, 'could not compute integral')
275
+
276
+ F, cond = F.args[0]
277
+ if F.has(Integral):
278
+ raise IntegralTransformError(
279
+ 'Mellin', f, 'integral in unexpected form')
280
+
281
+ def process_conds(cond):
282
+ """
283
+ Turn ``cond`` into a strip (a, b), and auxiliary conditions.
284
+ """
285
+ from sympy.solvers.inequalities import _solve_inequality
286
+ a = S.NegativeInfinity
287
+ b = S.Infinity
288
+ aux = S.true
289
+ conds = conjuncts(to_cnf(cond))
290
+ t = Dummy('t', real=True)
291
+ for c in conds:
292
+ a_ = S.Infinity
293
+ b_ = S.NegativeInfinity
294
+ aux_ = []
295
+ for d in disjuncts(c):
296
+ d_ = d.replace(
297
+ re, lambda x: x.as_real_imag()[0]).subs(re(s), t)
298
+ if not d.is_Relational or \
299
+ d.rel_op in ('==', '!=') \
300
+ or d_.has(s) or not d_.has(t):
301
+ aux_ += [d]
302
+ continue
303
+ soln = _solve_inequality(d_, t)
304
+ if not soln.is_Relational or \
305
+ soln.rel_op in ('==', '!='):
306
+ aux_ += [d]
307
+ continue
308
+ if soln.lts == t:
309
+ b_ = Max(soln.gts, b_)
310
+ else:
311
+ a_ = Min(soln.lts, a_)
312
+ if a_ is not S.Infinity and a_ != b:
313
+ a = Max(a_, a)
314
+ elif b_ is not S.NegativeInfinity and b_ != a:
315
+ b = Min(b_, b)
316
+ else:
317
+ aux = And(aux, Or(*aux_))
318
+ return a, b, aux
319
+
320
+ conds = [process_conds(c) for c in disjuncts(cond)]
321
+ conds = [x for x in conds if x[2] != False]
322
+ conds.sort(key=lambda x: (x[0] - x[1], count_ops(x[2])))
323
+
324
+ if not conds:
325
+ raise IntegralTransformError('Mellin', f, 'no convergence found')
326
+
327
+ a, b, aux = conds[0]
328
+ return _simplify(F.subs(s, s_), simplify), (a, b), aux
329
+
330
+
331
+ class MellinTransform(IntegralTransform):
332
+ """
333
+ Class representing unevaluated Mellin transforms.
334
+
335
+ For usage of this class, see the :class:`IntegralTransform` docstring.
336
+
337
+ For how to compute Mellin transforms, see the :func:`mellin_transform`
338
+ docstring.
339
+ """
340
+
341
+ _name = 'Mellin'
342
+
343
+ def _compute_transform(self, f, x, s, **hints):
344
+ return _mellin_transform(f, x, s, **hints)
345
+
346
+ def _as_integral(self, f, x, s):
347
+ return Integral(f*x**(s - 1), (x, S.Zero, S.Infinity))
348
+
349
+ def _collapse_extra(self, extra):
350
+ a = []
351
+ b = []
352
+ cond = []
353
+ for (sa, sb), c in extra:
354
+ a += [sa]
355
+ b += [sb]
356
+ cond += [c]
357
+ res = (Max(*a), Min(*b)), And(*cond)
358
+ if (res[0][0] >= res[0][1]) == True or res[1] == False:
359
+ raise IntegralTransformError(
360
+ 'Mellin', None, 'no combined convergence.')
361
+ return res
362
+
363
+
364
+ def mellin_transform(f, x, s, **hints):
365
+ r"""
366
+ Compute the Mellin transform `F(s)` of `f(x)`,
367
+
368
+ .. math :: F(s) = \int_0^\infty x^{s-1} f(x) \mathrm{d}x.
369
+
370
+ For all "sensible" functions, this converges absolutely in a strip
371
+ `a < \operatorname{Re}(s) < b`.
372
+
373
+ Explanation
374
+ ===========
375
+
376
+ The Mellin transform is related via change of variables to the Fourier
377
+ transform, and also to the (bilateral) Laplace transform.
378
+
379
+ This function returns ``(F, (a, b), cond)``
380
+ where ``F`` is the Mellin transform of ``f``, ``(a, b)`` is the fundamental strip
381
+ (as above), and ``cond`` are auxiliary convergence conditions.
382
+
383
+ If the integral cannot be computed in closed form, this function returns
384
+ an unevaluated :class:`MellinTransform` object.
385
+
386
+ For a description of possible hints, refer to the docstring of
387
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=False``,
388
+ then only `F` will be returned (i.e. not ``cond``, and also not the strip
389
+ ``(a, b)``).
390
+
391
+ Examples
392
+ ========
393
+
394
+ >>> from sympy import mellin_transform, exp
395
+ >>> from sympy.abc import x, s
396
+ >>> mellin_transform(exp(-x), x, s)
397
+ (gamma(s), (0, oo), True)
398
+
399
+ See Also
400
+ ========
401
+
402
+ inverse_mellin_transform, laplace_transform, fourier_transform
403
+ hankel_transform, inverse_hankel_transform
404
+ """
405
+ return MellinTransform(f, x, s).doit(**hints)
406
+
407
+
408
+ def _rewrite_sin(m_n, s, a, b):
409
+ """
410
+ Re-write the sine function ``sin(m*s + n)`` as gamma functions, compatible
411
+ with the strip (a, b).
412
+
413
+ Return ``(gamma1, gamma2, fac)`` so that ``f == fac/(gamma1 * gamma2)``.
414
+
415
+ Examples
416
+ ========
417
+
418
+ >>> from sympy.integrals.transforms import _rewrite_sin
419
+ >>> from sympy import pi, S
420
+ >>> from sympy.abc import s
421
+ >>> _rewrite_sin((pi, 0), s, 0, 1)
422
+ (gamma(s), gamma(1 - s), pi)
423
+ >>> _rewrite_sin((pi, 0), s, 1, 0)
424
+ (gamma(s - 1), gamma(2 - s), -pi)
425
+ >>> _rewrite_sin((pi, 0), s, -1, 0)
426
+ (gamma(s + 1), gamma(-s), -pi)
427
+ >>> _rewrite_sin((pi, pi/2), s, S(1)/2, S(3)/2)
428
+ (gamma(s - 1/2), gamma(3/2 - s), -pi)
429
+ >>> _rewrite_sin((pi, pi), s, 0, 1)
430
+ (gamma(s), gamma(1 - s), -pi)
431
+ >>> _rewrite_sin((2*pi, 0), s, 0, S(1)/2)
432
+ (gamma(2*s), gamma(1 - 2*s), pi)
433
+ >>> _rewrite_sin((2*pi, 0), s, S(1)/2, 1)
434
+ (gamma(2*s - 1), gamma(2 - 2*s), -pi)
435
+ """
436
+ # (This is a separate function because it is moderately complicated,
437
+ # and I want to doctest it.)
438
+ # We want to use pi/sin(pi*x) = gamma(x)*gamma(1-x).
439
+ # But there is one comlication: the gamma functions determine the
440
+ # inegration contour in the definition of the G-function. Usually
441
+ # it would not matter if this is slightly shifted, unless this way
442
+ # we create an undefined function!
443
+ # So we try to write this in such a way that the gammas are
444
+ # eminently on the right side of the strip.
445
+ m, n = m_n
446
+
447
+ m = expand_mul(m/pi)
448
+ n = expand_mul(n/pi)
449
+ r = ceiling(-m*a - n.as_real_imag()[0]) # Don't use re(n), does not expand
450
+ return gamma(m*s + n + r), gamma(1 - n - r - m*s), (-1)**r*pi
451
+
452
+
453
+ class MellinTransformStripError(ValueError):
454
+ """
455
+ Exception raised by _rewrite_gamma. Mainly for internal use.
456
+ """
457
+ pass
458
+
459
+
460
+ def _rewrite_gamma(f, s, a, b):
461
+ """
462
+ Try to rewrite the product f(s) as a product of gamma functions,
463
+ so that the inverse Mellin transform of f can be expressed as a meijer
464
+ G function.
465
+
466
+ Explanation
467
+ ===========
468
+
469
+ Return (an, ap), (bm, bq), arg, exp, fac such that
470
+ G((an, ap), (bm, bq), arg/z**exp)*fac is the inverse Mellin transform of f(s).
471
+
472
+ Raises IntegralTransformError or MellinTransformStripError on failure.
473
+
474
+ It is asserted that f has no poles in the fundamental strip designated by
475
+ (a, b). One of a and b is allowed to be None. The fundamental strip is
476
+ important, because it determines the inversion contour.
477
+
478
+ This function can handle exponentials, linear factors, trigonometric
479
+ functions.
480
+
481
+ This is a helper function for inverse_mellin_transform that will not
482
+ attempt any transformations on f.
483
+
484
+ Examples
485
+ ========
486
+
487
+ >>> from sympy.integrals.transforms import _rewrite_gamma
488
+ >>> from sympy.abc import s
489
+ >>> from sympy import oo
490
+ >>> _rewrite_gamma(s*(s+3)*(s-1), s, -oo, oo)
491
+ (([], [-3, 0, 1]), ([-2, 1, 2], []), 1, 1, -1)
492
+ >>> _rewrite_gamma((s-1)**2, s, -oo, oo)
493
+ (([], [1, 1]), ([2, 2], []), 1, 1, 1)
494
+
495
+ Importance of the fundamental strip:
496
+
497
+ >>> _rewrite_gamma(1/s, s, 0, oo)
498
+ (([1], []), ([], [0]), 1, 1, 1)
499
+ >>> _rewrite_gamma(1/s, s, None, oo)
500
+ (([1], []), ([], [0]), 1, 1, 1)
501
+ >>> _rewrite_gamma(1/s, s, 0, None)
502
+ (([1], []), ([], [0]), 1, 1, 1)
503
+ >>> _rewrite_gamma(1/s, s, -oo, 0)
504
+ (([], [1]), ([0], []), 1, 1, -1)
505
+ >>> _rewrite_gamma(1/s, s, None, 0)
506
+ (([], [1]), ([0], []), 1, 1, -1)
507
+ >>> _rewrite_gamma(1/s, s, -oo, None)
508
+ (([], [1]), ([0], []), 1, 1, -1)
509
+
510
+ >>> _rewrite_gamma(2**(-s+3), s, -oo, oo)
511
+ (([], []), ([], []), 1/2, 1, 8)
512
+ """
513
+ # Our strategy will be as follows:
514
+ # 1) Guess a constant c such that the inversion integral should be
515
+ # performed wrt s'=c*s (instead of plain s). Write s for s'.
516
+ # 2) Process all factors, rewrite them independently as gamma functions in
517
+ # argument s, or exponentials of s.
518
+ # 3) Try to transform all gamma functions s.t. they have argument
519
+ # a+s or a-s.
520
+ # 4) Check that the resulting G function parameters are valid.
521
+ # 5) Combine all the exponentials.
522
+
523
+ a_, b_ = S([a, b])
524
+
525
+ def left(c, is_numer):
526
+ """
527
+ Decide whether pole at c lies to the left of the fundamental strip.
528
+ """
529
+ # heuristically, this is the best chance for us to solve the inequalities
530
+ c = expand(re(c))
531
+ if a_ is None and b_ is S.Infinity:
532
+ return True
533
+ if a_ is None:
534
+ return c < b_
535
+ if b_ is None:
536
+ return c <= a_
537
+ if (c >= b_) == True:
538
+ return False
539
+ if (c <= a_) == True:
540
+ return True
541
+ if is_numer:
542
+ return None
543
+ if a_.free_symbols or b_.free_symbols or c.free_symbols:
544
+ return None # XXX
545
+ #raise IntegralTransformError('Inverse Mellin', f,
546
+ # 'Could not determine position of singularity %s'
547
+ # ' relative to fundamental strip' % c)
548
+ raise MellinTransformStripError('Pole inside critical strip?')
549
+
550
+ # 1)
551
+ s_multipliers = []
552
+ for g in f.atoms(gamma):
553
+ if not g.has(s):
554
+ continue
555
+ arg = g.args[0]
556
+ if arg.is_Add:
557
+ arg = arg.as_independent(s)[1]
558
+ coeff, _ = arg.as_coeff_mul(s)
559
+ s_multipliers += [coeff]
560
+ for g in f.atoms(sin, cos, tan, cot):
561
+ if not g.has(s):
562
+ continue
563
+ arg = g.args[0]
564
+ if arg.is_Add:
565
+ arg = arg.as_independent(s)[1]
566
+ coeff, _ = arg.as_coeff_mul(s)
567
+ s_multipliers += [coeff/pi]
568
+ s_multipliers = [Abs(x) if x.is_extended_real else x for x in s_multipliers]
569
+ common_coefficient = S.One
570
+ for x in s_multipliers:
571
+ if not x.is_Rational:
572
+ common_coefficient = x
573
+ break
574
+ s_multipliers = [x/common_coefficient for x in s_multipliers]
575
+ if not (all(x.is_Rational for x in s_multipliers) and
576
+ common_coefficient.is_extended_real):
577
+ raise IntegralTransformError("Gamma", None, "Nonrational multiplier")
578
+ s_multiplier = common_coefficient/reduce(ilcm, [S(x.q)
579
+ for x in s_multipliers], S.One)
580
+ if s_multiplier == common_coefficient:
581
+ if len(s_multipliers) == 0:
582
+ s_multiplier = common_coefficient
583
+ else:
584
+ s_multiplier = common_coefficient \
585
+ *reduce(igcd, [S(x.p) for x in s_multipliers])
586
+
587
+ f = f.subs(s, s/s_multiplier)
588
+ fac = S.One/s_multiplier
589
+ exponent = S.One/s_multiplier
590
+ if a_ is not None:
591
+ a_ *= s_multiplier
592
+ if b_ is not None:
593
+ b_ *= s_multiplier
594
+
595
+ # 2)
596
+ numer, denom = f.as_numer_denom()
597
+ numer = Mul.make_args(numer)
598
+ denom = Mul.make_args(denom)
599
+ args = list(zip(numer, repeat(True))) + list(zip(denom, repeat(False)))
600
+
601
+ facs = []
602
+ dfacs = []
603
+ # *_gammas will contain pairs (a, c) representing Gamma(a*s + c)
604
+ numer_gammas = []
605
+ denom_gammas = []
606
+ # exponentials will contain bases for exponentials of s
607
+ exponentials = []
608
+
609
+ def exception(fact):
610
+ return IntegralTransformError("Inverse Mellin", f, "Unrecognised form '%s'." % fact)
611
+ while args:
612
+ fact, is_numer = args.pop()
613
+ if is_numer:
614
+ ugammas, lgammas = numer_gammas, denom_gammas
615
+ ufacs = facs
616
+ else:
617
+ ugammas, lgammas = denom_gammas, numer_gammas
618
+ ufacs = dfacs
619
+
620
+ def linear_arg(arg):
621
+ """ Test if arg is of form a*s+b, raise exception if not. """
622
+ if not arg.is_polynomial(s):
623
+ raise exception(fact)
624
+ p = Poly(arg, s)
625
+ if p.degree() != 1:
626
+ raise exception(fact)
627
+ return p.all_coeffs()
628
+
629
+ # constants
630
+ if not fact.has(s):
631
+ ufacs += [fact]
632
+ # exponentials
633
+ elif fact.is_Pow or isinstance(fact, exp):
634
+ if fact.is_Pow:
635
+ base = fact.base
636
+ exp_ = fact.exp
637
+ else:
638
+ base = exp_polar(1)
639
+ exp_ = fact.exp
640
+ if exp_.is_Integer:
641
+ cond = is_numer
642
+ if exp_ < 0:
643
+ cond = not cond
644
+ args += [(base, cond)]*Abs(exp_)
645
+ continue
646
+ elif not base.has(s):
647
+ a, b = linear_arg(exp_)
648
+ if not is_numer:
649
+ base = 1/base
650
+ exponentials += [base**a]
651
+ facs += [base**b]
652
+ else:
653
+ raise exception(fact)
654
+ # linear factors
655
+ elif fact.is_polynomial(s):
656
+ p = Poly(fact, s)
657
+ if p.degree() != 1:
658
+ # We completely factor the poly. For this we need the roots.
659
+ # Now roots() only works in some cases (low degree), and CRootOf
660
+ # only works without parameters. So try both...
661
+ coeff = p.LT()[1]
662
+ rs = roots(p, s)
663
+ if len(rs) != p.degree():
664
+ rs = CRootOf.all_roots(p)
665
+ ufacs += [coeff]
666
+ args += [(s - c, is_numer) for c in rs]
667
+ continue
668
+ a, c = p.all_coeffs()
669
+ ufacs += [a]
670
+ c /= -a
671
+ # Now need to convert s - c
672
+ if left(c, is_numer):
673
+ ugammas += [(S.One, -c + 1)]
674
+ lgammas += [(S.One, -c)]
675
+ else:
676
+ ufacs += [-1]
677
+ ugammas += [(S.NegativeOne, c + 1)]
678
+ lgammas += [(S.NegativeOne, c)]
679
+ elif isinstance(fact, gamma):
680
+ a, b = linear_arg(fact.args[0])
681
+ if is_numer:
682
+ if (a > 0 and (left(-b/a, is_numer) == False)) or \
683
+ (a < 0 and (left(-b/a, is_numer) == True)):
684
+ raise NotImplementedError(
685
+ 'Gammas partially over the strip.')
686
+ ugammas += [(a, b)]
687
+ elif isinstance(fact, sin):
688
+ # We try to re-write all trigs as gammas. This is not in
689
+ # general the best strategy, since sometimes this is impossible,
690
+ # but rewriting as exponentials would work. However trig functions
691
+ # in inverse mellin transforms usually all come from simplifying
692
+ # gamma terms, so this should work.
693
+ a = fact.args[0]
694
+ if is_numer:
695
+ # No problem with the poles.
696
+ gamma1, gamma2, fac_ = gamma(a/pi), gamma(1 - a/pi), pi
697
+ else:
698
+ gamma1, gamma2, fac_ = _rewrite_sin(linear_arg(a), s, a_, b_)
699
+ args += [(gamma1, not is_numer), (gamma2, not is_numer)]
700
+ ufacs += [fac_]
701
+ elif isinstance(fact, tan):
702
+ a = fact.args[0]
703
+ args += [(sin(a, evaluate=False), is_numer),
704
+ (sin(pi/2 - a, evaluate=False), not is_numer)]
705
+ elif isinstance(fact, cos):
706
+ a = fact.args[0]
707
+ args += [(sin(pi/2 - a, evaluate=False), is_numer)]
708
+ elif isinstance(fact, cot):
709
+ a = fact.args[0]
710
+ args += [(sin(pi/2 - a, evaluate=False), is_numer),
711
+ (sin(a, evaluate=False), not is_numer)]
712
+ else:
713
+ raise exception(fact)
714
+
715
+ fac *= Mul(*facs)/Mul(*dfacs)
716
+
717
+ # 3)
718
+ an, ap, bm, bq = [], [], [], []
719
+ for gammas, plus, minus, is_numer in [(numer_gammas, an, bm, True),
720
+ (denom_gammas, bq, ap, False)]:
721
+ while gammas:
722
+ a, c = gammas.pop()
723
+ if a != -1 and a != +1:
724
+ # We use the gamma function multiplication theorem.
725
+ p = Abs(S(a))
726
+ newa = a/p
727
+ newc = c/p
728
+ if not a.is_Integer:
729
+ raise TypeError("a is not an integer")
730
+ for k in range(p):
731
+ gammas += [(newa, newc + k/p)]
732
+ if is_numer:
733
+ fac *= (2*pi)**((1 - p)/2) * p**(c - S.Half)
734
+ exponentials += [p**a]
735
+ else:
736
+ fac /= (2*pi)**((1 - p)/2) * p**(c - S.Half)
737
+ exponentials += [p**(-a)]
738
+ continue
739
+ if a == +1:
740
+ plus.append(1 - c)
741
+ else:
742
+ minus.append(c)
743
+
744
+ # 4)
745
+ # TODO
746
+
747
+ # 5)
748
+ arg = Mul(*exponentials)
749
+
750
+ # for testability, sort the arguments
751
+ an.sort(key=default_sort_key)
752
+ ap.sort(key=default_sort_key)
753
+ bm.sort(key=default_sort_key)
754
+ bq.sort(key=default_sort_key)
755
+
756
+ return (an, ap), (bm, bq), arg, exponent, fac
757
+
758
+
759
+ @_noconds_(True)
760
+ def _inverse_mellin_transform(F, s, x_, strip, as_meijerg=False):
761
+ """ A helper for the real inverse_mellin_transform function, this one here
762
+ assumes x to be real and positive. """
763
+ x = _dummy('t', 'inverse-mellin-transform', F, positive=True)
764
+ # Actually, we won't try integration at all. Instead we use the definition
765
+ # of the Meijer G function as a fairly general inverse mellin transform.
766
+ F = F.rewrite(gamma)
767
+ for g in [factor(F), expand_mul(F), expand(F)]:
768
+ if g.is_Add:
769
+ # do all terms separately
770
+ ress = [_inverse_mellin_transform(G, s, x, strip, as_meijerg,
771
+ noconds=False)
772
+ for G in g.args]
773
+ conds = [p[1] for p in ress]
774
+ ress = [p[0] for p in ress]
775
+ res = Add(*ress)
776
+ if not as_meijerg:
777
+ res = factor(res, gens=res.atoms(Heaviside))
778
+ return res.subs(x, x_), And(*conds)
779
+
780
+ try:
781
+ a, b, C, e, fac = _rewrite_gamma(g, s, strip[0], strip[1])
782
+ except IntegralTransformError:
783
+ continue
784
+ try:
785
+ G = meijerg(a, b, C/x**e)
786
+ except ValueError:
787
+ continue
788
+ if as_meijerg:
789
+ h = G
790
+ else:
791
+ try:
792
+ from sympy.simplify import hyperexpand
793
+ h = hyperexpand(G)
794
+ except NotImplementedError:
795
+ raise IntegralTransformError(
796
+ 'Inverse Mellin', F, 'Could not calculate integral')
797
+
798
+ if h.is_Piecewise and len(h.args) == 3:
799
+ # XXX we break modularity here!
800
+ h = Heaviside(x - Abs(C))*h.args[0].args[0] \
801
+ + Heaviside(Abs(C) - x)*h.args[1].args[0]
802
+ # We must ensure that the integral along the line we want converges,
803
+ # and return that value.
804
+ # See [L], 5.2
805
+ cond = [Abs(arg(G.argument)) < G.delta*pi]
806
+ # Note: we allow ">=" here, this corresponds to convergence if we let
807
+ # limits go to oo symmetrically. ">" corresponds to absolute convergence.
808
+ cond += [And(Or(len(G.ap) != len(G.bq), 0 >= re(G.nu) + 1),
809
+ Abs(arg(G.argument)) == G.delta*pi)]
810
+ cond = Or(*cond)
811
+ if cond == False:
812
+ raise IntegralTransformError(
813
+ 'Inverse Mellin', F, 'does not converge')
814
+ return (h*fac).subs(x, x_), cond
815
+
816
+ raise IntegralTransformError('Inverse Mellin', F, '')
817
+
818
+ _allowed = None
819
+
820
+
821
+ class InverseMellinTransform(IntegralTransform):
822
+ """
823
+ Class representing unevaluated inverse Mellin transforms.
824
+
825
+ For usage of this class, see the :class:`IntegralTransform` docstring.
826
+
827
+ For how to compute inverse Mellin transforms, see the
828
+ :func:`inverse_mellin_transform` docstring.
829
+ """
830
+
831
+ _name = 'Inverse Mellin'
832
+ _none_sentinel = Dummy('None')
833
+ _c = Dummy('c')
834
+
835
+ def __new__(cls, F, s, x, a, b, **opts):
836
+ if a is None:
837
+ a = InverseMellinTransform._none_sentinel
838
+ if b is None:
839
+ b = InverseMellinTransform._none_sentinel
840
+ return IntegralTransform.__new__(cls, F, s, x, a, b, **opts)
841
+
842
+ @property
843
+ def fundamental_strip(self):
844
+ a, b = self.args[3], self.args[4]
845
+ if a is InverseMellinTransform._none_sentinel:
846
+ a = None
847
+ if b is InverseMellinTransform._none_sentinel:
848
+ b = None
849
+ return a, b
850
+
851
+ def _compute_transform(self, F, s, x, **hints):
852
+ # IntegralTransform's doit will cause this hint to exist, but
853
+ # InverseMellinTransform should ignore it
854
+ hints.pop('simplify', True)
855
+ global _allowed
856
+ if _allowed is None:
857
+ _allowed = {
858
+ exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh, coth,
859
+ factorial, rf}
860
+ for f in postorder_traversal(F):
861
+ if f.is_Function and f.has(s) and f.func not in _allowed:
862
+ raise IntegralTransformError('Inverse Mellin', F,
863
+ 'Component %s not recognised.' % f)
864
+ strip = self.fundamental_strip
865
+ return _inverse_mellin_transform(F, s, x, strip, **hints)
866
+
867
+ def _as_integral(self, F, s, x):
868
+ c = self.__class__._c
869
+ return Integral(F*x**(-s), (s, c - S.ImaginaryUnit*S.Infinity, c +
870
+ S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit)
871
+
872
+
873
+ def inverse_mellin_transform(F, s, x, strip, **hints):
874
+ r"""
875
+ Compute the inverse Mellin transform of `F(s)` over the fundamental
876
+ strip given by ``strip=(a, b)``.
877
+
878
+ Explanation
879
+ ===========
880
+
881
+ This can be defined as
882
+
883
+ .. math:: f(x) = \frac{1}{2\pi i} \int_{c - i\infty}^{c + i\infty} x^{-s} F(s) \mathrm{d}s,
884
+
885
+ for any `c` in the fundamental strip. Under certain regularity
886
+ conditions on `F` and/or `f`,
887
+ this recovers `f` from its Mellin transform `F`
888
+ (and vice versa), for positive real `x`.
889
+
890
+ One of `a` or `b` may be passed as ``None``; a suitable `c` will be
891
+ inferred.
892
+
893
+ If the integral cannot be computed in closed form, this function returns
894
+ an unevaluated :class:`InverseMellinTransform` object.
895
+
896
+ Note that this function will assume x to be positive and real, regardless
897
+ of the SymPy assumptions!
898
+
899
+ For a description of possible hints, refer to the docstring of
900
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
901
+
902
+ Examples
903
+ ========
904
+
905
+ >>> from sympy import inverse_mellin_transform, oo, gamma
906
+ >>> from sympy.abc import x, s
907
+ >>> inverse_mellin_transform(gamma(s), s, x, (0, oo))
908
+ exp(-x)
909
+
910
+ The fundamental strip matters:
911
+
912
+ >>> f = 1/(s**2 - 1)
913
+ >>> inverse_mellin_transform(f, s, x, (-oo, -1))
914
+ x*(1 - 1/x**2)*Heaviside(x - 1)/2
915
+ >>> inverse_mellin_transform(f, s, x, (-1, 1))
916
+ -x*Heaviside(1 - x)/2 - Heaviside(x - 1)/(2*x)
917
+ >>> inverse_mellin_transform(f, s, x, (1, oo))
918
+ (1/2 - x**2/2)*Heaviside(1 - x)/x
919
+
920
+ See Also
921
+ ========
922
+
923
+ mellin_transform
924
+ hankel_transform, inverse_hankel_transform
925
+ """
926
+ return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints)
927
+
928
+
929
+ ##########################################################################
930
+ # Fourier Transform
931
+ ##########################################################################
932
+
933
+ @_noconds_(True)
934
+ def _fourier_transform(f, x, k, a, b, name, simplify=True):
935
+ r"""
936
+ Compute a general Fourier-type transform
937
+
938
+ .. math::
939
+
940
+ F(k) = a \int_{-\infty}^{\infty} e^{bixk} f(x)\, dx.
941
+
942
+ For suitable choice of *a* and *b*, this reduces to the standard Fourier
943
+ and inverse Fourier transforms.
944
+ """
945
+ F = integrate(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity))
946
+
947
+ if not F.has(Integral):
948
+ return _simplify(F, simplify), S.true
949
+
950
+ integral_f = integrate(f, (x, S.NegativeInfinity, S.Infinity))
951
+ if integral_f in (S.NegativeInfinity, S.Infinity, S.NaN) or integral_f.has(Integral):
952
+ raise IntegralTransformError(name, f, 'function not integrable on real axis')
953
+
954
+ if not F.is_Piecewise:
955
+ raise IntegralTransformError(name, f, 'could not compute integral')
956
+
957
+ F, cond = F.args[0]
958
+ if F.has(Integral):
959
+ raise IntegralTransformError(name, f, 'integral in unexpected form')
960
+
961
+ return _simplify(F, simplify), cond
962
+
963
+
964
+ class FourierTypeTransform(IntegralTransform):
965
+ """ Base class for Fourier transforms."""
966
+
967
+ def a(self):
968
+ raise NotImplementedError(
969
+ "Class %s must implement a(self) but does not" % self.__class__)
970
+
971
+ def b(self):
972
+ raise NotImplementedError(
973
+ "Class %s must implement b(self) but does not" % self.__class__)
974
+
975
+ def _compute_transform(self, f, x, k, **hints):
976
+ return _fourier_transform(f, x, k,
977
+ self.a(), self.b(),
978
+ self.__class__._name, **hints)
979
+
980
+ def _as_integral(self, f, x, k):
981
+ a = self.a()
982
+ b = self.b()
983
+ return Integral(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity))
984
+
985
+
986
+ class FourierTransform(FourierTypeTransform):
987
+ """
988
+ Class representing unevaluated Fourier transforms.
989
+
990
+ For usage of this class, see the :class:`IntegralTransform` docstring.
991
+
992
+ For how to compute Fourier transforms, see the :func:`fourier_transform`
993
+ docstring.
994
+ """
995
+
996
+ _name = 'Fourier'
997
+
998
+ def a(self):
999
+ return 1
1000
+
1001
+ def b(self):
1002
+ return -2*S.Pi
1003
+
1004
+
1005
+ def fourier_transform(f, x, k, **hints):
1006
+ r"""
1007
+ Compute the unitary, ordinary-frequency Fourier transform of ``f``, defined
1008
+ as
1009
+
1010
+ .. math:: F(k) = \int_{-\infty}^\infty f(x) e^{-2\pi i x k} \mathrm{d} x.
1011
+
1012
+ Explanation
1013
+ ===========
1014
+
1015
+ If the transform cannot be computed in closed form, this
1016
+ function returns an unevaluated :class:`FourierTransform` object.
1017
+
1018
+ For other Fourier transform conventions, see the function
1019
+ :func:`sympy.integrals.transforms._fourier_transform`.
1020
+
1021
+ For a description of possible hints, refer to the docstring of
1022
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
1023
+ Note that for this transform, by default ``noconds=True``.
1024
+
1025
+ Examples
1026
+ ========
1027
+
1028
+ >>> from sympy import fourier_transform, exp
1029
+ >>> from sympy.abc import x, k
1030
+ >>> fourier_transform(exp(-x**2), x, k)
1031
+ sqrt(pi)*exp(-pi**2*k**2)
1032
+ >>> fourier_transform(exp(-x**2), x, k, noconds=False)
1033
+ (sqrt(pi)*exp(-pi**2*k**2), True)
1034
+
1035
+ See Also
1036
+ ========
1037
+
1038
+ inverse_fourier_transform
1039
+ sine_transform, inverse_sine_transform
1040
+ cosine_transform, inverse_cosine_transform
1041
+ hankel_transform, inverse_hankel_transform
1042
+ mellin_transform, laplace_transform
1043
+ """
1044
+ return FourierTransform(f, x, k).doit(**hints)
1045
+
1046
+
1047
+ class InverseFourierTransform(FourierTypeTransform):
1048
+ """
1049
+ Class representing unevaluated inverse Fourier transforms.
1050
+
1051
+ For usage of this class, see the :class:`IntegralTransform` docstring.
1052
+
1053
+ For how to compute inverse Fourier transforms, see the
1054
+ :func:`inverse_fourier_transform` docstring.
1055
+ """
1056
+
1057
+ _name = 'Inverse Fourier'
1058
+
1059
+ def a(self):
1060
+ return 1
1061
+
1062
+ def b(self):
1063
+ return 2*S.Pi
1064
+
1065
+
1066
+ def inverse_fourier_transform(F, k, x, **hints):
1067
+ r"""
1068
+ Compute the unitary, ordinary-frequency inverse Fourier transform of `F`,
1069
+ defined as
1070
+
1071
+ .. math:: f(x) = \int_{-\infty}^\infty F(k) e^{2\pi i x k} \mathrm{d} k.
1072
+
1073
+ Explanation
1074
+ ===========
1075
+
1076
+ If the transform cannot be computed in closed form, this
1077
+ function returns an unevaluated :class:`InverseFourierTransform` object.
1078
+
1079
+ For other Fourier transform conventions, see the function
1080
+ :func:`sympy.integrals.transforms._fourier_transform`.
1081
+
1082
+ For a description of possible hints, refer to the docstring of
1083
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
1084
+ Note that for this transform, by default ``noconds=True``.
1085
+
1086
+ Examples
1087
+ ========
1088
+
1089
+ >>> from sympy import inverse_fourier_transform, exp, sqrt, pi
1090
+ >>> from sympy.abc import x, k
1091
+ >>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x)
1092
+ exp(-x**2)
1093
+ >>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x, noconds=False)
1094
+ (exp(-x**2), True)
1095
+
1096
+ See Also
1097
+ ========
1098
+
1099
+ fourier_transform
1100
+ sine_transform, inverse_sine_transform
1101
+ cosine_transform, inverse_cosine_transform
1102
+ hankel_transform, inverse_hankel_transform
1103
+ mellin_transform, laplace_transform
1104
+ """
1105
+ return InverseFourierTransform(F, k, x).doit(**hints)
1106
+
1107
+
1108
+ ##########################################################################
1109
+ # Fourier Sine and Cosine Transform
1110
+ ##########################################################################
1111
+
1112
+ @_noconds_(True)
1113
+ def _sine_cosine_transform(f, x, k, a, b, K, name, simplify=True):
1114
+ """
1115
+ Compute a general sine or cosine-type transform
1116
+ F(k) = a int_0^oo b*sin(x*k) f(x) dx.
1117
+ F(k) = a int_0^oo b*cos(x*k) f(x) dx.
1118
+
1119
+ For suitable choice of a and b, this reduces to the standard sine/cosine
1120
+ and inverse sine/cosine transforms.
1121
+ """
1122
+ F = integrate(a*f*K(b*x*k), (x, S.Zero, S.Infinity))
1123
+
1124
+ if not F.has(Integral):
1125
+ return _simplify(F, simplify), S.true
1126
+
1127
+ if not F.is_Piecewise:
1128
+ raise IntegralTransformError(name, f, 'could not compute integral')
1129
+
1130
+ F, cond = F.args[0]
1131
+ if F.has(Integral):
1132
+ raise IntegralTransformError(name, f, 'integral in unexpected form')
1133
+
1134
+ return _simplify(F, simplify), cond
1135
+
1136
+
1137
+ class SineCosineTypeTransform(IntegralTransform):
1138
+ """
1139
+ Base class for sine and cosine transforms.
1140
+ Specify cls._kern.
1141
+ """
1142
+
1143
+ def a(self):
1144
+ raise NotImplementedError(
1145
+ "Class %s must implement a(self) but does not" % self.__class__)
1146
+
1147
+ def b(self):
1148
+ raise NotImplementedError(
1149
+ "Class %s must implement b(self) but does not" % self.__class__)
1150
+
1151
+
1152
+ def _compute_transform(self, f, x, k, **hints):
1153
+ return _sine_cosine_transform(f, x, k,
1154
+ self.a(), self.b(),
1155
+ self.__class__._kern,
1156
+ self.__class__._name, **hints)
1157
+
1158
+ def _as_integral(self, f, x, k):
1159
+ a = self.a()
1160
+ b = self.b()
1161
+ K = self.__class__._kern
1162
+ return Integral(a*f*K(b*x*k), (x, S.Zero, S.Infinity))
1163
+
1164
+
1165
+ class SineTransform(SineCosineTypeTransform):
1166
+ """
1167
+ Class representing unevaluated sine transforms.
1168
+
1169
+ For usage of this class, see the :class:`IntegralTransform` docstring.
1170
+
1171
+ For how to compute sine transforms, see the :func:`sine_transform`
1172
+ docstring.
1173
+ """
1174
+
1175
+ _name = 'Sine'
1176
+ _kern = sin
1177
+
1178
+ def a(self):
1179
+ return sqrt(2)/sqrt(pi)
1180
+
1181
+ def b(self):
1182
+ return S.One
1183
+
1184
+
1185
+ def sine_transform(f, x, k, **hints):
1186
+ r"""
1187
+ Compute the unitary, ordinary-frequency sine transform of `f`, defined
1188
+ as
1189
+
1190
+ .. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \sin(2\pi x k) \mathrm{d} x.
1191
+
1192
+ Explanation
1193
+ ===========
1194
+
1195
+ If the transform cannot be computed in closed form, this
1196
+ function returns an unevaluated :class:`SineTransform` object.
1197
+
1198
+ For a description of possible hints, refer to the docstring of
1199
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
1200
+ Note that for this transform, by default ``noconds=True``.
1201
+
1202
+ Examples
1203
+ ========
1204
+
1205
+ >>> from sympy import sine_transform, exp
1206
+ >>> from sympy.abc import x, k, a
1207
+ >>> sine_transform(x*exp(-a*x**2), x, k)
1208
+ sqrt(2)*k*exp(-k**2/(4*a))/(4*a**(3/2))
1209
+ >>> sine_transform(x**(-a), x, k)
1210
+ 2**(1/2 - a)*k**(a - 1)*gamma(1 - a/2)/gamma(a/2 + 1/2)
1211
+
1212
+ See Also
1213
+ ========
1214
+
1215
+ fourier_transform, inverse_fourier_transform
1216
+ inverse_sine_transform
1217
+ cosine_transform, inverse_cosine_transform
1218
+ hankel_transform, inverse_hankel_transform
1219
+ mellin_transform, laplace_transform
1220
+ """
1221
+ return SineTransform(f, x, k).doit(**hints)
1222
+
1223
+
1224
+ class InverseSineTransform(SineCosineTypeTransform):
1225
+ """
1226
+ Class representing unevaluated inverse sine transforms.
1227
+
1228
+ For usage of this class, see the :class:`IntegralTransform` docstring.
1229
+
1230
+ For how to compute inverse sine transforms, see the
1231
+ :func:`inverse_sine_transform` docstring.
1232
+ """
1233
+
1234
+ _name = 'Inverse Sine'
1235
+ _kern = sin
1236
+
1237
+ def a(self):
1238
+ return sqrt(2)/sqrt(pi)
1239
+
1240
+ def b(self):
1241
+ return S.One
1242
+
1243
+
1244
+ def inverse_sine_transform(F, k, x, **hints):
1245
+ r"""
1246
+ Compute the unitary, ordinary-frequency inverse sine transform of `F`,
1247
+ defined as
1248
+
1249
+ .. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \sin(2\pi x k) \mathrm{d} k.
1250
+
1251
+ Explanation
1252
+ ===========
1253
+
1254
+ If the transform cannot be computed in closed form, this
1255
+ function returns an unevaluated :class:`InverseSineTransform` object.
1256
+
1257
+ For a description of possible hints, refer to the docstring of
1258
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
1259
+ Note that for this transform, by default ``noconds=True``.
1260
+
1261
+ Examples
1262
+ ========
1263
+
1264
+ >>> from sympy import inverse_sine_transform, exp, sqrt, gamma
1265
+ >>> from sympy.abc import x, k, a
1266
+ >>> inverse_sine_transform(2**((1-2*a)/2)*k**(a - 1)*
1267
+ ... gamma(-a/2 + 1)/gamma((a+1)/2), k, x)
1268
+ x**(-a)
1269
+ >>> inverse_sine_transform(sqrt(2)*k*exp(-k**2/(4*a))/(4*sqrt(a)**3), k, x)
1270
+ x*exp(-a*x**2)
1271
+
1272
+ See Also
1273
+ ========
1274
+
1275
+ fourier_transform, inverse_fourier_transform
1276
+ sine_transform
1277
+ cosine_transform, inverse_cosine_transform
1278
+ hankel_transform, inverse_hankel_transform
1279
+ mellin_transform, laplace_transform
1280
+ """
1281
+ return InverseSineTransform(F, k, x).doit(**hints)
1282
+
1283
+
1284
+ class CosineTransform(SineCosineTypeTransform):
1285
+ """
1286
+ Class representing unevaluated cosine transforms.
1287
+
1288
+ For usage of this class, see the :class:`IntegralTransform` docstring.
1289
+
1290
+ For how to compute cosine transforms, see the :func:`cosine_transform`
1291
+ docstring.
1292
+ """
1293
+
1294
+ _name = 'Cosine'
1295
+ _kern = cos
1296
+
1297
+ def a(self):
1298
+ return sqrt(2)/sqrt(pi)
1299
+
1300
+ def b(self):
1301
+ return S.One
1302
+
1303
+
1304
+ def cosine_transform(f, x, k, **hints):
1305
+ r"""
1306
+ Compute the unitary, ordinary-frequency cosine transform of `f`, defined
1307
+ as
1308
+
1309
+ .. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \cos(2\pi x k) \mathrm{d} x.
1310
+
1311
+ Explanation
1312
+ ===========
1313
+
1314
+ If the transform cannot be computed in closed form, this
1315
+ function returns an unevaluated :class:`CosineTransform` object.
1316
+
1317
+ For a description of possible hints, refer to the docstring of
1318
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
1319
+ Note that for this transform, by default ``noconds=True``.
1320
+
1321
+ Examples
1322
+ ========
1323
+
1324
+ >>> from sympy import cosine_transform, exp, sqrt, cos
1325
+ >>> from sympy.abc import x, k, a
1326
+ >>> cosine_transform(exp(-a*x), x, k)
1327
+ sqrt(2)*a/(sqrt(pi)*(a**2 + k**2))
1328
+ >>> cosine_transform(exp(-a*sqrt(x))*cos(a*sqrt(x)), x, k)
1329
+ a*exp(-a**2/(2*k))/(2*k**(3/2))
1330
+
1331
+ See Also
1332
+ ========
1333
+
1334
+ fourier_transform, inverse_fourier_transform,
1335
+ sine_transform, inverse_sine_transform
1336
+ inverse_cosine_transform
1337
+ hankel_transform, inverse_hankel_transform
1338
+ mellin_transform, laplace_transform
1339
+ """
1340
+ return CosineTransform(f, x, k).doit(**hints)
1341
+
1342
+
1343
+ class InverseCosineTransform(SineCosineTypeTransform):
1344
+ """
1345
+ Class representing unevaluated inverse cosine transforms.
1346
+
1347
+ For usage of this class, see the :class:`IntegralTransform` docstring.
1348
+
1349
+ For how to compute inverse cosine transforms, see the
1350
+ :func:`inverse_cosine_transform` docstring.
1351
+ """
1352
+
1353
+ _name = 'Inverse Cosine'
1354
+ _kern = cos
1355
+
1356
+ def a(self):
1357
+ return sqrt(2)/sqrt(pi)
1358
+
1359
+ def b(self):
1360
+ return S.One
1361
+
1362
+
1363
+ def inverse_cosine_transform(F, k, x, **hints):
1364
+ r"""
1365
+ Compute the unitary, ordinary-frequency inverse cosine transform of `F`,
1366
+ defined as
1367
+
1368
+ .. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \cos(2\pi x k) \mathrm{d} k.
1369
+
1370
+ Explanation
1371
+ ===========
1372
+
1373
+ If the transform cannot be computed in closed form, this
1374
+ function returns an unevaluated :class:`InverseCosineTransform` object.
1375
+
1376
+ For a description of possible hints, refer to the docstring of
1377
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
1378
+ Note that for this transform, by default ``noconds=True``.
1379
+
1380
+ Examples
1381
+ ========
1382
+
1383
+ >>> from sympy import inverse_cosine_transform, sqrt, pi
1384
+ >>> from sympy.abc import x, k, a
1385
+ >>> inverse_cosine_transform(sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)), k, x)
1386
+ exp(-a*x)
1387
+ >>> inverse_cosine_transform(1/sqrt(k), k, x)
1388
+ 1/sqrt(x)
1389
+
1390
+ See Also
1391
+ ========
1392
+
1393
+ fourier_transform, inverse_fourier_transform,
1394
+ sine_transform, inverse_sine_transform
1395
+ cosine_transform
1396
+ hankel_transform, inverse_hankel_transform
1397
+ mellin_transform, laplace_transform
1398
+ """
1399
+ return InverseCosineTransform(F, k, x).doit(**hints)
1400
+
1401
+
1402
+ ##########################################################################
1403
+ # Hankel Transform
1404
+ ##########################################################################
1405
+
1406
+ @_noconds_(True)
1407
+ def _hankel_transform(f, r, k, nu, name, simplify=True):
1408
+ r"""
1409
+ Compute a general Hankel transform
1410
+
1411
+ .. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r.
1412
+ """
1413
+ F = integrate(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity))
1414
+
1415
+ if not F.has(Integral):
1416
+ return _simplify(F, simplify), S.true
1417
+
1418
+ if not F.is_Piecewise:
1419
+ raise IntegralTransformError(name, f, 'could not compute integral')
1420
+
1421
+ F, cond = F.args[0]
1422
+ if F.has(Integral):
1423
+ raise IntegralTransformError(name, f, 'integral in unexpected form')
1424
+
1425
+ return _simplify(F, simplify), cond
1426
+
1427
+
1428
+ class HankelTypeTransform(IntegralTransform):
1429
+ """
1430
+ Base class for Hankel transforms.
1431
+ """
1432
+
1433
+ def doit(self, **hints):
1434
+ return self._compute_transform(self.function,
1435
+ self.function_variable,
1436
+ self.transform_variable,
1437
+ self.args[3],
1438
+ **hints)
1439
+
1440
+ def _compute_transform(self, f, r, k, nu, **hints):
1441
+ return _hankel_transform(f, r, k, nu, self._name, **hints)
1442
+
1443
+ def _as_integral(self, f, r, k, nu):
1444
+ return Integral(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity))
1445
+
1446
+ @property
1447
+ def as_integral(self):
1448
+ return self._as_integral(self.function,
1449
+ self.function_variable,
1450
+ self.transform_variable,
1451
+ self.args[3])
1452
+
1453
+
1454
+ class HankelTransform(HankelTypeTransform):
1455
+ """
1456
+ Class representing unevaluated Hankel transforms.
1457
+
1458
+ For usage of this class, see the :class:`IntegralTransform` docstring.
1459
+
1460
+ For how to compute Hankel transforms, see the :func:`hankel_transform`
1461
+ docstring.
1462
+ """
1463
+
1464
+ _name = 'Hankel'
1465
+
1466
+
1467
+ def hankel_transform(f, r, k, nu, **hints):
1468
+ r"""
1469
+ Compute the Hankel transform of `f`, defined as
1470
+
1471
+ .. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r.
1472
+
1473
+ Explanation
1474
+ ===========
1475
+
1476
+ If the transform cannot be computed in closed form, this
1477
+ function returns an unevaluated :class:`HankelTransform` object.
1478
+
1479
+ For a description of possible hints, refer to the docstring of
1480
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
1481
+ Note that for this transform, by default ``noconds=True``.
1482
+
1483
+ Examples
1484
+ ========
1485
+
1486
+ >>> from sympy import hankel_transform, inverse_hankel_transform
1487
+ >>> from sympy import exp
1488
+ >>> from sympy.abc import r, k, m, nu, a
1489
+
1490
+ >>> ht = hankel_transform(1/r**m, r, k, nu)
1491
+ >>> ht
1492
+ 2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2))
1493
+
1494
+ >>> inverse_hankel_transform(ht, k, r, nu)
1495
+ r**(-m)
1496
+
1497
+ >>> ht = hankel_transform(exp(-a*r), r, k, 0)
1498
+ >>> ht
1499
+ a/(k**3*(a**2/k**2 + 1)**(3/2))
1500
+
1501
+ >>> inverse_hankel_transform(ht, k, r, 0)
1502
+ exp(-a*r)
1503
+
1504
+ See Also
1505
+ ========
1506
+
1507
+ fourier_transform, inverse_fourier_transform
1508
+ sine_transform, inverse_sine_transform
1509
+ cosine_transform, inverse_cosine_transform
1510
+ inverse_hankel_transform
1511
+ mellin_transform, laplace_transform
1512
+ """
1513
+ return HankelTransform(f, r, k, nu).doit(**hints)
1514
+
1515
+
1516
+ class InverseHankelTransform(HankelTypeTransform):
1517
+ """
1518
+ Class representing unevaluated inverse Hankel transforms.
1519
+
1520
+ For usage of this class, see the :class:`IntegralTransform` docstring.
1521
+
1522
+ For how to compute inverse Hankel transforms, see the
1523
+ :func:`inverse_hankel_transform` docstring.
1524
+ """
1525
+
1526
+ _name = 'Inverse Hankel'
1527
+
1528
+
1529
+ def inverse_hankel_transform(F, k, r, nu, **hints):
1530
+ r"""
1531
+ Compute the inverse Hankel transform of `F` defined as
1532
+
1533
+ .. math:: f(r) = \int_{0}^\infty F_\nu(k) J_\nu(k r) k \mathrm{d} k.
1534
+
1535
+ Explanation
1536
+ ===========
1537
+
1538
+ If the transform cannot be computed in closed form, this
1539
+ function returns an unevaluated :class:`InverseHankelTransform` object.
1540
+
1541
+ For a description of possible hints, refer to the docstring of
1542
+ :func:`sympy.integrals.transforms.IntegralTransform.doit`.
1543
+ Note that for this transform, by default ``noconds=True``.
1544
+
1545
+ Examples
1546
+ ========
1547
+
1548
+ >>> from sympy import hankel_transform, inverse_hankel_transform
1549
+ >>> from sympy import exp
1550
+ >>> from sympy.abc import r, k, m, nu, a
1551
+
1552
+ >>> ht = hankel_transform(1/r**m, r, k, nu)
1553
+ >>> ht
1554
+ 2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2))
1555
+
1556
+ >>> inverse_hankel_transform(ht, k, r, nu)
1557
+ r**(-m)
1558
+
1559
+ >>> ht = hankel_transform(exp(-a*r), r, k, 0)
1560
+ >>> ht
1561
+ a/(k**3*(a**2/k**2 + 1)**(3/2))
1562
+
1563
+ >>> inverse_hankel_transform(ht, k, r, 0)
1564
+ exp(-a*r)
1565
+
1566
+ See Also
1567
+ ========
1568
+
1569
+ fourier_transform, inverse_fourier_transform
1570
+ sine_transform, inverse_sine_transform
1571
+ cosine_transform, inverse_cosine_transform
1572
+ hankel_transform
1573
+ mellin_transform, laplace_transform
1574
+ """
1575
+ return InverseHankelTransform(F, k, r, nu).doit(**hints)
1576
+
1577
+
1578
+ ##########################################################################
1579
+ # Laplace Transform
1580
+ ##########################################################################
1581
+
1582
+ # Stub classes and functions that used to be here
1583
+ import sympy.integrals.laplace as _laplace
1584
+
1585
+ LaplaceTransform = _laplace.LaplaceTransform
1586
+ laplace_transform = _laplace.laplace_transform
1587
+ laplace_correspondence = _laplace.laplace_correspondence
1588
+ laplace_initial_conds = _laplace.laplace_initial_conds
1589
+ InverseLaplaceTransform = _laplace.InverseLaplaceTransform
1590
+ inverse_laplace_transform = _laplace.inverse_laplace_transform
parrot/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest2.cpython-310.pyc ADDED
Binary file (1.01 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/parsing/autolev/test-examples/__pycache__/ruletest8.cpython-310.pyc ADDED
Binary file (1.86 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/parsing/fortran/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (251 Bytes). View file
 
parrot/lib/python3.10/site-packages/sympy/parsing/fortran/fortran_parser.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external import import_module
2
+
3
+ lfortran = import_module('lfortran')
4
+
5
+ if lfortran:
6
+ from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String,
7
+ Return, FunctionDefinition, Assignment)
8
+ from sympy.core import Add, Mul, Integer, Float
9
+ from sympy.core.symbol import Symbol
10
+
11
+ asr_mod = lfortran.asr
12
+ asr = lfortran.asr.asr
13
+ src_to_ast = lfortran.ast.src_to_ast
14
+ ast_to_asr = lfortran.semantic.ast_to_asr.ast_to_asr
15
+
16
+ """
17
+ This module contains all the necessary Classes and Function used to Parse
18
+ Fortran code into SymPy expression
19
+
20
+ The module and its API are currently under development and experimental.
21
+ It is also dependent on LFortran for the ASR that is converted to SymPy syntax
22
+ which is also under development.
23
+ The module only supports the features currently supported by the LFortran ASR
24
+ which will be updated as the development of LFortran and this module progresses
25
+
26
+ You might find unexpected bugs and exceptions while using the module, feel free
27
+ to report them to the SymPy Issue Tracker
28
+
29
+ The API for the module might also change while in development if better and
30
+ more effective ways are discovered for the process
31
+
32
+ Features Supported
33
+ ==================
34
+
35
+ - Variable Declarations (integers and reals)
36
+ - Function Definitions
37
+ - Assignments and Basic Binary Operations
38
+
39
+
40
+ Notes
41
+ =====
42
+
43
+ The module depends on an external dependency
44
+
45
+ LFortran : Required to parse Fortran source code into ASR
46
+
47
+
48
+ References
49
+ ==========
50
+
51
+ .. [1] https://github.com/sympy/sympy/issues
52
+ .. [2] https://gitlab.com/lfortran/lfortran
53
+ .. [3] https://docs.lfortran.org/
54
+
55
+ """
56
+
57
+
58
+ class ASR2PyVisitor(asr.ASTVisitor): # type: ignore
59
+ """
60
+ Visitor Class for LFortran ASR
61
+
62
+ It is a Visitor class derived from asr.ASRVisitor which visits all the
63
+ nodes of the LFortran ASR and creates corresponding AST node for each
64
+ ASR node
65
+
66
+ """
67
+
68
+ def __init__(self):
69
+ """Initialize the Parser"""
70
+ self._py_ast = []
71
+
72
+ def visit_TranslationUnit(self, node):
73
+ """
74
+ Function to visit all the elements of the Translation Unit
75
+ created by LFortran ASR
76
+ """
77
+ for s in node.global_scope.symbols:
78
+ sym = node.global_scope.symbols[s]
79
+ self.visit(sym)
80
+ for item in node.items:
81
+ self.visit(item)
82
+
83
+ def visit_Assignment(self, node):
84
+ """Visitor Function for Assignment
85
+
86
+ Visits each Assignment is the LFortran ASR and creates corresponding
87
+ assignment for SymPy.
88
+
89
+ Notes
90
+ =====
91
+
92
+ The function currently only supports variable assignment and binary
93
+ operation assignments of varying multitudes. Any type of numberS or
94
+ array is not supported.
95
+
96
+ Raises
97
+ ======
98
+
99
+ NotImplementedError() when called for Numeric assignments or Arrays
100
+
101
+ """
102
+ # TODO: Arithmetic Assignment
103
+ if isinstance(node.target, asr.Variable):
104
+ target = node.target
105
+ value = node.value
106
+ if isinstance(value, asr.Variable):
107
+ new_node = Assignment(
108
+ Variable(
109
+ target.name
110
+ ),
111
+ Variable(
112
+ value.name
113
+ )
114
+ )
115
+ elif (type(value) == asr.BinOp):
116
+ exp_ast = call_visitor(value)
117
+ for expr in exp_ast:
118
+ new_node = Assignment(
119
+ Variable(target.name),
120
+ expr
121
+ )
122
+ else:
123
+ raise NotImplementedError("Numeric assignments not supported")
124
+ else:
125
+ raise NotImplementedError("Arrays not supported")
126
+ self._py_ast.append(new_node)
127
+
128
+ def visit_BinOp(self, node):
129
+ """Visitor Function for Binary Operations
130
+
131
+ Visits each binary operation present in the LFortran ASR like addition,
132
+ subtraction, multiplication, division and creates the corresponding
133
+ operation node in SymPy's AST
134
+
135
+ In case of more than one binary operations, the function calls the
136
+ call_visitor() function on the child nodes of the binary operations
137
+ recursively until all the operations have been processed.
138
+
139
+ Notes
140
+ =====
141
+
142
+ The function currently only supports binary operations with Variables
143
+ or other binary operations. Numerics are not supported as of yet.
144
+
145
+ Raises
146
+ ======
147
+
148
+ NotImplementedError() when called for Numeric assignments
149
+
150
+ """
151
+ # TODO: Integer Binary Operations
152
+ op = node.op
153
+ lhs = node.left
154
+ rhs = node.right
155
+
156
+ if (type(lhs) == asr.Variable):
157
+ left_value = Symbol(lhs.name)
158
+ elif(type(lhs) == asr.BinOp):
159
+ l_exp_ast = call_visitor(lhs)
160
+ for exp in l_exp_ast:
161
+ left_value = exp
162
+ else:
163
+ raise NotImplementedError("Numbers Currently not supported")
164
+
165
+ if (type(rhs) == asr.Variable):
166
+ right_value = Symbol(rhs.name)
167
+ elif(type(rhs) == asr.BinOp):
168
+ r_exp_ast = call_visitor(rhs)
169
+ for exp in r_exp_ast:
170
+ right_value = exp
171
+ else:
172
+ raise NotImplementedError("Numbers Currently not supported")
173
+
174
+ if isinstance(op, asr.Add):
175
+ new_node = Add(left_value, right_value)
176
+ elif isinstance(op, asr.Sub):
177
+ new_node = Add(left_value, -right_value)
178
+ elif isinstance(op, asr.Div):
179
+ new_node = Mul(left_value, 1/right_value)
180
+ elif isinstance(op, asr.Mul):
181
+ new_node = Mul(left_value, right_value)
182
+
183
+ self._py_ast.append(new_node)
184
+
185
+ def visit_Variable(self, node):
186
+ """Visitor Function for Variable Declaration
187
+
188
+ Visits each variable declaration present in the ASR and creates a
189
+ Symbol declaration for each variable
190
+
191
+ Notes
192
+ =====
193
+
194
+ The functions currently only support declaration of integer and
195
+ real variables. Other data types are still under development.
196
+
197
+ Raises
198
+ ======
199
+
200
+ NotImplementedError() when called for unsupported data types
201
+
202
+ """
203
+ if isinstance(node.type, asr.Integer):
204
+ var_type = IntBaseType(String('integer'))
205
+ value = Integer(0)
206
+ elif isinstance(node.type, asr.Real):
207
+ var_type = FloatBaseType(String('real'))
208
+ value = Float(0.0)
209
+ else:
210
+ raise NotImplementedError("Data type not supported")
211
+
212
+ if not (node.intent == 'in'):
213
+ new_node = Variable(
214
+ node.name
215
+ ).as_Declaration(
216
+ type = var_type,
217
+ value = value
218
+ )
219
+ self._py_ast.append(new_node)
220
+
221
+ def visit_Sequence(self, seq):
222
+ """Visitor Function for code sequence
223
+
224
+ Visits a code sequence/ block and calls the visitor function on all the
225
+ children of the code block to create corresponding code in python
226
+
227
+ """
228
+ if seq is not None:
229
+ for node in seq:
230
+ self._py_ast.append(call_visitor(node))
231
+
232
+ def visit_Num(self, node):
233
+ """Visitor Function for Numbers in ASR
234
+
235
+ This function is currently under development and will be updated
236
+ with improvements in the LFortran ASR
237
+
238
+ """
239
+ # TODO:Numbers when the LFortran ASR is updated
240
+ # self._py_ast.append(Integer(node.n))
241
+ pass
242
+
243
+ def visit_Function(self, node):
244
+ """Visitor Function for function Definitions
245
+
246
+ Visits each function definition present in the ASR and creates a
247
+ function definition node in the Python AST with all the elements of the
248
+ given function
249
+
250
+ The functions declare all the variables required as SymPy symbols in
251
+ the function before the function definition
252
+
253
+ This function also the call_visior_function to parse the contents of
254
+ the function body
255
+
256
+ """
257
+ # TODO: Return statement, variable declaration
258
+ fn_args = [Variable(arg_iter.name) for arg_iter in node.args]
259
+ fn_body = []
260
+ fn_name = node.name
261
+ for i in node.body:
262
+ fn_ast = call_visitor(i)
263
+ try:
264
+ fn_body_expr = fn_ast
265
+ except UnboundLocalError:
266
+ fn_body_expr = []
267
+ for sym in node.symtab.symbols:
268
+ decl = call_visitor(node.symtab.symbols[sym])
269
+ for symbols in decl:
270
+ fn_body.append(symbols)
271
+ for elem in fn_body_expr:
272
+ fn_body.append(elem)
273
+ fn_body.append(
274
+ Return(
275
+ Variable(
276
+ node.return_var.name
277
+ )
278
+ )
279
+ )
280
+ if isinstance(node.return_var.type, asr.Integer):
281
+ ret_type = IntBaseType(String('integer'))
282
+ elif isinstance(node.return_var.type, asr.Real):
283
+ ret_type = FloatBaseType(String('real'))
284
+ else:
285
+ raise NotImplementedError("Data type not supported")
286
+ new_node = FunctionDefinition(
287
+ return_type = ret_type,
288
+ name = fn_name,
289
+ parameters = fn_args,
290
+ body = fn_body
291
+ )
292
+ self._py_ast.append(new_node)
293
+
294
+ def ret_ast(self):
295
+ """Returns the AST nodes"""
296
+ return self._py_ast
297
+ else:
298
+ class ASR2PyVisitor(): # type: ignore
299
+ def __init__(self, *args, **kwargs):
300
+ raise ImportError('lfortran not available')
301
+
302
+ def call_visitor(fort_node):
303
+ """Calls the AST Visitor on the Module
304
+
305
+ This function is used to call the AST visitor for a program or module
306
+ It imports all the required modules and calls the visit() function
307
+ on the given node
308
+
309
+ Parameters
310
+ ==========
311
+
312
+ fort_node : LFortran ASR object
313
+ Node for the operation for which the NodeVisitor is called
314
+
315
+ Returns
316
+ =======
317
+
318
+ res_ast : list
319
+ list of SymPy AST Nodes
320
+
321
+ """
322
+ v = ASR2PyVisitor()
323
+ v.visit(fort_node)
324
+ res_ast = v.ret_ast()
325
+ return res_ast
326
+
327
+
328
+ def src_to_sympy(src):
329
+ """Wrapper function to convert the given Fortran source code to SymPy Expressions
330
+
331
+ Parameters
332
+ ==========
333
+
334
+ src : string
335
+ A string with the Fortran source code
336
+
337
+ Returns
338
+ =======
339
+
340
+ py_src : string
341
+ A string with the Python source code compatible with SymPy
342
+
343
+ """
344
+ a_ast = src_to_ast(src, translation_unit=False)
345
+ a = ast_to_asr(a_ast)
346
+ py_src = call_visitor(a)
347
+ return py_src
parrot/lib/python3.10/site-packages/sympy/strategies/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Rewrite Rules
2
+
3
+ DISCLAIMER: This module is experimental. The interface is subject to change.
4
+
5
+ A rule is a function that transforms one expression into another
6
+
7
+ Rule :: Expr -> Expr
8
+
9
+ A strategy is a function that says how a rule should be applied to a syntax
10
+ tree. In general strategies take rules and produce a new rule
11
+
12
+ Strategy :: [Rules], Other-stuff -> Rule
13
+
14
+ This allows developers to separate a mathematical transformation from the
15
+ algorithmic details of applying that transformation. The goal is to separate
16
+ the work of mathematical programming from algorithmic programming.
17
+
18
+ Submodules
19
+
20
+ strategies.rl - some fundamental rules
21
+ strategies.core - generic non-SymPy specific strategies
22
+ strategies.traverse - strategies that traverse a SymPy tree
23
+ strategies.tools - some conglomerate strategies that do depend on SymPy
24
+ """
25
+
26
+ from . import rl
27
+ from . import traverse
28
+ from .rl import rm_id, unpack, flatten, sort, glom, distribute, rebuild
29
+ from .util import new
30
+ from .core import (
31
+ condition, debug, chain, null_safe, do_one, exhaust, minimize, tryit)
32
+ from .tools import canon, typed
33
+ from . import branch
34
+
35
+ __all__ = [
36
+ 'rl',
37
+
38
+ 'traverse',
39
+
40
+ 'rm_id', 'unpack', 'flatten', 'sort', 'glom', 'distribute', 'rebuild',
41
+
42
+ 'new',
43
+
44
+ 'condition', 'debug', 'chain', 'null_safe', 'do_one', 'exhaust',
45
+ 'minimize', 'tryit',
46
+
47
+ 'canon', 'typed',
48
+
49
+ 'branch',
50
+ ]
parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.63 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/rl.cpython-310.pyc ADDED
Binary file (5.51 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/tools.cpython-310.pyc ADDED
Binary file (1.83 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/traverse.cpython-310.pyc ADDED
Binary file (1.9 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/tree.cpython-310.pyc ADDED
Binary file (4.17 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/strategies/__pycache__/util.cpython-310.pyc ADDED
Binary file (775 Bytes). View file
 
parrot/lib/python3.10/site-packages/sympy/strategies/branch/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import traverse
2
+ from .core import (
3
+ condition, debug, multiplex, exhaust, notempty,
4
+ chain, onaction, sfilter, yieldify, do_one, identity)
5
+ from .tools import canon
6
+
7
+ __all__ = [
8
+ 'traverse',
9
+
10
+ 'condition', 'debug', 'multiplex', 'exhaust', 'notempty', 'chain',
11
+ 'onaction', 'sfilter', 'yieldify', 'do_one', 'identity',
12
+
13
+ 'canon',
14
+ ]
parrot/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (548 Bytes). View file
 
parrot/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/core.cpython-310.pyc ADDED
Binary file (3.9 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/strategies/branch/__pycache__/tools.cpython-310.pyc ADDED
Binary file (609 Bytes). View file