applied-ai-018 commited on
Commit
0f57d4e
·
verified ·
1 Parent(s): 8515497

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. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/factor_.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/modular.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc +0 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc +0 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc +0 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_elliptic_curve.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_qs.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_residue.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py +133 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py +20 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py +250 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_primetest.py +159 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_qs.py +124 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/tensor/__init__.py +23 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc +0 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/functions.cpython-310.pyc +0 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc +0 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/toperators.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/__init__.py +271 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/array_comprehension.py +399 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py +129 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/arrayop.py +528 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py +206 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/mutable_ndim_array.py +13 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/ndim_array.py +600 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/sparse_ndim_array.py +196 -0
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.51 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc ADDED
Binary file (5.13 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc ADDED
Binary file (9.17 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc ADDED
Binary file (3.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc ADDED
Binary file (9.12 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc ADDED
Binary file (6.55 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/elliptic_curve.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/factor_.cpython-310.pyc ADDED
Binary file (65.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc ADDED
Binary file (26.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/modular.cpython-310.pyc ADDED
Binary file (7.43 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc ADDED
Binary file (4.51 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc ADDED
Binary file (4.81 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc ADDED
Binary file (34.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_bbp_pi.cpython-310.pyc ADDED
Binary file (9.52 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_continued_fraction.cpython-310.pyc ADDED
Binary file (3.92 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_digits.cpython-310.pyc ADDED
Binary file (2.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_ecm.cpython-310.pyc ADDED
Binary file (2.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_egyptian_fraction.cpython-310.pyc ADDED
Binary file (2.76 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_elliptic_curve.cpython-310.pyc ADDED
Binary file (742 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_factor_.cpython-310.pyc ADDED
Binary file (26.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_generate.cpython-310.pyc ADDED
Binary file (10.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_modular.cpython-310.pyc ADDED
Binary file (1.89 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_multinomial.cpython-310.pyc ADDED
Binary file (2.69 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_partitions.cpython-310.pyc ADDED
Binary file (858 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_primetest.cpython-310.pyc ADDED
Binary file (6.08 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_qs.cpython-310.pyc ADDED
Binary file (4.85 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/__pycache__/test_residue.cpython-310.pyc ADDED
Binary file (11.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_bbp_pi.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.random import randint
2
+
3
+ from sympy.ntheory.bbp_pi import pi_hex_digits
4
+ from sympy.testing.pytest import raises
5
+
6
+
7
+ # http://www.herongyang.com/Cryptography/Blowfish-First-8366-Hex-Digits-of-PI.html
8
+ # There are actually 8336 listed there; with the prepended 3 there are 8337
9
+ # below
10
+ dig=''.join('''
11
+ 3243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89452821e638d013
12
+ 77be5466cf34e90c6cc0ac29b7c97c50dd3f84d5b5b54709179216d5d98979fb1bd1310ba698dfb5
13
+ ac2ffd72dbd01adfb7b8e1afed6a267e96ba7c9045f12c7f9924a19947b3916cf70801f2e2858efc
14
+ 16636920d871574e69a458fea3f4933d7e0d95748f728eb658718bcd5882154aee7b54a41dc25a59
15
+ b59c30d5392af26013c5d1b023286085f0ca417918b8db38ef8e79dcb0603a180e6c9e0e8bb01e8a
16
+ 3ed71577c1bd314b2778af2fda55605c60e65525f3aa55ab945748986263e8144055ca396a2aab10
17
+ b6b4cc5c341141e8cea15486af7c72e993b3ee1411636fbc2a2ba9c55d741831f6ce5c3e169b8793
18
+ 1eafd6ba336c24cf5c7a325381289586773b8f48986b4bb9afc4bfe81b6628219361d809ccfb21a9
19
+ 91487cac605dec8032ef845d5de98575b1dc262302eb651b8823893e81d396acc50f6d6ff383f442
20
+ 392e0b4482a484200469c8f04a9e1f9b5e21c66842f6e96c9a670c9c61abd388f06a51a0d2d8542f
21
+ 68960fa728ab5133a36eef0b6c137a3be4ba3bf0507efb2a98a1f1651d39af017666ca593e82430e
22
+ 888cee8619456f9fb47d84a5c33b8b5ebee06f75d885c12073401a449f56c16aa64ed3aa62363f77
23
+ 061bfedf72429b023d37d0d724d00a1248db0fead349f1c09b075372c980991b7b25d479d8f6e8de
24
+ f7e3fe501ab6794c3b976ce0bd04c006bac1a94fb6409f60c45e5c9ec2196a246368fb6faf3e6c53
25
+ b51339b2eb3b52ec6f6dfc511f9b30952ccc814544af5ebd09bee3d004de334afd660f2807192e4b
26
+ b3c0cba85745c8740fd20b5f39b9d3fbdb5579c0bd1a60320ad6a100c6402c7279679f25fefb1fa3
27
+ cc8ea5e9f8db3222f83c7516dffd616b152f501ec8ad0552ab323db5fafd23876053317b483e00df
28
+ 829e5c57bbca6f8ca01a87562edf1769dbd542a8f6287effc3ac6732c68c4f5573695b27b0bbca58
29
+ c8e1ffa35db8f011a010fa3d98fd2183b84afcb56c2dd1d35b9a53e479b6f84565d28e49bc4bfb97
30
+ 90e1ddf2daa4cb7e3362fb1341cee4c6e8ef20cada36774c01d07e9efe2bf11fb495dbda4dae9091
31
+ 98eaad8e716b93d5a0d08ed1d0afc725e08e3c5b2f8e7594b78ff6e2fbf2122b648888b812900df0
32
+ 1c4fad5ea0688fc31cd1cff191b3a8c1ad2f2f2218be0e1777ea752dfe8b021fa1e5a0cc0fb56f74
33
+ e818acf3d6ce89e299b4a84fe0fd13e0b77cc43b81d2ada8d9165fa2668095770593cc7314211a14
34
+ 77e6ad206577b5fa86c75442f5fb9d35cfebcdaf0c7b3e89a0d6411bd3ae1e7e4900250e2d2071b3
35
+ 5e226800bb57b8e0af2464369bf009b91e5563911d59dfa6aa78c14389d95a537f207d5ba202e5b9
36
+ c5832603766295cfa911c819684e734a41b3472dca7b14a94a1b5100529a532915d60f573fbc9bc6
37
+ e42b60a47681e6740008ba6fb5571be91ff296ec6b2a0dd915b6636521e7b9f9b6ff34052ec58556
38
+ 6453b02d5da99f8fa108ba47996e85076a4b7a70e9b5b32944db75092ec4192623ad6ea6b049a7df
39
+ 7d9cee60b88fedb266ecaa8c71699a17ff5664526cc2b19ee1193602a575094c29a0591340e4183a
40
+ 3e3f54989a5b429d656b8fe4d699f73fd6a1d29c07efe830f54d2d38e6f0255dc14cdd20868470eb
41
+ 266382e9c6021ecc5e09686b3f3ebaefc93c9718146b6a70a1687f358452a0e286b79c5305aa5007
42
+ 373e07841c7fdeae5c8e7d44ec5716f2b8b03ada37f0500c0df01c1f040200b3ffae0cf51a3cb574
43
+ b225837a58dc0921bdd19113f97ca92ff69432477322f547013ae5e58137c2dadcc8b576349af3dd
44
+ a7a94461460fd0030eecc8c73ea4751e41e238cd993bea0e2f3280bba1183eb3314e548b384f6db9
45
+ 086f420d03f60a04bf2cb8129024977c795679b072bcaf89afde9a771fd9930810b38bae12dccf3f
46
+ 2e5512721f2e6b7124501adde69f84cd877a5847187408da17bc9f9abce94b7d8cec7aec3adb851d
47
+ fa63094366c464c3d2ef1c18473215d908dd433b3724c2ba1612a14d432a65c45150940002133ae4
48
+ dd71dff89e10314e5581ac77d65f11199b043556f1d7a3c76b3c11183b5924a509f28fe6ed97f1fb
49
+ fa9ebabf2c1e153c6e86e34570eae96fb1860e5e0a5a3e2ab3771fe71c4e3d06fa2965dcb999e71d
50
+ 0f803e89d65266c8252e4cc9789c10b36ac6150eba94e2ea78a5fc3c531e0a2df4f2f74ea7361d2b
51
+ 3d1939260f19c279605223a708f71312b6ebadfe6eeac31f66e3bc4595a67bc883b17f37d1018cff
52
+ 28c332ddefbe6c5aa56558218568ab9802eecea50fdb2f953b2aef7dad5b6e2f841521b628290761
53
+ 70ecdd4775619f151013cca830eb61bd960334fe1eaa0363cfb5735c904c70a239d59e9e0bcbaade
54
+ 14eecc86bc60622ca79cab5cabb2f3846e648b1eaf19bdf0caa02369b9655abb5040685a323c2ab4
55
+ b3319ee9d5c021b8f79b540b19875fa09995f7997e623d7da8f837889a97e32d7711ed935f166812
56
+ 810e358829c7e61fd696dedfa17858ba9957f584a51b2272639b83c3ff1ac24696cdb30aeb532e30
57
+ 548fd948e46dbc312858ebf2ef34c6ffeafe28ed61ee7c3c735d4a14d9e864b7e342105d14203e13
58
+ e045eee2b6a3aaabeadb6c4f15facb4fd0c742f442ef6abbb5654f3b1d41cd2105d81e799e86854d
59
+ c7e44b476a3d816250cf62a1f25b8d2646fc8883a0c1c7b6a37f1524c369cb749247848a0b5692b2
60
+ 85095bbf00ad19489d1462b17423820e0058428d2a0c55f5ea1dadf43e233f70613372f0928d937e
61
+ 41d65fecf16c223bdb7cde3759cbee74604085f2a7ce77326ea607808419f8509ee8efd85561d997
62
+ 35a969a7aac50c06c25a04abfc800bcadc9e447a2ec3453484fdd567050e1e9ec9db73dbd3105588
63
+ cd675fda79e3674340c5c43465713e38d83d28f89ef16dff20153e21e78fb03d4ae6e39f2bdb83ad
64
+ f7e93d5a68948140f7f64c261c94692934411520f77602d4f7bcf46b2ed4a20068d40824713320f4
65
+ 6a43b7d4b7500061af1e39f62e9724454614214f74bf8b88404d95fc1d96b591af70f4ddd366a02f
66
+ 45bfbc09ec03bd97857fac6dd031cb850496eb27b355fd3941da2547e6abca0a9a28507825530429
67
+ f40a2c86dae9b66dfb68dc1462d7486900680ec0a427a18dee4f3ffea2e887ad8cb58ce0067af4d6
68
+ b6aace1e7cd3375fecce78a399406b2a4220fe9e35d9f385b9ee39d7ab3b124e8b1dc9faf74b6d18
69
+ 5626a36631eae397b23a6efa74dd5b43326841e7f7ca7820fbfb0af54ed8feb397454056acba4895
70
+ 2755533a3a20838d87fe6ba9b7d096954b55a867bca1159a58cca9296399e1db33a62a4a563f3125
71
+ f95ef47e1c9029317cfdf8e80204272f7080bb155c05282ce395c11548e4c66d2248c1133fc70f86
72
+ dc07f9c9ee41041f0f404779a45d886e17325f51ebd59bc0d1f2bcc18f41113564257b7834602a9c
73
+ 60dff8e8a31f636c1b0e12b4c202e1329eaf664fd1cad181156b2395e0333e92e13b240b62eebeb9
74
+ 2285b2a20ee6ba0d99de720c8c2da2f728d012784595b794fd647d0862e7ccf5f05449a36f877d48
75
+ fac39dfd27f33e8d1e0a476341992eff743a6f6eabf4f8fd37a812dc60a1ebddf8991be14cdb6e6b
76
+ 0dc67b55106d672c372765d43bdcd0e804f1290dc7cc00ffa3b5390f92690fed0b667b9ffbcedb7d
77
+ 9ca091cf0bd9155ea3bb132f88515bad247b9479bf763bd6eb37392eb3cc1159798026e297f42e31
78
+ 2d6842ada7c66a2b3b12754ccc782ef11c6a124237b79251e706a1bbe64bfb63501a6b101811caed
79
+ fa3d25bdd8e2e1c3c9444216590a121386d90cec6ed5abea2a64af674eda86a85fbebfe98864e4c3
80
+ fe9dbc8057f0f7c08660787bf86003604dd1fd8346f6381fb07745ae04d736fccc83426b33f01eab
81
+ 71b08041873c005e5f77a057bebde8ae2455464299bf582e614e58f48ff2ddfda2f474ef388789bd
82
+ c25366f9c3c8b38e74b475f25546fcd9b97aeb26618b1ddf84846a0e79915f95e2466e598e20b457
83
+ 708cd55591c902de4cb90bace1bb8205d011a862487574a99eb77f19b6e0a9dc09662d09a1c43246
84
+ 33e85a1f0209f0be8c4a99a0251d6efe101ab93d1d0ba5a4dfa186f20f2868f169dcb7da83573906
85
+ fea1e2ce9b4fcd7f5250115e01a70683faa002b5c40de6d0279af88c27773f8641c3604c0661a806
86
+ b5f0177a28c0f586e0006058aa30dc7d6211e69ed72338ea6353c2dd94c2c21634bbcbee5690bcb6
87
+ deebfc7da1ce591d766f05e4094b7c018839720a3d7c927c2486e3725f724d9db91ac15bb4d39eb8
88
+ fced54557808fca5b5d83d7cd34dad0fc41e50ef5eb161e6f8a28514d96c51133c6fd5c7e756e14e
89
+ c4362abfceddc6c837d79a323492638212670efa8e406000e03a39ce37d3faf5cfabc277375ac52d
90
+ 1b5cb0679e4fa33742d382274099bc9bbed5118e9dbf0f7315d62d1c7ec700c47bb78c1b6b21a190
91
+ 45b26eb1be6a366eb45748ab2fbc946e79c6a376d26549c2c8530ff8ee468dde7dd5730a1d4cd04d
92
+ c62939bbdba9ba4650ac9526e8be5ee304a1fad5f06a2d519a63ef8ce29a86ee22c089c2b843242e
93
+ f6a51e03aa9cf2d0a483c061ba9be96a4d8fe51550ba645bd62826a2f9a73a3ae14ba99586ef5562
94
+ e9c72fefd3f752f7da3f046f6977fa0a5980e4a91587b086019b09e6ad3b3ee593e990fd5a9e34d7
95
+ 972cf0b7d9022b8b5196d5ac3a017da67dd1cf3ed67c7d2d281f9f25cfadf2b89b5ad6b4725a88f5
96
+ 4ce029ac71e019a5e647b0acfded93fa9be8d3c48d283b57ccf8d5662979132e28785f0191ed7560
97
+ 55f7960e44e3d35e8c15056dd488f46dba03a161250564f0bdc3eb9e153c9057a297271aeca93a07
98
+ 2a1b3f6d9b1e6321f5f59c66fb26dcf3197533d928b155fdf5035634828aba3cbb28517711c20ad9
99
+ f8abcc5167ccad925f4de817513830dc8e379d58629320f991ea7a90c2fb3e7bce5121ce64774fbe
100
+ 32a8b6e37ec3293d4648de53696413e680a2ae0810dd6db22469852dfd09072166b39a460a6445c0
101
+ dd586cdecf1c20c8ae5bbef7dd1b588d40ccd2017f6bb4e3bbdda26a7e3a59ff453e350a44bcb4cd
102
+ d572eacea8fa6484bb8d6612aebf3c6f47d29be463542f5d9eaec2771bf64e6370740e0d8de75b13
103
+ 57f8721671af537d5d4040cb084eb4e2cc34d2466a0115af84e1b0042895983a1d06b89fb4ce6ea0
104
+ 486f3f3b823520ab82011a1d4b277227f8611560b1e7933fdcbb3a792b344525bda08839e151ce79
105
+ 4b2f32c9b7a01fbac9e01cc87ebcc7d1f6cf0111c3a1e8aac71a908749d44fbd9ad0dadecbd50ada
106
+ 380339c32ac69136678df9317ce0b12b4ff79e59b743f5bb3af2d519ff27d9459cbf97222c15e6fc
107
+ 2a0f91fc719b941525fae59361ceb69cebc2a8645912baa8d1b6c1075ee3056a0c10d25065cb03a4
108
+ 42e0ec6e0e1698db3b4c98a0be3278e9649f1f9532e0d392dfd3a0342b8971f21e1b0a74414ba334
109
+ 8cc5be7120c37632d8df359f8d9b992f2ee60b6f470fe3f11de54cda541edad891ce6279cfcd3e7e
110
+ 6f1618b166fd2c1d05848fd2c5f6fb2299f523f357a632762393a8353156cccd02acf081625a75eb
111
+ b56e16369788d273ccde96629281b949d04c50901b71c65614e6c6c7bd327a140a45e1d006c3f27b
112
+ 9ac9aa53fd62a80f00bb25bfe235bdd2f671126905b2040222b6cbcf7ccd769c2b53113ec01640e3
113
+ d338abbd602547adf0ba38209cf746ce7677afa1c52075606085cbfe4e8ae88dd87aaaf9b04cf9aa
114
+ 7e1948c25c02fb8a8c01c36ae4d6ebe1f990d4f869a65cdea03f09252dc208e69fb74e6132ce77e2
115
+ 5b578fdfe33ac372e6'''.split())
116
+
117
+
118
+ def test_hex_pi_nth_digits():
119
+ assert pi_hex_digits(0) == '3243f6a8885a30'
120
+ assert pi_hex_digits(1) == '243f6a8885a308'
121
+ assert pi_hex_digits(10000) == '68ac8fcfb8016c'
122
+ assert pi_hex_digits(13) == '08d313198a2e03'
123
+ assert pi_hex_digits(0, 3) == '324'
124
+ assert pi_hex_digits(0, 0) == ''
125
+ raises(ValueError, lambda: pi_hex_digits(-1))
126
+ raises(ValueError, lambda: pi_hex_digits(3.14))
127
+
128
+ # this will pick a random segment to compute every time
129
+ # it is run. If it ever fails, there is an error in the
130
+ # computation.
131
+ n = randint(0, len(dig))
132
+ prec = randint(0, len(dig) - n)
133
+ assert pi_hex_digits(n, prec) == dig[n: n + prec]
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_elliptic_curve.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory.elliptic_curve import EllipticCurve
2
+
3
+
4
+ def test_elliptic_curve():
5
+ # Point addition and multiplication
6
+ e3 = EllipticCurve(-1, 9)
7
+ p = e3(0, 3)
8
+ q = e3(-1, 3)
9
+ r = p + q
10
+ assert r.x == 1 and r.y == -3
11
+ r = 2*p + q
12
+ assert r.x == 35 and r.y == 207
13
+ r = -p + q
14
+ assert r.x == 37 and r.y == 225
15
+ # Verify result in http://www.lmfdb.org/EllipticCurve/Q
16
+ # Discriminant
17
+ assert EllipticCurve(-1, 9).discriminant == -34928
18
+ assert EllipticCurve(-2731, -55146, 1, 0, 1).discriminant == 25088
19
+ # Torsion points
20
+ assert len(EllipticCurve(0, 1).torsion_points()) == 6
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_generate.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, Rational, nan, zoo)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.ntheory.generate import (sieve, Sieve)
5
+ from sympy.series.limits import limit
6
+
7
+ from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \
8
+ primerange, primepi, prime, primorial, composite, compositepi, reduced_totient
9
+ from sympy.ntheory.generate import cycle_length
10
+ from sympy.ntheory.primetest import mr
11
+ from sympy.testing.pytest import raises
12
+
13
+ def test_prime():
14
+ assert prime(1) == 2
15
+ assert prime(2) == 3
16
+ assert prime(5) == 11
17
+ assert prime(11) == 31
18
+ assert prime(57) == 269
19
+ assert prime(296) == 1949
20
+ assert prime(559) == 4051
21
+ assert prime(3000) == 27449
22
+ assert prime(4096) == 38873
23
+ assert prime(9096) == 94321
24
+ assert prime(25023) == 287341
25
+ assert prime(10000000) == 179424673 # issue #20951
26
+ assert prime(99999999) == 2038074739
27
+ raises(ValueError, lambda: prime(0))
28
+ sieve.extend(3000)
29
+ assert prime(401) == 2749
30
+ raises(ValueError, lambda: prime(-1))
31
+
32
+
33
+ def test_primepi():
34
+ assert primepi(-1) == 0
35
+ assert primepi(1) == 0
36
+ assert primepi(2) == 1
37
+ assert primepi(Rational(7, 2)) == 2
38
+ assert primepi(3.5) == 2
39
+ assert primepi(5) == 3
40
+ assert primepi(11) == 5
41
+ assert primepi(57) == 16
42
+ assert primepi(296) == 62
43
+ assert primepi(559) == 102
44
+ assert primepi(3000) == 430
45
+ assert primepi(4096) == 564
46
+ assert primepi(9096) == 1128
47
+ assert primepi(25023) == 2763
48
+ assert primepi(10**8) == 5761455
49
+ assert primepi(253425253) == 13856396
50
+ assert primepi(8769575643) == 401464322
51
+ sieve.extend(3000)
52
+ assert primepi(2000) == 303
53
+
54
+ n = Symbol('n')
55
+ assert primepi(n).subs(n, 2) == 1
56
+
57
+ r = Symbol('r', real=True)
58
+ assert primepi(r).subs(r, 2) == 1
59
+
60
+ assert primepi(S.Infinity) is S.Infinity
61
+ assert primepi(S.NegativeInfinity) == 0
62
+
63
+ assert limit(primepi(n), n, 100) == 25
64
+
65
+ raises(ValueError, lambda: primepi(I))
66
+ raises(ValueError, lambda: primepi(1 + I))
67
+ raises(ValueError, lambda: primepi(zoo))
68
+ raises(ValueError, lambda: primepi(nan))
69
+
70
+
71
+ def test_composite():
72
+ from sympy.ntheory.generate import sieve
73
+ sieve._reset()
74
+ assert composite(1) == 4
75
+ assert composite(2) == 6
76
+ assert composite(5) == 10
77
+ assert composite(11) == 20
78
+ assert composite(41) == 58
79
+ assert composite(57) == 80
80
+ assert composite(296) == 370
81
+ assert composite(559) == 684
82
+ assert composite(3000) == 3488
83
+ assert composite(4096) == 4736
84
+ assert composite(9096) == 10368
85
+ assert composite(25023) == 28088
86
+ sieve.extend(3000)
87
+ assert composite(1957) == 2300
88
+ assert composite(2568) == 2998
89
+ raises(ValueError, lambda: composite(0))
90
+
91
+
92
+ def test_compositepi():
93
+ assert compositepi(1) == 0
94
+ assert compositepi(2) == 0
95
+ assert compositepi(5) == 1
96
+ assert compositepi(11) == 5
97
+ assert compositepi(57) == 40
98
+ assert compositepi(296) == 233
99
+ assert compositepi(559) == 456
100
+ assert compositepi(3000) == 2569
101
+ assert compositepi(4096) == 3531
102
+ assert compositepi(9096) == 7967
103
+ assert compositepi(25023) == 22259
104
+ assert compositepi(10**8) == 94238544
105
+ assert compositepi(253425253) == 239568856
106
+ assert compositepi(8769575643) == 8368111320
107
+ sieve.extend(3000)
108
+ assert compositepi(2321) == 1976
109
+
110
+
111
+ def test_generate():
112
+ from sympy.ntheory.generate import sieve
113
+ sieve._reset()
114
+ assert nextprime(-4) == 2
115
+ assert nextprime(2) == 3
116
+ assert nextprime(5) == 7
117
+ assert nextprime(12) == 13
118
+ assert prevprime(3) == 2
119
+ assert prevprime(7) == 5
120
+ assert prevprime(13) == 11
121
+ assert prevprime(19) == 17
122
+ assert prevprime(20) == 19
123
+
124
+ sieve.extend_to_no(9)
125
+ assert sieve._list[-1] == 23
126
+
127
+ assert sieve._list[-1] < 31
128
+ assert 31 in sieve
129
+
130
+ assert nextprime(90) == 97
131
+ assert nextprime(10**40) == (10**40 + 121)
132
+ assert prevprime(97) == 89
133
+ assert prevprime(10**40) == (10**40 - 17)
134
+
135
+ assert list(sieve.primerange(10, 1)) == []
136
+ assert list(sieve.primerange(5, 9)) == [5, 7]
137
+ sieve._reset(prime=True)
138
+ assert list(sieve.primerange(2, 13)) == [2, 3, 5, 7, 11]
139
+ assert list(sieve.primerange(13)) == [2, 3, 5, 7, 11]
140
+ assert list(sieve.primerange(8)) == [2, 3, 5, 7]
141
+ assert list(sieve.primerange(-2)) == []
142
+ assert list(sieve.primerange(29)) == [2, 3, 5, 7, 11, 13, 17, 19, 23]
143
+ assert list(sieve.primerange(34)) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
144
+
145
+ assert list(sieve.totientrange(5, 15)) == [4, 2, 6, 4, 6, 4, 10, 4, 12, 6]
146
+ sieve._reset(totient=True)
147
+ assert list(sieve.totientrange(3, 13)) == [2, 2, 4, 2, 6, 4, 6, 4, 10, 4]
148
+ assert list(sieve.totientrange(900, 1000)) == [totient(x) for x in range(900, 1000)]
149
+ assert list(sieve.totientrange(0, 1)) == []
150
+ assert list(sieve.totientrange(1, 2)) == [1]
151
+
152
+ assert list(sieve.mobiusrange(5, 15)) == [-1, 1, -1, 0, 0, 1, -1, 0, -1, 1]
153
+ sieve._reset(mobius=True)
154
+ assert list(sieve.mobiusrange(3, 13)) == [-1, 0, -1, 1, -1, 0, 0, 1, -1, 0]
155
+ assert list(sieve.mobiusrange(1050, 1100)) == [mobius(x) for x in range(1050, 1100)]
156
+ assert list(sieve.mobiusrange(0, 1)) == []
157
+ assert list(sieve.mobiusrange(1, 2)) == [1]
158
+
159
+ assert list(primerange(10, 1)) == []
160
+ assert list(primerange(2, 7)) == [2, 3, 5]
161
+ assert list(primerange(2, 10)) == [2, 3, 5, 7]
162
+ assert list(primerange(1050, 1100)) == [1051, 1061,
163
+ 1063, 1069, 1087, 1091, 1093, 1097]
164
+ s = Sieve()
165
+ for i in range(30, 2350, 376):
166
+ for j in range(2, 5096, 1139):
167
+ A = list(s.primerange(i, i + j))
168
+ B = list(primerange(i, i + j))
169
+ assert A == B
170
+ s = Sieve()
171
+ assert s[10] == 29
172
+
173
+ assert nextprime(2, 2) == 5
174
+
175
+ raises(ValueError, lambda: totient(0))
176
+
177
+ raises(ValueError, lambda: reduced_totient(0))
178
+
179
+ raises(ValueError, lambda: primorial(0))
180
+
181
+ assert mr(1, [2]) is False
182
+
183
+ func = lambda i: (i**2 + 1) % 51
184
+ assert next(cycle_length(func, 4)) == (6, 2)
185
+ assert list(cycle_length(func, 4, values=True)) == \
186
+ [17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
187
+ assert next(cycle_length(func, 4, nmax=5)) == (5, None)
188
+ assert list(cycle_length(func, 4, nmax=5, values=True)) == \
189
+ [17, 35, 2, 5, 26]
190
+ sieve.extend(3000)
191
+ assert nextprime(2968) == 2969
192
+ assert prevprime(2930) == 2927
193
+ raises(ValueError, lambda: prevprime(1))
194
+ raises(ValueError, lambda: prevprime(-4))
195
+
196
+
197
+ def test_randprime():
198
+ assert randprime(10, 1) is None
199
+ assert randprime(3, -3) is None
200
+ assert randprime(2, 3) == 2
201
+ assert randprime(1, 3) == 2
202
+ assert randprime(3, 5) == 3
203
+ raises(ValueError, lambda: randprime(-12, -2))
204
+ raises(ValueError, lambda: randprime(-10, 0))
205
+ raises(ValueError, lambda: randprime(20, 22))
206
+ raises(ValueError, lambda: randprime(0, 2))
207
+ raises(ValueError, lambda: randprime(1, 2))
208
+ for a in [100, 300, 500, 250000]:
209
+ for b in [100, 300, 500, 250000]:
210
+ p = randprime(a, a + b)
211
+ assert a <= p < (a + b) and isprime(p)
212
+
213
+
214
+ def test_primorial():
215
+ assert primorial(1) == 2
216
+ assert primorial(1, nth=0) == 1
217
+ assert primorial(2) == 6
218
+ assert primorial(2, nth=0) == 2
219
+ assert primorial(4, nth=0) == 6
220
+
221
+
222
+ def test_search():
223
+ assert 2 in sieve
224
+ assert 2.1 not in sieve
225
+ assert 1 not in sieve
226
+ assert 2**1000 not in sieve
227
+ raises(ValueError, lambda: sieve.search(1))
228
+
229
+
230
+ def test_sieve_slice():
231
+ assert sieve[5] == 11
232
+ assert list(sieve[5:10]) == [sieve[x] for x in range(5, 10)]
233
+ assert list(sieve[5:10:2]) == [sieve[x] for x in range(5, 10, 2)]
234
+ assert list(sieve[1:5]) == [2, 3, 5, 7]
235
+ raises(IndexError, lambda: sieve[:5])
236
+ raises(IndexError, lambda: sieve[0])
237
+ raises(IndexError, lambda: sieve[0:5])
238
+
239
+ def test_sieve_iter():
240
+ values = []
241
+ for value in sieve:
242
+ if value > 7:
243
+ break
244
+ values.append(value)
245
+ assert values == list(sieve[1:5])
246
+
247
+
248
+ def test_sieve_repr():
249
+ assert "sieve" in repr(sieve)
250
+ assert "prime" in repr(sieve)
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_primetest.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.ntheory.generate import Sieve, sieve
2
+ from sympy.ntheory.primetest import (mr, is_lucas_prp, is_square,
3
+ is_strong_lucas_prp, is_extra_strong_lucas_prp, isprime, is_euler_pseudoprime,
4
+ is_gaussian_prime)
5
+
6
+ from sympy.testing.pytest import slow
7
+ from sympy.core.numbers import I
8
+
9
+ def test_euler_pseudoprimes():
10
+ assert is_euler_pseudoprime(9, 1) == True
11
+ assert is_euler_pseudoprime(341, 2) == False
12
+ assert is_euler_pseudoprime(121, 3) == True
13
+ assert is_euler_pseudoprime(341, 4) == True
14
+ assert is_euler_pseudoprime(217, 5) == False
15
+ assert is_euler_pseudoprime(185, 6) == False
16
+ assert is_euler_pseudoprime(55, 111) == True
17
+ assert is_euler_pseudoprime(115, 114) == True
18
+ assert is_euler_pseudoprime(49, 117) == True
19
+ assert is_euler_pseudoprime(85, 84) == True
20
+ assert is_euler_pseudoprime(87, 88) == True
21
+ assert is_euler_pseudoprime(49, 128) == True
22
+ assert is_euler_pseudoprime(39, 77) == True
23
+ assert is_euler_pseudoprime(9881, 30) == True
24
+ assert is_euler_pseudoprime(8841, 29) == False
25
+ assert is_euler_pseudoprime(8421, 29) == False
26
+ assert is_euler_pseudoprime(9997, 19) == True
27
+
28
+ def test_is_extra_strong_lucas_prp():
29
+ assert is_extra_strong_lucas_prp(4) == False
30
+ assert is_extra_strong_lucas_prp(989) == True
31
+ assert is_extra_strong_lucas_prp(10877) == True
32
+ assert is_extra_strong_lucas_prp(9) == False
33
+ assert is_extra_strong_lucas_prp(16) == False
34
+ assert is_extra_strong_lucas_prp(169) == False
35
+
36
+ @slow
37
+ def test_prps():
38
+ oddcomposites = [n for n in range(1, 10**5) if
39
+ n % 2 and not isprime(n)]
40
+ # A checksum would be better.
41
+ assert sum(oddcomposites) == 2045603465
42
+ assert [n for n in oddcomposites if mr(n, [2])] == [
43
+ 2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141,
44
+ 52633, 65281, 74665, 80581, 85489, 88357, 90751]
45
+ assert [n for n in oddcomposites if mr(n, [3])] == [
46
+ 121, 703, 1891, 3281, 8401, 8911, 10585, 12403, 16531,
47
+ 18721, 19345, 23521, 31621, 44287, 47197, 55969, 63139,
48
+ 74593, 79003, 82513, 87913, 88573, 97567]
49
+ assert [n for n in oddcomposites if mr(n, [325])] == [
50
+ 9, 25, 27, 49, 65, 81, 325, 341, 343, 697, 1141, 2059,
51
+ 2149, 3097, 3537, 4033, 4681, 4941, 5833, 6517, 7987, 8911,
52
+ 12403, 12913, 15043, 16021, 20017, 22261, 23221, 24649,
53
+ 24929, 31841, 35371, 38503, 43213, 44173, 47197, 50041,
54
+ 55909, 56033, 58969, 59089, 61337, 65441, 68823, 72641,
55
+ 76793, 78409, 85879]
56
+ assert not any(mr(n, [9345883071009581737]) for n in oddcomposites)
57
+ assert [n for n in oddcomposites if is_lucas_prp(n)] == [
58
+ 323, 377, 1159, 1829, 3827, 5459, 5777, 9071, 9179, 10877,
59
+ 11419, 11663, 13919, 14839, 16109, 16211, 18407, 18971,
60
+ 19043, 22499, 23407, 24569, 25199, 25877, 26069, 27323,
61
+ 32759, 34943, 35207, 39059, 39203, 39689, 40309, 44099,
62
+ 46979, 47879, 50183, 51983, 53663, 56279, 58519, 60377,
63
+ 63881, 69509, 72389, 73919, 75077, 77219, 79547, 79799,
64
+ 82983, 84419, 86063, 90287, 94667, 97019, 97439]
65
+ assert [n for n in oddcomposites if is_strong_lucas_prp(n)] == [
66
+ 5459, 5777, 10877, 16109, 18971, 22499, 24569, 25199, 40309,
67
+ 58519, 75077, 97439]
68
+ assert [n for n in oddcomposites if is_extra_strong_lucas_prp(n)
69
+ ] == [
70
+ 989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059,
71
+ 72389, 73919, 75077]
72
+
73
+
74
+ def test_isprime():
75
+ s = Sieve()
76
+ s.extend(100000)
77
+ ps = set(s.primerange(2, 100001))
78
+ for n in range(100001):
79
+ # if (n in ps) != isprime(n): print n
80
+ assert (n in ps) == isprime(n)
81
+ assert isprime(179424673)
82
+ assert isprime(20678048681)
83
+ assert isprime(1968188556461)
84
+ assert isprime(2614941710599)
85
+ assert isprime(65635624165761929287)
86
+ assert isprime(1162566711635022452267983)
87
+ assert isprime(77123077103005189615466924501)
88
+ assert isprime(3991617775553178702574451996736229)
89
+ assert isprime(273952953553395851092382714516720001799)
90
+ assert isprime(int('''
91
+ 531137992816767098689588206552468627329593117727031923199444138200403\
92
+ 559860852242739162502265229285668889329486246501015346579337652707239\
93
+ 409519978766587351943831270835393219031728127'''))
94
+
95
+ # Some Mersenne primes
96
+ assert isprime(2**61 - 1)
97
+ assert isprime(2**89 - 1)
98
+ assert isprime(2**607 - 1)
99
+ # (but not all Mersenne's are primes
100
+ assert not isprime(2**601 - 1)
101
+
102
+ # pseudoprimes
103
+ #-------------
104
+ # to some small bases
105
+ assert not isprime(2152302898747)
106
+ assert not isprime(3474749660383)
107
+ assert not isprime(341550071728321)
108
+ assert not isprime(3825123056546413051)
109
+ # passes the base set [2, 3, 7, 61, 24251]
110
+ assert not isprime(9188353522314541)
111
+ # large examples
112
+ assert not isprime(877777777777777777777777)
113
+ # conjectured psi_12 given at http://mathworld.wolfram.com/StrongPseudoprime.html
114
+ assert not isprime(318665857834031151167461)
115
+ # conjectured psi_17 given at http://mathworld.wolfram.com/StrongPseudoprime.html
116
+ assert not isprime(564132928021909221014087501701)
117
+ # Arnault's 1993 number; a factor of it is
118
+ # 400958216639499605418306452084546853005188166041132508774506\
119
+ # 204738003217070119624271622319159721973358216316508535816696\
120
+ # 9145233813917169287527980445796800452592031836601
121
+ assert not isprime(int('''
122
+ 803837457453639491257079614341942108138837688287558145837488917522297\
123
+ 427376533365218650233616396004545791504202360320876656996676098728404\
124
+ 396540823292873879185086916685732826776177102938969773947016708230428\
125
+ 687109997439976544144845341155872450633409279022275296229414984230688\
126
+ 1685404326457534018329786111298960644845216191652872597534901'''))
127
+ # Arnault's 1995 number; can be factored as
128
+ # p1*(313*(p1 - 1) + 1)*(353*(p1 - 1) + 1) where p1 is
129
+ # 296744956686855105501541746429053327307719917998530433509950\
130
+ # 755312768387531717701995942385964281211880336647542183455624\
131
+ # 93168782883
132
+ assert not isprime(int('''
133
+ 288714823805077121267142959713039399197760945927972270092651602419743\
134
+ 230379915273311632898314463922594197780311092934965557841894944174093\
135
+ 380561511397999942154241693397290542371100275104208013496673175515285\
136
+ 922696291677532547504444585610194940420003990443211677661994962953925\
137
+ 045269871932907037356403227370127845389912612030924484149472897688540\
138
+ 6024976768122077071687938121709811322297802059565867'''))
139
+ sieve.extend(3000)
140
+ assert isprime(2819)
141
+ assert not isprime(2931)
142
+ assert not isprime(2.0)
143
+
144
+
145
+ def test_is_square():
146
+ assert [i for i in range(25) if is_square(i)] == [0, 1, 4, 9, 16]
147
+
148
+ # issue #17044
149
+ assert not is_square(60 ** 3)
150
+ assert not is_square(60 ** 5)
151
+ assert not is_square(84 ** 7)
152
+ assert not is_square(105 ** 9)
153
+ assert not is_square(120 ** 3)
154
+
155
+ def test_is_gaussianprime():
156
+ assert is_gaussian_prime(7*I)
157
+ assert is_gaussian_prime(7)
158
+ assert is_gaussian_prime(2 + 3*I)
159
+ assert not is_gaussian_prime(2 + 2*I)
llmeval-env/lib/python3.10/site-packages/sympy/ntheory/tests/test_qs.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sympy.ntheory import qs
4
+ from sympy.ntheory.qs import SievePolynomial, _generate_factor_base, \
5
+ _initialize_first_polynomial, _initialize_ith_poly, \
6
+ _gen_sieve_array, _check_smoothness, _trial_division_stage, _gauss_mod_2, \
7
+ _build_matrix, _find_factor
8
+ from sympy.testing.pytest import slow
9
+
10
+
11
+ @slow
12
+ def test_qs_1():
13
+ assert qs(10009202107, 100, 10000) == {100043, 100049}
14
+ assert qs(211107295182713951054568361, 1000, 10000) == \
15
+ {13791315212531, 15307263442931}
16
+ assert qs(980835832582657*990377764891511, 3000, 50000) == \
17
+ {980835832582657, 990377764891511}
18
+ assert qs(18640889198609*20991129234731, 1000, 50000) == \
19
+ {18640889198609, 20991129234731}
20
+
21
+
22
+ def test_qs_2() -> None:
23
+ n = 10009202107
24
+ M = 50
25
+ # a = 10, b = 15, modified_coeff = [a**2, 2*a*b, b**2 - N]
26
+ sieve_poly = SievePolynomial([100, 1600, -10009195707], 10, 80)
27
+ assert sieve_poly.eval(10) == -10009169707
28
+ assert sieve_poly.eval(5) == -10009185207
29
+
30
+ idx_1000, idx_5000, factor_base = _generate_factor_base(2000, n)
31
+ assert idx_1000 == 82
32
+ assert [factor_base[i].prime for i in range(15)] == \
33
+ [2, 3, 7, 11, 17, 19, 29, 31, 43, 59, 61, 67, 71, 73, 79]
34
+ assert [factor_base[i].tmem_p for i in range(15)] == \
35
+ [1, 1, 3, 5, 3, 6, 6, 14, 1, 16, 24, 22, 18, 22, 15]
36
+ assert [factor_base[i].log_p for i in range(5)] == \
37
+ [710, 1125, 1993, 2455, 2901]
38
+
39
+ g, B = _initialize_first_polynomial(
40
+ n, M, factor_base, idx_1000, idx_5000, seed=0)
41
+ assert g.a == 1133107
42
+ assert g.b == 682543
43
+ assert B == [272889, 409654]
44
+ assert [factor_base[i].soln1 for i in range(15)] == \
45
+ [0, 0, 3, 7, 13, 0, 8, 19, 9, 43, 27, 25, 63, 29, 19]
46
+ assert [factor_base[i].soln2 for i in range(15)] == \
47
+ [0, 1, 1, 3, 12, 16, 15, 6, 15, 1, 56, 55, 61, 58, 16]
48
+ assert [factor_base[i].a_inv for i in range(15)] == \
49
+ [1, 1, 5, 7, 3, 5, 26, 6, 40, 5, 21, 45, 4, 1, 8]
50
+ assert [factor_base[i].b_ainv for i in range(5)] == \
51
+ [[0, 0], [0, 2], [3, 0], [3, 9], [13, 13]]
52
+
53
+ g_1 = _initialize_ith_poly(n, factor_base, 1, g, B)
54
+ assert g_1.a == 1133107
55
+ assert g_1.b == 136765
56
+
57
+ sieve_array = _gen_sieve_array(M, factor_base)
58
+ assert sieve_array[0:5] == [8424, 13603, 1835, 5335, 710]
59
+
60
+ assert _check_smoothness(9645, factor_base) == (5, False)
61
+ assert _check_smoothness(210313, factor_base)[0][0:15] == \
62
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
63
+ assert _check_smoothness(210313, factor_base)[1]
64
+
65
+ partial_relations: dict[int, tuple[int, int]] = {}
66
+ smooth_relation, partial_relation = _trial_division_stage(
67
+ n, M, factor_base, sieve_array, sieve_poly, partial_relations,
68
+ ERROR_TERM=25*2**10)
69
+
70
+ assert partial_relations == {
71
+ 8699: (440, -10009008507),
72
+ 166741: (490, -10008962007),
73
+ 131449: (530, -10008921207),
74
+ 6653: (550, -10008899607)
75
+ }
76
+ assert [smooth_relation[i][0] for i in range(5)] == [
77
+ -250, -670615476700, -45211565844500, -231723037747200, -1811665537200]
78
+ assert [smooth_relation[i][1] for i in range(5)] == [
79
+ -10009139607, 1133094251961, 5302606761, 53804049849, 1950723889]
80
+ assert smooth_relation[0][2][0:15] == [
81
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
82
+
83
+ assert _gauss_mod_2(
84
+ [[0, 0, 1], [1, 0, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]]
85
+ ) == (
86
+ [[[0, 1, 1], 3], [[0, 1, 1], 4]],
87
+ [True, True, True, False, False],
88
+ [[0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 1], [0, 1, 1]]
89
+ )
90
+
91
+
92
+ def test_qs_3():
93
+ N = 1817
94
+ smooth_relations = [
95
+ (2455024, 637, [0, 0, 0, 1]),
96
+ (-27993000, 81536, [0, 1, 0, 1]),
97
+ (11461840, 12544, [0, 0, 0, 0]),
98
+ (149, 20384, [0, 1, 0, 1]),
99
+ (-31138074, 19208, [0, 1, 0, 0])
100
+ ]
101
+
102
+ matrix = _build_matrix(smooth_relations)
103
+ assert matrix == [
104
+ [0, 0, 0, 1],
105
+ [0, 1, 0, 1],
106
+ [0, 0, 0, 0],
107
+ [0, 1, 0, 1],
108
+ [0, 1, 0, 0]
109
+ ]
110
+
111
+ dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix)
112
+ assert dependent_row == [[[0, 0, 0, 0], 2], [[0, 1, 0, 0], 3]]
113
+ assert mark == [True, True, False, False, True]
114
+ assert gauss_matrix == [
115
+ [0, 0, 0, 1],
116
+ [0, 1, 0, 0],
117
+ [0, 0, 0, 0],
118
+ [0, 1, 0, 0],
119
+ [0, 1, 0, 1]
120
+ ]
121
+
122
+ factor = _find_factor(
123
+ dependent_row, mark, gauss_matrix, 0, smooth_relations, N)
124
+ assert factor == 23
llmeval-env/lib/python3.10/site-packages/sympy/tensor/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module to manipulate symbolic objects with indices including tensors
2
+
3
+ """
4
+ from .indexed import IndexedBase, Idx, Indexed
5
+ from .index_methods import get_contraction_structure, get_indices
6
+ from .functions import shape
7
+ from .array import (MutableDenseNDimArray, ImmutableDenseNDimArray,
8
+ MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct,
9
+ tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array,
10
+ DenseNDimArray, SparseNDimArray,)
11
+
12
+ __all__ = [
13
+ 'IndexedBase', 'Idx', 'Indexed',
14
+
15
+ 'get_contraction_structure', 'get_indices',
16
+
17
+ 'shape',
18
+
19
+ 'MutableDenseNDimArray', 'ImmutableDenseNDimArray',
20
+ 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray',
21
+ 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims',
22
+ 'Array', 'DenseNDimArray', 'SparseNDimArray',
23
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (954 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/functions.cpython-310.pyc ADDED
Binary file (5.28 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc ADDED
Binary file (23.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc ADDED
Binary file (151 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/tensor/__pycache__/toperators.cpython-310.pyc ADDED
Binary file (9.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/__init__.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ N-dim array module for SymPy.
3
+
4
+ Four classes are provided to handle N-dim arrays, given by the combinations
5
+ dense/sparse (i.e. whether to store all elements or only the non-zero ones in
6
+ memory) and mutable/immutable (immutable classes are SymPy objects, but cannot
7
+ change after they have been created).
8
+
9
+ Examples
10
+ ========
11
+
12
+ The following examples show the usage of ``Array``. This is an abbreviation for
13
+ ``ImmutableDenseNDimArray``, that is an immutable and dense N-dim array, the
14
+ other classes are analogous. For mutable classes it is also possible to change
15
+ element values after the object has been constructed.
16
+
17
+ Array construction can detect the shape of nested lists and tuples:
18
+
19
+ >>> from sympy import Array
20
+ >>> a1 = Array([[1, 2], [3, 4], [5, 6]])
21
+ >>> a1
22
+ [[1, 2], [3, 4], [5, 6]]
23
+ >>> a1.shape
24
+ (3, 2)
25
+ >>> a1.rank()
26
+ 2
27
+ >>> from sympy.abc import x, y, z
28
+ >>> a2 = Array([[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]])
29
+ >>> a2
30
+ [[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]]
31
+ >>> a2.shape
32
+ (2, 2, 2)
33
+ >>> a2.rank()
34
+ 3
35
+
36
+ Otherwise one could pass a 1-dim array followed by a shape tuple:
37
+
38
+ >>> m1 = Array(range(12), (3, 4))
39
+ >>> m1
40
+ [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
41
+ >>> m2 = Array(range(12), (3, 2, 2))
42
+ >>> m2
43
+ [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
44
+ >>> m2[1,1,1]
45
+ 7
46
+ >>> m2.reshape(4, 3)
47
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
48
+
49
+ Slice support:
50
+
51
+ >>> m2[:, 1, 1]
52
+ [3, 7, 11]
53
+
54
+ Elementwise derivative:
55
+
56
+ >>> from sympy.abc import x, y, z
57
+ >>> m3 = Array([x**3, x*y, z])
58
+ >>> m3.diff(x)
59
+ [3*x**2, y, 0]
60
+ >>> m3.diff(z)
61
+ [0, 0, 1]
62
+
63
+ Multiplication with other SymPy expressions is applied elementwisely:
64
+
65
+ >>> (1+x)*m3
66
+ [x**3*(x + 1), x*y*(x + 1), z*(x + 1)]
67
+
68
+ To apply a function to each element of the N-dim array, use ``applyfunc``:
69
+
70
+ >>> m3.applyfunc(lambda x: x/2)
71
+ [x**3/2, x*y/2, z/2]
72
+
73
+ N-dim arrays can be converted to nested lists by the ``tolist()`` method:
74
+
75
+ >>> m2.tolist()
76
+ [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
77
+ >>> isinstance(m2.tolist(), list)
78
+ True
79
+
80
+ If the rank is 2, it is possible to convert them to matrices with ``tomatrix()``:
81
+
82
+ >>> m1.tomatrix()
83
+ Matrix([
84
+ [0, 1, 2, 3],
85
+ [4, 5, 6, 7],
86
+ [8, 9, 10, 11]])
87
+
88
+ Products and contractions
89
+ -------------------------
90
+
91
+ Tensor product between arrays `A_{i_1,\ldots,i_n}` and `B_{j_1,\ldots,j_m}`
92
+ creates the combined array `P = A \otimes B` defined as
93
+
94
+ `P_{i_1,\ldots,i_n,j_1,\ldots,j_m} := A_{i_1,\ldots,i_n}\cdot B_{j_1,\ldots,j_m}.`
95
+
96
+ It is available through ``tensorproduct(...)``:
97
+
98
+ >>> from sympy import Array, tensorproduct
99
+ >>> from sympy.abc import x,y,z,t
100
+ >>> A = Array([x, y, z, t])
101
+ >>> B = Array([1, 2, 3, 4])
102
+ >>> tensorproduct(A, B)
103
+ [[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
104
+
105
+ In case you don't want to evaluate the tensor product immediately, you can use
106
+ ``ArrayTensorProduct``, which creates an unevaluated tensor product expression:
107
+
108
+ >>> from sympy.tensor.array.expressions import ArrayTensorProduct
109
+ >>> ArrayTensorProduct(A, B)
110
+ ArrayTensorProduct([x, y, z, t], [1, 2, 3, 4])
111
+
112
+ Calling ``.as_explicit()`` on ``ArrayTensorProduct`` is equivalent to just calling
113
+ ``tensorproduct(...)``:
114
+
115
+ >>> ArrayTensorProduct(A, B).as_explicit()
116
+ [[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]]
117
+
118
+ Tensor product between a rank-1 array and a matrix creates a rank-3 array:
119
+
120
+ >>> from sympy import eye
121
+ >>> p1 = tensorproduct(A, eye(4))
122
+ >>> p1
123
+ [[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]], [[y, 0, 0, 0], [0, y, 0, 0], [0, 0, y, 0], [0, 0, 0, y]], [[z, 0, 0, 0], [0, z, 0, 0], [0, 0, z, 0], [0, 0, 0, z]], [[t, 0, 0, 0], [0, t, 0, 0], [0, 0, t, 0], [0, 0, 0, t]]]
124
+
125
+ Now, to get back `A_0 \otimes \mathbf{1}` one can access `p_{0,m,n}` by slicing:
126
+
127
+ >>> p1[0,:,:]
128
+ [[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]]
129
+
130
+ Tensor contraction sums over the specified axes, for example contracting
131
+ positions `a` and `b` means
132
+
133
+ `A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies \sum_k A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}`
134
+
135
+ Remember that Python indexing is zero starting, to contract the a-th and b-th
136
+ axes it is therefore necessary to specify `a-1` and `b-1`
137
+
138
+ >>> from sympy import tensorcontraction
139
+ >>> C = Array([[x, y], [z, t]])
140
+
141
+ The matrix trace is equivalent to the contraction of a rank-2 array:
142
+
143
+ `A_{m,n} \implies \sum_k A_{k,k}`
144
+
145
+ >>> tensorcontraction(C, (0, 1))
146
+ t + x
147
+
148
+ To create an expression representing a tensor contraction that does not get
149
+ evaluated immediately, use ``ArrayContraction``, which is equivalent to
150
+ ``tensorcontraction(...)`` if it is followed by ``.as_explicit()``:
151
+
152
+ >>> from sympy.tensor.array.expressions import ArrayContraction
153
+ >>> ArrayContraction(C, (0, 1))
154
+ ArrayContraction([[x, y], [z, t]], (0, 1))
155
+ >>> ArrayContraction(C, (0, 1)).as_explicit()
156
+ t + x
157
+
158
+ Matrix product is equivalent to a tensor product of two rank-2 arrays, followed
159
+ by a contraction of the 2nd and 3rd axes (in Python indexing axes number 1, 2).
160
+
161
+ `A_{m,n}\cdot B_{i,j} \implies \sum_k A_{m, k}\cdot B_{k, j}`
162
+
163
+ >>> D = Array([[2, 1], [0, -1]])
164
+ >>> tensorcontraction(tensorproduct(C, D), (1, 2))
165
+ [[2*x, x - y], [2*z, -t + z]]
166
+
167
+ One may verify that the matrix product is equivalent:
168
+
169
+ >>> from sympy import Matrix
170
+ >>> Matrix([[x, y], [z, t]])*Matrix([[2, 1], [0, -1]])
171
+ Matrix([
172
+ [2*x, x - y],
173
+ [2*z, -t + z]])
174
+
175
+ or equivalently
176
+
177
+ >>> C.tomatrix()*D.tomatrix()
178
+ Matrix([
179
+ [2*x, x - y],
180
+ [2*z, -t + z]])
181
+
182
+ Diagonal operator
183
+ -----------------
184
+
185
+ The ``tensordiagonal`` function acts in a similar manner as ``tensorcontraction``,
186
+ but the joined indices are not summed over, for example diagonalizing
187
+ positions `a` and `b` means
188
+
189
+ `A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}
190
+ \implies \tilde{A}_{i_1,\ldots,i_{a-1},i_{a+1},\ldots,i_{b-1},i_{b+1},\ldots,i_n,k}`
191
+
192
+ where `\tilde{A}` is the array equivalent to the diagonal of `A` at positions
193
+ `a` and `b` moved to the last index slot.
194
+
195
+ Compare the difference between contraction and diagonal operators:
196
+
197
+ >>> from sympy import tensordiagonal
198
+ >>> from sympy.abc import a, b, c, d
199
+ >>> m = Matrix([[a, b], [c, d]])
200
+ >>> tensorcontraction(m, [0, 1])
201
+ a + d
202
+ >>> tensordiagonal(m, [0, 1])
203
+ [a, d]
204
+
205
+ In short, no summation occurs with ``tensordiagonal``.
206
+
207
+
208
+ Derivatives by array
209
+ --------------------
210
+
211
+ The usual derivative operation may be extended to support derivation with
212
+ respect to arrays, provided that all elements in the that array are symbols or
213
+ expressions suitable for derivations.
214
+
215
+ The definition of a derivative by an array is as follows: given the array
216
+ `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
217
+ the derivative of arrays will return a new array `B` defined by
218
+
219
+ `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
220
+
221
+ The function ``derive_by_array`` performs such an operation:
222
+
223
+ >>> from sympy import derive_by_array
224
+ >>> from sympy.abc import x, y, z, t
225
+ >>> from sympy import sin, exp
226
+
227
+ With scalars, it behaves exactly as the ordinary derivative:
228
+
229
+ >>> derive_by_array(sin(x*y), x)
230
+ y*cos(x*y)
231
+
232
+ Scalar derived by an array basis:
233
+
234
+ >>> derive_by_array(sin(x*y), [x, y, z])
235
+ [y*cos(x*y), x*cos(x*y), 0]
236
+
237
+ Deriving array by an array basis: `B^{nm} := \frac{\partial A^m}{\partial x^n}`
238
+
239
+ >>> basis = [x, y, z]
240
+ >>> ax = derive_by_array([exp(x), sin(y*z), t], basis)
241
+ >>> ax
242
+ [[exp(x), 0, 0], [0, z*cos(y*z), 0], [0, y*cos(y*z), 0]]
243
+
244
+ Contraction of the resulting array: `\sum_m \frac{\partial A^m}{\partial x^m}`
245
+
246
+ >>> tensorcontraction(ax, (0, 1))
247
+ z*cos(y*z) + exp(x)
248
+
249
+ """
250
+
251
+ from .dense_ndim_array import MutableDenseNDimArray, ImmutableDenseNDimArray, DenseNDimArray
252
+ from .sparse_ndim_array import MutableSparseNDimArray, ImmutableSparseNDimArray, SparseNDimArray
253
+ from .ndim_array import NDimArray, ArrayKind
254
+ from .arrayop import tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims
255
+ from .array_comprehension import ArrayComprehension, ArrayComprehensionMap
256
+
257
+ Array = ImmutableDenseNDimArray
258
+
259
+ __all__ = [
260
+ 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'DenseNDimArray',
261
+
262
+ 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'SparseNDimArray',
263
+
264
+ 'NDimArray', 'ArrayKind',
265
+
266
+ 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array',
267
+
268
+ 'permutedims', 'ArrayComprehension', 'ArrayComprehensionMap',
269
+
270
+ 'Array',
271
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/array_comprehension.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools, itertools
2
+ from sympy.core.sympify import _sympify, sympify
3
+ from sympy.core.expr import Expr
4
+ from sympy.core import Basic, Tuple
5
+ from sympy.tensor.array import ImmutableDenseNDimArray
6
+ from sympy.core.symbol import Symbol
7
+ from sympy.core.numbers import Integer
8
+
9
+
10
+ class ArrayComprehension(Basic):
11
+ """
12
+ Generate a list comprehension.
13
+
14
+ Explanation
15
+ ===========
16
+
17
+ If there is a symbolic dimension, for example, say [i for i in range(1, N)] where
18
+ N is a Symbol, then the expression will not be expanded to an array. Otherwise,
19
+ calling the doit() function will launch the expansion.
20
+
21
+ Examples
22
+ ========
23
+
24
+ >>> from sympy.tensor.array import ArrayComprehension
25
+ >>> from sympy import symbols
26
+ >>> i, j, k = symbols('i j k')
27
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
28
+ >>> a
29
+ ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
30
+ >>> a.doit()
31
+ [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
32
+ >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
33
+ >>> b.doit()
34
+ ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
35
+ """
36
+ def __new__(cls, function, *symbols, **assumptions):
37
+ if any(len(l) != 3 or None for l in symbols):
38
+ raise ValueError('ArrayComprehension requires values lower and upper bound'
39
+ ' for the expression')
40
+ arglist = [sympify(function)]
41
+ arglist.extend(cls._check_limits_validity(function, symbols))
42
+ obj = Basic.__new__(cls, *arglist, **assumptions)
43
+ obj._limits = obj._args[1:]
44
+ obj._shape = cls._calculate_shape_from_limits(obj._limits)
45
+ obj._rank = len(obj._shape)
46
+ obj._loop_size = cls._calculate_loop_size(obj._shape)
47
+ return obj
48
+
49
+ @property
50
+ def function(self):
51
+ """The function applied across limits.
52
+
53
+ Examples
54
+ ========
55
+
56
+ >>> from sympy.tensor.array import ArrayComprehension
57
+ >>> from sympy import symbols
58
+ >>> i, j = symbols('i j')
59
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
60
+ >>> a.function
61
+ 10*i + j
62
+ """
63
+ return self._args[0]
64
+
65
+ @property
66
+ def limits(self):
67
+ """
68
+ The list of limits that will be applied while expanding the array.
69
+
70
+ Examples
71
+ ========
72
+
73
+ >>> from sympy.tensor.array import ArrayComprehension
74
+ >>> from sympy import symbols
75
+ >>> i, j = symbols('i j')
76
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
77
+ >>> a.limits
78
+ ((i, 1, 4), (j, 1, 3))
79
+ """
80
+ return self._limits
81
+
82
+ @property
83
+ def free_symbols(self):
84
+ """
85
+ The set of the free_symbols in the array.
86
+ Variables appeared in the bounds are supposed to be excluded
87
+ from the free symbol set.
88
+
89
+ Examples
90
+ ========
91
+
92
+ >>> from sympy.tensor.array import ArrayComprehension
93
+ >>> from sympy import symbols
94
+ >>> i, j, k = symbols('i j k')
95
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
96
+ >>> a.free_symbols
97
+ set()
98
+ >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
99
+ >>> b.free_symbols
100
+ {k}
101
+ """
102
+ expr_free_sym = self.function.free_symbols
103
+ for var, inf, sup in self._limits:
104
+ expr_free_sym.discard(var)
105
+ curr_free_syms = inf.free_symbols.union(sup.free_symbols)
106
+ expr_free_sym = expr_free_sym.union(curr_free_syms)
107
+ return expr_free_sym
108
+
109
+ @property
110
+ def variables(self):
111
+ """The tuples of the variables in the limits.
112
+
113
+ Examples
114
+ ========
115
+
116
+ >>> from sympy.tensor.array import ArrayComprehension
117
+ >>> from sympy import symbols
118
+ >>> i, j, k = symbols('i j k')
119
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
120
+ >>> a.variables
121
+ [i, j]
122
+ """
123
+ return [l[0] for l in self._limits]
124
+
125
+ @property
126
+ def bound_symbols(self):
127
+ """The list of dummy variables.
128
+
129
+ Note
130
+ ====
131
+
132
+ Note that all variables are dummy variables since a limit without
133
+ lower bound or upper bound is not accepted.
134
+ """
135
+ return [l[0] for l in self._limits if len(l) != 1]
136
+
137
+ @property
138
+ def shape(self):
139
+ """
140
+ The shape of the expanded array, which may have symbols.
141
+
142
+ Note
143
+ ====
144
+
145
+ Both the lower and the upper bounds are included while
146
+ calculating the shape.
147
+
148
+ Examples
149
+ ========
150
+
151
+ >>> from sympy.tensor.array import ArrayComprehension
152
+ >>> from sympy import symbols
153
+ >>> i, j, k = symbols('i j k')
154
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
155
+ >>> a.shape
156
+ (4, 3)
157
+ >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
158
+ >>> b.shape
159
+ (4, k + 3)
160
+ """
161
+ return self._shape
162
+
163
+ @property
164
+ def is_shape_numeric(self):
165
+ """
166
+ Test if the array is shape-numeric which means there is no symbolic
167
+ dimension.
168
+
169
+ Examples
170
+ ========
171
+
172
+ >>> from sympy.tensor.array import ArrayComprehension
173
+ >>> from sympy import symbols
174
+ >>> i, j, k = symbols('i j k')
175
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
176
+ >>> a.is_shape_numeric
177
+ True
178
+ >>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
179
+ >>> b.is_shape_numeric
180
+ False
181
+ """
182
+ for _, inf, sup in self._limits:
183
+ if Basic(inf, sup).atoms(Symbol):
184
+ return False
185
+ return True
186
+
187
+ def rank(self):
188
+ """The rank of the expanded array.
189
+
190
+ Examples
191
+ ========
192
+
193
+ >>> from sympy.tensor.array import ArrayComprehension
194
+ >>> from sympy import symbols
195
+ >>> i, j, k = symbols('i j k')
196
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
197
+ >>> a.rank()
198
+ 2
199
+ """
200
+ return self._rank
201
+
202
+ def __len__(self):
203
+ """
204
+ The length of the expanded array which means the number
205
+ of elements in the array.
206
+
207
+ Raises
208
+ ======
209
+
210
+ ValueError : When the length of the array is symbolic
211
+
212
+ Examples
213
+ ========
214
+
215
+ >>> from sympy.tensor.array import ArrayComprehension
216
+ >>> from sympy import symbols
217
+ >>> i, j = symbols('i j')
218
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
219
+ >>> len(a)
220
+ 12
221
+ """
222
+ if self._loop_size.free_symbols:
223
+ raise ValueError('Symbolic length is not supported')
224
+ return self._loop_size
225
+
226
+ @classmethod
227
+ def _check_limits_validity(cls, function, limits):
228
+ #limits = sympify(limits)
229
+ new_limits = []
230
+ for var, inf, sup in limits:
231
+ var = _sympify(var)
232
+ inf = _sympify(inf)
233
+ #since this is stored as an argument, it should be
234
+ #a Tuple
235
+ if isinstance(sup, list):
236
+ sup = Tuple(*sup)
237
+ else:
238
+ sup = _sympify(sup)
239
+ new_limits.append(Tuple(var, inf, sup))
240
+ if any((not isinstance(i, Expr)) or i.atoms(Symbol, Integer) != i.atoms()
241
+ for i in [inf, sup]):
242
+ raise TypeError('Bounds should be an Expression(combination of Integer and Symbol)')
243
+ if (inf > sup) == True:
244
+ raise ValueError('Lower bound should be inferior to upper bound')
245
+ if var in inf.free_symbols or var in sup.free_symbols:
246
+ raise ValueError('Variable should not be part of its bounds')
247
+ return new_limits
248
+
249
+ @classmethod
250
+ def _calculate_shape_from_limits(cls, limits):
251
+ return tuple([sup - inf + 1 for _, inf, sup in limits])
252
+
253
+ @classmethod
254
+ def _calculate_loop_size(cls, shape):
255
+ if not shape:
256
+ return 0
257
+ loop_size = 1
258
+ for l in shape:
259
+ loop_size = loop_size * l
260
+
261
+ return loop_size
262
+
263
+ def doit(self, **hints):
264
+ if not self.is_shape_numeric:
265
+ return self
266
+
267
+ return self._expand_array()
268
+
269
+ def _expand_array(self):
270
+ res = []
271
+ for values in itertools.product(*[range(inf, sup+1)
272
+ for var, inf, sup
273
+ in self._limits]):
274
+ res.append(self._get_element(values))
275
+
276
+ return ImmutableDenseNDimArray(res, self.shape)
277
+
278
+ def _get_element(self, values):
279
+ temp = self.function
280
+ for var, val in zip(self.variables, values):
281
+ temp = temp.subs(var, val)
282
+ return temp
283
+
284
+ def tolist(self):
285
+ """Transform the expanded array to a list.
286
+
287
+ Raises
288
+ ======
289
+
290
+ ValueError : When there is a symbolic dimension
291
+
292
+ Examples
293
+ ========
294
+
295
+ >>> from sympy.tensor.array import ArrayComprehension
296
+ >>> from sympy import symbols
297
+ >>> i, j = symbols('i j')
298
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
299
+ >>> a.tolist()
300
+ [[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
301
+ """
302
+ if self.is_shape_numeric:
303
+ return self._expand_array().tolist()
304
+
305
+ raise ValueError("A symbolic array cannot be expanded to a list")
306
+
307
+ def tomatrix(self):
308
+ """Transform the expanded array to a matrix.
309
+
310
+ Raises
311
+ ======
312
+
313
+ ValueError : When there is a symbolic dimension
314
+ ValueError : When the rank of the expanded array is not equal to 2
315
+
316
+ Examples
317
+ ========
318
+
319
+ >>> from sympy.tensor.array import ArrayComprehension
320
+ >>> from sympy import symbols
321
+ >>> i, j = symbols('i j')
322
+ >>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
323
+ >>> a.tomatrix()
324
+ Matrix([
325
+ [11, 12, 13],
326
+ [21, 22, 23],
327
+ [31, 32, 33],
328
+ [41, 42, 43]])
329
+ """
330
+ from sympy.matrices import Matrix
331
+
332
+ if not self.is_shape_numeric:
333
+ raise ValueError("A symbolic array cannot be expanded to a matrix")
334
+ if self._rank != 2:
335
+ raise ValueError('Dimensions must be of size of 2')
336
+
337
+ return Matrix(self._expand_array().tomatrix())
338
+
339
+
340
+ def isLambda(v):
341
+ LAMBDA = lambda: 0
342
+ return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
343
+
344
+ class ArrayComprehensionMap(ArrayComprehension):
345
+ '''
346
+ A subclass of ArrayComprehension dedicated to map external function lambda.
347
+
348
+ Notes
349
+ =====
350
+
351
+ Only the lambda function is considered.
352
+ At most one argument in lambda function is accepted in order to avoid ambiguity
353
+ in value assignment.
354
+
355
+ Examples
356
+ ========
357
+
358
+ >>> from sympy.tensor.array import ArrayComprehensionMap
359
+ >>> from sympy import symbols
360
+ >>> i, j, k = symbols('i j k')
361
+ >>> a = ArrayComprehensionMap(lambda: 1, (i, 1, 4))
362
+ >>> a.doit()
363
+ [1, 1, 1, 1]
364
+ >>> b = ArrayComprehensionMap(lambda a: a+1, (j, 1, 4))
365
+ >>> b.doit()
366
+ [2, 3, 4, 5]
367
+
368
+ '''
369
+ def __new__(cls, function, *symbols, **assumptions):
370
+ if any(len(l) != 3 or None for l in symbols):
371
+ raise ValueError('ArrayComprehension requires values lower and upper bound'
372
+ ' for the expression')
373
+
374
+ if not isLambda(function):
375
+ raise ValueError('Data type not supported')
376
+
377
+ arglist = cls._check_limits_validity(function, symbols)
378
+ obj = Basic.__new__(cls, *arglist, **assumptions)
379
+ obj._limits = obj._args
380
+ obj._shape = cls._calculate_shape_from_limits(obj._limits)
381
+ obj._rank = len(obj._shape)
382
+ obj._loop_size = cls._calculate_loop_size(obj._shape)
383
+ obj._lambda = function
384
+ return obj
385
+
386
+ @property
387
+ def func(self):
388
+ class _(ArrayComprehensionMap):
389
+ def __new__(cls, *args, **kwargs):
390
+ return ArrayComprehensionMap(self._lambda, *args, **kwargs)
391
+ return _
392
+
393
+ def _get_element(self, values):
394
+ temp = self._lambda
395
+ if self._lambda.__code__.co_argcount == 0:
396
+ temp = temp()
397
+ elif self._lambda.__code__.co_argcount == 1:
398
+ temp = temp(functools.reduce(lambda a, b: a*b, values))
399
+ return temp
llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/array_derivatives.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.function import Derivative
5
+ from sympy.core.numbers import Integer
6
+ from sympy.matrices.common import MatrixCommon
7
+ from .ndim_array import NDimArray
8
+ from .arrayop import derive_by_array
9
+ from sympy.matrices.expressions.matexpr import MatrixExpr
10
+ from sympy.matrices.expressions.special import ZeroMatrix
11
+ from sympy.matrices.expressions.matexpr import _matrix_derivative
12
+
13
+
14
+ class ArrayDerivative(Derivative):
15
+
16
+ is_scalar = False
17
+
18
+ def __new__(cls, expr, *variables, **kwargs):
19
+ obj = super().__new__(cls, expr, *variables, **kwargs)
20
+ if isinstance(obj, ArrayDerivative):
21
+ obj._shape = obj._get_shape()
22
+ return obj
23
+
24
+ def _get_shape(self):
25
+ shape = ()
26
+ for v, count in self.variable_count:
27
+ if hasattr(v, "shape"):
28
+ for i in range(count):
29
+ shape += v.shape
30
+ if hasattr(self.expr, "shape"):
31
+ shape += self.expr.shape
32
+ return shape
33
+
34
+ @property
35
+ def shape(self):
36
+ return self._shape
37
+
38
+ @classmethod
39
+ def _get_zero_with_shape_like(cls, expr):
40
+ if isinstance(expr, (MatrixCommon, NDimArray)):
41
+ return expr.zeros(*expr.shape)
42
+ elif isinstance(expr, MatrixExpr):
43
+ return ZeroMatrix(*expr.shape)
44
+ else:
45
+ raise RuntimeError("Unable to determine shape of array-derivative.")
46
+
47
+ @staticmethod
48
+ def _call_derive_scalar_by_matrix(expr: Expr, v: MatrixCommon) -> Expr:
49
+ return v.applyfunc(lambda x: expr.diff(x))
50
+
51
+ @staticmethod
52
+ def _call_derive_scalar_by_matexpr(expr: Expr, v: MatrixExpr) -> Expr:
53
+ if expr.has(v):
54
+ return _matrix_derivative(expr, v)
55
+ else:
56
+ return ZeroMatrix(*v.shape)
57
+
58
+ @staticmethod
59
+ def _call_derive_scalar_by_array(expr: Expr, v: NDimArray) -> Expr:
60
+ return v.applyfunc(lambda x: expr.diff(x))
61
+
62
+ @staticmethod
63
+ def _call_derive_matrix_by_scalar(expr: MatrixCommon, v: Expr) -> Expr:
64
+ return _matrix_derivative(expr, v)
65
+
66
+ @staticmethod
67
+ def _call_derive_matexpr_by_scalar(expr: MatrixExpr, v: Expr) -> Expr:
68
+ return expr._eval_derivative(v)
69
+
70
+ @staticmethod
71
+ def _call_derive_array_by_scalar(expr: NDimArray, v: Expr) -> Expr:
72
+ return expr.applyfunc(lambda x: x.diff(v))
73
+
74
+ @staticmethod
75
+ def _call_derive_default(expr: Expr, v: Expr) -> Expr | None:
76
+ if expr.has(v):
77
+ return _matrix_derivative(expr, v)
78
+ else:
79
+ return None
80
+
81
+ @classmethod
82
+ def _dispatch_eval_derivative_n_times(cls, expr, v, count):
83
+ # Evaluate the derivative `n` times. If
84
+ # `_eval_derivative_n_times` is not overridden by the current
85
+ # object, the default in `Basic` will call a loop over
86
+ # `_eval_derivative`:
87
+
88
+ if not isinstance(count, (int, Integer)) or ((count <= 0) == True):
89
+ return None
90
+
91
+ # TODO: this could be done with multiple-dispatching:
92
+ if expr.is_scalar:
93
+ if isinstance(v, MatrixCommon):
94
+ result = cls._call_derive_scalar_by_matrix(expr, v)
95
+ elif isinstance(v, MatrixExpr):
96
+ result = cls._call_derive_scalar_by_matexpr(expr, v)
97
+ elif isinstance(v, NDimArray):
98
+ result = cls._call_derive_scalar_by_array(expr, v)
99
+ elif v.is_scalar:
100
+ # scalar by scalar has a special
101
+ return super()._dispatch_eval_derivative_n_times(expr, v, count)
102
+ else:
103
+ return None
104
+ elif v.is_scalar:
105
+ if isinstance(expr, MatrixCommon):
106
+ result = cls._call_derive_matrix_by_scalar(expr, v)
107
+ elif isinstance(expr, MatrixExpr):
108
+ result = cls._call_derive_matexpr_by_scalar(expr, v)
109
+ elif isinstance(expr, NDimArray):
110
+ result = cls._call_derive_array_by_scalar(expr, v)
111
+ else:
112
+ return None
113
+ else:
114
+ # Both `expr` and `v` are some array/matrix type:
115
+ if isinstance(expr, MatrixCommon) or isinstance(expr, MatrixCommon):
116
+ result = derive_by_array(expr, v)
117
+ elif isinstance(expr, MatrixExpr) and isinstance(v, MatrixExpr):
118
+ result = cls._call_derive_default(expr, v)
119
+ elif isinstance(expr, MatrixExpr) or isinstance(v, MatrixExpr):
120
+ # if one expression is a symbolic matrix expression while the other isn't, don't evaluate:
121
+ return None
122
+ else:
123
+ result = derive_by_array(expr, v)
124
+ if result is None:
125
+ return None
126
+ if count == 1:
127
+ return result
128
+ else:
129
+ return cls._dispatch_eval_derivative_n_times(result, v, count - 1)
llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/arrayop.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from collections.abc import Iterable
3
+
4
+ from sympy.core._print_helpers import Printable
5
+ from sympy.core.containers import Tuple
6
+ from sympy.core.function import diff
7
+ from sympy.core.singleton import S
8
+ from sympy.core.sympify import _sympify
9
+
10
+ from sympy.tensor.array.ndim_array import NDimArray
11
+ from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray
12
+ from sympy.tensor.array.sparse_ndim_array import SparseNDimArray
13
+
14
+
15
+ def _arrayfy(a):
16
+ from sympy.matrices import MatrixBase
17
+
18
+ if isinstance(a, NDimArray):
19
+ return a
20
+ if isinstance(a, (MatrixBase, list, tuple, Tuple)):
21
+ return ImmutableDenseNDimArray(a)
22
+ return a
23
+
24
+
25
+ def tensorproduct(*args):
26
+ """
27
+ Tensor product among scalars or array-like objects.
28
+
29
+ The equivalent operator for array expressions is ``ArrayTensorProduct``,
30
+ which can be used to keep the expression unevaluated.
31
+
32
+ Examples
33
+ ========
34
+
35
+ >>> from sympy.tensor.array import tensorproduct, Array
36
+ >>> from sympy.abc import x, y, z, t
37
+ >>> A = Array([[1, 2], [3, 4]])
38
+ >>> B = Array([x, y])
39
+ >>> tensorproduct(A, B)
40
+ [[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]]
41
+ >>> tensorproduct(A, x)
42
+ [[x, 2*x], [3*x, 4*x]]
43
+ >>> tensorproduct(A, B, B)
44
+ [[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]]
45
+
46
+ Applying this function on two matrices will result in a rank 4 array.
47
+
48
+ >>> from sympy import Matrix, eye
49
+ >>> m = Matrix([[x, y], [z, t]])
50
+ >>> p = tensorproduct(eye(3), m)
51
+ >>> p
52
+ [[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]]
53
+
54
+ See Also
55
+ ========
56
+
57
+ sympy.tensor.array.expressions.array_expressions.ArrayTensorProduct
58
+
59
+ """
60
+ from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray
61
+
62
+ if len(args) == 0:
63
+ return S.One
64
+ if len(args) == 1:
65
+ return _arrayfy(args[0])
66
+ from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
67
+ from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
68
+ from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
69
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
70
+ if any(isinstance(arg, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)) for arg in args):
71
+ return ArrayTensorProduct(*args)
72
+ if len(args) > 2:
73
+ return tensorproduct(tensorproduct(args[0], args[1]), *args[2:])
74
+
75
+ # length of args is 2:
76
+ a, b = map(_arrayfy, args)
77
+
78
+ if not isinstance(a, NDimArray) or not isinstance(b, NDimArray):
79
+ return a*b
80
+
81
+ if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray):
82
+ lp = len(b)
83
+ new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()}
84
+ return ImmutableSparseNDimArray(new_array, a.shape + b.shape)
85
+
86
+ product_list = [i*j for i in Flatten(a) for j in Flatten(b)]
87
+ return ImmutableDenseNDimArray(product_list, a.shape + b.shape)
88
+
89
+
90
+ def _util_contraction_diagonal(array, *contraction_or_diagonal_axes):
91
+ array = _arrayfy(array)
92
+
93
+ # Verify contraction_axes:
94
+ taken_dims = set()
95
+ for axes_group in contraction_or_diagonal_axes:
96
+ if not isinstance(axes_group, Iterable):
97
+ raise ValueError("collections of contraction/diagonal axes expected")
98
+
99
+ dim = array.shape[axes_group[0]]
100
+
101
+ for d in axes_group:
102
+ if d in taken_dims:
103
+ raise ValueError("dimension specified more than once")
104
+ if dim != array.shape[d]:
105
+ raise ValueError("cannot contract or diagonalize between axes of different dimension")
106
+ taken_dims.add(d)
107
+
108
+ rank = array.rank()
109
+
110
+ remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims]
111
+ cum_shape = [0]*rank
112
+ _cumul = 1
113
+ for i in range(rank):
114
+ cum_shape[rank - i - 1] = _cumul
115
+ _cumul *= int(array.shape[rank - i - 1])
116
+
117
+ # DEFINITION: by absolute position it is meant the position along the one
118
+ # dimensional array containing all the tensor components.
119
+
120
+ # Possible future work on this module: move computation of absolute
121
+ # positions to a class method.
122
+
123
+ # Determine absolute positions of the uncontracted indices:
124
+ remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])]
125
+ for i in range(rank) if i not in taken_dims]
126
+
127
+ # Determine absolute positions of the contracted indices:
128
+ summed_deltas = []
129
+ for axes_group in contraction_or_diagonal_axes:
130
+ lidx = []
131
+ for js in range(array.shape[axes_group[0]]):
132
+ lidx.append(sum([cum_shape[ig] * js for ig in axes_group]))
133
+ summed_deltas.append(lidx)
134
+
135
+ return array, remaining_indices, remaining_shape, summed_deltas
136
+
137
+
138
+ def tensorcontraction(array, *contraction_axes):
139
+ """
140
+ Contraction of an array-like object on the specified axes.
141
+
142
+ The equivalent operator for array expressions is ``ArrayContraction``,
143
+ which can be used to keep the expression unevaluated.
144
+
145
+ Examples
146
+ ========
147
+
148
+ >>> from sympy import Array, tensorcontraction
149
+ >>> from sympy import Matrix, eye
150
+ >>> tensorcontraction(eye(3), (0, 1))
151
+ 3
152
+ >>> A = Array(range(18), (3, 2, 3))
153
+ >>> A
154
+ [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
155
+ >>> tensorcontraction(A, (0, 2))
156
+ [21, 30]
157
+
158
+ Matrix multiplication may be emulated with a proper combination of
159
+ ``tensorcontraction`` and ``tensorproduct``
160
+
161
+ >>> from sympy import tensorproduct
162
+ >>> from sympy.abc import a,b,c,d,e,f,g,h
163
+ >>> m1 = Matrix([[a, b], [c, d]])
164
+ >>> m2 = Matrix([[e, f], [g, h]])
165
+ >>> p = tensorproduct(m1, m2)
166
+ >>> p
167
+ [[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]]
168
+ >>> tensorcontraction(p, (1, 2))
169
+ [[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]
170
+ >>> m1*m2
171
+ Matrix([
172
+ [a*e + b*g, a*f + b*h],
173
+ [c*e + d*g, c*f + d*h]])
174
+
175
+ See Also
176
+ ========
177
+
178
+ sympy.tensor.array.expressions.array_expressions.ArrayContraction
179
+
180
+ """
181
+ from sympy.tensor.array.expressions.array_expressions import _array_contraction
182
+ from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
183
+ from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
184
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
185
+ if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
186
+ return _array_contraction(array, *contraction_axes)
187
+
188
+ array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes)
189
+
190
+ # Compute the contracted array:
191
+ #
192
+ # 1. external for loops on all uncontracted indices.
193
+ # Uncontracted indices are determined by the combinatorial product of
194
+ # the absolute positions of the remaining indices.
195
+ # 2. internal loop on all contracted indices.
196
+ # It sums the values of the absolute contracted index and the absolute
197
+ # uncontracted index for the external loop.
198
+ contracted_array = []
199
+ for icontrib in itertools.product(*remaining_indices):
200
+ index_base_position = sum(icontrib)
201
+ isum = S.Zero
202
+ for sum_to_index in itertools.product(*summed_deltas):
203
+ idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
204
+ isum += array[idx]
205
+
206
+ contracted_array.append(isum)
207
+
208
+ if len(remaining_indices) == 0:
209
+ assert len(contracted_array) == 1
210
+ return contracted_array[0]
211
+
212
+ return type(array)(contracted_array, remaining_shape)
213
+
214
+
215
+ def tensordiagonal(array, *diagonal_axes):
216
+ """
217
+ Diagonalization of an array-like object on the specified axes.
218
+
219
+ This is equivalent to multiplying the expression by Kronecker deltas
220
+ uniting the axes.
221
+
222
+ The diagonal indices are put at the end of the axes.
223
+
224
+ The equivalent operator for array expressions is ``ArrayDiagonal``, which
225
+ can be used to keep the expression unevaluated.
226
+
227
+ Examples
228
+ ========
229
+
230
+ ``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is
231
+ equivalent to the diagonal of the matrix:
232
+
233
+ >>> from sympy import Array, tensordiagonal
234
+ >>> from sympy import Matrix, eye
235
+ >>> tensordiagonal(eye(3), (0, 1))
236
+ [1, 1, 1]
237
+
238
+ >>> from sympy.abc import a,b,c,d
239
+ >>> m1 = Matrix([[a, b], [c, d]])
240
+ >>> tensordiagonal(m1, [0, 1])
241
+ [a, d]
242
+
243
+ In case of higher dimensional arrays, the diagonalized out dimensions
244
+ are appended removed and appended as a single dimension at the end:
245
+
246
+ >>> A = Array(range(18), (3, 2, 3))
247
+ >>> A
248
+ [[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
249
+ >>> tensordiagonal(A, (0, 2))
250
+ [[0, 7, 14], [3, 10, 17]]
251
+ >>> from sympy import permutedims
252
+ >>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0])
253
+ True
254
+
255
+ See Also
256
+ ========
257
+
258
+ sympy.tensor.array.expressions.array_expressions.ArrayDiagonal
259
+
260
+ """
261
+ if any(len(i) <= 1 for i in diagonal_axes):
262
+ raise ValueError("need at least two axes to diagonalize")
263
+
264
+ from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
265
+ from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
266
+ from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, _array_diagonal
267
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
268
+ if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
269
+ return _array_diagonal(array, *diagonal_axes)
270
+
271
+ ArrayDiagonal._validate(array, *diagonal_axes)
272
+
273
+ array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes)
274
+
275
+ # Compute the diagonalized array:
276
+ #
277
+ # 1. external for loops on all undiagonalized indices.
278
+ # Undiagonalized indices are determined by the combinatorial product of
279
+ # the absolute positions of the remaining indices.
280
+ # 2. internal loop on all diagonal indices.
281
+ # It appends the values of the absolute diagonalized index and the absolute
282
+ # undiagonalized index for the external loop.
283
+ diagonalized_array = []
284
+ diagonal_shape = [len(i) for i in diagonal_deltas]
285
+ for icontrib in itertools.product(*remaining_indices):
286
+ index_base_position = sum(icontrib)
287
+ isum = []
288
+ for sum_to_index in itertools.product(*diagonal_deltas):
289
+ idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
290
+ isum.append(array[idx])
291
+
292
+ isum = type(array)(isum).reshape(*diagonal_shape)
293
+ diagonalized_array.append(isum)
294
+
295
+ return type(array)(diagonalized_array, remaining_shape + diagonal_shape)
296
+
297
+
298
+ def derive_by_array(expr, dx):
299
+ r"""
300
+ Derivative by arrays. Supports both arrays and scalars.
301
+
302
+ The equivalent operator for array expressions is ``array_derive``.
303
+
304
+ Explanation
305
+ ===========
306
+
307
+ Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
308
+ this function will return a new array `B` defined by
309
+
310
+ `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
311
+
312
+ Examples
313
+ ========
314
+
315
+ >>> from sympy import derive_by_array
316
+ >>> from sympy.abc import x, y, z, t
317
+ >>> from sympy import cos
318
+ >>> derive_by_array(cos(x*t), x)
319
+ -t*sin(t*x)
320
+ >>> derive_by_array(cos(x*t), [x, y, z, t])
321
+ [-t*sin(t*x), 0, 0, -x*sin(t*x)]
322
+ >>> derive_by_array([x, y**2*z], [[x, y], [z, t]])
323
+ [[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]]
324
+
325
+ """
326
+ from sympy.matrices import MatrixBase
327
+ from sympy.tensor.array import SparseNDimArray
328
+ array_types = (Iterable, MatrixBase, NDimArray)
329
+
330
+ if isinstance(dx, array_types):
331
+ dx = ImmutableDenseNDimArray(dx)
332
+ for i in dx:
333
+ if not i._diff_wrt:
334
+ raise ValueError("cannot derive by this array")
335
+
336
+ if isinstance(expr, array_types):
337
+ if isinstance(expr, NDimArray):
338
+ expr = expr.as_immutable()
339
+ else:
340
+ expr = ImmutableDenseNDimArray(expr)
341
+
342
+ if isinstance(dx, array_types):
343
+ if isinstance(expr, SparseNDimArray):
344
+ lp = len(expr)
345
+ new_array = {k + i*lp: v
346
+ for i, x in enumerate(Flatten(dx))
347
+ for k, v in expr.diff(x)._sparse_array.items()}
348
+ else:
349
+ new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)]
350
+ return type(expr)(new_array, dx.shape + expr.shape)
351
+ else:
352
+ return expr.diff(dx)
353
+ else:
354
+ expr = _sympify(expr)
355
+ if isinstance(dx, array_types):
356
+ return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape)
357
+ else:
358
+ dx = _sympify(dx)
359
+ return diff(expr, dx)
360
+
361
+
362
+ def permutedims(expr, perm=None, index_order_old=None, index_order_new=None):
363
+ """
364
+ Permutes the indices of an array.
365
+
366
+ Parameter specifies the permutation of the indices.
367
+
368
+ The equivalent operator for array expressions is ``PermuteDims``, which can
369
+ be used to keep the expression unevaluated.
370
+
371
+ Examples
372
+ ========
373
+
374
+ >>> from sympy.abc import x, y, z, t
375
+ >>> from sympy import sin
376
+ >>> from sympy import Array, permutedims
377
+ >>> a = Array([[x, y, z], [t, sin(x), 0]])
378
+ >>> a
379
+ [[x, y, z], [t, sin(x), 0]]
380
+ >>> permutedims(a, (1, 0))
381
+ [[x, t], [y, sin(x)], [z, 0]]
382
+
383
+ If the array is of second order, ``transpose`` can be used:
384
+
385
+ >>> from sympy import transpose
386
+ >>> transpose(a)
387
+ [[x, t], [y, sin(x)], [z, 0]]
388
+
389
+ Examples on higher dimensions:
390
+
391
+ >>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
392
+ >>> permutedims(b, (2, 1, 0))
393
+ [[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
394
+ >>> permutedims(b, (1, 2, 0))
395
+ [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
396
+
397
+ An alternative way to specify the same permutations as in the previous
398
+ lines involves passing the *old* and *new* indices, either as a list or as
399
+ a string:
400
+
401
+ >>> permutedims(b, index_order_old="cba", index_order_new="abc")
402
+ [[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
403
+ >>> permutedims(b, index_order_old="cab", index_order_new="abc")
404
+ [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
405
+
406
+ ``Permutation`` objects are also allowed:
407
+
408
+ >>> from sympy.combinatorics import Permutation
409
+ >>> permutedims(b, Permutation([1, 2, 0]))
410
+ [[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
411
+
412
+ See Also
413
+ ========
414
+
415
+ sympy.tensor.array.expressions.array_expressions.PermuteDims
416
+
417
+ """
418
+ from sympy.tensor.array import SparseNDimArray
419
+
420
+ from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
421
+ from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
422
+ from sympy.tensor.array.expressions.array_expressions import _permute_dims
423
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
424
+ from sympy.tensor.array.expressions import PermuteDims
425
+ from sympy.tensor.array.expressions.array_expressions import get_rank
426
+ perm = PermuteDims._get_permutation_from_arguments(perm, index_order_old, index_order_new, get_rank(expr))
427
+ if isinstance(expr, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
428
+ return _permute_dims(expr, perm)
429
+
430
+ if not isinstance(expr, NDimArray):
431
+ expr = ImmutableDenseNDimArray(expr)
432
+
433
+ from sympy.combinatorics import Permutation
434
+ if not isinstance(perm, Permutation):
435
+ perm = Permutation(list(perm))
436
+
437
+ if perm.size != expr.rank():
438
+ raise ValueError("wrong permutation size")
439
+
440
+ # Get the inverse permutation:
441
+ iperm = ~perm
442
+ new_shape = perm(expr.shape)
443
+
444
+ if isinstance(expr, SparseNDimArray):
445
+ return type(expr)({tuple(perm(expr._get_tuple_index(k))): v
446
+ for k, v in expr._sparse_array.items()}, new_shape)
447
+
448
+ indices_span = perm([range(i) for i in expr.shape])
449
+
450
+ new_array = [None]*len(expr)
451
+ for i, idx in enumerate(itertools.product(*indices_span)):
452
+ t = iperm(idx)
453
+ new_array[i] = expr[t]
454
+
455
+ return type(expr)(new_array, new_shape)
456
+
457
+
458
+ class Flatten(Printable):
459
+ """
460
+ Flatten an iterable object to a list in a lazy-evaluation way.
461
+
462
+ Notes
463
+ =====
464
+
465
+ This class is an iterator with which the memory cost can be economised.
466
+ Optimisation has been considered to ameliorate the performance for some
467
+ specific data types like DenseNDimArray and SparseNDimArray.
468
+
469
+ Examples
470
+ ========
471
+
472
+ >>> from sympy.tensor.array.arrayop import Flatten
473
+ >>> from sympy.tensor.array import Array
474
+ >>> A = Array(range(6)).reshape(2, 3)
475
+ >>> Flatten(A)
476
+ Flatten([[0, 1, 2], [3, 4, 5]])
477
+ >>> [i for i in Flatten(A)]
478
+ [0, 1, 2, 3, 4, 5]
479
+ """
480
+ def __init__(self, iterable):
481
+ from sympy.matrices.matrices import MatrixBase
482
+ from sympy.tensor.array import NDimArray
483
+
484
+ if not isinstance(iterable, (Iterable, MatrixBase)):
485
+ raise NotImplementedError("Data type not yet supported")
486
+
487
+ if isinstance(iterable, list):
488
+ iterable = NDimArray(iterable)
489
+
490
+ self._iter = iterable
491
+ self._idx = 0
492
+
493
+ def __iter__(self):
494
+ return self
495
+
496
+ def __next__(self):
497
+ from sympy.matrices.matrices import MatrixBase
498
+
499
+ if len(self._iter) > self._idx:
500
+ if isinstance(self._iter, DenseNDimArray):
501
+ result = self._iter._array[self._idx]
502
+
503
+ elif isinstance(self._iter, SparseNDimArray):
504
+ if self._idx in self._iter._sparse_array:
505
+ result = self._iter._sparse_array[self._idx]
506
+ else:
507
+ result = 0
508
+
509
+ elif isinstance(self._iter, MatrixBase):
510
+ result = self._iter[self._idx]
511
+
512
+ elif hasattr(self._iter, '__next__'):
513
+ result = next(self._iter)
514
+
515
+ else:
516
+ result = self._iter[self._idx]
517
+
518
+ else:
519
+ raise StopIteration
520
+
521
+ self._idx += 1
522
+ return result
523
+
524
+ def next(self):
525
+ return self.__next__()
526
+
527
+ def _sympystr(self, printer):
528
+ return type(self).__name__ + '(' + printer._print(self._iter) + ')'
llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/dense_ndim_array.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ from typing import List
3
+
4
+ from sympy.core.basic import Basic
5
+ from sympy.core.containers import Tuple
6
+ from sympy.core.singleton import S
7
+ from sympy.core.sympify import _sympify
8
+ from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
9
+ from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray, ArrayKind
10
+ from sympy.utilities.iterables import flatten
11
+
12
+
13
+ class DenseNDimArray(NDimArray):
14
+
15
+ _array: List[Basic]
16
+
17
+ def __new__(self, *args, **kwargs):
18
+ return ImmutableDenseNDimArray(*args, **kwargs)
19
+
20
+ @property
21
+ def kind(self) -> ArrayKind:
22
+ return ArrayKind._union(self._array)
23
+
24
+ def __getitem__(self, index):
25
+ """
26
+ Allows to get items from N-dim array.
27
+
28
+ Examples
29
+ ========
30
+
31
+ >>> from sympy import MutableDenseNDimArray
32
+ >>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2))
33
+ >>> a
34
+ [[0, 1], [2, 3]]
35
+ >>> a[0, 0]
36
+ 0
37
+ >>> a[1, 1]
38
+ 3
39
+ >>> a[0]
40
+ [0, 1]
41
+ >>> a[1]
42
+ [2, 3]
43
+
44
+
45
+ Symbolic index:
46
+
47
+ >>> from sympy.abc import i, j
48
+ >>> a[i, j]
49
+ [[0, 1], [2, 3]][i, j]
50
+
51
+ Replace `i` and `j` to get element `(1, 1)`:
52
+
53
+ >>> a[i, j].subs({i: 1, j: 1})
54
+ 3
55
+
56
+ """
57
+ syindex = self._check_symbolic_index(index)
58
+ if syindex is not None:
59
+ return syindex
60
+
61
+ index = self._check_index_for_getitem(index)
62
+
63
+ if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
64
+ sl_factors, eindices = self._get_slice_data_for_array_access(index)
65
+ array = [self._array[self._parse_index(i)] for i in eindices]
66
+ nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
67
+ return type(self)(array, nshape)
68
+ else:
69
+ index = self._parse_index(index)
70
+ return self._array[index]
71
+
72
+ @classmethod
73
+ def zeros(cls, *shape):
74
+ list_length = functools.reduce(lambda x, y: x*y, shape, S.One)
75
+ return cls._new(([0]*list_length,), shape)
76
+
77
+ def tomatrix(self):
78
+ """
79
+ Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy import MutableDenseNDimArray
85
+ >>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3))
86
+ >>> b = a.tomatrix()
87
+ >>> b
88
+ Matrix([
89
+ [1, 1, 1],
90
+ [1, 1, 1],
91
+ [1, 1, 1]])
92
+
93
+ """
94
+ from sympy.matrices import Matrix
95
+
96
+ if self.rank() != 2:
97
+ raise ValueError('Dimensions must be of size of 2')
98
+
99
+ return Matrix(self.shape[0], self.shape[1], self._array)
100
+
101
+ def reshape(self, *newshape):
102
+ """
103
+ Returns MutableDenseNDimArray instance with new shape. Elements number
104
+ must be suitable to new shape. The only argument of method sets
105
+ new shape.
106
+
107
+ Examples
108
+ ========
109
+
110
+ >>> from sympy import MutableDenseNDimArray
111
+ >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
112
+ >>> a.shape
113
+ (2, 3)
114
+ >>> a
115
+ [[1, 2, 3], [4, 5, 6]]
116
+ >>> b = a.reshape(3, 2)
117
+ >>> b.shape
118
+ (3, 2)
119
+ >>> b
120
+ [[1, 2], [3, 4], [5, 6]]
121
+
122
+ """
123
+ new_total_size = functools.reduce(lambda x,y: x*y, newshape)
124
+ if new_total_size != self._loop_size:
125
+ raise ValueError('Expecting reshape size to %d but got prod(%s) = %d' % (
126
+ self._loop_size, str(newshape), new_total_size))
127
+
128
+ # there is no `.func` as this class does not subtype `Basic`:
129
+ return type(self)(self._array, newshape)
130
+
131
+
132
+ class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray): # type: ignore
133
+ def __new__(cls, iterable, shape=None, **kwargs):
134
+ return cls._new(iterable, shape, **kwargs)
135
+
136
+ @classmethod
137
+ def _new(cls, iterable, shape, **kwargs):
138
+ shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
139
+ shape = Tuple(*map(_sympify, shape))
140
+ cls._check_special_bounds(flat_list, shape)
141
+ flat_list = flatten(flat_list)
142
+ flat_list = Tuple(*flat_list)
143
+ self = Basic.__new__(cls, flat_list, shape, **kwargs)
144
+ self._shape = shape
145
+ self._array = list(flat_list)
146
+ self._rank = len(shape)
147
+ self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1)
148
+ return self
149
+
150
+ def __setitem__(self, index, value):
151
+ raise TypeError('immutable N-dim array')
152
+
153
+ def as_mutable(self):
154
+ return MutableDenseNDimArray(self)
155
+
156
+ def _eval_simplify(self, **kwargs):
157
+ from sympy.simplify.simplify import simplify
158
+ return self.applyfunc(simplify)
159
+
160
+ class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray):
161
+
162
+ def __new__(cls, iterable=None, shape=None, **kwargs):
163
+ return cls._new(iterable, shape, **kwargs)
164
+
165
+ @classmethod
166
+ def _new(cls, iterable, shape, **kwargs):
167
+ shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
168
+ flat_list = flatten(flat_list)
169
+ self = object.__new__(cls)
170
+ self._shape = shape
171
+ self._array = list(flat_list)
172
+ self._rank = len(shape)
173
+ self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
174
+ return self
175
+
176
+ def __setitem__(self, index, value):
177
+ """Allows to set items to MutableDenseNDimArray.
178
+
179
+ Examples
180
+ ========
181
+
182
+ >>> from sympy import MutableDenseNDimArray
183
+ >>> a = MutableDenseNDimArray.zeros(2, 2)
184
+ >>> a[0,0] = 1
185
+ >>> a[1,1] = 1
186
+ >>> a
187
+ [[1, 0], [0, 1]]
188
+
189
+ """
190
+ if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
191
+ value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
192
+ for i in eindices:
193
+ other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
194
+ self._array[self._parse_index(i)] = value[other_i]
195
+ else:
196
+ index = self._parse_index(index)
197
+ self._setter_iterable_check(value)
198
+ value = _sympify(value)
199
+ self._array[index] = value
200
+
201
+ def as_immutable(self):
202
+ return ImmutableDenseNDimArray(self)
203
+
204
+ @property
205
+ def free_symbols(self):
206
+ return {i for j in self._array for i in j.free_symbols}
llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/mutable_ndim_array.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.tensor.array.ndim_array import NDimArray
2
+
3
+
4
+ class MutableNDimArray(NDimArray):
5
+
6
+ def as_immutable(self):
7
+ raise NotImplementedError("abstract method")
8
+
9
+ def as_mutable(self):
10
+ return self
11
+
12
+ def _sympy_(self):
13
+ return self.as_immutable()
llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/ndim_array.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.core.containers import (Dict, Tuple)
3
+ from sympy.core.expr import Expr
4
+ from sympy.core.kind import Kind, NumberKind, UndefinedKind
5
+ from sympy.core.numbers import Integer
6
+ from sympy.core.singleton import S
7
+ from sympy.core.sympify import sympify
8
+ from sympy.external.gmpy import SYMPY_INTS
9
+ from sympy.printing.defaults import Printable
10
+
11
+ import itertools
12
+ from collections.abc import Iterable
13
+
14
+
15
+ class ArrayKind(Kind):
16
+ """
17
+ Kind for N-dimensional array in SymPy.
18
+
19
+ This kind represents the multidimensional array that algebraic
20
+ operations are defined. Basic class for this kind is ``NDimArray``,
21
+ but any expression representing the array can have this.
22
+
23
+ Parameters
24
+ ==========
25
+
26
+ element_kind : Kind
27
+ Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`,
28
+ which means that the array contains only numbers.
29
+
30
+ Examples
31
+ ========
32
+
33
+ Any instance of array class has ``ArrayKind``.
34
+
35
+ >>> from sympy import NDimArray
36
+ >>> NDimArray([1,2,3]).kind
37
+ ArrayKind(NumberKind)
38
+
39
+ Although expressions representing an array may be not instance of
40
+ array class, it will have ``ArrayKind`` as well.
41
+
42
+ >>> from sympy import Integral
43
+ >>> from sympy.tensor.array import NDimArray
44
+ >>> from sympy.abc import x
45
+ >>> intA = Integral(NDimArray([1,2,3]), x)
46
+ >>> isinstance(intA, NDimArray)
47
+ False
48
+ >>> intA.kind
49
+ ArrayKind(NumberKind)
50
+
51
+ Use ``isinstance()`` to check for ``ArrayKind` without specifying
52
+ the element kind. Use ``is`` with specifying the element kind.
53
+
54
+ >>> from sympy.tensor.array import ArrayKind
55
+ >>> from sympy.core import NumberKind
56
+ >>> boolA = NDimArray([True, False])
57
+ >>> isinstance(boolA.kind, ArrayKind)
58
+ True
59
+ >>> boolA.kind is ArrayKind(NumberKind)
60
+ False
61
+
62
+ See Also
63
+ ========
64
+
65
+ shape : Function to return the shape of objects with ``MatrixKind``.
66
+
67
+ """
68
+ def __new__(cls, element_kind=NumberKind):
69
+ obj = super().__new__(cls, element_kind)
70
+ obj.element_kind = element_kind
71
+ return obj
72
+
73
+ def __repr__(self):
74
+ return "ArrayKind(%s)" % self.element_kind
75
+
76
+ @classmethod
77
+ def _union(cls, kinds) -> 'ArrayKind':
78
+ elem_kinds = {e.kind for e in kinds}
79
+ if len(elem_kinds) == 1:
80
+ elemkind, = elem_kinds
81
+ else:
82
+ elemkind = UndefinedKind
83
+ return ArrayKind(elemkind)
84
+
85
+
86
+ class NDimArray(Printable):
87
+ """N-dimensional array.
88
+
89
+ Examples
90
+ ========
91
+
92
+ Create an N-dim array of zeros:
93
+
94
+ >>> from sympy import MutableDenseNDimArray
95
+ >>> a = MutableDenseNDimArray.zeros(2, 3, 4)
96
+ >>> a
97
+ [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
98
+
99
+ Create an N-dim array from a list;
100
+
101
+ >>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
102
+ >>> a
103
+ [[2, 3], [4, 5]]
104
+
105
+ >>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
106
+ >>> b
107
+ [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
108
+
109
+ Create an N-dim array from a flat list with dimension shape:
110
+
111
+ >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
112
+ >>> a
113
+ [[1, 2, 3], [4, 5, 6]]
114
+
115
+ Create an N-dim array from a matrix:
116
+
117
+ >>> from sympy import Matrix
118
+ >>> a = Matrix([[1,2],[3,4]])
119
+ >>> a
120
+ Matrix([
121
+ [1, 2],
122
+ [3, 4]])
123
+ >>> b = MutableDenseNDimArray(a)
124
+ >>> b
125
+ [[1, 2], [3, 4]]
126
+
127
+ Arithmetic operations on N-dim arrays
128
+
129
+ >>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
130
+ >>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
131
+ >>> c = a + b
132
+ >>> c
133
+ [[5, 5], [5, 5]]
134
+ >>> a - b
135
+ [[-3, -3], [-3, -3]]
136
+
137
+ """
138
+
139
+ _diff_wrt = True
140
+ is_scalar = False
141
+
142
+ def __new__(cls, iterable, shape=None, **kwargs):
143
+ from sympy.tensor.array import ImmutableDenseNDimArray
144
+ return ImmutableDenseNDimArray(iterable, shape, **kwargs)
145
+
146
+ def __getitem__(self, index):
147
+ raise NotImplementedError("A subclass of NDimArray should implement __getitem__")
148
+
149
+ def _parse_index(self, index):
150
+ if isinstance(index, (SYMPY_INTS, Integer)):
151
+ if index >= self._loop_size:
152
+ raise ValueError("Only a tuple index is accepted")
153
+ return index
154
+
155
+ if self._loop_size == 0:
156
+ raise ValueError("Index not valid with an empty array")
157
+
158
+ if len(index) != self._rank:
159
+ raise ValueError('Wrong number of array axes')
160
+
161
+ real_index = 0
162
+ # check if input index can exist in current indexing
163
+ for i in range(self._rank):
164
+ if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
165
+ raise ValueError('Index ' + str(index) + ' out of border')
166
+ if index[i] < 0:
167
+ real_index += 1
168
+ real_index = real_index*self.shape[i] + index[i]
169
+
170
+ return real_index
171
+
172
+ def _get_tuple_index(self, integer_index):
173
+ index = []
174
+ for i, sh in enumerate(reversed(self.shape)):
175
+ index.append(integer_index % sh)
176
+ integer_index //= sh
177
+ index.reverse()
178
+ return tuple(index)
179
+
180
+ def _check_symbolic_index(self, index):
181
+ # Check if any index is symbolic:
182
+ tuple_index = (index if isinstance(index, tuple) else (index,))
183
+ if any((isinstance(i, Expr) and (not i.is_number)) for i in tuple_index):
184
+ for i, nth_dim in zip(tuple_index, self.shape):
185
+ if ((i < 0) == True) or ((i >= nth_dim) == True):
186
+ raise ValueError("index out of range")
187
+ from sympy.tensor import Indexed
188
+ return Indexed(self, *tuple_index)
189
+ return None
190
+
191
+ def _setter_iterable_check(self, value):
192
+ from sympy.matrices.matrices import MatrixBase
193
+ if isinstance(value, (Iterable, MatrixBase, NDimArray)):
194
+ raise NotImplementedError
195
+
196
+ @classmethod
197
+ def _scan_iterable_shape(cls, iterable):
198
+ def f(pointer):
199
+ if not isinstance(pointer, Iterable):
200
+ return [pointer], ()
201
+
202
+ if len(pointer) == 0:
203
+ return [], (0,)
204
+
205
+ result = []
206
+ elems, shapes = zip(*[f(i) for i in pointer])
207
+ if len(set(shapes)) != 1:
208
+ raise ValueError("could not determine shape unambiguously")
209
+ for i in elems:
210
+ result.extend(i)
211
+ return result, (len(shapes),)+shapes[0]
212
+
213
+ return f(iterable)
214
+
215
+ @classmethod
216
+ def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
217
+ from sympy.matrices.matrices import MatrixBase
218
+ from sympy.tensor.array import SparseNDimArray
219
+
220
+ if shape is None:
221
+ if iterable is None:
222
+ shape = ()
223
+ iterable = ()
224
+ # Construction of a sparse array from a sparse array
225
+ elif isinstance(iterable, SparseNDimArray):
226
+ return iterable._shape, iterable._sparse_array
227
+
228
+ # Construct N-dim array from another N-dim array:
229
+ elif isinstance(iterable, NDimArray):
230
+ shape = iterable.shape
231
+
232
+ # Construct N-dim array from an iterable (numpy arrays included):
233
+ elif isinstance(iterable, Iterable):
234
+ iterable, shape = cls._scan_iterable_shape(iterable)
235
+
236
+ # Construct N-dim array from a Matrix:
237
+ elif isinstance(iterable, MatrixBase):
238
+ shape = iterable.shape
239
+
240
+ else:
241
+ shape = ()
242
+ iterable = (iterable,)
243
+
244
+ if isinstance(iterable, (Dict, dict)) and shape is not None:
245
+ new_dict = iterable.copy()
246
+ for k, v in new_dict.items():
247
+ if isinstance(k, (tuple, Tuple)):
248
+ new_key = 0
249
+ for i, idx in enumerate(k):
250
+ new_key = new_key * shape[i] + idx
251
+ iterable[new_key] = iterable[k]
252
+ del iterable[k]
253
+
254
+ if isinstance(shape, (SYMPY_INTS, Integer)):
255
+ shape = (shape,)
256
+
257
+ if not all(isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape):
258
+ raise TypeError("Shape should contain integers only.")
259
+
260
+ return tuple(shape), iterable
261
+
262
+ def __len__(self):
263
+ """Overload common function len(). Returns number of elements in array.
264
+
265
+ Examples
266
+ ========
267
+
268
+ >>> from sympy import MutableDenseNDimArray
269
+ >>> a = MutableDenseNDimArray.zeros(3, 3)
270
+ >>> a
271
+ [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
272
+ >>> len(a)
273
+ 9
274
+
275
+ """
276
+ return self._loop_size
277
+
278
+ @property
279
+ def shape(self):
280
+ """
281
+ Returns array shape (dimension).
282
+
283
+ Examples
284
+ ========
285
+
286
+ >>> from sympy import MutableDenseNDimArray
287
+ >>> a = MutableDenseNDimArray.zeros(3, 3)
288
+ >>> a.shape
289
+ (3, 3)
290
+
291
+ """
292
+ return self._shape
293
+
294
+ def rank(self):
295
+ """
296
+ Returns rank of array.
297
+
298
+ Examples
299
+ ========
300
+
301
+ >>> from sympy import MutableDenseNDimArray
302
+ >>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
303
+ >>> a.rank()
304
+ 5
305
+
306
+ """
307
+ return self._rank
308
+
309
+ def diff(self, *args, **kwargs):
310
+ """
311
+ Calculate the derivative of each element in the array.
312
+
313
+ Examples
314
+ ========
315
+
316
+ >>> from sympy import ImmutableDenseNDimArray
317
+ >>> from sympy.abc import x, y
318
+ >>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
319
+ >>> M.diff(x)
320
+ [[1, 0], [0, y]]
321
+
322
+ """
323
+ from sympy.tensor.array.array_derivatives import ArrayDerivative
324
+ kwargs.setdefault('evaluate', True)
325
+ return ArrayDerivative(self.as_immutable(), *args, **kwargs)
326
+
327
+ def _eval_derivative(self, base):
328
+ # Types are (base: scalar, self: array)
329
+ return self.applyfunc(lambda x: base.diff(x))
330
+
331
+ def _eval_derivative_n_times(self, s, n):
332
+ return Basic._eval_derivative_n_times(self, s, n)
333
+
334
+ def applyfunc(self, f):
335
+ """Apply a function to each element of the N-dim array.
336
+
337
+ Examples
338
+ ========
339
+
340
+ >>> from sympy import ImmutableDenseNDimArray
341
+ >>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
342
+ >>> m
343
+ [[0, 1], [2, 3]]
344
+ >>> m.applyfunc(lambda i: 2*i)
345
+ [[0, 2], [4, 6]]
346
+ """
347
+ from sympy.tensor.array import SparseNDimArray
348
+ from sympy.tensor.array.arrayop import Flatten
349
+
350
+ if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
351
+ return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
352
+
353
+ return type(self)(map(f, Flatten(self)), self.shape)
354
+
355
+ def _sympystr(self, printer):
356
+ def f(sh, shape_left, i, j):
357
+ if len(shape_left) == 1:
358
+ return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
359
+
360
+ sh //= shape_left[0]
361
+ return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
362
+
363
+ if self.rank() == 0:
364
+ return printer._print(self[()])
365
+
366
+ return f(self._loop_size, self.shape, 0, self._loop_size)
367
+
368
+ def tolist(self):
369
+ """
370
+ Converting MutableDenseNDimArray to one-dim list
371
+
372
+ Examples
373
+ ========
374
+
375
+ >>> from sympy import MutableDenseNDimArray
376
+ >>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
377
+ >>> a
378
+ [[1, 2], [3, 4]]
379
+ >>> b = a.tolist()
380
+ >>> b
381
+ [[1, 2], [3, 4]]
382
+ """
383
+
384
+ def f(sh, shape_left, i, j):
385
+ if len(shape_left) == 1:
386
+ return [self[self._get_tuple_index(e)] for e in range(i, j)]
387
+ result = []
388
+ sh //= shape_left[0]
389
+ for e in range(shape_left[0]):
390
+ result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
391
+ return result
392
+
393
+ return f(self._loop_size, self.shape, 0, self._loop_size)
394
+
395
+ def __add__(self, other):
396
+ from sympy.tensor.array.arrayop import Flatten
397
+
398
+ if not isinstance(other, NDimArray):
399
+ return NotImplemented
400
+
401
+ if self.shape != other.shape:
402
+ raise ValueError("array shape mismatch")
403
+ result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
404
+
405
+ return type(self)(result_list, self.shape)
406
+
407
+ def __sub__(self, other):
408
+ from sympy.tensor.array.arrayop import Flatten
409
+
410
+ if not isinstance(other, NDimArray):
411
+ return NotImplemented
412
+
413
+ if self.shape != other.shape:
414
+ raise ValueError("array shape mismatch")
415
+ result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
416
+
417
+ return type(self)(result_list, self.shape)
418
+
419
+ def __mul__(self, other):
420
+ from sympy.matrices.matrices import MatrixBase
421
+ from sympy.tensor.array import SparseNDimArray
422
+ from sympy.tensor.array.arrayop import Flatten
423
+
424
+ if isinstance(other, (Iterable, NDimArray, MatrixBase)):
425
+ raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
426
+
427
+ other = sympify(other)
428
+ if isinstance(self, SparseNDimArray):
429
+ if other.is_zero:
430
+ return type(self)({}, self.shape)
431
+ return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
432
+
433
+ result_list = [i*other for i in Flatten(self)]
434
+ return type(self)(result_list, self.shape)
435
+
436
+ def __rmul__(self, other):
437
+ from sympy.matrices.matrices import MatrixBase
438
+ from sympy.tensor.array import SparseNDimArray
439
+ from sympy.tensor.array.arrayop import Flatten
440
+
441
+ if isinstance(other, (Iterable, NDimArray, MatrixBase)):
442
+ raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
443
+
444
+ other = sympify(other)
445
+ if isinstance(self, SparseNDimArray):
446
+ if other.is_zero:
447
+ return type(self)({}, self.shape)
448
+ return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
449
+
450
+ result_list = [other*i for i in Flatten(self)]
451
+ return type(self)(result_list, self.shape)
452
+
453
+ def __truediv__(self, other):
454
+ from sympy.matrices.matrices import MatrixBase
455
+ from sympy.tensor.array import SparseNDimArray
456
+ from sympy.tensor.array.arrayop import Flatten
457
+
458
+ if isinstance(other, (Iterable, NDimArray, MatrixBase)):
459
+ raise ValueError("scalar expected")
460
+
461
+ other = sympify(other)
462
+ if isinstance(self, SparseNDimArray) and other != S.Zero:
463
+ return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
464
+
465
+ result_list = [i/other for i in Flatten(self)]
466
+ return type(self)(result_list, self.shape)
467
+
468
+ def __rtruediv__(self, other):
469
+ raise NotImplementedError('unsupported operation on NDimArray')
470
+
471
+ def __neg__(self):
472
+ from sympy.tensor.array import SparseNDimArray
473
+ from sympy.tensor.array.arrayop import Flatten
474
+
475
+ if isinstance(self, SparseNDimArray):
476
+ return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
477
+
478
+ result_list = [-i for i in Flatten(self)]
479
+ return type(self)(result_list, self.shape)
480
+
481
+ def __iter__(self):
482
+ def iterator():
483
+ if self._shape:
484
+ for i in range(self._shape[0]):
485
+ yield self[i]
486
+ else:
487
+ yield self[()]
488
+
489
+ return iterator()
490
+
491
+ def __eq__(self, other):
492
+ """
493
+ NDimArray instances can be compared to each other.
494
+ Instances equal if they have same shape and data.
495
+
496
+ Examples
497
+ ========
498
+
499
+ >>> from sympy import MutableDenseNDimArray
500
+ >>> a = MutableDenseNDimArray.zeros(2, 3)
501
+ >>> b = MutableDenseNDimArray.zeros(2, 3)
502
+ >>> a == b
503
+ True
504
+ >>> c = a.reshape(3, 2)
505
+ >>> c == b
506
+ False
507
+ >>> a[0,0] = 1
508
+ >>> b[0,0] = 2
509
+ >>> a == b
510
+ False
511
+ """
512
+ from sympy.tensor.array import SparseNDimArray
513
+ if not isinstance(other, NDimArray):
514
+ return False
515
+
516
+ if not self.shape == other.shape:
517
+ return False
518
+
519
+ if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
520
+ return dict(self._sparse_array) == dict(other._sparse_array)
521
+
522
+ return list(self) == list(other)
523
+
524
+ def __ne__(self, other):
525
+ return not self == other
526
+
527
+ def _eval_transpose(self):
528
+ if self.rank() != 2:
529
+ raise ValueError("array rank not 2")
530
+ from .arrayop import permutedims
531
+ return permutedims(self, (1, 0))
532
+
533
+ def transpose(self):
534
+ return self._eval_transpose()
535
+
536
+ def _eval_conjugate(self):
537
+ from sympy.tensor.array.arrayop import Flatten
538
+
539
+ return self.func([i.conjugate() for i in Flatten(self)], self.shape)
540
+
541
+ def conjugate(self):
542
+ return self._eval_conjugate()
543
+
544
+ def _eval_adjoint(self):
545
+ return self.transpose().conjugate()
546
+
547
+ def adjoint(self):
548
+ return self._eval_adjoint()
549
+
550
+ def _slice_expand(self, s, dim):
551
+ if not isinstance(s, slice):
552
+ return (s,)
553
+ start, stop, step = s.indices(dim)
554
+ return [start + i*step for i in range((stop-start)//step)]
555
+
556
+ def _get_slice_data_for_array_access(self, index):
557
+ sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
558
+ eindices = itertools.product(*sl_factors)
559
+ return sl_factors, eindices
560
+
561
+ def _get_slice_data_for_array_assignment(self, index, value):
562
+ if not isinstance(value, NDimArray):
563
+ value = type(self)(value)
564
+ sl_factors, eindices = self._get_slice_data_for_array_access(index)
565
+ slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
566
+ # TODO: add checks for dimensions for `value`?
567
+ return value, eindices, slice_offsets
568
+
569
+ @classmethod
570
+ def _check_special_bounds(cls, flat_list, shape):
571
+ if shape == () and len(flat_list) != 1:
572
+ raise ValueError("arrays without shape need one scalar value")
573
+ if shape == (0,) and len(flat_list) > 0:
574
+ raise ValueError("if array shape is (0,) there cannot be elements")
575
+
576
+ def _check_index_for_getitem(self, index):
577
+ if isinstance(index, (SYMPY_INTS, Integer, slice)):
578
+ index = (index,)
579
+
580
+ if len(index) < self.rank():
581
+ index = tuple(index) + \
582
+ tuple(slice(None) for i in range(len(index), self.rank()))
583
+
584
+ if len(index) > self.rank():
585
+ raise ValueError('Dimension of index greater than rank of array')
586
+
587
+ return index
588
+
589
+
590
+ class ImmutableNDimArray(NDimArray, Basic):
591
+ _op_priority = 11.0
592
+
593
+ def __hash__(self):
594
+ return Basic.__hash__(self)
595
+
596
+ def as_immutable(self):
597
+ return self
598
+
599
+ def as_mutable(self):
600
+ raise NotImplementedError("abstract method")
llmeval-env/lib/python3.10/site-packages/sympy/tensor/array/sparse_ndim_array.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.core.containers import (Dict, Tuple)
3
+ from sympy.core.singleton import S
4
+ from sympy.core.sympify import _sympify
5
+ from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
6
+ from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray
7
+ from sympy.utilities.iterables import flatten
8
+
9
+ import functools
10
+
11
+ class SparseNDimArray(NDimArray):
12
+
13
+ def __new__(self, *args, **kwargs):
14
+ return ImmutableSparseNDimArray(*args, **kwargs)
15
+
16
+ def __getitem__(self, index):
17
+ """
18
+ Get an element from a sparse N-dim array.
19
+
20
+ Examples
21
+ ========
22
+
23
+ >>> from sympy import MutableSparseNDimArray
24
+ >>> a = MutableSparseNDimArray(range(4), (2, 2))
25
+ >>> a
26
+ [[0, 1], [2, 3]]
27
+ >>> a[0, 0]
28
+ 0
29
+ >>> a[1, 1]
30
+ 3
31
+ >>> a[0]
32
+ [0, 1]
33
+ >>> a[1]
34
+ [2, 3]
35
+
36
+ Symbolic indexing:
37
+
38
+ >>> from sympy.abc import i, j
39
+ >>> a[i, j]
40
+ [[0, 1], [2, 3]][i, j]
41
+
42
+ Replace `i` and `j` to get element `(0, 0)`:
43
+
44
+ >>> a[i, j].subs({i: 0, j: 0})
45
+ 0
46
+
47
+ """
48
+ syindex = self._check_symbolic_index(index)
49
+ if syindex is not None:
50
+ return syindex
51
+
52
+ index = self._check_index_for_getitem(index)
53
+
54
+ # `index` is a tuple with one or more slices:
55
+ if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
56
+ sl_factors, eindices = self._get_slice_data_for_array_access(index)
57
+ array = [self._sparse_array.get(self._parse_index(i), S.Zero) for i in eindices]
58
+ nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
59
+ return type(self)(array, nshape)
60
+ else:
61
+ index = self._parse_index(index)
62
+ return self._sparse_array.get(index, S.Zero)
63
+
64
+ @classmethod
65
+ def zeros(cls, *shape):
66
+ """
67
+ Return a sparse N-dim array of zeros.
68
+ """
69
+ return cls({}, shape)
70
+
71
+ def tomatrix(self):
72
+ """
73
+ Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
74
+
75
+ Examples
76
+ ========
77
+
78
+ >>> from sympy import MutableSparseNDimArray
79
+ >>> a = MutableSparseNDimArray([1 for i in range(9)], (3, 3))
80
+ >>> b = a.tomatrix()
81
+ >>> b
82
+ Matrix([
83
+ [1, 1, 1],
84
+ [1, 1, 1],
85
+ [1, 1, 1]])
86
+ """
87
+ from sympy.matrices import SparseMatrix
88
+ if self.rank() != 2:
89
+ raise ValueError('Dimensions must be of size of 2')
90
+
91
+ mat_sparse = {}
92
+ for key, value in self._sparse_array.items():
93
+ mat_sparse[self._get_tuple_index(key)] = value
94
+
95
+ return SparseMatrix(self.shape[0], self.shape[1], mat_sparse)
96
+
97
+ def reshape(self, *newshape):
98
+ new_total_size = functools.reduce(lambda x,y: x*y, newshape)
99
+ if new_total_size != self._loop_size:
100
+ raise ValueError("Invalid reshape parameters " + newshape)
101
+
102
+ return type(self)(self._sparse_array, newshape)
103
+
104
+ class ImmutableSparseNDimArray(SparseNDimArray, ImmutableNDimArray): # type: ignore
105
+
106
+ def __new__(cls, iterable=None, shape=None, **kwargs):
107
+ shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
108
+ shape = Tuple(*map(_sympify, shape))
109
+ cls._check_special_bounds(flat_list, shape)
110
+ loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
111
+
112
+ # Sparse array:
113
+ if isinstance(flat_list, (dict, Dict)):
114
+ sparse_array = Dict(flat_list)
115
+ else:
116
+ sparse_array = {}
117
+ for i, el in enumerate(flatten(flat_list)):
118
+ if el != 0:
119
+ sparse_array[i] = _sympify(el)
120
+
121
+ sparse_array = Dict(sparse_array)
122
+
123
+ self = Basic.__new__(cls, sparse_array, shape, **kwargs)
124
+ self._shape = shape
125
+ self._rank = len(shape)
126
+ self._loop_size = loop_size
127
+ self._sparse_array = sparse_array
128
+
129
+ return self
130
+
131
+ def __setitem__(self, index, value):
132
+ raise TypeError("immutable N-dim array")
133
+
134
+ def as_mutable(self):
135
+ return MutableSparseNDimArray(self)
136
+
137
+
138
+ class MutableSparseNDimArray(MutableNDimArray, SparseNDimArray):
139
+
140
+ def __new__(cls, iterable=None, shape=None, **kwargs):
141
+ shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
142
+ self = object.__new__(cls)
143
+ self._shape = shape
144
+ self._rank = len(shape)
145
+ self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
146
+
147
+ # Sparse array:
148
+ if isinstance(flat_list, (dict, Dict)):
149
+ self._sparse_array = dict(flat_list)
150
+ return self
151
+
152
+ self._sparse_array = {}
153
+
154
+ for i, el in enumerate(flatten(flat_list)):
155
+ if el != 0:
156
+ self._sparse_array[i] = _sympify(el)
157
+
158
+ return self
159
+
160
+ def __setitem__(self, index, value):
161
+ """Allows to set items to MutableDenseNDimArray.
162
+
163
+ Examples
164
+ ========
165
+
166
+ >>> from sympy import MutableSparseNDimArray
167
+ >>> a = MutableSparseNDimArray.zeros(2, 2)
168
+ >>> a[0, 0] = 1
169
+ >>> a[1, 1] = 1
170
+ >>> a
171
+ [[1, 0], [0, 1]]
172
+ """
173
+ if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
174
+ value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
175
+ for i in eindices:
176
+ other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
177
+ other_value = value[other_i]
178
+ complete_index = self._parse_index(i)
179
+ if other_value != 0:
180
+ self._sparse_array[complete_index] = other_value
181
+ elif complete_index in self._sparse_array:
182
+ self._sparse_array.pop(complete_index)
183
+ else:
184
+ index = self._parse_index(index)
185
+ value = _sympify(value)
186
+ if value == 0 and index in self._sparse_array:
187
+ self._sparse_array.pop(index)
188
+ else:
189
+ self._sparse_array[index] = value
190
+
191
+ def as_immutable(self):
192
+ return ImmutableSparseNDimArray(self)
193
+
194
+ @property
195
+ def free_symbols(self):
196
+ return {i for j in self._sparse_array.values() for i in j.free_symbols}