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

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. .gitattributes +2 -0
  2. llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/__init__.cpython-310.pyc +0 -0
  3. llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/table_vs16.cpython-310.pyc +0 -0
  4. llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/table_wide.cpython-310.pyc +0 -0
  5. llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/table_zero.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/unicode_versions.cpython-310.pyc +0 -0
  7. llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/wcwidth.cpython-310.pyc +0 -0
  8. llava_next/lib/python3.10/site-packages/wcwidth/table_vs16.py +125 -0
  9. llava_next/lib/python3.10/site-packages/wcwidth/table_wide.py +0 -0
  10. llava_next/lib/python3.10/site-packages/wcwidth/table_zero.py +0 -0
  11. llava_next/lib/python3.10/site-packages/wcwidth/wcwidth.py +345 -0
  12. parrot/lib/python3.10/site-packages/aiofiles/__pycache__/base.cpython-310.pyc +0 -0
  13. parrot/lib/python3.10/site-packages/aiofiles/tempfile/__init__.py +357 -0
  14. parrot/lib/python3.10/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-310.pyc +0 -0
  15. parrot/lib/python3.10/site-packages/aiofiles/tempfile/temptypes.py +69 -0
  16. parrot/lib/python3.10/site-packages/sympy/abc.py +111 -0
  17. parrot/lib/python3.10/site-packages/sympy/conftest.py +96 -0
  18. parrot/lib/python3.10/site-packages/sympy/discrete/__init__.py +20 -0
  19. parrot/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc +0 -0
  20. parrot/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc +0 -0
  21. parrot/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc +0 -0
  22. parrot/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc +0 -0
  23. parrot/lib/python3.10/site-packages/sympy/discrete/recurrences.py +166 -0
  24. parrot/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py +0 -0
  25. parrot/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  26. parrot/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc +0 -0
  27. parrot/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc +0 -0
  28. parrot/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc +0 -0
  29. parrot/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py +392 -0
  30. parrot/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py +59 -0
  31. parrot/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py +154 -0
  32. parrot/lib/python3.10/site-packages/sympy/discrete/transforms.py +425 -0
  33. parrot/lib/python3.10/site-packages/sympy/multipledispatch/__init__.py +11 -0
  34. parrot/lib/python3.10/site-packages/sympy/multipledispatch/conflict.py +68 -0
  35. parrot/lib/python3.10/site-packages/sympy/multipledispatch/core.py +83 -0
  36. parrot/lib/python3.10/site-packages/sympy/multipledispatch/dispatcher.py +413 -0
  37. parrot/lib/python3.10/site-packages/sympy/multipledispatch/tests/__init__.py +0 -0
  38. parrot/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_dispatcher.cpython-310.pyc +0 -0
  39. parrot/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_dispatcher.py +284 -0
  40. parrot/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc +0 -0
  41. parrot/lib/python3.10/site-packages/sympy/parsing/__pycache__/ast_parser.cpython-310.pyc +0 -0
  42. parrot/lib/python3.10/site-packages/sympy/parsing/__pycache__/maxima.cpython-310.pyc +0 -0
  43. parrot/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc +0 -0
  44. parrot/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt +21 -0
  45. parrot/lib/python3.10/site-packages/sympy/parsing/latex/__init__.py +66 -0
  46. parrot/lib/python3.10/site-packages/sympy/parsing/latex/_build_latex_antlr.py +91 -0
  47. parrot/lib/python3.10/site-packages/sympy/parsing/latex/_parse_latex_antlr.py +607 -0
  48. parrot/lib/python3.10/site-packages/sympy/parsing/latex/errors.py +2 -0
  49. parrot/lib/python3.10/site-packages/sympy/parsing/latex/lark/__init__.py +2 -0
  50. parrot/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py +1257 -0
.gitattributes CHANGED
@@ -332,3 +332,5 @@ llava_next/lib/python3.10/site-packages/pandas/tests/indexing/__pycache__/test_l
332
  parrot/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
333
  parrot/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
334
  parrot/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_tf_objects.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
332
  parrot/lib/python3.10/site-packages/transformers/models/seamless_m4t_v2/__pycache__/modeling_seamless_m4t_v2.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
333
  parrot/lib/python3.10/site-packages/transformers/models/speecht5/__pycache__/modeling_speecht5.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
334
  parrot/lib/python3.10/site-packages/transformers/utils/__pycache__/dummy_tf_objects.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
335
+ parrot/lib/python3.10/site-packages/transformers/__pycache__/modeling_tf_utils.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
336
+ parrot/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (526 Bytes). View file
 
llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/table_vs16.cpython-310.pyc ADDED
Binary file (1.73 kB). View file
 
llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/table_wide.cpython-310.pyc ADDED
Binary file (8.24 kB). View file
 
llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/table_zero.cpython-310.pyc ADDED
Binary file (24 kB). View file
 
llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/unicode_versions.cpython-310.pyc ADDED
Binary file (898 Bytes). View file
 
llava_next/lib/python3.10/site-packages/wcwidth/__pycache__/wcwidth.cpython-310.pyc ADDED
Binary file (10 kB). View file
 
llava_next/lib/python3.10/site-packages/wcwidth/table_vs16.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Exports VS16_NARROW_TO_WIDE table keyed by supporting unicode version level.
3
+
4
+ This code generated by wcwidth/bin/update-tables.py on 2023-11-07 16:43:49 UTC.
5
+ """
6
+ VS16_NARROW_TO_WIDE = {
7
+ '9.0.0': (
8
+ # Source: 9.0.0
9
+ # Date: 2023-02-01, 02:22:54 GMT
10
+ #
11
+ (0x00023, 0x00023,), # Number Sign
12
+ (0x0002a, 0x0002a,), # Asterisk
13
+ (0x00030, 0x00039,), # Digit Zero ..Digit Nine
14
+ (0x000a9, 0x000a9,), # Copyright Sign
15
+ (0x000ae, 0x000ae,), # Registered Sign
16
+ (0x0203c, 0x0203c,), # Double Exclamation Mark
17
+ (0x02049, 0x02049,), # Exclamation Question Mark
18
+ (0x02122, 0x02122,), # Trade Mark Sign
19
+ (0x02139, 0x02139,), # Information Source
20
+ (0x02194, 0x02199,), # Left Right Arrow ..South West Arrow
21
+ (0x021a9, 0x021aa,), # Leftwards Arrow With Hoo..Rightwards Arrow With Ho
22
+ (0x02328, 0x02328,), # Keyboard
23
+ (0x023cf, 0x023cf,), # Eject Symbol
24
+ (0x023ed, 0x023ef,), # Black Right-pointing Dou..Black Right-pointing Tri
25
+ (0x023f1, 0x023f2,), # Stopwatch ..Timer Clock
26
+ (0x023f8, 0x023fa,), # Double Vertical Bar ..Black Circle For Record
27
+ (0x024c2, 0x024c2,), # Circled Latin Capital Letter M
28
+ (0x025aa, 0x025ab,), # Black Small Square ..White Small Square
29
+ (0x025b6, 0x025b6,), # Black Right-pointing Triangle
30
+ (0x025c0, 0x025c0,), # Black Left-pointing Triangle
31
+ (0x025fb, 0x025fc,), # White Medium Square ..Black Medium Square
32
+ (0x02600, 0x02604,), # Black Sun With Rays ..Comet
33
+ (0x0260e, 0x0260e,), # Black Telephone
34
+ (0x02611, 0x02611,), # Ballot Box With Check
35
+ (0x02618, 0x02618,), # Shamrock
36
+ (0x0261d, 0x0261d,), # White Up Pointing Index
37
+ (0x02620, 0x02620,), # Skull And Crossbones
38
+ (0x02622, 0x02623,), # Radioactive Sign ..Biohazard Sign
39
+ (0x02626, 0x02626,), # Orthodox Cross
40
+ (0x0262a, 0x0262a,), # Star And Crescent
41
+ (0x0262e, 0x0262f,), # Peace Symbol ..Yin Yang
42
+ (0x02638, 0x0263a,), # Wheel Of Dharma ..White Smiling Face
43
+ (0x02640, 0x02640,), # Female Sign
44
+ (0x02642, 0x02642,), # Male Sign
45
+ (0x0265f, 0x02660,), # Black Chess Pawn ..Black Spade Suit
46
+ (0x02663, 0x02663,), # Black Club Suit
47
+ (0x02665, 0x02666,), # Black Heart Suit ..Black Diamond Suit
48
+ (0x02668, 0x02668,), # Hot Springs
49
+ (0x0267b, 0x0267b,), # Black Universal Recycling Symbol
50
+ (0x0267e, 0x0267e,), # Permanent Paper Sign
51
+ (0x02692, 0x02692,), # Hammer And Pick
52
+ (0x02694, 0x02697,), # Crossed Swords ..Alembic
53
+ (0x02699, 0x02699,), # Gear
54
+ (0x0269b, 0x0269c,), # Atom Symbol ..Fleur-de-lis
55
+ (0x026a0, 0x026a0,), # Warning Sign
56
+ (0x026a7, 0x026a7,), # Male With Stroke And Male And Female Sign
57
+ (0x026b0, 0x026b1,), # Coffin ..Funeral Urn
58
+ (0x026c8, 0x026c8,), # Thunder Cloud And Rain
59
+ (0x026cf, 0x026cf,), # Pick
60
+ (0x026d1, 0x026d1,), # Helmet With White Cross
61
+ (0x026d3, 0x026d3,), # Chains
62
+ (0x026e9, 0x026e9,), # Shinto Shrine
63
+ (0x026f0, 0x026f1,), # Mountain ..Umbrella On Ground
64
+ (0x026f4, 0x026f4,), # Ferry
65
+ (0x026f7, 0x026f9,), # Skier ..Person With Ball
66
+ (0x02702, 0x02702,), # Black Scissors
67
+ (0x02708, 0x02709,), # Airplane ..Envelope
68
+ (0x0270c, 0x0270d,), # Victory Hand ..Writing Hand
69
+ (0x0270f, 0x0270f,), # Pencil
70
+ (0x02712, 0x02712,), # Black Nib
71
+ (0x02714, 0x02714,), # Heavy Check Mark
72
+ (0x02716, 0x02716,), # Heavy Multiplication X
73
+ (0x0271d, 0x0271d,), # Latin Cross
74
+ (0x02721, 0x02721,), # Star Of David
75
+ (0x02733, 0x02734,), # Eight Spoked Asterisk ..Eight Pointed Black Star
76
+ (0x02744, 0x02744,), # Snowflake
77
+ (0x02747, 0x02747,), # Sparkle
78
+ (0x02763, 0x02764,), # Heavy Heart Exclamation ..Heavy Black Heart
79
+ (0x027a1, 0x027a1,), # Black Rightwards Arrow
80
+ (0x02934, 0x02935,), # Arrow Pointing Rightward..Arrow Pointing Rightward
81
+ (0x02b05, 0x02b07,), # Leftwards Black Arrow ..Downwards Black Arrow
82
+ (0x1f170, 0x1f171,), # Negative Squared Latin C..Negative Squared Latin C
83
+ (0x1f17e, 0x1f17f,), # Negative Squared Latin C..Negative Squared Latin C
84
+ (0x1f321, 0x1f321,), # Thermometer
85
+ (0x1f324, 0x1f32c,), # White Sun With Small Clo..Wind Blowing Face
86
+ (0x1f336, 0x1f336,), # Hot Pepper
87
+ (0x1f37d, 0x1f37d,), # Fork And Knife With Plate
88
+ (0x1f396, 0x1f397,), # Military Medal ..Reminder Ribbon
89
+ (0x1f399, 0x1f39b,), # Studio Microphone ..Control Knobs
90
+ (0x1f39e, 0x1f39f,), # Film Frames ..Admission Tickets
91
+ (0x1f3cb, 0x1f3ce,), # Weight Lifter ..Racing Car
92
+ (0x1f3d4, 0x1f3df,), # Snow Capped Mountain ..Stadium
93
+ (0x1f3f3, 0x1f3f3,), # Waving White Flag
94
+ (0x1f3f5, 0x1f3f5,), # Rosette
95
+ (0x1f3f7, 0x1f3f7,), # Label
96
+ (0x1f43f, 0x1f43f,), # Chipmunk
97
+ (0x1f441, 0x1f441,), # Eye
98
+ (0x1f4fd, 0x1f4fd,), # Film Projector
99
+ (0x1f549, 0x1f54a,), # Om Symbol ..Dove Of Peace
100
+ (0x1f56f, 0x1f570,), # Candle ..Mantelpiece Clock
101
+ (0x1f573, 0x1f579,), # Hole ..Joystick
102
+ (0x1f587, 0x1f587,), # Linked Paperclips
103
+ (0x1f58a, 0x1f58d,), # Lower Left Ballpoint Pen..Lower Left Crayon
104
+ (0x1f590, 0x1f590,), # Raised Hand With Fingers Splayed
105
+ (0x1f5a5, 0x1f5a5,), # Desktop Computer
106
+ (0x1f5a8, 0x1f5a8,), # Printer
107
+ (0x1f5b1, 0x1f5b2,), # Three Button Mouse ..Trackball
108
+ (0x1f5bc, 0x1f5bc,), # Frame With Picture
109
+ (0x1f5c2, 0x1f5c4,), # Card Index Dividers ..File Cabinet
110
+ (0x1f5d1, 0x1f5d3,), # Wastebasket ..Spiral Calendar Pad
111
+ (0x1f5dc, 0x1f5de,), # Compression ..Rolled-up Newspaper
112
+ (0x1f5e1, 0x1f5e1,), # Dagger Knife
113
+ (0x1f5e3, 0x1f5e3,), # Speaking Head In Silhouette
114
+ (0x1f5e8, 0x1f5e8,), # Left Speech Bubble
115
+ (0x1f5ef, 0x1f5ef,), # Right Anger Bubble
116
+ (0x1f5f3, 0x1f5f3,), # Ballot Box With Ballot
117
+ (0x1f5fa, 0x1f5fa,), # World Map
118
+ (0x1f6cb, 0x1f6cb,), # Couch And Lamp
119
+ (0x1f6cd, 0x1f6cf,), # Shopping Bags ..Bed
120
+ (0x1f6e0, 0x1f6e5,), # Hammer And Wrench ..Motor Boat
121
+ (0x1f6e9, 0x1f6e9,), # Small Airplane
122
+ (0x1f6f0, 0x1f6f0,), # Satellite
123
+ (0x1f6f3, 0x1f6f3,), # Passenger Ship
124
+ ),
125
+ }
llava_next/lib/python3.10/site-packages/wcwidth/table_wide.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/wcwidth/table_zero.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/wcwidth/wcwidth.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This is a python implementation of wcwidth() and wcswidth().
3
+
4
+ https://github.com/jquast/wcwidth
5
+
6
+ from Markus Kuhn's C code, retrieved from:
7
+
8
+ http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
9
+
10
+ This is an implementation of wcwidth() and wcswidth() (defined in
11
+ IEEE Std 1002.1-2001) for Unicode.
12
+
13
+ http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html
14
+ http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html
15
+
16
+ In fixed-width output devices, Latin characters all occupy a single
17
+ "cell" position of equal width, whereas ideographic CJK characters
18
+ occupy two such cells. Interoperability between terminal-line
19
+ applications and (teletype-style) character terminals using the
20
+ UTF-8 encoding requires agreement on which character should advance
21
+ the cursor by how many cell positions. No established formal
22
+ standards exist at present on which Unicode character shall occupy
23
+ how many cell positions on character terminals. These routines are
24
+ a first attempt of defining such behavior based on simple rules
25
+ applied to data provided by the Unicode Consortium.
26
+
27
+ For some graphical characters, the Unicode standard explicitly
28
+ defines a character-cell width via the definition of the East Asian
29
+ FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes.
30
+ In all these cases, there is no ambiguity about which width a
31
+ terminal shall use. For characters in the East Asian Ambiguous (A)
32
+ class, the width choice depends purely on a preference of backward
33
+ compatibility with either historic CJK or Western practice.
34
+ Choosing single-width for these characters is easy to justify as
35
+ the appropriate long-term solution, as the CJK practice of
36
+ displaying these characters as double-width comes from historic
37
+ implementation simplicity (8-bit encoded characters were displayed
38
+ single-width and 16-bit ones double-width, even for Greek,
39
+ Cyrillic, etc.) and not any typographic considerations.
40
+
41
+ Much less clear is the choice of width for the Not East Asian
42
+ (Neutral) class. Existing practice does not dictate a width for any
43
+ of these characters. It would nevertheless make sense
44
+ typographically to allocate two character cells to characters such
45
+ as for instance EM SPACE or VOLUME INTEGRAL, which cannot be
46
+ represented adequately with a single-width glyph. The following
47
+ routines at present merely assign a single-cell width to all
48
+ neutral characters, in the interest of simplicity. This is not
49
+ entirely satisfactory and should be reconsidered before
50
+ establishing a formal standard in this area. At the moment, the
51
+ decision which Not East Asian (Neutral) characters should be
52
+ represented by double-width glyphs cannot yet be answered by
53
+ applying a simple rule from the Unicode database content. Setting
54
+ up a proper standard for the behavior of UTF-8 character terminals
55
+ will require a careful analysis not only of each Unicode character,
56
+ but also of each presentation form, something the author of these
57
+ routines has avoided to do so far.
58
+
59
+ http://www.unicode.org/unicode/reports/tr11/
60
+
61
+ Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
62
+ """
63
+ from __future__ import division
64
+
65
+ # std imports
66
+ import os
67
+ import sys
68
+ import warnings
69
+
70
+ # local
71
+ from .table_vs16 import VS16_NARROW_TO_WIDE
72
+ from .table_wide import WIDE_EASTASIAN
73
+ from .table_zero import ZERO_WIDTH
74
+ from .unicode_versions import list_versions
75
+
76
+ try:
77
+ # std imports
78
+ from functools import lru_cache
79
+ except ImportError:
80
+ # lru_cache was added in Python 3.2
81
+ # 3rd party
82
+ from backports.functools_lru_cache import lru_cache
83
+
84
+ # global cache
85
+ _PY3 = sys.version_info[0] >= 3
86
+
87
+
88
+ def _bisearch(ucs, table):
89
+ """
90
+ Auxiliary function for binary search in interval table.
91
+
92
+ :arg int ucs: Ordinal value of unicode character.
93
+ :arg list table: List of starting and ending ranges of ordinal values,
94
+ in form of ``[(start, end), ...]``.
95
+ :rtype: int
96
+ :returns: 1 if ordinal value ucs is found within lookup table, else 0.
97
+ """
98
+ lbound = 0
99
+ ubound = len(table) - 1
100
+
101
+ if ucs < table[0][0] or ucs > table[ubound][1]:
102
+ return 0
103
+ while ubound >= lbound:
104
+ mid = (lbound + ubound) // 2
105
+ if ucs > table[mid][1]:
106
+ lbound = mid + 1
107
+ elif ucs < table[mid][0]:
108
+ ubound = mid - 1
109
+ else:
110
+ return 1
111
+
112
+ return 0
113
+
114
+
115
+ @lru_cache(maxsize=1000)
116
+ def wcwidth(wc, unicode_version='auto'):
117
+ r"""
118
+ Given one Unicode character, return its printable length on a terminal.
119
+
120
+ :param str wc: A single Unicode character.
121
+ :param str unicode_version: A Unicode version number, such as
122
+ ``'6.0.0'``. A list of version levels suported by wcwidth
123
+ is returned by :func:`list_versions`.
124
+
125
+ Any version string may be specified without error -- the nearest
126
+ matching version is selected. When ``latest`` (default), the
127
+ highest Unicode version level is used.
128
+ :return: The width, in cells, necessary to display the character of
129
+ Unicode string character, ``wc``. Returns 0 if the ``wc`` argument has
130
+ no printable effect on a terminal (such as NUL '\0'), -1 if ``wc`` is
131
+ not printable, or has an indeterminate effect on the terminal, such as
132
+ a control character. Otherwise, the number of column positions the
133
+ character occupies on a graphic terminal (1 or 2) is returned.
134
+ :rtype: int
135
+
136
+ See :ref:`Specification` for details of cell measurement.
137
+ """
138
+ ucs = ord(wc) if wc else 0
139
+
140
+ # small optimization: early return of 1 for printable ASCII, this provides
141
+ # approximately 40% performance improvement for mostly-ascii documents, with
142
+ # less than 1% impact to others.
143
+ if 32 <= ucs < 0x7f:
144
+ return 1
145
+
146
+ # C0/C1 control characters are -1 for compatibility with POSIX-like calls
147
+ if ucs and ucs < 32 or 0x07F <= ucs < 0x0A0:
148
+ return -1
149
+
150
+ _unicode_version = _wcmatch_version(unicode_version)
151
+
152
+ # Zero width
153
+ if _bisearch(ucs, ZERO_WIDTH[_unicode_version]):
154
+ return 0
155
+
156
+ # 1 or 2 width
157
+ return 1 + _bisearch(ucs, WIDE_EASTASIAN[_unicode_version])
158
+
159
+
160
+ def wcswidth(pwcs, n=None, unicode_version='auto'):
161
+ """
162
+ Given a unicode string, return its printable length on a terminal.
163
+
164
+ :param str pwcs: Measure width of given unicode string.
165
+ :param int n: When ``n`` is None (default), return the length of the entire
166
+ string, otherwise only the first ``n`` characters are measured. This
167
+ argument exists only for compatibility with the C POSIX function
168
+ signature. It is suggested instead to use python's string slicing
169
+ capability, ``wcswidth(pwcs[:n])``
170
+ :param str unicode_version: An explicit definition of the unicode version
171
+ level to use for determination, may be ``auto`` (default), which uses
172
+ the Environment Variable, ``UNICODE_VERSION`` if defined, or the latest
173
+ available unicode version, otherwise.
174
+ :rtype: int
175
+ :returns: The width, in cells, needed to display the first ``n`` characters
176
+ of the unicode string ``pwcs``. Returns ``-1`` for C0 and C1 control
177
+ characters!
178
+
179
+ See :ref:`Specification` for details of cell measurement.
180
+ """
181
+ # this 'n' argument is a holdover for POSIX function
182
+ _unicode_version = None
183
+ end = len(pwcs) if n is None else n
184
+ width = 0
185
+ idx = 0
186
+ last_measured_char = None
187
+ while idx < end:
188
+ char = pwcs[idx]
189
+ if char == u'\u200D':
190
+ # Zero Width Joiner, do not measure this or next character
191
+ idx += 2
192
+ continue
193
+ if char == u'\uFE0F' and last_measured_char:
194
+ # on variation selector 16 (VS16) following another character,
195
+ # conditionally add '1' to the measured width if that character is
196
+ # known to be converted from narrow to wide by the VS16 character.
197
+ if _unicode_version is None:
198
+ _unicode_version = _wcversion_value(_wcmatch_version(unicode_version))
199
+ if _unicode_version >= (9, 0, 0):
200
+ width += _bisearch(ord(last_measured_char), VS16_NARROW_TO_WIDE["9.0.0"])
201
+ last_measured_char = None
202
+ idx += 1
203
+ continue
204
+ # measure character at current index
205
+ wcw = wcwidth(char, unicode_version)
206
+ if wcw < 0:
207
+ # early return -1 on C0 and C1 control characters
208
+ return wcw
209
+ if wcw > 0:
210
+ # track last character measured to contain a cell, so that
211
+ # subsequent VS-16 modifiers may be understood
212
+ last_measured_char = char
213
+ width += wcw
214
+ idx += 1
215
+ return width
216
+
217
+
218
+ @lru_cache(maxsize=128)
219
+ def _wcversion_value(ver_string):
220
+ """
221
+ Integer-mapped value of given dotted version string.
222
+
223
+ :param str ver_string: Unicode version string, of form ``n.n.n``.
224
+ :rtype: tuple(int)
225
+ :returns: tuple of digit tuples, ``tuple(int, [...])``.
226
+ """
227
+ retval = tuple(map(int, (ver_string.split('.'))))
228
+ return retval
229
+
230
+
231
+ @lru_cache(maxsize=8)
232
+ def _wcmatch_version(given_version):
233
+ """
234
+ Return nearest matching supported Unicode version level.
235
+
236
+ If an exact match is not determined, the nearest lowest version level is
237
+ returned after a warning is emitted. For example, given supported levels
238
+ ``4.1.0`` and ``5.0.0``, and a version string of ``4.9.9``, then ``4.1.0``
239
+ is selected and returned:
240
+
241
+ >>> _wcmatch_version('4.9.9')
242
+ '4.1.0'
243
+ >>> _wcmatch_version('8.0')
244
+ '8.0.0'
245
+ >>> _wcmatch_version('1')
246
+ '4.1.0'
247
+
248
+ :param str given_version: given version for compare, may be ``auto``
249
+ (default), to select Unicode Version from Environment Variable,
250
+ ``UNICODE_VERSION``. If the environment variable is not set, then the
251
+ latest is used.
252
+ :rtype: str
253
+ :returns: unicode string, or non-unicode ``str`` type for python 2
254
+ when given ``version`` is also type ``str``.
255
+ """
256
+ # Design note: the choice to return the same type that is given certainly
257
+ # complicates it for python 2 str-type, but allows us to define an api that
258
+ # uses 'string-type' for unicode version level definitions, so all of our
259
+ # example code works with all versions of python.
260
+ #
261
+ # That, along with the string-to-numeric and comparisons of earliest,
262
+ # latest, matching, or nearest, greatly complicates this function.
263
+ # Performance is somewhat curbed by memoization.
264
+ _return_str = not _PY3 and isinstance(given_version, str)
265
+
266
+ if _return_str:
267
+ # avoid list-comprehension to work around a coverage issue:
268
+ # https://github.com/nedbat/coveragepy/issues/753
269
+ unicode_versions = list(map(lambda ucs: ucs.encode(), list_versions()))
270
+ else:
271
+ unicode_versions = list_versions()
272
+ latest_version = unicode_versions[-1]
273
+
274
+ if given_version in (u'auto', 'auto'):
275
+ given_version = os.environ.get(
276
+ 'UNICODE_VERSION',
277
+ 'latest' if not _return_str else latest_version.encode())
278
+
279
+ if given_version in (u'latest', 'latest'):
280
+ # default match, when given as 'latest', use the most latest unicode
281
+ # version specification level supported.
282
+ return latest_version if not _return_str else latest_version.encode()
283
+
284
+ if given_version in unicode_versions:
285
+ # exact match, downstream has specified an explicit matching version
286
+ # matching any value of list_versions().
287
+ return given_version if not _return_str else given_version.encode()
288
+
289
+ # The user's version is not supported by ours. We return the newest unicode
290
+ # version level that we support below their given value.
291
+ try:
292
+ cmp_given = _wcversion_value(given_version)
293
+
294
+ except ValueError:
295
+ # submitted value raises ValueError in int(), warn and use latest.
296
+ warnings.warn("UNICODE_VERSION value, {given_version!r}, is invalid. "
297
+ "Value should be in form of `integer[.]+', the latest "
298
+ "supported unicode version {latest_version!r} has been "
299
+ "inferred.".format(given_version=given_version,
300
+ latest_version=latest_version))
301
+ return latest_version if not _return_str else latest_version.encode()
302
+
303
+ # given version is less than any available version, return earliest
304
+ # version.
305
+ earliest_version = unicode_versions[0]
306
+ cmp_earliest_version = _wcversion_value(earliest_version)
307
+
308
+ if cmp_given <= cmp_earliest_version:
309
+ # this probably isn't what you wanted, the oldest wcwidth.c you will
310
+ # find in the wild is likely version 5 or 6, which we both support,
311
+ # but it's better than not saying anything at all.
312
+ warnings.warn("UNICODE_VERSION value, {given_version!r}, is lower "
313
+ "than any available unicode version. Returning lowest "
314
+ "version level, {earliest_version!r}".format(
315
+ given_version=given_version,
316
+ earliest_version=earliest_version))
317
+ return earliest_version if not _return_str else earliest_version.encode()
318
+
319
+ # create list of versions which are less than our equal to given version,
320
+ # and return the tail value, which is the highest level we may support,
321
+ # or the latest value we support, when completely unmatched or higher
322
+ # than any supported version.
323
+ #
324
+ # function will never complete, always returns.
325
+ for idx, unicode_version in enumerate(unicode_versions):
326
+ # look ahead to next value
327
+ try:
328
+ cmp_next_version = _wcversion_value(unicode_versions[idx + 1])
329
+ except IndexError:
330
+ # at end of list, return latest version
331
+ return latest_version if not _return_str else latest_version.encode()
332
+
333
+ # Maybe our given version has less parts, as in tuple(8, 0), than the
334
+ # next compare version tuple(8, 0, 0). Test for an exact match by
335
+ # comparison of only the leading dotted piece(s): (8, 0) == (8, 0).
336
+ if cmp_given == cmp_next_version[:len(cmp_given)]:
337
+ return unicode_versions[idx + 1]
338
+
339
+ # Or, if any next value is greater than our given support level
340
+ # version, return the current value in index. Even though it must
341
+ # be less than the given value, its our closest possible match. That
342
+ # is, 4.1 is returned for given 4.9.9, where 4.1 and 5.0 are available.
343
+ if cmp_next_version > cmp_given:
344
+ return unicode_version
345
+ assert False, ("Code path unreachable", given_version, unicode_versions) # pragma: no cover
parrot/lib/python3.10/site-packages/aiofiles/__pycache__/base.cpython-310.pyc ADDED
Binary file (4.56 kB). View file
 
parrot/lib/python3.10/site-packages/aiofiles/tempfile/__init__.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ from functools import partial, singledispatch
3
+ from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOBase
4
+ from tempfile import NamedTemporaryFile as syncNamedTemporaryFile
5
+ from tempfile import SpooledTemporaryFile as syncSpooledTemporaryFile
6
+ from tempfile import TemporaryDirectory as syncTemporaryDirectory
7
+ from tempfile import TemporaryFile as syncTemporaryFile
8
+ from tempfile import _TemporaryFileWrapper as syncTemporaryFileWrapper
9
+
10
+ from ..base import AiofilesContextManager
11
+ from ..threadpool.binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO
12
+ from ..threadpool.text import AsyncTextIOWrapper
13
+ from .temptypes import AsyncSpooledTemporaryFile, AsyncTemporaryDirectory
14
+ import sys
15
+
16
+ __all__ = [
17
+ "NamedTemporaryFile",
18
+ "TemporaryFile",
19
+ "SpooledTemporaryFile",
20
+ "TemporaryDirectory",
21
+ ]
22
+
23
+
24
+ # ================================================================
25
+ # Public methods for async open and return of temp file/directory
26
+ # objects with async interface
27
+ # ================================================================
28
+ if sys.version_info >= (3, 12):
29
+
30
+ def NamedTemporaryFile(
31
+ mode="w+b",
32
+ buffering=-1,
33
+ encoding=None,
34
+ newline=None,
35
+ suffix=None,
36
+ prefix=None,
37
+ dir=None,
38
+ delete=True,
39
+ delete_on_close=True,
40
+ loop=None,
41
+ executor=None,
42
+ ):
43
+ """Async open a named temporary file"""
44
+ return AiofilesContextManager(
45
+ _temporary_file(
46
+ named=True,
47
+ mode=mode,
48
+ buffering=buffering,
49
+ encoding=encoding,
50
+ newline=newline,
51
+ suffix=suffix,
52
+ prefix=prefix,
53
+ dir=dir,
54
+ delete=delete,
55
+ delete_on_close=delete_on_close,
56
+ loop=loop,
57
+ executor=executor,
58
+ )
59
+ )
60
+
61
+ else:
62
+
63
+ def NamedTemporaryFile(
64
+ mode="w+b",
65
+ buffering=-1,
66
+ encoding=None,
67
+ newline=None,
68
+ suffix=None,
69
+ prefix=None,
70
+ dir=None,
71
+ delete=True,
72
+ loop=None,
73
+ executor=None,
74
+ ):
75
+ """Async open a named temporary file"""
76
+ return AiofilesContextManager(
77
+ _temporary_file(
78
+ named=True,
79
+ mode=mode,
80
+ buffering=buffering,
81
+ encoding=encoding,
82
+ newline=newline,
83
+ suffix=suffix,
84
+ prefix=prefix,
85
+ dir=dir,
86
+ delete=delete,
87
+ loop=loop,
88
+ executor=executor,
89
+ )
90
+ )
91
+
92
+
93
+ def TemporaryFile(
94
+ mode="w+b",
95
+ buffering=-1,
96
+ encoding=None,
97
+ newline=None,
98
+ suffix=None,
99
+ prefix=None,
100
+ dir=None,
101
+ loop=None,
102
+ executor=None,
103
+ ):
104
+ """Async open an unnamed temporary file"""
105
+ return AiofilesContextManager(
106
+ _temporary_file(
107
+ named=False,
108
+ mode=mode,
109
+ buffering=buffering,
110
+ encoding=encoding,
111
+ newline=newline,
112
+ suffix=suffix,
113
+ prefix=prefix,
114
+ dir=dir,
115
+ loop=loop,
116
+ executor=executor,
117
+ )
118
+ )
119
+
120
+
121
+ def SpooledTemporaryFile(
122
+ max_size=0,
123
+ mode="w+b",
124
+ buffering=-1,
125
+ encoding=None,
126
+ newline=None,
127
+ suffix=None,
128
+ prefix=None,
129
+ dir=None,
130
+ loop=None,
131
+ executor=None,
132
+ ):
133
+ """Async open a spooled temporary file"""
134
+ return AiofilesContextManager(
135
+ _spooled_temporary_file(
136
+ max_size=max_size,
137
+ mode=mode,
138
+ buffering=buffering,
139
+ encoding=encoding,
140
+ newline=newline,
141
+ suffix=suffix,
142
+ prefix=prefix,
143
+ dir=dir,
144
+ loop=loop,
145
+ executor=executor,
146
+ )
147
+ )
148
+
149
+
150
+ def TemporaryDirectory(suffix=None, prefix=None, dir=None, loop=None, executor=None):
151
+ """Async open a temporary directory"""
152
+ return AiofilesContextManagerTempDir(
153
+ _temporary_directory(
154
+ suffix=suffix, prefix=prefix, dir=dir, loop=loop, executor=executor
155
+ )
156
+ )
157
+
158
+
159
+ # =========================================================
160
+ # Internal coroutines to open new temp files/directories
161
+ # =========================================================
162
+ if sys.version_info >= (3, 12):
163
+
164
+ async def _temporary_file(
165
+ named=True,
166
+ mode="w+b",
167
+ buffering=-1,
168
+ encoding=None,
169
+ newline=None,
170
+ suffix=None,
171
+ prefix=None,
172
+ dir=None,
173
+ delete=True,
174
+ delete_on_close=True,
175
+ loop=None,
176
+ executor=None,
177
+ max_size=0,
178
+ ):
179
+ """Async method to open a temporary file with async interface"""
180
+ if loop is None:
181
+ loop = asyncio.get_running_loop()
182
+
183
+ if named:
184
+ cb = partial(
185
+ syncNamedTemporaryFile,
186
+ mode=mode,
187
+ buffering=buffering,
188
+ encoding=encoding,
189
+ newline=newline,
190
+ suffix=suffix,
191
+ prefix=prefix,
192
+ dir=dir,
193
+ delete=delete,
194
+ delete_on_close=delete_on_close,
195
+ )
196
+ else:
197
+ cb = partial(
198
+ syncTemporaryFile,
199
+ mode=mode,
200
+ buffering=buffering,
201
+ encoding=encoding,
202
+ newline=newline,
203
+ suffix=suffix,
204
+ prefix=prefix,
205
+ dir=dir,
206
+ )
207
+
208
+ f = await loop.run_in_executor(executor, cb)
209
+
210
+ # Wrap based on type of underlying IO object
211
+ if type(f) is syncTemporaryFileWrapper:
212
+ # _TemporaryFileWrapper was used (named files)
213
+ result = wrap(f.file, f, loop=loop, executor=executor)
214
+ result._closer = f._closer
215
+ return result
216
+ else:
217
+ # IO object was returned directly without wrapper
218
+ return wrap(f, f, loop=loop, executor=executor)
219
+
220
+ else:
221
+
222
+ async def _temporary_file(
223
+ named=True,
224
+ mode="w+b",
225
+ buffering=-1,
226
+ encoding=None,
227
+ newline=None,
228
+ suffix=None,
229
+ prefix=None,
230
+ dir=None,
231
+ delete=True,
232
+ loop=None,
233
+ executor=None,
234
+ max_size=0,
235
+ ):
236
+ """Async method to open a temporary file with async interface"""
237
+ if loop is None:
238
+ loop = asyncio.get_running_loop()
239
+
240
+ if named:
241
+ cb = partial(
242
+ syncNamedTemporaryFile,
243
+ mode=mode,
244
+ buffering=buffering,
245
+ encoding=encoding,
246
+ newline=newline,
247
+ suffix=suffix,
248
+ prefix=prefix,
249
+ dir=dir,
250
+ delete=delete,
251
+ )
252
+ else:
253
+ cb = partial(
254
+ syncTemporaryFile,
255
+ mode=mode,
256
+ buffering=buffering,
257
+ encoding=encoding,
258
+ newline=newline,
259
+ suffix=suffix,
260
+ prefix=prefix,
261
+ dir=dir,
262
+ )
263
+
264
+ f = await loop.run_in_executor(executor, cb)
265
+
266
+ # Wrap based on type of underlying IO object
267
+ if type(f) is syncTemporaryFileWrapper:
268
+ # _TemporaryFileWrapper was used (named files)
269
+ result = wrap(f.file, f, loop=loop, executor=executor)
270
+ # add delete property
271
+ result.delete = f.delete
272
+ return result
273
+ else:
274
+ # IO object was returned directly without wrapper
275
+ return wrap(f, f, loop=loop, executor=executor)
276
+
277
+
278
+ async def _spooled_temporary_file(
279
+ max_size=0,
280
+ mode="w+b",
281
+ buffering=-1,
282
+ encoding=None,
283
+ newline=None,
284
+ suffix=None,
285
+ prefix=None,
286
+ dir=None,
287
+ loop=None,
288
+ executor=None,
289
+ ):
290
+ """Open a spooled temporary file with async interface"""
291
+ if loop is None:
292
+ loop = asyncio.get_running_loop()
293
+
294
+ cb = partial(
295
+ syncSpooledTemporaryFile,
296
+ max_size=max_size,
297
+ mode=mode,
298
+ buffering=buffering,
299
+ encoding=encoding,
300
+ newline=newline,
301
+ suffix=suffix,
302
+ prefix=prefix,
303
+ dir=dir,
304
+ )
305
+
306
+ f = await loop.run_in_executor(executor, cb)
307
+
308
+ # Single interface provided by SpooledTemporaryFile for all modes
309
+ return AsyncSpooledTemporaryFile(f, loop=loop, executor=executor)
310
+
311
+
312
+ async def _temporary_directory(
313
+ suffix=None, prefix=None, dir=None, loop=None, executor=None
314
+ ):
315
+ """Async method to open a temporary directory with async interface"""
316
+ if loop is None:
317
+ loop = asyncio.get_running_loop()
318
+
319
+ cb = partial(syncTemporaryDirectory, suffix, prefix, dir)
320
+ f = await loop.run_in_executor(executor, cb)
321
+
322
+ return AsyncTemporaryDirectory(f, loop=loop, executor=executor)
323
+
324
+
325
+ class AiofilesContextManagerTempDir(AiofilesContextManager):
326
+ """With returns the directory location, not the object (matching sync lib)"""
327
+
328
+ async def __aenter__(self):
329
+ self._obj = await self._coro
330
+ return self._obj.name
331
+
332
+
333
+ @singledispatch
334
+ def wrap(base_io_obj, file, *, loop=None, executor=None):
335
+ """Wrap the object with interface based on type of underlying IO"""
336
+ raise TypeError("Unsupported IO type: {}".format(base_io_obj))
337
+
338
+
339
+ @wrap.register(TextIOBase)
340
+ def _(base_io_obj, file, *, loop=None, executor=None):
341
+ return AsyncTextIOWrapper(file, loop=loop, executor=executor)
342
+
343
+
344
+ @wrap.register(BufferedWriter)
345
+ def _(base_io_obj, file, *, loop=None, executor=None):
346
+ return AsyncBufferedIOBase(file, loop=loop, executor=executor)
347
+
348
+
349
+ @wrap.register(BufferedReader)
350
+ @wrap.register(BufferedRandom)
351
+ def _(base_io_obj, file, *, loop=None, executor=None):
352
+ return AsyncBufferedReader(file, loop=loop, executor=executor)
353
+
354
+
355
+ @wrap.register(FileIO)
356
+ def _(base_io_obj, file, *, loop=None, executor=None):
357
+ return AsyncFileIO(file, loop=loop, executor=executor)
parrot/lib/python3.10/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5.96 kB). View file
 
parrot/lib/python3.10/site-packages/aiofiles/tempfile/temptypes.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async wrappers for spooled temp files and temp directory objects"""
2
+ from functools import partial
3
+
4
+ from ..base import AsyncBase
5
+ from ..threadpool.utils import (
6
+ cond_delegate_to_executor,
7
+ delegate_to_executor,
8
+ proxy_property_directly,
9
+ )
10
+
11
+
12
+ @delegate_to_executor("fileno", "rollover")
13
+ @cond_delegate_to_executor(
14
+ "close",
15
+ "flush",
16
+ "isatty",
17
+ "read",
18
+ "readline",
19
+ "readlines",
20
+ "seek",
21
+ "tell",
22
+ "truncate",
23
+ )
24
+ @proxy_property_directly("closed", "encoding", "mode", "name", "newlines")
25
+ class AsyncSpooledTemporaryFile(AsyncBase):
26
+ """Async wrapper for SpooledTemporaryFile class"""
27
+
28
+ async def _check(self):
29
+ if self._file._rolled:
30
+ return
31
+ max_size = self._file._max_size
32
+ if max_size and self._file.tell() > max_size:
33
+ await self.rollover()
34
+
35
+ async def write(self, s):
36
+ """Implementation to anticipate rollover"""
37
+ if self._file._rolled:
38
+ cb = partial(self._file.write, s)
39
+ return await self._loop.run_in_executor(self._executor, cb)
40
+ else:
41
+ file = self._file._file # reference underlying base IO object
42
+ rv = file.write(s)
43
+ await self._check()
44
+ return rv
45
+
46
+ async def writelines(self, iterable):
47
+ """Implementation to anticipate rollover"""
48
+ if self._file._rolled:
49
+ cb = partial(self._file.writelines, iterable)
50
+ return await self._loop.run_in_executor(self._executor, cb)
51
+ else:
52
+ file = self._file._file # reference underlying base IO object
53
+ rv = file.writelines(iterable)
54
+ await self._check()
55
+ return rv
56
+
57
+
58
+ @delegate_to_executor("cleanup")
59
+ @proxy_property_directly("name")
60
+ class AsyncTemporaryDirectory:
61
+ """Async wrapper for TemporaryDirectory class"""
62
+
63
+ def __init__(self, file, loop, executor):
64
+ self._file = file
65
+ self._loop = loop
66
+ self._executor = executor
67
+
68
+ async def close(self):
69
+ await self.cleanup()
parrot/lib/python3.10/site-packages/sympy/abc.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module exports all latin and greek letters as Symbols, so you can
3
+ conveniently do
4
+
5
+ >>> from sympy.abc import x, y
6
+
7
+ instead of the slightly more clunky-looking
8
+
9
+ >>> from sympy import symbols
10
+ >>> x, y = symbols('x y')
11
+
12
+ Caveats
13
+ =======
14
+
15
+ 1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``,
16
+ ``E``, and ``Q`` are colliding with names defined in SymPy. If you import them
17
+ from both ``sympy.abc`` and ``sympy``, the second import will "win".
18
+ This is an issue only for * imports, which should only be used for short-lived
19
+ code such as interactive sessions and throwaway scripts that do not survive
20
+ until the next SymPy upgrade, where ``sympy`` may contain a different set of
21
+ names.
22
+
23
+ 2. This module does not define symbol names on demand, i.e.
24
+ ``from sympy.abc import foo`` will be reported as an error because
25
+ ``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``,
26
+ you still need to use ``Symbol('foo')`` or ``symbols('foo')``.
27
+ You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though
28
+ sticking with one and only one way to get the symbols does tend to make the code
29
+ more readable.
30
+
31
+ The module also defines some special names to help detect which names clash
32
+ with the default SymPy namespace.
33
+
34
+ ``_clash1`` defines all the single letter variables that clash with
35
+ SymPy objects; ``_clash2`` defines the multi-letter clashing symbols;
36
+ and ``_clash`` is the union of both. These can be passed for ``locals``
37
+ during sympification if one desires Symbols rather than the non-Symbol
38
+ objects for those names.
39
+
40
+ Examples
41
+ ========
42
+
43
+ >>> from sympy import S
44
+ >>> from sympy.abc import _clash1, _clash2, _clash
45
+ >>> S("Q & C", locals=_clash1)
46
+ C & Q
47
+ >>> S('pi(x)', locals=_clash2)
48
+ pi(x)
49
+ >>> S('pi(C, Q)', locals=_clash)
50
+ pi(C, Q)
51
+
52
+ """
53
+
54
+ from typing import Any, Dict as tDict
55
+
56
+ import string
57
+
58
+ from .core import Symbol, symbols
59
+ from .core.alphabets import greeks
60
+ from sympy.parsing.sympy_parser import null
61
+
62
+ ##### Symbol definitions #####
63
+
64
+ # Implementation note: The easiest way to avoid typos in the symbols()
65
+ # parameter is to copy it from the left-hand side of the assignment.
66
+
67
+ a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j')
68
+ k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t')
69
+ u, v, w, x, y, z = symbols('u, v, w, x, y, z')
70
+
71
+ A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J')
72
+ K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T')
73
+ U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z')
74
+
75
+ alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta')
76
+ epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta')
77
+ iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu')
78
+ nu, xi, omicron, pi = symbols('nu, xi, omicron, pi')
79
+ rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon')
80
+ phi, chi, psi, omega = symbols('phi, chi, psi, omega')
81
+
82
+
83
+ ##### Clashing-symbols diagnostics #####
84
+
85
+ # We want to know which names in SymPy collide with those in here.
86
+ # This is mostly for diagnosing SymPy's namespace during SymPy development.
87
+
88
+ _latin = list(string.ascii_letters)
89
+ # QOSINE should not be imported as they clash; gamma, pi and zeta clash, too
90
+ _greek = list(greeks) # make a copy, so we can mutate it
91
+ # Note: We import lamda since lambda is a reserved keyword in Python
92
+ _greek.remove("lambda")
93
+ _greek.append("lamda")
94
+
95
+ ns: tDict[str, Any] = {}
96
+ exec('from sympy import *', ns)
97
+ _clash1: tDict[str, Any] = {}
98
+ _clash2: tDict[str, Any] = {}
99
+ while ns:
100
+ _k, _ = ns.popitem()
101
+ if _k in _greek:
102
+ _clash2[_k] = null
103
+ _greek.remove(_k)
104
+ elif _k in _latin:
105
+ _clash1[_k] = null
106
+ _latin.remove(_k)
107
+ _clash = {}
108
+ _clash.update(_clash1)
109
+ _clash.update(_clash2)
110
+
111
+ del _latin, _greek, Symbol, _k, null
parrot/lib/python3.10/site-packages/sympy/conftest.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ sys._running_pytest = True # type: ignore
4
+ from sympy.external.importtools import version_tuple
5
+
6
+ import pytest
7
+ from sympy.core.cache import clear_cache, USE_CACHE
8
+ from sympy.external.gmpy import GROUND_TYPES
9
+ from sympy.utilities.misc import ARCH
10
+ import re
11
+
12
+ try:
13
+ import hypothesis
14
+
15
+ hypothesis.settings.register_profile("sympy_hypothesis_profile", deadline=None)
16
+ hypothesis.settings.load_profile("sympy_hypothesis_profile")
17
+ except ImportError:
18
+ raise ImportError(
19
+ "hypothesis is a required dependency to run the SymPy test suite. "
20
+ "Install it with 'pip install hypothesis' or 'conda install -c conda-forge hypothesis'"
21
+ )
22
+
23
+
24
+ sp = re.compile(r"([0-9]+)/([1-9][0-9]*)")
25
+
26
+
27
+ def process_split(config, items):
28
+ split = config.getoption("--split")
29
+ if not split:
30
+ return
31
+ m = sp.match(split)
32
+ if not m:
33
+ raise ValueError(
34
+ "split must be a string of the form a/b " "where a and b are ints."
35
+ )
36
+ i, t = map(int, m.groups())
37
+ start, end = (i - 1) * len(items) // t, i * len(items) // t
38
+
39
+ if i < t:
40
+ # remove elements from end of list first
41
+ del items[end:]
42
+ del items[:start]
43
+
44
+
45
+ def pytest_report_header(config):
46
+ s = "architecture: %s\n" % ARCH
47
+ s += "cache: %s\n" % USE_CACHE
48
+ version = ""
49
+ if GROUND_TYPES == "gmpy":
50
+ import gmpy2
51
+
52
+ version = gmpy2.version()
53
+ elif GROUND_TYPES == "flint":
54
+ try:
55
+ from flint import __version__
56
+ except ImportError:
57
+ version = "unknown"
58
+ else:
59
+ version = f'(python-flint=={__version__})'
60
+ s += "ground types: %s %s\n" % (GROUND_TYPES, version)
61
+ return s
62
+
63
+
64
+ def pytest_terminal_summary(terminalreporter):
65
+ if terminalreporter.stats.get("error", None) or terminalreporter.stats.get(
66
+ "failed", None
67
+ ):
68
+ terminalreporter.write_sep(" ", "DO *NOT* COMMIT!", red=True, bold=True)
69
+
70
+
71
+ def pytest_addoption(parser):
72
+ parser.addoption("--split", action="store", default="", help="split tests")
73
+
74
+
75
+ def pytest_collection_modifyitems(config, items):
76
+ """pytest hook."""
77
+ # handle splits
78
+ process_split(config, items)
79
+
80
+
81
+ @pytest.fixture(autouse=True, scope="module")
82
+ def file_clear_cache():
83
+ clear_cache()
84
+
85
+
86
+ @pytest.fixture(autouse=True, scope="module")
87
+ def check_disabled(request):
88
+ if getattr(request.module, "disabled", False):
89
+ pytest.skip("test requirements not met.")
90
+ elif getattr(request.module, "ipython", False):
91
+ # need to check version and options for ipython tests
92
+ if (
93
+ version_tuple(pytest.__version__) < version_tuple("2.6.3")
94
+ and pytest.config.getvalue("-s") != "no"
95
+ ):
96
+ pytest.skip("run py.test with -s or upgrade to newer version.")
parrot/lib/python3.10/site-packages/sympy/discrete/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This module contains functions which operate on discrete sequences.
2
+
3
+ Transforms - ``fft``, ``ifft``, ``ntt``, ``intt``, ``fwht``, ``ifwht``,
4
+ ``mobius_transform``, ``inverse_mobius_transform``
5
+
6
+ Convolutions - ``convolution``, ``convolution_fft``, ``convolution_ntt``,
7
+ ``convolution_fwht``, ``convolution_subset``,
8
+ ``covering_product``, ``intersecting_product``
9
+ """
10
+
11
+ from .transforms import (fft, ifft, ntt, intt, fwht, ifwht,
12
+ mobius_transform, inverse_mobius_transform)
13
+ from .convolutions import convolution, covering_product, intersecting_product
14
+
15
+ __all__ = [
16
+ 'fft', 'ifft', 'ntt', 'intt', 'fwht', 'ifwht', 'mobius_transform',
17
+ 'inverse_mobius_transform',
18
+
19
+ 'convolution', 'covering_product', 'intersecting_product',
20
+ ]
parrot/lib/python3.10/site-packages/sympy/discrete/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (939 Bytes). View file
 
parrot/lib/python3.10/site-packages/sympy/discrete/__pycache__/convolutions.cpython-310.pyc ADDED
Binary file (16.2 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/discrete/__pycache__/recurrences.cpython-310.pyc ADDED
Binary file (5.08 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/discrete/__pycache__/transforms.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/discrete/recurrences.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Recurrences
3
+ """
4
+
5
+ from sympy.core import S, sympify
6
+ from sympy.utilities.iterables import iterable
7
+ from sympy.utilities.misc import as_int
8
+
9
+
10
+ def linrec(coeffs, init, n):
11
+ r"""
12
+ Evaluation of univariate linear recurrences of homogeneous type
13
+ having coefficients independent of the recurrence variable.
14
+
15
+ Parameters
16
+ ==========
17
+
18
+ coeffs : iterable
19
+ Coefficients of the recurrence
20
+ init : iterable
21
+ Initial values of the recurrence
22
+ n : Integer
23
+ Point of evaluation for the recurrence
24
+
25
+ Notes
26
+ =====
27
+
28
+ Let `y(n)` be the recurrence of given type, ``c`` be the sequence
29
+ of coefficients, ``b`` be the sequence of initial/base values of the
30
+ recurrence and ``k`` (equal to ``len(c)``) be the order of recurrence.
31
+ Then,
32
+
33
+ .. math :: y(n) = \begin{cases} b_n & 0 \le n < k \\
34
+ c_0 y(n-1) + c_1 y(n-2) + \cdots + c_{k-1} y(n-k) & n \ge k
35
+ \end{cases}
36
+
37
+ Let `x_0, x_1, \ldots, x_n` be a sequence and consider the transformation
38
+ that maps each polynomial `f(x)` to `T(f(x))` where each power `x^i` is
39
+ replaced by the corresponding value `x_i`. The sequence is then a solution
40
+ of the recurrence if and only if `T(x^i p(x)) = 0` for each `i \ge 0` where
41
+ `p(x) = x^k - c_0 x^(k-1) - \cdots - c_{k-1}` is the characteristic
42
+ polynomial.
43
+
44
+ Then `T(f(x)p(x)) = 0` for each polynomial `f(x)` (as it is a linear
45
+ combination of powers `x^i`). Now, if `x^n` is congruent to
46
+ `g(x) = a_0 x^0 + a_1 x^1 + \cdots + a_{k-1} x^{k-1}` modulo `p(x)`, then
47
+ `T(x^n) = x_n` is equal to
48
+ `T(g(x)) = a_0 x_0 + a_1 x_1 + \cdots + a_{k-1} x_{k-1}`.
49
+
50
+ Computation of `x^n`,
51
+ given `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
52
+ is performed using exponentiation by squaring (refer to [1_]) with
53
+ an additional reduction step performed to retain only first `k` powers
54
+ of `x` in the representation of `x^n`.
55
+
56
+ Examples
57
+ ========
58
+
59
+ >>> from sympy.discrete.recurrences import linrec
60
+ >>> from sympy.abc import x, y, z
61
+
62
+ >>> linrec(coeffs=[1, 1], init=[0, 1], n=10)
63
+ 55
64
+
65
+ >>> linrec(coeffs=[1, 1], init=[x, y], n=10)
66
+ 34*x + 55*y
67
+
68
+ >>> linrec(coeffs=[x, y], init=[0, 1], n=5)
69
+ x**2*y + x*(x**3 + 2*x*y) + y**2
70
+
71
+ >>> linrec(coeffs=[1, 2, 3, 0, 0, 4], init=[x, y, z], n=16)
72
+ 13576*x + 5676*y + 2356*z
73
+
74
+ References
75
+ ==========
76
+
77
+ .. [1] https://en.wikipedia.org/wiki/Exponentiation_by_squaring
78
+ .. [2] https://en.wikipedia.org/w/index.php?title=Modular_exponentiation&section=6#Matrices
79
+
80
+ See Also
81
+ ========
82
+
83
+ sympy.polys.agca.extensions.ExtensionElement.__pow__
84
+
85
+ """
86
+
87
+ if not coeffs:
88
+ return S.Zero
89
+
90
+ if not iterable(coeffs):
91
+ raise TypeError("Expected a sequence of coefficients for"
92
+ " the recurrence")
93
+
94
+ if not iterable(init):
95
+ raise TypeError("Expected a sequence of values for the initialization"
96
+ " of the recurrence")
97
+
98
+ n = as_int(n)
99
+ if n < 0:
100
+ raise ValueError("Point of evaluation of recurrence must be a "
101
+ "non-negative integer")
102
+
103
+ c = [sympify(arg) for arg in coeffs]
104
+ b = [sympify(arg) for arg in init]
105
+ k = len(c)
106
+
107
+ if len(b) > k:
108
+ raise TypeError("Count of initial values should not exceed the "
109
+ "order of the recurrence")
110
+ else:
111
+ b += [S.Zero]*(k - len(b)) # remaining initial values default to zero
112
+
113
+ if n < k:
114
+ return b[n]
115
+ terms = [u*v for u, v in zip(linrec_coeffs(c, n), b)]
116
+ return sum(terms[:-1], terms[-1])
117
+
118
+
119
+ def linrec_coeffs(c, n):
120
+ r"""
121
+ Compute the coefficients of n'th term in linear recursion
122
+ sequence defined by c.
123
+
124
+ `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`.
125
+
126
+ It computes the coefficients by using binary exponentiation.
127
+ This function is used by `linrec` and `_eval_pow_by_cayley`.
128
+
129
+ Parameters
130
+ ==========
131
+
132
+ c = coefficients of the divisor polynomial
133
+ n = exponent of x, so dividend is x^n
134
+
135
+ """
136
+
137
+ k = len(c)
138
+
139
+ def _square_and_reduce(u, offset):
140
+ # squares `(u_0 + u_1 x + u_2 x^2 + \cdots + u_{k-1} x^k)` (and
141
+ # multiplies by `x` if offset is 1) and reduces the above result of
142
+ # length upto `2k` to `k` using the characteristic equation of the
143
+ # recurrence given by, `x^k = c_0 x^{k-1} + c_1 x^{k-2} + \cdots + c_{k-1}`
144
+
145
+ w = [S.Zero]*(2*len(u) - 1 + offset)
146
+ for i, p in enumerate(u):
147
+ for j, q in enumerate(u):
148
+ w[offset + i + j] += p*q
149
+
150
+ for j in range(len(w) - 1, k - 1, -1):
151
+ for i in range(k):
152
+ w[j - i - 1] += w[j]*c[i]
153
+
154
+ return w[:k]
155
+
156
+ def _final_coeffs(n):
157
+ # computes the final coefficient list - `cf` corresponding to the
158
+ # point at which recurrence is to be evalauted - `n`, such that,
159
+ # `y(n) = cf_0 y(k-1) + cf_1 y(k-2) + \cdots + cf_{k-1} y(0)`
160
+
161
+ if n < k:
162
+ return [S.Zero]*n + [S.One] + [S.Zero]*(k - n - 1)
163
+ else:
164
+ return _square_and_reduce(_final_coeffs(n // 2), n % 2)
165
+
166
+ return _final_coeffs(n)
parrot/lib/python3.10/site-packages/sympy/discrete/tests/__init__.py ADDED
File without changes
parrot/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (172 Bytes). View file
 
parrot/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_convolutions.cpython-310.pyc ADDED
Binary file (16.3 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_recurrences.cpython-310.pyc ADDED
Binary file (3.43 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/discrete/tests/__pycache__/test_transforms.cpython-310.pyc ADDED
Binary file (6.72 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/discrete/tests/test_convolutions.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (E, Rational, pi)
2
+ from sympy.functions.elementary.exponential import exp
3
+ from sympy.functions.elementary.miscellaneous import sqrt
4
+ from sympy.core import S, symbols, I
5
+ from sympy.discrete.convolutions import (
6
+ convolution, convolution_fft, convolution_ntt, convolution_fwht,
7
+ convolution_subset, covering_product, intersecting_product,
8
+ convolution_int)
9
+ from sympy.testing.pytest import raises
10
+ from sympy.abc import x, y
11
+
12
+ def test_convolution():
13
+ # fft
14
+ a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
15
+ b = [9, 5, 5, 4, 3, 2]
16
+ c = [3, 5, 3, 7, 8]
17
+ d = [1422, 6572, 3213, 5552]
18
+ e = [-1, Rational(5, 3), Rational(7, 5)]
19
+
20
+ assert convolution(a, b) == convolution_fft(a, b)
21
+ assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9)
22
+ assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7)
23
+ assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3)
24
+
25
+ # prime moduli of the form (m*2**k + 1), sequence length
26
+ # should be a divisor of 2**k
27
+ p = 7*17*2**23 + 1
28
+ q = 19*2**10 + 1
29
+
30
+ # ntt
31
+ assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q)
32
+ assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p)
33
+ assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p)
34
+ raises(TypeError, lambda: convolution(b, d, dps=5, prime=q))
35
+ raises(TypeError, lambda: convolution(b, d, dps=6, prime=q))
36
+
37
+ # fwht
38
+ assert convolution(a, b, dyadic=True) == convolution_fwht(a, b)
39
+ assert convolution(a, b, dyadic=False) == convolution(a, b)
40
+ raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True))
41
+ raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True))
42
+ raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True))
43
+ raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True))
44
+
45
+ # subset
46
+ assert convolution(a, b, subset=True) == convolution_subset(a, b) == \
47
+ convolution(a, b, subset=True, dyadic=False) == \
48
+ convolution(a, b, subset=True)
49
+ assert convolution(a, b, subset=False) == convolution(a, b)
50
+ raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True))
51
+ raises(TypeError, lambda: convolution(c, d, subset=True, dps=6))
52
+ raises(TypeError, lambda: convolution(a, c, subset=True, prime=q))
53
+
54
+ # integer
55
+ assert convolution([0], [0]) == convolution_int([0], [0])
56
+ assert convolution(b, c) == convolution_int(b, c)
57
+
58
+ # rational
59
+ assert convolution([Rational(1,2)], [Rational(1,2)]) == [Rational(1, 4)]
60
+ assert convolution(b, e) == [-9, 10, Rational(239, 15), Rational(34, 3),
61
+ Rational(32, 3), Rational(43, 5), Rational(113, 15),
62
+ Rational(14, 5)]
63
+
64
+
65
+ def test_cyclic_convolution():
66
+ # fft
67
+ a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
68
+ b = [9, 5, 5, 4, 3, 2]
69
+
70
+ assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \
71
+ convolution([1, 2, 3], [4, 5, 6], cycle=5) == \
72
+ convolution([1, 2, 3], [4, 5, 6])
73
+
74
+ assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28]
75
+
76
+ a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)]
77
+ b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)]
78
+
79
+ assert convolution(a, b, cycle=0) == \
80
+ convolution(a, b, cycle=len(a) + len(b) - 1)
81
+
82
+ assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340),
83
+ Rational(11125, 4032), Rational(3653, 1080)]
84
+
85
+ assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24),
86
+ Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)]
87
+
88
+ assert convolution(a, b, cycle=9) == \
89
+ convolution(a, b, cycle=0) + [S.Zero]
90
+
91
+ # ntt
92
+ a = [2313, 5323532, S(3232), 42142, 42242421]
93
+ b = [S(33456), 56757, 45754, 432423]
94
+
95
+ assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \
96
+ convolution(a, b, prime=19*2**10 + 1, cycle=8) == \
97
+ convolution(a, b, prime=19*2**10 + 1)
98
+
99
+ assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664,
100
+ 15534, 3517]
101
+
102
+ assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260,
103
+ 15534, 3517, 16314, 13688]
104
+
105
+ assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \
106
+ convolution(a, b, prime=19*2**10 + 1) + [0]
107
+
108
+ # fwht
109
+ u, v, w, x, y = symbols('u v w x y')
110
+ p, q, r, s, t = symbols('p q r s t')
111
+ c = [u, v, w, x, y]
112
+ d = [p, q, r, s, t]
113
+
114
+ assert convolution(a, b, dyadic=True, cycle=3) == \
115
+ [2499522285783, 19861417974796, 4702176579021]
116
+
117
+ assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143,
118
+ 2114320852171, 20571217906407, 246166418903, 1413262436976]
119
+
120
+ assert convolution(c, d, dyadic=True, cycle=4) == \
121
+ [p*u + p*y + q*v + r*w + s*x + t*u + t*y,
122
+ p*v + q*u + q*y + r*x + s*w + t*v,
123
+ p*w + q*x + r*u + r*y + s*v + t*w,
124
+ p*x + q*w + r*v + s*u + s*y + t*x]
125
+
126
+ assert convolution(c, d, dyadic=True, cycle=6) == \
127
+ [p*u + q*v + r*w + r*y + s*x + t*w + t*y,
128
+ p*v + q*u + r*x + s*w + s*y + t*x,
129
+ p*w + q*x + r*u + s*v,
130
+ p*x + q*w + r*v + s*u,
131
+ p*y + t*u,
132
+ q*y + t*v]
133
+
134
+ # subset
135
+ assert convolution(a, b, subset=True, cycle=7) == [18266671799811,
136
+ 178235365533, 213958794, 246166418903, 1413262436976,
137
+ 2397553088697, 1932759730434]
138
+
139
+ assert convolution(a[1:], b, subset=True, cycle=4) == \
140
+ [178104086592, 302255835516, 244982785880, 3717819845434]
141
+
142
+ assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162,
143
+ 178235365533, 213958794, 245166224504, 1413262436976, 2397553088697]
144
+
145
+ assert convolution(c, d, subset=True, cycle=3) == \
146
+ [p*u + p*x + q*w + r*v + r*y + s*u + t*w,
147
+ p*v + p*y + q*u + s*y + t*u + t*x,
148
+ p*w + q*y + r*u + t*v]
149
+
150
+ assert convolution(c, d, subset=True, cycle=5) == \
151
+ [p*u + q*y + t*v,
152
+ p*v + q*u + r*y + t*w,
153
+ p*w + r*u + s*y + t*x,
154
+ p*x + q*w + r*v + s*u,
155
+ p*y + t*u]
156
+
157
+ raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1))
158
+
159
+
160
+ def test_convolution_fft():
161
+ assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3))
162
+ assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
163
+ assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7]
164
+ assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
165
+
166
+ assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I]
167
+ assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + 3*I/5], [Rational(2, 5) + 4*I/7]) == \
168
+ [Rational(-26, 35) + I*48/35, Rational(-38, 35) + I*116/35, Rational(58, 35) + I*542/175]
169
+
170
+ assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \
171
+ [Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)]
172
+
173
+ assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \
174
+ [Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)]
175
+
176
+ assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \
177
+ [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6),
178
+ sqrt(2)/pi + 1, sqrt(2)*exp(-1)]
179
+
180
+ assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \
181
+ [12350041, 190918524, 374911166, 2362431729]
182
+
183
+ assert convolution_fft([312313, 31278232], [32139631, 319631]) == \
184
+ [10037624576503, 1005370659728895, 9997492572392]
185
+
186
+ raises(TypeError, lambda: convolution_fft(x, y))
187
+ raises(ValueError, lambda: convolution_fft([x, y], [y, x]))
188
+
189
+
190
+ def test_convolution_ntt():
191
+ # prime moduli of the form (m*2**k + 1), sequence length
192
+ # should be a divisor of 2**k
193
+ p = 7*17*2**23 + 1
194
+ q = 19*2**10 + 1
195
+ r = 2*500000003 + 1 # only for sequences of length 1 or 2
196
+ # s = 2*3*5*7 # composite modulus
197
+
198
+ assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r))
199
+ assert convolution_ntt([2], [3], r) == [6]
200
+ assert convolution_ntt([2, 3], [4], r) == [8, 12]
201
+
202
+ assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619,
203
+ 459741727, 79180879, 831885249, 381344700, 369993322]
204
+ assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \
205
+ [8158, 3065, 3682, 7090, 1239, 2232, 3744]
206
+
207
+ assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \
208
+ convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q)
209
+ assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \
210
+ convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q)
211
+
212
+ raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r))
213
+ raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q))
214
+ raises(TypeError, lambda: convolution_ntt(x, y, p))
215
+
216
+
217
+ def test_convolution_fwht():
218
+ assert convolution_fwht([], []) == []
219
+ assert convolution_fwht([], [1]) == []
220
+ assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27]
221
+
222
+ assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \
223
+ [Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)]
224
+
225
+ a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I]
226
+ b = [94, 51, 53, 45, 31, 27, 13]
227
+ c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8]
228
+
229
+ assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I,
230
+ 45*sqrt(3) + Rational(5848, 15) + 135*I,
231
+ 94*sqrt(3) + Rational(1257, 5) + 65*I,
232
+ 51*sqrt(3) + Rational(3974, 15),
233
+ 13*sqrt(3) + 452 + 470*I,
234
+ Rational(4513, 15) + 255*I,
235
+ 31*sqrt(3) + Rational(1314, 5) + 265*I,
236
+ 27*sqrt(3) + Rational(3676, 15) + 225*I]
237
+
238
+ assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I,
239
+ Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I,
240
+ Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I]
241
+
242
+ assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*293/5, -1 + I*204/5,
243
+ Rational(133, 15) + I*35/6, Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0]
244
+
245
+ u, v, w, x, y, z = symbols('u v w x y z')
246
+
247
+ assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x]
248
+
249
+ assert convolution_fwht([u, v, w], [x, y]) == \
250
+ [u*x + v*y, u*y + v*x, w*x, w*y]
251
+
252
+ assert convolution_fwht([u, v, w], [x, y, z]) == \
253
+ [u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y]
254
+
255
+ raises(TypeError, lambda: convolution_fwht(x, y))
256
+ raises(TypeError, lambda: convolution_fwht(x*y, u + v))
257
+
258
+
259
+ def test_convolution_subset():
260
+ assert convolution_subset([], []) == []
261
+ assert convolution_subset([], [Rational(1, 3)]) == []
262
+ assert convolution_subset([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
263
+
264
+ a = [1, Rational(5, 3), sqrt(3), 4 + 5*I]
265
+ b = [64, 71, 55, 47, 33, 29, 15]
266
+ c = [3 + I*2/3, 5 + 7*I, 7, Rational(7, 5), 9]
267
+
268
+ assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3),
269
+ 71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84,
270
+ 15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I]
271
+
272
+ assert convolution_subset(b, c) == [192 + I*128/3, 533 + I*1486/3,
273
+ 613 + I*110/3, Rational(5013, 5) + I*1249/3,
274
+ 675 + 22*I, 891 + I*751/3,
275
+ 771 + 10*I, Rational(3736, 5) + 105*I]
276
+
277
+ assert convolution_subset(a, c) == convolution_subset(c, a)
278
+ assert convolution_subset(a[:2], b) == \
279
+ [64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25]
280
+
281
+ assert convolution_subset(a[:2], c) == \
282
+ [3 + I*2/3, 10 + I*73/9, 7, Rational(196, 15), 9, 15, 0, 0]
283
+
284
+ u, v, w, x, y, z = symbols('u v w x y z')
285
+
286
+ assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y]
287
+ assert convolution_subset([u, v, w, x], [y, z]) == \
288
+ [u*y, u*z + v*y, w*y, w*z + x*y]
289
+
290
+ assert convolution_subset([u, v], [x, y, z]) == \
291
+ convolution_subset([x, y, z], [u, v])
292
+
293
+ raises(TypeError, lambda: convolution_subset(x, z))
294
+ raises(TypeError, lambda: convolution_subset(Rational(7, 3), u))
295
+
296
+
297
+ def test_covering_product():
298
+ assert covering_product([], []) == []
299
+ assert covering_product([], [Rational(1, 3)]) == []
300
+ assert covering_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
301
+
302
+ a = [1, Rational(5, 8), sqrt(7), 4 + 9*I]
303
+ b = [66, 81, 95, 49, 37, 89, 17]
304
+ c = [3 + I*2/3, 51 + 72*I, 7, Rational(7, 15), 91]
305
+
306
+ assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7),
307
+ 130*sqrt(7) + 1303 + 2619*I, 37,
308
+ Rational(671, 4), 17 + 54*sqrt(7),
309
+ 89*sqrt(7) + Rational(4661, 8) + 1287*I]
310
+
311
+ assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I,
312
+ 1412 + I*190/3, Rational(42684, 5) + I*31202/3,
313
+ 9484 + I*74/3, 22163 + I*27394/3,
314
+ 10621 + I*34/3, Rational(90236, 15) + 1224*I]
315
+
316
+ assert covering_product(a, c) == covering_product(c, a)
317
+ assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I,
318
+ 1412 + I*190/3, Rational(42684, 5) + I*31202/3,
319
+ 111 + I*74/3, 6693 + I*27394/3,
320
+ 429 + I*34/3, Rational(23351, 15) + 1224*I]
321
+
322
+ assert covering_product(a, c[:-1]) == [3 + I*2/3,
323
+ Rational(339, 4) + I*1409/12, 7 + 10*sqrt(7) + 2*sqrt(7)*I/3,
324
+ -403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*12658/15]
325
+
326
+ u, v, w, x, y, z = symbols('u v w x y z')
327
+
328
+ assert covering_product([u, v, w], [x, y]) == \
329
+ [u*x, u*y + v*x + v*y, w*x, w*y]
330
+
331
+ assert covering_product([u, v, w, x], [y, z]) == \
332
+ [u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z]
333
+
334
+ assert covering_product([u, v], [x, y, z]) == \
335
+ covering_product([x, y, z], [u, v])
336
+
337
+ raises(TypeError, lambda: covering_product(x, z))
338
+ raises(TypeError, lambda: covering_product(Rational(7, 3), u))
339
+
340
+
341
+ def test_intersecting_product():
342
+ assert intersecting_product([], []) == []
343
+ assert intersecting_product([], [Rational(1, 3)]) == []
344
+ assert intersecting_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
345
+
346
+ a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I]
347
+ b = [67, 51, 65, 48, 36, 79, 27]
348
+ c = [3 + I*2/5, 5 + 9*I, 7, Rational(7, 19), 13]
349
+
350
+ assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I,
351
+ 178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I,
352
+ 192 + 336*I, 0, 0, 0, 0]
353
+
354
+ assert intersecting_product(b, c) == [Rational(128553, 19) + I*9521/5,
355
+ Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0]
356
+
357
+ assert intersecting_product(a, c) == intersecting_product(c, a)
358
+ assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*8622/5,
359
+ Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0]
360
+
361
+ assert intersecting_product(a, c[:-2]) == \
362
+ [Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*3021/40,
363
+ -43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0]
364
+
365
+ u, v, w, x, y, z = symbols('u v w x y z')
366
+
367
+ assert intersecting_product([u, v, w], [x, y]) == \
368
+ [u*x + u*y + v*x + w*x + w*y, v*y, 0, 0]
369
+
370
+ assert intersecting_product([u, v, w, x], [y, z]) == \
371
+ [u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0]
372
+
373
+ assert intersecting_product([u, v], [x, y, z]) == \
374
+ intersecting_product([x, y, z], [u, v])
375
+
376
+ raises(TypeError, lambda: intersecting_product(x, z))
377
+ raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
378
+
379
+
380
+ def test_convolution_int():
381
+ assert convolution_int([1], [1]) == [1]
382
+ assert convolution_int([1, 1], [0]) == [0]
383
+ assert convolution_int([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
384
+ assert convolution_int([1], [5, 6, 7]) == [5, 6, 7]
385
+ assert convolution_int([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
386
+ assert convolution_int([10, -5, 1, 3], [-5, 6, 7]) == [-50, 85, 35, -44, 25, 21]
387
+ assert convolution_int([0, 1, 0, -1], [1, 0, -1, 0]) == [0, 1, 0, -2, 0, 1]
388
+ assert convolution_int(
389
+ [-341, -5, 1, 3, -71, -99, 43, 87],
390
+ [5, 6, 7, 12, 345, 21, -78, -7, -89]
391
+ ) == [-1705, -2071, -2412, -4106, -118035, -9774, 25998, 2981, 5509,
392
+ -34317, 19228, 38870, 5485, 1724, -4436, -7743]
parrot/lib/python3.10/site-packages/sympy/discrete/tests/test_recurrences.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import Rational
2
+ from sympy.functions.combinatorial.numbers import fibonacci
3
+ from sympy.core import S, symbols
4
+ from sympy.testing.pytest import raises
5
+ from sympy.discrete.recurrences import linrec
6
+
7
+ def test_linrec():
8
+ assert linrec(coeffs=[1, 1], init=[1, 1], n=20) == 10946
9
+ assert linrec(coeffs=[1, 2, 3, 4, 5], init=[1, 1, 0, 2], n=10) == 1040
10
+ assert linrec(coeffs=[0, 0, 11, 13], init=[23, 27], n=25) == 59628567384
11
+ assert linrec(coeffs=[0, 0, 1, 1, 2], init=[1, 5, 3], n=15) == 165
12
+ assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=70) == \
13
+ 56889923441670659718376223533331214868804815612050381493741233489928913241
14
+ assert linrec(coeffs=[0]*55 + [1, 1, 2, 3], init=[0]*50 + [1, 2, 3], n=4000) == \
15
+ 702633573874937994980598979769135096432444135301118916539
16
+
17
+ assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**4)
18
+ assert linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4], n=10**5)
19
+
20
+ assert all(linrec(coeffs=[1, 1], init=[0, 1], n=n) == fibonacci(n)
21
+ for n in range(95, 115))
22
+
23
+ assert all(linrec(coeffs=[1, 1], init=[1, 1], n=n) == fibonacci(n + 1)
24
+ for n in range(595, 615))
25
+
26
+ a = [S.Half, Rational(3, 4), Rational(5, 6), 7, Rational(8, 9), Rational(3, 5)]
27
+ b = [1, 2, 8, Rational(5, 7), Rational(3, 7), Rational(2, 9), 6]
28
+ x, y, z = symbols('x y z')
29
+
30
+ assert linrec(coeffs=a[:5], init=b[:4], n=80) == \
31
+ Rational(1726244235456268979436592226626304376013002142588105090705187189,
32
+ 1960143456748895967474334873705475211264)
33
+
34
+ assert linrec(coeffs=a[:4], init=b[:4], n=50) == \
35
+ Rational(368949940033050147080268092104304441, 504857282956046106624)
36
+
37
+ assert linrec(coeffs=a[3:], init=b[:3], n=35) == \
38
+ Rational(97409272177295731943657945116791049305244422833125109,
39
+ 814315512679031689453125)
40
+
41
+ assert linrec(coeffs=[0]*60 + [Rational(2, 3), Rational(4, 5)], init=b, n=3000) == \
42
+ Rational(26777668739896791448594650497024, 48084516708184142230517578125)
43
+
44
+ raises(TypeError, lambda: linrec(coeffs=[11, 13, 15, 17], init=[1, 2, 3, 4, 5], n=1))
45
+ raises(TypeError, lambda: linrec(coeffs=a[:4], init=b[:5], n=10000))
46
+ raises(ValueError, lambda: linrec(coeffs=a[:4], init=b[:4], n=-10000))
47
+ raises(TypeError, lambda: linrec(x, b, n=10000))
48
+ raises(TypeError, lambda: linrec(a, y, n=10000))
49
+
50
+ assert linrec(coeffs=[x, y, z], init=[1, 1, 1], n=4) == \
51
+ x**2 + x*y + x*z + y + z
52
+ assert linrec(coeffs=[1, 2, 1], init=[x, y, z], n=20) == \
53
+ 269542*x + 664575*y + 578949*z
54
+ assert linrec(coeffs=[0, 3, 1, 2], init=[x, y], n=30) == \
55
+ 58516436*x + 56372788*y
56
+ assert linrec(coeffs=[0]*50 + [1, 2, 3], init=[x, y, z], n=1000) == \
57
+ 11477135884896*x + 25999077948732*y + 41975630244216*z
58
+ assert linrec(coeffs=[], init=[1, 1], n=20) == 0
59
+ assert linrec(coeffs=[x, y, z], init=[1, 2, 3], n=2) == 3
parrot/lib/python3.10/site-packages/sympy/discrete/tests/test_transforms.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.functions.elementary.miscellaneous import sqrt
2
+ from sympy.core import S, Symbol, symbols, I, Rational
3
+ from sympy.discrete import (fft, ifft, ntt, intt, fwht, ifwht,
4
+ mobius_transform, inverse_mobius_transform)
5
+ from sympy.testing.pytest import raises
6
+
7
+
8
+ def test_fft_ifft():
9
+ assert all(tf(ls) == ls for tf in (fft, ifft)
10
+ for ls in ([], [Rational(5, 3)]))
11
+
12
+ ls = list(range(6))
13
+ fls = [15, -7*sqrt(2)/2 - 4 - sqrt(2)*I/2 + 2*I, 2 + 3*I,
14
+ -4 + 7*sqrt(2)/2 - 2*I - sqrt(2)*I/2, -3,
15
+ -4 + 7*sqrt(2)/2 + sqrt(2)*I/2 + 2*I,
16
+ 2 - 3*I, -7*sqrt(2)/2 - 4 - 2*I + sqrt(2)*I/2]
17
+
18
+ assert fft(ls) == fls
19
+ assert ifft(fls) == ls + [S.Zero]*2
20
+
21
+ ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
22
+ ifls = [Rational(9, 4) + 3*I, I*Rational(-7, 4), Rational(3, 4) + I, -2 - I/4]
23
+
24
+ assert ifft(ls) == ifls
25
+ assert fft(ifls) == ls + [S.Zero]
26
+
27
+ x = Symbol('x', real=True)
28
+ raises(TypeError, lambda: fft(x))
29
+ raises(ValueError, lambda: ifft([x, 2*x, 3*x**2, 4*x**3]))
30
+
31
+
32
+ def test_ntt_intt():
33
+ # prime moduli of the form (m*2**k + 1), sequence length
34
+ # should be a divisor of 2**k
35
+ p = 7*17*2**23 + 1
36
+ q = 2*500000003 + 1 # only for sequences of length 1 or 2
37
+ r = 2*3*5*7 # composite modulus
38
+
39
+ assert all(tf(ls, p) == ls for tf in (ntt, intt)
40
+ for ls in ([], [5]))
41
+
42
+ ls = list(range(6))
43
+ nls = [15, 801133602, 738493201, 334102277, 998244350, 849020224,
44
+ 259751156, 12232587]
45
+
46
+ assert ntt(ls, p) == nls
47
+ assert intt(nls, p) == ls + [0]*2
48
+
49
+ ls = [1 + 2*I, 3 + 4*I, 5 + 6*I]
50
+ x = Symbol('x', integer=True)
51
+
52
+ raises(TypeError, lambda: ntt(x, p))
53
+ raises(ValueError, lambda: intt([x, 2*x, 3*x**2, 4*x**3], p))
54
+ raises(ValueError, lambda: intt(ls, p))
55
+ raises(ValueError, lambda: ntt([1.2, 2.1, 3.5], p))
56
+ raises(ValueError, lambda: ntt([3, 5, 6], q))
57
+ raises(ValueError, lambda: ntt([4, 5, 7], r))
58
+ raises(ValueError, lambda: ntt([1.0, 2.0, 3.0], p))
59
+
60
+
61
+ def test_fwht_ifwht():
62
+ assert all(tf(ls) == ls for tf in (fwht, ifwht) \
63
+ for ls in ([], [Rational(7, 4)]))
64
+
65
+ ls = [213, 321, 43235, 5325, 312, 53]
66
+ fls = [49459, 38061, -47661, -37759, 48729, 37543, -48391, -38277]
67
+
68
+ assert fwht(ls) == fls
69
+ assert ifwht(fls) == ls + [S.Zero]*2
70
+
71
+ ls = [S.Half + 2*I, Rational(3, 7) + 4*I, Rational(5, 6) + 6*I, Rational(7, 3), Rational(9, 4)]
72
+ ifls = [Rational(533, 672) + I*3/2, Rational(23, 224) + I/2, Rational(1, 672), Rational(107, 224) - I,
73
+ Rational(155, 672) + I*3/2, Rational(-103, 224) + I/2, Rational(-377, 672), Rational(-19, 224) - I]
74
+
75
+ assert ifwht(ls) == ifls
76
+ assert fwht(ifls) == ls + [S.Zero]*3
77
+
78
+ x, y = symbols('x y')
79
+
80
+ raises(TypeError, lambda: fwht(x))
81
+
82
+ ls = [x, 2*x, 3*x**2, 4*x**3]
83
+ ifls = [x**3 + 3*x**2/4 + x*Rational(3, 4),
84
+ -x**3 + 3*x**2/4 - x/4,
85
+ -x**3 - 3*x**2/4 + x*Rational(3, 4),
86
+ x**3 - 3*x**2/4 - x/4]
87
+
88
+ assert ifwht(ls) == ifls
89
+ assert fwht(ifls) == ls
90
+
91
+ ls = [x, y, x**2, y**2, x*y]
92
+ fls = [x**2 + x*y + x + y**2 + y,
93
+ x**2 + x*y + x - y**2 - y,
94
+ -x**2 + x*y + x - y**2 + y,
95
+ -x**2 + x*y + x + y**2 - y,
96
+ x**2 - x*y + x + y**2 + y,
97
+ x**2 - x*y + x - y**2 - y,
98
+ -x**2 - x*y + x - y**2 + y,
99
+ -x**2 - x*y + x + y**2 - y]
100
+
101
+ assert fwht(ls) == fls
102
+ assert ifwht(fls) == ls + [S.Zero]*3
103
+
104
+ ls = list(range(6))
105
+
106
+ assert fwht(ls) == [x*8 for x in ifwht(ls)]
107
+
108
+
109
+ def test_mobius_transform():
110
+ assert all(tf(ls, subset=subset) == ls
111
+ for ls in ([], [Rational(7, 4)]) for subset in (True, False)
112
+ for tf in (mobius_transform, inverse_mobius_transform))
113
+
114
+ w, x, y, z = symbols('w x y z')
115
+
116
+ assert mobius_transform([x, y]) == [x, x + y]
117
+ assert inverse_mobius_transform([x, x + y]) == [x, y]
118
+ assert mobius_transform([x, y], subset=False) == [x + y, y]
119
+ assert inverse_mobius_transform([x + y, y], subset=False) == [x, y]
120
+
121
+ assert mobius_transform([w, x, y, z]) == [w, w + x, w + y, w + x + y + z]
122
+ assert inverse_mobius_transform([w, w + x, w + y, w + x + y + z]) == \
123
+ [w, x, y, z]
124
+ assert mobius_transform([w, x, y, z], subset=False) == \
125
+ [w + x + y + z, x + z, y + z, z]
126
+ assert inverse_mobius_transform([w + x + y + z, x + z, y + z, z], subset=False) == \
127
+ [w, x, y, z]
128
+
129
+ ls = [Rational(2, 3), Rational(6, 7), Rational(5, 8), 9, Rational(5, 3) + 7*I]
130
+ mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168),
131
+ Rational(7, 3) + 7*I, Rational(67, 21) + 7*I, Rational(71, 24) + 7*I,
132
+ Rational(2153, 168) + 7*I]
133
+
134
+ assert mobius_transform(ls) == mls
135
+ assert inverse_mobius_transform(mls) == ls + [S.Zero]*3
136
+
137
+ mls = [Rational(2153, 168) + 7*I, Rational(69, 7), Rational(77, 8), 9, Rational(5, 3) + 7*I, 0, 0, 0]
138
+
139
+ assert mobius_transform(ls, subset=False) == mls
140
+ assert inverse_mobius_transform(mls, subset=False) == ls + [S.Zero]*3
141
+
142
+ ls = ls[:-1]
143
+ mls = [Rational(2, 3), Rational(32, 21), Rational(31, 24), Rational(1873, 168)]
144
+
145
+ assert mobius_transform(ls) == mls
146
+ assert inverse_mobius_transform(mls) == ls
147
+
148
+ mls = [Rational(1873, 168), Rational(69, 7), Rational(77, 8), 9]
149
+
150
+ assert mobius_transform(ls, subset=False) == mls
151
+ assert inverse_mobius_transform(mls, subset=False) == ls
152
+
153
+ raises(TypeError, lambda: mobius_transform(x, subset=True))
154
+ raises(TypeError, lambda: inverse_mobius_transform(y, subset=False))
parrot/lib/python3.10/site-packages/sympy/discrete/transforms.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Discrete Fourier Transform, Number Theoretic Transform,
3
+ Walsh Hadamard Transform, Mobius Transform
4
+ """
5
+
6
+ from sympy.core import S, Symbol, sympify
7
+ from sympy.core.function import expand_mul
8
+ from sympy.core.numbers import pi, I
9
+ from sympy.functions.elementary.trigonometric import sin, cos
10
+ from sympy.ntheory import isprime, primitive_root
11
+ from sympy.utilities.iterables import ibin, iterable
12
+ from sympy.utilities.misc import as_int
13
+
14
+
15
+ #----------------------------------------------------------------------------#
16
+ # #
17
+ # Discrete Fourier Transform #
18
+ # #
19
+ #----------------------------------------------------------------------------#
20
+
21
+ def _fourier_transform(seq, dps, inverse=False):
22
+ """Utility function for the Discrete Fourier Transform"""
23
+
24
+ if not iterable(seq):
25
+ raise TypeError("Expected a sequence of numeric coefficients "
26
+ "for Fourier Transform")
27
+
28
+ a = [sympify(arg) for arg in seq]
29
+ if any(x.has(Symbol) for x in a):
30
+ raise ValueError("Expected non-symbolic coefficients")
31
+
32
+ n = len(a)
33
+ if n < 2:
34
+ return a
35
+
36
+ b = n.bit_length() - 1
37
+ if n&(n - 1): # not a power of 2
38
+ b += 1
39
+ n = 2**b
40
+
41
+ a += [S.Zero]*(n - len(a))
42
+ for i in range(1, n):
43
+ j = int(ibin(i, b, str=True)[::-1], 2)
44
+ if i < j:
45
+ a[i], a[j] = a[j], a[i]
46
+
47
+ ang = -2*pi/n if inverse else 2*pi/n
48
+
49
+ if dps is not None:
50
+ ang = ang.evalf(dps + 2)
51
+
52
+ w = [cos(ang*i) + I*sin(ang*i) for i in range(n // 2)]
53
+
54
+ h = 2
55
+ while h <= n:
56
+ hf, ut = h // 2, n // h
57
+ for i in range(0, n, h):
58
+ for j in range(hf):
59
+ u, v = a[i + j], expand_mul(a[i + j + hf]*w[ut * j])
60
+ a[i + j], a[i + j + hf] = u + v, u - v
61
+ h *= 2
62
+
63
+ if inverse:
64
+ a = [(x/n).evalf(dps) for x in a] if dps is not None \
65
+ else [x/n for x in a]
66
+
67
+ return a
68
+
69
+
70
+ def fft(seq, dps=None):
71
+ r"""
72
+ Performs the Discrete Fourier Transform (**DFT**) in the complex domain.
73
+
74
+ The sequence is automatically padded to the right with zeros, as the
75
+ *radix-2 FFT* requires the number of sample points to be a power of 2.
76
+
77
+ This method should be used with default arguments only for short sequences
78
+ as the complexity of expressions increases with the size of the sequence.
79
+
80
+ Parameters
81
+ ==========
82
+
83
+ seq : iterable
84
+ The sequence on which **DFT** is to be applied.
85
+ dps : Integer
86
+ Specifies the number of decimal digits for precision.
87
+
88
+ Examples
89
+ ========
90
+
91
+ >>> from sympy import fft, ifft
92
+
93
+ >>> fft([1, 2, 3, 4])
94
+ [10, -2 - 2*I, -2, -2 + 2*I]
95
+ >>> ifft(_)
96
+ [1, 2, 3, 4]
97
+
98
+ >>> ifft([1, 2, 3, 4])
99
+ [5/2, -1/2 + I/2, -1/2, -1/2 - I/2]
100
+ >>> fft(_)
101
+ [1, 2, 3, 4]
102
+
103
+ >>> ifft([1, 7, 3, 4], dps=15)
104
+ [3.75, -0.5 - 0.75*I, -1.75, -0.5 + 0.75*I]
105
+ >>> fft(_)
106
+ [1.0, 7.0, 3.0, 4.0]
107
+
108
+ References
109
+ ==========
110
+
111
+ .. [1] https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm
112
+ .. [2] https://mathworld.wolfram.com/FastFourierTransform.html
113
+
114
+ """
115
+
116
+ return _fourier_transform(seq, dps=dps)
117
+
118
+
119
+ def ifft(seq, dps=None):
120
+ return _fourier_transform(seq, dps=dps, inverse=True)
121
+
122
+ ifft.__doc__ = fft.__doc__
123
+
124
+
125
+ #----------------------------------------------------------------------------#
126
+ # #
127
+ # Number Theoretic Transform #
128
+ # #
129
+ #----------------------------------------------------------------------------#
130
+
131
+ def _number_theoretic_transform(seq, prime, inverse=False):
132
+ """Utility function for the Number Theoretic Transform"""
133
+
134
+ if not iterable(seq):
135
+ raise TypeError("Expected a sequence of integer coefficients "
136
+ "for Number Theoretic Transform")
137
+
138
+ p = as_int(prime)
139
+ if not isprime(p):
140
+ raise ValueError("Expected prime modulus for "
141
+ "Number Theoretic Transform")
142
+
143
+ a = [as_int(x) % p for x in seq]
144
+
145
+ n = len(a)
146
+ if n < 1:
147
+ return a
148
+
149
+ b = n.bit_length() - 1
150
+ if n&(n - 1):
151
+ b += 1
152
+ n = 2**b
153
+
154
+ if (p - 1) % n:
155
+ raise ValueError("Expected prime modulus of the form (m*2**k + 1)")
156
+
157
+ a += [0]*(n - len(a))
158
+ for i in range(1, n):
159
+ j = int(ibin(i, b, str=True)[::-1], 2)
160
+ if i < j:
161
+ a[i], a[j] = a[j], a[i]
162
+
163
+ pr = primitive_root(p)
164
+
165
+ rt = pow(pr, (p - 1) // n, p)
166
+ if inverse:
167
+ rt = pow(rt, p - 2, p)
168
+
169
+ w = [1]*(n // 2)
170
+ for i in range(1, n // 2):
171
+ w[i] = w[i - 1]*rt % p
172
+
173
+ h = 2
174
+ while h <= n:
175
+ hf, ut = h // 2, n // h
176
+ for i in range(0, n, h):
177
+ for j in range(hf):
178
+ u, v = a[i + j], a[i + j + hf]*w[ut * j]
179
+ a[i + j], a[i + j + hf] = (u + v) % p, (u - v) % p
180
+ h *= 2
181
+
182
+ if inverse:
183
+ rv = pow(n, p - 2, p)
184
+ a = [x*rv % p for x in a]
185
+
186
+ return a
187
+
188
+
189
+ def ntt(seq, prime):
190
+ r"""
191
+ Performs the Number Theoretic Transform (**NTT**), which specializes the
192
+ Discrete Fourier Transform (**DFT**) over quotient ring `Z/pZ` for prime
193
+ `p` instead of complex numbers `C`.
194
+
195
+ The sequence is automatically padded to the right with zeros, as the
196
+ *radix-2 NTT* requires the number of sample points to be a power of 2.
197
+
198
+ Parameters
199
+ ==========
200
+
201
+ seq : iterable
202
+ The sequence on which **DFT** is to be applied.
203
+ prime : Integer
204
+ Prime modulus of the form `(m 2^k + 1)` to be used for performing
205
+ **NTT** on the sequence.
206
+
207
+ Examples
208
+ ========
209
+
210
+ >>> from sympy import ntt, intt
211
+ >>> ntt([1, 2, 3, 4], prime=3*2**8 + 1)
212
+ [10, 643, 767, 122]
213
+ >>> intt(_, 3*2**8 + 1)
214
+ [1, 2, 3, 4]
215
+ >>> intt([1, 2, 3, 4], prime=3*2**8 + 1)
216
+ [387, 415, 384, 353]
217
+ >>> ntt(_, prime=3*2**8 + 1)
218
+ [1, 2, 3, 4]
219
+
220
+ References
221
+ ==========
222
+
223
+ .. [1] http://www.apfloat.org/ntt.html
224
+ .. [2] https://mathworld.wolfram.com/NumberTheoreticTransform.html
225
+ .. [3] https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general%29
226
+
227
+ """
228
+
229
+ return _number_theoretic_transform(seq, prime=prime)
230
+
231
+
232
+ def intt(seq, prime):
233
+ return _number_theoretic_transform(seq, prime=prime, inverse=True)
234
+
235
+ intt.__doc__ = ntt.__doc__
236
+
237
+
238
+ #----------------------------------------------------------------------------#
239
+ # #
240
+ # Walsh Hadamard Transform #
241
+ # #
242
+ #----------------------------------------------------------------------------#
243
+
244
+ def _walsh_hadamard_transform(seq, inverse=False):
245
+ """Utility function for the Walsh Hadamard Transform"""
246
+
247
+ if not iterable(seq):
248
+ raise TypeError("Expected a sequence of coefficients "
249
+ "for Walsh Hadamard Transform")
250
+
251
+ a = [sympify(arg) for arg in seq]
252
+ n = len(a)
253
+ if n < 2:
254
+ return a
255
+
256
+ if n&(n - 1):
257
+ n = 2**n.bit_length()
258
+
259
+ a += [S.Zero]*(n - len(a))
260
+ h = 2
261
+ while h <= n:
262
+ hf = h // 2
263
+ for i in range(0, n, h):
264
+ for j in range(hf):
265
+ u, v = a[i + j], a[i + j + hf]
266
+ a[i + j], a[i + j + hf] = u + v, u - v
267
+ h *= 2
268
+
269
+ if inverse:
270
+ a = [x/n for x in a]
271
+
272
+ return a
273
+
274
+
275
+ def fwht(seq):
276
+ r"""
277
+ Performs the Walsh Hadamard Transform (**WHT**), and uses Hadamard
278
+ ordering for the sequence.
279
+
280
+ The sequence is automatically padded to the right with zeros, as the
281
+ *radix-2 FWHT* requires the number of sample points to be a power of 2.
282
+
283
+ Parameters
284
+ ==========
285
+
286
+ seq : iterable
287
+ The sequence on which WHT is to be applied.
288
+
289
+ Examples
290
+ ========
291
+
292
+ >>> from sympy import fwht, ifwht
293
+ >>> fwht([4, 2, 2, 0, 0, 2, -2, 0])
294
+ [8, 0, 8, 0, 8, 8, 0, 0]
295
+ >>> ifwht(_)
296
+ [4, 2, 2, 0, 0, 2, -2, 0]
297
+
298
+ >>> ifwht([19, -1, 11, -9, -7, 13, -15, 5])
299
+ [2, 0, 4, 0, 3, 10, 0, 0]
300
+ >>> fwht(_)
301
+ [19, -1, 11, -9, -7, 13, -15, 5]
302
+
303
+ References
304
+ ==========
305
+
306
+ .. [1] https://en.wikipedia.org/wiki/Hadamard_transform
307
+ .. [2] https://en.wikipedia.org/wiki/Fast_Walsh%E2%80%93Hadamard_transform
308
+
309
+ """
310
+
311
+ return _walsh_hadamard_transform(seq)
312
+
313
+
314
+ def ifwht(seq):
315
+ return _walsh_hadamard_transform(seq, inverse=True)
316
+
317
+ ifwht.__doc__ = fwht.__doc__
318
+
319
+
320
+ #----------------------------------------------------------------------------#
321
+ # #
322
+ # Mobius Transform for Subset Lattice #
323
+ # #
324
+ #----------------------------------------------------------------------------#
325
+
326
+ def _mobius_transform(seq, sgn, subset):
327
+ r"""Utility function for performing Mobius Transform using
328
+ Yate's Dynamic Programming method"""
329
+
330
+ if not iterable(seq):
331
+ raise TypeError("Expected a sequence of coefficients")
332
+
333
+ a = [sympify(arg) for arg in seq]
334
+
335
+ n = len(a)
336
+ if n < 2:
337
+ return a
338
+
339
+ if n&(n - 1):
340
+ n = 2**n.bit_length()
341
+
342
+ a += [S.Zero]*(n - len(a))
343
+
344
+ if subset:
345
+ i = 1
346
+ while i < n:
347
+ for j in range(n):
348
+ if j & i:
349
+ a[j] += sgn*a[j ^ i]
350
+ i *= 2
351
+
352
+ else:
353
+ i = 1
354
+ while i < n:
355
+ for j in range(n):
356
+ if j & i:
357
+ continue
358
+ a[j] += sgn*a[j ^ i]
359
+ i *= 2
360
+
361
+ return a
362
+
363
+
364
+ def mobius_transform(seq, subset=True):
365
+ r"""
366
+ Performs the Mobius Transform for subset lattice with indices of
367
+ sequence as bitmasks.
368
+
369
+ The indices of each argument, considered as bit strings, correspond
370
+ to subsets of a finite set.
371
+
372
+ The sequence is automatically padded to the right with zeros, as the
373
+ definition of subset/superset based on bitmasks (indices) requires
374
+ the size of sequence to be a power of 2.
375
+
376
+ Parameters
377
+ ==========
378
+
379
+ seq : iterable
380
+ The sequence on which Mobius Transform is to be applied.
381
+ subset : bool
382
+ Specifies if Mobius Transform is applied by enumerating subsets
383
+ or supersets of the given set.
384
+
385
+ Examples
386
+ ========
387
+
388
+ >>> from sympy import symbols
389
+ >>> from sympy import mobius_transform, inverse_mobius_transform
390
+ >>> x, y, z = symbols('x y z')
391
+
392
+ >>> mobius_transform([x, y, z])
393
+ [x, x + y, x + z, x + y + z]
394
+ >>> inverse_mobius_transform(_)
395
+ [x, y, z, 0]
396
+
397
+ >>> mobius_transform([x, y, z], subset=False)
398
+ [x + y + z, y, z, 0]
399
+ >>> inverse_mobius_transform(_, subset=False)
400
+ [x, y, z, 0]
401
+
402
+ >>> mobius_transform([1, 2, 3, 4])
403
+ [1, 3, 4, 10]
404
+ >>> inverse_mobius_transform(_)
405
+ [1, 2, 3, 4]
406
+ >>> mobius_transform([1, 2, 3, 4], subset=False)
407
+ [10, 6, 7, 4]
408
+ >>> inverse_mobius_transform(_, subset=False)
409
+ [1, 2, 3, 4]
410
+
411
+ References
412
+ ==========
413
+
414
+ .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_inversion_formula
415
+ .. [2] https://people.csail.mit.edu/rrw/presentations/subset-conv.pdf
416
+ .. [3] https://arxiv.org/pdf/1211.0189.pdf
417
+
418
+ """
419
+
420
+ return _mobius_transform(seq, sgn=+1, subset=subset)
421
+
422
+ def inverse_mobius_transform(seq, subset=True):
423
+ return _mobius_transform(seq, sgn=-1, subset=subset)
424
+
425
+ inverse_mobius_transform.__doc__ = mobius_transform.__doc__
parrot/lib/python3.10/site-packages/sympy/multipledispatch/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .core import dispatch
2
+ from .dispatcher import (Dispatcher, halt_ordering, restart_ordering,
3
+ MDNotImplementedError)
4
+
5
+ __version__ = '0.4.9'
6
+
7
+ __all__ = [
8
+ 'dispatch',
9
+
10
+ 'Dispatcher', 'halt_ordering', 'restart_ordering', 'MDNotImplementedError',
11
+ ]
parrot/lib/python3.10/site-packages/sympy/multipledispatch/conflict.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .utils import _toposort, groupby
2
+
3
+ class AmbiguityWarning(Warning):
4
+ pass
5
+
6
+
7
+ def supercedes(a, b):
8
+ """ A is consistent and strictly more specific than B """
9
+ return len(a) == len(b) and all(map(issubclass, a, b))
10
+
11
+
12
+ def consistent(a, b):
13
+ """ It is possible for an argument list to satisfy both A and B """
14
+ return (len(a) == len(b) and
15
+ all(issubclass(aa, bb) or issubclass(bb, aa)
16
+ for aa, bb in zip(a, b)))
17
+
18
+
19
+ def ambiguous(a, b):
20
+ """ A is consistent with B but neither is strictly more specific """
21
+ return consistent(a, b) and not (supercedes(a, b) or supercedes(b, a))
22
+
23
+
24
+ def ambiguities(signatures):
25
+ """ All signature pairs such that A is ambiguous with B """
26
+ signatures = list(map(tuple, signatures))
27
+ return {(a, b) for a in signatures for b in signatures
28
+ if hash(a) < hash(b)
29
+ and ambiguous(a, b)
30
+ and not any(supercedes(c, a) and supercedes(c, b)
31
+ for c in signatures)}
32
+
33
+
34
+ def super_signature(signatures):
35
+ """ A signature that would break ambiguities """
36
+ n = len(signatures[0])
37
+ assert all(len(s) == n for s in signatures)
38
+
39
+ return [max([type.mro(sig[i]) for sig in signatures], key=len)[0]
40
+ for i in range(n)]
41
+
42
+
43
+ def edge(a, b, tie_breaker=hash):
44
+ """ A should be checked before B
45
+
46
+ Tie broken by tie_breaker, defaults to ``hash``
47
+ """
48
+ if supercedes(a, b):
49
+ if supercedes(b, a):
50
+ return tie_breaker(a) > tie_breaker(b)
51
+ else:
52
+ return True
53
+ return False
54
+
55
+
56
+ def ordering(signatures):
57
+ """ A sane ordering of signatures to check, first to last
58
+
59
+ Topoological sort of edges as given by ``edge`` and ``supercedes``
60
+ """
61
+ signatures = list(map(tuple, signatures))
62
+ edges = [(a, b) for a in signatures for b in signatures if edge(a, b)]
63
+ edges = groupby(lambda x: x[0], edges)
64
+ for s in signatures:
65
+ if s not in edges:
66
+ edges[s] = []
67
+ edges = {k: [b for a, b in v] for k, v in edges.items()}
68
+ return _toposort(edges)
parrot/lib/python3.10/site-packages/sympy/multipledispatch/core.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Any
3
+
4
+ import inspect
5
+
6
+ from .dispatcher import Dispatcher, MethodDispatcher, ambiguity_warn
7
+
8
+ # XXX: This parameter to dispatch isn't documented and isn't used anywhere in
9
+ # sympy. Maybe it should just be removed.
10
+ global_namespace: dict[str, Any] = {}
11
+
12
+
13
+ def dispatch(*types, namespace=global_namespace, on_ambiguity=ambiguity_warn):
14
+ """ Dispatch function on the types of the inputs
15
+
16
+ Supports dispatch on all non-keyword arguments.
17
+
18
+ Collects implementations based on the function name. Ignores namespaces.
19
+
20
+ If ambiguous type signatures occur a warning is raised when the function is
21
+ defined suggesting the additional method to break the ambiguity.
22
+
23
+ Examples
24
+ --------
25
+
26
+ >>> from sympy.multipledispatch import dispatch
27
+ >>> @dispatch(int)
28
+ ... def f(x):
29
+ ... return x + 1
30
+
31
+ >>> @dispatch(float)
32
+ ... def f(x): # noqa: F811
33
+ ... return x - 1
34
+
35
+ >>> f(3)
36
+ 4
37
+ >>> f(3.0)
38
+ 2.0
39
+
40
+ Specify an isolated namespace with the namespace keyword argument
41
+
42
+ >>> my_namespace = dict()
43
+ >>> @dispatch(int, namespace=my_namespace)
44
+ ... def foo(x):
45
+ ... return x + 1
46
+
47
+ Dispatch on instance methods within classes
48
+
49
+ >>> class MyClass(object):
50
+ ... @dispatch(list)
51
+ ... def __init__(self, data):
52
+ ... self.data = data
53
+ ... @dispatch(int)
54
+ ... def __init__(self, datum): # noqa: F811
55
+ ... self.data = [datum]
56
+ """
57
+ types = tuple(types)
58
+
59
+ def _(func):
60
+ name = func.__name__
61
+
62
+ if ismethod(func):
63
+ dispatcher = inspect.currentframe().f_back.f_locals.get(
64
+ name,
65
+ MethodDispatcher(name))
66
+ else:
67
+ if name not in namespace:
68
+ namespace[name] = Dispatcher(name)
69
+ dispatcher = namespace[name]
70
+
71
+ dispatcher.add(types, func, on_ambiguity=on_ambiguity)
72
+ return dispatcher
73
+ return _
74
+
75
+
76
+ def ismethod(func):
77
+ """ Is func a method?
78
+
79
+ Note that this has to work as the method is defined but before the class is
80
+ defined. At this stage methods look like functions.
81
+ """
82
+ signature = inspect.signature(func)
83
+ return signature.parameters.get('self', None) is not None
parrot/lib/python3.10/site-packages/sympy/multipledispatch/dispatcher.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from warnings import warn
4
+ import inspect
5
+ from .conflict import ordering, ambiguities, super_signature, AmbiguityWarning
6
+ from .utils import expand_tuples
7
+ import itertools as itl
8
+
9
+
10
+ class MDNotImplementedError(NotImplementedError):
11
+ """ A NotImplementedError for multiple dispatch """
12
+
13
+
14
+ ### Functions for on_ambiguity
15
+
16
+ def ambiguity_warn(dispatcher, ambiguities):
17
+ """ Raise warning when ambiguity is detected
18
+
19
+ Parameters
20
+ ----------
21
+ dispatcher : Dispatcher
22
+ The dispatcher on which the ambiguity was detected
23
+ ambiguities : set
24
+ Set of type signature pairs that are ambiguous within this dispatcher
25
+
26
+ See Also:
27
+ Dispatcher.add
28
+ warning_text
29
+ """
30
+ warn(warning_text(dispatcher.name, ambiguities), AmbiguityWarning)
31
+
32
+
33
+ class RaiseNotImplementedError:
34
+ """Raise ``NotImplementedError`` when called."""
35
+
36
+ def __init__(self, dispatcher):
37
+ self.dispatcher = dispatcher
38
+
39
+ def __call__(self, *args, **kwargs):
40
+ types = tuple(type(a) for a in args)
41
+ raise NotImplementedError(
42
+ "Ambiguous signature for %s: <%s>" % (
43
+ self.dispatcher.name, str_signature(types)
44
+ ))
45
+
46
+ def ambiguity_register_error_ignore_dup(dispatcher, ambiguities):
47
+ """
48
+ If super signature for ambiguous types is duplicate types, ignore it.
49
+ Else, register instance of ``RaiseNotImplementedError`` for ambiguous types.
50
+
51
+ Parameters
52
+ ----------
53
+ dispatcher : Dispatcher
54
+ The dispatcher on which the ambiguity was detected
55
+ ambiguities : set
56
+ Set of type signature pairs that are ambiguous within this dispatcher
57
+
58
+ See Also:
59
+ Dispatcher.add
60
+ ambiguity_warn
61
+ """
62
+ for amb in ambiguities:
63
+ signature = tuple(super_signature(amb))
64
+ if len(set(signature)) == 1:
65
+ continue
66
+ dispatcher.add(
67
+ signature, RaiseNotImplementedError(dispatcher),
68
+ on_ambiguity=ambiguity_register_error_ignore_dup
69
+ )
70
+
71
+ ###
72
+
73
+
74
+ _unresolved_dispatchers: set[Dispatcher] = set()
75
+ _resolve = [True]
76
+
77
+
78
+ def halt_ordering():
79
+ _resolve[0] = False
80
+
81
+
82
+ def restart_ordering(on_ambiguity=ambiguity_warn):
83
+ _resolve[0] = True
84
+ while _unresolved_dispatchers:
85
+ dispatcher = _unresolved_dispatchers.pop()
86
+ dispatcher.reorder(on_ambiguity=on_ambiguity)
87
+
88
+
89
+ class Dispatcher:
90
+ """ Dispatch methods based on type signature
91
+
92
+ Use ``dispatch`` to add implementations
93
+
94
+ Examples
95
+ --------
96
+
97
+ >>> from sympy.multipledispatch import dispatch
98
+ >>> @dispatch(int)
99
+ ... def f(x):
100
+ ... return x + 1
101
+
102
+ >>> @dispatch(float)
103
+ ... def f(x): # noqa: F811
104
+ ... return x - 1
105
+
106
+ >>> f(3)
107
+ 4
108
+ >>> f(3.0)
109
+ 2.0
110
+ """
111
+ __slots__ = '__name__', 'name', 'funcs', 'ordering', '_cache', 'doc'
112
+
113
+ def __init__(self, name, doc=None):
114
+ self.name = self.__name__ = name
115
+ self.funcs = {}
116
+ self._cache = {}
117
+ self.ordering = []
118
+ self.doc = doc
119
+
120
+ def register(self, *types, **kwargs):
121
+ """ Register dispatcher with new implementation
122
+
123
+ >>> from sympy.multipledispatch.dispatcher import Dispatcher
124
+ >>> f = Dispatcher('f')
125
+ >>> @f.register(int)
126
+ ... def inc(x):
127
+ ... return x + 1
128
+
129
+ >>> @f.register(float)
130
+ ... def dec(x):
131
+ ... return x - 1
132
+
133
+ >>> @f.register(list)
134
+ ... @f.register(tuple)
135
+ ... def reverse(x):
136
+ ... return x[::-1]
137
+
138
+ >>> f(1)
139
+ 2
140
+
141
+ >>> f(1.0)
142
+ 0.0
143
+
144
+ >>> f([1, 2, 3])
145
+ [3, 2, 1]
146
+ """
147
+ def _(func):
148
+ self.add(types, func, **kwargs)
149
+ return func
150
+ return _
151
+
152
+ @classmethod
153
+ def get_func_params(cls, func):
154
+ if hasattr(inspect, "signature"):
155
+ sig = inspect.signature(func)
156
+ return sig.parameters.values()
157
+
158
+ @classmethod
159
+ def get_func_annotations(cls, func):
160
+ """ Get annotations of function positional parameters
161
+ """
162
+ params = cls.get_func_params(func)
163
+ if params:
164
+ Parameter = inspect.Parameter
165
+
166
+ params = (param for param in params
167
+ if param.kind in
168
+ (Parameter.POSITIONAL_ONLY,
169
+ Parameter.POSITIONAL_OR_KEYWORD))
170
+
171
+ annotations = tuple(
172
+ param.annotation
173
+ for param in params)
174
+
175
+ if not any(ann is Parameter.empty for ann in annotations):
176
+ return annotations
177
+
178
+ def add(self, signature, func, on_ambiguity=ambiguity_warn):
179
+ """ Add new types/method pair to dispatcher
180
+
181
+ >>> from sympy.multipledispatch import Dispatcher
182
+ >>> D = Dispatcher('add')
183
+ >>> D.add((int, int), lambda x, y: x + y)
184
+ >>> D.add((float, float), lambda x, y: x + y)
185
+
186
+ >>> D(1, 2)
187
+ 3
188
+ >>> D(1, 2.0)
189
+ Traceback (most recent call last):
190
+ ...
191
+ NotImplementedError: Could not find signature for add: <int, float>
192
+
193
+ When ``add`` detects a warning it calls the ``on_ambiguity`` callback
194
+ with a dispatcher/itself, and a set of ambiguous type signature pairs
195
+ as inputs. See ``ambiguity_warn`` for an example.
196
+ """
197
+ # Handle annotations
198
+ if not signature:
199
+ annotations = self.get_func_annotations(func)
200
+ if annotations:
201
+ signature = annotations
202
+
203
+ # Handle union types
204
+ if any(isinstance(typ, tuple) for typ in signature):
205
+ for typs in expand_tuples(signature):
206
+ self.add(typs, func, on_ambiguity)
207
+ return
208
+
209
+ for typ in signature:
210
+ if not isinstance(typ, type):
211
+ str_sig = ', '.join(c.__name__ if isinstance(c, type)
212
+ else str(c) for c in signature)
213
+ raise TypeError("Tried to dispatch on non-type: %s\n"
214
+ "In signature: <%s>\n"
215
+ "In function: %s" %
216
+ (typ, str_sig, self.name))
217
+
218
+ self.funcs[signature] = func
219
+ self.reorder(on_ambiguity=on_ambiguity)
220
+ self._cache.clear()
221
+
222
+ def reorder(self, on_ambiguity=ambiguity_warn):
223
+ if _resolve[0]:
224
+ self.ordering = ordering(self.funcs)
225
+ amb = ambiguities(self.funcs)
226
+ if amb:
227
+ on_ambiguity(self, amb)
228
+ else:
229
+ _unresolved_dispatchers.add(self)
230
+
231
+ def __call__(self, *args, **kwargs):
232
+ types = tuple([type(arg) for arg in args])
233
+ try:
234
+ func = self._cache[types]
235
+ except KeyError:
236
+ func = self.dispatch(*types)
237
+ if not func:
238
+ raise NotImplementedError(
239
+ 'Could not find signature for %s: <%s>' %
240
+ (self.name, str_signature(types)))
241
+ self._cache[types] = func
242
+ try:
243
+ return func(*args, **kwargs)
244
+
245
+ except MDNotImplementedError:
246
+ funcs = self.dispatch_iter(*types)
247
+ next(funcs) # burn first
248
+ for func in funcs:
249
+ try:
250
+ return func(*args, **kwargs)
251
+ except MDNotImplementedError:
252
+ pass
253
+ raise NotImplementedError("Matching functions for "
254
+ "%s: <%s> found, but none completed successfully"
255
+ % (self.name, str_signature(types)))
256
+
257
+ def __str__(self):
258
+ return "<dispatched %s>" % self.name
259
+ __repr__ = __str__
260
+
261
+ def dispatch(self, *types):
262
+ """ Deterimine appropriate implementation for this type signature
263
+
264
+ This method is internal. Users should call this object as a function.
265
+ Implementation resolution occurs within the ``__call__`` method.
266
+
267
+ >>> from sympy.multipledispatch import dispatch
268
+ >>> @dispatch(int)
269
+ ... def inc(x):
270
+ ... return x + 1
271
+
272
+ >>> implementation = inc.dispatch(int)
273
+ >>> implementation(3)
274
+ 4
275
+
276
+ >>> print(inc.dispatch(float))
277
+ None
278
+
279
+ See Also:
280
+ ``sympy.multipledispatch.conflict`` - module to determine resolution order
281
+ """
282
+
283
+ if types in self.funcs:
284
+ return self.funcs[types]
285
+
286
+ try:
287
+ return next(self.dispatch_iter(*types))
288
+ except StopIteration:
289
+ return None
290
+
291
+ def dispatch_iter(self, *types):
292
+ n = len(types)
293
+ for signature in self.ordering:
294
+ if len(signature) == n and all(map(issubclass, types, signature)):
295
+ result = self.funcs[signature]
296
+ yield result
297
+
298
+ def resolve(self, types):
299
+ """ Deterimine appropriate implementation for this type signature
300
+
301
+ .. deprecated:: 0.4.4
302
+ Use ``dispatch(*types)`` instead
303
+ """
304
+ warn("resolve() is deprecated, use dispatch(*types)",
305
+ DeprecationWarning)
306
+
307
+ return self.dispatch(*types)
308
+
309
+ def __getstate__(self):
310
+ return {'name': self.name,
311
+ 'funcs': self.funcs}
312
+
313
+ def __setstate__(self, d):
314
+ self.name = d['name']
315
+ self.funcs = d['funcs']
316
+ self.ordering = ordering(self.funcs)
317
+ self._cache = {}
318
+
319
+ @property
320
+ def __doc__(self):
321
+ docs = ["Multiply dispatched method: %s" % self.name]
322
+
323
+ if self.doc:
324
+ docs.append(self.doc)
325
+
326
+ other = []
327
+ for sig in self.ordering[::-1]:
328
+ func = self.funcs[sig]
329
+ if func.__doc__:
330
+ s = 'Inputs: <%s>\n' % str_signature(sig)
331
+ s += '-' * len(s) + '\n'
332
+ s += func.__doc__.strip()
333
+ docs.append(s)
334
+ else:
335
+ other.append(str_signature(sig))
336
+
337
+ if other:
338
+ docs.append('Other signatures:\n ' + '\n '.join(other))
339
+
340
+ return '\n\n'.join(docs)
341
+
342
+ def _help(self, *args):
343
+ return self.dispatch(*map(type, args)).__doc__
344
+
345
+ def help(self, *args, **kwargs):
346
+ """ Print docstring for the function corresponding to inputs """
347
+ print(self._help(*args))
348
+
349
+ def _source(self, *args):
350
+ func = self.dispatch(*map(type, args))
351
+ if not func:
352
+ raise TypeError("No function found")
353
+ return source(func)
354
+
355
+ def source(self, *args, **kwargs):
356
+ """ Print source code for the function corresponding to inputs """
357
+ print(self._source(*args))
358
+
359
+
360
+ def source(func):
361
+ s = 'File: %s\n\n' % inspect.getsourcefile(func)
362
+ s = s + inspect.getsource(func)
363
+ return s
364
+
365
+
366
+ class MethodDispatcher(Dispatcher):
367
+ """ Dispatch methods based on type signature
368
+
369
+ See Also:
370
+ Dispatcher
371
+ """
372
+
373
+ @classmethod
374
+ def get_func_params(cls, func):
375
+ if hasattr(inspect, "signature"):
376
+ sig = inspect.signature(func)
377
+ return itl.islice(sig.parameters.values(), 1, None)
378
+
379
+ def __get__(self, instance, owner):
380
+ self.obj = instance
381
+ self.cls = owner
382
+ return self
383
+
384
+ def __call__(self, *args, **kwargs):
385
+ types = tuple([type(arg) for arg in args])
386
+ func = self.dispatch(*types)
387
+ if not func:
388
+ raise NotImplementedError('Could not find signature for %s: <%s>' %
389
+ (self.name, str_signature(types)))
390
+ return func(self.obj, *args, **kwargs)
391
+
392
+
393
+ def str_signature(sig):
394
+ """ String representation of type signature
395
+
396
+ >>> from sympy.multipledispatch.dispatcher import str_signature
397
+ >>> str_signature((int, float))
398
+ 'int, float'
399
+ """
400
+ return ', '.join(cls.__name__ for cls in sig)
401
+
402
+
403
+ def warning_text(name, amb):
404
+ """ The text for ambiguity warnings """
405
+ text = "\nAmbiguities exist in dispatched function %s\n\n" % (name)
406
+ text += "The following signatures may result in ambiguous behavior:\n"
407
+ for pair in amb:
408
+ text += "\t" + \
409
+ ', '.join('[' + str_signature(s) + ']' for s in pair) + "\n"
410
+ text += "\n\nConsider making the following additions:\n\n"
411
+ text += '\n\n'.join(['@dispatch(' + str_signature(super_signature(s))
412
+ + ')\ndef %s(...)' % name for s in amb])
413
+ return text
parrot/lib/python3.10/site-packages/sympy/multipledispatch/tests/__init__.py ADDED
File without changes
parrot/lib/python3.10/site-packages/sympy/multipledispatch/tests/__pycache__/test_dispatcher.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/multipledispatch/tests/test_dispatcher.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.multipledispatch.dispatcher import (Dispatcher, MDNotImplementedError,
2
+ MethodDispatcher, halt_ordering,
3
+ restart_ordering,
4
+ ambiguity_register_error_ignore_dup)
5
+ from sympy.testing.pytest import raises, warns
6
+
7
+
8
+ def identity(x):
9
+ return x
10
+
11
+
12
+ def inc(x):
13
+ return x + 1
14
+
15
+
16
+ def dec(x):
17
+ return x - 1
18
+
19
+
20
+ def test_dispatcher():
21
+ f = Dispatcher('f')
22
+ f.add((int,), inc)
23
+ f.add((float,), dec)
24
+
25
+ with warns(DeprecationWarning, test_stacklevel=False):
26
+ assert f.resolve((int,)) == inc
27
+ assert f.dispatch(int) is inc
28
+
29
+ assert f(1) == 2
30
+ assert f(1.0) == 0.0
31
+
32
+
33
+ def test_union_types():
34
+ f = Dispatcher('f')
35
+ f.register((int, float))(inc)
36
+
37
+ assert f(1) == 2
38
+ assert f(1.0) == 2.0
39
+
40
+
41
+ def test_dispatcher_as_decorator():
42
+ f = Dispatcher('f')
43
+
44
+ @f.register(int)
45
+ def inc(x): # noqa:F811
46
+ return x + 1
47
+
48
+ @f.register(float) # noqa:F811
49
+ def inc(x): # noqa:F811
50
+ return x - 1
51
+
52
+ assert f(1) == 2
53
+ assert f(1.0) == 0.0
54
+
55
+
56
+ def test_register_instance_method():
57
+
58
+ class Test:
59
+ __init__ = MethodDispatcher('f')
60
+
61
+ @__init__.register(list)
62
+ def _init_list(self, data):
63
+ self.data = data
64
+
65
+ @__init__.register(object)
66
+ def _init_obj(self, datum):
67
+ self.data = [datum]
68
+
69
+ a = Test(3)
70
+ b = Test([3])
71
+ assert a.data == b.data
72
+
73
+
74
+ def test_on_ambiguity():
75
+ f = Dispatcher('f')
76
+
77
+ def identity(x): return x
78
+
79
+ ambiguities = [False]
80
+
81
+ def on_ambiguity(dispatcher, amb):
82
+ ambiguities[0] = True
83
+
84
+ f.add((object, object), identity, on_ambiguity=on_ambiguity)
85
+ assert not ambiguities[0]
86
+ f.add((object, float), identity, on_ambiguity=on_ambiguity)
87
+ assert not ambiguities[0]
88
+ f.add((float, object), identity, on_ambiguity=on_ambiguity)
89
+ assert ambiguities[0]
90
+
91
+
92
+ def test_raise_error_on_non_class():
93
+ f = Dispatcher('f')
94
+ assert raises(TypeError, lambda: f.add((1,), inc))
95
+
96
+
97
+ def test_docstring():
98
+
99
+ def one(x, y):
100
+ """ Docstring number one """
101
+ return x + y
102
+
103
+ def two(x, y):
104
+ """ Docstring number two """
105
+ return x + y
106
+
107
+ def three(x, y):
108
+ return x + y
109
+
110
+ master_doc = 'Doc of the multimethod itself'
111
+
112
+ f = Dispatcher('f', doc=master_doc)
113
+ f.add((object, object), one)
114
+ f.add((int, int), two)
115
+ f.add((float, float), three)
116
+
117
+ assert one.__doc__.strip() in f.__doc__
118
+ assert two.__doc__.strip() in f.__doc__
119
+ assert f.__doc__.find(one.__doc__.strip()) < \
120
+ f.__doc__.find(two.__doc__.strip())
121
+ assert 'object, object' in f.__doc__
122
+ assert master_doc in f.__doc__
123
+
124
+
125
+ def test_help():
126
+ def one(x, y):
127
+ """ Docstring number one """
128
+ return x + y
129
+
130
+ def two(x, y):
131
+ """ Docstring number two """
132
+ return x + y
133
+
134
+ def three(x, y):
135
+ """ Docstring number three """
136
+ return x + y
137
+
138
+ master_doc = 'Doc of the multimethod itself'
139
+
140
+ f = Dispatcher('f', doc=master_doc)
141
+ f.add((object, object), one)
142
+ f.add((int, int), two)
143
+ f.add((float, float), three)
144
+
145
+ assert f._help(1, 1) == two.__doc__
146
+ assert f._help(1.0, 2.0) == three.__doc__
147
+
148
+
149
+ def test_source():
150
+ def one(x, y):
151
+ """ Docstring number one """
152
+ return x + y
153
+
154
+ def two(x, y):
155
+ """ Docstring number two """
156
+ return x - y
157
+
158
+ master_doc = 'Doc of the multimethod itself'
159
+
160
+ f = Dispatcher('f', doc=master_doc)
161
+ f.add((int, int), one)
162
+ f.add((float, float), two)
163
+
164
+ assert 'x + y' in f._source(1, 1)
165
+ assert 'x - y' in f._source(1.0, 1.0)
166
+
167
+
168
+ def test_source_raises_on_missing_function():
169
+ f = Dispatcher('f')
170
+
171
+ assert raises(TypeError, lambda: f.source(1))
172
+
173
+
174
+ def test_halt_method_resolution():
175
+ g = [0]
176
+
177
+ def on_ambiguity(a, b):
178
+ g[0] += 1
179
+
180
+ f = Dispatcher('f')
181
+
182
+ halt_ordering()
183
+
184
+ def func(*args):
185
+ pass
186
+
187
+ f.add((int, object), func)
188
+ f.add((object, int), func)
189
+
190
+ assert g == [0]
191
+
192
+ restart_ordering(on_ambiguity=on_ambiguity)
193
+
194
+ assert g == [1]
195
+
196
+ assert set(f.ordering) == {(int, object), (object, int)}
197
+
198
+
199
+ def test_no_implementations():
200
+ f = Dispatcher('f')
201
+ assert raises(NotImplementedError, lambda: f('hello'))
202
+
203
+
204
+ def test_register_stacking():
205
+ f = Dispatcher('f')
206
+
207
+ @f.register(list)
208
+ @f.register(tuple)
209
+ def rev(x):
210
+ return x[::-1]
211
+
212
+ assert f((1, 2, 3)) == (3, 2, 1)
213
+ assert f([1, 2, 3]) == [3, 2, 1]
214
+
215
+ assert raises(NotImplementedError, lambda: f('hello'))
216
+ assert rev('hello') == 'olleh'
217
+
218
+
219
+ def test_dispatch_method():
220
+ f = Dispatcher('f')
221
+
222
+ @f.register(list)
223
+ def rev(x):
224
+ return x[::-1]
225
+
226
+ @f.register(int, int)
227
+ def add(x, y):
228
+ return x + y
229
+
230
+ class MyList(list):
231
+ pass
232
+
233
+ assert f.dispatch(list) is rev
234
+ assert f.dispatch(MyList) is rev
235
+ assert f.dispatch(int, int) is add
236
+
237
+
238
+ def test_not_implemented():
239
+ f = Dispatcher('f')
240
+
241
+ @f.register(object)
242
+ def _(x):
243
+ return 'default'
244
+
245
+ @f.register(int)
246
+ def _(x):
247
+ if x % 2 == 0:
248
+ return 'even'
249
+ else:
250
+ raise MDNotImplementedError()
251
+
252
+ assert f('hello') == 'default' # default behavior
253
+ assert f(2) == 'even' # specialized behavior
254
+ assert f(3) == 'default' # fall bac to default behavior
255
+ assert raises(NotImplementedError, lambda: f(1, 2))
256
+
257
+
258
+ def test_not_implemented_error():
259
+ f = Dispatcher('f')
260
+
261
+ @f.register(float)
262
+ def _(a):
263
+ raise MDNotImplementedError()
264
+
265
+ assert raises(NotImplementedError, lambda: f(1.0))
266
+
267
+ def test_ambiguity_register_error_ignore_dup():
268
+ f = Dispatcher('f')
269
+
270
+ class A:
271
+ pass
272
+ class B(A):
273
+ pass
274
+ class C(A):
275
+ pass
276
+
277
+ # suppress warning for registering ambiguous signal
278
+ f.add((A, B), lambda x,y: None, ambiguity_register_error_ignore_dup)
279
+ f.add((B, A), lambda x,y: None, ambiguity_register_error_ignore_dup)
280
+ f.add((A, C), lambda x,y: None, ambiguity_register_error_ignore_dup)
281
+ f.add((C, A), lambda x,y: None, ambiguity_register_error_ignore_dup)
282
+
283
+ # raises error if ambiguous signal is passed
284
+ assert raises(NotImplementedError, lambda: f(B(), C()))
parrot/lib/python3.10/site-packages/sympy/parsing/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (306 Bytes). View file
 
parrot/lib/python3.10/site-packages/sympy/parsing/__pycache__/ast_parser.cpython-310.pyc ADDED
Binary file (3.12 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/parsing/__pycache__/maxima.cpython-310.pyc ADDED
Binary file (2.46 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/parsing/__pycache__/sympy_parser.cpython-310.pyc ADDED
Binary file (30.4 kB). View file
 
parrot/lib/python3.10/site-packages/sympy/parsing/latex/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright 2016, latex2sympy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
parrot/lib/python3.10/site-packages/sympy/parsing/latex/__init__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.external import import_module
2
+ from sympy.utilities.decorator import doctest_depends_on
3
+
4
+ from sympy.parsing.latex.lark import LarkLaTeXParser, TransformToSymPyExpr, parse_latex_lark # noqa
5
+
6
+ from .errors import LaTeXParsingError # noqa
7
+
8
+
9
+ __doctest_requires__ = {('parse_latex',): ['antlr4', 'lark']}
10
+
11
+
12
+ @doctest_depends_on(modules=('antlr4', 'lark'))
13
+ def parse_latex(s, strict=False, backend="antlr"):
14
+ r"""Converts the input LaTeX string ``s`` to a SymPy ``Expr``.
15
+
16
+ Parameters
17
+ ==========
18
+
19
+ s : str
20
+ The LaTeX string to parse. In Python source containing LaTeX,
21
+ *raw strings* (denoted with ``r"``, like this one) are preferred,
22
+ as LaTeX makes liberal use of the ``\`` character, which would
23
+ trigger escaping in normal Python strings.
24
+ backend : str, optional
25
+ Currently, there are two backends supported: ANTLR, and Lark.
26
+ The default setting is to use the ANTLR backend, which can be
27
+ changed to Lark if preferred.
28
+
29
+ Use ``backend="antlr"`` for the ANTLR-based parser, and
30
+ ``backend="lark"`` for the Lark-based parser.
31
+
32
+ The ``backend`` option is case-sensitive, and must be in
33
+ all lowercase.
34
+ strict : bool, optional
35
+ This option is only available with the ANTLR backend.
36
+
37
+ If True, raise an exception if the string cannot be parsed as
38
+ valid LaTeX. If False, try to recover gracefully from common
39
+ mistakes.
40
+
41
+ Examples
42
+ ========
43
+
44
+ >>> from sympy.parsing.latex import parse_latex
45
+ >>> expr = parse_latex(r"\frac {1 + \sqrt {\a}} {\b}")
46
+ >>> expr
47
+ (sqrt(a) + 1)/b
48
+ >>> expr.evalf(4, subs=dict(a=5, b=2))
49
+ 1.618
50
+ >>> func = parse_latex(r"\int_1^\alpha \dfrac{\mathrm{d}t}{t}", backend="lark")
51
+ >>> func.evalf(subs={"alpha": 2})
52
+ 0.693147180559945
53
+ """
54
+
55
+ if backend == "antlr":
56
+ _latex = import_module(
57
+ 'sympy.parsing.latex._parse_latex_antlr',
58
+ import_kwargs={'fromlist': ['X']})
59
+
60
+ if _latex is not None:
61
+ return _latex.parse_latex(s, strict)
62
+ elif backend == "lark":
63
+ return parse_latex_lark(s)
64
+ else:
65
+ raise NotImplementedError(f"Using the '{backend}' backend in the LaTeX" \
66
+ " parser is not supported.")
parrot/lib/python3.10/site-packages/sympy/parsing/latex/_build_latex_antlr.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import glob
4
+
5
+ from sympy.utilities.misc import debug
6
+
7
+ here = os.path.dirname(__file__)
8
+ grammar_file = os.path.abspath(os.path.join(here, "LaTeX.g4"))
9
+ dir_latex_antlr = os.path.join(here, "_antlr")
10
+
11
+ header = '''\
12
+ # *** GENERATED BY `setup.py antlr`, DO NOT EDIT BY HAND ***
13
+ #
14
+ # Generated from ../LaTeX.g4, derived from latex2sympy
15
+ # latex2sympy is licensed under the MIT license
16
+ # https://github.com/augustt198/latex2sympy/blob/master/LICENSE.txt
17
+ #
18
+ # Generated with antlr4
19
+ # antlr4 is licensed under the BSD-3-Clause License
20
+ # https://github.com/antlr/antlr4/blob/master/LICENSE.txt
21
+ '''
22
+
23
+
24
+ def check_antlr_version():
25
+ debug("Checking antlr4 version...")
26
+
27
+ try:
28
+ debug(subprocess.check_output(["antlr4"])
29
+ .decode('utf-8').split("\n")[0])
30
+ return True
31
+ except (subprocess.CalledProcessError, FileNotFoundError):
32
+ debug("The 'antlr4' command line tool is not installed, "
33
+ "or not on your PATH.\n"
34
+ "> Please refer to the README.md file for more information.")
35
+ return False
36
+
37
+
38
+ def build_parser(output_dir=dir_latex_antlr):
39
+ check_antlr_version()
40
+
41
+ debug("Updating ANTLR-generated code in {}".format(output_dir))
42
+
43
+ if not os.path.exists(output_dir):
44
+ os.makedirs(output_dir)
45
+
46
+ with open(os.path.join(output_dir, "__init__.py"), "w+") as fp:
47
+ fp.write(header)
48
+
49
+ args = [
50
+ "antlr4",
51
+ grammar_file,
52
+ "-o", output_dir,
53
+ # for now, not generating these as latex2sympy did not use them
54
+ "-no-visitor",
55
+ "-no-listener",
56
+ ]
57
+
58
+ debug("Running code generation...\n\t$ {}".format(" ".join(args)))
59
+ subprocess.check_output(args, cwd=output_dir)
60
+
61
+ debug("Applying headers, removing unnecessary files and renaming...")
62
+ # Handle case insensitive file systems. If the files are already
63
+ # generated, they will be written to latex* but LaTeX*.* won't match them.
64
+ for path in (glob.glob(os.path.join(output_dir, "LaTeX*.*")) or
65
+ glob.glob(os.path.join(output_dir, "latex*.*"))):
66
+
67
+ # Remove files ending in .interp or .tokens as they are not needed.
68
+ if not path.endswith(".py"):
69
+ os.unlink(path)
70
+ continue
71
+
72
+ new_path = os.path.join(output_dir, os.path.basename(path).lower())
73
+ with open(path, 'r') as f:
74
+ lines = [line.rstrip() + '\n' for line in f.readlines()]
75
+
76
+ os.unlink(path)
77
+
78
+ with open(new_path, "w") as out_file:
79
+ offset = 0
80
+ while lines[offset].startswith('#'):
81
+ offset += 1
82
+ out_file.write(header)
83
+ out_file.writelines(lines[offset:])
84
+
85
+ debug("\t{}".format(new_path))
86
+
87
+ return True
88
+
89
+
90
+ if __name__ == "__main__":
91
+ build_parser()
parrot/lib/python3.10/site-packages/sympy/parsing/latex/_parse_latex_antlr.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ported from latex2sympy by @augustt198
2
+ # https://github.com/augustt198/latex2sympy
3
+ # See license in LICENSE.txt
4
+ from importlib.metadata import version
5
+ import sympy
6
+ from sympy.external import import_module
7
+ from sympy.printing.str import StrPrinter
8
+ from sympy.physics.quantum.state import Bra, Ket
9
+
10
+ from .errors import LaTeXParsingError
11
+
12
+
13
+ LaTeXParser = LaTeXLexer = MathErrorListener = None
14
+
15
+ try:
16
+ LaTeXParser = import_module('sympy.parsing.latex._antlr.latexparser',
17
+ import_kwargs={'fromlist': ['LaTeXParser']}).LaTeXParser
18
+ LaTeXLexer = import_module('sympy.parsing.latex._antlr.latexlexer',
19
+ import_kwargs={'fromlist': ['LaTeXLexer']}).LaTeXLexer
20
+ except Exception:
21
+ pass
22
+
23
+ ErrorListener = import_module('antlr4.error.ErrorListener',
24
+ warn_not_installed=True,
25
+ import_kwargs={'fromlist': ['ErrorListener']}
26
+ )
27
+
28
+
29
+
30
+ if ErrorListener:
31
+ class MathErrorListener(ErrorListener.ErrorListener): # type:ignore # noqa:F811
32
+ def __init__(self, src):
33
+ super(ErrorListener.ErrorListener, self).__init__()
34
+ self.src = src
35
+
36
+ def syntaxError(self, recog, symbol, line, col, msg, e):
37
+ fmt = "%s\n%s\n%s"
38
+ marker = "~" * col + "^"
39
+
40
+ if msg.startswith("missing"):
41
+ err = fmt % (msg, self.src, marker)
42
+ elif msg.startswith("no viable"):
43
+ err = fmt % ("I expected something else here", self.src, marker)
44
+ elif msg.startswith("mismatched"):
45
+ names = LaTeXParser.literalNames
46
+ expected = [
47
+ names[i] for i in e.getExpectedTokens() if i < len(names)
48
+ ]
49
+ if len(expected) < 10:
50
+ expected = " ".join(expected)
51
+ err = (fmt % ("I expected one of these: " + expected, self.src,
52
+ marker))
53
+ else:
54
+ err = (fmt % ("I expected something else here", self.src,
55
+ marker))
56
+ else:
57
+ err = fmt % ("I don't understand this", self.src, marker)
58
+ raise LaTeXParsingError(err)
59
+
60
+
61
+ def parse_latex(sympy, strict=False):
62
+ antlr4 = import_module('antlr4')
63
+
64
+ if None in [antlr4, MathErrorListener] or \
65
+ not version('antlr4-python3-runtime').startswith('4.11'):
66
+ raise ImportError("LaTeX parsing requires the antlr4 Python package,"
67
+ " provided by pip (antlr4-python3-runtime) or"
68
+ " conda (antlr-python-runtime), version 4.11")
69
+
70
+ sympy = sympy.strip()
71
+ matherror = MathErrorListener(sympy)
72
+
73
+ stream = antlr4.InputStream(sympy)
74
+ lex = LaTeXLexer(stream)
75
+ lex.removeErrorListeners()
76
+ lex.addErrorListener(matherror)
77
+
78
+ tokens = antlr4.CommonTokenStream(lex)
79
+ parser = LaTeXParser(tokens)
80
+
81
+ # remove default console error listener
82
+ parser.removeErrorListeners()
83
+ parser.addErrorListener(matherror)
84
+
85
+ relation = parser.math().relation()
86
+ if strict and (relation.start.start != 0 or relation.stop.stop != len(sympy) - 1):
87
+ raise LaTeXParsingError("Invalid LaTeX")
88
+ expr = convert_relation(relation)
89
+
90
+ return expr
91
+
92
+
93
+ def convert_relation(rel):
94
+ if rel.expr():
95
+ return convert_expr(rel.expr())
96
+
97
+ lh = convert_relation(rel.relation(0))
98
+ rh = convert_relation(rel.relation(1))
99
+ if rel.LT():
100
+ return sympy.StrictLessThan(lh, rh)
101
+ elif rel.LTE():
102
+ return sympy.LessThan(lh, rh)
103
+ elif rel.GT():
104
+ return sympy.StrictGreaterThan(lh, rh)
105
+ elif rel.GTE():
106
+ return sympy.GreaterThan(lh, rh)
107
+ elif rel.EQUAL():
108
+ return sympy.Eq(lh, rh)
109
+ elif rel.NEQ():
110
+ return sympy.Ne(lh, rh)
111
+
112
+
113
+ def convert_expr(expr):
114
+ return convert_add(expr.additive())
115
+
116
+
117
+ def convert_add(add):
118
+ if add.ADD():
119
+ lh = convert_add(add.additive(0))
120
+ rh = convert_add(add.additive(1))
121
+ return sympy.Add(lh, rh, evaluate=False)
122
+ elif add.SUB():
123
+ lh = convert_add(add.additive(0))
124
+ rh = convert_add(add.additive(1))
125
+ if hasattr(rh, "is_Atom") and rh.is_Atom:
126
+ return sympy.Add(lh, -1 * rh, evaluate=False)
127
+ return sympy.Add(lh, sympy.Mul(-1, rh, evaluate=False), evaluate=False)
128
+ else:
129
+ return convert_mp(add.mp())
130
+
131
+
132
+ def convert_mp(mp):
133
+ if hasattr(mp, 'mp'):
134
+ mp_left = mp.mp(0)
135
+ mp_right = mp.mp(1)
136
+ else:
137
+ mp_left = mp.mp_nofunc(0)
138
+ mp_right = mp.mp_nofunc(1)
139
+
140
+ if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT():
141
+ lh = convert_mp(mp_left)
142
+ rh = convert_mp(mp_right)
143
+ return sympy.Mul(lh, rh, evaluate=False)
144
+ elif mp.DIV() or mp.CMD_DIV() or mp.COLON():
145
+ lh = convert_mp(mp_left)
146
+ rh = convert_mp(mp_right)
147
+ return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False)
148
+ else:
149
+ if hasattr(mp, 'unary'):
150
+ return convert_unary(mp.unary())
151
+ else:
152
+ return convert_unary(mp.unary_nofunc())
153
+
154
+
155
+ def convert_unary(unary):
156
+ if hasattr(unary, 'unary'):
157
+ nested_unary = unary.unary()
158
+ else:
159
+ nested_unary = unary.unary_nofunc()
160
+ if hasattr(unary, 'postfix_nofunc'):
161
+ first = unary.postfix()
162
+ tail = unary.postfix_nofunc()
163
+ postfix = [first] + tail
164
+ else:
165
+ postfix = unary.postfix()
166
+
167
+ if unary.ADD():
168
+ return convert_unary(nested_unary)
169
+ elif unary.SUB():
170
+ numabs = convert_unary(nested_unary)
171
+ # Use Integer(-n) instead of Mul(-1, n)
172
+ return -numabs
173
+ elif postfix:
174
+ return convert_postfix_list(postfix)
175
+
176
+
177
+ def convert_postfix_list(arr, i=0):
178
+ if i >= len(arr):
179
+ raise LaTeXParsingError("Index out of bounds")
180
+
181
+ res = convert_postfix(arr[i])
182
+ if isinstance(res, sympy.Expr):
183
+ if i == len(arr) - 1:
184
+ return res # nothing to multiply by
185
+ else:
186
+ if i > 0:
187
+ left = convert_postfix(arr[i - 1])
188
+ right = convert_postfix(arr[i + 1])
189
+ if isinstance(left, sympy.Expr) and isinstance(
190
+ right, sympy.Expr):
191
+ left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol)
192
+ right_syms = convert_postfix(arr[i + 1]).atoms(
193
+ sympy.Symbol)
194
+ # if the left and right sides contain no variables and the
195
+ # symbol in between is 'x', treat as multiplication.
196
+ if not (left_syms or right_syms) and str(res) == 'x':
197
+ return convert_postfix_list(arr, i + 1)
198
+ # multiply by next
199
+ return sympy.Mul(
200
+ res, convert_postfix_list(arr, i + 1), evaluate=False)
201
+ else: # must be derivative
202
+ wrt = res[0]
203
+ if i == len(arr) - 1:
204
+ raise LaTeXParsingError("Expected expression for derivative")
205
+ else:
206
+ expr = convert_postfix_list(arr, i + 1)
207
+ return sympy.Derivative(expr, wrt)
208
+
209
+
210
+ def do_subs(expr, at):
211
+ if at.expr():
212
+ at_expr = convert_expr(at.expr())
213
+ syms = at_expr.atoms(sympy.Symbol)
214
+ if len(syms) == 0:
215
+ return expr
216
+ elif len(syms) > 0:
217
+ sym = next(iter(syms))
218
+ return expr.subs(sym, at_expr)
219
+ elif at.equality():
220
+ lh = convert_expr(at.equality().expr(0))
221
+ rh = convert_expr(at.equality().expr(1))
222
+ return expr.subs(lh, rh)
223
+
224
+
225
+ def convert_postfix(postfix):
226
+ if hasattr(postfix, 'exp'):
227
+ exp_nested = postfix.exp()
228
+ else:
229
+ exp_nested = postfix.exp_nofunc()
230
+
231
+ exp = convert_exp(exp_nested)
232
+ for op in postfix.postfix_op():
233
+ if op.BANG():
234
+ if isinstance(exp, list):
235
+ raise LaTeXParsingError("Cannot apply postfix to derivative")
236
+ exp = sympy.factorial(exp, evaluate=False)
237
+ elif op.eval_at():
238
+ ev = op.eval_at()
239
+ at_b = None
240
+ at_a = None
241
+ if ev.eval_at_sup():
242
+ at_b = do_subs(exp, ev.eval_at_sup())
243
+ if ev.eval_at_sub():
244
+ at_a = do_subs(exp, ev.eval_at_sub())
245
+ if at_b is not None and at_a is not None:
246
+ exp = sympy.Add(at_b, -1 * at_a, evaluate=False)
247
+ elif at_b is not None:
248
+ exp = at_b
249
+ elif at_a is not None:
250
+ exp = at_a
251
+
252
+ return exp
253
+
254
+
255
+ def convert_exp(exp):
256
+ if hasattr(exp, 'exp'):
257
+ exp_nested = exp.exp()
258
+ else:
259
+ exp_nested = exp.exp_nofunc()
260
+
261
+ if exp_nested:
262
+ base = convert_exp(exp_nested)
263
+ if isinstance(base, list):
264
+ raise LaTeXParsingError("Cannot raise derivative to power")
265
+ if exp.atom():
266
+ exponent = convert_atom(exp.atom())
267
+ elif exp.expr():
268
+ exponent = convert_expr(exp.expr())
269
+ return sympy.Pow(base, exponent, evaluate=False)
270
+ else:
271
+ if hasattr(exp, 'comp'):
272
+ return convert_comp(exp.comp())
273
+ else:
274
+ return convert_comp(exp.comp_nofunc())
275
+
276
+
277
+ def convert_comp(comp):
278
+ if comp.group():
279
+ return convert_expr(comp.group().expr())
280
+ elif comp.abs_group():
281
+ return sympy.Abs(convert_expr(comp.abs_group().expr()), evaluate=False)
282
+ elif comp.atom():
283
+ return convert_atom(comp.atom())
284
+ elif comp.floor():
285
+ return convert_floor(comp.floor())
286
+ elif comp.ceil():
287
+ return convert_ceil(comp.ceil())
288
+ elif comp.func():
289
+ return convert_func(comp.func())
290
+
291
+
292
+ def convert_atom(atom):
293
+ if atom.LETTER():
294
+ sname = atom.LETTER().getText()
295
+ if atom.subexpr():
296
+ if atom.subexpr().expr(): # subscript is expr
297
+ subscript = convert_expr(atom.subexpr().expr())
298
+ else: # subscript is atom
299
+ subscript = convert_atom(atom.subexpr().atom())
300
+ sname += '_{' + StrPrinter().doprint(subscript) + '}'
301
+ if atom.SINGLE_QUOTES():
302
+ sname += atom.SINGLE_QUOTES().getText() # put after subscript for easy identify
303
+ return sympy.Symbol(sname)
304
+ elif atom.SYMBOL():
305
+ s = atom.SYMBOL().getText()[1:]
306
+ if s == "infty":
307
+ return sympy.oo
308
+ else:
309
+ if atom.subexpr():
310
+ subscript = None
311
+ if atom.subexpr().expr(): # subscript is expr
312
+ subscript = convert_expr(atom.subexpr().expr())
313
+ else: # subscript is atom
314
+ subscript = convert_atom(atom.subexpr().atom())
315
+ subscriptName = StrPrinter().doprint(subscript)
316
+ s += '_{' + subscriptName + '}'
317
+ return sympy.Symbol(s)
318
+ elif atom.number():
319
+ s = atom.number().getText().replace(",", "")
320
+ return sympy.Number(s)
321
+ elif atom.DIFFERENTIAL():
322
+ var = get_differential_var(atom.DIFFERENTIAL())
323
+ return sympy.Symbol('d' + var.name)
324
+ elif atom.mathit():
325
+ text = rule2text(atom.mathit().mathit_text())
326
+ return sympy.Symbol(text)
327
+ elif atom.frac():
328
+ return convert_frac(atom.frac())
329
+ elif atom.binom():
330
+ return convert_binom(atom.binom())
331
+ elif atom.bra():
332
+ val = convert_expr(atom.bra().expr())
333
+ return Bra(val)
334
+ elif atom.ket():
335
+ val = convert_expr(atom.ket().expr())
336
+ return Ket(val)
337
+
338
+
339
+ def rule2text(ctx):
340
+ stream = ctx.start.getInputStream()
341
+ # starting index of starting token
342
+ startIdx = ctx.start.start
343
+ # stopping index of stopping token
344
+ stopIdx = ctx.stop.stop
345
+
346
+ return stream.getText(startIdx, stopIdx)
347
+
348
+
349
+ def convert_frac(frac):
350
+ diff_op = False
351
+ partial_op = False
352
+ if frac.lower and frac.upper:
353
+ lower_itv = frac.lower.getSourceInterval()
354
+ lower_itv_len = lower_itv[1] - lower_itv[0] + 1
355
+ if (frac.lower.start == frac.lower.stop
356
+ and frac.lower.start.type == LaTeXLexer.DIFFERENTIAL):
357
+ wrt = get_differential_var_str(frac.lower.start.text)
358
+ diff_op = True
359
+ elif (lower_itv_len == 2 and frac.lower.start.type == LaTeXLexer.SYMBOL
360
+ and frac.lower.start.text == '\\partial'
361
+ and (frac.lower.stop.type == LaTeXLexer.LETTER
362
+ or frac.lower.stop.type == LaTeXLexer.SYMBOL)):
363
+ partial_op = True
364
+ wrt = frac.lower.stop.text
365
+ if frac.lower.stop.type == LaTeXLexer.SYMBOL:
366
+ wrt = wrt[1:]
367
+
368
+ if diff_op or partial_op:
369
+ wrt = sympy.Symbol(wrt)
370
+ if (diff_op and frac.upper.start == frac.upper.stop
371
+ and frac.upper.start.type == LaTeXLexer.LETTER
372
+ and frac.upper.start.text == 'd'):
373
+ return [wrt]
374
+ elif (partial_op and frac.upper.start == frac.upper.stop
375
+ and frac.upper.start.type == LaTeXLexer.SYMBOL
376
+ and frac.upper.start.text == '\\partial'):
377
+ return [wrt]
378
+ upper_text = rule2text(frac.upper)
379
+
380
+ expr_top = None
381
+ if diff_op and upper_text.startswith('d'):
382
+ expr_top = parse_latex(upper_text[1:])
383
+ elif partial_op and frac.upper.start.text == '\\partial':
384
+ expr_top = parse_latex(upper_text[len('\\partial'):])
385
+ if expr_top:
386
+ return sympy.Derivative(expr_top, wrt)
387
+ if frac.upper:
388
+ expr_top = convert_expr(frac.upper)
389
+ else:
390
+ expr_top = sympy.Number(frac.upperd.text)
391
+ if frac.lower:
392
+ expr_bot = convert_expr(frac.lower)
393
+ else:
394
+ expr_bot = sympy.Number(frac.lowerd.text)
395
+ inverse_denom = sympy.Pow(expr_bot, -1, evaluate=False)
396
+ if expr_top == 1:
397
+ return inverse_denom
398
+ else:
399
+ return sympy.Mul(expr_top, inverse_denom, evaluate=False)
400
+
401
+ def convert_binom(binom):
402
+ expr_n = convert_expr(binom.n)
403
+ expr_k = convert_expr(binom.k)
404
+ return sympy.binomial(expr_n, expr_k, evaluate=False)
405
+
406
+ def convert_floor(floor):
407
+ val = convert_expr(floor.val)
408
+ return sympy.floor(val, evaluate=False)
409
+
410
+ def convert_ceil(ceil):
411
+ val = convert_expr(ceil.val)
412
+ return sympy.ceiling(val, evaluate=False)
413
+
414
+ def convert_func(func):
415
+ if func.func_normal():
416
+ if func.L_PAREN(): # function called with parenthesis
417
+ arg = convert_func_arg(func.func_arg())
418
+ else:
419
+ arg = convert_func_arg(func.func_arg_noparens())
420
+
421
+ name = func.func_normal().start.text[1:]
422
+
423
+ # change arc<trig> -> a<trig>
424
+ if name in [
425
+ "arcsin", "arccos", "arctan", "arccsc", "arcsec", "arccot"
426
+ ]:
427
+ name = "a" + name[3:]
428
+ expr = getattr(sympy.functions, name)(arg, evaluate=False)
429
+ if name in ["arsinh", "arcosh", "artanh"]:
430
+ name = "a" + name[2:]
431
+ expr = getattr(sympy.functions, name)(arg, evaluate=False)
432
+
433
+ if name == "exp":
434
+ expr = sympy.exp(arg, evaluate=False)
435
+
436
+ if name in ("log", "lg", "ln"):
437
+ if func.subexpr():
438
+ if func.subexpr().expr():
439
+ base = convert_expr(func.subexpr().expr())
440
+ else:
441
+ base = convert_atom(func.subexpr().atom())
442
+ elif name == "lg": # ISO 80000-2:2019
443
+ base = 10
444
+ elif name in ("ln", "log"): # SymPy's latex printer prints ln as log by default
445
+ base = sympy.E
446
+ expr = sympy.log(arg, base, evaluate=False)
447
+
448
+ func_pow = None
449
+ should_pow = True
450
+ if func.supexpr():
451
+ if func.supexpr().expr():
452
+ func_pow = convert_expr(func.supexpr().expr())
453
+ else:
454
+ func_pow = convert_atom(func.supexpr().atom())
455
+
456
+ if name in [
457
+ "sin", "cos", "tan", "csc", "sec", "cot", "sinh", "cosh",
458
+ "tanh"
459
+ ]:
460
+ if func_pow == -1:
461
+ name = "a" + name
462
+ should_pow = False
463
+ expr = getattr(sympy.functions, name)(arg, evaluate=False)
464
+
465
+ if func_pow and should_pow:
466
+ expr = sympy.Pow(expr, func_pow, evaluate=False)
467
+
468
+ return expr
469
+ elif func.LETTER() or func.SYMBOL():
470
+ if func.LETTER():
471
+ fname = func.LETTER().getText()
472
+ elif func.SYMBOL():
473
+ fname = func.SYMBOL().getText()[1:]
474
+ fname = str(fname) # can't be unicode
475
+ if func.subexpr():
476
+ if func.subexpr().expr(): # subscript is expr
477
+ subscript = convert_expr(func.subexpr().expr())
478
+ else: # subscript is atom
479
+ subscript = convert_atom(func.subexpr().atom())
480
+ subscriptName = StrPrinter().doprint(subscript)
481
+ fname += '_{' + subscriptName + '}'
482
+ if func.SINGLE_QUOTES():
483
+ fname += func.SINGLE_QUOTES().getText()
484
+ input_args = func.args()
485
+ output_args = []
486
+ while input_args.args(): # handle multiple arguments to function
487
+ output_args.append(convert_expr(input_args.expr()))
488
+ input_args = input_args.args()
489
+ output_args.append(convert_expr(input_args.expr()))
490
+ return sympy.Function(fname)(*output_args)
491
+ elif func.FUNC_INT():
492
+ return handle_integral(func)
493
+ elif func.FUNC_SQRT():
494
+ expr = convert_expr(func.base)
495
+ if func.root:
496
+ r = convert_expr(func.root)
497
+ return sympy.root(expr, r, evaluate=False)
498
+ else:
499
+ return sympy.sqrt(expr, evaluate=False)
500
+ elif func.FUNC_OVERLINE():
501
+ expr = convert_expr(func.base)
502
+ return sympy.conjugate(expr, evaluate=False)
503
+ elif func.FUNC_SUM():
504
+ return handle_sum_or_prod(func, "summation")
505
+ elif func.FUNC_PROD():
506
+ return handle_sum_or_prod(func, "product")
507
+ elif func.FUNC_LIM():
508
+ return handle_limit(func)
509
+
510
+
511
+ def convert_func_arg(arg):
512
+ if hasattr(arg, 'expr'):
513
+ return convert_expr(arg.expr())
514
+ else:
515
+ return convert_mp(arg.mp_nofunc())
516
+
517
+
518
+ def handle_integral(func):
519
+ if func.additive():
520
+ integrand = convert_add(func.additive())
521
+ elif func.frac():
522
+ integrand = convert_frac(func.frac())
523
+ else:
524
+ integrand = 1
525
+
526
+ int_var = None
527
+ if func.DIFFERENTIAL():
528
+ int_var = get_differential_var(func.DIFFERENTIAL())
529
+ else:
530
+ for sym in integrand.atoms(sympy.Symbol):
531
+ s = str(sym)
532
+ if len(s) > 1 and s[0] == 'd':
533
+ if s[1] == '\\':
534
+ int_var = sympy.Symbol(s[2:])
535
+ else:
536
+ int_var = sympy.Symbol(s[1:])
537
+ int_sym = sym
538
+ if int_var:
539
+ integrand = integrand.subs(int_sym, 1)
540
+ else:
541
+ # Assume dx by default
542
+ int_var = sympy.Symbol('x')
543
+
544
+ if func.subexpr():
545
+ if func.subexpr().atom():
546
+ lower = convert_atom(func.subexpr().atom())
547
+ else:
548
+ lower = convert_expr(func.subexpr().expr())
549
+ if func.supexpr().atom():
550
+ upper = convert_atom(func.supexpr().atom())
551
+ else:
552
+ upper = convert_expr(func.supexpr().expr())
553
+ return sympy.Integral(integrand, (int_var, lower, upper))
554
+ else:
555
+ return sympy.Integral(integrand, int_var)
556
+
557
+
558
+ def handle_sum_or_prod(func, name):
559
+ val = convert_mp(func.mp())
560
+ iter_var = convert_expr(func.subeq().equality().expr(0))
561
+ start = convert_expr(func.subeq().equality().expr(1))
562
+ if func.supexpr().expr(): # ^{expr}
563
+ end = convert_expr(func.supexpr().expr())
564
+ else: # ^atom
565
+ end = convert_atom(func.supexpr().atom())
566
+
567
+ if name == "summation":
568
+ return sympy.Sum(val, (iter_var, start, end))
569
+ elif name == "product":
570
+ return sympy.Product(val, (iter_var, start, end))
571
+
572
+
573
+ def handle_limit(func):
574
+ sub = func.limit_sub()
575
+ if sub.LETTER():
576
+ var = sympy.Symbol(sub.LETTER().getText())
577
+ elif sub.SYMBOL():
578
+ var = sympy.Symbol(sub.SYMBOL().getText()[1:])
579
+ else:
580
+ var = sympy.Symbol('x')
581
+ if sub.SUB():
582
+ direction = "-"
583
+ elif sub.ADD():
584
+ direction = "+"
585
+ else:
586
+ direction = "+-"
587
+ approaching = convert_expr(sub.expr())
588
+ content = convert_mp(func.mp())
589
+
590
+ return sympy.Limit(content, var, approaching, direction)
591
+
592
+
593
+ def get_differential_var(d):
594
+ text = get_differential_var_str(d.getText())
595
+ return sympy.Symbol(text)
596
+
597
+
598
+ def get_differential_var_str(text):
599
+ for i in range(1, len(text)):
600
+ c = text[i]
601
+ if not (c == " " or c == "\r" or c == "\n" or c == "\t"):
602
+ idx = i
603
+ break
604
+ text = text[idx:]
605
+ if text[0] == "\\":
606
+ text = text[1:]
607
+ return text
parrot/lib/python3.10/site-packages/sympy/parsing/latex/errors.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ class LaTeXParsingError(Exception):
2
+ pass
parrot/lib/python3.10/site-packages/sympy/parsing/latex/lark/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .latex_parser import parse_latex_lark, LarkLaTeXParser # noqa
2
+ from .transformer import TransformToSymPyExpr # noqa
parrot/lib/python3.10/site-packages/sympy/parsing/sympy_parser.py ADDED
@@ -0,0 +1,1257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Transform a string with Python-like source code into SymPy expression. """
2
+
3
+ from tokenize import (generate_tokens, untokenize, TokenError,
4
+ NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE)
5
+
6
+ from keyword import iskeyword
7
+
8
+ import ast
9
+ import unicodedata
10
+ from io import StringIO
11
+ import builtins
12
+ import types
13
+ from typing import Tuple as tTuple, Dict as tDict, Any, Callable, \
14
+ List, Optional, Union as tUnion
15
+
16
+ from sympy.assumptions.ask import AssumptionKeys
17
+ from sympy.core.basic import Basic
18
+ from sympy.core import Symbol
19
+ from sympy.core.function import Function
20
+ from sympy.utilities.misc import func_name
21
+ from sympy.functions.elementary.miscellaneous import Max, Min
22
+
23
+
24
+ null = ''
25
+
26
+ TOKEN = tTuple[int, str]
27
+ DICT = tDict[str, Any]
28
+ TRANS = Callable[[List[TOKEN], DICT, DICT], List[TOKEN]]
29
+
30
+ def _token_splittable(token_name: str) -> bool:
31
+ """
32
+ Predicate for whether a token name can be split into multiple tokens.
33
+
34
+ A token is splittable if it does not contain an underscore character and
35
+ it is not the name of a Greek letter. This is used to implicitly convert
36
+ expressions like 'xyz' into 'x*y*z'.
37
+ """
38
+ if '_' in token_name:
39
+ return False
40
+ try:
41
+ return not unicodedata.lookup('GREEK SMALL LETTER ' + token_name)
42
+ except KeyError:
43
+ return len(token_name) > 1
44
+
45
+
46
+ def _token_callable(token: TOKEN, local_dict: DICT, global_dict: DICT, nextToken=None):
47
+ """
48
+ Predicate for whether a token name represents a callable function.
49
+
50
+ Essentially wraps ``callable``, but looks up the token name in the
51
+ locals and globals.
52
+ """
53
+ func = local_dict.get(token[1])
54
+ if not func:
55
+ func = global_dict.get(token[1])
56
+ return callable(func) and not isinstance(func, Symbol)
57
+
58
+
59
+ def _add_factorial_tokens(name: str, result: List[TOKEN]) -> List[TOKEN]:
60
+ if result == [] or result[-1][1] == '(':
61
+ raise TokenError()
62
+
63
+ beginning = [(NAME, name), (OP, '(')]
64
+ end = [(OP, ')')]
65
+
66
+ diff = 0
67
+ length = len(result)
68
+
69
+ for index, token in enumerate(result[::-1]):
70
+ toknum, tokval = token
71
+ i = length - index - 1
72
+
73
+ if tokval == ')':
74
+ diff += 1
75
+ elif tokval == '(':
76
+ diff -= 1
77
+
78
+ if diff == 0:
79
+ if i - 1 >= 0 and result[i - 1][0] == NAME:
80
+ return result[:i - 1] + beginning + result[i - 1:] + end
81
+ else:
82
+ return result[:i] + beginning + result[i:] + end
83
+
84
+ return result
85
+
86
+
87
+ class ParenthesisGroup(List[TOKEN]):
88
+ """List of tokens representing an expression in parentheses."""
89
+ pass
90
+
91
+
92
+ class AppliedFunction:
93
+ """
94
+ A group of tokens representing a function and its arguments.
95
+
96
+ `exponent` is for handling the shorthand sin^2, ln^2, etc.
97
+ """
98
+ def __init__(self, function: TOKEN, args: ParenthesisGroup, exponent=None):
99
+ if exponent is None:
100
+ exponent = []
101
+ self.function = function
102
+ self.args = args
103
+ self.exponent = exponent
104
+ self.items = ['function', 'args', 'exponent']
105
+
106
+ def expand(self) -> List[TOKEN]:
107
+ """Return a list of tokens representing the function"""
108
+ return [self.function, *self.args]
109
+
110
+ def __getitem__(self, index):
111
+ return getattr(self, self.items[index])
112
+
113
+ def __repr__(self):
114
+ return "AppliedFunction(%s, %s, %s)" % (self.function, self.args,
115
+ self.exponent)
116
+
117
+
118
+ def _flatten(result: List[tUnion[TOKEN, AppliedFunction]]):
119
+ result2: List[TOKEN] = []
120
+ for tok in result:
121
+ if isinstance(tok, AppliedFunction):
122
+ result2.extend(tok.expand())
123
+ else:
124
+ result2.append(tok)
125
+ return result2
126
+
127
+
128
+ def _group_parentheses(recursor: TRANS):
129
+ def _inner(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
130
+ """Group tokens between parentheses with ParenthesisGroup.
131
+
132
+ Also processes those tokens recursively.
133
+
134
+ """
135
+ result: List[tUnion[TOKEN, ParenthesisGroup]] = []
136
+ stacks: List[ParenthesisGroup] = []
137
+ stacklevel = 0
138
+ for token in tokens:
139
+ if token[0] == OP:
140
+ if token[1] == '(':
141
+ stacks.append(ParenthesisGroup([]))
142
+ stacklevel += 1
143
+ elif token[1] == ')':
144
+ stacks[-1].append(token)
145
+ stack = stacks.pop()
146
+
147
+ if len(stacks) > 0:
148
+ # We don't recurse here since the upper-level stack
149
+ # would reprocess these tokens
150
+ stacks[-1].extend(stack)
151
+ else:
152
+ # Recurse here to handle nested parentheses
153
+ # Strip off the outer parentheses to avoid an infinite loop
154
+ inner = stack[1:-1]
155
+ inner = recursor(inner,
156
+ local_dict,
157
+ global_dict)
158
+ parenGroup = [stack[0]] + inner + [stack[-1]]
159
+ result.append(ParenthesisGroup(parenGroup))
160
+ stacklevel -= 1
161
+ continue
162
+ if stacklevel:
163
+ stacks[-1].append(token)
164
+ else:
165
+ result.append(token)
166
+ if stacklevel:
167
+ raise TokenError("Mismatched parentheses")
168
+ return result
169
+ return _inner
170
+
171
+
172
+ def _apply_functions(tokens: List[tUnion[TOKEN, ParenthesisGroup]], local_dict: DICT, global_dict: DICT):
173
+ """Convert a NAME token + ParenthesisGroup into an AppliedFunction.
174
+
175
+ Note that ParenthesisGroups, if not applied to any function, are
176
+ converted back into lists of tokens.
177
+
178
+ """
179
+ result: List[tUnion[TOKEN, AppliedFunction]] = []
180
+ symbol = None
181
+ for tok in tokens:
182
+ if isinstance(tok, ParenthesisGroup):
183
+ if symbol and _token_callable(symbol, local_dict, global_dict):
184
+ result[-1] = AppliedFunction(symbol, tok)
185
+ symbol = None
186
+ else:
187
+ result.extend(tok)
188
+ elif tok[0] == NAME:
189
+ symbol = tok
190
+ result.append(tok)
191
+ else:
192
+ symbol = None
193
+ result.append(tok)
194
+ return result
195
+
196
+
197
+ def _implicit_multiplication(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT):
198
+ """Implicitly adds '*' tokens.
199
+
200
+ Cases:
201
+
202
+ - Two AppliedFunctions next to each other ("sin(x)cos(x)")
203
+
204
+ - AppliedFunction next to an open parenthesis ("sin x (cos x + 1)")
205
+
206
+ - A close parenthesis next to an AppliedFunction ("(x+2)sin x")\
207
+
208
+ - A close parenthesis next to an open parenthesis ("(x+2)(x+3)")
209
+
210
+ - AppliedFunction next to an implicitly applied function ("sin(x)cos x")
211
+
212
+ """
213
+ result: List[tUnion[TOKEN, AppliedFunction]] = []
214
+ skip = False
215
+ for tok, nextTok in zip(tokens, tokens[1:]):
216
+ result.append(tok)
217
+ if skip:
218
+ skip = False
219
+ continue
220
+ if tok[0] == OP and tok[1] == '.' and nextTok[0] == NAME:
221
+ # Dotted name. Do not do implicit multiplication
222
+ skip = True
223
+ continue
224
+ if isinstance(tok, AppliedFunction):
225
+ if isinstance(nextTok, AppliedFunction):
226
+ result.append((OP, '*'))
227
+ elif nextTok == (OP, '('):
228
+ # Applied function followed by an open parenthesis
229
+ if tok.function[1] == "Function":
230
+ tok.function = (tok.function[0], 'Symbol')
231
+ result.append((OP, '*'))
232
+ elif nextTok[0] == NAME:
233
+ # Applied function followed by implicitly applied function
234
+ result.append((OP, '*'))
235
+ else:
236
+ if tok == (OP, ')'):
237
+ if isinstance(nextTok, AppliedFunction):
238
+ # Close parenthesis followed by an applied function
239
+ result.append((OP, '*'))
240
+ elif nextTok[0] == NAME:
241
+ # Close parenthesis followed by an implicitly applied function
242
+ result.append((OP, '*'))
243
+ elif nextTok == (OP, '('):
244
+ # Close parenthesis followed by an open parenthesis
245
+ result.append((OP, '*'))
246
+ elif tok[0] == NAME and not _token_callable(tok, local_dict, global_dict):
247
+ if isinstance(nextTok, AppliedFunction) or \
248
+ (nextTok[0] == NAME and _token_callable(nextTok, local_dict, global_dict)):
249
+ # Constant followed by (implicitly applied) function
250
+ result.append((OP, '*'))
251
+ elif nextTok == (OP, '('):
252
+ # Constant followed by parenthesis
253
+ result.append((OP, '*'))
254
+ elif nextTok[0] == NAME:
255
+ # Constant followed by constant
256
+ result.append((OP, '*'))
257
+ if tokens:
258
+ result.append(tokens[-1])
259
+ return result
260
+
261
+
262
+ def _implicit_application(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT):
263
+ """Adds parentheses as needed after functions."""
264
+ result: List[tUnion[TOKEN, AppliedFunction]] = []
265
+ appendParen = 0 # number of closing parentheses to add
266
+ skip = 0 # number of tokens to delay before adding a ')' (to
267
+ # capture **, ^, etc.)
268
+ exponentSkip = False # skipping tokens before inserting parentheses to
269
+ # work with function exponentiation
270
+ for tok, nextTok in zip(tokens, tokens[1:]):
271
+ result.append(tok)
272
+ if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]):
273
+ if _token_callable(tok, local_dict, global_dict, nextTok): # type: ignore
274
+ result.append((OP, '('))
275
+ appendParen += 1
276
+ # name followed by exponent - function exponentiation
277
+ elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'):
278
+ if _token_callable(tok, local_dict, global_dict): # type: ignore
279
+ exponentSkip = True
280
+ elif exponentSkip:
281
+ # if the last token added was an applied function (i.e. the
282
+ # power of the function exponent) OR a multiplication (as
283
+ # implicit multiplication would have added an extraneous
284
+ # multiplication)
285
+ if (isinstance(tok, AppliedFunction)
286
+ or (tok[0] == OP and tok[1] == '*')):
287
+ # don't add anything if the next token is a multiplication
288
+ # or if there's already a parenthesis (if parenthesis, still
289
+ # stop skipping tokens)
290
+ if not (nextTok[0] == OP and nextTok[1] == '*'):
291
+ if not(nextTok[0] == OP and nextTok[1] == '('):
292
+ result.append((OP, '('))
293
+ appendParen += 1
294
+ exponentSkip = False
295
+ elif appendParen:
296
+ if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'):
297
+ skip = 1
298
+ continue
299
+ if skip:
300
+ skip -= 1
301
+ continue
302
+ result.append((OP, ')'))
303
+ appendParen -= 1
304
+
305
+ if tokens:
306
+ result.append(tokens[-1])
307
+
308
+ if appendParen:
309
+ result.extend([(OP, ')')] * appendParen)
310
+ return result
311
+
312
+
313
+ def function_exponentiation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
314
+ """Allows functions to be exponentiated, e.g. ``cos**2(x)``.
315
+
316
+ Examples
317
+ ========
318
+
319
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
320
+ ... standard_transformations, function_exponentiation)
321
+ >>> transformations = standard_transformations + (function_exponentiation,)
322
+ >>> parse_expr('sin**4(x)', transformations=transformations)
323
+ sin(x)**4
324
+ """
325
+ result: List[TOKEN] = []
326
+ exponent: List[TOKEN] = []
327
+ consuming_exponent = False
328
+ level = 0
329
+ for tok, nextTok in zip(tokens, tokens[1:]):
330
+ if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**':
331
+ if _token_callable(tok, local_dict, global_dict):
332
+ consuming_exponent = True
333
+ elif consuming_exponent:
334
+ if tok[0] == NAME and tok[1] == 'Function':
335
+ tok = (NAME, 'Symbol')
336
+ exponent.append(tok)
337
+
338
+ # only want to stop after hitting )
339
+ if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(':
340
+ consuming_exponent = False
341
+ # if implicit multiplication was used, we may have )*( instead
342
+ if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(':
343
+ consuming_exponent = False
344
+ del exponent[-1]
345
+ continue
346
+ elif exponent and not consuming_exponent:
347
+ if tok[0] == OP:
348
+ if tok[1] == '(':
349
+ level += 1
350
+ elif tok[1] == ')':
351
+ level -= 1
352
+ if level == 0:
353
+ result.append(tok)
354
+ result.extend(exponent)
355
+ exponent = []
356
+ continue
357
+ result.append(tok)
358
+ if tokens:
359
+ result.append(tokens[-1])
360
+ if exponent:
361
+ result.extend(exponent)
362
+ return result
363
+
364
+
365
+ def split_symbols_custom(predicate: Callable[[str], bool]):
366
+ """Creates a transformation that splits symbol names.
367
+
368
+ ``predicate`` should return True if the symbol name is to be split.
369
+
370
+ For instance, to retain the default behavior but avoid splitting certain
371
+ symbol names, a predicate like this would work:
372
+
373
+
374
+ >>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable,
375
+ ... standard_transformations, implicit_multiplication,
376
+ ... split_symbols_custom)
377
+ >>> def can_split(symbol):
378
+ ... if symbol not in ('list', 'of', 'unsplittable', 'names'):
379
+ ... return _token_splittable(symbol)
380
+ ... return False
381
+ ...
382
+ >>> transformation = split_symbols_custom(can_split)
383
+ >>> parse_expr('unsplittable', transformations=standard_transformations +
384
+ ... (transformation, implicit_multiplication))
385
+ unsplittable
386
+ """
387
+ def _split_symbols(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
388
+ result: List[TOKEN] = []
389
+ split = False
390
+ split_previous=False
391
+
392
+ for tok in tokens:
393
+ if split_previous:
394
+ # throw out closing parenthesis of Symbol that was split
395
+ split_previous=False
396
+ continue
397
+ split_previous=False
398
+
399
+ if tok[0] == NAME and tok[1] in ['Symbol', 'Function']:
400
+ split = True
401
+
402
+ elif split and tok[0] == NAME:
403
+ symbol = tok[1][1:-1]
404
+
405
+ if predicate(symbol):
406
+ tok_type = result[-2][1] # Symbol or Function
407
+ del result[-2:] # Get rid of the call to Symbol
408
+
409
+ i = 0
410
+ while i < len(symbol):
411
+ char = symbol[i]
412
+ if char in local_dict or char in global_dict:
413
+ result.append((NAME, "%s" % char))
414
+ elif char.isdigit():
415
+ chars = [char]
416
+ for i in range(i + 1, len(symbol)):
417
+ if not symbol[i].isdigit():
418
+ i -= 1
419
+ break
420
+ chars.append(symbol[i])
421
+ char = ''.join(chars)
422
+ result.extend([(NAME, 'Number'), (OP, '('),
423
+ (NAME, "'%s'" % char), (OP, ')')])
424
+ else:
425
+ use = tok_type if i == len(symbol) else 'Symbol'
426
+ result.extend([(NAME, use), (OP, '('),
427
+ (NAME, "'%s'" % char), (OP, ')')])
428
+ i += 1
429
+
430
+ # Set split_previous=True so will skip
431
+ # the closing parenthesis of the original Symbol
432
+ split = False
433
+ split_previous = True
434
+ continue
435
+
436
+ else:
437
+ split = False
438
+
439
+ result.append(tok)
440
+
441
+ return result
442
+
443
+ return _split_symbols
444
+
445
+
446
+ #: Splits symbol names for implicit multiplication.
447
+ #:
448
+ #: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not
449
+ #: split Greek character names, so ``theta`` will *not* become
450
+ #: ``t*h*e*t*a``. Generally this should be used with
451
+ #: ``implicit_multiplication``.
452
+ split_symbols = split_symbols_custom(_token_splittable)
453
+
454
+
455
+ def implicit_multiplication(tokens: List[TOKEN], local_dict: DICT,
456
+ global_dict: DICT) -> List[TOKEN]:
457
+ """Makes the multiplication operator optional in most cases.
458
+
459
+ Use this before :func:`implicit_application`, otherwise expressions like
460
+ ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``.
461
+
462
+ Examples
463
+ ========
464
+
465
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
466
+ ... standard_transformations, implicit_multiplication)
467
+ >>> transformations = standard_transformations + (implicit_multiplication,)
468
+ >>> parse_expr('3 x y', transformations=transformations)
469
+ 3*x*y
470
+ """
471
+ # These are interdependent steps, so we don't expose them separately
472
+ res1 = _group_parentheses(implicit_multiplication)(tokens, local_dict, global_dict)
473
+ res2 = _apply_functions(res1, local_dict, global_dict)
474
+ res3 = _implicit_multiplication(res2, local_dict, global_dict)
475
+ result = _flatten(res3)
476
+ return result
477
+
478
+
479
+ def implicit_application(tokens: List[TOKEN], local_dict: DICT,
480
+ global_dict: DICT) -> List[TOKEN]:
481
+ """Makes parentheses optional in some cases for function calls.
482
+
483
+ Use this after :func:`implicit_multiplication`, otherwise expressions
484
+ like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than
485
+ ``sin(2*x)``.
486
+
487
+ Examples
488
+ ========
489
+
490
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
491
+ ... standard_transformations, implicit_application)
492
+ >>> transformations = standard_transformations + (implicit_application,)
493
+ >>> parse_expr('cot z + csc z', transformations=transformations)
494
+ cot(z) + csc(z)
495
+ """
496
+ res1 = _group_parentheses(implicit_application)(tokens, local_dict, global_dict)
497
+ res2 = _apply_functions(res1, local_dict, global_dict)
498
+ res3 = _implicit_application(res2, local_dict, global_dict)
499
+ result = _flatten(res3)
500
+ return result
501
+
502
+
503
+ def implicit_multiplication_application(result: List[TOKEN], local_dict: DICT,
504
+ global_dict: DICT) -> List[TOKEN]:
505
+ """Allows a slightly relaxed syntax.
506
+
507
+ - Parentheses for single-argument method calls are optional.
508
+
509
+ - Multiplication is implicit.
510
+
511
+ - Symbol names can be split (i.e. spaces are not needed between
512
+ symbols).
513
+
514
+ - Functions can be exponentiated.
515
+
516
+ Examples
517
+ ========
518
+
519
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
520
+ ... standard_transformations, implicit_multiplication_application)
521
+ >>> parse_expr("10sin**2 x**2 + 3xyz + tan theta",
522
+ ... transformations=(standard_transformations +
523
+ ... (implicit_multiplication_application,)))
524
+ 3*x*y*z + 10*sin(x**2)**2 + tan(theta)
525
+
526
+ """
527
+ for step in (split_symbols, implicit_multiplication,
528
+ implicit_application, function_exponentiation):
529
+ result = step(result, local_dict, global_dict)
530
+
531
+ return result
532
+
533
+
534
+ def auto_symbol(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
535
+ """Inserts calls to ``Symbol``/``Function`` for undefined variables."""
536
+ result: List[TOKEN] = []
537
+ prevTok = (-1, '')
538
+
539
+ tokens.append((-1, '')) # so zip traverses all tokens
540
+ for tok, nextTok in zip(tokens, tokens[1:]):
541
+ tokNum, tokVal = tok
542
+ nextTokNum, nextTokVal = nextTok
543
+ if tokNum == NAME:
544
+ name = tokVal
545
+
546
+ if (name in ['True', 'False', 'None']
547
+ or iskeyword(name)
548
+ # Don't convert attribute access
549
+ or (prevTok[0] == OP and prevTok[1] == '.')
550
+ # Don't convert keyword arguments
551
+ or (prevTok[0] == OP and prevTok[1] in ('(', ',')
552
+ and nextTokNum == OP and nextTokVal == '=')
553
+ # the name has already been defined
554
+ or name in local_dict and local_dict[name] is not null):
555
+ result.append((NAME, name))
556
+ continue
557
+ elif name in local_dict:
558
+ local_dict.setdefault(null, set()).add(name)
559
+ if nextTokVal == '(':
560
+ local_dict[name] = Function(name)
561
+ else:
562
+ local_dict[name] = Symbol(name)
563
+ result.append((NAME, name))
564
+ continue
565
+ elif name in global_dict:
566
+ obj = global_dict[name]
567
+ if isinstance(obj, (AssumptionKeys, Basic, type)) or callable(obj):
568
+ result.append((NAME, name))
569
+ continue
570
+
571
+ result.extend([
572
+ (NAME, 'Symbol' if nextTokVal != '(' else 'Function'),
573
+ (OP, '('),
574
+ (NAME, repr(str(name))),
575
+ (OP, ')'),
576
+ ])
577
+ else:
578
+ result.append((tokNum, tokVal))
579
+
580
+ prevTok = (tokNum, tokVal)
581
+
582
+ return result
583
+
584
+
585
+ def lambda_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
586
+ """Substitutes "lambda" with its SymPy equivalent Lambda().
587
+ However, the conversion does not take place if only "lambda"
588
+ is passed because that is a syntax error.
589
+
590
+ """
591
+ result: List[TOKEN] = []
592
+ flag = False
593
+ toknum, tokval = tokens[0]
594
+ tokLen = len(tokens)
595
+
596
+ if toknum == NAME and tokval == 'lambda':
597
+ if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE:
598
+ # In Python 3.6.7+, inputs without a newline get NEWLINE added to
599
+ # the tokens
600
+ result.extend(tokens)
601
+ elif tokLen > 2:
602
+ result.extend([
603
+ (NAME, 'Lambda'),
604
+ (OP, '('),
605
+ (OP, '('),
606
+ (OP, ')'),
607
+ (OP, ')'),
608
+ ])
609
+ for tokNum, tokVal in tokens[1:]:
610
+ if tokNum == OP and tokVal == ':':
611
+ tokVal = ','
612
+ flag = True
613
+ if not flag and tokNum == OP and tokVal in ('*', '**'):
614
+ raise TokenError("Starred arguments in lambda not supported")
615
+ if flag:
616
+ result.insert(-1, (tokNum, tokVal))
617
+ else:
618
+ result.insert(-2, (tokNum, tokVal))
619
+ else:
620
+ result.extend(tokens)
621
+
622
+ return result
623
+
624
+
625
+ def factorial_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
626
+ """Allows standard notation for factorial."""
627
+ result: List[TOKEN] = []
628
+ nfactorial = 0
629
+ for toknum, tokval in tokens:
630
+ if toknum == OP and tokval == "!":
631
+ # In Python 3.12 "!" are OP instead of ERRORTOKEN
632
+ nfactorial += 1
633
+ elif toknum == ERRORTOKEN:
634
+ op = tokval
635
+ if op == '!':
636
+ nfactorial += 1
637
+ else:
638
+ nfactorial = 0
639
+ result.append((OP, op))
640
+ else:
641
+ if nfactorial == 1:
642
+ result = _add_factorial_tokens('factorial', result)
643
+ elif nfactorial == 2:
644
+ result = _add_factorial_tokens('factorial2', result)
645
+ elif nfactorial > 2:
646
+ raise TokenError
647
+ nfactorial = 0
648
+ result.append((toknum, tokval))
649
+ return result
650
+
651
+
652
+ def convert_xor(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
653
+ """Treats XOR, ``^``, as exponentiation, ``**``."""
654
+ result: List[TOKEN] = []
655
+ for toknum, tokval in tokens:
656
+ if toknum == OP:
657
+ if tokval == '^':
658
+ result.append((OP, '**'))
659
+ else:
660
+ result.append((toknum, tokval))
661
+ else:
662
+ result.append((toknum, tokval))
663
+
664
+ return result
665
+
666
+
667
+ def repeated_decimals(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
668
+ """
669
+ Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90)
670
+
671
+ Run this before auto_number.
672
+
673
+ """
674
+ result: List[TOKEN] = []
675
+
676
+ def is_digit(s):
677
+ return all(i in '0123456789_' for i in s)
678
+
679
+ # num will running match any DECIMAL [ INTEGER ]
680
+ num: List[TOKEN] = []
681
+ for toknum, tokval in tokens:
682
+ if toknum == NUMBER:
683
+ if (not num and '.' in tokval and 'e' not in tokval.lower() and
684
+ 'j' not in tokval.lower()):
685
+ num.append((toknum, tokval))
686
+ elif is_digit(tokval)and len(num) == 2:
687
+ num.append((toknum, tokval))
688
+ elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]):
689
+ # Python 2 tokenizes 00123 as '00', '123'
690
+ # Python 3 tokenizes 01289 as '012', '89'
691
+ num.append((toknum, tokval))
692
+ else:
693
+ num = []
694
+ elif toknum == OP:
695
+ if tokval == '[' and len(num) == 1:
696
+ num.append((OP, tokval))
697
+ elif tokval == ']' and len(num) >= 3:
698
+ num.append((OP, tokval))
699
+ elif tokval == '.' and not num:
700
+ # handle .[1]
701
+ num.append((NUMBER, '0.'))
702
+ else:
703
+ num = []
704
+ else:
705
+ num = []
706
+
707
+ result.append((toknum, tokval))
708
+
709
+ if num and num[-1][1] == ']':
710
+ # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post,
711
+ # and d/e = repetend
712
+ result = result[:-len(num)]
713
+ pre, post = num[0][1].split('.')
714
+ repetend = num[2][1]
715
+ if len(num) == 5:
716
+ repetend += num[3][1]
717
+
718
+ pre = pre.replace('_', '')
719
+ post = post.replace('_', '')
720
+ repetend = repetend.replace('_', '')
721
+
722
+ zeros = '0'*len(post)
723
+ post, repetends = [w.lstrip('0') for w in [post, repetend]]
724
+ # or else interpreted as octal
725
+
726
+ a = pre or '0'
727
+ b, c = post or '0', '1' + zeros
728
+ d, e = repetends, ('9'*len(repetend)) + zeros
729
+
730
+ seq = [
731
+ (OP, '('),
732
+ (NAME, 'Integer'),
733
+ (OP, '('),
734
+ (NUMBER, a),
735
+ (OP, ')'),
736
+ (OP, '+'),
737
+ (NAME, 'Rational'),
738
+ (OP, '('),
739
+ (NUMBER, b),
740
+ (OP, ','),
741
+ (NUMBER, c),
742
+ (OP, ')'),
743
+ (OP, '+'),
744
+ (NAME, 'Rational'),
745
+ (OP, '('),
746
+ (NUMBER, d),
747
+ (OP, ','),
748
+ (NUMBER, e),
749
+ (OP, ')'),
750
+ (OP, ')'),
751
+ ]
752
+ result.extend(seq)
753
+ num = []
754
+
755
+ return result
756
+
757
+
758
+ def auto_number(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
759
+ """
760
+ Converts numeric literals to use SymPy equivalents.
761
+
762
+ Complex numbers use ``I``, integer literals use ``Integer``, and float
763
+ literals use ``Float``.
764
+
765
+ """
766
+ result: List[TOKEN] = []
767
+
768
+ for toknum, tokval in tokens:
769
+ if toknum == NUMBER:
770
+ number = tokval
771
+ postfix = []
772
+
773
+ if number.endswith(('j', 'J')):
774
+ number = number[:-1]
775
+ postfix = [(OP, '*'), (NAME, 'I')]
776
+
777
+ if '.' in number or (('e' in number or 'E' in number) and
778
+ not (number.startswith(('0x', '0X')))):
779
+ seq = [(NAME, 'Float'), (OP, '('),
780
+ (NUMBER, repr(str(number))), (OP, ')')]
781
+ else:
782
+ seq = [(NAME, 'Integer'), (OP, '('), (
783
+ NUMBER, number), (OP, ')')]
784
+
785
+ result.extend(seq + postfix)
786
+ else:
787
+ result.append((toknum, tokval))
788
+
789
+ return result
790
+
791
+
792
+ def rationalize(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
793
+ """Converts floats into ``Rational``. Run AFTER ``auto_number``."""
794
+ result: List[TOKEN] = []
795
+ passed_float = False
796
+ for toknum, tokval in tokens:
797
+ if toknum == NAME:
798
+ if tokval == 'Float':
799
+ passed_float = True
800
+ tokval = 'Rational'
801
+ result.append((toknum, tokval))
802
+ elif passed_float == True and toknum == NUMBER:
803
+ passed_float = False
804
+ result.append((STRING, tokval))
805
+ else:
806
+ result.append((toknum, tokval))
807
+
808
+ return result
809
+
810
+
811
+ def _transform_equals_sign(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT):
812
+ """Transforms the equals sign ``=`` to instances of Eq.
813
+
814
+ This is a helper function for ``convert_equals_signs``.
815
+ Works with expressions containing one equals sign and no
816
+ nesting. Expressions like ``(1=2)=False`` will not work with this
817
+ and should be used with ``convert_equals_signs``.
818
+
819
+ Examples: 1=2 to Eq(1,2)
820
+ 1*2=x to Eq(1*2, x)
821
+
822
+ This does not deal with function arguments yet.
823
+
824
+ """
825
+ result: List[TOKEN] = []
826
+ if (OP, "=") in tokens:
827
+ result.append((NAME, "Eq"))
828
+ result.append((OP, "("))
829
+ for token in tokens:
830
+ if token == (OP, "="):
831
+ result.append((OP, ","))
832
+ continue
833
+ result.append(token)
834
+ result.append((OP, ")"))
835
+ else:
836
+ result = tokens
837
+ return result
838
+
839
+
840
+ def convert_equals_signs(tokens: List[TOKEN], local_dict: DICT,
841
+ global_dict: DICT) -> List[TOKEN]:
842
+ """ Transforms all the equals signs ``=`` to instances of Eq.
843
+
844
+ Parses the equals signs in the expression and replaces them with
845
+ appropriate Eq instances. Also works with nested equals signs.
846
+
847
+ Does not yet play well with function arguments.
848
+ For example, the expression ``(x=y)`` is ambiguous and can be interpreted
849
+ as x being an argument to a function and ``convert_equals_signs`` will not
850
+ work for this.
851
+
852
+ See also
853
+ ========
854
+ convert_equality_operators
855
+
856
+ Examples
857
+ ========
858
+
859
+ >>> from sympy.parsing.sympy_parser import (parse_expr,
860
+ ... standard_transformations, convert_equals_signs)
861
+ >>> parse_expr("1*2=x", transformations=(
862
+ ... standard_transformations + (convert_equals_signs,)))
863
+ Eq(2, x)
864
+ >>> parse_expr("(1*2=x)=False", transformations=(
865
+ ... standard_transformations + (convert_equals_signs,)))
866
+ Eq(Eq(2, x), False)
867
+
868
+ """
869
+ res1 = _group_parentheses(convert_equals_signs)(tokens, local_dict, global_dict)
870
+ res2 = _apply_functions(res1, local_dict, global_dict)
871
+ res3 = _transform_equals_sign(res2, local_dict, global_dict)
872
+ result = _flatten(res3)
873
+ return result
874
+
875
+
876
+ #: Standard transformations for :func:`parse_expr`.
877
+ #: Inserts calls to :class:`~.Symbol`, :class:`~.Integer`, and other SymPy
878
+ #: datatypes and allows the use of standard factorial notation (e.g. ``x!``).
879
+ standard_transformations: tTuple[TRANS, ...] \
880
+ = (lambda_notation, auto_symbol, repeated_decimals, auto_number,
881
+ factorial_notation)
882
+
883
+
884
+ def stringify_expr(s: str, local_dict: DICT, global_dict: DICT,
885
+ transformations: tTuple[TRANS, ...]) -> str:
886
+ """
887
+ Converts the string ``s`` to Python code, in ``local_dict``
888
+
889
+ Generally, ``parse_expr`` should be used.
890
+ """
891
+
892
+ tokens = []
893
+ input_code = StringIO(s.strip())
894
+ for toknum, tokval, _, _, _ in generate_tokens(input_code.readline):
895
+ tokens.append((toknum, tokval))
896
+
897
+ for transform in transformations:
898
+ tokens = transform(tokens, local_dict, global_dict)
899
+
900
+ return untokenize(tokens)
901
+
902
+
903
+ def eval_expr(code, local_dict: DICT, global_dict: DICT):
904
+ """
905
+ Evaluate Python code generated by ``stringify_expr``.
906
+
907
+ Generally, ``parse_expr`` should be used.
908
+ """
909
+ expr = eval(
910
+ code, global_dict, local_dict) # take local objects in preference
911
+ return expr
912
+
913
+
914
+ def parse_expr(s: str, local_dict: Optional[DICT] = None,
915
+ transformations: tUnion[tTuple[TRANS, ...], str] \
916
+ = standard_transformations,
917
+ global_dict: Optional[DICT] = None, evaluate=True):
918
+ """Converts the string ``s`` to a SymPy expression, in ``local_dict``.
919
+
920
+ Parameters
921
+ ==========
922
+
923
+ s : str
924
+ The string to parse.
925
+
926
+ local_dict : dict, optional
927
+ A dictionary of local variables to use when parsing.
928
+
929
+ global_dict : dict, optional
930
+ A dictionary of global variables. By default, this is initialized
931
+ with ``from sympy import *``; provide this parameter to override
932
+ this behavior (for instance, to parse ``"Q & S"``).
933
+
934
+ transformations : tuple or str
935
+ A tuple of transformation functions used to modify the tokens of the
936
+ parsed expression before evaluation. The default transformations
937
+ convert numeric literals into their SymPy equivalents, convert
938
+ undefined variables into SymPy symbols, and allow the use of standard
939
+ mathematical factorial notation (e.g. ``x!``). Selection via
940
+ string is available (see below).
941
+
942
+ evaluate : bool, optional
943
+ When False, the order of the arguments will remain as they were in the
944
+ string and automatic simplification that would normally occur is
945
+ suppressed. (see examples)
946
+
947
+ Examples
948
+ ========
949
+
950
+ >>> from sympy.parsing.sympy_parser import parse_expr
951
+ >>> parse_expr("1/2")
952
+ 1/2
953
+ >>> type(_)
954
+ <class 'sympy.core.numbers.Half'>
955
+ >>> from sympy.parsing.sympy_parser import standard_transformations,\\
956
+ ... implicit_multiplication_application
957
+ >>> transformations = (standard_transformations +
958
+ ... (implicit_multiplication_application,))
959
+ >>> parse_expr("2x", transformations=transformations)
960
+ 2*x
961
+
962
+ When evaluate=False, some automatic simplifications will not occur:
963
+
964
+ >>> parse_expr("2**3"), parse_expr("2**3", evaluate=False)
965
+ (8, 2**3)
966
+
967
+ In addition the order of the arguments will not be made canonical.
968
+ This feature allows one to tell exactly how the expression was entered:
969
+
970
+ >>> a = parse_expr('1 + x', evaluate=False)
971
+ >>> b = parse_expr('x + 1', evaluate=0)
972
+ >>> a == b
973
+ False
974
+ >>> a.args
975
+ (1, x)
976
+ >>> b.args
977
+ (x, 1)
978
+
979
+ Note, however, that when these expressions are printed they will
980
+ appear the same:
981
+
982
+ >>> assert str(a) == str(b)
983
+
984
+ As a convenience, transformations can be seen by printing ``transformations``:
985
+
986
+ >>> from sympy.parsing.sympy_parser import transformations
987
+
988
+ >>> print(transformations)
989
+ 0: lambda_notation
990
+ 1: auto_symbol
991
+ 2: repeated_decimals
992
+ 3: auto_number
993
+ 4: factorial_notation
994
+ 5: implicit_multiplication_application
995
+ 6: convert_xor
996
+ 7: implicit_application
997
+ 8: implicit_multiplication
998
+ 9: convert_equals_signs
999
+ 10: function_exponentiation
1000
+ 11: rationalize
1001
+
1002
+ The ``T`` object provides a way to select these transformations:
1003
+
1004
+ >>> from sympy.parsing.sympy_parser import T
1005
+
1006
+ If you print it, you will see the same list as shown above.
1007
+
1008
+ >>> str(T) == str(transformations)
1009
+ True
1010
+
1011
+ Standard slicing will return a tuple of transformations:
1012
+
1013
+ >>> T[:5] == standard_transformations
1014
+ True
1015
+
1016
+ So ``T`` can be used to specify the parsing transformations:
1017
+
1018
+ >>> parse_expr("2x", transformations=T[:5])
1019
+ Traceback (most recent call last):
1020
+ ...
1021
+ SyntaxError: invalid syntax
1022
+ >>> parse_expr("2x", transformations=T[:6])
1023
+ 2*x
1024
+ >>> parse_expr('.3', transformations=T[3, 11])
1025
+ 3/10
1026
+ >>> parse_expr('.3x', transformations=T[:])
1027
+ 3*x/10
1028
+
1029
+ As a further convenience, strings 'implicit' and 'all' can be used
1030
+ to select 0-5 and all the transformations, respectively.
1031
+
1032
+ >>> parse_expr('.3x', transformations='all')
1033
+ 3*x/10
1034
+
1035
+ See Also
1036
+ ========
1037
+
1038
+ stringify_expr, eval_expr, standard_transformations,
1039
+ implicit_multiplication_application
1040
+
1041
+ """
1042
+
1043
+ if local_dict is None:
1044
+ local_dict = {}
1045
+ elif not isinstance(local_dict, dict):
1046
+ raise TypeError('expecting local_dict to be a dict')
1047
+ elif null in local_dict:
1048
+ raise ValueError('cannot use "" in local_dict')
1049
+
1050
+ if global_dict is None:
1051
+ global_dict = {}
1052
+ exec('from sympy import *', global_dict)
1053
+
1054
+ builtins_dict = vars(builtins)
1055
+ for name, obj in builtins_dict.items():
1056
+ if isinstance(obj, types.BuiltinFunctionType):
1057
+ global_dict[name] = obj
1058
+ global_dict['max'] = Max
1059
+ global_dict['min'] = Min
1060
+
1061
+ elif not isinstance(global_dict, dict):
1062
+ raise TypeError('expecting global_dict to be a dict')
1063
+
1064
+ transformations = transformations or ()
1065
+ if isinstance(transformations, str):
1066
+ if transformations == 'all':
1067
+ _transformations = T[:]
1068
+ elif transformations == 'implicit':
1069
+ _transformations = T[:6]
1070
+ else:
1071
+ raise ValueError('unknown transformation group name')
1072
+ else:
1073
+ _transformations = transformations
1074
+
1075
+ code = stringify_expr(s, local_dict, global_dict, _transformations)
1076
+
1077
+ if not evaluate:
1078
+ code = compile(evaluateFalse(code), '<string>', 'eval') # type: ignore
1079
+
1080
+ try:
1081
+ rv = eval_expr(code, local_dict, global_dict)
1082
+ # restore neutral definitions for names
1083
+ for i in local_dict.pop(null, ()):
1084
+ local_dict[i] = null
1085
+ return rv
1086
+ except Exception as e:
1087
+ # restore neutral definitions for names
1088
+ for i in local_dict.pop(null, ()):
1089
+ local_dict[i] = null
1090
+ raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}")
1091
+
1092
+
1093
+ def evaluateFalse(s: str):
1094
+ """
1095
+ Replaces operators with the SymPy equivalent and sets evaluate=False.
1096
+ """
1097
+ node = ast.parse(s)
1098
+ transformed_node = EvaluateFalseTransformer().visit(node)
1099
+ # node is a Module, we want an Expression
1100
+ transformed_node = ast.Expression(transformed_node.body[0].value)
1101
+
1102
+ return ast.fix_missing_locations(transformed_node)
1103
+
1104
+
1105
+ class EvaluateFalseTransformer(ast.NodeTransformer):
1106
+ operators = {
1107
+ ast.Add: 'Add',
1108
+ ast.Mult: 'Mul',
1109
+ ast.Pow: 'Pow',
1110
+ ast.Sub: 'Add',
1111
+ ast.Div: 'Mul',
1112
+ ast.BitOr: 'Or',
1113
+ ast.BitAnd: 'And',
1114
+ ast.BitXor: 'Not',
1115
+ }
1116
+ functions = (
1117
+ 'Abs', 'im', 're', 'sign', 'arg', 'conjugate',
1118
+ 'acos', 'acot', 'acsc', 'asec', 'asin', 'atan',
1119
+ 'acosh', 'acoth', 'acsch', 'asech', 'asinh', 'atanh',
1120
+ 'cos', 'cot', 'csc', 'sec', 'sin', 'tan',
1121
+ 'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh',
1122
+ 'exp', 'ln', 'log', 'sqrt', 'cbrt',
1123
+ )
1124
+
1125
+ relational_operators = {
1126
+ ast.NotEq: 'Ne',
1127
+ ast.Lt: 'Lt',
1128
+ ast.LtE: 'Le',
1129
+ ast.Gt: 'Gt',
1130
+ ast.GtE: 'Ge',
1131
+ ast.Eq: 'Eq'
1132
+ }
1133
+ def visit_Compare(self, node):
1134
+ if node.ops[0].__class__ in self.relational_operators:
1135
+ sympy_class = self.relational_operators[node.ops[0].__class__]
1136
+ right = self.visit(node.comparators[0])
1137
+ left = self.visit(node.left)
1138
+ new_node = ast.Call(
1139
+ func=ast.Name(id=sympy_class, ctx=ast.Load()),
1140
+ args=[left, right],
1141
+ keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
1142
+ )
1143
+ return new_node
1144
+ return node
1145
+
1146
+ def flatten(self, args, func):
1147
+ result = []
1148
+ for arg in args:
1149
+ if isinstance(arg, ast.Call):
1150
+ arg_func = arg.func
1151
+ if isinstance(arg_func, ast.Call):
1152
+ arg_func = arg_func.func
1153
+ if arg_func.id == func:
1154
+ result.extend(self.flatten(arg.args, func))
1155
+ else:
1156
+ result.append(arg)
1157
+ else:
1158
+ result.append(arg)
1159
+ return result
1160
+
1161
+ def visit_BinOp(self, node):
1162
+ if node.op.__class__ in self.operators:
1163
+ sympy_class = self.operators[node.op.__class__]
1164
+ right = self.visit(node.right)
1165
+ left = self.visit(node.left)
1166
+
1167
+ rev = False
1168
+ if isinstance(node.op, ast.Sub):
1169
+ right = ast.Call(
1170
+ func=ast.Name(id='Mul', ctx=ast.Load()),
1171
+ args=[ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1)), right],
1172
+ keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
1173
+ )
1174
+ elif isinstance(node.op, ast.Div):
1175
+ if isinstance(node.left, ast.UnaryOp):
1176
+ left, right = right, left
1177
+ rev = True
1178
+ left = ast.Call(
1179
+ func=ast.Name(id='Pow', ctx=ast.Load()),
1180
+ args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1))],
1181
+ keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
1182
+ )
1183
+ else:
1184
+ right = ast.Call(
1185
+ func=ast.Name(id='Pow', ctx=ast.Load()),
1186
+ args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Constant(1))],
1187
+ keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
1188
+ )
1189
+
1190
+ if rev: # undo reversal
1191
+ left, right = right, left
1192
+ new_node = ast.Call(
1193
+ func=ast.Name(id=sympy_class, ctx=ast.Load()),
1194
+ args=[left, right],
1195
+ keywords=[ast.keyword(arg='evaluate', value=ast.Constant(value=False))]
1196
+ )
1197
+
1198
+ if sympy_class in ('Add', 'Mul'):
1199
+ # Denest Add or Mul as appropriate
1200
+ new_node.args = self.flatten(new_node.args, sympy_class)
1201
+
1202
+ return new_node
1203
+ return node
1204
+
1205
+ def visit_Call(self, node):
1206
+ new_node = self.generic_visit(node)
1207
+ if isinstance(node.func, ast.Name) and node.func.id in self.functions:
1208
+ new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.Constant(value=False)))
1209
+ return new_node
1210
+
1211
+
1212
+ _transformation = { # items can be added but never re-ordered
1213
+ 0: lambda_notation,
1214
+ 1: auto_symbol,
1215
+ 2: repeated_decimals,
1216
+ 3: auto_number,
1217
+ 4: factorial_notation,
1218
+ 5: implicit_multiplication_application,
1219
+ 6: convert_xor,
1220
+ 7: implicit_application,
1221
+ 8: implicit_multiplication,
1222
+ 9: convert_equals_signs,
1223
+ 10: function_exponentiation,
1224
+ 11: rationalize}
1225
+
1226
+ transformations = '\n'.join('%s: %s' % (i, func_name(f)) for i, f in _transformation.items())
1227
+
1228
+
1229
+ class _T():
1230
+ """class to retrieve transformations from a given slice
1231
+
1232
+ EXAMPLES
1233
+ ========
1234
+
1235
+ >>> from sympy.parsing.sympy_parser import T, standard_transformations
1236
+ >>> assert T[:5] == standard_transformations
1237
+ """
1238
+ def __init__(self):
1239
+ self.N = len(_transformation)
1240
+
1241
+ def __str__(self):
1242
+ return transformations
1243
+
1244
+ def __getitem__(self, t):
1245
+ if not type(t) is tuple:
1246
+ t = (t,)
1247
+ i = []
1248
+ for ti in t:
1249
+ if type(ti) is int:
1250
+ i.append(range(self.N)[ti])
1251
+ elif type(ti) is slice:
1252
+ i.extend(range(*ti.indices(self.N)))
1253
+ else:
1254
+ raise TypeError('unexpected slice arg')
1255
+ return tuple([_transformation[_] for _ in i])
1256
+
1257
+ T = _T()