s42chen commited on
Commit
6673bc9
·
verified ·
1 Parent(s): bd347f9

Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 31)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +30 -0
  2. shared/package-files/8b/8b708a4ae3f837f3c08fba3e09b93cccf11d16cd0259604201f8362570f1e55f/blob +0 -0
  3. shared/package-files/8b/8b70c48d5a6b496a9281fec532dfb15c5ab470a65eb0b3baedea082b186b8eb8/blob +0 -0
  4. shared/package-files/8b/8b71472317bf3adabf819e665c725d03e3064baa45f6ffbfd78cca83eaa46e8d/blob +70 -0
  5. shared/package-files/8b/8b720740d5d007214c0af8e3c9dfe1c302520a2523d33d6b4704bd5852b60057/blob +196 -0
  6. shared/package-files/8b/8b733ea1edb0f9d08a0245ea92a765985b083b214a570d5fb50799bacd9c3be6/blob +89 -0
  7. shared/package-files/8b/8b77e6c948fb88a4c36fc94c5fac6b974e5d8cb0167dfba63cd0558b7e8fb4a2/blob +3 -0
  8. shared/package-files/8b/8b784d08319ab7ff0320c1c5a36d9db3dc77e12ca55f6abd56ef9610b022fed5/blob +81 -0
  9. shared/package-files/8b/8b78797c860c531e3ffcca1cecca52d532df2bc4aedfe8857dab8e5d70146f86/blob +550 -0
  10. shared/package-files/8b/8b790ac38c4ee3ff7d7c93753bba315c694f53ea8c24a0cf8ab6d6693c3be93a/blob +365 -0
  11. shared/package-files/8b/8b7ae587d5e6626d839e50e6bdbaaf7778f29bab25a57b9866ccec713ec6ce15/blob +88 -0
  12. shared/package-files/8b/8b7b8f573b4784884ded9423b548f06d1deabe36673008b8a8a784d31e49539b/blob +50 -0
  13. shared/package-files/8b/8b7c37207ece2c8fce70644de6738aadc1c4262f356485f699f83b4cffe3a880/blob +442 -0
  14. shared/package-files/8b/8b7d767810c385f42c26a20463b1cb3b89a6ebe177830d31a6d6019fe8dc1986/blob +15 -0
  15. shared/package-files/8b/8b7e063d10197b15cc4fa6f0b9fe52132bdd992f9b442cbd28c8f03793baa639/blob +1204 -0
  16. shared/package-files/8b/8b7eb84a05022d26118d0b32ca0bd8d40ae311a3b9b8b8a9dc7c94f91ef368ba/blob +0 -0
  17. shared/package-files/8b/8b813bd8c270347eb5ec038972ee3150da92249c11df6840e915e92c1926855b/blob +25 -0
  18. shared/package-files/8b/8b82530cc91901d5591a65b20eadef3769e711739c5a4e18e8c00302ea3824c3/blob +0 -0
  19. shared/package-files/8b/8b8318b8974f0efa80f9a0f97da51096db1cbca83be1effcb840b479e6cafcf0/blob +61 -0
  20. shared/package-files/8b/8b85846791ab2c8a5463c83a5be3c043e2570d7448434d41398969ed47e3e6f2/blob +0 -0
  21. shared/package-files/8b/8b8d83314c282428810d5111dc76fad3b4f773ab535f425c1cd951483f735c50/blob +0 -0
  22. shared/package-files/8b/8b90a1c3f99957578f8c2af8bc0faa53712eb21108af45f6802dce7e258183cb/blob +0 -0
  23. shared/package-files/8b/8b90c2623ff71532b5856bc5736ec3488566bdcf66628a9bad443b4783bc23ed/blob +113 -0
  24. shared/package-files/8b/8b9121a163d486ee2495add7bb866f5c5d6554b3e223a660e21ea8f236a26a6a/blob +6 -0
  25. shared/package-files/8b/8b9262fc79b943a382d24a96dab8a16757398cd7d7ea33766fd7e5ed6382a645/blob +547 -0
  26. shared/package-files/8b/8b98ae07154d4192178886dad7c2939d83412ccd802457b11bfa7dba4356364e/blob +461 -0
  27. shared/package-files/8b/8b99e880d840da023013d691988e76f16c3dc20737eb2fb046659b390e819fc0/blob +32 -0
  28. shared/package-files/8b/8b9ede33ab32ae2505bc06eb5402e7ce20b0fc8e2510dcb305c25d39a1fbd725/blob +0 -0
  29. shared/package-files/8b/8b9f5dff2e2f70ac88457066a9b8e3d18518df408da36edd42f904642f50d944/blob +921 -0
  30. shared/package-files/8b/8b9f6fe4750edf6e8b848fb49cfa169d2cafe88b2e0ddff1469e0d744bbc1946/blob +341 -0
  31. shared/package-files/8b/8b9fc65039f9df190eb3bfc0d68cdc0eed6070fa2b21afe4c48288f1988068d0/blob +44 -0
  32. shared/package-files/8b/8b9fd73515667141ecfc6067f2b27f4a4afb3340139b737521f811d33c8a523b/blob +56 -0
  33. shared/package-files/8b/8ba054d3b7ea9a8fd954531d3abe5cbaf18bfa0e635d39c7082e31ab2a021ba0/blob +23 -0
  34. shared/package-files/8b/8ba3d5ba862412d7d509da7ad8828cfba503ea44e5e04c88b39e86fa3ddd455e/blob +566 -0
  35. shared/package-files/8b/8ba7b82882992c27f751fa5bdb557635ea45f1848558817b2c047bdbef7b46fd/blob +0 -0
  36. shared/package-files/8b/8babb286a74d5fb93bad98906f3c4b70386c0e3dfb4f31edf184a012887bec5c/blob +606 -0
  37. shared/package-files/8b/8bac1070af4cf22f337ff5aaa8184c8f638229a9af3fb4fff630b919418fd47e/blob +3 -0
  38. shared/package-files/8b/8badfd129686a5d20216b1aba16450f6f471722c8b6ddfc61278dd572283abc0/blob +3 -0
  39. shared/package-files/8b/8bb075675e65561a64af676d362b7a55867696d0f0f5a15973451b8c155294c6/blob +24 -0
  40. shared/package-files/8b/8bb0c4a825ec10fb775f144093ab733132671db740246a713f00825d3b889e34/blob +31 -0
  41. shared/package-files/8b/8bb7d57be88bc8bb50c427c06b82317711feb9f70798c93b85b0861b94f1018e/blob +1008 -0
  42. shared/package-files/8b/8bb850c565aa389fdc16f3a46965ad23d82adff60f2393fc2762b63185e8e6c9/blob +18 -0
  43. shared/package-files/8b/8bba1a38cadd44be6132d04665742d0768d1fe020372a96d73424c64f7931cc6/blob +27 -0
  44. shared/package-files/8b/8bbbffb486494564490858800c2c1538ea7fb7d568fda669fdc10bd2570e049f/blob +6 -0
  45. shared/package-files/8b/8bbc55b991109d8aee328e317ef188d22ce8cc8d6a26f70f3bc0ebeca454d158/blob +213 -0
  46. shared/package-files/8b/8bc0648758f4ee980fea922fcc5c45219eee0254757d03826c81e1eefd38c70f/blob +9 -0
  47. shared/package-files/8b/8bc0e900307c66122e70a73c96df497d86d000d46f47aeeee7da107f9c229ef8/blob +26 -0
  48. shared/package-files/8b/8bc152afd712148ae1d7a3bc87b7289bc2cab5df67b0b63cc221214a9935fda6/blob +31 -0
  49. shared/package-files/8b/8bc19c6d27178483db3047bbbae3205ea87f714da6666d9fea1b29220996e6e3/blob +35 -0
  50. shared/package-files/8b/8bc4ba21bd4e4237082c0fa5e2093392d3197b5f1369e50d238f4f2d1a7a3815/blob +90 -0
.gitattributes CHANGED
@@ -661,3 +661,33 @@ shared/package-files/8a/8ac25926942fd2d950af21f4d44c867f080a1930719c78ad39b385e4
661
  shared/package-files/8a/8ad986ba46fc5e109cc6577e9fa6f3cc010ba312d7f4ce57c41ceaef8b7713a8/blob filter=lfs diff=lfs merge=lfs -text
662
  shared/package-files/8b/8b062c94aa3d3603fb6cfe6f79a17c9541f4d6cb03b79fe13c1b2514811b3441/blob filter=lfs diff=lfs merge=lfs -text
663
  shared/package-files/8b/8b511ea60575653c9ae0f6ed7c8e0c3fff8f837b6ec1d36414e0ce52529c54e4/blob filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
  shared/package-files/8a/8ad986ba46fc5e109cc6577e9fa6f3cc010ba312d7f4ce57c41ceaef8b7713a8/blob filter=lfs diff=lfs merge=lfs -text
662
  shared/package-files/8b/8b062c94aa3d3603fb6cfe6f79a17c9541f4d6cb03b79fe13c1b2514811b3441/blob filter=lfs diff=lfs merge=lfs -text
663
  shared/package-files/8b/8b511ea60575653c9ae0f6ed7c8e0c3fff8f837b6ec1d36414e0ce52529c54e4/blob filter=lfs diff=lfs merge=lfs -text
664
+ shared/package-files/8b/8b77e6c948fb88a4c36fc94c5fac6b974e5d8cb0167dfba63cd0558b7e8fb4a2/blob filter=lfs diff=lfs merge=lfs -text
665
+ shared/package-files/8b/8bac1070af4cf22f337ff5aaa8184c8f638229a9af3fb4fff630b919418fd47e/blob filter=lfs diff=lfs merge=lfs -text
666
+ shared/package-files/8b/8badfd129686a5d20216b1aba16450f6f471722c8b6ddfc61278dd572283abc0/blob filter=lfs diff=lfs merge=lfs -text
667
+ shared/package-files/8c/8c0b31952c785db21c12ee89a6919f196f37c6988d2a6e67dbc5f4a76b374c80/blob filter=lfs diff=lfs merge=lfs -text
668
+ shared/package-files/8c/8c1e0aa212e2594fad2a3e7a964f58be3f0bebcff5d58c21e383252f4246cb29/blob filter=lfs diff=lfs merge=lfs -text
669
+ shared/package-files/8c/8cbe5d21569103e83cc659ea0fbcb604479711feffc7cbc8f42d18d16fdec3e9/blob filter=lfs diff=lfs merge=lfs -text
670
+ shared/package-files/8c/8cf47083fdd8d31bfa4d690671609e9dbe6e8be0d1e6fad6bcd19aabfd1c1393/blob filter=lfs diff=lfs merge=lfs -text
671
+ shared/package-files/8d/8d52a949e0ca302330a392daad94829b54d353da60486150cbe059e0c64f7809/blob filter=lfs diff=lfs merge=lfs -text
672
+ shared/package-files/8d/8d5ae8b518fb9ebeeecb8ae9b4938c39999724ee32105945c9b97f9ad43741a3/blob filter=lfs diff=lfs merge=lfs -text
673
+ shared/package-files/8d/8db6e820fa88b1cec786e285d6becaf5d68c15f9266d7112cc3dae41f4beaf72/blob filter=lfs diff=lfs merge=lfs -text
674
+ shared/package-files/8d/8dd79f3894a6b02fd3504c822889b5e754568ef02cba18b3649fa92719462997/blob filter=lfs diff=lfs merge=lfs -text
675
+ shared/package-files/8e/8e4407820b776a4b85072983eebf370d315e382afa282065dfe7a06ad7cd1cae/blob filter=lfs diff=lfs merge=lfs -text
676
+ shared/package-files/8e/8e5fb3e5090f1b8b279994f9cb5a5eee4a5b24fa449c9b742065f494bde6f2fc/blob filter=lfs diff=lfs merge=lfs -text
677
+ shared/package-files/8e/8e73d0673b78407c09bf6ee46287f822c51dfe3927c3d8b44a0e020592cdd07f/blob filter=lfs diff=lfs merge=lfs -text
678
+ shared/package-files/8e/8e839f2c461a3ac515aeab1c91336ae012878b6b0323e88f83e8fdf52966a897/blob filter=lfs diff=lfs merge=lfs -text
679
+ shared/package-files/8e/8eda7d391f086bf1cc946e2321b7c1b9fb16e71ddaba1b9303ee496d2052b4d3/blob filter=lfs diff=lfs merge=lfs -text
680
+ shared/package-files/8e/8edff6532664a50b5d7e29936d60c358506f94a5498606a953a6c601243e9299/blob filter=lfs diff=lfs merge=lfs -text
681
+ shared/package-files/8e/8ef75af97e9a7f419439343a56de7cab5bd9467cdce745674e85099d82ac8ea4/blob filter=lfs diff=lfs merge=lfs -text
682
+ shared/package-files/8f/8f08ba828f67e01006b79f343d1134b33657a7001d0ce5e1b964dd275b500e7f/blob filter=lfs diff=lfs merge=lfs -text
683
+ shared/package-files/8f/8f78092b6539927132aebd28deb0e0d1b72f43596b79e074e3206f4a784dd000/blob filter=lfs diff=lfs merge=lfs -text
684
+ shared/package-files/8f/8f83378aaa0fd5fecd454eb3fc3e5f7ecb379990a5e40a37838d57fa3953598b/blob filter=lfs diff=lfs merge=lfs -text
685
+ shared/package-files/90/90708fbbce4c895ba7c413e5e91107a7b14c7d9a789cffd0be93657d91832678/blob filter=lfs diff=lfs merge=lfs -text
686
+ shared/package-files/90/90c6cb7fd3be8d363318f45257de6670ba19d9336d096dc3efb309bac88b2bf9/blob filter=lfs diff=lfs merge=lfs -text
687
+ shared/package-files/90/90daa30314af66948ae80c21871dda21a1a83bdafc675580390044c524c75325/blob filter=lfs diff=lfs merge=lfs -text
688
+ shared/package-files/91/917b32cedb7d14c961076c6206d91737b04ce14cf8058de12c95fdcb684632c2/blob filter=lfs diff=lfs merge=lfs -text
689
+ shared/package-files/91/91ad59d218af59b4cec410b351ef00c8752d29e9ffda8b15a501c0c7e08b9ed0/blob filter=lfs diff=lfs merge=lfs -text
690
+ shared/package-files/92/92bc9451b4920ac3713e4607abdc40daf4bb4d407e7d0b23ed952eae1e91b348/blob filter=lfs diff=lfs merge=lfs -text
691
+ shared/package-files/93/931d5ee943e952abef8c5b1ee511d27ceedca8179e2ed95c0d238ec65e4a7e82/blob filter=lfs diff=lfs merge=lfs -text
692
+ shared/package-files/93/934c22ded0e7d169c4d4678876c96051adf3d94545da962f60b41659b075da3b/blob filter=lfs diff=lfs merge=lfs -text
693
+ shared/package-files/93/93536616961eb1fab232f4a4dc87e37d7814f6763ac2c25e270ca13c55bfaeae/blob filter=lfs diff=lfs merge=lfs -text
shared/package-files/8b/8b708a4ae3f837f3c08fba3e09b93cccf11d16cd0259604201f8362570f1e55f/blob ADDED
Binary file (2.09 kB). View file
 
shared/package-files/8b/8b70c48d5a6b496a9281fec532dfb15c5ab470a65eb0b3baedea082b186b8eb8/blob ADDED
Binary file (120 Bytes). View file
 
shared/package-files/8b/8b71472317bf3adabf819e665c725d03e3064baa45f6ffbfd78cca83eaa46e8d/blob ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fix incompatible renames
2
+
3
+ Fixes:
4
+ * sys.maxint -> sys.maxsize
5
+ """
6
+ # Author: Christian Heimes
7
+ # based on Collin Winter's fix_import
8
+
9
+ # Local imports
10
+ from .. import fixer_base
11
+ from ..fixer_util import Name, attr_chain
12
+
13
+ MAPPING = {"sys": {"maxint" : "maxsize"},
14
+ }
15
+ LOOKUP = {}
16
+
17
+ def alternates(members):
18
+ return "(" + "|".join(map(repr, members)) + ")"
19
+
20
+
21
+ def build_pattern():
22
+ #bare = set()
23
+ for module, replace in list(MAPPING.items()):
24
+ for old_attr, new_attr in list(replace.items()):
25
+ LOOKUP[(module, old_attr)] = new_attr
26
+ #bare.add(module)
27
+ #bare.add(old_attr)
28
+ #yield """
29
+ # import_name< 'import' (module=%r
30
+ # | dotted_as_names< any* module=%r any* >) >
31
+ # """ % (module, module)
32
+ yield """
33
+ import_from< 'from' module_name=%r 'import'
34
+ ( attr_name=%r | import_as_name< attr_name=%r 'as' any >) >
35
+ """ % (module, old_attr, old_attr)
36
+ yield """
37
+ power< module_name=%r trailer< '.' attr_name=%r > any* >
38
+ """ % (module, old_attr)
39
+ #yield """bare_name=%s""" % alternates(bare)
40
+
41
+
42
+ class FixRenames(fixer_base.BaseFix):
43
+ BM_compatible = True
44
+ PATTERN = "|".join(build_pattern())
45
+
46
+ order = "pre" # Pre-order tree traversal
47
+
48
+ # Don't match the node if it's within another match
49
+ def match(self, node):
50
+ match = super(FixRenames, self).match
51
+ results = match(node)
52
+ if results:
53
+ if any(match(obj) for obj in attr_chain(node, "parent")):
54
+ return False
55
+ return results
56
+ return False
57
+
58
+ #def start_tree(self, tree, filename):
59
+ # super(FixRenames, self).start_tree(tree, filename)
60
+ # self.replace = {}
61
+
62
+ def transform(self, node, results):
63
+ mod_name = results.get("module_name")
64
+ attr_name = results.get("attr_name")
65
+ #bare_name = results.get("bare_name")
66
+ #import_mod = results.get("module")
67
+
68
+ if mod_name and attr_name:
69
+ new_attr = LOOKUP[(mod_name.value, attr_name.value)]
70
+ attr_name.replace(Name(new_attr, prefix=attr_name.prefix))
shared/package-files/8b/8b720740d5d007214c0af8e3c9dfe1c302520a2523d33d6b4704bd5852b60057/blob ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols
2
+ from sympy.functions.elementary.trigonometric import (cos, sin)
3
+ from sympy.polys import QQ, ZZ
4
+ from sympy.polys.polytools import Poly
5
+ from sympy.polys.polyerrors import NotInvertible
6
+ from sympy.polys.agca.extensions import FiniteExtension
7
+ from sympy.polys.domainmatrix import DomainMatrix
8
+
9
+ from sympy.testing.pytest import raises
10
+
11
+ from sympy.abc import x, y, t
12
+
13
+
14
+ def test_FiniteExtension():
15
+ # Gaussian integers
16
+ A = FiniteExtension(Poly(x**2 + 1, x))
17
+ assert A.rank == 2
18
+ assert str(A) == 'ZZ[x]/(x**2 + 1)'
19
+ i = A.generator
20
+ assert i.parent() is A
21
+
22
+ assert i*i == A(-1)
23
+ raises(TypeError, lambda: i*())
24
+
25
+ assert A.basis == (A.one, i)
26
+ assert A(1) == A.one
27
+ assert i**2 == A(-1)
28
+ assert i**2 != -1 # no coercion
29
+ assert (2 + i)*(1 - i) == 3 - i
30
+ assert (1 + i)**8 == A(16)
31
+ assert A(1).inverse() == A(1)
32
+ raises(NotImplementedError, lambda: A(2).inverse())
33
+
34
+ # Finite field of order 27
35
+ F = FiniteExtension(Poly(x**3 - x + 1, x, modulus=3))
36
+ assert F.rank == 3
37
+ a = F.generator # also generates the cyclic group F - {0}
38
+ assert F.basis == (F(1), a, a**2)
39
+ assert a**27 == a
40
+ assert a**26 == F(1)
41
+ assert a**13 == F(-1)
42
+ assert a**9 == a + 1
43
+ assert a**3 == a - 1
44
+ assert a**6 == a**2 + a + 1
45
+ assert F(x**2 + x).inverse() == 1 - a
46
+ assert F(x + 2)**(-1) == F(x + 2).inverse()
47
+ assert a**19 * a**(-19) == F(1)
48
+ assert (a - 1) / (2*a**2 - 1) == a**2 + 1
49
+ assert (a - 1) // (2*a**2 - 1) == a**2 + 1
50
+ assert 2/(a**2 + 1) == a**2 - a + 1
51
+ assert (a**2 + 1)/2 == -a**2 - 1
52
+ raises(NotInvertible, lambda: F(0).inverse())
53
+
54
+ # Function field of an elliptic curve
55
+ K = FiniteExtension(Poly(t**2 - x**3 - x + 1, t, field=True))
56
+ assert K.rank == 2
57
+ assert str(K) == 'ZZ(x)[t]/(t**2 - x**3 - x + 1)'
58
+ y = K.generator
59
+ c = 1/(x**3 - x**2 + x - 1)
60
+ assert ((y + x)*(y - x)).inverse() == K(c)
61
+ assert (y + x)*(y - x)*c == K(1) # explicit inverse of y + x
62
+
63
+
64
+ def test_FiniteExtension_eq_hash():
65
+ # Test eq and hash
66
+ p1 = Poly(x**2 - 2, x, domain=ZZ)
67
+ p2 = Poly(x**2 - 2, x, domain=QQ)
68
+ K1 = FiniteExtension(p1)
69
+ K2 = FiniteExtension(p2)
70
+ assert K1 == FiniteExtension(Poly(x**2 - 2))
71
+ assert K2 != FiniteExtension(Poly(x**2 - 2))
72
+ assert len({K1, K2, FiniteExtension(p1)}) == 2
73
+
74
+
75
+ def test_FiniteExtension_mod():
76
+ # Test mod
77
+ K = FiniteExtension(Poly(x**3 + 1, x, domain=QQ))
78
+ xf = K(x)
79
+ assert (xf**2 - 1) % 1 == K.zero
80
+ assert 1 % (xf**2 - 1) == K.zero
81
+ assert (xf**2 - 1) / (xf - 1) == xf + 1
82
+ assert (xf**2 - 1) // (xf - 1) == xf + 1
83
+ assert (xf**2 - 1) % (xf - 1) == K.zero
84
+ raises(ZeroDivisionError, lambda: (xf**2 - 1) % 0)
85
+ raises(TypeError, lambda: xf % [])
86
+ raises(TypeError, lambda: [] % xf)
87
+
88
+ # Test mod over ring
89
+ K = FiniteExtension(Poly(x**3 + 1, x, domain=ZZ))
90
+ xf = K(x)
91
+ assert (xf**2 - 1) % 1 == K.zero
92
+ raises(NotImplementedError, lambda: (xf**2 - 1) % (xf - 1))
93
+
94
+
95
+ def test_FiniteExtension_from_sympy():
96
+ # Test to_sympy/from_sympy
97
+ K = FiniteExtension(Poly(x**3 + 1, x, domain=ZZ))
98
+ xf = K(x)
99
+ assert K.from_sympy(x) == xf
100
+ assert K.to_sympy(xf) == x
101
+
102
+
103
+ def test_FiniteExtension_set_domain():
104
+ KZ = FiniteExtension(Poly(x**2 + 1, x, domain='ZZ'))
105
+ KQ = FiniteExtension(Poly(x**2 + 1, x, domain='QQ'))
106
+ assert KZ.set_domain(QQ) == KQ
107
+
108
+
109
+ def test_FiniteExtension_exquo():
110
+ # Test exquo
111
+ K = FiniteExtension(Poly(x**4 + 1))
112
+ xf = K(x)
113
+ assert K.exquo(xf**2 - 1, xf - 1) == xf + 1
114
+
115
+
116
+ def test_FiniteExtension_convert():
117
+ # Test from_MonogenicFiniteExtension
118
+ K1 = FiniteExtension(Poly(x**2 + 1))
119
+ K2 = QQ[x]
120
+ x1, x2 = K1(x), K2(x)
121
+ assert K1.convert(x2) == x1
122
+ assert K2.convert(x1) == x2
123
+
124
+ K = FiniteExtension(Poly(x**2 - 1, domain=QQ))
125
+ assert K.convert_from(QQ(1, 2), QQ) == K.one/2
126
+
127
+
128
+ def test_FiniteExtension_division_ring():
129
+ # Test division in FiniteExtension over a ring
130
+ KQ = FiniteExtension(Poly(x**2 - 1, x, domain=QQ))
131
+ KZ = FiniteExtension(Poly(x**2 - 1, x, domain=ZZ))
132
+ KQt = FiniteExtension(Poly(x**2 - 1, x, domain=QQ[t]))
133
+ KQtf = FiniteExtension(Poly(x**2 - 1, x, domain=QQ.frac_field(t)))
134
+ assert KQ.is_Field is True
135
+ assert KZ.is_Field is False
136
+ assert KQt.is_Field is False
137
+ assert KQtf.is_Field is True
138
+ for K in KQ, KZ, KQt, KQtf:
139
+ xK = K.convert(x)
140
+ assert xK / K.one == xK
141
+ assert xK // K.one == xK
142
+ assert xK % K.one == K.zero
143
+ raises(ZeroDivisionError, lambda: xK / K.zero)
144
+ raises(ZeroDivisionError, lambda: xK // K.zero)
145
+ raises(ZeroDivisionError, lambda: xK % K.zero)
146
+ if K.is_Field:
147
+ assert xK / xK == K.one
148
+ assert xK // xK == K.one
149
+ assert xK % xK == K.zero
150
+ else:
151
+ raises(NotImplementedError, lambda: xK / xK)
152
+ raises(NotImplementedError, lambda: xK // xK)
153
+ raises(NotImplementedError, lambda: xK % xK)
154
+
155
+
156
+ def test_FiniteExtension_Poly():
157
+ K = FiniteExtension(Poly(x**2 - 2))
158
+ p = Poly(x, y, domain=K)
159
+ assert p.domain == K
160
+ assert p.as_expr() == x
161
+ assert (p**2).as_expr() == 2
162
+
163
+ K = FiniteExtension(Poly(x**2 - 2, x, domain=QQ))
164
+ K2 = FiniteExtension(Poly(t**2 - 2, t, domain=K))
165
+ assert str(K2) == 'QQ[x]/(x**2 - 2)[t]/(t**2 - 2)'
166
+
167
+ eK = K2.convert(x + t)
168
+ assert K2.to_sympy(eK) == x + t
169
+ assert K2.to_sympy(eK ** 2) == 4 + 2*x*t
170
+ p = Poly(x + t, y, domain=K2)
171
+ assert p**2 == Poly(4 + 2*x*t, y, domain=K2)
172
+
173
+
174
+ def test_FiniteExtension_sincos_jacobian():
175
+ # Use FiniteExtensino to compute the Jacobian of a matrix involving sin
176
+ # and cos of different symbols.
177
+ r, p, t = symbols('rho, phi, theta')
178
+ elements = [
179
+ [sin(p)*cos(t), r*cos(p)*cos(t), -r*sin(p)*sin(t)],
180
+ [sin(p)*sin(t), r*cos(p)*sin(t), r*sin(p)*cos(t)],
181
+ [ cos(p), -r*sin(p), 0],
182
+ ]
183
+
184
+ def make_extension(K):
185
+ K = FiniteExtension(Poly(sin(p)**2+cos(p)**2-1, sin(p), domain=K[cos(p)]))
186
+ K = FiniteExtension(Poly(sin(t)**2+cos(t)**2-1, sin(t), domain=K[cos(t)]))
187
+ return K
188
+
189
+ Ksc1 = make_extension(ZZ[r])
190
+ Ksc2 = make_extension(ZZ)[r]
191
+
192
+ for K in [Ksc1, Ksc2]:
193
+ elements_K = [[K.convert(e) for e in row] for row in elements]
194
+ J = DomainMatrix(elements_K, (3, 3), K)
195
+ det = J.charpoly()[-1] * (-K.one)**3
196
+ assert det == K.convert(r**2*sin(p))
shared/package-files/8b/8b733ea1edb0f9d08a0245ea92a765985b083b214a570d5fb50799bacd9c3be6/blob ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2008-2011 by Enthought, Inc.
2
+ # Copyright (c) 2013-2015 Continuum Analytics, Inc.
3
+ # All rights reserved.
4
+
5
+ from __future__ import absolute_import
6
+
7
+ import json
8
+ import logging
9
+ import sys
10
+ from os.path import abspath, basename, exists, join
11
+
12
+ try:
13
+ from .._version import __version__
14
+ except ImportError:
15
+ __version__ = "dev"
16
+
17
+ from ..utils import DEFAULT_BASE_PREFIX, DEFAULT_PREFIX
18
+
19
+ if sys.platform == 'win32':
20
+ from ..platforms.win_utils.win_elevate import isUserAdmin, runAsAdmin
21
+ from .win32 import Menu, ShortCut
22
+
23
+
24
+ def _install(path, remove=False, prefix=None, mode=None, root_prefix=None):
25
+ prefix = prefix or DEFAULT_PREFIX
26
+ root_prefix = root_prefix or DEFAULT_BASE_PREFIX
27
+ if abspath(prefix) == abspath(root_prefix):
28
+ env_name = None
29
+ else:
30
+ env_name = basename(prefix)
31
+
32
+ data = json.load(open(path))
33
+ try:
34
+ menu_name = data['menu_name']
35
+ except KeyError:
36
+ menu_name = 'Python-%d.%d' % sys.version_info[:2]
37
+
38
+ shortcuts = data['menu_items']
39
+ m = Menu(menu_name, prefix=prefix, env_name=env_name, mode=mode, root_prefix=root_prefix)
40
+ if remove:
41
+ for sc in shortcuts:
42
+ ShortCut(m, sc).remove()
43
+ m.remove()
44
+ else:
45
+ m.create()
46
+ for sc in shortcuts:
47
+ ShortCut(m, sc).create()
48
+
49
+
50
+ def install(path, remove=False, prefix=None, recursing=False, root_prefix=None):
51
+ """
52
+ Install Menu and shortcuts
53
+
54
+ # Specifying `root_prefix` is used with conda-standalone, because we can't use
55
+ # `sys.prefix`, therefore we need to specify it
56
+ """
57
+ prefix = prefix or DEFAULT_PREFIX
58
+ root_prefix = root_prefix or DEFAULT_BASE_PREFIX
59
+ if not sys.platform == 'win32':
60
+ raise RuntimeError("menuinst._legacy is only supported on Windows.")
61
+
62
+ # this root_prefix is intentional. We want to reflect the state of the root installation.
63
+
64
+ if not exists(join(root_prefix, '.nonadmin')):
65
+ if isUserAdmin():
66
+ _install(path, remove, prefix, mode='system', root_prefix=root_prefix)
67
+ else:
68
+ retcode = 1
69
+ try:
70
+ if not recursing:
71
+ retcode = runAsAdmin(
72
+ [
73
+ join(root_prefix, 'python'),
74
+ '-c',
75
+ "import menuinst; menuinst.install(%r, %r, %r, %r, %r)"
76
+ % (path, bool(remove), prefix, True, root_prefix),
77
+ ]
78
+ )
79
+ except OSError:
80
+ pass
81
+
82
+ if retcode != 0:
83
+ logging.warn(
84
+ "Insufficient permissions to write menu folder. "
85
+ "Falling back to user location"
86
+ )
87
+ _install(path, remove, prefix, mode='user', root_prefix=root_prefix)
88
+ else:
89
+ _install(path, remove, prefix, mode='user', root_prefix=root_prefix)
shared/package-files/8b/8b77e6c948fb88a4c36fc94c5fac6b974e5d8cb0167dfba63cd0558b7e8fb4a2/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b77e6c948fb88a4c36fc94c5fac6b974e5d8cb0167dfba63cd0558b7e8fb4a2
3
+ size 84693320
shared/package-files/8b/8b784d08319ab7ff0320c1c5a36d9db3dc77e12ca55f6abd56ef9610b022fed5/blob ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/util/ApproximateClock.h>
3
+ #include <torch/csrc/autograd/profiler.h>
4
+
5
+ namespace c10d {
6
+ constexpr int kUnsetTime = -1;
7
+
8
+ inline int64_t current_time_in_nanos() {
9
+ return c10::getTime();
10
+ }
11
+
12
+ class TORCH_API Timer {
13
+ private:
14
+ // The timestamp of forward call start time in each iteration.
15
+ int64_t forward_start_time = kUnsetTime;
16
+ // The timestamp of backward computation start and end time in each
17
+ // iteration.
18
+ int64_t backward_compute_start_time = kUnsetTime;
19
+ int64_t backward_compute_end_time = kUnsetTime;
20
+ // The timestamp of first communication call start time in each iteration.
21
+ int64_t backward_comm_start_time = kUnsetTime;
22
+ // The timestamp of last communication call end time in each iteration.
23
+ int64_t backward_comm_end_time = kUnsetTime;
24
+
25
+ public:
26
+ enum class Event {
27
+ kForwardStart,
28
+ kBackwardComputeStart,
29
+ kBackwardComputeEnd,
30
+ kBackwardCommStart,
31
+ kBackwardCommEnd,
32
+ };
33
+
34
+ // Record the current event, i.e., mark it as having occurred now. Default
35
+ // CPU implementation.
36
+ virtual void record(Event event) {
37
+ getTimeRef(event) = current_time_in_nanos();
38
+ }
39
+
40
+ // Return the difference between when two events occurred, in nanoseconds.
41
+ // Or nullopt if one of them hasn't been recorded.
42
+ virtual c10::optional<int64_t> measureDifference(Event start, Event end) = 0;
43
+
44
+ virtual ~Timer() = default;
45
+
46
+ // Return host-side timestamp, or nullopt if it has not yet been recorded.
47
+ c10::optional<int64_t> getTimestamp(Event event) {
48
+ auto time = getTimeRef(event);
49
+ if (time == kUnsetTime) {
50
+ return c10::nullopt;
51
+ } else {
52
+ return time;
53
+ }
54
+ }
55
+
56
+ // Return host-side time member variable corresponding to the given event.
57
+ int64_t& getTimeRef(Event event) {
58
+ switch (event) {
59
+ case Event::kForwardStart:
60
+ return forward_start_time;
61
+ case Event::kBackwardComputeStart:
62
+ return backward_compute_start_time;
63
+ case Event::kBackwardComputeEnd:
64
+ return backward_compute_end_time;
65
+ case Event::kBackwardCommStart:
66
+ return backward_comm_start_time;
67
+ case Event::kBackwardCommEnd:
68
+ return backward_comm_end_time;
69
+ default:
70
+ TORCH_INTERNAL_ASSERT(false);
71
+ }
72
+ }
73
+ };
74
+
75
+ TORCH_DECLARE_TYPED_REGISTRY(
76
+ TimerRegistry,
77
+ c10::DeviceType,
78
+ Timer,
79
+ std::unique_ptr,
80
+ c10::Device);
81
+ } // namespace c10d
shared/package-files/8b/8b78797c860c531e3ffcca1cecca52d532df2bc4aedfe8857dab8e5d70146f86/blob ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Distance dependence measure and the dCov test
3
+
4
+ Implementation of Székely et al. (2007) calculation of distance
5
+ dependence statistics, including the Distance covariance (dCov) test
6
+ for independence of random vectors of arbitrary length.
7
+
8
+ Author: Ron Itzikovitch
9
+
10
+ References
11
+ ----------
12
+ .. Szekely, G.J., Rizzo, M.L., and Bakirov, N.K. (2007)
13
+ "Measuring and testing dependence by correlation of distances".
14
+ Annals of Statistics, Vol. 35 No. 6, pp. 2769-2794.
15
+
16
+ """
17
+
18
+ from typing import NamedTuple
19
+ import warnings
20
+
21
+ import numpy as np
22
+ from scipy.spatial.distance import pdist, squareform
23
+ from scipy.stats import norm
24
+
25
+ from statsmodels.tools.rng_qrng import check_random_state
26
+ from statsmodels.tools.sm_exceptions import HypothesisTestWarning
27
+ from statsmodels.tools.validation import string_like
28
+
29
+
30
+ class DistDependStat(NamedTuple):
31
+ """
32
+ Result of :func:`distance_statistics`.
33
+
34
+ Parameters
35
+ ----------
36
+ test_statistic : float
37
+ The "basic" test statistic (i.e., the one used when the `emp`
38
+ method is chosen when calling ``distance_covariance_test()``).
39
+ distance_correlation : float
40
+ The distance correlation between `x` and `y`.
41
+ distance_covariance : float
42
+ The distance covariance of `x` and `y`.
43
+ dvar_x : float
44
+ The distance variance of `x`.
45
+ dvar_y : float
46
+ The distance variance of `y`.
47
+ S : float
48
+ The mean of the euclidean distances in `x` multiplied by those
49
+ of `y`. Mostly used internally.
50
+ """
51
+
52
+ test_statistic: float
53
+ distance_correlation: float
54
+ distance_covariance: float
55
+ dvar_x: float
56
+ dvar_y: float
57
+ S: float
58
+
59
+
60
+ def distance_covariance_test(x, y, B=None, method="auto", rng=None):
61
+ r"""
62
+ The Distance Covariance (dCov) test
63
+
64
+ Apply the Distance Covariance (dCov) test of independence to `x` and `y`.
65
+ This test was introduced in [1]_, and is based on the distance covariance
66
+ statistic. The test is applicable to random vectors of arbitrary length
67
+ (see the notes section for more details).
68
+
69
+ Parameters
70
+ ----------
71
+ x : array_like, 1-D or 2-D
72
+ If `x` is 1-D than it is assumed to be a vector of observations of a
73
+ single random variable. If `x` is 2-D than the rows should be
74
+ observations and the columns are treated as the components of a
75
+ random vector, i.e., each column represents a different component of
76
+ the random vector `x`.
77
+ y : array_like, 1-D or 2-D
78
+ Same as `x`, but only the number of observation has to match that of
79
+ `x`. If `y` is 2-D note that the number of columns of `y` (i.e., the
80
+ number of components in the random vector) does not need to match
81
+ the number of columns in `x`.
82
+ B : int, optional
83
+ The number of iterations to perform when evaluating the null
84
+ distribution of the test statistic when the `emp` method is
85
+ applied (see below). if `B` is `None` than as in [1]_ we set
86
+ `B` to be ``B = 200 + 5000/n``, where `n` is the number of
87
+ observations.
88
+ method : {'auto', 'emp', 'asym'}, optional
89
+ The method by which to obtain the p-value for the test.
90
+
91
+ - `auto` : Default method. The number of observations will be used to
92
+ determine the method.
93
+ - `emp` : Empirical evaluation of the p-value using permutations of
94
+ the rows of `y` to obtain the null distribution.
95
+ - `asym` : An asymptotic approximation of the distribution of the test
96
+ statistic is used to find the p-value.
97
+
98
+ rng : int, array_like of int, numpy.random.Generator, numpy.random.RandomState, optional
99
+ If `rng` is None, a new ``Generator`` is created using fresh
100
+ entropy from the operating system. If `rng` is an int or array
101
+ of ints, a new ``Generator`` is created, seeded with `rng`. If
102
+ `rng` is already a ``Generator`` or ``RandomState`` instance,
103
+ that instance is used.
104
+
105
+ Returns
106
+ -------
107
+ test_statistic : float
108
+ The value of the test statistic used in the test.
109
+ pval : float
110
+ The p-value.
111
+ chosen_method : str
112
+ The method that was used to obtain the p-value. Mostly relevant when
113
+ the function is called with `method='auto'`.
114
+
115
+ Notes
116
+ -----
117
+ The test applies to random vectors of arbitrary dimensions, i.e., `x`
118
+ can be a 1-D vector of observations for a single random variable while
119
+ `y` can be a `k` by `n` 2-D array (where `k > 1`). In other words, it
120
+ is also possible for `x` and `y` to both be 2-D arrays and have the
121
+ same number of rows (observations) while differing in the number of
122
+ columns.
123
+
124
+ As noted in [1]_ the statistics are sensitive to all types of departures
125
+ from independence, including nonlinear or nonmonotone dependence
126
+ structure.
127
+
128
+ References
129
+ ----------
130
+ .. [1] Szekely, G.J., Rizzo, M.L., and Bakirov, N.K. (2007)
131
+ "Measuring and testing dependence by correlation of distances".
132
+ Annals of Statistics, Vol. 35 No. 6, pp. 2769-2794.
133
+
134
+ Examples
135
+ --------
136
+ >>> from statsmodels.stats.dist_dependence_measures import
137
+ ... distance_covariance_test
138
+ >>> data = np.random.rand(1000, 10)
139
+ >>> x, y = data[:, :3], data[:, 3:]
140
+ >>> x.shape
141
+ (1000, 3)
142
+ >>> y.shape
143
+ (1000, 7)
144
+ >>> distance_covariance_test(x, y)
145
+ (1.0426404792714983, 0.2971148340813543, 'asym')
146
+ # (test_statistic, pval, chosen_method)
147
+
148
+ """
149
+ x, y = _validate_and_tranform_x_and_y(x, y)
150
+
151
+ method = string_like(
152
+ method, "method", options=("auto", "emp", "asym"), lower=False
153
+ )
154
+
155
+ n = x.shape[0]
156
+ stats = distance_statistics(x, y)
157
+
158
+ if (method == "auto" and n <= 500) or method == "emp":
159
+ chosen_method = "emp"
160
+ rng = check_random_state(rng)
161
+ test_statistic, pval = _empirical_pvalue(x, y, B, n, stats, rng)
162
+
163
+ else: # method == "asym", or method == "auto" and n > 500
164
+ chosen_method = "asym"
165
+ test_statistic, pval = _asymptotic_pvalue(stats)
166
+
167
+ # In case we got an extreme p-value (0 or 1) when using the empirical
168
+ # distribution of the test statistic under the null, we fall back
169
+ # to the asymptotic approximation.
170
+ if chosen_method == "emp" and pval in [0, 1]:
171
+ msg = (
172
+ f"p-value was {pval} when using the empirical method. "
173
+ "The asymptotic approximation will be used instead"
174
+ )
175
+ warnings.warn(msg, HypothesisTestWarning, stacklevel=2)
176
+ _, pval = _asymptotic_pvalue(stats)
177
+
178
+ return test_statistic, pval, chosen_method
179
+
180
+
181
+ def _validate_and_tranform_x_and_y(x, y):
182
+ r"""
183
+ Ensure `x` and `y` have proper shape and transform/reshape them if required
184
+
185
+ Parameters
186
+ ----------
187
+ x : array_like, 1-D or 2-D
188
+ If `x` is 1-D than it is assumed to be a vector of observations of a
189
+ single random variable. If `x` is 2-D than the rows should be
190
+ observations and the columns are treated as the components of a
191
+ random vector, i.e., each column represents a different component of
192
+ the random vector `x`.
193
+ y : array_like, 1-D or 2-D
194
+ Same as `x`, but only the number of observation has to match that of
195
+ `x`. If `y` is 2-D note that the number of columns of `y` (i.e., the
196
+ number of components in the random vector) does not need to match
197
+ the number of columns in `x`.
198
+
199
+ Returns
200
+ -------
201
+ x : ndarray, 2-D
202
+ y : ndarray, 2-D
203
+
204
+ Raises
205
+ ------
206
+ ValueError
207
+ If `x` and `y` have a different number of observations.
208
+
209
+ """
210
+ x = np.asanyarray(x)
211
+ y = np.asanyarray(y)
212
+
213
+ if x.shape[0] != y.shape[0]:
214
+ raise ValueError("x and y must have the same number of observations (rows).")
215
+
216
+ if len(x.shape) == 1:
217
+ x = x.reshape((x.shape[0], 1))
218
+
219
+ if len(y.shape) == 1:
220
+ y = y.reshape((y.shape[0], 1))
221
+
222
+ return x, y
223
+
224
+
225
+ def _empirical_pvalue(x, y, B, n, stats, rng):
226
+ r"""
227
+ Calculate the empirical p-value based on permutations of `y`'s rows
228
+
229
+ Parameters
230
+ ----------
231
+ x : array_like, 1-D or 2-D
232
+ If `x` is 1-D than it is assumed to be a vector of observations of a
233
+ single random variable. If `x` is 2-D than the rows should be
234
+ observations and the columns are treated as the components of a
235
+ random vector, i.e., each column represents a different component of
236
+ the random vector `x`.
237
+ y : array_like, 1-D or 2-D
238
+ Same as `x`, but only the number of observation has to match that of
239
+ `x`. If `y` is 2-D note that the number of columns of `y` (i.e., the
240
+ number of components in the random vector) does not need to match
241
+ the number of columns in `x`.
242
+ B : int
243
+ The number of iterations when evaluating the null distribution.
244
+ n : int
245
+ Number of observations found in each of `x` and `y`.
246
+ stats : DistDependStat
247
+ The result obtained from calling ``distance_statistics(x, y)``.
248
+ rng : int, array_like of int, numpy.random.Generator, numpy.random.RandomState, optional
249
+ If `rng` is None, a new ``Generator`` is created using fresh
250
+ entropy from the operating system. If `rng` is an int or array
251
+ of ints, a new ``Generator`` is created, seeded with `rng`. If
252
+ `rng` is already a ``Generator`` or ``RandomState`` instance,
253
+ that instance is used.
254
+
255
+ Returns
256
+ -------
257
+ test_statistic : float
258
+ The empirical test statistic.
259
+ pval : float
260
+ The empirical p-value.
261
+
262
+ """
263
+ B = int(B) if B else int(np.floor(200 + 5000 / n))
264
+ empirical_dist = _get_test_statistic_distribution(x, y, B, rng)
265
+ pval = 1 - np.searchsorted(sorted(empirical_dist), stats.test_statistic) / len(
266
+ empirical_dist
267
+ )
268
+ test_statistic = stats.test_statistic
269
+
270
+ return test_statistic, pval
271
+
272
+
273
+ def _asymptotic_pvalue(stats):
274
+ r"""
275
+ Calculate the p-value using an asymptotic approximation of the null distribution
276
+
277
+ Parameters
278
+ ----------
279
+ stats : DistDependStat
280
+ The result obtained from calling ``distance_statistics(x, y)``.
281
+
282
+ Returns
283
+ -------
284
+ test_statistic : float
285
+ The test statistic.
286
+ pval : float
287
+ The asymptotic p-value.
288
+
289
+ """
290
+ test_statistic = np.sqrt(stats.test_statistic / stats.S)
291
+ pval = (1 - norm.cdf(test_statistic)) * 2
292
+
293
+ return test_statistic, pval
294
+
295
+
296
+ def _get_test_statistic_distribution(x, y, B, rng):
297
+ r"""
298
+ Compute the empirical distribution of the test statistic under permutation
299
+
300
+ Parameters
301
+ ----------
302
+ x : array_like, 1-D or 2-D
303
+ If `x` is 1-D than it is assumed to be a vector of observations of a
304
+ single random variable. If `x` is 2-D than the rows should be
305
+ observations and the columns are treated as the components of a
306
+ random vector, i.e., each column represents a different component of
307
+ the random vector `x`.
308
+ y : array_like, 1-D or 2-D
309
+ Same as `x`, but only the number of observation has to match that of
310
+ `x`. If `y` is 2-D note that the number of columns of `y` (i.e., the
311
+ number of components in the random vector) does not need to match
312
+ the number of columns in `x`.
313
+ B : int
314
+ The number of iterations to perform when evaluating the null
315
+ distribution.
316
+ rng : int, array_like of int, numpy.random.Generator, numpy.random.RandomState, optional
317
+ If `rng` is None, a new ``Generator`` is created using fresh
318
+ entropy from the operating system. If `rng` is an int or array
319
+ of ints, a new ``Generator`` is created, seeded with `rng`. If
320
+ `rng` is already a ``Generator`` or ``RandomState`` instance,
321
+ that instance is used.
322
+
323
+ Returns
324
+ -------
325
+ emp_dist : ndarray
326
+ The empirical distribution of the test statistic.
327
+
328
+ """
329
+ y = y.copy()
330
+ emp_dist = np.zeros(B)
331
+ x_dist = squareform(pdist(x, "euclidean"))
332
+ for i in range(B):
333
+ rng.shuffle(y)
334
+ emp_dist[i] = distance_statistics(x, y, x_dist=x_dist).test_statistic
335
+
336
+ return emp_dist
337
+
338
+
339
+ def distance_statistics(x, y, x_dist=None, y_dist=None):
340
+ r"""
341
+ Calculate various distance dependence statistics
342
+
343
+ Calculate several distance dependence statistics as described in [1]_.
344
+
345
+ Parameters
346
+ ----------
347
+ x : array_like, 1-D or 2-D
348
+ If `x` is 1-D than it is assumed to be a vector of observations of a
349
+ single random variable. If `x` is 2-D than the rows should be
350
+ observations and the columns are treated as the components of a
351
+ random vector, i.e., each column represents a different component of
352
+ the random vector `x`.
353
+ y : array_like, 1-D or 2-D
354
+ Same as `x`, but only the number of observation has to match that of
355
+ `x`. If `y` is 2-D note that the number of columns of `y` (i.e., the
356
+ number of components in the random vector) does not need to match
357
+ the number of columns in `x`.
358
+ x_dist : array_like, 2-D, optional
359
+ A square 2-D array_like object whose values are the euclidean
360
+ distances between `x`'s rows.
361
+ y_dist : array_like, 2-D, optional
362
+ A square 2-D array_like object whose values are the euclidean
363
+ distances between `y`'s rows.
364
+
365
+ Returns
366
+ -------
367
+ DistDependStat
368
+ A named tuple of distance dependence statistics. See
369
+ :class:`DistDependStat` for the full list of fields.
370
+
371
+ References
372
+ ----------
373
+ .. [1] Szekely, G.J., Rizzo, M.L., and Bakirov, N.K. (2007)
374
+ "Measuring and testing dependence by correlation of distances".
375
+ Annals of Statistics, Vol. 35 No. 6, pp. 2769-2794.
376
+
377
+ Examples
378
+ --------
379
+
380
+ >>> from statsmodels.stats.dist_dependence_measures import
381
+ ... distance_statistics
382
+ >>> distance_statistics(np.random.random(1000), np.random.random(1000))
383
+ DistDependStat(test_statistic=0.07948284320205831,
384
+ distance_correlation=0.04269511890990793,
385
+ distance_covariance=0.008915315092696293,
386
+ dvar_x=0.20719027438266704, dvar_y=0.21044934264957588,
387
+ S=0.10892061635588891)
388
+
389
+ """
390
+ x, y = _validate_and_tranform_x_and_y(x, y)
391
+
392
+ n = x.shape[0]
393
+
394
+ a = x_dist if x_dist is not None else squareform(pdist(x, "euclidean"))
395
+ b = y_dist if y_dist is not None else squareform(pdist(y, "euclidean"))
396
+
397
+ a_row_means = a.mean(axis=0, keepdims=True)
398
+ b_row_means = b.mean(axis=0, keepdims=True)
399
+ a_col_means = a.mean(axis=1, keepdims=True)
400
+ b_col_means = b.mean(axis=1, keepdims=True)
401
+ a_mean = a.mean()
402
+ b_mean = b.mean()
403
+
404
+ A = a - a_row_means - a_col_means + a_mean
405
+ B = b - b_row_means - b_col_means + b_mean
406
+
407
+ S = a_mean * b_mean
408
+ dcov = np.sqrt(np.multiply(A, B).mean())
409
+ dvar_x = np.sqrt(np.multiply(A, A).mean())
410
+ dvar_y = np.sqrt(np.multiply(B, B).mean())
411
+ dcor = dcov / np.sqrt(dvar_x * dvar_y)
412
+
413
+ test_statistic = n * dcov**2
414
+
415
+ return DistDependStat(
416
+ test_statistic=test_statistic,
417
+ distance_correlation=dcor,
418
+ distance_covariance=dcov,
419
+ dvar_x=dvar_x,
420
+ dvar_y=dvar_y,
421
+ S=S,
422
+ )
423
+
424
+
425
+ def distance_covariance(x, y):
426
+ r"""
427
+ Distance covariance
428
+
429
+ Calculate the empirical distance covariance as described in [1]_.
430
+
431
+ Parameters
432
+ ----------
433
+ x : array_like, 1-D or 2-D
434
+ If `x` is 1-D than it is assumed to be a vector of observations of a
435
+ single random variable. If `x` is 2-D than the rows should be
436
+ observations and the columns are treated as the components of a
437
+ random vector, i.e., each column represents a different component of
438
+ the random vector `x`.
439
+ y : array_like, 1-D or 2-D
440
+ Same as `x`, but only the number of observation has to match that of
441
+ `x`. If `y` is 2-D note that the number of columns of `y` (i.e., the
442
+ number of components in the random vector) does not need to match
443
+ the number of columns in `x`.
444
+
445
+ Returns
446
+ -------
447
+ float
448
+ The empirical distance covariance between `x` and `y`.
449
+
450
+ References
451
+ ----------
452
+ .. [1] Szekely, G.J., Rizzo, M.L., and Bakirov, N.K. (2007)
453
+ "Measuring and testing dependence by correlation of distances".
454
+ Annals of Statistics, Vol. 35 No. 6, pp. 2769-2794.
455
+
456
+ Examples
457
+ --------
458
+
459
+ >>> from statsmodels.stats.dist_dependence_measures import
460
+ ... distance_covariance
461
+ >>> distance_covariance(np.random.random(1000), np.random.random(1000))
462
+ 0.007575063951951362
463
+
464
+ """
465
+ return distance_statistics(x, y).distance_covariance
466
+
467
+
468
+ def distance_variance(x):
469
+ r"""
470
+ Distance variance
471
+
472
+ Calculate the empirical distance variance as described in [1]_.
473
+
474
+ Parameters
475
+ ----------
476
+ x : array_like, 1-D or 2-D
477
+ If `x` is 1-D than it is assumed to be a vector of observations of a
478
+ single random variable. If `x` is 2-D than the rows should be
479
+ observations and the columns are treated as the components of a
480
+ random vector, i.e., each column represents a different component of
481
+ the random vector `x`.
482
+
483
+ Returns
484
+ -------
485
+ float
486
+ The empirical distance variance of `x`.
487
+
488
+ References
489
+ ----------
490
+ .. [1] Szekely, G.J., Rizzo, M.L., and Bakirov, N.K. (2007)
491
+ "Measuring and testing dependence by correlation of distances".
492
+ Annals of Statistics, Vol. 35 No. 6, pp. 2769-2794.
493
+
494
+ Examples
495
+ --------
496
+
497
+ >>> from statsmodels.stats.dist_dependence_measures import
498
+ ... distance_variance
499
+ >>> distance_variance(np.random.random(1000))
500
+ 0.21732609190659702
501
+
502
+ """
503
+ return distance_covariance(x, x)
504
+
505
+
506
+ def distance_correlation(x, y):
507
+ r"""
508
+ Distance correlation
509
+
510
+ Calculate the empirical distance correlation as described in [1]_.
511
+ This statistic is analogous to product-moment correlation and describes
512
+ the dependence between `x` and `y`, which are random vectors of
513
+ arbitrary length. The statistics' values range between 0 (implies
514
+ independence) and 1 (implies complete dependence).
515
+
516
+ Parameters
517
+ ----------
518
+ x : array_like, 1-D or 2-D
519
+ If `x` is 1-D than it is assumed to be a vector of observations of a
520
+ single random variable. If `x` is 2-D than the rows should be
521
+ observations and the columns are treated as the components of a
522
+ random vector, i.e., each column represents a different component of
523
+ the random vector `x`.
524
+ y : array_like, 1-D or 2-D
525
+ Same as `x`, but only the number of observation has to match that of
526
+ `x`. If `y` is 2-D note that the number of columns of `y` (i.e., the
527
+ number of components in the random vector) does not need to match
528
+ the number of columns in `x`.
529
+
530
+ Returns
531
+ -------
532
+ float
533
+ The empirical distance correlation between `x` and `y`.
534
+
535
+ References
536
+ ----------
537
+ .. [1] Szekely, G.J., Rizzo, M.L., and Bakirov, N.K. (2007)
538
+ "Measuring and testing dependence by correlation of distances".
539
+ Annals of Statistics, Vol. 35 No. 6, pp. 2769-2794.
540
+
541
+ Examples
542
+ --------
543
+
544
+ >>> from statsmodels.stats.dist_dependence_measures import
545
+ ... distance_correlation
546
+ >>> distance_correlation(np.random.random(1000), np.random.random(1000))
547
+ 0.04060497840149489
548
+
549
+ """
550
+ return distance_statistics(x, y).distance_correlation
shared/package-files/8b/8b790ac38c4ee3ff7d7c93753bba315c694f53ea8c24a0cf8ab6d6693c3be93a/blob ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import List, Optional, Tuple
3
+
4
+ import PIL.Image
5
+ import torch
6
+ from torch.nn.functional import conv2d, pad as torch_pad
7
+
8
+ from torchvision import tv_tensors
9
+ from torchvision.transforms._functional_tensor import _max_value
10
+ from torchvision.transforms.functional import pil_to_tensor, to_pil_image
11
+
12
+ from torchvision.utils import _log_api_usage_once
13
+
14
+ from ._meta import _convert_bounding_box_format
15
+
16
+ from ._utils import _get_kernel, _register_kernel_internal, is_pure_tensor
17
+
18
+
19
+ def normalize(
20
+ inpt: torch.Tensor,
21
+ mean: List[float],
22
+ std: List[float],
23
+ inplace: bool = False,
24
+ ) -> torch.Tensor:
25
+ """See :class:`~torchvision.transforms.v2.Normalize` for details."""
26
+ if torch.jit.is_scripting():
27
+ return normalize_image(inpt, mean=mean, std=std, inplace=inplace)
28
+
29
+ _log_api_usage_once(normalize)
30
+
31
+ kernel = _get_kernel(normalize, type(inpt))
32
+ return kernel(inpt, mean=mean, std=std, inplace=inplace)
33
+
34
+
35
+ @_register_kernel_internal(normalize, torch.Tensor)
36
+ @_register_kernel_internal(normalize, tv_tensors.Image)
37
+ def normalize_image(image: torch.Tensor, mean: List[float], std: List[float], inplace: bool = False) -> torch.Tensor:
38
+ if not image.is_floating_point():
39
+ raise TypeError(f"Input tensor should be a float tensor. Got {image.dtype}.")
40
+
41
+ if image.ndim < 3:
42
+ raise ValueError(f"Expected tensor to be a tensor image of size (..., C, H, W). Got {image.shape}.")
43
+
44
+ if isinstance(std, (tuple, list)):
45
+ divzero = not all(std)
46
+ elif isinstance(std, (int, float)):
47
+ divzero = std == 0
48
+ else:
49
+ divzero = False
50
+ if divzero:
51
+ raise ValueError("std evaluated to zero, leading to division by zero.")
52
+
53
+ dtype = image.dtype
54
+ device = image.device
55
+ mean = torch.as_tensor(mean, dtype=dtype, device=device)
56
+ std = torch.as_tensor(std, dtype=dtype, device=device)
57
+ if mean.ndim == 1:
58
+ mean = mean.view(-1, 1, 1)
59
+ if std.ndim == 1:
60
+ std = std.view(-1, 1, 1)
61
+
62
+ if inplace:
63
+ image = image.sub_(mean)
64
+ else:
65
+ image = image.sub(mean)
66
+
67
+ return image.div_(std)
68
+
69
+
70
+ @_register_kernel_internal(normalize, tv_tensors.Video)
71
+ def normalize_video(video: torch.Tensor, mean: List[float], std: List[float], inplace: bool = False) -> torch.Tensor:
72
+ return normalize_image(video, mean, std, inplace=inplace)
73
+
74
+
75
+ def gaussian_blur(inpt: torch.Tensor, kernel_size: List[int], sigma: Optional[List[float]] = None) -> torch.Tensor:
76
+ """See :class:`~torchvision.transforms.v2.GaussianBlur` for details."""
77
+ if torch.jit.is_scripting():
78
+ return gaussian_blur_image(inpt, kernel_size=kernel_size, sigma=sigma)
79
+
80
+ _log_api_usage_once(gaussian_blur)
81
+
82
+ kernel = _get_kernel(gaussian_blur, type(inpt))
83
+ return kernel(inpt, kernel_size=kernel_size, sigma=sigma)
84
+
85
+
86
+ def _get_gaussian_kernel1d(kernel_size: int, sigma: float, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
87
+ lim = (kernel_size - 1) / (2.0 * math.sqrt(2.0) * sigma)
88
+ x = torch.linspace(-lim, lim, steps=kernel_size, dtype=dtype, device=device)
89
+ kernel1d = torch.softmax(x.pow_(2).neg_(), dim=0)
90
+ return kernel1d
91
+
92
+
93
+ def _get_gaussian_kernel2d(
94
+ kernel_size: List[int], sigma: List[float], dtype: torch.dtype, device: torch.device
95
+ ) -> torch.Tensor:
96
+ kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0], dtype, device)
97
+ kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1], dtype, device)
98
+ kernel2d = kernel1d_y.unsqueeze(-1) * kernel1d_x
99
+ return kernel2d
100
+
101
+
102
+ @_register_kernel_internal(gaussian_blur, torch.Tensor)
103
+ @_register_kernel_internal(gaussian_blur, tv_tensors.Image)
104
+ def gaussian_blur_image(
105
+ image: torch.Tensor, kernel_size: List[int], sigma: Optional[List[float]] = None
106
+ ) -> torch.Tensor:
107
+ # TODO: consider deprecating integers from sigma on the future
108
+ if isinstance(kernel_size, int):
109
+ kernel_size = [kernel_size, kernel_size]
110
+ elif len(kernel_size) != 2:
111
+ raise ValueError(f"If kernel_size is a sequence its length should be 2. Got {len(kernel_size)}")
112
+ for ksize in kernel_size:
113
+ if ksize % 2 == 0 or ksize < 0:
114
+ raise ValueError(f"kernel_size should have odd and positive integers. Got {kernel_size}")
115
+
116
+ if sigma is None:
117
+ sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size]
118
+ else:
119
+ if isinstance(sigma, (list, tuple)):
120
+ length = len(sigma)
121
+ if length == 1:
122
+ s = float(sigma[0])
123
+ sigma = [s, s]
124
+ elif length != 2:
125
+ raise ValueError(f"If sigma is a sequence, its length should be 2. Got {length}")
126
+ elif isinstance(sigma, (int, float)):
127
+ s = float(sigma)
128
+ sigma = [s, s]
129
+ else:
130
+ raise TypeError(f"sigma should be either float or sequence of floats. Got {type(sigma)}")
131
+ for s in sigma:
132
+ if s <= 0.0:
133
+ raise ValueError(f"sigma should have positive values. Got {sigma}")
134
+
135
+ if image.numel() == 0:
136
+ return image
137
+
138
+ dtype = image.dtype
139
+ shape = image.shape
140
+ ndim = image.ndim
141
+ if ndim == 3:
142
+ image = image.unsqueeze(dim=0)
143
+ elif ndim > 4:
144
+ image = image.reshape((-1,) + shape[-3:])
145
+
146
+ fp = torch.is_floating_point(image)
147
+ kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype if fp else torch.float32, device=image.device)
148
+ kernel = kernel.expand(shape[-3], 1, kernel.shape[0], kernel.shape[1])
149
+
150
+ output = image if fp else image.to(dtype=torch.float32)
151
+
152
+ # padding = (left, right, top, bottom)
153
+ padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2]
154
+ output = torch_pad(output, padding, mode="reflect")
155
+ output = conv2d(output, kernel, groups=shape[-3])
156
+
157
+ if ndim == 3:
158
+ output = output.squeeze(dim=0)
159
+ elif ndim > 4:
160
+ output = output.reshape(shape)
161
+
162
+ if not fp:
163
+ output = output.round_().to(dtype=dtype)
164
+
165
+ return output
166
+
167
+
168
+ @_register_kernel_internal(gaussian_blur, PIL.Image.Image)
169
+ def _gaussian_blur_image_pil(
170
+ image: PIL.Image.Image, kernel_size: List[int], sigma: Optional[List[float]] = None
171
+ ) -> PIL.Image.Image:
172
+ t_img = pil_to_tensor(image)
173
+ output = gaussian_blur_image(t_img, kernel_size=kernel_size, sigma=sigma)
174
+ return to_pil_image(output, mode=image.mode)
175
+
176
+
177
+ @_register_kernel_internal(gaussian_blur, tv_tensors.Video)
178
+ def gaussian_blur_video(
179
+ video: torch.Tensor, kernel_size: List[int], sigma: Optional[List[float]] = None
180
+ ) -> torch.Tensor:
181
+ return gaussian_blur_image(video, kernel_size, sigma)
182
+
183
+
184
+ def to_dtype(inpt: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor:
185
+ """See :func:`~torchvision.transforms.v2.ToDtype` for details."""
186
+ if torch.jit.is_scripting():
187
+ return to_dtype_image(inpt, dtype=dtype, scale=scale)
188
+
189
+ _log_api_usage_once(to_dtype)
190
+
191
+ kernel = _get_kernel(to_dtype, type(inpt))
192
+ return kernel(inpt, dtype=dtype, scale=scale)
193
+
194
+
195
+ def _num_value_bits(dtype: torch.dtype) -> int:
196
+ if dtype == torch.uint8:
197
+ return 8
198
+ elif dtype == torch.int8:
199
+ return 7
200
+ elif dtype == torch.int16:
201
+ return 15
202
+ elif dtype == torch.int32:
203
+ return 31
204
+ elif dtype == torch.int64:
205
+ return 63
206
+ else:
207
+ raise TypeError(f"Number of value bits is only defined for integer dtypes, but got {dtype}.")
208
+
209
+
210
+ @_register_kernel_internal(to_dtype, torch.Tensor)
211
+ @_register_kernel_internal(to_dtype, tv_tensors.Image)
212
+ def to_dtype_image(image: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor:
213
+
214
+ if image.dtype == dtype:
215
+ return image
216
+ elif not scale:
217
+ return image.to(dtype)
218
+
219
+ float_input = image.is_floating_point()
220
+ if torch.jit.is_scripting():
221
+ # TODO: remove this branch as soon as `dtype.is_floating_point` is supported by JIT
222
+ float_output = torch.tensor(0, dtype=dtype).is_floating_point()
223
+ else:
224
+ float_output = dtype.is_floating_point
225
+
226
+ if float_input:
227
+ # float to float
228
+ if float_output:
229
+ return image.to(dtype)
230
+
231
+ # float to int
232
+ if (image.dtype == torch.float32 and dtype in (torch.int32, torch.int64)) or (
233
+ image.dtype == torch.float64 and dtype == torch.int64
234
+ ):
235
+ raise RuntimeError(f"The conversion from {image.dtype} to {dtype} cannot be performed safely.")
236
+
237
+ # For data in the range `[0.0, 1.0]`, just multiplying by the maximum value of the integer range and converting
238
+ # to the integer dtype is not sufficient. For example, `torch.rand(...).mul(255).to(torch.uint8)` will only
239
+ # be `255` if the input is exactly `1.0`. See https://github.com/pytorch/vision/pull/2078#issuecomment-612045321
240
+ # for a detailed analysis.
241
+ # To mitigate this, we could round before we convert to the integer dtype, but this is an extra operation.
242
+ # Instead, we can also multiply by the maximum value plus something close to `1`. See
243
+ # https://github.com/pytorch/vision/pull/2078#issuecomment-613524965 for details.
244
+ eps = 1e-3
245
+ max_value = float(_max_value(dtype))
246
+ # We need to scale first since the conversion would otherwise turn the input range `[0.0, 1.0]` into the
247
+ # discrete set `{0, 1}`.
248
+ return image.mul(max_value + 1.0 - eps).to(dtype)
249
+ else:
250
+ # int to float
251
+ if float_output:
252
+ return image.to(dtype).mul_(1.0 / _max_value(image.dtype))
253
+
254
+ # int to int
255
+ num_value_bits_input = _num_value_bits(image.dtype)
256
+ num_value_bits_output = _num_value_bits(dtype)
257
+
258
+ if num_value_bits_input > num_value_bits_output:
259
+ return image.bitwise_right_shift(num_value_bits_input - num_value_bits_output).to(dtype)
260
+ else:
261
+ return image.to(dtype).bitwise_left_shift_(num_value_bits_output - num_value_bits_input)
262
+
263
+
264
+ # We encourage users to use to_dtype() instead but we keep this for BC
265
+ def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float32) -> torch.Tensor:
266
+ """[DEPRECATED] Use to_dtype() instead."""
267
+ return to_dtype_image(image, dtype=dtype, scale=True)
268
+
269
+
270
+ @_register_kernel_internal(to_dtype, tv_tensors.Video)
271
+ def to_dtype_video(video: torch.Tensor, dtype: torch.dtype = torch.float, scale: bool = False) -> torch.Tensor:
272
+ return to_dtype_image(video, dtype, scale=scale)
273
+
274
+
275
+ @_register_kernel_internal(to_dtype, tv_tensors.BoundingBoxes, tv_tensor_wrapper=False)
276
+ @_register_kernel_internal(to_dtype, tv_tensors.Mask, tv_tensor_wrapper=False)
277
+ def _to_dtype_tensor_dispatch(inpt: torch.Tensor, dtype: torch.dtype, scale: bool = False) -> torch.Tensor:
278
+ # We don't need to unwrap and rewrap here, since TVTensor.to() preserves the type
279
+ return inpt.to(dtype)
280
+
281
+
282
+ def sanitize_bounding_boxes(
283
+ bounding_boxes: torch.Tensor,
284
+ format: Optional[tv_tensors.BoundingBoxFormat] = None,
285
+ canvas_size: Optional[Tuple[int, int]] = None,
286
+ min_size: float = 1.0,
287
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
288
+ """Remove degenerate/invalid bounding boxes and return the corresponding indexing mask.
289
+
290
+ This removes bounding boxes that:
291
+
292
+ - are below a given ``min_size``: by default this also removes degenerate boxes that have e.g. X2 <= X1.
293
+ - have any coordinate outside of their corresponding image. You may want to
294
+ call :func:`~torchvision.transforms.v2.functional.clamp_bounding_boxes` first to avoid undesired removals.
295
+
296
+ It is recommended to call it at the end of a pipeline, before passing the
297
+ input to the models. It is critical to call this transform if
298
+ :class:`~torchvision.transforms.v2.RandomIoUCrop` was called.
299
+ If you want to be extra careful, you may call it after all transforms that
300
+ may modify bounding boxes but once at the end should be enough in most
301
+ cases.
302
+
303
+ Args:
304
+ bounding_boxes (Tensor or :class:`~torchvision.tv_tensors.BoundingBoxes`): The bounding boxes to be sanitized.
305
+ format (str or :class:`~torchvision.tv_tensors.BoundingBoxFormat`, optional): The format of the bounding boxes.
306
+ Must be left to none if ``bounding_boxes`` is a :class:`~torchvision.tv_tensors.BoundingBoxes` object.
307
+ canvas_size (tuple of int, optional): The canvas_size of the bounding boxes
308
+ (size of the corresponding image/video).
309
+ Must be left to none if ``bounding_boxes`` is a :class:`~torchvision.tv_tensors.BoundingBoxes` object.
310
+ min_size (float, optional) The size below which bounding boxes are removed. Default is 1.
311
+
312
+ Returns:
313
+ out (tuple of Tensors): The subset of valid bounding boxes, and the corresponding indexing mask.
314
+ The mask can then be used to subset other tensors (e.g. labels) that are associated with the bounding boxes.
315
+ """
316
+ if torch.jit.is_scripting() or is_pure_tensor(bounding_boxes):
317
+ if format is None or canvas_size is None:
318
+ raise ValueError(
319
+ "format and canvas_size cannot be None if bounding_boxes is a pure tensor. "
320
+ f"Got format={format} and canvas_size={canvas_size}."
321
+ "Set those to appropriate values or pass bounding_boxes as a tv_tensors.BoundingBoxes object."
322
+ )
323
+ if isinstance(format, str):
324
+ format = tv_tensors.BoundingBoxFormat[format.upper()]
325
+ valid = _get_sanitize_bounding_boxes_mask(
326
+ bounding_boxes, format=format, canvas_size=canvas_size, min_size=min_size
327
+ )
328
+ bounding_boxes = bounding_boxes[valid]
329
+ else:
330
+ if not isinstance(bounding_boxes, tv_tensors.BoundingBoxes):
331
+ raise ValueError("bouding_boxes must be a tv_tensors.BoundingBoxes instance or a pure tensor.")
332
+ if format is not None or canvas_size is not None:
333
+ raise ValueError(
334
+ "format and canvas_size must be None when bounding_boxes is a tv_tensors.BoundingBoxes instance. "
335
+ f"Got format={format} and canvas_size={canvas_size}. "
336
+ "Leave those to None or pass bouding_boxes as a pure tensor."
337
+ )
338
+ valid = _get_sanitize_bounding_boxes_mask(
339
+ bounding_boxes, format=bounding_boxes.format, canvas_size=bounding_boxes.canvas_size, min_size=min_size
340
+ )
341
+ bounding_boxes = tv_tensors.wrap(bounding_boxes[valid], like=bounding_boxes)
342
+
343
+ return bounding_boxes, valid
344
+
345
+
346
+ def _get_sanitize_bounding_boxes_mask(
347
+ bounding_boxes: torch.Tensor,
348
+ format: tv_tensors.BoundingBoxFormat,
349
+ canvas_size: Tuple[int, int],
350
+ min_size: float = 1.0,
351
+ ) -> torch.Tensor:
352
+
353
+ bounding_boxes = _convert_bounding_box_format(
354
+ bounding_boxes, new_format=tv_tensors.BoundingBoxFormat.XYXY, old_format=format
355
+ )
356
+
357
+ image_h, image_w = canvas_size
358
+ ws, hs = bounding_boxes[:, 2] - bounding_boxes[:, 0], bounding_boxes[:, 3] - bounding_boxes[:, 1]
359
+ valid = (ws >= min_size) & (hs >= min_size) & (bounding_boxes >= 0).all(dim=-1)
360
+ # TODO: Do we really need to check for out of bounds here? All
361
+ # transforms should be clamping anyway, so this should never happen?
362
+ image_h, image_w = canvas_size
363
+ valid &= (bounding_boxes[:, 0] <= image_w) & (bounding_boxes[:, 2] <= image_w)
364
+ valid &= (bounding_boxes[:, 1] <= image_h) & (bounding_boxes[:, 3] <= image_h)
365
+ return valid
shared/package-files/8b/8b7ae587d5e6626d839e50e6bdbaaf7778f29bab25a57b9866ccec713ec6ce15/blob ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/NumericUtils.h>
4
+ #include <ATen/native/Resize.h>
5
+ #include <c10/util/irange.h>
6
+
7
+ #ifndef AT_PER_OPERATOR_HEADERS
8
+ #include <ATen/Functions.h>
9
+ #else
10
+ #include <ATen/ops/empty.h>
11
+ #endif
12
+
13
+ namespace at::native {
14
+
15
+ // ensure we get good values and indices for kthvalue, mode
16
+ // this will always be with the reducing dim as 1-d
17
+ inline void _reduction_with_indices_allocate_or_resize_output(
18
+ Tensor& values,
19
+ Tensor& indices,
20
+ const Tensor& self,
21
+ int64_t dim_,
22
+ bool keepdim) {
23
+ int64_t dim = maybe_wrap_dim(dim_, self.dim(), /*wrap_scalar=*/true);
24
+ auto result_sizes = self.sizes().vec();
25
+ if (!result_sizes.empty()) {
26
+ result_sizes[dim] = 1;
27
+ }
28
+ if (values.defined()) {
29
+ TORCH_CHECK(
30
+ self.options().type_equal(values.options()),
31
+ "output values must be of same type as input");
32
+ if (!keepdim && values.dim() == self.dim() - 1) {
33
+ // unsqueeze to preserve passed in noncontiguous tensor in resize
34
+ values.unsqueeze_(dim);
35
+ }
36
+ resize_output(values, result_sizes);
37
+ } else {
38
+ values = at::empty(result_sizes, self.options());
39
+ }
40
+ if (indices.defined()) {
41
+ TORCH_CHECK(
42
+ indices.dtype() == kLong, "output indices must be of scalar type Long");
43
+ TORCH_CHECK(
44
+ indices.device() == self.device(),
45
+ "output indices must be on same device as input");
46
+ if (!keepdim && indices.dim() == self.dim() - 1) {
47
+ // unsqueeze to preserve passed in noncontiguous tensor in resize
48
+ indices.unsqueeze_(dim);
49
+ }
50
+ resize_output(indices, result_sizes);
51
+ } else {
52
+ indices = at::empty(result_sizes, self.options().dtype(kLong));
53
+ }
54
+ }
55
+
56
+ // ensure we get good values and indices for topk
57
+ inline void _allocate_or_resize_output_with_indices(
58
+ Tensor& values,
59
+ Tensor& indices,
60
+ const Tensor& self,
61
+ int64_t dim_,
62
+ int64_t k) {
63
+ int64_t dim = maybe_wrap_dim(dim_, self.dim(), /*wrap_scalar=*/true);
64
+ auto result_sizes = self.sizes().vec();
65
+ if (!result_sizes.empty()) {
66
+ result_sizes[dim] = k;
67
+ }
68
+ if (values.defined()) {
69
+ TORCH_CHECK(
70
+ self.options().type_equal(values.options()),
71
+ "output values must be of same type as input");
72
+ values.resize_(result_sizes);
73
+ } else {
74
+ values = at::empty(result_sizes, self.options());
75
+ }
76
+ if (indices.defined()) {
77
+ TORCH_CHECK(
78
+ indices.dtype() == kLong, "output indices must be of scalar type Long");
79
+ TORCH_CHECK(
80
+ indices.device() == self.device(),
81
+ "output indices must be on same device as input");
82
+ indices.resize_(result_sizes);
83
+ } else {
84
+ indices = at::empty(result_sizes, self.options().dtype(kLong));
85
+ }
86
+ }
87
+
88
+ } // namespace at::native
shared/package-files/8b/8b7b8f573b4784884ded9423b548f06d1deabe36673008b8a8a784d31e49539b/blob ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from multiprocessing import pool
2
+ from multiprocessing.process import Process as Process, active_children as active_children, current_process as current_process
3
+ from multiprocessing.util import SUBDEBUG as SUBDEBUG, SUBWARNING as SUBWARNING
4
+ from Queue import Queue as _BaseQueue
5
+ from typing import Any, Callable, Iterable, Optional, TypeVar
6
+
7
+ class ProcessError(Exception): ...
8
+ class BufferTooShort(ProcessError): ...
9
+ class TimeoutError(ProcessError): ...
10
+ class AuthenticationError(ProcessError): ...
11
+
12
+ _T = TypeVar("_T")
13
+
14
+ class Queue(_BaseQueue[_T]):
15
+ def __init__(self, maxsize: int = ...) -> None: ...
16
+ def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ...
17
+ def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ...
18
+ def qsize(self) -> int: ...
19
+ def empty(self) -> bool: ...
20
+ def full(self) -> bool: ...
21
+ def put_nowait(self, item: _T) -> None: ...
22
+ def get_nowait(self) -> _T: ...
23
+ def close(self) -> None: ...
24
+ def join_thread(self) -> None: ...
25
+ def cancel_join_thread(self) -> None: ...
26
+
27
+ def Manager(): ...
28
+ def Pipe(duplex: bool = ...): ...
29
+ def cpu_count() -> int: ...
30
+ def freeze_support(): ...
31
+ def get_logger(): ...
32
+ def log_to_stderr(level: Optional[Any] = ...): ...
33
+ def allow_connection_pickling(): ...
34
+ def Lock(): ...
35
+ def RLock(): ...
36
+ def Condition(lock: Optional[Any] = ...): ...
37
+ def Semaphore(value: int = ...): ...
38
+ def BoundedSemaphore(value: int = ...): ...
39
+ def Event(): ...
40
+ def JoinableQueue(maxsize: int = ...): ...
41
+ def RawValue(typecode_or_type, *args): ...
42
+ def RawArray(typecode_or_type, size_or_initializer): ...
43
+ def Value(typecode_or_type, *args, **kwds): ...
44
+ def Array(typecode_or_type, size_or_initializer, **kwds): ...
45
+ def Pool(
46
+ processes: Optional[int] = ...,
47
+ initializer: Optional[Callable[..., Any]] = ...,
48
+ initargs: Iterable[Any] = ...,
49
+ maxtasksperchild: Optional[int] = ...,
50
+ ) -> pool.Pool: ...
shared/package-files/8b/8b7c37207ece2c8fce70644de6738aadc1c4262f356485f699f83b4cffe3a880/blob ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // DO NOT DEFINE STATIC DATA IN THIS HEADER!
4
+ // See Note [Do not compile initializers with AVX]
5
+
6
+ #include <ATen/cpu/vec/intrinsics.h>
7
+ #include <ATen/cpu/vec/vec_base.h>
8
+ #include <c10/util/irange.h>
9
+ #if defined(CPU_CAPABILITY_AVX2) && !defined(_MSC_VER)
10
+ #include <sleef.h>
11
+ #endif
12
+
13
+ namespace at::vec {
14
+ // See Note [CPU_CAPABILITY namespace]
15
+ inline namespace CPU_CAPABILITY {
16
+
17
+
18
+ #if defined(CPU_CAPABILITY_AVX2) && !defined(_MSC_VER)
19
+
20
+ template <> class Vectorized<double> {
21
+ private:
22
+ __m256d values;
23
+ public:
24
+ using value_type = double;
25
+ using size_type = int;
26
+ static constexpr size_type size() {
27
+ return 4;
28
+ }
29
+ Vectorized() {}
30
+ Vectorized(__m256d v) : values(v) {}
31
+ Vectorized(double val) {
32
+ values = _mm256_set1_pd(val);
33
+ }
34
+ Vectorized(double val1, double val2, double val3, double val4) {
35
+ values = _mm256_setr_pd(val1, val2, val3, val4);
36
+ }
37
+ operator __m256d() const {
38
+ return values;
39
+ }
40
+ template <int64_t mask>
41
+ static Vectorized<double> blend(const Vectorized<double>& a, const Vectorized<double>& b) {
42
+ return _mm256_blend_pd(a.values, b.values, mask);
43
+ }
44
+ static Vectorized<double> blendv(const Vectorized<double>& a, const Vectorized<double>& b,
45
+ const Vectorized<double>& mask) {
46
+ return _mm256_blendv_pd(a.values, b.values, mask.values);
47
+ }
48
+ template<typename step_t>
49
+ static Vectorized<double> arange(double base = 0., step_t step = static_cast<step_t>(1)) {
50
+ return Vectorized<double>(base, base + step, base + 2 * step, base + 3 * step);
51
+ }
52
+ static Vectorized<double> set(const Vectorized<double>& a, const Vectorized<double>& b,
53
+ int64_t count = size()) {
54
+ switch (count) {
55
+ case 0:
56
+ return a;
57
+ case 1:
58
+ return blend<1>(a, b);
59
+ case 2:
60
+ return blend<3>(a, b);
61
+ case 3:
62
+ return blend<7>(a, b);
63
+ }
64
+ return b;
65
+ }
66
+ static Vectorized<double> loadu(const void* ptr, int64_t count = size()) {
67
+ if (count == size())
68
+ return _mm256_loadu_pd(reinterpret_cast<const double*>(ptr));
69
+
70
+
71
+ __at_align__ double tmp_values[size()];
72
+ // Ensure uninitialized memory does not change the output value See https://github.com/pytorch/pytorch/issues/32502
73
+ // for more details. We do not initialize arrays to zero using "={0}" because gcc would compile it to two
74
+ // instructions while a loop would be compiled to one instruction.
75
+ for (const auto i : c10::irange(size())) {
76
+ tmp_values[i] = 0.0;
77
+ }
78
+ std::memcpy(
79
+ tmp_values,
80
+ reinterpret_cast<const double*>(ptr),
81
+ count * sizeof(double));
82
+ return _mm256_load_pd(tmp_values);
83
+ }
84
+ void store(void* ptr, int count = size()) const {
85
+ if (count == size()) {
86
+ _mm256_storeu_pd(reinterpret_cast<double*>(ptr), values);
87
+ } else if (count > 0) {
88
+ double tmp_values[size()];
89
+ _mm256_storeu_pd(reinterpret_cast<double*>(tmp_values), values);
90
+ std::memcpy(ptr, tmp_values, count * sizeof(double));
91
+ }
92
+ }
93
+ const double& operator[](int idx) const = delete;
94
+ double& operator[](int idx) = delete;
95
+ int zero_mask() const {
96
+ // returns an integer mask where all zero elements are translated to 1-bit and others are translated to 0-bit
97
+ __m256d cmp = _mm256_cmp_pd(values, _mm256_set1_pd(0.0), _CMP_EQ_OQ);
98
+ return _mm256_movemask_pd(cmp);
99
+ }
100
+ Vectorized<double> isnan() const {
101
+ return _mm256_cmp_pd(values, _mm256_set1_pd(0.0), _CMP_UNORD_Q);
102
+ }
103
+ bool has_inf_nan() const {
104
+ __m256d self_sub = _mm256_sub_pd(values, values);
105
+ return (_mm256_movemask_epi8(_mm256_castpd_si256(self_sub)) & 0x77777777) != 0;
106
+ }
107
+ Vectorized<double> map(double (*const f)(double)) const {
108
+ __at_align__ double tmp[size()];
109
+ store(tmp);
110
+ for (const auto i : c10::irange(size())) {
111
+ tmp[i] = f(tmp[i]);
112
+ }
113
+ return loadu(tmp);
114
+ }
115
+ Vectorized<double> abs() const {
116
+ auto mask = _mm256_set1_pd(-0.f);
117
+ return _mm256_andnot_pd(mask, values);
118
+ }
119
+ Vectorized<double> angle() const {
120
+ const auto zero_vec = _mm256_set1_pd(0.f);
121
+ const auto nan_vec = _mm256_set1_pd(NAN);
122
+ const auto not_nan_mask = _mm256_cmp_pd(values, values, _CMP_EQ_OQ);
123
+ const auto nan_mask = _mm256_cmp_pd(not_nan_mask, zero_vec, _CMP_EQ_OQ);
124
+ const auto pi = _mm256_set1_pd(c10::pi<double>);
125
+
126
+ const auto neg_mask = _mm256_cmp_pd(values, zero_vec, _CMP_LT_OQ);
127
+ auto angle = _mm256_blendv_pd(zero_vec, pi, neg_mask);
128
+ angle = _mm256_blendv_pd(angle, nan_vec, nan_mask);
129
+ return angle;
130
+ }
131
+ Vectorized<double> real() const {
132
+ return *this;
133
+ }
134
+ Vectorized<double> imag() const {
135
+ return _mm256_set1_pd(0);
136
+ }
137
+ Vectorized<double> conj() const {
138
+ return *this;
139
+ }
140
+ Vectorized<double> acos() const {
141
+ return Vectorized<double>(Sleef_acosd4_u10(values));
142
+ }
143
+ Vectorized<double> acosh() const {
144
+ return Vectorized<double>(Sleef_acoshd4_u10(values));
145
+ }
146
+ Vectorized<double> asin() const {
147
+ return Vectorized<double>(Sleef_asind4_u10(values));
148
+ }
149
+ Vectorized<double> atan() const {
150
+ return Vectorized<double>(Sleef_atand4_u10(values));
151
+ }
152
+ Vectorized<double> atanh() const {
153
+ return Vectorized<double>(Sleef_atanhd4_u10(values));
154
+ }
155
+ Vectorized<double> atan2(const Vectorized<double> &b) const {
156
+ return Vectorized<double>(Sleef_atan2d4_u10(values, b));
157
+ }
158
+ Vectorized<double> copysign(const Vectorized<double> &sign) const {
159
+ return Vectorized<double>(Sleef_copysignd4(values, sign));
160
+ }
161
+ Vectorized<double> erf() const {
162
+ return Vectorized<double>(Sleef_erfd4_u10(values));
163
+ }
164
+ Vectorized<double> erfc() const {
165
+ return Vectorized<double>(Sleef_erfcd4_u15(values));
166
+ }
167
+ Vectorized<double> erfinv() const {
168
+ return map(calc_erfinv);
169
+ }
170
+ Vectorized<double> exp() const {
171
+ return Vectorized<double>(Sleef_expd4_u10(values));
172
+ }
173
+ Vectorized<double> exp2() const {
174
+ return Vectorized<double>(Sleef_exp2d4_u10(values));
175
+ }
176
+ Vectorized<double> expm1() const {
177
+ return Vectorized<double>(Sleef_expm1d4_u10(values));
178
+ }
179
+ Vectorized<double> exp_u20() const {
180
+ return exp();
181
+ }
182
+ Vectorized<double> fmod(const Vectorized<double>& q) const {
183
+ return Vectorized<double>(Sleef_fmodd4(values, q));
184
+ }
185
+ Vectorized<double> hypot(const Vectorized<double> &b) const {
186
+ return Vectorized<double>(Sleef_hypotd4_u05(values, b));
187
+ }
188
+ Vectorized<double> i0() const {
189
+ return map(calc_i0);
190
+ }
191
+ Vectorized<double> i0e() const {
192
+ return map(calc_i0e);
193
+ }
194
+ Vectorized<double> digamma() const {
195
+ return map(calc_digamma);
196
+ }
197
+ Vectorized<double> igamma(const Vectorized<double> &x) const {
198
+ __at_align__ double tmp[size()];
199
+ __at_align__ double tmp_x[size()];
200
+ store(tmp);
201
+ x.store(tmp_x);
202
+ for (const auto i : c10::irange(size())) {
203
+ tmp[i] = calc_igamma(tmp[i], tmp_x[i]);
204
+ }
205
+ return loadu(tmp);
206
+ }
207
+ Vectorized<double> igammac(const Vectorized<double> &x) const {
208
+ __at_align__ double tmp[size()];
209
+ __at_align__ double tmp_x[size()];
210
+ store(tmp);
211
+ x.store(tmp_x);
212
+ for (const auto i : c10::irange(size())) {
213
+ tmp[i] = calc_igammac(tmp[i], tmp_x[i]);
214
+ }
215
+ return loadu(tmp);
216
+ }
217
+ Vectorized<double> log() const {
218
+ return Vectorized<double>(Sleef_logd4_u10(values));
219
+ }
220
+ Vectorized<double> log2() const {
221
+ return Vectorized<double>(Sleef_log2d4_u10(values));
222
+ }
223
+ Vectorized<double> log10() const {
224
+ return Vectorized<double>(Sleef_log10d4_u10(values));
225
+ }
226
+ Vectorized<double> log1p() const {
227
+ return Vectorized<double>(Sleef_log1pd4_u10(values));
228
+ }
229
+ Vectorized<double> sin() const {
230
+ return Vectorized<double>(Sleef_sind4_u10(values));
231
+ }
232
+ Vectorized<double> sinh() const {
233
+ return Vectorized<double>(Sleef_sinhd4_u10(values));
234
+ }
235
+ Vectorized<double> cos() const {
236
+ return Vectorized<double>(Sleef_cosd4_u10(values));
237
+ }
238
+ Vectorized<double> cosh() const {
239
+ return Vectorized<double>(Sleef_coshd4_u10(values));
240
+ }
241
+ Vectorized<double> ceil() const {
242
+ return _mm256_ceil_pd(values);
243
+ }
244
+ Vectorized<double> floor() const {
245
+ return _mm256_floor_pd(values);
246
+ }
247
+ Vectorized<double> frac() const;
248
+ Vectorized<double> neg() const {
249
+ return _mm256_xor_pd(_mm256_set1_pd(-0.), values);
250
+ }
251
+ Vectorized<double> nextafter(const Vectorized<double> &b) const {
252
+ return Vectorized<double>(Sleef_nextafterd4(values, b));
253
+ }
254
+ Vectorized<double> round() const {
255
+ return _mm256_round_pd(values, (_MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC));
256
+ }
257
+ Vectorized<double> tan() const {
258
+ return Vectorized<double>(Sleef_tand4_u10(values));
259
+ }
260
+ Vectorized<double> tanh() const {
261
+ return Vectorized<double>(Sleef_tanhd4_u10(values));
262
+ }
263
+ Vectorized<double> trunc() const {
264
+ return _mm256_round_pd(values, (_MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC));
265
+ }
266
+ Vectorized<double> lgamma() const {
267
+ return Vectorized<double>(Sleef_lgammad4_u10(values));
268
+ }
269
+ Vectorized<double> sqrt() const {
270
+ return _mm256_sqrt_pd(values);
271
+ }
272
+ Vectorized<double> reciprocal() const {
273
+ return _mm256_div_pd(_mm256_set1_pd(1), values);
274
+ }
275
+ Vectorized<double> rsqrt() const {
276
+ return _mm256_div_pd(_mm256_set1_pd(1), _mm256_sqrt_pd(values));
277
+ }
278
+ Vectorized<double> pow(const Vectorized<double> &b) const {
279
+ return Vectorized<double>(Sleef_powd4_u10(values, b));
280
+ }
281
+ // Comparison using the _CMP_**_OQ predicate.
282
+ // `O`: get false if an operand is NaN
283
+ // `Q`: do not raise if an operand is NaN
284
+ Vectorized<double> operator==(const Vectorized<double>& other) const {
285
+ return _mm256_cmp_pd(values, other.values, _CMP_EQ_OQ);
286
+ }
287
+
288
+ Vectorized<double> operator!=(const Vectorized<double>& other) const {
289
+ return _mm256_cmp_pd(values, other.values, _CMP_NEQ_UQ);
290
+ }
291
+
292
+ Vectorized<double> operator<(const Vectorized<double>& other) const {
293
+ return _mm256_cmp_pd(values, other.values, _CMP_LT_OQ);
294
+ }
295
+
296
+ Vectorized<double> operator<=(const Vectorized<double>& other) const {
297
+ return _mm256_cmp_pd(values, other.values, _CMP_LE_OQ);
298
+ }
299
+
300
+ Vectorized<double> operator>(const Vectorized<double>& other) const {
301
+ return _mm256_cmp_pd(values, other.values, _CMP_GT_OQ);
302
+ }
303
+
304
+ Vectorized<double> operator>=(const Vectorized<double>& other) const {
305
+ return _mm256_cmp_pd(values, other.values, _CMP_GE_OQ);
306
+ }
307
+
308
+ Vectorized<double> eq(const Vectorized<double>& other) const;
309
+ Vectorized<double> ne(const Vectorized<double>& other) const;
310
+ Vectorized<double> lt(const Vectorized<double>& other) const;
311
+ Vectorized<double> le(const Vectorized<double>& other) const;
312
+ Vectorized<double> gt(const Vectorized<double>& other) const;
313
+ Vectorized<double> ge(const Vectorized<double>& other) const;
314
+ };
315
+
316
+ template <>
317
+ Vectorized<double> inline operator+(const Vectorized<double>& a, const Vectorized<double>& b) {
318
+ return _mm256_add_pd(a, b);
319
+ }
320
+
321
+ template <>
322
+ Vectorized<double> inline operator-(const Vectorized<double>& a, const Vectorized<double>& b) {
323
+ return _mm256_sub_pd(a, b);
324
+ }
325
+
326
+ template <>
327
+ Vectorized<double> inline operator*(const Vectorized<double>& a, const Vectorized<double>& b) {
328
+ return _mm256_mul_pd(a, b);
329
+ }
330
+
331
+ template <>
332
+ Vectorized<double> inline operator/(const Vectorized<double>& a, const Vectorized<double>& b) {
333
+ return _mm256_div_pd(a, b);
334
+ }
335
+
336
+ // frac. Implement this here so we can use subtraction.
337
+ inline Vectorized<double> Vectorized<double>::frac() const {
338
+ return *this - this->trunc();
339
+ }
340
+
341
+ // Implements the IEEE 754 201X `maximum` operation, which propagates NaN if
342
+ // either input is a NaN.
343
+ template <>
344
+ Vectorized<double> inline maximum(const Vectorized<double>& a, const Vectorized<double>& b) {
345
+ Vectorized<double> max = _mm256_max_pd(a, b);
346
+ Vectorized<double> isnan = _mm256_cmp_pd(a, b, _CMP_UNORD_Q);
347
+ // Exploit the fact that all-ones is a NaN.
348
+ return _mm256_or_pd(max, isnan);
349
+ }
350
+
351
+ // Implements the IEEE 754 201X `minimum` operation, which propagates NaN if
352
+ // either input is a NaN.
353
+ template <>
354
+ Vectorized<double> inline minimum(const Vectorized<double>& a, const Vectorized<double>& b) {
355
+ Vectorized<double> min = _mm256_min_pd(a, b);
356
+ Vectorized<double> isnan = _mm256_cmp_pd(a, b, _CMP_UNORD_Q);
357
+ // Exploit the fact that all-ones is a NaN.
358
+ return _mm256_or_pd(min, isnan);
359
+ }
360
+
361
+ template <>
362
+ Vectorized<double> inline clamp(const Vectorized<double>& a, const Vectorized<double>& min, const Vectorized<double>& max) {
363
+ return _mm256_min_pd(max, _mm256_max_pd(min, a));
364
+ }
365
+
366
+ template <>
367
+ Vectorized<double> inline clamp_min(const Vectorized<double>& a, const Vectorized<double>& min) {
368
+ return _mm256_max_pd(min, a);
369
+ }
370
+
371
+ template <>
372
+ Vectorized<double> inline clamp_max(const Vectorized<double>& a, const Vectorized<double>& max) {
373
+ return _mm256_min_pd(max, a);
374
+ }
375
+
376
+ template <>
377
+ Vectorized<double> inline operator&(const Vectorized<double>& a, const Vectorized<double>& b) {
378
+ return _mm256_and_pd(a, b);
379
+ }
380
+
381
+ template <>
382
+ Vectorized<double> inline operator|(const Vectorized<double>& a, const Vectorized<double>& b) {
383
+ return _mm256_or_pd(a, b);
384
+ }
385
+
386
+ template <>
387
+ Vectorized<double> inline operator^(const Vectorized<double>& a, const Vectorized<double>& b) {
388
+ return _mm256_xor_pd(a, b);
389
+ }
390
+
391
+ inline Vectorized<double> Vectorized<double>::eq(const Vectorized<double>& other) const {
392
+ return (*this == other) & Vectorized<double>(1.0);
393
+ }
394
+
395
+ inline Vectorized<double> Vectorized<double>::ne(const Vectorized<double>& other) const {
396
+ return (*this != other) & Vectorized<double>(1.0);
397
+ }
398
+
399
+ inline Vectorized<double> Vectorized<double>::gt(const Vectorized<double>& other) const {
400
+ return (*this > other) & Vectorized<double>(1.0);
401
+ }
402
+
403
+ inline Vectorized<double> Vectorized<double>::ge(const Vectorized<double>& other) const {
404
+ return (*this >= other) & Vectorized<double>(1.0);
405
+ }
406
+
407
+ inline Vectorized<double> Vectorized<double>::lt(const Vectorized<double>& other) const {
408
+ return (*this < other) & Vectorized<double>(1.0);
409
+ }
410
+
411
+ inline Vectorized<double> Vectorized<double>::le(const Vectorized<double>& other) const {
412
+ return (*this <= other) & Vectorized<double>(1.0);
413
+ }
414
+
415
+ template <>
416
+ inline void convert(const double* src, double* dst, int64_t n) {
417
+ int64_t i;
418
+ #pragma unroll
419
+ for (i = 0; i <= (n - Vectorized<double>::size()); i += Vectorized<double>::size()) {
420
+ _mm256_storeu_pd(dst + i, _mm256_loadu_pd(src + i));
421
+ }
422
+ #pragma unroll
423
+ for (; i < n; i++) {
424
+ dst[i] = src[i];
425
+ }
426
+ }
427
+
428
+ #ifdef CPU_CAPABILITY_AVX2
429
+ template <>
430
+ Vectorized<double> inline fmadd(const Vectorized<double>& a, const Vectorized<double>& b, const Vectorized<double>& c) {
431
+ return _mm256_fmadd_pd(a, b, c);
432
+ }
433
+
434
+ template <>
435
+ Vectorized<double> inline fmsub(const Vectorized<double>& a, const Vectorized<double>& b, const Vectorized<double>& c) {
436
+ return _mm256_fmsub_pd(a, b, c);
437
+ }
438
+ #endif
439
+
440
+ #endif
441
+
442
+ }} // namespace at::vec::CPU_CAPABILITY
shared/package-files/8b/8b7d767810c385f42c26a20463b1cb3b89a6ebe177830d31a6d6019fe8dc1986/blob ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/autograd/variable.h>
4
+ #include <torch/csrc/python_headers.h>
5
+ #include <cstdint>
6
+
7
+ extern PyTypeObject THPSizeType;
8
+
9
+ #define THPSize_Check(obj) (Py_TYPE(obj) == &THPSizeType)
10
+
11
+ PyObject* THPSize_New(const torch::autograd::Variable& t);
12
+ PyObject* THPSize_NewFromSizes(int64_t dim, const int64_t* sizes);
13
+ PyObject* THPSize_NewFromSymSizes(const at::Tensor& t);
14
+
15
+ void THPSize_init(PyObject* module);
shared/package-files/8b/8b7e063d10197b15cc4fa6f0b9fe52132bdd992f9b442cbd28c8f03793baa639/blob ADDED
@@ -0,0 +1,1204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AST nodes generated by the parser for the compiler. Also provides
2
+ some node tree helper functions used by the parser and compiler in order
3
+ to normalize nodes.
4
+ """
5
+ import inspect
6
+ import operator
7
+ import typing as t
8
+ from collections import deque
9
+
10
+ from markupsafe import Markup
11
+
12
+ from .utils import _PassArg
13
+
14
+ if t.TYPE_CHECKING:
15
+ import typing_extensions as te
16
+ from .environment import Environment
17
+
18
+ _NodeBound = t.TypeVar("_NodeBound", bound="Node")
19
+
20
+ _binop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
21
+ "*": operator.mul,
22
+ "/": operator.truediv,
23
+ "//": operator.floordiv,
24
+ "**": operator.pow,
25
+ "%": operator.mod,
26
+ "+": operator.add,
27
+ "-": operator.sub,
28
+ }
29
+
30
+ _uaop_to_func: t.Dict[str, t.Callable[[t.Any], t.Any]] = {
31
+ "not": operator.not_,
32
+ "+": operator.pos,
33
+ "-": operator.neg,
34
+ }
35
+
36
+ _cmpop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
37
+ "eq": operator.eq,
38
+ "ne": operator.ne,
39
+ "gt": operator.gt,
40
+ "gteq": operator.ge,
41
+ "lt": operator.lt,
42
+ "lteq": operator.le,
43
+ "in": lambda a, b: a in b,
44
+ "notin": lambda a, b: a not in b,
45
+ }
46
+
47
+
48
+ class Impossible(Exception):
49
+ """Raised if the node could not perform a requested action."""
50
+
51
+
52
+ class NodeType(type):
53
+ """A metaclass for nodes that handles the field and attribute
54
+ inheritance. fields and attributes from the parent class are
55
+ automatically forwarded to the child."""
56
+
57
+ def __new__(mcs, name, bases, d): # type: ignore
58
+ for attr in "fields", "attributes":
59
+ storage = []
60
+ storage.extend(getattr(bases[0] if bases else object, attr, ()))
61
+ storage.extend(d.get(attr, ()))
62
+ assert len(bases) <= 1, "multiple inheritance not allowed"
63
+ assert len(storage) == len(set(storage)), "layout conflict"
64
+ d[attr] = tuple(storage)
65
+ d.setdefault("abstract", False)
66
+ return type.__new__(mcs, name, bases, d)
67
+
68
+
69
+ class EvalContext:
70
+ """Holds evaluation time information. Custom attributes can be attached
71
+ to it in extensions.
72
+ """
73
+
74
+ def __init__(
75
+ self, environment: "Environment", template_name: t.Optional[str] = None
76
+ ) -> None:
77
+ self.environment = environment
78
+ if callable(environment.autoescape):
79
+ self.autoescape = environment.autoescape(template_name)
80
+ else:
81
+ self.autoescape = environment.autoescape
82
+ self.volatile = False
83
+
84
+ def save(self) -> t.Mapping[str, t.Any]:
85
+ return self.__dict__.copy()
86
+
87
+ def revert(self, old: t.Mapping[str, t.Any]) -> None:
88
+ self.__dict__.clear()
89
+ self.__dict__.update(old)
90
+
91
+
92
+ def get_eval_context(node: "Node", ctx: t.Optional[EvalContext]) -> EvalContext:
93
+ if ctx is None:
94
+ if node.environment is None:
95
+ raise RuntimeError(
96
+ "if no eval context is passed, the node must have an"
97
+ " attached environment."
98
+ )
99
+ return EvalContext(node.environment)
100
+ return ctx
101
+
102
+
103
+ class Node(metaclass=NodeType):
104
+ """Baseclass for all Jinja nodes. There are a number of nodes available
105
+ of different types. There are four major types:
106
+
107
+ - :class:`Stmt`: statements
108
+ - :class:`Expr`: expressions
109
+ - :class:`Helper`: helper nodes
110
+ - :class:`Template`: the outermost wrapper node
111
+
112
+ All nodes have fields and attributes. Fields may be other nodes, lists,
113
+ or arbitrary values. Fields are passed to the constructor as regular
114
+ positional arguments, attributes as keyword arguments. Each node has
115
+ two attributes: `lineno` (the line number of the node) and `environment`.
116
+ The `environment` attribute is set at the end of the parsing process for
117
+ all nodes automatically.
118
+ """
119
+
120
+ fields: t.Tuple[str, ...] = ()
121
+ attributes: t.Tuple[str, ...] = ("lineno", "environment")
122
+ abstract = True
123
+
124
+ lineno: int
125
+ environment: t.Optional["Environment"]
126
+
127
+ def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:
128
+ if self.abstract:
129
+ raise TypeError("abstract nodes are not instantiable")
130
+ if fields:
131
+ if len(fields) != len(self.fields):
132
+ if not self.fields:
133
+ raise TypeError(f"{type(self).__name__!r} takes 0 arguments")
134
+ raise TypeError(
135
+ f"{type(self).__name__!r} takes 0 or {len(self.fields)}"
136
+ f" argument{'s' if len(self.fields) != 1 else ''}"
137
+ )
138
+ for name, arg in zip(self.fields, fields):
139
+ setattr(self, name, arg)
140
+ for attr in self.attributes:
141
+ setattr(self, attr, attributes.pop(attr, None))
142
+ if attributes:
143
+ raise TypeError(f"unknown attribute {next(iter(attributes))!r}")
144
+
145
+ def iter_fields(
146
+ self,
147
+ exclude: t.Optional[t.Container[str]] = None,
148
+ only: t.Optional[t.Container[str]] = None,
149
+ ) -> t.Iterator[t.Tuple[str, t.Any]]:
150
+ """This method iterates over all fields that are defined and yields
151
+ ``(key, value)`` tuples. Per default all fields are returned, but
152
+ it's possible to limit that to some fields by providing the `only`
153
+ parameter or to exclude some using the `exclude` parameter. Both
154
+ should be sets or tuples of field names.
155
+ """
156
+ for name in self.fields:
157
+ if (
158
+ (exclude is None and only is None)
159
+ or (exclude is not None and name not in exclude)
160
+ or (only is not None and name in only)
161
+ ):
162
+ try:
163
+ yield name, getattr(self, name)
164
+ except AttributeError:
165
+ pass
166
+
167
+ def iter_child_nodes(
168
+ self,
169
+ exclude: t.Optional[t.Container[str]] = None,
170
+ only: t.Optional[t.Container[str]] = None,
171
+ ) -> t.Iterator["Node"]:
172
+ """Iterates over all direct child nodes of the node. This iterates
173
+ over all fields and yields the values of they are nodes. If the value
174
+ of a field is a list all the nodes in that list are returned.
175
+ """
176
+ for _, item in self.iter_fields(exclude, only):
177
+ if isinstance(item, list):
178
+ for n in item:
179
+ if isinstance(n, Node):
180
+ yield n
181
+ elif isinstance(item, Node):
182
+ yield item
183
+
184
+ def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:
185
+ """Find the first node of a given type. If no such node exists the
186
+ return value is `None`.
187
+ """
188
+ for result in self.find_all(node_type):
189
+ return result
190
+
191
+ return None
192
+
193
+ def find_all(
194
+ self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]
195
+ ) -> t.Iterator[_NodeBound]:
196
+ """Find all the nodes of a given type. If the type is a tuple,
197
+ the check is performed for any of the tuple items.
198
+ """
199
+ for child in self.iter_child_nodes():
200
+ if isinstance(child, node_type):
201
+ yield child # type: ignore
202
+ yield from child.find_all(node_type)
203
+
204
+ def set_ctx(self, ctx: str) -> "Node":
205
+ """Reset the context of a node and all child nodes. Per default the
206
+ parser will all generate nodes that have a 'load' context as it's the
207
+ most common one. This method is used in the parser to set assignment
208
+ targets and other nodes to a store context.
209
+ """
210
+ todo = deque([self])
211
+ while todo:
212
+ node = todo.popleft()
213
+ if "ctx" in node.fields:
214
+ node.ctx = ctx # type: ignore
215
+ todo.extend(node.iter_child_nodes())
216
+ return self
217
+
218
+ def set_lineno(self, lineno: int, override: bool = False) -> "Node":
219
+ """Set the line numbers of the node and children."""
220
+ todo = deque([self])
221
+ while todo:
222
+ node = todo.popleft()
223
+ if "lineno" in node.attributes:
224
+ if node.lineno is None or override:
225
+ node.lineno = lineno
226
+ todo.extend(node.iter_child_nodes())
227
+ return self
228
+
229
+ def set_environment(self, environment: "Environment") -> "Node":
230
+ """Set the environment for all nodes."""
231
+ todo = deque([self])
232
+ while todo:
233
+ node = todo.popleft()
234
+ node.environment = environment
235
+ todo.extend(node.iter_child_nodes())
236
+ return self
237
+
238
+ def __eq__(self, other: t.Any) -> bool:
239
+ if type(self) is not type(other):
240
+ return NotImplemented
241
+
242
+ return tuple(self.iter_fields()) == tuple(other.iter_fields())
243
+
244
+ __hash__ = object.__hash__
245
+
246
+ def __repr__(self) -> str:
247
+ args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)
248
+ return f"{type(self).__name__}({args_str})"
249
+
250
+ def dump(self) -> str:
251
+ def _dump(node: t.Union[Node, t.Any]) -> None:
252
+ if not isinstance(node, Node):
253
+ buf.append(repr(node))
254
+ return
255
+
256
+ buf.append(f"nodes.{type(node).__name__}(")
257
+ if not node.fields:
258
+ buf.append(")")
259
+ return
260
+ for idx, field in enumerate(node.fields):
261
+ if idx:
262
+ buf.append(", ")
263
+ value = getattr(node, field)
264
+ if isinstance(value, list):
265
+ buf.append("[")
266
+ for idx, item in enumerate(value):
267
+ if idx:
268
+ buf.append(", ")
269
+ _dump(item)
270
+ buf.append("]")
271
+ else:
272
+ _dump(value)
273
+ buf.append(")")
274
+
275
+ buf: t.List[str] = []
276
+ _dump(self)
277
+ return "".join(buf)
278
+
279
+
280
+ class Stmt(Node):
281
+ """Base node for all statements."""
282
+
283
+ abstract = True
284
+
285
+
286
+ class Helper(Node):
287
+ """Nodes that exist in a specific context only."""
288
+
289
+ abstract = True
290
+
291
+
292
+ class Template(Node):
293
+ """Node that represents a template. This must be the outermost node that
294
+ is passed to the compiler.
295
+ """
296
+
297
+ fields = ("body",)
298
+ body: t.List[Node]
299
+
300
+
301
+ class Output(Stmt):
302
+ """A node that holds multiple expressions which are then printed out.
303
+ This is used both for the `print` statement and the regular template data.
304
+ """
305
+
306
+ fields = ("nodes",)
307
+ nodes: t.List["Expr"]
308
+
309
+
310
+ class Extends(Stmt):
311
+ """Represents an extends statement."""
312
+
313
+ fields = ("template",)
314
+ template: "Expr"
315
+
316
+
317
+ class For(Stmt):
318
+ """The for loop. `target` is the target for the iteration (usually a
319
+ :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
320
+ of nodes that are used as loop-body, and `else_` a list of nodes for the
321
+ `else` block. If no else node exists it has to be an empty list.
322
+
323
+ For filtered nodes an expression can be stored as `test`, otherwise `None`.
324
+ """
325
+
326
+ fields = ("target", "iter", "body", "else_", "test", "recursive")
327
+ target: Node
328
+ iter: Node
329
+ body: t.List[Node]
330
+ else_: t.List[Node]
331
+ test: t.Optional[Node]
332
+ recursive: bool
333
+
334
+
335
+ class If(Stmt):
336
+ """If `test` is true, `body` is rendered, else `else_`."""
337
+
338
+ fields = ("test", "body", "elif_", "else_")
339
+ test: Node
340
+ body: t.List[Node]
341
+ elif_: t.List["If"]
342
+ else_: t.List[Node]
343
+
344
+
345
+ class Macro(Stmt):
346
+ """A macro definition. `name` is the name of the macro, `args` a list of
347
+ arguments and `defaults` a list of defaults if there are any. `body` is
348
+ a list of nodes for the macro body.
349
+ """
350
+
351
+ fields = ("name", "args", "defaults", "body")
352
+ name: str
353
+ args: t.List["Name"]
354
+ defaults: t.List["Expr"]
355
+ body: t.List[Node]
356
+
357
+
358
+ class CallBlock(Stmt):
359
+ """Like a macro without a name but a call instead. `call` is called with
360
+ the unnamed macro as `caller` argument this node holds.
361
+ """
362
+
363
+ fields = ("call", "args", "defaults", "body")
364
+ call: "Call"
365
+ args: t.List["Name"]
366
+ defaults: t.List["Expr"]
367
+ body: t.List[Node]
368
+
369
+
370
+ class FilterBlock(Stmt):
371
+ """Node for filter sections."""
372
+
373
+ fields = ("body", "filter")
374
+ body: t.List[Node]
375
+ filter: "Filter"
376
+
377
+
378
+ class With(Stmt):
379
+ """Specific node for with statements. In older versions of Jinja the
380
+ with statement was implemented on the base of the `Scope` node instead.
381
+
382
+ .. versionadded:: 2.9.3
383
+ """
384
+
385
+ fields = ("targets", "values", "body")
386
+ targets: t.List["Expr"]
387
+ values: t.List["Expr"]
388
+ body: t.List[Node]
389
+
390
+
391
+ class Block(Stmt):
392
+ """A node that represents a block.
393
+
394
+ .. versionchanged:: 3.0.0
395
+ the `required` field was added.
396
+ """
397
+
398
+ fields = ("name", "body", "scoped", "required")
399
+ name: str
400
+ body: t.List[Node]
401
+ scoped: bool
402
+ required: bool
403
+
404
+
405
+ class Include(Stmt):
406
+ """A node that represents the include tag."""
407
+
408
+ fields = ("template", "with_context", "ignore_missing")
409
+ template: "Expr"
410
+ with_context: bool
411
+ ignore_missing: bool
412
+
413
+
414
+ class Import(Stmt):
415
+ """A node that represents the import tag."""
416
+
417
+ fields = ("template", "target", "with_context")
418
+ template: "Expr"
419
+ target: str
420
+ with_context: bool
421
+
422
+
423
+ class FromImport(Stmt):
424
+ """A node that represents the from import tag. It's important to not
425
+ pass unsafe names to the name attribute. The compiler translates the
426
+ attribute lookups directly into getattr calls and does *not* use the
427
+ subscript callback of the interface. As exported variables may not
428
+ start with double underscores (which the parser asserts) this is not a
429
+ problem for regular Jinja code, but if this node is used in an extension
430
+ extra care must be taken.
431
+
432
+ The list of names may contain tuples if aliases are wanted.
433
+ """
434
+
435
+ fields = ("template", "names", "with_context")
436
+ template: "Expr"
437
+ names: t.List[t.Union[str, t.Tuple[str, str]]]
438
+ with_context: bool
439
+
440
+
441
+ class ExprStmt(Stmt):
442
+ """A statement that evaluates an expression and discards the result."""
443
+
444
+ fields = ("node",)
445
+ node: Node
446
+
447
+
448
+ class Assign(Stmt):
449
+ """Assigns an expression to a target."""
450
+
451
+ fields = ("target", "node")
452
+ target: "Expr"
453
+ node: Node
454
+
455
+
456
+ class AssignBlock(Stmt):
457
+ """Assigns a block to a target."""
458
+
459
+ fields = ("target", "filter", "body")
460
+ target: "Expr"
461
+ filter: t.Optional["Filter"]
462
+ body: t.List[Node]
463
+
464
+
465
+ class Expr(Node):
466
+ """Baseclass for all expressions."""
467
+
468
+ abstract = True
469
+
470
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
471
+ """Return the value of the expression as constant or raise
472
+ :exc:`Impossible` if this was not possible.
473
+
474
+ An :class:`EvalContext` can be provided, if none is given
475
+ a default context is created which requires the nodes to have
476
+ an attached environment.
477
+
478
+ .. versionchanged:: 2.4
479
+ the `eval_ctx` parameter was added.
480
+ """
481
+ raise Impossible()
482
+
483
+ def can_assign(self) -> bool:
484
+ """Check if it's possible to assign something to this node."""
485
+ return False
486
+
487
+
488
+ class BinExpr(Expr):
489
+ """Baseclass for all binary expressions."""
490
+
491
+ fields = ("left", "right")
492
+ left: Expr
493
+ right: Expr
494
+ operator: str
495
+ abstract = True
496
+
497
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
498
+ eval_ctx = get_eval_context(self, eval_ctx)
499
+
500
+ # intercepted operators cannot be folded at compile time
501
+ if (
502
+ eval_ctx.environment.sandboxed
503
+ and self.operator in eval_ctx.environment.intercepted_binops # type: ignore
504
+ ):
505
+ raise Impossible()
506
+ f = _binop_to_func[self.operator]
507
+ try:
508
+ return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
509
+ except Exception as e:
510
+ raise Impossible() from e
511
+
512
+
513
+ class UnaryExpr(Expr):
514
+ """Baseclass for all unary expressions."""
515
+
516
+ fields = ("node",)
517
+ node: Expr
518
+ operator: str
519
+ abstract = True
520
+
521
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
522
+ eval_ctx = get_eval_context(self, eval_ctx)
523
+
524
+ # intercepted operators cannot be folded at compile time
525
+ if (
526
+ eval_ctx.environment.sandboxed
527
+ and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
528
+ ):
529
+ raise Impossible()
530
+ f = _uaop_to_func[self.operator]
531
+ try:
532
+ return f(self.node.as_const(eval_ctx))
533
+ except Exception as e:
534
+ raise Impossible() from e
535
+
536
+
537
+ class Name(Expr):
538
+ """Looks up a name or stores a value in a name.
539
+ The `ctx` of the node can be one of the following values:
540
+
541
+ - `store`: store a value in the name
542
+ - `load`: load that name
543
+ - `param`: like `store` but if the name was defined as function parameter.
544
+ """
545
+
546
+ fields = ("name", "ctx")
547
+ name: str
548
+ ctx: str
549
+
550
+ def can_assign(self) -> bool:
551
+ return self.name not in {"true", "false", "none", "True", "False", "None"}
552
+
553
+
554
+ class NSRef(Expr):
555
+ """Reference to a namespace value assignment"""
556
+
557
+ fields = ("name", "attr")
558
+ name: str
559
+ attr: str
560
+
561
+ def can_assign(self) -> bool:
562
+ # We don't need any special checks here; NSRef assignments have a
563
+ # runtime check to ensure the target is a namespace object which will
564
+ # have been checked already as it is created using a normal assignment
565
+ # which goes through a `Name` node.
566
+ return True
567
+
568
+
569
+ class Literal(Expr):
570
+ """Baseclass for literals."""
571
+
572
+ abstract = True
573
+
574
+
575
+ class Const(Literal):
576
+ """All constant values. The parser will return this node for simple
577
+ constants such as ``42`` or ``"foo"`` but it can be used to store more
578
+ complex values such as lists too. Only constants with a safe
579
+ representation (objects where ``eval(repr(x)) == x`` is true).
580
+ """
581
+
582
+ fields = ("value",)
583
+ value: t.Any
584
+
585
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
586
+ return self.value
587
+
588
+ @classmethod
589
+ def from_untrusted(
590
+ cls,
591
+ value: t.Any,
592
+ lineno: t.Optional[int] = None,
593
+ environment: "t.Optional[Environment]" = None,
594
+ ) -> "Const":
595
+ """Return a const object if the value is representable as
596
+ constant value in the generated code, otherwise it will raise
597
+ an `Impossible` exception.
598
+ """
599
+ from .compiler import has_safe_repr
600
+
601
+ if not has_safe_repr(value):
602
+ raise Impossible()
603
+ return cls(value, lineno=lineno, environment=environment)
604
+
605
+
606
+ class TemplateData(Literal):
607
+ """A constant template string."""
608
+
609
+ fields = ("data",)
610
+ data: str
611
+
612
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
613
+ eval_ctx = get_eval_context(self, eval_ctx)
614
+ if eval_ctx.volatile:
615
+ raise Impossible()
616
+ if eval_ctx.autoescape:
617
+ return Markup(self.data)
618
+ return self.data
619
+
620
+
621
+ class Tuple(Literal):
622
+ """For loop unpacking and some other things like multiple arguments
623
+ for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
624
+ is used for loading the names or storing.
625
+ """
626
+
627
+ fields = ("items", "ctx")
628
+ items: t.List[Expr]
629
+ ctx: str
630
+
631
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[t.Any, ...]:
632
+ eval_ctx = get_eval_context(self, eval_ctx)
633
+ return tuple(x.as_const(eval_ctx) for x in self.items)
634
+
635
+ def can_assign(self) -> bool:
636
+ for item in self.items:
637
+ if not item.can_assign():
638
+ return False
639
+ return True
640
+
641
+
642
+ class List(Literal):
643
+ """Any list literal such as ``[1, 2, 3]``"""
644
+
645
+ fields = ("items",)
646
+ items: t.List[Expr]
647
+
648
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]:
649
+ eval_ctx = get_eval_context(self, eval_ctx)
650
+ return [x.as_const(eval_ctx) for x in self.items]
651
+
652
+
653
+ class Dict(Literal):
654
+ """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
655
+ :class:`Pair` nodes.
656
+ """
657
+
658
+ fields = ("items",)
659
+ items: t.List["Pair"]
660
+
661
+ def as_const(
662
+ self, eval_ctx: t.Optional[EvalContext] = None
663
+ ) -> t.Dict[t.Any, t.Any]:
664
+ eval_ctx = get_eval_context(self, eval_ctx)
665
+ return dict(x.as_const(eval_ctx) for x in self.items)
666
+
667
+
668
+ class Pair(Helper):
669
+ """A key, value pair for dicts."""
670
+
671
+ fields = ("key", "value")
672
+ key: Expr
673
+ value: Expr
674
+
675
+ def as_const(
676
+ self, eval_ctx: t.Optional[EvalContext] = None
677
+ ) -> t.Tuple[t.Any, t.Any]:
678
+ eval_ctx = get_eval_context(self, eval_ctx)
679
+ return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
680
+
681
+
682
+ class Keyword(Helper):
683
+ """A key, value pair for keyword arguments where key is a string."""
684
+
685
+ fields = ("key", "value")
686
+ key: str
687
+ value: Expr
688
+
689
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:
690
+ eval_ctx = get_eval_context(self, eval_ctx)
691
+ return self.key, self.value.as_const(eval_ctx)
692
+
693
+
694
+ class CondExpr(Expr):
695
+ """A conditional expression (inline if expression). (``{{
696
+ foo if bar else baz }}``)
697
+ """
698
+
699
+ fields = ("test", "expr1", "expr2")
700
+ test: Expr
701
+ expr1: Expr
702
+ expr2: t.Optional[Expr]
703
+
704
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
705
+ eval_ctx = get_eval_context(self, eval_ctx)
706
+ if self.test.as_const(eval_ctx):
707
+ return self.expr1.as_const(eval_ctx)
708
+
709
+ # if we evaluate to an undefined object, we better do that at runtime
710
+ if self.expr2 is None:
711
+ raise Impossible()
712
+
713
+ return self.expr2.as_const(eval_ctx)
714
+
715
+
716
+ def args_as_const(
717
+ node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
718
+ ) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
719
+ args = [x.as_const(eval_ctx) for x in node.args]
720
+ kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)
721
+
722
+ if node.dyn_args is not None:
723
+ try:
724
+ args.extend(node.dyn_args.as_const(eval_ctx))
725
+ except Exception as e:
726
+ raise Impossible() from e
727
+
728
+ if node.dyn_kwargs is not None:
729
+ try:
730
+ kwargs.update(node.dyn_kwargs.as_const(eval_ctx))
731
+ except Exception as e:
732
+ raise Impossible() from e
733
+
734
+ return args, kwargs
735
+
736
+
737
+ class _FilterTestCommon(Expr):
738
+ fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")
739
+ node: Expr
740
+ name: str
741
+ args: t.List[Expr]
742
+ kwargs: t.List[Pair]
743
+ dyn_args: t.Optional[Expr]
744
+ dyn_kwargs: t.Optional[Expr]
745
+ abstract = True
746
+ _is_filter = True
747
+
748
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
749
+ eval_ctx = get_eval_context(self, eval_ctx)
750
+
751
+ if eval_ctx.volatile:
752
+ raise Impossible()
753
+
754
+ if self._is_filter:
755
+ env_map = eval_ctx.environment.filters
756
+ else:
757
+ env_map = eval_ctx.environment.tests
758
+
759
+ func = env_map.get(self.name)
760
+ pass_arg = _PassArg.from_obj(func) # type: ignore
761
+
762
+ if func is None or pass_arg is _PassArg.context:
763
+ raise Impossible()
764
+
765
+ if eval_ctx.environment.is_async and (
766
+ getattr(func, "jinja_async_variant", False) is True
767
+ or inspect.iscoroutinefunction(func)
768
+ ):
769
+ raise Impossible()
770
+
771
+ args, kwargs = args_as_const(self, eval_ctx)
772
+ args.insert(0, self.node.as_const(eval_ctx))
773
+
774
+ if pass_arg is _PassArg.eval_context:
775
+ args.insert(0, eval_ctx)
776
+ elif pass_arg is _PassArg.environment:
777
+ args.insert(0, eval_ctx.environment)
778
+
779
+ try:
780
+ return func(*args, **kwargs)
781
+ except Exception as e:
782
+ raise Impossible() from e
783
+
784
+
785
+ class Filter(_FilterTestCommon):
786
+ """Apply a filter to an expression. ``name`` is the name of the
787
+ filter, the other fields are the same as :class:`Call`.
788
+
789
+ If ``node`` is ``None``, the filter is being used in a filter block
790
+ and is applied to the content of the block.
791
+ """
792
+
793
+ node: t.Optional[Expr] # type: ignore
794
+
795
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
796
+ if self.node is None:
797
+ raise Impossible()
798
+
799
+ return super().as_const(eval_ctx=eval_ctx)
800
+
801
+
802
+ class Test(_FilterTestCommon):
803
+ """Apply a test to an expression. ``name`` is the name of the test,
804
+ the other field are the same as :class:`Call`.
805
+
806
+ .. versionchanged:: 3.0
807
+ ``as_const`` shares the same logic for filters and tests. Tests
808
+ check for volatile, async, and ``@pass_context`` etc.
809
+ decorators.
810
+ """
811
+
812
+ _is_filter = False
813
+
814
+
815
+ class Call(Expr):
816
+ """Calls an expression. `args` is a list of arguments, `kwargs` a list
817
+ of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
818
+ and `dyn_kwargs` has to be either `None` or a node that is used as
819
+ node for dynamic positional (``*args``) or keyword (``**kwargs``)
820
+ arguments.
821
+ """
822
+
823
+ fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")
824
+ node: Expr
825
+ args: t.List[Expr]
826
+ kwargs: t.List[Keyword]
827
+ dyn_args: t.Optional[Expr]
828
+ dyn_kwargs: t.Optional[Expr]
829
+
830
+
831
+ class Getitem(Expr):
832
+ """Get an attribute or item from an expression and prefer the item."""
833
+
834
+ fields = ("node", "arg", "ctx")
835
+ node: Expr
836
+ arg: Expr
837
+ ctx: str
838
+
839
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
840
+ if self.ctx != "load":
841
+ raise Impossible()
842
+
843
+ eval_ctx = get_eval_context(self, eval_ctx)
844
+
845
+ try:
846
+ return eval_ctx.environment.getitem(
847
+ self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
848
+ )
849
+ except Exception as e:
850
+ raise Impossible() from e
851
+
852
+
853
+ class Getattr(Expr):
854
+ """Get an attribute or item from an expression that is a ascii-only
855
+ bytestring and prefer the attribute.
856
+ """
857
+
858
+ fields = ("node", "attr", "ctx")
859
+ node: Expr
860
+ attr: str
861
+ ctx: str
862
+
863
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
864
+ if self.ctx != "load":
865
+ raise Impossible()
866
+
867
+ eval_ctx = get_eval_context(self, eval_ctx)
868
+
869
+ try:
870
+ return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)
871
+ except Exception as e:
872
+ raise Impossible() from e
873
+
874
+
875
+ class Slice(Expr):
876
+ """Represents a slice object. This must only be used as argument for
877
+ :class:`Subscript`.
878
+ """
879
+
880
+ fields = ("start", "stop", "step")
881
+ start: t.Optional[Expr]
882
+ stop: t.Optional[Expr]
883
+ step: t.Optional[Expr]
884
+
885
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:
886
+ eval_ctx = get_eval_context(self, eval_ctx)
887
+
888
+ def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:
889
+ if obj is None:
890
+ return None
891
+ return obj.as_const(eval_ctx)
892
+
893
+ return slice(const(self.start), const(self.stop), const(self.step))
894
+
895
+
896
+ class Concat(Expr):
897
+ """Concatenates the list of expressions provided after converting
898
+ them to strings.
899
+ """
900
+
901
+ fields = ("nodes",)
902
+ nodes: t.List[Expr]
903
+
904
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
905
+ eval_ctx = get_eval_context(self, eval_ctx)
906
+ return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)
907
+
908
+
909
+ class Compare(Expr):
910
+ """Compares an expression with some other expressions. `ops` must be a
911
+ list of :class:`Operand`\\s.
912
+ """
913
+
914
+ fields = ("expr", "ops")
915
+ expr: Expr
916
+ ops: t.List["Operand"]
917
+
918
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
919
+ eval_ctx = get_eval_context(self, eval_ctx)
920
+ result = value = self.expr.as_const(eval_ctx)
921
+
922
+ try:
923
+ for op in self.ops:
924
+ new_value = op.expr.as_const(eval_ctx)
925
+ result = _cmpop_to_func[op.op](value, new_value)
926
+
927
+ if not result:
928
+ return False
929
+
930
+ value = new_value
931
+ except Exception as e:
932
+ raise Impossible() from e
933
+
934
+ return result
935
+
936
+
937
+ class Operand(Helper):
938
+ """Holds an operator and an expression."""
939
+
940
+ fields = ("op", "expr")
941
+ op: str
942
+ expr: Expr
943
+
944
+
945
+ class Mul(BinExpr):
946
+ """Multiplies the left with the right node."""
947
+
948
+ operator = "*"
949
+
950
+
951
+ class Div(BinExpr):
952
+ """Divides the left by the right node."""
953
+
954
+ operator = "/"
955
+
956
+
957
+ class FloorDiv(BinExpr):
958
+ """Divides the left by the right node and converts the
959
+ result into an integer by truncating.
960
+ """
961
+
962
+ operator = "//"
963
+
964
+
965
+ class Add(BinExpr):
966
+ """Add the left to the right node."""
967
+
968
+ operator = "+"
969
+
970
+
971
+ class Sub(BinExpr):
972
+ """Subtract the right from the left node."""
973
+
974
+ operator = "-"
975
+
976
+
977
+ class Mod(BinExpr):
978
+ """Left modulo right."""
979
+
980
+ operator = "%"
981
+
982
+
983
+ class Pow(BinExpr):
984
+ """Left to the power of right."""
985
+
986
+ operator = "**"
987
+
988
+
989
+ class And(BinExpr):
990
+ """Short circuited AND."""
991
+
992
+ operator = "and"
993
+
994
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
995
+ eval_ctx = get_eval_context(self, eval_ctx)
996
+ return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
997
+
998
+
999
+ class Or(BinExpr):
1000
+ """Short circuited OR."""
1001
+
1002
+ operator = "or"
1003
+
1004
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
1005
+ eval_ctx = get_eval_context(self, eval_ctx)
1006
+ return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
1007
+
1008
+
1009
+ class Not(UnaryExpr):
1010
+ """Negate the expression."""
1011
+
1012
+ operator = "not"
1013
+
1014
+
1015
+ class Neg(UnaryExpr):
1016
+ """Make the expression negative."""
1017
+
1018
+ operator = "-"
1019
+
1020
+
1021
+ class Pos(UnaryExpr):
1022
+ """Make the expression positive (noop for most expressions)"""
1023
+
1024
+ operator = "+"
1025
+
1026
+
1027
+ # Helpers for extensions
1028
+
1029
+
1030
+ class EnvironmentAttribute(Expr):
1031
+ """Loads an attribute from the environment object. This is useful for
1032
+ extensions that want to call a callback stored on the environment.
1033
+ """
1034
+
1035
+ fields = ("name",)
1036
+ name: str
1037
+
1038
+
1039
+ class ExtensionAttribute(Expr):
1040
+ """Returns the attribute of an extension bound to the environment.
1041
+ The identifier is the identifier of the :class:`Extension`.
1042
+
1043
+ This node is usually constructed by calling the
1044
+ :meth:`~jinja2.ext.Extension.attr` method on an extension.
1045
+ """
1046
+
1047
+ fields = ("identifier", "name")
1048
+ identifier: str
1049
+ name: str
1050
+
1051
+
1052
+ class ImportedName(Expr):
1053
+ """If created with an import name the import name is returned on node
1054
+ access. For example ``ImportedName('cgi.escape')`` returns the `escape`
1055
+ function from the cgi module on evaluation. Imports are optimized by the
1056
+ compiler so there is no need to assign them to local variables.
1057
+ """
1058
+
1059
+ fields = ("importname",)
1060
+ importname: str
1061
+
1062
+
1063
+ class InternalName(Expr):
1064
+ """An internal name in the compiler. You cannot create these nodes
1065
+ yourself but the parser provides a
1066
+ :meth:`~jinja2.parser.Parser.free_identifier` method that creates
1067
+ a new identifier for you. This identifier is not available from the
1068
+ template and is not treated specially by the compiler.
1069
+ """
1070
+
1071
+ fields = ("name",)
1072
+ name: str
1073
+
1074
+ def __init__(self) -> None:
1075
+ raise TypeError(
1076
+ "Can't create internal names. Use the "
1077
+ "`free_identifier` method on a parser."
1078
+ )
1079
+
1080
+
1081
+ class MarkSafe(Expr):
1082
+ """Mark the wrapped expression as safe (wrap it as `Markup`)."""
1083
+
1084
+ fields = ("expr",)
1085
+ expr: Expr
1086
+
1087
+ def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:
1088
+ eval_ctx = get_eval_context(self, eval_ctx)
1089
+ return Markup(self.expr.as_const(eval_ctx))
1090
+
1091
+
1092
+ class MarkSafeIfAutoescape(Expr):
1093
+ """Mark the wrapped expression as safe (wrap it as `Markup`) but
1094
+ only if autoescaping is active.
1095
+
1096
+ .. versionadded:: 2.5
1097
+ """
1098
+
1099
+ fields = ("expr",)
1100
+ expr: Expr
1101
+
1102
+ def as_const(
1103
+ self, eval_ctx: t.Optional[EvalContext] = None
1104
+ ) -> t.Union[Markup, t.Any]:
1105
+ eval_ctx = get_eval_context(self, eval_ctx)
1106
+ if eval_ctx.volatile:
1107
+ raise Impossible()
1108
+ expr = self.expr.as_const(eval_ctx)
1109
+ if eval_ctx.autoescape:
1110
+ return Markup(expr)
1111
+ return expr
1112
+
1113
+
1114
+ class ContextReference(Expr):
1115
+ """Returns the current template context. It can be used like a
1116
+ :class:`Name` node, with a ``'load'`` ctx and will return the
1117
+ current :class:`~jinja2.runtime.Context` object.
1118
+
1119
+ Here an example that assigns the current template name to a
1120
+ variable named `foo`::
1121
+
1122
+ Assign(Name('foo', ctx='store'),
1123
+ Getattr(ContextReference(), 'name'))
1124
+
1125
+ This is basically equivalent to using the
1126
+ :func:`~jinja2.pass_context` decorator when using the high-level
1127
+ API, which causes a reference to the context to be passed as the
1128
+ first argument to a function.
1129
+ """
1130
+
1131
+
1132
+ class DerivedContextReference(Expr):
1133
+ """Return the current template context including locals. Behaves
1134
+ exactly like :class:`ContextReference`, but includes local
1135
+ variables, such as from a ``for`` loop.
1136
+
1137
+ .. versionadded:: 2.11
1138
+ """
1139
+
1140
+
1141
+ class Continue(Stmt):
1142
+ """Continue a loop."""
1143
+
1144
+
1145
+ class Break(Stmt):
1146
+ """Break a loop."""
1147
+
1148
+
1149
+ class Scope(Stmt):
1150
+ """An artificial scope."""
1151
+
1152
+ fields = ("body",)
1153
+ body: t.List[Node]
1154
+
1155
+
1156
+ class OverlayScope(Stmt):
1157
+ """An overlay scope for extensions. This is a largely unoptimized scope
1158
+ that however can be used to introduce completely arbitrary variables into
1159
+ a sub scope from a dictionary or dictionary like object. The `context`
1160
+ field has to evaluate to a dictionary object.
1161
+
1162
+ Example usage::
1163
+
1164
+ OverlayScope(context=self.call_method('get_context'),
1165
+ body=[...])
1166
+
1167
+ .. versionadded:: 2.10
1168
+ """
1169
+
1170
+ fields = ("context", "body")
1171
+ context: Expr
1172
+ body: t.List[Node]
1173
+
1174
+
1175
+ class EvalContextModifier(Stmt):
1176
+ """Modifies the eval context. For each option that should be modified,
1177
+ a :class:`Keyword` has to be added to the :attr:`options` list.
1178
+
1179
+ Example to change the `autoescape` setting::
1180
+
1181
+ EvalContextModifier(options=[Keyword('autoescape', Const(True))])
1182
+ """
1183
+
1184
+ fields = ("options",)
1185
+ options: t.List[Keyword]
1186
+
1187
+
1188
+ class ScopedEvalContextModifier(EvalContextModifier):
1189
+ """Modifies the eval context and reverts it later. Works exactly like
1190
+ :class:`EvalContextModifier` but will only modify the
1191
+ :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
1192
+ """
1193
+
1194
+ fields = ("body",)
1195
+ body: t.List[Node]
1196
+
1197
+
1198
+ # make sure nobody creates custom nodes
1199
+ def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":
1200
+ raise TypeError("can't create custom node types")
1201
+
1202
+
1203
+ NodeType.__new__ = staticmethod(_failing_new) # type: ignore
1204
+ del _failing_new
shared/package-files/8b/8b7eb84a05022d26118d0b32ca0bd8d40ae311a3b9b8b8a9dc7c94f91ef368ba/blob ADDED
Binary file (200 Bytes). View file
 
shared/package-files/8b/8b813bd8c270347eb5ec038972ee3150da92249c11df6840e915e92c1926855b/blob ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor special_i1(const at::Tensor & self);
21
+ TORCH_API at::Tensor & special_i1_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & special_i1_outf(const at::Tensor & self, at::Tensor & out);
23
+
24
+ } // namespace cpu
25
+ } // namespace at
shared/package-files/8b/8b82530cc91901d5591a65b20eadef3769e711739c5a4e18e8c00302ea3824c3/blob ADDED
The diff for this file is too large to render. See raw diff
 
shared/package-files/8b/8b8318b8974f0efa80f9a0f97da51096db1cbca83be1effcb840b479e6cafcf0/blob ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.utils.data.datapipes.utils.common import _check_unpickable_fn
2
+ from typing import Callable, TypeVar
3
+ from torch.utils.data.datapipes._decorator import functional_datapipe
4
+ from torch.utils.data.datapipes.datapipe import MapDataPipe
5
+
6
+ __all__ = ["MapperMapDataPipe", "default_fn"]
7
+
8
+ T_co = TypeVar('T_co', covariant=True)
9
+
10
+
11
+ # Default function to return each item directly
12
+ # In order to keep datapipe picklable, eliminates the usage
13
+ # of python lambda function
14
+ def default_fn(data):
15
+ return data
16
+
17
+
18
+ @functional_datapipe('map')
19
+ class MapperMapDataPipe(MapDataPipe[T_co]):
20
+ r"""
21
+ Apply the input function over each item from the source DataPipe (functional name: ``map``).
22
+
23
+ The function can be any regular Python function or partial object. Lambda
24
+ function is not recommended as it is not supported by pickle.
25
+
26
+ Args:
27
+ datapipe: Source MapDataPipe
28
+ fn: Function being applied to each item
29
+
30
+ Example:
31
+ >>> # xdoctest: +SKIP
32
+ >>> from torchdata.datapipes.map import SequenceWrapper, Mapper
33
+ >>> def add_one(x):
34
+ ... return x + 1
35
+ >>> dp = SequenceWrapper(range(10))
36
+ >>> map_dp_1 = dp.map(add_one)
37
+ >>> list(map_dp_1)
38
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
39
+ >>> map_dp_2 = Mapper(dp, lambda x: x + 1)
40
+ >>> list(map_dp_2)
41
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
42
+ """
43
+
44
+ datapipe: MapDataPipe
45
+ fn: Callable
46
+
47
+ def __init__(
48
+ self,
49
+ datapipe: MapDataPipe,
50
+ fn: Callable = default_fn,
51
+ ) -> None:
52
+ super().__init__()
53
+ self.datapipe = datapipe
54
+ _check_unpickable_fn(fn)
55
+ self.fn = fn # type: ignore[assignment]
56
+
57
+ def __len__(self) -> int:
58
+ return len(self.datapipe)
59
+
60
+ def __getitem__(self, index) -> T_co:
61
+ return self.fn(self.datapipe[index])
shared/package-files/8b/8b85846791ab2c8a5463c83a5be3c043e2570d7448434d41398969ed47e3e6f2/blob ADDED
Binary file (114 Bytes). View file
 
shared/package-files/8b/8b8d83314c282428810d5111dc76fad3b4f773ab535f425c1cd951483f735c50/blob ADDED
The diff for this file is too large to render. See raw diff
 
shared/package-files/8b/8b90a1c3f99957578f8c2af8bc0faa53712eb21108af45f6802dce7e258183cb/blob ADDED
Binary file (1.75 kB). View file
 
shared/package-files/8b/8b90c2623ff71532b5856bc5736ec3488566bdcf66628a9bad443b4783bc23ed/blob ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*quarterly, seasonally adjusted, U.S.
2
+ fixed investment (y1), change in business inventories (y2),
3
+ 1947Q1-1972Q4;
4
+ source: U.S. Department of Commerce, Bureau of Economic Analysis,
5
+ The National Income and Product Accounts of the United States, 1929-1974
6
+ */
7
+
8
+ <1947 Q1>
9
+ y1 y2
10
+ 69.6 0.1
11
+ 67.6 -0.9
12
+ 69.5 -2.9
13
+ 74.7 2.7
14
+ 77.1 4.1
15
+ 77.4 5.6
16
+ 76.6 6.9
17
+ 76.1 5.3
18
+ 71.8 -0.3
19
+ 68.9 -7.1
20
+ 68.5 -2.5
21
+ 70.6 -7.7
22
+ 75.4 4.4
23
+ 82.3 7.7
24
+ 88.2 8.0
25
+ 86.9 22.1
26
+ 83.4 13.4
27
+ 80.3 19.9
28
+ 79.4 14.6
29
+ 78.6 7.0
30
+ 79.3 7.3
31
+ 80.3 -2.7
32
+ 75.3 5.4
33
+ 80.6 7.2
34
+ 83.9 3.9
35
+ 84.2 5.1
36
+ 84.4 1.9
37
+ 83.8 -5.0
38
+ 82.8 -3.4
39
+ 84.1 -4.1
40
+ 87.0 -2.7
41
+ 88.5 1.5
42
+ 92.1 5.9
43
+ 96.1 8.0
44
+ 98.3 7.8
45
+ 98.8 9.2
46
+ 96.6 7.5
47
+ 97.4 5.5
48
+ 97.6 4.9
49
+ 96.6 5.4
50
+ 96.2 2.5
51
+ 95.3 2.9
52
+ 96.4 3.7
53
+ 94.9 -3.0
54
+ 90.0 -6.8
55
+ 87.2 -6.2
56
+ 88.0 0.3
57
+ 93.0 5.3
58
+ 98.3 5.0
59
+ 101.6 13.0
60
+ 102.6 -0.4
61
+ 101.4 8.2
62
+ 104.9 13.5
63
+ 101.8 4.9
64
+ 98.8 3.0
65
+ 98.6 -3.9
66
+ 97.7 -3.8
67
+ 99.2 1.9
68
+ 101.3 6.6
69
+ 104.6 6.7
70
+ 106.1 10.6
71
+ 109.9 9.2
72
+ 111.1 8.0
73
+ 110.1 4.7
74
+ 110.7 7.6
75
+ 116.0 7.0
76
+ 118.5 9.3
77
+ 122.0 7.1
78
+ 124.0 6.1
79
+ 124.0 8.0
80
+ 124.9 7.3
81
+ 126.4 7.9
82
+ 133.4 13.4
83
+ 137.9 10.6
84
+ 140.1 12.4
85
+ 143.8 8.8
86
+ 147.5 13.5
87
+ 146.2 17.8
88
+ 145.0 15.1
89
+ 139.7 20.5
90
+ 136.4 14.6
91
+ 139.6 7.5
92
+ 141.1 12.2
93
+ 145.5 13.8
94
+ 148.9 6.3
95
+ 148.9 11.8
96
+ 150.7 9.2
97
+ 155.0 7.6
98
+ 159.1 9.8
99
+ 158.4 12.2
100
+ 158.1 13.4
101
+ 154.3 6.8
102
+ 151.8 2.9
103
+ 150.0 4.8
104
+ 150.4 6.3
105
+ 149.5 3.3
106
+ 154.3 7.9
107
+ 158.4 10.0
108
+ 162.1 5.0
109
+ 166.0 3.7
110
+ 174.3 4.8
111
+ 176.1 10.1
112
+ 178.2 12.1
113
+ 186.7 10.8
shared/package-files/8b/8b9121a163d486ee2495add7bb866f5c5d6554b3e223a660e21ea8f236a26a6a/blob ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from numpy.core import _dtype_ctypes
2
+
3
+ _globals = globals()
4
+
5
+ for item in _dtype_ctypes.__dir__():
6
+ _globals[item] = getattr(_dtype_ctypes, item)
shared/package-files/8b/8b9262fc79b943a382d24a96dab8a16757398cd7d7ea33766fd7e5ed6382a645/blob ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ build-backend = 'mesonpy'
3
+ requires = [
4
+ 'meson-python',
5
+ "cython>=3.0.13,<4", # Sync with CYTHON_MIN_VER in setup
6
+ "numpy>=2.0.0,<3",
7
+ "scipy>=1.13,<2",
8
+ "setuptools_scm>=9.2.0,<10",
9
+ ]
10
+
11
+ [project]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Environment :: Console",
15
+ "Programming Language :: Cython",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Programming Language :: Python :: 3.14",
21
+ "Operating System :: OS Independent",
22
+ "Intended Audience :: End Users/Desktop",
23
+ "Intended Audience :: Developers",
24
+ "Intended Audience :: Science/Research",
25
+ "Natural Language :: English",
26
+ "Topic :: Office/Business :: Financial",
27
+ "Topic :: Scientific/Engineering",
28
+ ]
29
+ description = "Statistical computations and models for Python"
30
+ dynamic = ["version"]
31
+ keywords = [
32
+ "statistics",
33
+ "econometrics",
34
+ "time series",
35
+ "regression",
36
+ "anova",
37
+ "statistical tests",
38
+ "linear models",
39
+ "generalized linear models",
40
+ "discrete choice models",
41
+ "robust linear models",
42
+ "mixed linear models",
43
+ "time series analysis",
44
+ "state space models",
45
+ "vector autoregression",
46
+ "volatility modeling",
47
+ "unit root tests",
48
+ "cointegration tests",
49
+ "nonparametric methods",
50
+ "multivariate statistics"
51
+ ]
52
+ license = "BSD-3-Clause"
53
+ license-files = [ "LICENSE.txt" ]
54
+ maintainers = [
55
+ { name = "statsmodels Developers", email = "pystatsmodels@googlegroups.com" },
56
+ ]
57
+ name = "statsmodels"
58
+ dependencies = [
59
+ "numpy>=1.23.5,<3", # released March 2022
60
+ "scipy>=1.8,!=1.9.2", # released Feb 2022, 1.9.2 blocked due to bug
61
+ "pandas>=1.4,!=2.1.0", # released Feb 2022, 2.1.0 blocked due to bug
62
+ "patsy>=0.5.6", # released December 2023
63
+ "packaging>=21.3", # released Nov 2021
64
+ "formulaic>=1.1.0", # released December 2024
65
+ ]
66
+ readme = "README.md"
67
+ requires-python = ">=3.10"
68
+
69
+ [project.optional-dependencies]
70
+ test = [
71
+ # test
72
+ "pytest>=8.4.1,<10",
73
+ "pytest-randomly",
74
+ "pytest-run-parallel",
75
+ "pytest-xdist",
76
+ "pytest-cov",
77
+ "coverage[toml]",
78
+ "meson",
79
+ 'ninja; sys_platform != "emscripten"',
80
+ ]
81
+ doc = [
82
+ # Requirements for doc build, in addition to requirements.txt
83
+ "sphinx",
84
+ # Avoid warnings which break Sphinx by pinning pandas
85
+ "pandas>=2.2.2,!=2.1.0",
86
+ "pydata-sphinx-theme",
87
+ "jupyter",
88
+ "notebook",
89
+ "nbsphinx",
90
+ "nbconvert",
91
+ "pyyaml",
92
+ "pandas-datareader",
93
+ "simplegeneric",
94
+ "seaborn",
95
+ "numpydoc",
96
+ # "theano-pymc; os_name != 'nt'", # disabled because it is not compatible with move recent Python version
97
+ "pymc; os_name != 'nt'",
98
+ "arviz; os_name != 'nt'",
99
+ "jinja2",
100
+ "pickleshare",
101
+ "pytest>=8.4.1,<10",
102
+ ]
103
+ dev = [
104
+ # build
105
+ "cython>=3.0.10,<4",
106
+ "setuptools_scm~=9.0",
107
+ "meson-python>=0.18.0",
108
+ "meson",
109
+ "ninja",
110
+ # run
111
+ "matplotlib>=3",
112
+ "colorama",
113
+ "joblib",
114
+ # Remove due to failures on azure CI
115
+ # cvxopt; os_name != "win32"
116
+ # Pin on Win32
117
+ "pywinpty; os_name == 'nt'",
118
+ # code quality
119
+ "ruff",
120
+ ]
121
+ polars = [
122
+ # Polars support
123
+ "polars>=1.0.0",
124
+ ]
125
+
126
+ [project.urls]
127
+ homepage = "https://www.statsmodels.org"
128
+ documentation = "https://www.statsmodels.org/stable/index.html"
129
+ repository = "https://github.com/statsmodels/statsmodels"
130
+ changelog = "https://bashtage.github.io/arch/changes.html"
131
+ bugtracker = "https://github.com/statsmodels/statsmodels/issues"
132
+
133
+ [tool.meson-python.args]
134
+ setup = ['--vsenv']
135
+
136
+ [tool.ruff]
137
+ line-length = 88
138
+ fix = false
139
+ # Matches requires-python (>=3.10) and [tool.black]'s target-version below;
140
+ # also affects which pyupgrade (UP) rules apply.
141
+ target-version = "py310"
142
+ # archive/ is explicitly documented (archive/README) as deprecated, no
143
+ # longer maintained legacy code; excluded so it's not linted as if it
144
+ # were part of the active codebase.
145
+ extend-exclude = ["archive", "examples/python"]
146
+
147
+ [tool.ruff.lint]
148
+ typing-modules = ["statsmodels.compat.python", "compat.python"]
149
+
150
+ select = [
151
+ # pyflakes
152
+ "F",
153
+ # pycodestyle
154
+ "E", "W",
155
+ # flake8-2020
156
+ "YTT",
157
+ # flake8-bugbear
158
+ "B",
159
+ # flake8-quotes
160
+ "Q",
161
+ # flake8-debugger
162
+ "T10",
163
+ # flake8-gettext
164
+ "INT",
165
+ # pylint
166
+ "PL",
167
+ # flake8-pytest-style
168
+ "PT",
169
+ # misc lints
170
+ "PIE",
171
+ # flake8-pyi
172
+ "PYI",
173
+ # tidy imports
174
+ "TID",
175
+ # implicit string concatenation
176
+ "ISC",
177
+ # flake8-type-checking
178
+ "TC",
179
+ # comprehensions
180
+ "C4",
181
+ # pygrep-hooks
182
+ "PGH",
183
+ # Ruff-specific rules
184
+ "RUF",
185
+ # Perflint
186
+ "PERF",
187
+ # flynt
188
+ "FLY",
189
+ # flake8-future-annotations
190
+ "FA",
191
+ # flake8-import-conventions
192
+ "ICN",
193
+ # flake8-slots
194
+ "SLOT",
195
+ # flake8-raise
196
+ "RSE",
197
+ # flake8-async
198
+ "ASYNC",
199
+ # flake8-executable
200
+ "EXE",
201
+ # flake8-logging-format
202
+ "G",
203
+ # flake8-logging
204
+ "LOG",
205
+ # refurb
206
+ "FURB",
207
+ # flake8-bandit
208
+ "S",
209
+ # isort
210
+ "I",
211
+ # pyupgrade
212
+ "UP",
213
+ # flake8-builtins
214
+ "A",
215
+ # flake8-airflow (this project has no Airflow usage, so this and the
216
+ # frameworks below are all currently clean; enabled for completeness)
217
+ "AIR",
218
+ # flake8-commas: only COM812/COM819 fail (already in the never-enable
219
+ # list above), COM818 is otherwise clean
220
+ "COM",
221
+ # flake8-django (no Django usage, currently clean)
222
+ "DJ",
223
+ # flake8-datetimez
224
+ "DTZ",
225
+ # flake8-fastapi (no FastAPI usage, currently clean)
226
+ "FAST",
227
+ # pandas-vet
228
+ "PD",
229
+ # flake8-use-pathlib: os.path is used throughout, but fewer than half
230
+ # the rule's codes actually fire here, so the category is selected with
231
+ # the failing codes carved out below (see ignore list) rather than
232
+ # listing the larger set of passing codes individually. A full
233
+ # os.path -> pathlib migration is a bigger undertaking than a config
234
+ # change.
235
+ "PTH",
236
+ # pep8-naming: most of "N" fails on scientific/statistical variable
237
+ # naming conventions (e.g. X, Y, N806 alone is 2000+ hits), so only the
238
+ # individually-clean rules are selected rather than the whole category.
239
+ "N804", "N811", "N813", "N817",
240
+ # flake8-simplify: most of "SIM" still has real hits, so only the
241
+ # individually-clean rules are selected rather than the whole category.
242
+ "SIM107", "SIM109", "SIM110", "SIM112", "SIM116", "SIM202", "SIM208",
243
+ "SIM220", "SIM221", "SIM222", "SIM223", "SIM911",
244
+ # tryceratops: TRY003 alone (no vanilla-args messages in raise) is
245
+ # 1300+ hits, so only the individually-clean rules are selected rather
246
+ # than the whole category.
247
+ "TRY400", "TRY401",
248
+ # flake8-use-pathlib
249
+ "PTH",
250
+ "RET501",
251
+ "RET502",
252
+ "RET507",
253
+ "RET508",
254
+ ]
255
+
256
+ # pydocstyle ("D") is intentionally NOT selected above. This project already
257
+ # validates numpydoc docstring structure via tools/validate_docstrings.py
258
+ # (built on the numpydoc package), which understands our numpydoc convention
259
+ # far more precisely than ruff's generic pydocstyle checks do - even with
260
+ # `[tool.ruff.lint.pydocstyle] convention = "numpy"` set, D still produces
261
+ # tens of thousands of violations and disagrees with the dedicated
262
+ # validator in places. Do not add "D" to select.
263
+
264
+ ignore = [
265
+ # Required to allow black formatting
266
+ # Whitespace before ':' (Needed for black)
267
+ "E203",
268
+ # Line too long (### > 88 characters) (Needed for black)
269
+ "E501",
270
+ # Multiple statements on one line (colon) (E701)
271
+ "E701",
272
+
273
+ ### Never enable: these conflict with the black/ruff-format formatter.
274
+ # ISC001 is deliberately NOT in this list: we keep ISC001 enabled and fix
275
+ # the occasional real violation by hand instead of suppressing it.
276
+ "COM812", # missing-trailing-comma: black decides this, not us
277
+ "COM819", # prohibited-trailing-comma: black decides this, not us
278
+ "Q003", # avoidable-escaped-quote
279
+
280
+ ### Intentionally disabled
281
+ # Counts below are from `ruff check . --select ALL`
282
+ # (this project's conformance scope), refreshed 2026-07-27.
283
+ # Too many arguments to function call
284
+ "PLR0913", # 645
285
+ # Too many returns
286
+ "PLR0911", # 12
287
+ # Too many branches
288
+ "PLR0912", # 221
289
+ # Too many statements
290
+ "PLR0915", # 221
291
+ # Too many positional arguments
292
+ "PLR0917", # 617
293
+ # Redefined loop name
294
+ "PLW2901", # 49
295
+ # incorrect-dict-iterator, flags valid Series.items usage
296
+ "PERF102", # 5
297
+ # try-except-in-loop, becomes useless in Python 3.11
298
+ "PERF203", # 9
299
+ # pytest-parametrize-names-wrong-type
300
+ "PT006", # 36
301
+ # pytest-raises-with-multiple-statements
302
+ "PT012", # 15
303
+ # Docstring contains ambiguous letter
304
+ "RUF002", # Do Not Enable
305
+ # Magic number
306
+ "PLR2004", # 717
307
+ # import-outside-toplevel
308
+ "PLC0415", # 853
309
+
310
+ ### TODO: Enable gradually
311
+ # Too many uses of dict(...) instread of {...}
312
+ # Would be good enforce eventually
313
+ "C408", # 324
314
+ # Too many places without match= in pytest raises
315
+ # Would be goot enforce eventually
316
+ "PT011", # 519
317
+ "RUF059", # 342
318
+ "PERF401", # 30
319
+ # collection-literal-concatenation
320
+ "RUF005", # 138
321
+ # mutable-class-default
322
+ "RUF012", # 177
323
+ # repeated-equality-comparison
324
+ "PLR1714", # 27
325
+
326
+ ### New 2026-07-27 when enabling ASYNC, EXE, G, LOG, FURB, S, full ICN
327
+ # assert is used pervasively outside of tests in this codebase (input
328
+ # validation, invariant checks); not adopting flake8-bandit's blanket
329
+ # objection to it
330
+ "S101", # 1669
331
+ # try/except/pass: mostly deliberate best-effort cleanup code
332
+ "S110", # 5
333
+ # pickle usage: needed for model persistence, a documented feature
334
+ "S301", # 11
335
+ # eval usage in a handful of expression-parsing helpers
336
+ "S307", # 3
337
+ # urlopen used only for fetching public, hardcoded dataset URLs
338
+ "S310", # 2
339
+ # subprocess with shell=True / without shell=True check: used in a couple
340
+ # of dev/CI helper scripts, not on untrusted input
341
+ "S602", # 2
342
+ "S603", # 2
343
+
344
+ ### New 2026-07-27 when enabling A, DTZ, PD, PTH
345
+ # Variable/argument/import shadows a builtin name (e.g. `id`, `type`,
346
+ # `filter`); common in this codebase's mathematical notation and not
347
+ # worth a rename sweep
348
+ "A001", # 35
349
+ "A002", # 10
350
+ "A004", # 2
351
+ # datetime()/datetime.now() without tzinfo; this project works with
352
+ # naive timestamps throughout (dataset dates, log timestamps) and does
353
+ # not need timezone-aware datetimes
354
+ "DTZ001", # 82
355
+ "DTZ005", # 4
356
+ # inplace=True is used deliberately in a number of places
357
+ "PD002", # 10
358
+ # .pivot()/.unstack() and .stack() instead of .pivot_table()/.melt():
359
+ # deliberate choices, not accidental API misuse
360
+ "PD010", # 25
361
+ "PD013", # 13
362
+ # .values instead of .to_numpy(): a pervasive, long-standing idiom
363
+ # throughout this codebase, not worth a mechanical rewrite
364
+ "PD011", # 308
365
+ # os.path used throughout instead of pathlib; a real modernization
366
+ # opportunity, but a bigger migration than a quick fix
367
+ "PTH100", # 107
368
+ "PTH103", # 4
369
+ "PTH106", # 1
370
+ "PTH107", # 6
371
+ "PTH110", # 13
372
+ "PTH111", # 1
373
+ "PTH112", # 1
374
+ "PTH113", # 1
375
+ "PTH118", # 237
376
+ "PTH119", # 1
377
+ "PTH120", # 123
378
+ "PTH122", # 4
379
+ "PTH123", # 89
380
+ "PTH204", # 4
381
+ "PTH207", # 6
382
+ "PTH208", # 3
383
+ ]
384
+
385
+ [tool.ruff.lint.flake8-quotes]
386
+ multiline-quotes = "double"
387
+
388
+ [tool.ruff.lint.isort]
389
+ # Mirrors original [tool.isort] below as closely as ruff's isort implementation
390
+ # allows.
391
+ combine-as-imports = true
392
+ force-sort-within-sections = true
393
+ known-first-party = ["statsmodels"]
394
+ known-third-party = ["Cython", "cython", "numpy", "matplotlib", "pandas", "patsy", "pytest", "cvxopt"]
395
+ section-order = ["future", "compat", "standard-library", "third-party", "first-party", "local-folder"]
396
+ split-on-trailing-comma = true
397
+
398
+ [tool.ruff.lint.isort.sections]
399
+ # Mirrors known_compat from [tool.isort].
400
+ compat = ["statsmodels.compat", "setuptools"]
401
+
402
+ [tool.ruff.lint.per-file-ignores]
403
+ # relative imports allowed for asv_bench
404
+ "statsmodels/__init__.py" = ["PT028"]
405
+ "statsmodels/tsa/vector_ar/var_model.py" = ["PT028"]
406
+ "statsmodels/stats/rates.py" = ["PT028"]
407
+ "statsmodels/stats/proportion.py" = ["PT028"]
408
+ "statsmodels/stats/oneway.py" = ["PT028"]
409
+ "statsmodels/stats/multivariate.py" = ["PT028"]
410
+ "statsmodels/stats/diagnostic_gen.py" = ["PT028"]
411
+ "statsmodels/discrete/_diagnostics_count.py" = ["PT028"]
412
+ "statsmodels/examples/tests/test_notebooks.py" = ["F401"]
413
+ # Example scripts/notebooks are left as-is (not converted to pathlib).
414
+ "**/examples/**" = ["PTH"]
415
+ [tool.pytest.ini_options]
416
+ minversion = "8.4.1"
417
+ addopts = "--strict --durations=30 --junitxml=test-data.xml --randomly-dont-reset-seed"
418
+ testpaths = "statsmodels"
419
+ xfail_strict = true
420
+ empty_parameter_set_mark = "fail_at_collect"
421
+ filterwarnings = [
422
+ "ignore:`formatargspec`:DeprecationWarning:statsmodels",
423
+ "ignore:Using or importing:DeprecationWarning",
424
+ "ignore:Session._key_changed is deprecated:DeprecationWarning",
425
+ "error:Support for multi-dimensional:DeprecationWarning",
426
+ "error:Mutating unit root tests is deprecated:FutureWarning",
427
+ "error:Lag selection has changed:DeprecationWarning",
428
+ "error:More than 20 figures have been opened:RuntimeWarning:",
429
+ "error:Inequality constraints incompatible::",
430
+ "error:Parameters are not consistent with a::",
431
+ "ignore:The --strict option is deprecated:pytest.PytestDeprecationWarning",
432
+ "error:The default for reindex:FutureWarning:",
433
+ "error:Values in x were outside bounds:RuntimeWarning:",
434
+ "error:The random_state property is deprecated:FutureWarning",
435
+ "error:random_state is deprecated:FutureWarning",
436
+ "error:seed is deprecated:FutureWarning",
437
+ "error:get_state is deprecated:FutureWarning",
438
+ "error:Conversion of an array with ndim:DeprecationWarning:",
439
+ "error:the matrix subclass is not the recommended::",
440
+ "error:The Dataframe Interchange Protocol::",
441
+ "error:Setting the shape:DeprecationWarning:",
442
+ "error:After 0.17 or January 2028:FutureWarning:",
443
+ "error:A future version of pandas:",
444
+ "error:The inplace keyword in::",
445
+ "error:Keyword arguments have been passed:FutureWarning:",
446
+ "error:After statsmodels 0.15 is released:FutureWarning:",
447
+ "error:Passing `None` as the seed currently:FutureWarning:",
448
+ "error:the 'random_state' keyword is deprecated:FutureWarning:",
449
+ "error:the 'seed' keyword is deprecated:FutureWarning:",
450
+ "error:the 'center' keyword is deprecated:FutureWarning:",
451
+ "error:Unpacking:FutureWarning:",
452
+ "error:The test statistic is outside:statsmodels.tools.sm_exceptions.InterpolationWarning:",
453
+ "error:The design matrix is:statsmodels.tools.sm_exceptions.SingularMatrixWarning:",
454
+ "error:Fast medcouple algorithm:UserWarning:",
455
+ "error:medcouple is undefined:UserWarning:",
456
+ "error:Provided `endog` series:UserWarning:",
457
+ # Strict checks disabled
458
+ # "error:overflow encountered in square:RuntimeWarning",
459
+ # "error:invalid value encountered in cos:RuntimeWarning",
460
+ # "error:divide by zero encountered in double_scalars:RuntimeWarning",
461
+ # "error:invalid value encountered in log:RuntimeWarning",
462
+ # "error:invalid value encountered in sqrt:RuntimeWarning:",
463
+ # "error:overflow encountered in double_scalars:RuntimeWarning:",
464
+ # "error:overflow encountered in multiply:RuntimeWarning:",
465
+ ]
466
+ junit_family = "xunit2"
467
+ markers = [
468
+ "example: mark a test that runs example code",
469
+ "matplotlib: mark a test that requires matplotlib",
470
+ "slow: mark a test as slow",
471
+ "smoke: mark a test as a smoke test",
472
+ "high_memory: mark a test as a high memory utilization test",
473
+ "low_precision: mark a test as low precision",
474
+ "todo: mark a test as incomplete",
475
+ "polars: mark a test that requires polars",
476
+ "singleton_randomstate: mark a test as changing the singleton RandomState",
477
+ "joblib: mark a test as using joblib for parallel computation",
478
+ ]
479
+
480
+ [tool.ruff.format]
481
+ quote-style = "double"
482
+
483
+ [tool.coverage.run]
484
+ source = ["statsmodels"]
485
+ branch = true
486
+ plugins = ["Cython.Coverage"]
487
+ omit = [
488
+ # print_version is untestable
489
+ "*/print_version.py",
490
+ # skip compatibility code
491
+ "*/compat/*",
492
+ # Unused file
493
+ "*/results/gee_generate_tests.py",
494
+ # Results for tests
495
+ "*/tests/results/*",
496
+ # Simulation checks
497
+ "*/tests/*_simulation_check.py",
498
+ # Misc non-test files in test directories
499
+ "*/tests/_*",
500
+ "*/tests/e*",
501
+ "*/tests/c*",
502
+ "*/tests/d*",
503
+ "*/tests/g*",
504
+ "*/tests/m*",
505
+ "*/tests/p*",
506
+ "*/tests/r*",
507
+ "*/tests/s*",
508
+ "*/_version.py",
509
+ "*/_pss_critical_values/*",
510
+ ]
511
+
512
+ [tool.coverage.report]
513
+ show_missing = true
514
+ ignore_errors = false
515
+ # Regexes for lines to exclude from consideration
516
+ exclude_also = [
517
+ # Have to re-enable the standard pragma
518
+ "pragma: no cover",
519
+
520
+ # Do not complain about missing debug-only code:
521
+ "def __repr__",
522
+ "if self\\.debug",
523
+ "if pdf_output:",
524
+
525
+ # Do not complain if tests do not hit defensive assertion code:
526
+ "raise AssertionError",
527
+ "raise NotImplementedError",
528
+ "except NotImplementedError",
529
+ "except ImportError",
530
+ "except (HTTPError, URLError, SSLError, timeout)",
531
+ "except IGNORED_EXCEPTIONS",
532
+
533
+ # Ignore pass
534
+ "pass",
535
+
536
+ # Do not complain if non-runnable code is not run:
537
+ "if 0:",
538
+ "if __name__ == .__main__.:",
539
+ ]
540
+
541
+ [tool.coverage.html]
542
+ directory = "coverage_html_report"
543
+
544
+
545
+ [tool.black]
546
+ line-length = 88
547
+ target-version = ["py310"]
shared/package-files/8b/8b98ae07154d4192178886dad7c2939d83412ccd802457b11bfa7dba4356364e/blob ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstdint>
4
+ #include <stdexcept>
5
+ #include <type_traits>
6
+ #include <utility>
7
+
8
+ #include <c10/core/OptionalRef.h>
9
+ #include <c10/core/ScalarType.h>
10
+ #include <c10/core/SymBool.h>
11
+ #include <c10/core/SymFloat.h>
12
+ #include <c10/core/SymInt.h>
13
+ #include <c10/core/SymNodeImpl.h>
14
+ #include <c10/macros/Export.h>
15
+ #include <c10/macros/Macros.h>
16
+ #include <c10/util/Deprecated.h>
17
+ #include <c10/util/Exception.h>
18
+ #include <c10/util/Half.h>
19
+ #include <c10/util/TypeCast.h>
20
+ #include <c10/util/complex.h>
21
+ #include <c10/util/intrusive_ptr.h>
22
+
23
+ namespace c10 {
24
+
25
+ /**
26
+ * Scalar represents a 0-dimensional tensor which contains a single element.
27
+ * Unlike a tensor, numeric literals (in C++) are implicitly convertible to
28
+ * Scalar (which is why, for example, we provide both add(Tensor) and
29
+ * add(Scalar) overloads for many operations). It may also be used in
30
+ * circumstances where you statically know a tensor is 0-dim and single size,
31
+ * but don't know its type.
32
+ */
33
+ class C10_API Scalar {
34
+ public:
35
+ Scalar() : Scalar(int64_t(0)) {}
36
+
37
+ void destroy() {
38
+ if (Tag::HAS_si == tag || Tag::HAS_sd == tag || Tag::HAS_sb == tag) {
39
+ raw::intrusive_ptr::decref(v.p);
40
+ v.p = nullptr;
41
+ }
42
+ }
43
+
44
+ ~Scalar() {
45
+ destroy();
46
+ }
47
+
48
+ #define DEFINE_IMPLICIT_CTOR(type, name) \
49
+ Scalar(type vv) : Scalar(vv, true) {}
50
+
51
+ AT_FORALL_SCALAR_TYPES_AND7(
52
+ Half,
53
+ BFloat16,
54
+ Float8_e5m2,
55
+ Float8_e4m3fn,
56
+ Float8_e5m2fnuz,
57
+ Float8_e4m3fnuz,
58
+ ComplexHalf,
59
+ DEFINE_IMPLICIT_CTOR)
60
+ AT_FORALL_COMPLEX_TYPES(DEFINE_IMPLICIT_CTOR)
61
+
62
+ // Helper constructors to allow Scalar creation from long and long long types
63
+ // As std::is_same_v<long, long long> is false(except Android), one needs to
64
+ // provide a constructor from either long or long long in addition to one from
65
+ // int64_t
66
+ #if defined(__APPLE__) || defined(__MACOSX)
67
+ static_assert(
68
+ std::is_same_v<long long, int64_t>,
69
+ "int64_t is the same as long long on MacOS");
70
+ Scalar(long vv) : Scalar(vv, true) {}
71
+ #endif
72
+ #if defined(__linux__) && !defined(__ANDROID__)
73
+ static_assert(
74
+ std::is_same_v<long, int64_t>,
75
+ "int64_t is the same as long on Linux");
76
+ Scalar(long long vv) : Scalar(vv, true) {}
77
+ #endif
78
+
79
+ Scalar(uint16_t vv) : Scalar(vv, true) {}
80
+ Scalar(uint32_t vv) : Scalar(vv, true) {}
81
+ Scalar(uint64_t vv) {
82
+ if (vv > static_cast<uint64_t>(INT64_MAX)) {
83
+ tag = Tag::HAS_u;
84
+ v.u = vv;
85
+ } else {
86
+ tag = Tag::HAS_i;
87
+ // NB: no need to use convert, we've already tested convertibility
88
+ v.i = static_cast<int64_t>(vv);
89
+ }
90
+ }
91
+
92
+ #undef DEFINE_IMPLICIT_CTOR
93
+
94
+ // Value* is both implicitly convertible to SymbolicVariable and bool which
95
+ // causes ambiguity error. Specialized constructor for bool resolves this
96
+ // problem.
97
+ template <
98
+ typename T,
99
+ typename std::enable_if_t<std::is_same_v<T, bool>, bool>* = nullptr>
100
+ Scalar(T vv) : tag(Tag::HAS_b) {
101
+ v.i = convert<int64_t, bool>(vv);
102
+ }
103
+
104
+ template <
105
+ typename T,
106
+ typename std::enable_if_t<std::is_same_v<T, c10::SymBool>, bool>* =
107
+ nullptr>
108
+ Scalar(T vv) : tag(Tag::HAS_sb) {
109
+ v.i = convert<int64_t, c10::SymBool>(vv);
110
+ }
111
+
112
+ #define DEFINE_ACCESSOR(type, name) \
113
+ type to##name() const { \
114
+ if (Tag::HAS_d == tag) { \
115
+ return checked_convert<type, double>(v.d, #type); \
116
+ } else if (Tag::HAS_z == tag) { \
117
+ return checked_convert<type, c10::complex<double>>(v.z, #type); \
118
+ } \
119
+ if (Tag::HAS_b == tag) { \
120
+ return checked_convert<type, bool>(v.i, #type); \
121
+ } else if (Tag::HAS_i == tag) { \
122
+ return checked_convert<type, int64_t>(v.i, #type); \
123
+ } else if (Tag::HAS_u == tag) { \
124
+ return checked_convert<type, uint64_t>(v.u, #type); \
125
+ } else if (Tag::HAS_si == tag) { \
126
+ return checked_convert<type, int64_t>( \
127
+ toSymInt().guard_int(__FILE__, __LINE__), #type); \
128
+ } else if (Tag::HAS_sd == tag) { \
129
+ return checked_convert<type, int64_t>( \
130
+ toSymFloat().guard_float(__FILE__, __LINE__), #type); \
131
+ } else if (Tag::HAS_sb == tag) { \
132
+ return checked_convert<type, int64_t>( \
133
+ toSymBool().guard_bool(__FILE__, __LINE__), #type); \
134
+ } \
135
+ TORCH_CHECK(false) \
136
+ }
137
+
138
+ // TODO: Support ComplexHalf accessor
139
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_ACCESSOR)
140
+ DEFINE_ACCESSOR(uint16_t, UInt16)
141
+ DEFINE_ACCESSOR(uint32_t, UInt32)
142
+ DEFINE_ACCESSOR(uint64_t, UInt64)
143
+
144
+ #undef DEFINE_ACCESSOR
145
+
146
+ SymInt toSymInt() const {
147
+ if (Tag::HAS_si == tag) {
148
+ return c10::SymInt(intrusive_ptr<SymNodeImpl>::reclaim_copy(
149
+ static_cast<SymNodeImpl*>(v.p)));
150
+ } else {
151
+ return toLong();
152
+ }
153
+ }
154
+
155
+ SymFloat toSymFloat() const {
156
+ if (Tag::HAS_sd == tag) {
157
+ return c10::SymFloat(intrusive_ptr<SymNodeImpl>::reclaim_copy(
158
+ static_cast<SymNodeImpl*>(v.p)));
159
+ } else {
160
+ return toDouble();
161
+ }
162
+ }
163
+
164
+ SymBool toSymBool() const {
165
+ if (Tag::HAS_sb == tag) {
166
+ return c10::SymBool(intrusive_ptr<SymNodeImpl>::reclaim_copy(
167
+ static_cast<SymNodeImpl*>(v.p)));
168
+ } else {
169
+ return toBool();
170
+ }
171
+ }
172
+
173
+ // also support scalar.to<int64_t>();
174
+ // Deleted for unsupported types, but specialized below for supported types
175
+ template <typename T>
176
+ T to() const = delete;
177
+
178
+ // audit uses of data_ptr
179
+ const void* data_ptr() const {
180
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
181
+ return static_cast<const void*>(&v);
182
+ }
183
+
184
+ bool isFloatingPoint() const {
185
+ return Tag::HAS_d == tag || Tag::HAS_sd == tag;
186
+ }
187
+
188
+ C10_DEPRECATED_MESSAGE(
189
+ "isIntegral is deprecated. Please use the overload with 'includeBool' parameter instead.")
190
+ bool isIntegral() const {
191
+ return Tag::HAS_i == tag || Tag::HAS_si == tag || Tag::HAS_u == tag;
192
+ }
193
+ bool isIntegral(bool includeBool) const {
194
+ return Tag::HAS_i == tag || Tag::HAS_si == tag || Tag::HAS_u == tag ||
195
+ (includeBool && isBoolean());
196
+ }
197
+
198
+ bool isComplex() const {
199
+ return Tag::HAS_z == tag;
200
+ }
201
+ bool isBoolean() const {
202
+ return Tag::HAS_b == tag || Tag::HAS_sb == tag;
203
+ }
204
+
205
+ // you probably don't actually want these; they're mostly for testing
206
+ bool isSymInt() const {
207
+ return Tag::HAS_si == tag;
208
+ }
209
+ bool isSymFloat() const {
210
+ return Tag::HAS_sd == tag;
211
+ }
212
+ bool isSymBool() const {
213
+ return Tag::HAS_sb == tag;
214
+ }
215
+
216
+ bool isSymbolic() const {
217
+ return Tag::HAS_si == tag || Tag::HAS_sd == tag || Tag::HAS_sb == tag;
218
+ }
219
+
220
+ C10_ALWAYS_INLINE Scalar& operator=(Scalar&& other) noexcept {
221
+ if (&other == this) {
222
+ return *this;
223
+ }
224
+
225
+ destroy();
226
+ moveFrom(std::move(other));
227
+ return *this;
228
+ }
229
+
230
+ C10_ALWAYS_INLINE Scalar& operator=(const Scalar& other) {
231
+ if (&other == this) {
232
+ return *this;
233
+ }
234
+
235
+ *this = Scalar(other);
236
+ return *this;
237
+ }
238
+
239
+ Scalar operator-() const;
240
+ Scalar conj() const;
241
+ Scalar log() const;
242
+
243
+ template <
244
+ typename T,
245
+ typename std::enable_if_t<!c10::is_complex<T>::value, int> = 0>
246
+ bool equal(T num) const {
247
+ if (isComplex()) {
248
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
249
+ auto val = v.z;
250
+ return (val.real() == num) && (val.imag() == T());
251
+ } else if (isFloatingPoint()) {
252
+ TORCH_CHECK(!isSymbolic(), "NYI SymFloat equality");
253
+ return v.d == num;
254
+ } else if (tag == Tag::HAS_i) {
255
+ if (overflows<T>(v.i, /* strict_unsigned */ true)) {
256
+ return false;
257
+ } else {
258
+ return static_cast<T>(v.i) == num;
259
+ }
260
+ } else if (tag == Tag::HAS_u) {
261
+ if (overflows<T>(v.u, /* strict_unsigned */ true)) {
262
+ return false;
263
+ } else {
264
+ return static_cast<T>(v.u) == num;
265
+ }
266
+ } else if (tag == Tag::HAS_si) {
267
+ TORCH_INTERNAL_ASSERT(false, "NYI SymInt equality");
268
+ } else if (isBoolean()) {
269
+ // boolean scalar does not equal to a non boolean value
270
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
271
+ return false;
272
+ } else {
273
+ TORCH_INTERNAL_ASSERT(false);
274
+ }
275
+ }
276
+
277
+ template <
278
+ typename T,
279
+ typename std::enable_if_t<c10::is_complex<T>::value, int> = 0>
280
+ bool equal(T num) const {
281
+ if (isComplex()) {
282
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
283
+ return v.z == num;
284
+ } else if (isFloatingPoint()) {
285
+ TORCH_CHECK(!isSymbolic(), "NYI SymFloat equality");
286
+ return (v.d == num.real()) && (num.imag() == T());
287
+ } else if (tag == Tag::HAS_i) {
288
+ if (overflows<T>(v.i, /* strict_unsigned */ true)) {
289
+ return false;
290
+ } else {
291
+ return static_cast<T>(v.i) == num.real() && num.imag() == T();
292
+ }
293
+ } else if (tag == Tag::HAS_u) {
294
+ if (overflows<T>(v.u, /* strict_unsigned */ true)) {
295
+ return false;
296
+ } else {
297
+ return static_cast<T>(v.u) == num.real() && num.imag() == T();
298
+ }
299
+ } else if (tag == Tag::HAS_si) {
300
+ TORCH_INTERNAL_ASSERT(false, "NYI SymInt equality");
301
+ } else if (isBoolean()) {
302
+ // boolean scalar does not equal to a non boolean value
303
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
304
+ return false;
305
+ } else {
306
+ TORCH_INTERNAL_ASSERT(false);
307
+ }
308
+ }
309
+
310
+ bool equal(bool num) const {
311
+ if (isBoolean()) {
312
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
313
+ return static_cast<bool>(v.i) == num;
314
+ } else {
315
+ return false;
316
+ }
317
+ }
318
+
319
+ ScalarType type() const {
320
+ if (isComplex()) {
321
+ return ScalarType::ComplexDouble;
322
+ } else if (isFloatingPoint()) {
323
+ return ScalarType::Double;
324
+ } else if (isIntegral(/*includeBool=*/false)) {
325
+ // Represent all integers as long, UNLESS it is unsigned and therefore
326
+ // unrepresentable as long
327
+ if (Tag::HAS_u == tag) {
328
+ return ScalarType::UInt64;
329
+ }
330
+ return ScalarType::Long;
331
+ } else if (isBoolean()) {
332
+ return ScalarType::Bool;
333
+ } else {
334
+ throw std::runtime_error("Unknown scalar type.");
335
+ }
336
+ }
337
+
338
+ Scalar(Scalar&& rhs) noexcept : tag(rhs.tag) {
339
+ moveFrom(std::move(rhs));
340
+ }
341
+
342
+ Scalar(const Scalar& rhs) : tag(rhs.tag), v(rhs.v) {
343
+ if (isSymbolic()) {
344
+ c10::raw::intrusive_ptr::incref(v.p);
345
+ }
346
+ }
347
+
348
+ Scalar(c10::SymInt si) {
349
+ if (auto m = si.maybe_as_int()) {
350
+ tag = Tag::HAS_i;
351
+ v.i = *m;
352
+ } else {
353
+ tag = Tag::HAS_si;
354
+ v.p = std::move(si).release();
355
+ }
356
+ }
357
+
358
+ Scalar(c10::SymFloat sd) {
359
+ if (sd.is_symbolic()) {
360
+ tag = Tag::HAS_sd;
361
+ v.p = std::move(sd).release();
362
+ } else {
363
+ tag = Tag::HAS_d;
364
+ v.d = sd.as_float_unchecked();
365
+ }
366
+ }
367
+
368
+ Scalar(c10::SymBool sb) {
369
+ if (auto m = sb.maybe_as_bool()) {
370
+ tag = Tag::HAS_b;
371
+ v.i = *m;
372
+ } else {
373
+ tag = Tag::HAS_sb;
374
+ v.p = std::move(sb).release();
375
+ }
376
+ }
377
+
378
+ // We can't set v in the initializer list using the
379
+ // syntax v{ .member = ... } because it doesn't work on MSVC
380
+ private:
381
+ enum class Tag { HAS_d, HAS_i, HAS_u, HAS_z, HAS_b, HAS_sd, HAS_si, HAS_sb };
382
+
383
+ // Note [Meaning of HAS_u]
384
+ // ~~~~~~~~~~~~~~~~~~~~~~~
385
+ // HAS_u is a bit special. On its face, it just means that we
386
+ // are holding an unsigned integer. However, we generally don't
387
+ // distinguish between different bit sizes in Scalar (e.g., we represent
388
+ // float as double), instead, it represents a mathematical notion
389
+ // of some quantity (integral versus floating point). So actually,
390
+ // HAS_u is used solely to represent unsigned integers that could
391
+ // not be represented as a signed integer. That means only uint64_t
392
+ // potentially can get this tag; smaller types like uint8_t fits into a
393
+ // regular int and so for BC reasons we keep as an int.
394
+
395
+ // NB: assumes that self has already been cleared
396
+ // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
397
+ C10_ALWAYS_INLINE void moveFrom(Scalar&& rhs) noexcept {
398
+ v = rhs.v;
399
+ tag = rhs.tag;
400
+ if (rhs.tag == Tag::HAS_si || rhs.tag == Tag::HAS_sd ||
401
+ rhs.tag == Tag::HAS_sb) {
402
+ // Move out of scalar
403
+ rhs.tag = Tag::HAS_i;
404
+ rhs.v.i = 0;
405
+ }
406
+ }
407
+
408
+ Tag tag;
409
+
410
+ union v_t {
411
+ double d{};
412
+ int64_t i;
413
+ // See Note [Meaning of HAS_u]
414
+ uint64_t u;
415
+ c10::complex<double> z;
416
+ c10::intrusive_ptr_target* p;
417
+ // NOLINTNEXTLINE(modernize-use-equals-default)
418
+ v_t() {} // default constructor
419
+ } v;
420
+
421
+ template <
422
+ typename T,
423
+ typename std::enable_if_t<
424
+ std::is_integral_v<T> && !std::is_same_v<T, bool>,
425
+ bool>* = nullptr>
426
+ Scalar(T vv, bool) : tag(Tag::HAS_i) {
427
+ v.i = convert<decltype(v.i), T>(vv);
428
+ }
429
+
430
+ template <
431
+ typename T,
432
+ typename std::enable_if_t<
433
+ !std::is_integral_v<T> && !c10::is_complex<T>::value,
434
+ bool>* = nullptr>
435
+ Scalar(T vv, bool) : tag(Tag::HAS_d) {
436
+ v.d = convert<decltype(v.d), T>(vv);
437
+ }
438
+
439
+ template <
440
+ typename T,
441
+ typename std::enable_if_t<c10::is_complex<T>::value, bool>* = nullptr>
442
+ Scalar(T vv, bool) : tag(Tag::HAS_z) {
443
+ v.z = convert<decltype(v.z), T>(vv);
444
+ }
445
+ };
446
+
447
+ using OptionalScalarRef = c10::OptionalRef<Scalar>;
448
+
449
+ // define the scalar.to<int64_t>() specializations
450
+ #define DEFINE_TO(T, name) \
451
+ template <> \
452
+ inline T Scalar::to<T>() const { \
453
+ return to##name(); \
454
+ }
455
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_TO)
456
+ DEFINE_TO(uint16_t, UInt16)
457
+ DEFINE_TO(uint32_t, UInt32)
458
+ DEFINE_TO(uint64_t, UInt64)
459
+ #undef DEFINE_TO
460
+
461
+ } // namespace c10
shared/package-files/8b/8b99e880d840da023013d691988e76f16c3dc20737eb2fb046659b390e819fc0/blob ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor random(const at::Tensor & self, int64_t from, c10::optional<int64_t> to, c10::optional<at::Generator> generator=c10::nullopt);
20
+ TORCH_API at::Tensor & random_from_out(const at::Tensor & self, int64_t from, c10::optional<int64_t> to, c10::optional<at::Generator> generator, at::Tensor & out);
21
+ TORCH_API at::Tensor & random_(at::Tensor & self, int64_t from, c10::optional<int64_t> to, c10::optional<at::Generator> generator=c10::nullopt);
22
+ TORCH_API at::Tensor & random_meta_(at::Tensor & self, int64_t from, c10::optional<int64_t> to, c10::optional<at::Generator> generator=c10::nullopt);
23
+ TORCH_API at::Tensor random(const at::Tensor & self, int64_t to, c10::optional<at::Generator> generator=c10::nullopt);
24
+ TORCH_API at::Tensor & random_to_out(const at::Tensor & self, int64_t to, c10::optional<at::Generator> generator, at::Tensor & out);
25
+ TORCH_API at::Tensor & random_(at::Tensor & self, int64_t to, c10::optional<at::Generator> generator=c10::nullopt);
26
+ TORCH_API at::Tensor & random_meta_(at::Tensor & self, int64_t to, c10::optional<at::Generator> generator=c10::nullopt);
27
+ TORCH_API at::Tensor random(const at::Tensor & self, c10::optional<at::Generator> generator=c10::nullopt);
28
+ TORCH_API at::Tensor & random_out(const at::Tensor & self, c10::optional<at::Generator> generator, at::Tensor & out);
29
+ TORCH_API at::Tensor & random_(at::Tensor & self, c10::optional<at::Generator> generator=c10::nullopt);
30
+ TORCH_API at::Tensor & random_meta_(at::Tensor & self, c10::optional<at::Generator> generator=c10::nullopt);
31
+ } // namespace native
32
+ } // namespace at
shared/package-files/8b/8b9ede33ab32ae2505bc06eb5402e7ce20b0fc8e2510dcb305c25d39a1fbd725/blob ADDED
Binary file (350 Bytes). View file
 
shared/package-files/8b/8b9f5dff2e2f70ac88457066a9b8e3d18518df408da36edd42f904642f50d944/blob ADDED
@@ -0,0 +1,921 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Abstract linear algebra library.
2
+
3
+ This module defines a class hierarchy that implements a kind of "lazy"
4
+ matrix representation, called the ``LinearOperator``. It can be used to do
5
+ linear algebra with extremely large sparse or structured matrices, without
6
+ representing those explicitly in memory. Such matrices can be added,
7
+ multiplied, transposed, etc.
8
+
9
+ As a motivating example, suppose you want have a matrix where almost all of
10
+ the elements have the value one. The standard sparse matrix representation
11
+ skips the storage of zeros, but not ones. By contrast, a LinearOperator is
12
+ able to represent such matrices efficiently. First, we need a compact way to
13
+ represent an all-ones matrix::
14
+
15
+ >>> import numpy as np
16
+ >>> from scipy.sparse.linalg._interface import LinearOperator
17
+ >>> class Ones(LinearOperator):
18
+ ... def __init__(self, shape):
19
+ ... super().__init__(dtype=None, shape=shape)
20
+ ... def _matvec(self, x):
21
+ ... return np.repeat(x.sum(), self.shape[0])
22
+
23
+ Instances of this class emulate ``np.ones(shape)``, but using a constant
24
+ amount of storage, independent of ``shape``. The ``_matvec`` method specifies
25
+ how this linear operator multiplies with (operates on) a vector. We can now
26
+ add this operator to a sparse matrix that stores only offsets from one::
27
+
28
+ >>> from scipy.sparse.linalg._interface import aslinearoperator
29
+ >>> from scipy.sparse import csr_array
30
+ >>> offsets = csr_array([[1, 0, 2], [0, -1, 0], [0, 0, 3]])
31
+ >>> A = aslinearoperator(offsets) + Ones(offsets.shape)
32
+ >>> A.dot([1, 2, 3])
33
+ array([13, 4, 15])
34
+
35
+ The result is the same as that given by its dense, explicitly-stored
36
+ counterpart::
37
+
38
+ >>> (np.ones(A.shape, A.dtype) + offsets.toarray()).dot([1, 2, 3])
39
+ array([13, 4, 15])
40
+
41
+ Several algorithms in the ``scipy.sparse`` library are able to operate on
42
+ ``LinearOperator`` instances.
43
+ """
44
+
45
+ import warnings
46
+
47
+ import numpy as np
48
+
49
+ from scipy.sparse import issparse
50
+ from scipy.sparse._sputils import isshape, isintlike, asmatrix, is_pydata_spmatrix
51
+
52
+ __all__ = ['LinearOperator', 'aslinearoperator']
53
+
54
+
55
+ class LinearOperator:
56
+ """Common interface for performing matrix vector products
57
+
58
+ Many iterative methods (e.g. cg, gmres) do not need to know the
59
+ individual entries of a matrix to solve a linear system A@x=b.
60
+ Such solvers only require the computation of matrix vector
61
+ products, A@v where v is a dense vector. This class serves as
62
+ an abstract interface between iterative solvers and matrix-like
63
+ objects.
64
+
65
+ To construct a concrete LinearOperator, either pass appropriate
66
+ callables to the constructor of this class, or subclass it.
67
+
68
+ A subclass must implement either one of the methods ``_matvec``
69
+ and ``_matmat``, and the attributes/properties ``shape`` (pair of
70
+ integers) and ``dtype`` (may be None). It may call the ``__init__``
71
+ on this class to have these attributes validated. Implementing
72
+ ``_matvec`` automatically implements ``_matmat`` (using a naive
73
+ algorithm) and vice-versa.
74
+
75
+ Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint``
76
+ to implement the Hermitian adjoint (conjugate transpose). As with
77
+ ``_matvec`` and ``_matmat``, implementing either ``_rmatvec`` or
78
+ ``_adjoint`` implements the other automatically. Implementing
79
+ ``_adjoint`` is preferable; ``_rmatvec`` is mostly there for
80
+ backwards compatibility.
81
+
82
+ Parameters
83
+ ----------
84
+ shape : tuple
85
+ Matrix dimensions (M, N).
86
+ matvec : callable f(v)
87
+ Returns returns A @ v.
88
+ rmatvec : callable f(v)
89
+ Returns A^H @ v, where A^H is the conjugate transpose of A.
90
+ matmat : callable f(V)
91
+ Returns A @ V, where V is a dense matrix with dimensions (N, K).
92
+ dtype : dtype
93
+ Data type of the matrix.
94
+ rmatmat : callable f(V)
95
+ Returns A^H @ V, where V is a dense matrix with dimensions (M, K).
96
+
97
+ Attributes
98
+ ----------
99
+ args : tuple
100
+ For linear operators describing products etc. of other linear
101
+ operators, the operands of the binary operation.
102
+ ndim : int
103
+ Number of dimensions (this is always 2)
104
+
105
+ See Also
106
+ --------
107
+ aslinearoperator : Construct LinearOperators
108
+
109
+ Notes
110
+ -----
111
+ The user-defined matvec() function must properly handle the case
112
+ where v has shape (N,) as well as the (N,1) case. The shape of
113
+ the return type is handled internally by LinearOperator.
114
+
115
+ It is highly recommended to explicitly specify the `dtype`, otherwise
116
+ it is determined automatically at the cost of a single matvec application
117
+ on `int8` zero vector using the promoted `dtype` of the output.
118
+ Python `int` could be difficult to automatically cast to numpy integers
119
+ in the definition of the `matvec` so the determination may be inaccurate.
120
+ It is assumed that `matmat`, `rmatvec`, and `rmatmat` would result in
121
+ the same dtype of the output given an `int8` input as `matvec`.
122
+
123
+ LinearOperator instances can also be multiplied, added with each
124
+ other and exponentiated, all lazily: the result of these operations
125
+ is always a new, composite LinearOperator, that defers linear
126
+ operations to the original operators and combines the results.
127
+
128
+ More details regarding how to subclass a LinearOperator and several
129
+ examples of concrete LinearOperator instances can be found in the
130
+ external project `PyLops <https://pylops.readthedocs.io>`_.
131
+
132
+
133
+ Examples
134
+ --------
135
+ >>> import numpy as np
136
+ >>> from scipy.sparse.linalg import LinearOperator
137
+ >>> def mv(v):
138
+ ... return np.array([2*v[0], 3*v[1]])
139
+ ...
140
+ >>> A = LinearOperator((2,2), matvec=mv)
141
+ >>> A
142
+ <2x2 _CustomLinearOperator with dtype=int8>
143
+ >>> A.matvec(np.ones(2))
144
+ array([ 2., 3.])
145
+ >>> A @ np.ones(2)
146
+ array([ 2., 3.])
147
+
148
+ """
149
+
150
+ ndim = 2
151
+ # Necessary for right matmul with numpy arrays.
152
+ __array_ufunc__ = None
153
+
154
+ def __new__(cls, *args, **kwargs):
155
+ if cls is LinearOperator:
156
+ # Operate as _CustomLinearOperator factory.
157
+ return super().__new__(_CustomLinearOperator)
158
+ else:
159
+ obj = super().__new__(cls)
160
+
161
+ if (type(obj)._matvec == LinearOperator._matvec
162
+ and type(obj)._matmat == LinearOperator._matmat):
163
+ warnings.warn("LinearOperator subclass should implement"
164
+ " at least one of _matvec and _matmat.",
165
+ category=RuntimeWarning, stacklevel=2)
166
+
167
+ return obj
168
+
169
+ def __init__(self, dtype, shape):
170
+ """Initialize this LinearOperator.
171
+
172
+ To be called by subclasses. ``dtype`` may be None; ``shape`` should
173
+ be convertible to a length-2 tuple.
174
+ """
175
+ if dtype is not None:
176
+ dtype = np.dtype(dtype)
177
+
178
+ shape = tuple(shape)
179
+ if not isshape(shape):
180
+ raise ValueError(f"invalid shape {shape!r} (must be 2-d)")
181
+
182
+ self.dtype = dtype
183
+ self.shape = shape
184
+
185
+ def _init_dtype(self):
186
+ """Determine the dtype by executing `matvec` on an `int8` test vector.
187
+
188
+ In `np.promote_types` hierarchy, the type `int8` is the smallest,
189
+ so we call `matvec` on `int8` and use the promoted dtype of the output
190
+ to set the default `dtype` of the `LinearOperator`.
191
+ We assume that `matmat`, `rmatvec`, and `rmatmat` would result in
192
+ the same dtype of the output given an `int8` input as `matvec`.
193
+
194
+ Called from subclasses at the end of the __init__ routine.
195
+ """
196
+ if self.dtype is None:
197
+ v = np.zeros(self.shape[-1], dtype=np.int8)
198
+ try:
199
+ matvec_v = np.asarray(self.matvec(v))
200
+ except OverflowError:
201
+ # Python large `int` promoted to `np.int64`or `np.int32`
202
+ self.dtype = np.dtype(int)
203
+ else:
204
+ self.dtype = matvec_v.dtype
205
+
206
+ def _matmat(self, X):
207
+ """Default matrix-matrix multiplication handler.
208
+
209
+ Falls back on the user-defined _matvec method, so defining that will
210
+ define matrix multiplication (though in a very suboptimal way).
211
+ """
212
+
213
+ return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T])
214
+
215
+ def _matvec(self, x):
216
+ """Default matrix-vector multiplication handler.
217
+
218
+ If self is a linear operator of shape (M, N), then this method will
219
+ be called on a shape (N,) or (N, 1) ndarray, and should return a
220
+ shape (M,) or (M, 1) ndarray.
221
+
222
+ This default implementation falls back on _matmat, so defining that
223
+ will define matrix-vector multiplication as well.
224
+ """
225
+ return self.matmat(x.reshape(-1, 1))
226
+
227
+ def matvec(self, x):
228
+ """Matrix-vector multiplication.
229
+
230
+ Performs the operation y=A@x where A is an MxN linear
231
+ operator and x is a column vector or 1-d array.
232
+
233
+ Parameters
234
+ ----------
235
+ x : {matrix, ndarray}
236
+ An array with shape (N,) or (N,1).
237
+
238
+ Returns
239
+ -------
240
+ y : {matrix, ndarray}
241
+ A matrix or ndarray with shape (M,) or (M,1) depending
242
+ on the type and shape of the x argument.
243
+
244
+ Notes
245
+ -----
246
+ This matvec wraps the user-specified matvec routine or overridden
247
+ _matvec method to ensure that y has the correct shape and type.
248
+
249
+ """
250
+
251
+ x = np.asanyarray(x)
252
+
253
+ M,N = self.shape
254
+
255
+ if x.shape != (N,) and x.shape != (N,1):
256
+ raise ValueError('dimension mismatch')
257
+
258
+ y = self._matvec(x)
259
+
260
+ if isinstance(x, np.matrix):
261
+ y = asmatrix(y)
262
+ else:
263
+ y = np.asarray(y)
264
+
265
+ if x.ndim == 1:
266
+ y = y.reshape(M)
267
+ elif x.ndim == 2:
268
+ y = y.reshape(M,1)
269
+ else:
270
+ raise ValueError('invalid shape returned by user-defined matvec()')
271
+
272
+ return y
273
+
274
+ def rmatvec(self, x):
275
+ """Adjoint matrix-vector multiplication.
276
+
277
+ Performs the operation y = A^H @ x where A is an MxN linear
278
+ operator and x is a column vector or 1-d array.
279
+
280
+ Parameters
281
+ ----------
282
+ x : {matrix, ndarray}
283
+ An array with shape (M,) or (M,1).
284
+
285
+ Returns
286
+ -------
287
+ y : {matrix, ndarray}
288
+ A matrix or ndarray with shape (N,) or (N,1) depending
289
+ on the type and shape of the x argument.
290
+
291
+ Notes
292
+ -----
293
+ This rmatvec wraps the user-specified rmatvec routine or overridden
294
+ _rmatvec method to ensure that y has the correct shape and type.
295
+
296
+ """
297
+
298
+ x = np.asanyarray(x)
299
+
300
+ M,N = self.shape
301
+
302
+ if x.shape != (M,) and x.shape != (M,1):
303
+ raise ValueError('dimension mismatch')
304
+
305
+ y = self._rmatvec(x)
306
+
307
+ if isinstance(x, np.matrix):
308
+ y = asmatrix(y)
309
+ else:
310
+ y = np.asarray(y)
311
+
312
+ if x.ndim == 1:
313
+ y = y.reshape(N)
314
+ elif x.ndim == 2:
315
+ y = y.reshape(N,1)
316
+ else:
317
+ raise ValueError('invalid shape returned by user-defined rmatvec()')
318
+
319
+ return y
320
+
321
+ def _rmatvec(self, x):
322
+ """Default implementation of _rmatvec; defers to adjoint."""
323
+ if type(self)._adjoint == LinearOperator._adjoint:
324
+ # _adjoint not overridden, prevent infinite recursion
325
+ if (hasattr(self, "_rmatmat")
326
+ and type(self)._rmatmat != LinearOperator._rmatmat):
327
+ # Try to use _rmatmat as a fallback
328
+ return self._rmatmat(x.reshape(-1, 1)).reshape(-1)
329
+ raise NotImplementedError
330
+ else:
331
+ return self.H.matvec(x)
332
+
333
+ def matmat(self, X):
334
+ """Matrix-matrix multiplication.
335
+
336
+ Performs the operation y=A@X where A is an MxN linear
337
+ operator and X dense N*K matrix or ndarray.
338
+
339
+ Parameters
340
+ ----------
341
+ X : {matrix, ndarray}
342
+ An array with shape (N,K).
343
+
344
+ Returns
345
+ -------
346
+ Y : {matrix, ndarray}
347
+ A matrix or ndarray with shape (M,K) depending on
348
+ the type of the X argument.
349
+
350
+ Notes
351
+ -----
352
+ This matmat wraps any user-specified matmat routine or overridden
353
+ _matmat method to ensure that y has the correct type.
354
+
355
+ """
356
+ if not (issparse(X) or is_pydata_spmatrix(X)):
357
+ X = np.asanyarray(X)
358
+
359
+ if X.ndim != 2:
360
+ raise ValueError(f'expected 2-d ndarray or matrix, not {X.ndim}-d')
361
+
362
+ if X.shape[0] != self.shape[1]:
363
+ raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}')
364
+
365
+ try:
366
+ Y = self._matmat(X)
367
+ except Exception as e:
368
+ if issparse(X) or is_pydata_spmatrix(X):
369
+ raise TypeError(
370
+ "Unable to multiply a LinearOperator with a sparse matrix."
371
+ " Wrap the matrix in aslinearoperator first."
372
+ ) from e
373
+ raise
374
+
375
+ if isinstance(Y, np.matrix):
376
+ Y = asmatrix(Y)
377
+
378
+ return Y
379
+
380
+ def rmatmat(self, X):
381
+ """Adjoint matrix-matrix multiplication.
382
+
383
+ Performs the operation y = A^H @ x where A is an MxN linear
384
+ operator and x is a column vector or 1-d array, or 2-d array.
385
+ The default implementation defers to the adjoint.
386
+
387
+ Parameters
388
+ ----------
389
+ X : {matrix, ndarray}
390
+ A matrix or 2D array.
391
+
392
+ Returns
393
+ -------
394
+ Y : {matrix, ndarray}
395
+ A matrix or 2D array depending on the type of the input.
396
+
397
+ Notes
398
+ -----
399
+ This rmatmat wraps the user-specified rmatmat routine.
400
+
401
+ """
402
+ if not (issparse(X) or is_pydata_spmatrix(X)):
403
+ X = np.asanyarray(X)
404
+
405
+ if X.ndim != 2:
406
+ raise ValueError('expected 2-d ndarray or matrix, not %d-d'
407
+ % X.ndim)
408
+
409
+ if X.shape[0] != self.shape[0]:
410
+ raise ValueError(f'dimension mismatch: {self.shape}, {X.shape}')
411
+
412
+ try:
413
+ Y = self._rmatmat(X)
414
+ except Exception as e:
415
+ if issparse(X) or is_pydata_spmatrix(X):
416
+ raise TypeError(
417
+ "Unable to multiply a LinearOperator with a sparse matrix."
418
+ " Wrap the matrix in aslinearoperator() first."
419
+ ) from e
420
+ raise
421
+
422
+ if isinstance(Y, np.matrix):
423
+ Y = asmatrix(Y)
424
+ return Y
425
+
426
+ def _rmatmat(self, X):
427
+ """Default implementation of _rmatmat defers to rmatvec or adjoint."""
428
+ if type(self)._adjoint == LinearOperator._adjoint:
429
+ return np.hstack([self.rmatvec(col.reshape(-1, 1)) for col in X.T])
430
+ else:
431
+ return self.H.matmat(X)
432
+
433
+ def __call__(self, x):
434
+ return self@x
435
+
436
+ def __mul__(self, x):
437
+ return self.dot(x)
438
+
439
+ def __truediv__(self, other):
440
+ if not np.isscalar(other):
441
+ raise ValueError("Can only divide a linear operator by a scalar.")
442
+
443
+ return _ScaledLinearOperator(self, 1.0/other)
444
+
445
+ def dot(self, x):
446
+ """Matrix-matrix or matrix-vector multiplication.
447
+
448
+ Parameters
449
+ ----------
450
+ x : array_like
451
+ 1-d or 2-d array, representing a vector or matrix.
452
+
453
+ Returns
454
+ -------
455
+ Ax : array
456
+ 1-d or 2-d array (depending on the shape of x) that represents
457
+ the result of applying this linear operator on x.
458
+
459
+ """
460
+ if isinstance(x, LinearOperator):
461
+ return _ProductLinearOperator(self, x)
462
+ elif np.isscalar(x):
463
+ return _ScaledLinearOperator(self, x)
464
+ else:
465
+ if not issparse(x) and not is_pydata_spmatrix(x):
466
+ # Sparse matrices shouldn't be converted to numpy arrays.
467
+ x = np.asarray(x)
468
+
469
+ if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1:
470
+ return self.matvec(x)
471
+ elif x.ndim == 2:
472
+ return self.matmat(x)
473
+ else:
474
+ raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}')
475
+
476
+ def __matmul__(self, other):
477
+ if np.isscalar(other):
478
+ raise ValueError("Scalar operands are not allowed, "
479
+ "use '*' instead")
480
+ return self.__mul__(other)
481
+
482
+ def __rmatmul__(self, other):
483
+ if np.isscalar(other):
484
+ raise ValueError("Scalar operands are not allowed, "
485
+ "use '*' instead")
486
+ return self.__rmul__(other)
487
+
488
+ def __rmul__(self, x):
489
+ if np.isscalar(x):
490
+ return _ScaledLinearOperator(self, x)
491
+ else:
492
+ return self._rdot(x)
493
+
494
+ def _rdot(self, x):
495
+ """Matrix-matrix or matrix-vector multiplication from the right.
496
+
497
+ Parameters
498
+ ----------
499
+ x : array_like
500
+ 1-d or 2-d array, representing a vector or matrix.
501
+
502
+ Returns
503
+ -------
504
+ xA : array
505
+ 1-d or 2-d array (depending on the shape of x) that represents
506
+ the result of applying this linear operator on x from the right.
507
+
508
+ Notes
509
+ -----
510
+ This is copied from dot to implement right multiplication.
511
+ """
512
+ if isinstance(x, LinearOperator):
513
+ return _ProductLinearOperator(x, self)
514
+ elif np.isscalar(x):
515
+ return _ScaledLinearOperator(self, x)
516
+ else:
517
+ if not issparse(x) and not is_pydata_spmatrix(x):
518
+ # Sparse matrices shouldn't be converted to numpy arrays.
519
+ x = np.asarray(x)
520
+
521
+ # We use transpose instead of rmatvec/rmatmat to avoid
522
+ # unnecessary complex conjugation if possible.
523
+ if x.ndim == 1 or x.ndim == 2 and x.shape[0] == 1:
524
+ return self.T.matvec(x.T).T
525
+ elif x.ndim == 2:
526
+ return self.T.matmat(x.T).T
527
+ else:
528
+ raise ValueError(f'expected 1-d or 2-d array or matrix, got {x!r}')
529
+
530
+ def __pow__(self, p):
531
+ if np.isscalar(p):
532
+ return _PowerLinearOperator(self, p)
533
+ else:
534
+ return NotImplemented
535
+
536
+ def __add__(self, x):
537
+ if isinstance(x, LinearOperator):
538
+ return _SumLinearOperator(self, x)
539
+ else:
540
+ return NotImplemented
541
+
542
+ def __neg__(self):
543
+ return _ScaledLinearOperator(self, -1)
544
+
545
+ def __sub__(self, x):
546
+ return self.__add__(-x)
547
+
548
+ def __repr__(self):
549
+ M,N = self.shape
550
+ if self.dtype is None:
551
+ dt = 'unspecified dtype'
552
+ else:
553
+ dt = 'dtype=' + str(self.dtype)
554
+
555
+ return '<%dx%d %s with %s>' % (M, N, self.__class__.__name__, dt)
556
+
557
+ def adjoint(self):
558
+ """Hermitian adjoint.
559
+
560
+ Returns the Hermitian adjoint of self, aka the Hermitian
561
+ conjugate or Hermitian transpose. For a complex matrix, the
562
+ Hermitian adjoint is equal to the conjugate transpose.
563
+
564
+ Can be abbreviated self.H instead of self.adjoint().
565
+
566
+ Returns
567
+ -------
568
+ A_H : LinearOperator
569
+ Hermitian adjoint of self.
570
+ """
571
+ return self._adjoint()
572
+
573
+ H = property(adjoint)
574
+
575
+ def transpose(self):
576
+ """Transpose this linear operator.
577
+
578
+ Returns a LinearOperator that represents the transpose of this one.
579
+ Can be abbreviated self.T instead of self.transpose().
580
+ """
581
+ return self._transpose()
582
+
583
+ T = property(transpose)
584
+
585
+ def _adjoint(self):
586
+ """Default implementation of _adjoint; defers to rmatvec."""
587
+ return _AdjointLinearOperator(self)
588
+
589
+ def _transpose(self):
590
+ """ Default implementation of _transpose; defers to rmatvec + conj"""
591
+ return _TransposedLinearOperator(self)
592
+
593
+
594
+ class _CustomLinearOperator(LinearOperator):
595
+ """Linear operator defined in terms of user-specified operations."""
596
+
597
+ def __init__(self, shape, matvec, rmatvec=None, matmat=None,
598
+ dtype=None, rmatmat=None):
599
+ super().__init__(dtype, shape)
600
+
601
+ self.args = ()
602
+
603
+ self.__matvec_impl = matvec
604
+ self.__rmatvec_impl = rmatvec
605
+ self.__rmatmat_impl = rmatmat
606
+ self.__matmat_impl = matmat
607
+
608
+ self._init_dtype()
609
+
610
+ def _matmat(self, X):
611
+ if self.__matmat_impl is not None:
612
+ return self.__matmat_impl(X)
613
+ else:
614
+ return super()._matmat(X)
615
+
616
+ def _matvec(self, x):
617
+ return self.__matvec_impl(x)
618
+
619
+ def _rmatvec(self, x):
620
+ func = self.__rmatvec_impl
621
+ if func is None:
622
+ raise NotImplementedError("rmatvec is not defined")
623
+ return self.__rmatvec_impl(x)
624
+
625
+ def _rmatmat(self, X):
626
+ if self.__rmatmat_impl is not None:
627
+ return self.__rmatmat_impl(X)
628
+ else:
629
+ return super()._rmatmat(X)
630
+
631
+ def _adjoint(self):
632
+ return _CustomLinearOperator(shape=(self.shape[1], self.shape[0]),
633
+ matvec=self.__rmatvec_impl,
634
+ rmatvec=self.__matvec_impl,
635
+ matmat=self.__rmatmat_impl,
636
+ rmatmat=self.__matmat_impl,
637
+ dtype=self.dtype)
638
+
639
+
640
+ class _AdjointLinearOperator(LinearOperator):
641
+ """Adjoint of arbitrary Linear Operator"""
642
+
643
+ def __init__(self, A):
644
+ shape = (A.shape[1], A.shape[0])
645
+ super().__init__(dtype=A.dtype, shape=shape)
646
+ self.A = A
647
+ self.args = (A,)
648
+
649
+ def _matvec(self, x):
650
+ return self.A._rmatvec(x)
651
+
652
+ def _rmatvec(self, x):
653
+ return self.A._matvec(x)
654
+
655
+ def _matmat(self, x):
656
+ return self.A._rmatmat(x)
657
+
658
+ def _rmatmat(self, x):
659
+ return self.A._matmat(x)
660
+
661
+ class _TransposedLinearOperator(LinearOperator):
662
+ """Transposition of arbitrary Linear Operator"""
663
+
664
+ def __init__(self, A):
665
+ shape = (A.shape[1], A.shape[0])
666
+ super().__init__(dtype=A.dtype, shape=shape)
667
+ self.A = A
668
+ self.args = (A,)
669
+
670
+ def _matvec(self, x):
671
+ # NB. np.conj works also on sparse matrices
672
+ return np.conj(self.A._rmatvec(np.conj(x)))
673
+
674
+ def _rmatvec(self, x):
675
+ return np.conj(self.A._matvec(np.conj(x)))
676
+
677
+ def _matmat(self, x):
678
+ # NB. np.conj works also on sparse matrices
679
+ return np.conj(self.A._rmatmat(np.conj(x)))
680
+
681
+ def _rmatmat(self, x):
682
+ return np.conj(self.A._matmat(np.conj(x)))
683
+
684
+ def _get_dtype(operators, dtypes=None):
685
+ if dtypes is None:
686
+ dtypes = []
687
+ for obj in operators:
688
+ if obj is not None and hasattr(obj, 'dtype'):
689
+ dtypes.append(obj.dtype)
690
+ return np.result_type(*dtypes)
691
+
692
+
693
+ class _SumLinearOperator(LinearOperator):
694
+ def __init__(self, A, B):
695
+ if not isinstance(A, LinearOperator) or \
696
+ not isinstance(B, LinearOperator):
697
+ raise ValueError('both operands have to be a LinearOperator')
698
+ if A.shape != B.shape:
699
+ raise ValueError(f'cannot add {A} and {B}: shape mismatch')
700
+ self.args = (A, B)
701
+ super().__init__(_get_dtype([A, B]), A.shape)
702
+
703
+ def _matvec(self, x):
704
+ return self.args[0].matvec(x) + self.args[1].matvec(x)
705
+
706
+ def _rmatvec(self, x):
707
+ return self.args[0].rmatvec(x) + self.args[1].rmatvec(x)
708
+
709
+ def _rmatmat(self, x):
710
+ return self.args[0].rmatmat(x) + self.args[1].rmatmat(x)
711
+
712
+ def _matmat(self, x):
713
+ return self.args[0].matmat(x) + self.args[1].matmat(x)
714
+
715
+ def _adjoint(self):
716
+ A, B = self.args
717
+ return A.H + B.H
718
+
719
+
720
+ class _ProductLinearOperator(LinearOperator):
721
+ def __init__(self, A, B):
722
+ if not isinstance(A, LinearOperator) or \
723
+ not isinstance(B, LinearOperator):
724
+ raise ValueError('both operands have to be a LinearOperator')
725
+ if A.shape[1] != B.shape[0]:
726
+ raise ValueError(f'cannot multiply {A} and {B}: shape mismatch')
727
+ super().__init__(_get_dtype([A, B]),
728
+ (A.shape[0], B.shape[1]))
729
+ self.args = (A, B)
730
+
731
+ def _matvec(self, x):
732
+ return self.args[0].matvec(self.args[1].matvec(x))
733
+
734
+ def _rmatvec(self, x):
735
+ return self.args[1].rmatvec(self.args[0].rmatvec(x))
736
+
737
+ def _rmatmat(self, x):
738
+ return self.args[1].rmatmat(self.args[0].rmatmat(x))
739
+
740
+ def _matmat(self, x):
741
+ return self.args[0].matmat(self.args[1].matmat(x))
742
+
743
+ def _adjoint(self):
744
+ A, B = self.args
745
+ return B.H @ A.H
746
+
747
+
748
+ class _ScaledLinearOperator(LinearOperator):
749
+ def __init__(self, A, alpha):
750
+ if not isinstance(A, LinearOperator):
751
+ raise ValueError('LinearOperator expected as A')
752
+ if not np.isscalar(alpha):
753
+ raise ValueError('scalar expected as alpha')
754
+ if isinstance(A, _ScaledLinearOperator):
755
+ A, alpha_original = A.args
756
+ # Avoid in-place multiplication so that we don't accidentally mutate
757
+ # the original prefactor.
758
+ alpha = alpha * alpha_original
759
+
760
+ dtype = _get_dtype([A], [type(alpha)])
761
+ super().__init__(dtype, A.shape)
762
+ self.args = (A, alpha)
763
+ # Note: args[1] is alpha (a scalar), so use `*` below, not `@`
764
+
765
+ def _matvec(self, x):
766
+ return self.args[1] * self.args[0].matvec(x)
767
+
768
+ def _rmatvec(self, x):
769
+ return np.conj(self.args[1]) * self.args[0].rmatvec(x)
770
+
771
+ def _rmatmat(self, x):
772
+ return np.conj(self.args[1]) * self.args[0].rmatmat(x)
773
+
774
+ def _matmat(self, x):
775
+ return self.args[1] * self.args[0].matmat(x)
776
+
777
+ def _adjoint(self):
778
+ A, alpha = self.args
779
+ return A.H * np.conj(alpha)
780
+
781
+
782
+ class _PowerLinearOperator(LinearOperator):
783
+ def __init__(self, A, p):
784
+ if not isinstance(A, LinearOperator):
785
+ raise ValueError('LinearOperator expected as A')
786
+ if A.shape[0] != A.shape[1]:
787
+ raise ValueError(f'square LinearOperator expected, got {A!r}')
788
+ if not isintlike(p) or p < 0:
789
+ raise ValueError('non-negative integer expected as p')
790
+
791
+ super().__init__(_get_dtype([A]), A.shape)
792
+ self.args = (A, p)
793
+
794
+ def _power(self, fun, x):
795
+ res = np.array(x, copy=True)
796
+ for i in range(self.args[1]):
797
+ res = fun(res)
798
+ return res
799
+
800
+ def _matvec(self, x):
801
+ return self._power(self.args[0].matvec, x)
802
+
803
+ def _rmatvec(self, x):
804
+ return self._power(self.args[0].rmatvec, x)
805
+
806
+ def _rmatmat(self, x):
807
+ return self._power(self.args[0].rmatmat, x)
808
+
809
+ def _matmat(self, x):
810
+ return self._power(self.args[0].matmat, x)
811
+
812
+ def _adjoint(self):
813
+ A, p = self.args
814
+ return A.H ** p
815
+
816
+
817
+ class MatrixLinearOperator(LinearOperator):
818
+ def __init__(self, A):
819
+ super().__init__(A.dtype, A.shape)
820
+ self.A = A
821
+ self.__adj = None
822
+ self.args = (A,)
823
+
824
+ def _matmat(self, X):
825
+ return self.A.dot(X)
826
+
827
+ def _adjoint(self):
828
+ if self.__adj is None:
829
+ self.__adj = _AdjointMatrixOperator(self.A)
830
+ return self.__adj
831
+
832
+
833
+ class _AdjointMatrixOperator(MatrixLinearOperator):
834
+ def __init__(self, adjoint_array):
835
+ self.A = adjoint_array.T.conj()
836
+ self.args = (adjoint_array,)
837
+ self.shape = adjoint_array.shape[1], adjoint_array.shape[0]
838
+
839
+ @property
840
+ def dtype(self):
841
+ return self.args[0].dtype
842
+
843
+ def _adjoint(self):
844
+ return MatrixLinearOperator(self.args[0])
845
+
846
+
847
+ class IdentityOperator(LinearOperator):
848
+ def __init__(self, shape, dtype=None):
849
+ super().__init__(dtype, shape)
850
+
851
+ def _matvec(self, x):
852
+ return x
853
+
854
+ def _rmatvec(self, x):
855
+ return x
856
+
857
+ def _rmatmat(self, x):
858
+ return x
859
+
860
+ def _matmat(self, x):
861
+ return x
862
+
863
+ def _adjoint(self):
864
+ return self
865
+
866
+
867
+ def aslinearoperator(A):
868
+ """Return A as a LinearOperator.
869
+
870
+ 'A' may be any of the following types:
871
+ - ndarray
872
+ - matrix
873
+ - sparse array (e.g. csr_array, lil_array, etc.)
874
+ - LinearOperator
875
+ - An object with .shape and .matvec attributes
876
+
877
+ See the LinearOperator documentation for additional information.
878
+
879
+ Notes
880
+ -----
881
+ If 'A' has no .dtype attribute, the data type is determined by calling
882
+ :func:`LinearOperator.matvec()` - set the .dtype attribute to prevent this
883
+ call upon the linear operator creation.
884
+
885
+ Examples
886
+ --------
887
+ >>> import numpy as np
888
+ >>> from scipy.sparse.linalg import aslinearoperator
889
+ >>> M = np.array([[1,2,3],[4,5,6]], dtype=np.int32)
890
+ >>> aslinearoperator(M)
891
+ <2x3 MatrixLinearOperator with dtype=int32>
892
+ """
893
+ if isinstance(A, LinearOperator):
894
+ return A
895
+
896
+ elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):
897
+ if A.ndim > 2:
898
+ raise ValueError('array must have ndim <= 2')
899
+ A = np.atleast_2d(np.asarray(A))
900
+ return MatrixLinearOperator(A)
901
+
902
+ elif issparse(A) or is_pydata_spmatrix(A):
903
+ return MatrixLinearOperator(A)
904
+
905
+ else:
906
+ if hasattr(A, 'shape') and hasattr(A, 'matvec'):
907
+ rmatvec = None
908
+ rmatmat = None
909
+ dtype = None
910
+
911
+ if hasattr(A, 'rmatvec'):
912
+ rmatvec = A.rmatvec
913
+ if hasattr(A, 'rmatmat'):
914
+ rmatmat = A.rmatmat
915
+ if hasattr(A, 'dtype'):
916
+ dtype = A.dtype
917
+ return LinearOperator(A.shape, A.matvec, rmatvec=rmatvec,
918
+ rmatmat=rmatmat, dtype=dtype)
919
+
920
+ else:
921
+ raise TypeError('type not understood')
shared/package-files/8b/8b9f6fe4750edf6e8b848fb49cfa169d2cafe88b2e0ddff1469e0d744bbc1946/blob ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import math
3
+ import sys
4
+
5
+ from numba import jit, types
6
+ from numba.tests.support import TestCase, skip_unless_py314_or_later
7
+ from .complex_usecases import *
8
+ import unittest
9
+
10
+ enable_pyobj_flags = {'forceobj': True}
11
+ no_pyobj_flags = {'nopython': True}
12
+
13
+
14
+ class BaseComplexTest(object):
15
+
16
+ def basic_values(self):
17
+ reals = [-0.0, +0.0, 1, -1, +1.5, -3.5,
18
+ float('-inf'), float('+inf')]
19
+ if sys.platform != 'win32':
20
+ reals += [float('nan')]
21
+ return [complex(x, y) for x, y in itertools.product(reals, reals)]
22
+
23
+ def more_values(self):
24
+ reals = [-0.0, +0.0, 1, -1, -math.pi, +math.pi,
25
+ float('-inf'), float('+inf')]
26
+ if sys.platform != 'win32':
27
+ reals += [float('nan')]
28
+ return [complex(x, y) for x, y in itertools.product(reals, reals)]
29
+
30
+ def non_nan_values(self):
31
+ reals = [-0.0, +0.0, 1, -1, -math.pi, +math.pi,
32
+ float('inf'), float('-inf')]
33
+ return [complex(x, y) for x, y in itertools.product(reals, reals)]
34
+
35
+ def run_unary(self, pyfunc, x_types, x_values, ulps=1, abs_tol=None,
36
+ flags=enable_pyobj_flags):
37
+ for tx in x_types:
38
+ cfunc = jit((tx,), **flags)(pyfunc)
39
+ prec = 'single' if tx in (types.float32, types.complex64) else 'double'
40
+ for vx in x_values:
41
+ try:
42
+ expected = pyfunc(vx)
43
+ except ValueError as e:
44
+ self.assertIn("math domain error", str(e))
45
+ continue
46
+ got = cfunc(vx)
47
+ msg = 'for input %r with prec %r' % (vx, prec)
48
+ self.assertPreciseEqual(got, expected, prec=prec,
49
+ ulps=ulps, abs_tol=abs_tol, msg=msg)
50
+
51
+ def run_binary(self, pyfunc, value_types, values, ulps=1,
52
+ flags=enable_pyobj_flags):
53
+ for tx, ty in value_types:
54
+ cfunc = jit((tx, ty), **flags)(pyfunc)
55
+ prec = ('single'
56
+ if set([tx, ty]) & set([types.float32, types.complex64])
57
+ else 'double')
58
+ for vx, vy in values:
59
+ try:
60
+ expected = pyfunc(vx, vy)
61
+ except ValueError as e:
62
+ self.assertIn("math domain error", str(e))
63
+ continue
64
+ except ZeroDivisionError:
65
+ continue
66
+ got = cfunc(vx, vy)
67
+ msg = 'for input %r with prec %r' % ((vx, vy), prec)
68
+ self.assertPreciseEqual(got, expected, prec=prec,
69
+ ulps=ulps, msg=msg)
70
+
71
+
72
+ class TestComplex(BaseComplexTest, TestCase):
73
+
74
+ def test_real(self, flags=enable_pyobj_flags):
75
+ self.run_unary(real_usecase, [types.complex64, types.complex128],
76
+ self.basic_values(), flags=flags)
77
+ self.run_unary(real_usecase, [types.int8, types.int64],
78
+ [1, 0, -3], flags=flags)
79
+ self.run_unary(real_usecase, [types.float32, types.float64],
80
+ [1.5, -0.5], flags=flags)
81
+
82
+ def test_real_npm(self):
83
+ self.test_real(flags=no_pyobj_flags)
84
+
85
+ def test_imag(self, flags=enable_pyobj_flags):
86
+ self.run_unary(imag_usecase, [types.complex64, types.complex128],
87
+ self.basic_values(), flags=flags)
88
+ self.run_unary(imag_usecase, [types.int8, types.int64],
89
+ [1, 0, -3], flags=flags)
90
+ self.run_unary(imag_usecase, [types.float32, types.float64],
91
+ [1.5, -0.5], flags=flags)
92
+
93
+ def test_imag_npm(self):
94
+ self.test_imag(flags=no_pyobj_flags)
95
+
96
+ def test_conjugate(self, flags=enable_pyobj_flags):
97
+ self.run_unary(conjugate_usecase, [types.complex64, types.complex128],
98
+ self.basic_values(), flags=flags)
99
+ self.run_unary(conjugate_usecase, [types.int8, types.int64],
100
+ [1, 0, -3], flags=flags)
101
+ self.run_unary(conjugate_usecase, [types.float32, types.float64],
102
+ [1.5, -0.5], flags=flags)
103
+
104
+ def test_conjugate_npm(self):
105
+ self.test_conjugate(flags=no_pyobj_flags)
106
+
107
+ def test_div(self, flags=enable_pyobj_flags):
108
+ """
109
+ Test complex.__div__ implementation with non-trivial values.
110
+ """
111
+ # XXX Fold into test_operator?
112
+ values = list(itertools.product(self.more_values(), self.more_values()))
113
+ value_types = [(types.complex128, types.complex128),
114
+ (types.complex64, types.complex64)]
115
+ self.run_binary(div_usecase, value_types, values, flags=flags)
116
+
117
+ def test_div_npm(self):
118
+ self.test_div(flags=no_pyobj_flags)
119
+
120
+
121
+ @skip_unless_py314_or_later
122
+ class TestComplexNaNRecovery(BaseComplexTest, TestCase):
123
+ """
124
+ Verify CPython NaN-recovery for complex mul / div.
125
+ """
126
+
127
+ def special_values(self):
128
+ # 1e200 (large finite) is here so mul can overflow before recovering
129
+ reals = [-0.0, +0.0, 1, -1, 1e200,
130
+ float('-inf'), float('+inf'), float('nan')]
131
+ return [complex(x, y) for x, y in itertools.product(reals, reals)]
132
+
133
+ def test_mul(self, flags=no_pyobj_flags):
134
+ values = list(itertools.product(self.special_values(),
135
+ self.special_values()))
136
+ value_types = [(types.complex128, types.complex128)]
137
+ self.run_binary(mul_usecase, value_types, values, flags=flags)
138
+
139
+ def test_div(self, flags=no_pyobj_flags):
140
+ values = list(itertools.product(self.special_values(),
141
+ self.special_values()))
142
+ value_types = [(types.complex128, types.complex128)]
143
+ self.run_binary(div_usecase, value_types, values, flags=flags)
144
+
145
+ def test_div_zero(self, flags=no_pyobj_flags):
146
+ cfunc = jit((types.complex128, types.complex128), **flags)(div_usecase)
147
+ for denom in [0j, complex(0.0, 0.0), complex(-0.0, -0.0),
148
+ complex(0.0, -0.0), complex(-0.0, 0.0)]:
149
+ with self.assertRaises(ZeroDivisionError):
150
+ cfunc(1+1j, denom)
151
+
152
+
153
+ class TestCMath(BaseComplexTest, TestCase):
154
+ """
155
+ Tests for cmath module support.
156
+ """
157
+
158
+ def check_predicate_func(self, pyfunc, flags):
159
+ self.run_unary(pyfunc, [types.complex128, types.complex64],
160
+ self.basic_values(), flags=flags)
161
+
162
+ def check_unary_func(self, pyfunc, flags, ulps=1, abs_tol=None,
163
+ values=None):
164
+ self.run_unary(pyfunc, [types.complex128],
165
+ values or self.more_values(), flags=flags, ulps=ulps,
166
+ abs_tol=abs_tol)
167
+ # Avoid discontinuities around pi when in single precision.
168
+ self.run_unary(pyfunc, [types.complex64],
169
+ values or self.basic_values(), flags=flags, ulps=ulps,
170
+ abs_tol=abs_tol)
171
+
172
+ # Conversions
173
+
174
+ def test_phase(self):
175
+ self.check_unary_func(phase_usecase, enable_pyobj_flags)
176
+
177
+ def test_phase_npm(self):
178
+ self.check_unary_func(phase_usecase, no_pyobj_flags)
179
+
180
+ def test_polar(self):
181
+ self.check_unary_func(polar_usecase, enable_pyobj_flags)
182
+
183
+ def test_polar_npm(self):
184
+ self.check_unary_func(polar_usecase, no_pyobj_flags)
185
+
186
+ def test_rect(self, flags=enable_pyobj_flags):
187
+ def do_test(tp, seed_values):
188
+ values = [(z.real, z.imag) for z in seed_values
189
+ if not math.isinf(z.imag) or z.real == 0]
190
+ self.run_binary(rect_usecase, [(tp, tp)], values, flags=flags)
191
+ do_test(types.float64, self.more_values())
192
+ # Avoid discontinuities around pi when in single precision.
193
+ do_test(types.float32, self.basic_values())
194
+
195
+ def test_rect_npm(self):
196
+ self.test_rect(flags=no_pyobj_flags)
197
+
198
+ # Classification
199
+
200
+ def test_isnan(self, flags=enable_pyobj_flags):
201
+ self.check_predicate_func(isnan_usecase, enable_pyobj_flags)
202
+
203
+ def test_isnan_npm(self):
204
+ self.check_predicate_func(isnan_usecase, no_pyobj_flags)
205
+
206
+ def test_isinf(self, flags=enable_pyobj_flags):
207
+ self.check_predicate_func(isinf_usecase, enable_pyobj_flags)
208
+
209
+ def test_isinf_npm(self):
210
+ self.check_predicate_func(isinf_usecase, no_pyobj_flags)
211
+
212
+ def test_isfinite(self, flags=enable_pyobj_flags):
213
+ self.check_predicate_func(isfinite_usecase, enable_pyobj_flags)
214
+
215
+ def test_isfinite_npm(self):
216
+ self.check_predicate_func(isfinite_usecase, no_pyobj_flags)
217
+
218
+ # Power and logarithms
219
+
220
+ def test_exp(self):
221
+ self.check_unary_func(exp_usecase, enable_pyobj_flags, ulps=2)
222
+
223
+ def test_exp_npm(self):
224
+ # Aggressive optimization fixes the following subnormal float problem.
225
+ ## The two tests are failing due to subnormal float problems.
226
+ ## We are seeing (6.9532198665326e-310+2.1221202807e-314j) != 0j
227
+ self.check_unary_func(exp_usecase, no_pyobj_flags, ulps=2)
228
+
229
+ def test_log(self):
230
+ self.check_unary_func(log_usecase, enable_pyobj_flags)
231
+
232
+ def test_log_npm(self):
233
+ self.check_unary_func(log_usecase, no_pyobj_flags)
234
+
235
+ def test_log_base(self, flags=enable_pyobj_flags):
236
+ values = list(itertools.product(self.more_values(), self.more_values()))
237
+ value_types = [(types.complex128, types.complex128),
238
+ (types.complex64, types.complex64)]
239
+ self.run_binary(log_base_usecase, value_types, values, flags=flags,
240
+ ulps=3)
241
+
242
+ def test_log_base_npm(self):
243
+ self.test_log_base(flags=no_pyobj_flags)
244
+
245
+ def test_log10(self):
246
+ self.check_unary_func(log10_usecase, enable_pyobj_flags)
247
+
248
+ def test_log10_npm(self):
249
+ self.check_unary_func(log10_usecase, no_pyobj_flags)
250
+
251
+ def test_sqrt(self):
252
+ self.check_unary_func(sqrt_usecase, enable_pyobj_flags)
253
+
254
+ def test_sqrt_npm(self):
255
+ self.check_unary_func(sqrt_usecase, no_pyobj_flags)
256
+ # issue #3499, check large complex128 values, values cross the float32
257
+ # representation limit threshold
258
+ values = [-10 ** i for i in range(36, 41)]
259
+ self.run_unary(sqrt_usecase, [types.complex128],
260
+ values, flags=no_pyobj_flags)
261
+
262
+ # Trigonometric functions
263
+
264
+ def test_acos(self):
265
+ self.check_unary_func(acos_usecase, enable_pyobj_flags, ulps=2)
266
+
267
+ def test_acos_npm(self):
268
+ self.check_unary_func(acos_usecase, no_pyobj_flags, ulps=2)
269
+
270
+ def test_asin(self):
271
+ self.check_unary_func(asin_usecase, enable_pyobj_flags, ulps=2)
272
+
273
+ def test_asin_npm(self):
274
+ self.check_unary_func(asin_usecase, no_pyobj_flags, ulps=2)
275
+
276
+ def test_atan(self):
277
+ self.check_unary_func(atan_usecase, enable_pyobj_flags, ulps=2,)
278
+
279
+ def test_atan_npm(self):
280
+ self.check_unary_func(atan_usecase, no_pyobj_flags, ulps=2,)
281
+
282
+ def test_cos(self):
283
+ self.check_unary_func(cos_usecase, enable_pyobj_flags, ulps=2)
284
+
285
+ def test_cos_npm(self):
286
+ self.check_unary_func(cos_usecase, no_pyobj_flags, ulps=2)
287
+
288
+ def test_sin(self):
289
+ # See test_sinh.
290
+ self.check_unary_func(sin_usecase, enable_pyobj_flags, abs_tol='eps')
291
+
292
+ def test_sin_npm(self):
293
+ self.check_unary_func(sin_usecase, no_pyobj_flags, abs_tol='eps')
294
+
295
+ def test_tan(self):
296
+ self.check_unary_func(tan_usecase, enable_pyobj_flags, ulps=2)
297
+
298
+ def test_tan_npm(self):
299
+ self.check_unary_func(tan_usecase, enable_pyobj_flags, ulps=2)
300
+
301
+ # Hyperbolic functions
302
+
303
+ def test_acosh(self):
304
+ self.check_unary_func(acosh_usecase, enable_pyobj_flags)
305
+
306
+ def test_acosh_npm(self):
307
+ self.check_unary_func(acosh_usecase, no_pyobj_flags)
308
+
309
+ def test_asinh(self):
310
+ self.check_unary_func(asinh_usecase, enable_pyobj_flags, ulps=2)
311
+
312
+ def test_asinh_npm(self):
313
+ self.check_unary_func(asinh_usecase, no_pyobj_flags, ulps=2)
314
+
315
+ def test_atanh(self):
316
+ self.check_unary_func(atanh_usecase, enable_pyobj_flags, ulps=2)
317
+
318
+ def test_atanh_npm(self):
319
+ self.check_unary_func(atanh_usecase, no_pyobj_flags, ulps=2)
320
+
321
+ def test_cosh(self):
322
+ self.check_unary_func(cosh_usecase, enable_pyobj_flags, ulps=2)
323
+
324
+ def test_cosh_npm(self):
325
+ self.check_unary_func(cosh_usecase, no_pyobj_flags, ulps=2)
326
+
327
+ def test_sinh(self):
328
+ self.check_unary_func(sinh_usecase, enable_pyobj_flags, abs_tol='eps')
329
+
330
+ def test_sinh_npm(self):
331
+ self.check_unary_func(sinh_usecase, no_pyobj_flags, abs_tol='eps')
332
+
333
+ def test_tanh(self):
334
+ self.check_unary_func(tanh_usecase, enable_pyobj_flags, ulps=2)
335
+
336
+ def test_tanh_npm(self):
337
+ self.check_unary_func(tanh_usecase, enable_pyobj_flags, ulps=2)
338
+
339
+
340
+ if __name__ == '__main__':
341
+ unittest.main()
shared/package-files/8b/8b9fc65039f9df190eb3bfc0d68cdc0eed6070fa2b21afe4c48288f1988068d0/blob ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from .expanded_weights_impl import implements_per_sample_grads
4
+ from .expanded_weights_utils import \
5
+ forward_helper, set_grad_sample_if_exists, unpack_expanded_weight_or_tensor, is_batch_first
6
+ from typing import List, Optional
7
+
8
+ @implements_per_sample_grads(F.linear)
9
+ class LinearPerSampleGrad(torch.autograd.Function):
10
+ @staticmethod
11
+ def forward(ctx, _, __, *expanded_args_and_kwargs):
12
+ if len(expanded_args_and_kwargs[0].shape) <= 1:
13
+ raise RuntimeError("Input does not have a batch dimension. Expanded Weights expected input "
14
+ f"of at least rank 2, got of rank {len(expanded_args_and_kwargs[0].shape)}")
15
+ expanded_kwargs = {'bias': expanded_args_and_kwargs[2] if len(expanded_args_and_kwargs) == 3 else None}
16
+ expanded_args = expanded_args_and_kwargs[:2]
17
+ ctx.batch_first = is_batch_first(expanded_args_and_kwargs)
18
+ output = forward_helper(F.linear, expanded_args, expanded_kwargs)
19
+ ctx.args = expanded_args
20
+ ctx.kwargs = expanded_kwargs
21
+ return output
22
+
23
+ @staticmethod
24
+ def backward(ctx, grad_output):
25
+ input, weight = ctx.args
26
+ bias = ctx.kwargs['bias']
27
+ results: List[Optional[torch.Tensor]] = []
28
+ results.append(None) # for kwarg_names
29
+ results.append(None) # for op reference
30
+
31
+ if input.requires_grad:
32
+ results.append(grad_output.matmul(unpack_expanded_weight_or_tensor(weight)))
33
+ else:
34
+ results.append(None)
35
+ results.extend([None] * 2) # weight and bias don't compute batched gradients
36
+
37
+ if not ctx.batch_first:
38
+ grad_output = grad_output.transpose(0, 1)
39
+ input = input.transpose(0, 1)
40
+
41
+ # weight and bias get their grad_sample fields set directly if they exist
42
+ set_grad_sample_if_exists(weight, lambda _: torch.einsum("n...i,n...j->nij", grad_output, input))
43
+ set_grad_sample_if_exists(bias, lambda _: torch.einsum("n...k->nk", grad_output))
44
+ return tuple(results)
shared/package-files/8b/8b9fd73515667141ecfc6067f2b27f4a4afb3340139b737521f811d33c8a523b/blob ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import functools
4
+ from typing import Any
5
+
6
+ import narwhals.stable.v1 as narwhals
7
+ import numpy
8
+ import pandas
9
+
10
+
11
+ @functools.singledispatch
12
+ def lag(data: Any, k: int = 1) -> Any:
13
+ """
14
+ Shift the data indices forward or backward by the specified number of
15
+ intervals.
16
+
17
+ Args:
18
+ data: The array-like dataset to be lagged along its first axis.
19
+ k: The number of intervals to shift back the observations by. For "lead"
20
+ shifts, use negative integers.
21
+
22
+ Notes:
23
+ * For this transform to make sense, `data` must represent a time-series
24
+ collected at regularly spaced intervals.
25
+ * `k` is chosen as the offset parameter for compatibility with R.
26
+ """
27
+ raise NotImplementedError(
28
+ f"No implementation of `lag` for data of type {type(data)}."
29
+ )
30
+
31
+
32
+ @lag.register
33
+ def _(data: pandas.Series, offset: int = 1) -> pandas.Series:
34
+ return data.shift(offset)
35
+
36
+
37
+ @lag.register
38
+ def _(data: numpy.ndarray, offset: int = 1) -> numpy.ndarray:
39
+ if data.shape == () or offset == 0:
40
+ return data
41
+
42
+ data = numpy.copy(data).astype(float)
43
+
44
+ if offset > 0:
45
+ data[offset:] = data[:-offset]
46
+ data[:offset] = numpy.nan
47
+ else:
48
+ data[:offset] = data[-offset:]
49
+ data[offset:] = numpy.nan
50
+
51
+ return data
52
+
53
+
54
+ @lag.register
55
+ def _(data: narwhals.Series, offset: int = 1) -> narwhals.Series:
56
+ return data.shift(offset)
shared/package-files/8b/8ba054d3b7ea9a8fd954531d3abe5cbaf18bfa0e635d39c7082e31ab2a021ba0/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API bool _use_cudnn_rnn_flatten_weight();
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
shared/package-files/8b/8ba3d5ba862412d7d509da7ad8828cfba503ea44e5e04c88b39e86fa3ddd455e/blob ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import copy
3
+ import functools
4
+ import logging
5
+ import os
6
+ import shutil
7
+ import sys
8
+ import textwrap
9
+ from importlib import import_module
10
+ from typing import Union
11
+
12
+ import torch
13
+ import torch.fx as fx
14
+
15
+ from torch._dynamo.debug_utils import (
16
+ AccuracyError,
17
+ backend_accuracy_fails,
18
+ BUCK_CMD_PREFIX,
19
+ BuckTargetWriter,
20
+ extra_imports,
21
+ generate_config_string,
22
+ helper_for_dump_minify,
23
+ InputReader,
24
+ InputWriter,
25
+ minifier_dir,
26
+ NNModuleToString,
27
+ NopInputReader,
28
+ run_fwd_maybe_bwd,
29
+ same_two_models,
30
+ )
31
+ from torch.fx.experimental.symbolic_shapes import fx_placeholder_targets
32
+ from torch.hub import tqdm
33
+
34
+ from .. import config
35
+ from ..backends.registry import lookup_backend, register_debug_backend
36
+ from ..debug_utils import clone_inputs_retaining_gradness
37
+
38
+ log = logging.getLogger(__name__)
39
+
40
+
41
+ inductor_config = import_module("torch._inductor.config")
42
+ use_buck = inductor_config.is_fbcode()
43
+
44
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
45
+ # MAIN ENTRY POINT
46
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
47
+
48
+
49
+ def wrap_backend_debug(unconfigured_compiler_fn, compiler_name: str):
50
+ """
51
+ A minifier decorator that wraps the TorchDynamo produced Fx graph modules.
52
+ As opposed to wrap_compiler_debug, this wrapper intercepts at the
53
+ TorchDynamo produced Fx Graph Module. This makes it backend-agnostic to some
54
+ level, e.g., it is useful for minifying issues related to Aot Autograd
55
+ tracing. If an error is found, we minify and save the minified repro in
56
+ repro.tar.gz.
57
+ """
58
+
59
+ @functools.wraps(unconfigured_compiler_fn)
60
+ def debug_wrapper(gm, example_inputs, **kwargs):
61
+ compiler_fn = functools.partial(unconfigured_compiler_fn, **kwargs)
62
+ assert config.repro_after in ("dynamo", "aot", None)
63
+
64
+ if config.repro_after == "dynamo":
65
+
66
+ def add_paths(exc):
67
+ exc.minifier_path = os.path.join(minifier_dir(), "minifier_launcher.py")
68
+ if use_buck:
69
+ exc.buck_command = " ".join(
70
+ BUCK_CMD_PREFIX
71
+ + [BuckTargetWriter(exc.minifier_path).cmd_line_path]
72
+ )
73
+
74
+ if config.repro_level == 3:
75
+ dump_to_minify_after_dynamo(gm, example_inputs, compiler_name)
76
+
77
+ # Check for either accuracy (level 4) or other type of failures.
78
+ if config.repro_level == 4:
79
+ # Check Accuracy
80
+ compiled_gm = compiler_fn(copy.deepcopy(gm), example_inputs)
81
+ if backend_accuracy_fails(gm, example_inputs, compiler_fn):
82
+ log.warning(
83
+ "Accuracy failed for the TorchDynamo produced graph. Creating script to minify the error."
84
+ )
85
+ dump_to_minify_after_dynamo(
86
+ fx.GraphModule(gm, copy.deepcopy(gm.graph)),
87
+ example_inputs,
88
+ compiler_name,
89
+ )
90
+ exc = AccuracyError("Bad accuracy detected.")
91
+ add_paths(exc)
92
+ raise exc
93
+ else:
94
+ try:
95
+ compiled_gm = compiler_fn(copy.deepcopy(gm), example_inputs)
96
+ run_fwd_maybe_bwd(compiled_gm, example_inputs)
97
+ except Exception as exc:
98
+ log.warning(
99
+ "Compiled Fx GraphModule failed. Creating script to minify the error."
100
+ )
101
+ if config.repro_level == 1:
102
+ dump_state_fn = functools.partial(
103
+ dump_backend_state, compiler_name=compiler_name
104
+ )
105
+ dump_state_fn(
106
+ fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs
107
+ )
108
+ elif config.repro_level == 2:
109
+ dump_to_minify_after_dynamo(
110
+ fx.GraphModule(gm, copy.deepcopy(gm.graph)),
111
+ example_inputs,
112
+ compiler_name,
113
+ )
114
+ add_paths(exc)
115
+ raise
116
+ else:
117
+ compiled_gm = compiler_fn(gm, example_inputs)
118
+
119
+ return compiled_gm
120
+
121
+ debug_wrapper._torchdynamo_orig_callable = unconfigured_compiler_fn # type: ignore[attr-defined]
122
+ if hasattr(unconfigured_compiler_fn, "compiler_name"):
123
+ debug_wrapper.__name__ = unconfigured_compiler_fn.compiler_name
124
+ if hasattr(unconfigured_compiler_fn, "get_compiler_config"):
125
+ debug_wrapper.get_compiler_config = unconfigured_compiler_fn.get_compiler_config # type: ignore[attr-defined]
126
+ return debug_wrapper
127
+
128
+
129
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
130
+ # REPRO DUMPERS
131
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
132
+
133
+
134
+ def generate_dynamo_fx_repro_string(
135
+ gm,
136
+ args,
137
+ compiler_name,
138
+ check_accuracy=False,
139
+ *,
140
+ stable_output=False,
141
+ save_dir=None,
142
+ command="run",
143
+ ):
144
+ """
145
+ Generate a repro string for backend-agnostic minified version.
146
+ """
147
+
148
+ model_str = NNModuleToString.convert(gm)
149
+
150
+ # TODO: Figure out why torch.compile'd hash isn't work on this codepath
151
+ writer = InputWriter(save_dir, stable_hash=True)
152
+ for placeholder, arg in zip(fx_placeholder_targets(gm), args):
153
+ if isinstance(arg, (int, torch.SymInt)):
154
+ writer.symint(placeholder, arg)
155
+ elif isinstance(arg, torch.Tensor):
156
+ # TODO: improve these names with FQN
157
+ writer.tensor(placeholder, arg)
158
+ else:
159
+ raise TypeError(f"arg is neither SymInt/int nor torch.Tensor, {arg}")
160
+ load_args = "\n".join(writer.lines())
161
+
162
+ return textwrap.dedent(
163
+ f"""
164
+ from math import inf
165
+ import torch
166
+ from torch import tensor, device
167
+ import torch.fx as fx
168
+ import torch._dynamo
169
+ from torch._dynamo.testing import rand_strided
170
+ from torch._dynamo.debug_utils import run_fwd_maybe_bwd
171
+
172
+ {generate_config_string(stable_output=stable_output)}
173
+
174
+ {extra_imports}
175
+
176
+ {model_str}
177
+ mod = Repro()
178
+
179
+ {load_args}
180
+
181
+ if __name__ == '__main__':
182
+ from torch._dynamo.repro.after_dynamo import run_repro
183
+ run_repro(mod, load_args, accuracy={check_accuracy!r}, command={command!r},
184
+ save_dir={save_dir!r}, autocast={torch.is_autocast_enabled()!r}, backend={compiler_name!r})
185
+ """
186
+ )
187
+
188
+
189
+ def dump_backend_repro_as_file(gm, args, compiler_name, check_accuracy=False):
190
+ """
191
+ Saves the repro to a repro.py file
192
+ """
193
+ curdir = os.getcwd()
194
+ subdir = os.path.join(os.getcwd(), "checkpoints")
195
+ if not os.path.exists(subdir):
196
+ os.makedirs(subdir, exist_ok=True)
197
+ file_name = os.path.join(subdir, f"minified_{len(gm.graph.nodes)}_nodes.py")
198
+ log.warning(
199
+ "Writing checkpoint with %s nodes to %s", len(gm.graph.nodes), file_name
200
+ )
201
+
202
+ with open(file_name, "w") as fd:
203
+ fd.write(
204
+ generate_dynamo_fx_repro_string(
205
+ gm, args, compiler_name, check_accuracy, save_dir=subdir
206
+ )
207
+ )
208
+ latest_repro = os.path.join(curdir, "repro.py")
209
+ log.warning("Copying %s to %s for convenience", file_name, latest_repro)
210
+
211
+ if use_buck:
212
+ BuckTargetWriter(latest_repro).write()
213
+
214
+ shutil.copyfile(file_name, latest_repro)
215
+
216
+
217
+ def dump_backend_state(gm, args, compiler_name, check_accuracy=False):
218
+ """
219
+ Dumps the dynamo graph to repro the issue.
220
+ 1) It tries to convert Fx GraphModule to a string. If we can, it writes to a
221
+ repro.py file.
222
+ 2) If we can't convert Fx GraphModule to a string, we use to_folder to save
223
+ the module and save a tar file.
224
+ """
225
+ assert NNModuleToString.can_convert_to_string(gm)
226
+ return dump_backend_repro_as_file(gm, args, compiler_name, check_accuracy)
227
+ # return dump_backend_repro_as_tarfile(gm, args, compiler_name)
228
+
229
+
230
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
231
+ # MINIFIER DUMPER
232
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
233
+
234
+
235
+ def dump_to_minify_after_dynamo(gm, args, compiler_name):
236
+ # TODO: factor this out
237
+ subdir = os.path.join(minifier_dir(), "checkpoints")
238
+ if not os.path.exists(subdir):
239
+ os.makedirs(subdir, exist_ok=True)
240
+ helper_for_dump_minify(
241
+ generate_dynamo_fx_repro_string(
242
+ gm,
243
+ args,
244
+ compiler_name,
245
+ check_accuracy=config.repro_level == 4,
246
+ save_dir=subdir,
247
+ command="minify",
248
+ )
249
+ )
250
+
251
+
252
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
253
+ # MINIFIER BACKENDS
254
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
255
+
256
+
257
+ @register_debug_backend
258
+ def dynamo_minifier_backend(gm, example_inputs, compiler_name):
259
+ from functorch.compile import minifier
260
+
261
+ compiler_fn = lookup_backend(compiler_name)
262
+
263
+ # TODO: It's inconsistent to pass SymInt inputs but REAL tensors.
264
+ # We should pass ints and look at the GraphModule placeholders
265
+ # to resolve them to SymInt (if necessary)
266
+ example_inputs = [
267
+ i.node.hint if isinstance(i, torch.SymInt) else i for i in example_inputs
268
+ ]
269
+
270
+ try:
271
+ compiled_gm = compiler_fn(gm, example_inputs)
272
+ run_fwd_maybe_bwd(compiled_gm, example_inputs)
273
+ raise ValueError("No issue was detected")
274
+ except Exception as exc:
275
+ orig_failure = str(exc)
276
+ log.warning(
277
+ "Compiled Fx GraphModule failed. Creating script to minify the error."
278
+ )
279
+ dump_state_fn = functools.partial(
280
+ dump_backend_state, compiler_name=compiler_name
281
+ )
282
+ dump_state_fn(fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs)
283
+ fails_fn = functools.partial(
284
+ backend_fails,
285
+ compiler_fn=compiler_fn,
286
+ orig_failure=orig_failure,
287
+ )
288
+ minifier(
289
+ gm,
290
+ example_inputs,
291
+ module_fails=fails_fn,
292
+ dump_state=dump_state_fn,
293
+ )
294
+ return gm
295
+
296
+
297
+ @register_debug_backend
298
+ def dynamo_accuracy_minifier_backend(gm, example_inputs, compiler_name):
299
+ from functorch.compile import minifier
300
+
301
+ compiler_fn = lookup_backend(compiler_name)
302
+
303
+ # Set the eval mode to remove randomness.
304
+ gm.eval()
305
+
306
+ # Check Accuracy
307
+ if backend_accuracy_fails(
308
+ gm, example_inputs, compiler_fn, only_fwd=config.repro_forward_only
309
+ ):
310
+ log.warning("Accuracy failed for the TorchDynamo produced graph")
311
+ dump_state_fn = functools.partial(
312
+ dump_backend_state, compiler_name=compiler_name, check_accuracy=True
313
+ )
314
+ fails_fn = functools.partial(
315
+ backend_accuracy_fails,
316
+ compiler_fn=compiler_fn,
317
+ only_fwd=config.repro_forward_only,
318
+ )
319
+ dump_state_fn(fx.GraphModule(gm, copy.deepcopy(gm.graph)), example_inputs)
320
+ minifier(
321
+ gm,
322
+ example_inputs,
323
+ module_fails=fails_fn,
324
+ dump_state=dump_state_fn,
325
+ )
326
+ else:
327
+ log.error("Input graph does not fail accuracy testing")
328
+ return gm
329
+
330
+
331
+ def backend_fails(gm, example_inputs, compiler_fn, orig_failure):
332
+ """
333
+ Minifier uses this function to identify if the minified graph module fails
334
+ with the same error.
335
+
336
+ One caveat is that minifier can potentially go into a wrong direction when
337
+ the resulting graph module fails for a different reason. To avoid this, we
338
+ save the string for the original exception and check similarity between new
339
+ and old exception. They can be somewhat different in some cases, when the
340
+ exception string depends on the failing node information. So, we have a
341
+ loose similarity metric to guide the minifier path.
342
+ """
343
+ from difflib import SequenceMatcher
344
+
345
+ try:
346
+ # Run the original gm to check eager validity
347
+ run_fwd_maybe_bwd(gm, clone_inputs_retaining_gradness(example_inputs))
348
+ compiled_gm = compiler_fn(gm, example_inputs)
349
+ run_fwd_maybe_bwd(compiled_gm, clone_inputs_retaining_gradness(example_inputs))
350
+ return False
351
+ except Exception as e:
352
+ new_failure = str(e)
353
+ if SequenceMatcher(None, orig_failure, new_failure).ratio() > 0.5:
354
+ return True
355
+ return False
356
+
357
+
358
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
359
+ # REPRO MAIN
360
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
361
+
362
+
363
+ def run_load_args(options, mod, load_args):
364
+ if not hasattr(load_args, "_version"):
365
+ log.warning(
366
+ "load_args does not have a _version attribute, please file a bug to PyTorch "
367
+ "and describe how you generate this repro script"
368
+ )
369
+ else:
370
+ if load_args._version > 0:
371
+ log.warning(
372
+ "load_args is version %s, but this version of PyTorch only supports "
373
+ "version 0. We will try to run it anyway but there may be an incompatibility; "
374
+ "if so, try upgrading your version of PyTorch.",
375
+ load_args._version,
376
+ )
377
+
378
+ nop_reader = NopInputReader()
379
+ load_args(nop_reader)
380
+
381
+ with tqdm(desc="Loading inputs", total=nop_reader.total) as pbar:
382
+ input_reader = InputReader(save_dir=options.save_dir, pbar=pbar)
383
+ load_args(input_reader)
384
+ args = input_reader.args
385
+
386
+ return args
387
+
388
+
389
+ def repro_minify(options, mod, load_args):
390
+ args = run_load_args(options, mod, load_args)
391
+
392
+ # Setup debug minifier compiler
393
+ if not options.accuracy:
394
+ compiler_fn = lookup_backend("dynamo_minifier_backend")
395
+ else:
396
+ compiler_fn = lookup_backend("dynamo_accuracy_minifier_backend")
397
+
398
+ if options.backend is None:
399
+ raise RuntimeError(
400
+ "Compiler name is None - this likely means that a custom compiler "
401
+ "was called by torchdynamo. Please remove this error, import your "
402
+ "custom compiler function, and replace the backend=None "
403
+ "line in run_repro to backend=<my_imported_custom_function>"
404
+ )
405
+
406
+ dynamo_minifier_backend = functools.partial(
407
+ compiler_fn,
408
+ compiler_name=options.backend,
409
+ )
410
+ opt_mod = torch._dynamo.optimize(dynamo_minifier_backend)(mod)
411
+
412
+ with torch.cuda.amp.autocast(enabled=options.autocast):
413
+ opt_mod(*args)
414
+
415
+
416
+ def repro_run(options, mod, load_args):
417
+ opt_mod = torch._dynamo.optimize(options.backend)(mod)
418
+
419
+ if options.accuracy != "":
420
+ mod.eval()
421
+ opt_mod.eval()
422
+
423
+ with torch.cuda.amp.autocast(enabled=options.autocast):
424
+ # TODO: disable clone
425
+ args = run_load_args(options, mod, load_args)
426
+ assert same_two_models(mod, mod, args), "Eager itself failed"
427
+ if not same_two_models(mod, opt_mod, args):
428
+ raise AccuracyError("Dynamo failed")
429
+ else:
430
+ with torch.cuda.amp.autocast(enabled=options.autocast):
431
+ args = run_load_args(options, mod, load_args)
432
+ ref = run_fwd_maybe_bwd(
433
+ mod, args, only_fwd=options.only_fwd, disable_clone=True
434
+ )
435
+ del args
436
+
437
+ args = run_load_args(options, mod, load_args)
438
+ res = run_fwd_maybe_bwd(
439
+ opt_mod, args, only_fwd=options.only_fwd, disable_clone=True
440
+ )
441
+
442
+
443
+ def run_repro(
444
+ mod,
445
+ load_args,
446
+ *,
447
+ command="run",
448
+ accuracy: Union[bool, str] = "",
449
+ save_dir=None,
450
+ autocast=False,
451
+ backend="inductor",
452
+ **kwargs,
453
+ ):
454
+ for k in kwargs:
455
+ log.warning(
456
+ "Unrecognized kwarg %s; perhaps this repro was made on a newer version of PyTorch",
457
+ k,
458
+ )
459
+
460
+ if accuracy is True:
461
+ accuracy = "accuracy"
462
+ elif accuracy is False:
463
+ accuracy = ""
464
+
465
+ parser = argparse.ArgumentParser(
466
+ description=f"""\
467
+ An after_dynamo repro script, typically triggering a bug in Dynamo or
468
+ AOTAutograd. When run with no arguments, this script defaults to running
469
+ '{command}'. Extra flags may be available; to find out more, try '{command}
470
+ --help'. There are also alternate subcommands available, see below.
471
+
472
+ default settings on this script:
473
+ {accuracy=}
474
+ {save_dir=}
475
+ """,
476
+ formatter_class=argparse.RawTextHelpFormatter,
477
+ )
478
+
479
+ def common_flags(parser):
480
+ accuracy_group = parser.add_mutually_exclusive_group()
481
+ accuracy_group.add_argument(
482
+ "--no-accuracy",
483
+ dest="accuracy",
484
+ action="store_const",
485
+ const="",
486
+ default=accuracy,
487
+ help="do not test accuracy, just run the module and see if it errors",
488
+ )
489
+ accuracy_group.add_argument(
490
+ "--accuracy",
491
+ action="store_const",
492
+ const="accuracy",
493
+ default=accuracy,
494
+ help="test accuracy",
495
+ )
496
+ parser.add_argument(
497
+ "--save-dir",
498
+ type=str,
499
+ default=save_dir,
500
+ metavar="DIR",
501
+ help="directory where saved inputs live",
502
+ )
503
+ parser.add_argument(
504
+ "--no-save-dir",
505
+ dest="save_dir",
506
+ action="store_const",
507
+ const=None,
508
+ help="don't use any directory for saved inputs",
509
+ )
510
+ parser.add_argument(
511
+ "--no-isolate",
512
+ dest="isolate",
513
+ action="store_false",
514
+ default=False,
515
+ help="no isolate (doesn't do anything for after_dynamo)",
516
+ )
517
+ parser.add_argument(
518
+ "--autocast",
519
+ default=autocast,
520
+ action="store_true",
521
+ help="use torch.cuda.amp.autocast",
522
+ )
523
+ parser.add_argument(
524
+ "--no-autocast",
525
+ dest="autocast",
526
+ action="store_false",
527
+ help="don't use torch.cuda.amp.autocast",
528
+ )
529
+ parser.add_argument(
530
+ "--backend",
531
+ type=str,
532
+ default=backend,
533
+ metavar="BACKEND",
534
+ help="torch.compile backend to use",
535
+ )
536
+
537
+ subparsers = parser.add_subparsers(
538
+ dest="command", metavar="{run,minify}", required=True
539
+ )
540
+
541
+ parser_run = subparsers.add_parser(
542
+ "run",
543
+ help="just run the repro",
544
+ )
545
+ common_flags(parser_run)
546
+ parser_run.add_argument(
547
+ "--only-fwd",
548
+ action="store_true",
549
+ help="don't run backwards compilation for testing",
550
+ )
551
+
552
+ parser_minify = subparsers.add_parser(
553
+ "minify", help="run the minifier on the repro"
554
+ )
555
+ common_flags(parser_minify)
556
+
557
+ args = None
558
+ if len(sys.argv) <= 1:
559
+ args = [command, *sys.argv[1:]]
560
+
561
+ options = parser.parse_args(args)
562
+ COMMAND_FNS = {
563
+ "minify": repro_minify,
564
+ "run": repro_run,
565
+ }
566
+ COMMAND_FNS[options.command](options, mod, load_args)
shared/package-files/8b/8ba7b82882992c27f751fa5bdb557635ea45f1848558817b2c047bdbef7b46fd/blob ADDED
Binary file (470 Bytes). View file
 
shared/package-files/8b/8babb286a74d5fb93bad98906f3c4b70386c0e3dfb4f31edf184a012887bec5c/blob ADDED
@@ -0,0 +1,606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Set, Tuple, Callable
2
+ from collections import OrderedDict
3
+ import torch
4
+ from torch.ao.quantization.fx._model_report.detector import (
5
+ DetectorBase,
6
+ DETECTOR_OBS_ARGS_KEY,
7
+ DETECTOR_OBS_TO_INSERT_KEY,
8
+ DETECTOR_IS_POST_OBS_KEY,
9
+ DETECTOR_TARGET_NODE_KEY,
10
+ DetectorQConfigInfo
11
+ )
12
+ from torch.ao.quantization.fx._model_report.model_report_visualizer import ModelReportVisualizer
13
+ from torch.ao.quantization.fx.graph_module import GraphModule
14
+ from torch.ao.quantization.observer import ObserverBase
15
+ from torch.ao.quantization.qconfig_mapping import QConfigMapping, QConfig
16
+ from torch.ao.quantization.fx._equalize import EqualizationQConfig
17
+
18
+ class ModelReport:
19
+ r"""
20
+ The ModelReport class aims to provide users an easy way to diagnose issues that they run into
21
+ with their models. The class works with all traceable GraphModules to help diagnose issues,
22
+ though the requirements on the type of model more-so depends on the specific report the user
23
+ is trying to generate. With respect to the reports, the ModelReport class is initialized with
24
+ a set of Detector classes, each of which generate reports on quantization configuration
25
+ issues a use might have.
26
+
27
+ Currently supports generating reports on:
28
+ - Suggestions for per-channel vs. per-tensor quantization (nn.Module)
29
+ - Suggestions for dynamic vs static quantization for linear layers (Graph Modules)
30
+ - Suggestions for input-weight equalization for linear and conv layers (Graph Modules)
31
+ - Suggestions for outlier detection for all layers (Graph Modules)
32
+
33
+ The ModelReport class has the primary functionality of inserting observers (primarily the ModelReportObserver)
34
+ where needed for each detector to gather the information it needs, and then after callibration, the ModelReport
35
+ class compiles the report generated by each Detector class into a single report to return to the user. It also
36
+ has the capability to remove all the observers it inserted as well.
37
+
38
+ * :attr:`_model` The model we wish to generate the report for. Must be a traceable GraphModule
39
+
40
+ * :attr:`_desired_report_detectors` The set of Detectors representing desired reports from the ModelReport class
41
+ Make sure that these are all unique types of detectors [do not have more than 1 of the same class]
42
+
43
+ * :attr:`_desired_detector_names` The set of detector names of the _desired_report_detectors.
44
+ This set is generated by calling the get_detector_name() of each detector
45
+
46
+ * :attr:`_detector_name_to_observer_fqns` The mapping from each detector to fqns of observers of interest
47
+ The purpose of this is to keep track of what observers were inserted for each detector, so that they
48
+ can be removed at the end if desired
49
+
50
+ * :attr:`_prepared_flag` A boolean flag that keeps track of whether we have prepared the model or not
51
+ This is to ensure we only insert observers once with the ModelReport instance
52
+
53
+ * :attr:`_removed_observers` A boolean to track if we have removed observers already
54
+ The purpose is to ensure we don't attempt to remove observers twice with the same ModelReport
55
+ instance. This also allows the functionality where we can generate the report multiple times
56
+ as long as we haven't removed the observers yet.
57
+
58
+ Note:
59
+ This class was initially designed to work with the Fx Graph Mode workflow in mind. However,
60
+ full functionality is available as long as there is a traceable GraphModule that is being used.
61
+ One method to get a traceable GraphModule without going through the Fx workflow is to use
62
+ the QuantizationTracer class.
63
+
64
+ General Flow for Fx workflow:
65
+ 1.) Initialize ModelReport object with reports of interest by passing in initialized detector objects and model
66
+ 2.) Prepare your model with prepare_fx
67
+ 3.) Call model_report.prepare_detailed_calibration to add relevant observers
68
+ 4.) Callibrate your model with data
69
+ 5.) Call model_report.generate_report on your model to generate report and optionally remove added observers
70
+ Optional
71
+ 6.) Call model_report.generate_visualizer to get a ModelReportVisualizer instance
72
+ 7.) To help in parsing report information and debugging, view report info as a:
73
+ - Table
74
+ - Histogram
75
+ - Line plot
76
+ 8.) Call model_report.generate_qconfigs to generate the qconfigs based on the report suggestions
77
+
78
+ Example (with QuantizationTracer):
79
+ >>> # xdoctest: +SKIP
80
+ >>> # get the necessary qconfig
81
+ >>> config = PrepareCustomConfig()
82
+ >>> skipped_module_names, skipped_module_classes = get_skipped_module_name_and_classes(config, False)
83
+
84
+ >>> # initialize our model and get GraphModule
85
+ >>> model = SomeModel()
86
+ >>> tracer = QuantizationTracer(skipped_module_names, skipped_module_classes)
87
+ >>> graph_module = GraphModule(model, tracer.trace(model))
88
+
89
+ >>> # get our set of detectors and ModelReport instance
90
+ >>> detector_set = set([DynamicStaticDetector(tolerance=0.5), InputWeightEqualizationDetector(ratio_threshold=0.7)])
91
+ >>> tracer_reporter = ModelReport(graph_module, tracer_detector_set)
92
+
93
+ >>> # now we insert the observers and callibrate the model
94
+ >>> tracer_model_with_observers = tracer_reporter.prepare_detailed_calibration()
95
+ >>> for i in range(num_callibration_batches):
96
+ >>> example_input = get_callibration_input()
97
+ >>> tracer_model_with_observers(example_input)
98
+
99
+ >>> # finally we generate the reports and optionally remove the observers we inserted
100
+ >>> reports = tracer_reporter.generate_model_report(remove_inserted_observers=True)
101
+
102
+ >>> # Optional: we can generate the qconfig mapping based on the suggestions
103
+ >>> qconfigs = model_report.generate_qconfig_mapping()
104
+
105
+ >>> # Optional: we can generate the equalization mapping based on the suggestions
106
+ >>> qconfigs = model_report.generate_equalization_mapping()
107
+
108
+ >>> # Optional: we get a ModelReportVisualizer instance to do any visualizations desired
109
+ >>> model_report_visualizer = tracer_reporter.generate_visualizer()
110
+
111
+ """
112
+
113
+ def __init__(self, model: GraphModule, desired_report_detectors: Set[DetectorBase]):
114
+
115
+ if len(desired_report_detectors) == 0:
116
+ raise ValueError("Should include at least 1 desired report")
117
+
118
+ # keep track of the model we wish to generate report for
119
+ self._model: GraphModule = model
120
+
121
+ # keep the reports private so they can't be modified
122
+ self._desired_report_detectors = desired_report_detectors
123
+ self._desired_detector_names = {detector.get_detector_name() for detector in desired_report_detectors}
124
+
125
+ # keep a mapping of desired reports to observers of interest
126
+ # this is to get the readings, and to remove them, can create a large set
127
+ # this set can then be used to traverse the graph and remove added observers
128
+ self._detector_name_to_observer_fqns: Dict[str, Set[str]] = {}
129
+
130
+ # initialize each report to have empty set of observers of interest
131
+ for desired_report in self._desired_detector_names:
132
+ self._detector_name_to_observer_fqns[desired_report] = set()
133
+
134
+ # flags to ensure that we can only prepare and remove observers once
135
+ self._prepared_flag = False
136
+ self._removed_observers = False
137
+
138
+ # store the reports that we generated for visualization purposes
139
+ # initially empty since no reports generated
140
+ self._generated_reports: Dict[str, Dict] = {}
141
+
142
+ def get_desired_reports_names(self) -> Set[str]:
143
+ """ Returns a copy of the desired reports for viewing """
144
+ return self._desired_detector_names.copy()
145
+
146
+ def get_observers_of_interest(self) -> Dict[str, Set[str]]:
147
+ """ Returns a copy of the observers of interest for viewing """
148
+ return self._detector_name_to_observer_fqns.copy()
149
+
150
+ def prepare_detailed_calibration(self) -> GraphModule:
151
+ r"""
152
+ Takes in a graph model and inserts the following observers:
153
+ - ModelReportObserver
154
+
155
+ Each observer is inserted based on the desired_reports into the relevant locations
156
+
157
+ Right now, each report in self._desired_detector_names has independent insertions
158
+ However, if a module already has a Observer of the same type, the insertion will not occur
159
+ This is because all of the same type of Observer collect same information, so redundant
160
+
161
+ Returns the same GraphModule with the observers inserted
162
+ """
163
+
164
+ # if already prepared once, cannot prepare again
165
+ if self._prepared_flag:
166
+ raise ValueError("Already ran preparing detailed callibration. Run the report generation next after callibration.")
167
+
168
+ # loop through each detector, find where placements should be, and keep track
169
+ insert_observers_fqns: Dict[str, Any] = {}
170
+
171
+ for detector in self._desired_report_detectors:
172
+ # determine observer points for each detector
173
+ obs_fqn_to_info = detector.determine_observer_insert_points(self._model)
174
+ # map each insert point to the observer to use
175
+ insert_observers_fqns.update(obs_fqn_to_info)
176
+ # update the set of observers this report cares about
177
+ self._detector_name_to_observer_fqns[detector.get_detector_name()] = set(obs_fqn_to_info.keys())
178
+
179
+ # now insert all the observers at their desired locations
180
+ for observer_fqn in insert_observers_fqns:
181
+ target_node = insert_observers_fqns[observer_fqn][DETECTOR_TARGET_NODE_KEY]
182
+ insert_obs = insert_observers_fqns[observer_fqn][DETECTOR_OBS_TO_INSERT_KEY]
183
+ insert_post = insert_observers_fqns[observer_fqn][DETECTOR_IS_POST_OBS_KEY]
184
+ observer_args = insert_observers_fqns[observer_fqn][DETECTOR_OBS_ARGS_KEY]
185
+ self._insert_observer_around_module(
186
+ observer_fqn, target_node, insert_obs, observer_args, insert_post
187
+ )
188
+
189
+ self._prepared_flag = True
190
+
191
+ return self._model
192
+
193
+ def _insert_observer_around_module(
194
+ self,
195
+ obs_fqn: str,
196
+ target_node: torch.fx.node.Node,
197
+ obs_to_insert: ObserverBase,
198
+ observer_args: Tuple,
199
+ insert_post: bool
200
+ ):
201
+ r"""
202
+ Helper function that inserts the observer into both the graph structure and the module of the model
203
+
204
+ Args
205
+ node_fqn (str): The fully qualified name of the observer we want to insert
206
+ target_node (torch.fx.node.Node): The node in model we are inserting observers around
207
+ obs_to_insert (ObserverBase): The observer we are inserting around target_node
208
+ observer_args (Tuple): The arguments we want to pass into the observer
209
+ insert_post (bool): whether this is meant to be a post observer for this node
210
+ """
211
+ # if we are inserting post, then our target node is the next node
212
+ if insert_post:
213
+ target_node = target_node.next
214
+
215
+ with self._model.graph.inserting_before(target_node):
216
+ self._model.add_submodule(obs_fqn, obs_to_insert)
217
+ self._model.graph.create_node(op="call_module", target=obs_fqn, args=observer_args)
218
+
219
+ # recompile model after inserts are made
220
+ self._model.recompile()
221
+
222
+ def _get_node_from_fqn(self, node_fqn: str) -> torch.fx.node.Node:
223
+ r"""
224
+ Takes in a node fqn and returns the node based on the fqn
225
+
226
+ Args
227
+ node_fqn (str): The fully qualified name of the node we want to find in model
228
+
229
+ Returns the Node object of the given node_fqn otherwise returns None
230
+ """
231
+ node_to_return = None
232
+ for node in self._model.graph.nodes:
233
+ # if the target matches the fqn, it's the node we are looking for
234
+ if node.target == node_fqn:
235
+ node_to_return = node
236
+ break
237
+
238
+ if node_to_return is None:
239
+ raise ValueError("The node_fqn is was not found within the module.")
240
+
241
+ # assert for MyPy
242
+ assert isinstance(node_to_return, torch.fx.node.Node)
243
+
244
+ return node_to_return
245
+
246
+ def generate_model_report(
247
+ self, remove_inserted_observers: bool
248
+ ) -> Dict[str, Tuple[str, Dict]]:
249
+ r"""
250
+ Generates all the requested reports.
251
+
252
+ Note:
253
+ You should have callibrated the model with relevant data before calling this
254
+
255
+ The reports generated are specified by the desired_reports specified in desired_reports
256
+
257
+ Can optionally remove all the observers inserted by the ModelReport instance
258
+
259
+ Args:
260
+ remove_inserted_observers (bool): True to remove the observers inserted by this ModelReport instance
261
+
262
+ Returns a mapping of each desired report name to a tuple with:
263
+ The textual summary of that report information
264
+ A dictionary containing relevant statistics or information for that report
265
+
266
+ Note:
267
+ Throws exception if we try to generate report on model we already removed observers from
268
+ Throws exception if we try to generate report without preparing for callibration
269
+ """
270
+ # if we haven't prepped model for callibration, then we shouldn't generate report yet
271
+ if not self._prepared_flag:
272
+ raise Exception("Cannot generate report without preparing model for callibration")
273
+
274
+ # if we already removed the observers, we cannot generate report
275
+ if self._removed_observers:
276
+ raise Exception("Cannot generate report on model you already removed observers from")
277
+
278
+ # keep track of all the reports of interest and their outputs
279
+ reports_of_interest = {}
280
+
281
+ for detector in self._desired_report_detectors:
282
+ # generate the individual report for the detector
283
+ report_output = detector.generate_detector_report(self._model)
284
+ reports_of_interest[detector.get_detector_name()] = report_output
285
+
286
+ # if user wishes to remove inserted observers, go ahead and remove
287
+ if remove_inserted_observers:
288
+ self._removed_observers = True
289
+ # get the set of all Observers inserted by this instance of ModelReport
290
+ all_observers_of_interest: Set[str] = set()
291
+ for desired_report in self._detector_name_to_observer_fqns:
292
+ observers_of_interest = self._detector_name_to_observer_fqns[desired_report]
293
+ all_observers_of_interest.update(observers_of_interest)
294
+
295
+ # go through all_observers_of_interest and remove them from the graph and model
296
+ for observer_fqn in all_observers_of_interest:
297
+ # remove the observer from the model
298
+ self._model.delete_submodule(observer_fqn)
299
+
300
+ # remove the observer from the graph structure
301
+ node_obj = self._get_node_from_fqn(observer_fqn)
302
+
303
+ if node_obj:
304
+ self._model.graph.erase_node(node_obj)
305
+ else:
306
+ raise ValueError("Node no longer exists in GraphModule structure")
307
+
308
+ # remember to recompile the model
309
+ self._model.recompile()
310
+
311
+ # save the generated reports for visualization purposes
312
+ saved_reports: Dict[str, Dict] = {
313
+ report_name : report_tuple[1] for report_name, report_tuple in reports_of_interest.items()
314
+ }
315
+
316
+ self._generated_reports = saved_reports
317
+
318
+ # return the reports of interest
319
+ return reports_of_interest
320
+
321
+ def _is_same_info_for_same_key(self, info_dict_a: Dict, info_dict_b: Dict) -> bool:
322
+ r"""
323
+ Takes in two dictionaries and ensures that any common keys between the two have the same
324
+ values.
325
+
326
+ Args:
327
+ info_dict_a (Dict): First dictionary we wish to compare
328
+ info_dict_b (Dict): Second dictionary we wish to compare
329
+
330
+ Returns True if all shared keys have same values, false otherwise
331
+ """
332
+ # get the set of keys for both
333
+ dict_a_keys: Set = set(info_dict_a.keys())
334
+ dict_b_keys: Set = set(info_dict_b.keys())
335
+
336
+ # get the insersection keys and check if same value for both dicts
337
+ intersecting_keys: Set = dict_a_keys.intersection(dict_b_keys)
338
+
339
+ for key in intersecting_keys:
340
+ dict_a_val = info_dict_a[key]
341
+ dict_b_val = info_dict_b[key]
342
+
343
+ # if it's a tensor we have to handle separately
344
+ if type(dict_a_val) == torch.Tensor:
345
+ # if dict_b_val not tensor, automatically false
346
+ if type(dict_b_val) != torch.Tensor or sum(dict_a_val != dict_b_val) != 0:
347
+ return False
348
+ else:
349
+ # for non-tensor vals
350
+ if dict_a_val != dict_b_val:
351
+ return False
352
+
353
+ # if no non matching shared keys found, return true
354
+ return True
355
+
356
+ def _reformat_reports_for_visualizer(self) -> OrderedDict:
357
+ r"""
358
+ Takes the generated reports and reformats them into the format that is desired by the
359
+ ModelReportVisualizer
360
+
361
+ Returns an OrderedDict mapping module_fqns to their features
362
+ """
363
+ # we want to reorder and reformat the information so it is ordered in terms of order
364
+ # found in the model
365
+
366
+ # first create new dict with all modules as keys and features under respective module
367
+ module_fqns_to_features: Dict[str, Dict] = {}
368
+
369
+ for report_name in self._generated_reports:
370
+ # get mod -> feature dict and go through
371
+ module_info = self._generated_reports[report_name]
372
+
373
+ for module_fqn in module_info:
374
+ # check if already in our accumulation dict
375
+ if module_fqn in module_fqns_to_features:
376
+ # we merge all the features together
377
+ new_info: Dict = module_info[module_fqn]
378
+ present_info: Dict = module_fqns_to_features[module_fqn]
379
+
380
+ # merge them together into the new unioned dict
381
+ # same features keys -> same info, so okay if override
382
+
383
+ # do safety check to make sure shared keys have same info
384
+ if self._is_same_info_for_same_key(new_info, present_info):
385
+ module_fqns_to_features[module_fqn] = {**new_info, **present_info}
386
+ else:
387
+ error_str = "You have the same key with different values across detectors. "
388
+ error_str += "Someone incorrectly implemented a detector with conflicting keys to existing detectors."
389
+ raise ValueError(error_str)
390
+ else:
391
+ # we just set it
392
+ module_fqns_to_features[module_fqn] = module_info[module_fqn]
393
+
394
+ # our ordered dict so that modules can be ordered in order of how they appear in model
395
+ features_by_module: OrderedDict[str, Dict] = OrderedDict()
396
+
397
+ # we loop through modules in graph in order
398
+ for fqn, module in self._model.named_modules():
399
+ # find that fqn in fqns_to_features
400
+ if fqn in module_fqns_to_features:
401
+ # add it to our ordered dict
402
+ features_by_module[fqn] = module_fqns_to_features[fqn]
403
+
404
+ # return the ordered dict of info we created
405
+ return features_by_module
406
+
407
+ def generate_visualizer(self) -> ModelReportVisualizer:
408
+ r"""
409
+ Generates a ModelReportVisualizer instance using the reports generated
410
+ by the generate_model_report() method.
411
+
412
+ Returns the generated ModelReportVisualizer instance initialized
413
+
414
+ Note:
415
+ Throws exception if attempt to get visualizers without generating report
416
+ """
417
+ # check if user has generated reports at least once
418
+ if len(self._generated_reports) == 0:
419
+ raise Exception("Unable to generate visualizers without first generating reports")
420
+
421
+ # get the ordered dict mapping modules to their full set of collected features / stats
422
+ module_fqns_to_features: OrderedDict = self._reformat_reports_for_visualizer()
423
+
424
+ # create and return ModelReportVisualizer instance
425
+ visualizer: ModelReportVisualizer = ModelReportVisualizer(module_fqns_to_features)
426
+
427
+ return visualizer
428
+
429
+ def _generate_qconfig_mapping_helper(
430
+ self,
431
+ detector_qconfig_info_combined: Dict[str, DetectorQConfigInfo],
432
+ generation_function: Callable
433
+ ) -> QConfigMapping:
434
+ r"""
435
+ This helper takes in the compiled detector qconfig info that
436
+ has been compiled together and merges it into a QConfigMapping
437
+ """
438
+ # keep track of the qconfigmapping
439
+ qconfig_mapping = QConfigMapping()
440
+
441
+ # loop through each module / fqn and attempt to create QConfigMapping
442
+ for fqn, module in self._model.named_modules():
443
+ # if we have a qconfig info for this module
444
+ if fqn in detector_qconfig_info_combined:
445
+ qconfig_info_compiled = detector_qconfig_info_combined[fqn]
446
+
447
+ # now generate the qconfig and add it to the mapping
448
+ generated_qconfig = generation_function(qconfig_info_compiled, module)
449
+
450
+ # add to our config
451
+ qconfig_mapping.set_module_name(fqn, generated_qconfig)
452
+
453
+ # return compiled mapping
454
+ return qconfig_mapping
455
+
456
+ def _update_detector_quantizaiton_qconfig_info(self, combined_info: DetectorQConfigInfo, new_info: DetectorQConfigInfo):
457
+ r"""
458
+ Takes in the old and new information and updates the combined information.
459
+
460
+ Args:
461
+ combined_info (DetectorQConfigInfo): The DetectorQConfigInfo we are compiling all of the information in
462
+ new_info (DetectorQConfigInfo): The DetectorQConfigInfo with the information we are trying to merge the new info
463
+ into it
464
+ """
465
+ combined_info.is_activation_dynamic = combined_info.is_activation_dynamic or new_info.is_activation_dynamic
466
+ combined_info.is_weight_per_channel = combined_info.is_weight_per_channel or new_info.is_weight_per_channel
467
+
468
+ def _update_detector_equalization_qconfig_info(self, combined_info: DetectorQConfigInfo, new_info: DetectorQConfigInfo):
469
+ r"""
470
+ Takes in the old and new information and updates the combined information.
471
+
472
+ Args:
473
+ combined_info (DetectorQConfigInfo): The DetectorQConfigInfo we are compiling all of the information in
474
+ new_info (DetectorQConfigInfo): The DetectorQConfigInfo with the information we are trying to merge the new info
475
+ into it
476
+ """
477
+ is_equalization_recommended = combined_info.is_equalization_recommended or new_info.is_equalization_recommended
478
+ combined_info.is_equalization_recommended = is_equalization_recommended
479
+
480
+ def _generate_module_fqn_to_detector_info_mapping(
481
+ self,
482
+ update_qconfig_info_function: Callable
483
+ ) -> Dict[str, DetectorQConfigInfo]:
484
+ r"""
485
+ Generates a QConfigMapping based on the suggestions of the
486
+ ModelReport API. The generated mapping encompasses all the
487
+ different types of feedback from the different detectors
488
+ all into one place.
489
+
490
+ These configs are based on the suggestions provided by the ModelReport API
491
+ and can only be generated once the reports have been generated.
492
+
493
+ Args:
494
+ update_qconfig_info_function (Callable) takes in a function that takes in two DetectorQConfigInfo
495
+ and updates the one that is being compiled
496
+
497
+ Returns a Dict mapping module_fqns to DetectorQConfigInfo objects
498
+
499
+ Note:
500
+ Throws exception if we try to generate mapping on model we already removed observers from
501
+ Throws exception if we try to generate mapping without preparing for callibration
502
+ """
503
+ # if we haven't prepped model for callibration, then we shouldn't generate mapping yet
504
+ if not self._prepared_flag:
505
+ raise Exception("Cannot generate report without preparing model for callibration")
506
+
507
+ # if we already removed the observers, we cannot mapping
508
+ if self._removed_observers:
509
+ raise Exception("Cannot generate report on model you already removed observers from")
510
+
511
+ # keep track of qconfig info for each module across detectors
512
+ detector_qconfig_info_combined: Dict[str, DetectorQConfigInfo] = {}
513
+
514
+ for detector in self._desired_report_detectors:
515
+ # get the info from the detector
516
+ detector_info: Dict[str, DetectorQConfigInfo] = detector.get_qconfig_info(self._model)
517
+
518
+ # we go through the modules
519
+ for module_fqn in detector_info:
520
+ # see if we already have info on it
521
+ if module_fqn in detector_qconfig_info_combined:
522
+ # we combine the current options with what is there
523
+ current_options = detector_qconfig_info_combined[module_fqn]
524
+ detector_options = detector_info[module_fqn]
525
+
526
+ update_qconfig_info_function(current_options, detector_options)
527
+ else:
528
+ # we just use this for now
529
+ detector_qconfig_info_combined[module_fqn] = detector_info[module_fqn]
530
+
531
+ return detector_qconfig_info_combined
532
+
533
+ def generate_qconfig_mapping(self) -> QConfigMapping:
534
+ r"""
535
+ Generates a QConfigMapping based on the suggestions of the
536
+ ModelReport API. The generated mapping encompasses all the
537
+ different types of feedback from the different detectors
538
+ all into one place.
539
+
540
+ These configs are based on the suggestions provided by the ModelReport API
541
+ and can only be generated once the reports have been generated.
542
+
543
+ Returns a QConfigMapping for the quantization configuration
544
+
545
+ Note:
546
+ Throws exception if we try to generate mapping on model we already removed observers from
547
+ Throws exception if we try to generate mapping without preparing for callibration
548
+ """
549
+ # get the mapping info
550
+ detector_qconfig_info_combined = self._generate_module_fqn_to_detector_info_mapping(
551
+ self._update_detector_quantizaiton_qconfig_info
552
+ )
553
+
554
+ # we will do a bit of processing and remove fqns that don't have input weight recommended
555
+
556
+ # now we generate the QConfig for each of the options
557
+ mapping: QConfigMapping = self._generate_qconfig_mapping_helper(
558
+ detector_qconfig_info_combined,
559
+ self._quantization_config_generator
560
+ )
561
+
562
+ # return the generated mapping
563
+ return mapping
564
+
565
+ def _quantization_config_generator(self, detector_qconfig_info: DetectorQConfigInfo, module: torch.nn.Module) -> QConfig:
566
+ r"""
567
+ Returns the quantization configuration generated by the DetectorQConfigInfo object
568
+ """
569
+ return detector_qconfig_info.generate_quantization_qconfig(module)
570
+
571
+ def _equalization_config_generator(
572
+ self,
573
+ detector_qconfig_info: DetectorQConfigInfo,
574
+ module: torch.nn.Module
575
+ ) -> EqualizationQConfig:
576
+ r"""
577
+ We ignore the module argument here, and only focus on thedetector_qconfig_info
578
+
579
+ Returns the equalization configuration generated by the DetectorQConfigInfo object
580
+ """
581
+ return detector_qconfig_info.generate_equalization_qconfig()
582
+
583
+ def generate_equalization_mapping(self) -> QConfigMapping:
584
+ r"""
585
+ Generates a QConfigMapping based on the suggestions of the
586
+ ModelReport API for equalization. The generated mapping encompasses all the
587
+ different types of feedback from the input-weight equalization detector.
588
+
589
+ These configs are based on the suggestions provided by the ModelReport API
590
+ and can only be generated once the reports have been generated.
591
+
592
+ Returns a QConfigMapping for the equalization configuration
593
+ """
594
+ # get the mapping info
595
+ detector_qconfig_info_combined = self._generate_module_fqn_to_detector_info_mapping(
596
+ self._update_detector_equalization_qconfig_info
597
+ )
598
+
599
+ # now we generate the QConfig for each of the options
600
+ mapping: QConfigMapping = self._generate_qconfig_mapping_helper(
601
+ detector_qconfig_info_combined,
602
+ self._equalization_config_generator
603
+ )
604
+
605
+ # return the generated mapping
606
+ return mapping
shared/package-files/8b/8bac1070af4cf22f337ff5aaa8184c8f638229a9af3fb4fff630b919418fd47e/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bac1070af4cf22f337ff5aaa8184c8f638229a9af3fb4fff630b919418fd47e
3
+ size 208346
shared/package-files/8b/8badfd129686a5d20216b1aba16450f6f471722c8b6ddfc61278dd572283abc0/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8badfd129686a5d20216b1aba16450f6f471722c8b6ddfc61278dd572283abc0
3
+ size 555268959
shared/package-files/8b/8bb075675e65561a64af676d362b7a55867696d0f0f5a15973451b8c155294c6/blob ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API ::std::vector<at::Tensor> _foreach_sign(at::TensorList self);
21
+ TORCH_API void _foreach_sign_(at::TensorList self);
22
+
23
+ } // namespace cuda
24
+ } // namespace at
shared/package-files/8b/8bb0c4a825ec10fb775f144093ab733132671db740246a713f00825d3b889e34/blob ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test that all docstrings are the same:
3
+
4
+ >>> len({f.__doc__ for f in (a, b, c, d)})
5
+ 1
6
+ """
7
+ from numba import guvectorize, int64, njit, vectorize
8
+
9
+
10
+ def a():
11
+ """>>> x = 1"""
12
+ return 1
13
+
14
+
15
+ @njit
16
+ def b():
17
+ """>>> x = 1"""
18
+ return 1
19
+
20
+
21
+ @guvectorize([(int64[:], int64, int64[:])], "(n),()->(n)")
22
+ def c(x, y, res):
23
+ """>>> x = 1"""
24
+ for i in range(x.shape[0]):
25
+ res[i] = x[i] + y
26
+
27
+
28
+ @vectorize([int64(int64, int64)])
29
+ def d(x, y):
30
+ """>>> x = 1"""
31
+ return x + y
shared/package-files/8b/8bb7d57be88bc8bb50c427c06b82317711feb9f70798c93b85b0861b94f1018e/blob ADDED
@@ -0,0 +1,1008 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ StartFontMetrics 2.0
2
+ Comment Copyright (c) 1989, 1991 Adobe Systems Incorporated. All Rights Reserved.
3
+ Comment Creation Date: Fri Jan 17 13:15:45 1992
4
+ Comment UniqueID 37666
5
+ Comment VMusage 34143 41035
6
+ FontName Utopia-Italic
7
+ FullName Utopia Italic
8
+ FamilyName Utopia
9
+ Weight Regular
10
+ ItalicAngle -13
11
+ IsFixedPitch false
12
+ FontBBox -201 -250 1170 890
13
+ UnderlinePosition -100
14
+ UnderlineThickness 50
15
+ Version 001.002
16
+ Notice Copyright (c) 1989, 1991 Adobe Systems Incorporated. All Rights Reserved.Utopia is a registered trademark of Adobe Systems Incorporated.
17
+ EncodingScheme AdobeStandardEncoding
18
+ CapHeight 692
19
+ XHeight 502
20
+ Ascender 742
21
+ Descender -242
22
+ StartCharMetrics 228
23
+ C 32 ; WX 225 ; N space ; B 0 0 0 0 ;
24
+ C 33 ; WX 240 ; N exclam ; B 34 -12 290 707 ;
25
+ C 34 ; WX 402 ; N quotedbl ; B 171 469 454 742 ;
26
+ C 35 ; WX 530 ; N numbersign ; B 54 0 585 668 ;
27
+ C 36 ; WX 530 ; N dollar ; B 31 -109 551 743 ;
28
+ C 37 ; WX 826 ; N percent ; B 98 -25 795 702 ;
29
+ C 38 ; WX 725 ; N ampersand ; B 60 -12 703 680 ;
30
+ C 39 ; WX 216 ; N quoteright ; B 112 482 265 742 ;
31
+ C 40 ; WX 350 ; N parenleft ; B 106 -128 458 692 ;
32
+ C 41 ; WX 350 ; N parenright ; B -46 -128 306 692 ;
33
+ C 42 ; WX 412 ; N asterisk ; B 106 356 458 707 ;
34
+ C 43 ; WX 570 ; N plus ; B 58 0 542 490 ;
35
+ C 44 ; WX 265 ; N comma ; B 11 -134 173 142 ;
36
+ C 45 ; WX 392 ; N hyphen ; B 82 216 341 286 ;
37
+ C 46 ; WX 265 ; N period ; B 47 -12 169 113 ;
38
+ C 47 ; WX 270 ; N slash ; B 0 -15 341 707 ;
39
+ C 48 ; WX 530 ; N zero ; B 60 -12 541 680 ;
40
+ C 49 ; WX 530 ; N one ; B 74 0 429 680 ;
41
+ C 50 ; WX 530 ; N two ; B -2 0 538 680 ;
42
+ C 51 ; WX 530 ; N three ; B 19 -12 524 680 ;
43
+ C 52 ; WX 530 ; N four ; B 32 0 509 668 ;
44
+ C 53 ; WX 530 ; N five ; B 24 -12 550 668 ;
45
+ C 54 ; WX 530 ; N six ; B 56 -12 551 680 ;
46
+ C 55 ; WX 530 ; N seven ; B 130 -12 600 668 ;
47
+ C 56 ; WX 530 ; N eight ; B 46 -12 535 680 ;
48
+ C 57 ; WX 530 ; N nine ; B 51 -12 536 680 ;
49
+ C 58 ; WX 265 ; N colon ; B 47 -12 248 490 ;
50
+ C 59 ; WX 265 ; N semicolon ; B 11 -134 248 490 ;
51
+ C 60 ; WX 570 ; N less ; B 51 1 529 497 ;
52
+ C 61 ; WX 570 ; N equal ; B 58 111 542 389 ;
53
+ C 62 ; WX 570 ; N greater ; B 51 1 529 497 ;
54
+ C 63 ; WX 425 ; N question ; B 115 -12 456 707 ;
55
+ C 64 ; WX 794 ; N at ; B 88 -15 797 707 ;
56
+ C 65 ; WX 624 ; N A ; B -58 0 623 692 ;
57
+ C 66 ; WX 632 ; N B ; B 3 0 636 692 ;
58
+ C 67 ; WX 661 ; N C ; B 79 -15 723 707 ;
59
+ C 68 ; WX 763 ; N D ; B 5 0 767 692 ;
60
+ C 69 ; WX 596 ; N E ; B 3 0 657 692 ;
61
+ C 70 ; WX 571 ; N F ; B 3 0 660 692 ;
62
+ C 71 ; WX 709 ; N G ; B 79 -15 737 707 ;
63
+ C 72 ; WX 775 ; N H ; B 5 0 857 692 ;
64
+ C 73 ; WX 345 ; N I ; B 5 0 428 692 ;
65
+ C 74 ; WX 352 ; N J ; B -78 -119 436 692 ;
66
+ C 75 ; WX 650 ; N K ; B 5 -5 786 692 ;
67
+ C 76 ; WX 565 ; N L ; B 5 0 568 692 ;
68
+ C 77 ; WX 920 ; N M ; B -4 0 1002 692 ;
69
+ C 78 ; WX 763 ; N N ; B -4 0 855 692 ;
70
+ C 79 ; WX 753 ; N O ; B 79 -15 754 707 ;
71
+ C 80 ; WX 614 ; N P ; B 5 0 646 692 ;
72
+ C 81 ; WX 753 ; N Q ; B 79 -203 754 707 ;
73
+ C 82 ; WX 640 ; N R ; B 5 0 642 692 ;
74
+ C 83 ; WX 533 ; N S ; B 34 -15 542 707 ;
75
+ C 84 ; WX 606 ; N T ; B 102 0 708 692 ;
76
+ C 85 ; WX 794 ; N U ; B 131 -15 880 692 ;
77
+ C 86 ; WX 637 ; N V ; B 96 0 786 692 ;
78
+ C 87 ; WX 946 ; N W ; B 86 0 1075 692 ;
79
+ C 88 ; WX 632 ; N X ; B -36 0 735 692 ;
80
+ C 89 ; WX 591 ; N Y ; B 96 0 744 692 ;
81
+ C 90 ; WX 622 ; N Z ; B -20 0 703 692 ;
82
+ C 91 ; WX 330 ; N bracketleft ; B 69 -128 414 692 ;
83
+ C 92 ; WX 390 ; N backslash ; B 89 -15 371 707 ;
84
+ C 93 ; WX 330 ; N bracketright ; B -21 -128 324 692 ;
85
+ C 94 ; WX 570 ; N asciicircum ; B 83 228 547 668 ;
86
+ C 95 ; WX 500 ; N underscore ; B 0 -125 500 -75 ;
87
+ C 96 ; WX 216 ; N quoteleft ; B 130 488 283 748 ;
88
+ C 97 ; WX 561 ; N a ; B 31 -12 563 502 ;
89
+ C 98 ; WX 559 ; N b ; B 47 -12 557 742 ;
90
+ C 99 ; WX 441 ; N c ; B 46 -12 465 502 ;
91
+ C 100 ; WX 587 ; N d ; B 37 -12 612 742 ;
92
+ C 101 ; WX 453 ; N e ; B 45 -12 471 502 ;
93
+ C 102 ; WX 315 ; N f ; B -107 -242 504 742 ; L i fi ; L l fl ;
94
+ C 103 ; WX 499 ; N g ; B -5 -242 573 512 ;
95
+ C 104 ; WX 607 ; N h ; B 57 -12 588 742 ;
96
+ C 105 ; WX 317 ; N i ; B 79 -12 328 715 ;
97
+ C 106 ; WX 309 ; N j ; B -95 -242 330 715 ;
98
+ C 107 ; WX 545 ; N k ; B 57 -12 567 742 ;
99
+ C 108 ; WX 306 ; N l ; B 76 -12 331 742 ;
100
+ C 109 ; WX 912 ; N m ; B 63 -12 894 502 ;
101
+ C 110 ; WX 618 ; N n ; B 63 -12 600 502 ;
102
+ C 111 ; WX 537 ; N o ; B 49 -12 522 502 ;
103
+ C 112 ; WX 590 ; N p ; B 22 -242 586 502 ;
104
+ C 113 ; WX 559 ; N q ; B 38 -242 567 525 ;
105
+ C 114 ; WX 402 ; N r ; B 69 -12 448 502 ;
106
+ C 115 ; WX 389 ; N s ; B 19 -12 397 502 ;
107
+ C 116 ; WX 341 ; N t ; B 84 -12 404 616 ;
108
+ C 117 ; WX 618 ; N u ; B 89 -12 609 502 ;
109
+ C 118 ; WX 510 ; N v ; B 84 -12 528 502 ;
110
+ C 119 ; WX 785 ; N w ; B 87 -12 808 502 ;
111
+ C 120 ; WX 516 ; N x ; B -4 -12 531 502 ;
112
+ C 121 ; WX 468 ; N y ; B -40 -242 505 502 ;
113
+ C 122 ; WX 468 ; N z ; B 4 -12 483 490 ;
114
+ C 123 ; WX 340 ; N braceleft ; B 100 -128 423 692 ;
115
+ C 124 ; WX 270 ; N bar ; B 130 -250 198 750 ;
116
+ C 125 ; WX 340 ; N braceright ; B -20 -128 302 692 ;
117
+ C 126 ; WX 570 ; N asciitilde ; B 98 176 522 318 ;
118
+ C 161 ; WX 240 ; N exclamdown ; B -18 -217 238 502 ;
119
+ C 162 ; WX 530 ; N cent ; B 94 -21 563 669 ;
120
+ C 163 ; WX 530 ; N sterling ; B 9 0 549 680 ;
121
+ C 164 ; WX 100 ; N fraction ; B -201 -24 369 698 ;
122
+ C 165 ; WX 530 ; N yen ; B 72 0 645 668 ;
123
+ C 166 ; WX 530 ; N florin ; B 4 -135 588 691 ;
124
+ C 167 ; WX 530 ; N section ; B 55 -115 533 707 ;
125
+ C 168 ; WX 530 ; N currency ; B 56 90 536 578 ;
126
+ C 169 ; WX 216 ; N quotesingle ; B 161 469 274 742 ;
127
+ C 170 ; WX 402 ; N quotedblleft ; B 134 488 473 748 ;
128
+ C 171 ; WX 462 ; N guillemotleft ; B 79 41 470 435 ;
129
+ C 172 ; WX 277 ; N guilsinglleft ; B 71 41 267 435 ;
130
+ C 173 ; WX 277 ; N guilsinglright ; B 44 41 240 435 ;
131
+ C 174 ; WX 607 ; N fi ; B -107 -242 589 742 ;
132
+ C 175 ; WX 603 ; N fl ; B -107 -242 628 742 ;
133
+ C 177 ; WX 500 ; N endash ; B 12 221 524 279 ;
134
+ C 178 ; WX 500 ; N dagger ; B 101 -125 519 717 ;
135
+ C 179 ; WX 490 ; N daggerdbl ; B 39 -119 509 717 ;
136
+ C 180 ; WX 265 ; N periodcentered ; B 89 187 211 312 ;
137
+ C 182 ; WX 560 ; N paragraph ; B 109 -101 637 692 ;
138
+ C 183 ; WX 500 ; N bullet ; B 110 192 429 512 ;
139
+ C 184 ; WX 216 ; N quotesinglbase ; B -7 -109 146 151 ;
140
+ C 185 ; WX 402 ; N quotedblbase ; B -7 -109 332 151 ;
141
+ C 186 ; WX 402 ; N quotedblright ; B 107 484 446 744 ;
142
+ C 187 ; WX 462 ; N guillemotright ; B 29 41 420 435 ;
143
+ C 188 ; WX 1000 ; N ellipsis ; B 85 -12 873 113 ;
144
+ C 189 ; WX 1200 ; N perthousand ; B 98 -25 1170 702 ;
145
+ C 191 ; WX 425 ; N questiondown ; B 3 -217 344 502 ;
146
+ C 193 ; WX 400 ; N grave ; B 146 542 368 723 ;
147
+ C 194 ; WX 400 ; N acute ; B 214 542 436 723 ;
148
+ C 195 ; WX 400 ; N circumflex ; B 187 546 484 720 ;
149
+ C 196 ; WX 400 ; N tilde ; B 137 563 492 682 ;
150
+ C 197 ; WX 400 ; N macron ; B 193 597 489 656 ;
151
+ C 198 ; WX 400 ; N breve ; B 227 568 501 698 ;
152
+ C 199 ; WX 402 ; N dotaccent ; B 252 570 359 680 ;
153
+ C 200 ; WX 400 ; N dieresis ; B 172 572 487 682 ;
154
+ C 202 ; WX 400 ; N ring ; B 186 550 402 752 ;
155
+ C 203 ; WX 400 ; N cedilla ; B 62 -230 241 0 ;
156
+ C 205 ; WX 400 ; N hungarumlaut ; B 176 546 455 750 ;
157
+ C 206 ; WX 350 ; N ogonek ; B 68 -219 248 0 ;
158
+ C 207 ; WX 400 ; N caron ; B 213 557 510 731 ;
159
+ C 208 ; WX 1000 ; N emdash ; B 12 221 1024 279 ;
160
+ C 225 ; WX 880 ; N AE ; B -88 0 941 692 ;
161
+ C 227 ; WX 425 ; N ordfeminine ; B 77 265 460 590 ;
162
+ C 232 ; WX 571 ; N Lslash ; B 11 0 574 692 ;
163
+ C 233 ; WX 753 ; N Oslash ; B 79 -45 754 736 ;
164
+ C 234 ; WX 1020 ; N OE ; B 79 0 1081 692 ;
165
+ C 235 ; WX 389 ; N ordmasculine ; B 86 265 420 590 ;
166
+ C 241 ; WX 779 ; N ae ; B 34 -12 797 514 ;
167
+ C 245 ; WX 317 ; N dotlessi ; B 79 -12 299 502 ;
168
+ C 248 ; WX 318 ; N lslash ; B 45 -12 376 742 ;
169
+ C 249 ; WX 537 ; N oslash ; B 49 -39 522 529 ;
170
+ C 250 ; WX 806 ; N oe ; B 49 -12 824 502 ;
171
+ C 251 ; WX 577 ; N germandbls ; B -107 -242 630 742 ;
172
+ C -1 ; WX 370 ; N onesuperior ; B 90 272 326 680 ;
173
+ C -1 ; WX 570 ; N minus ; B 58 221 542 279 ;
174
+ C -1 ; WX 400 ; N degree ; B 152 404 428 680 ;
175
+ C -1 ; WX 537 ; N oacute ; B 49 -12 530 723 ;
176
+ C -1 ; WX 753 ; N Odieresis ; B 79 -15 754 848 ;
177
+ C -1 ; WX 537 ; N odieresis ; B 49 -12 532 682 ;
178
+ C -1 ; WX 596 ; N Eacute ; B 3 0 657 890 ;
179
+ C -1 ; WX 618 ; N ucircumflex ; B 89 -12 609 720 ;
180
+ C -1 ; WX 890 ; N onequarter ; B 97 -24 805 698 ;
181
+ C -1 ; WX 570 ; N logicalnot ; B 58 102 542 389 ;
182
+ C -1 ; WX 596 ; N Ecircumflex ; B 3 0 657 876 ;
183
+ C -1 ; WX 890 ; N onehalf ; B 71 -24 812 698 ;
184
+ C -1 ; WX 753 ; N Otilde ; B 79 -15 754 842 ;
185
+ C -1 ; WX 618 ; N uacute ; B 89 -12 609 723 ;
186
+ C -1 ; WX 453 ; N eacute ; B 45 -12 508 723 ;
187
+ C -1 ; WX 317 ; N iacute ; B 79 -12 398 723 ;
188
+ C -1 ; WX 596 ; N Egrave ; B 3 0 657 890 ;
189
+ C -1 ; WX 317 ; N icircumflex ; B 79 -12 383 720 ;
190
+ C -1 ; WX 618 ; N mu ; B 11 -232 609 502 ;
191
+ C -1 ; WX 270 ; N brokenbar ; B 130 -175 198 675 ;
192
+ C -1 ; WX 584 ; N thorn ; B 16 -242 580 700 ;
193
+ C -1 ; WX 624 ; N Aring ; B -58 0 623 861 ;
194
+ C -1 ; WX 468 ; N yacute ; B -40 -242 505 723 ;
195
+ C -1 ; WX 591 ; N Ydieresis ; B 96 0 744 848 ;
196
+ C -1 ; WX 1100 ; N trademark ; B 91 277 1094 692 ;
197
+ C -1 ; WX 836 ; N registered ; B 91 -15 819 707 ;
198
+ C -1 ; WX 537 ; N ocircumflex ; B 49 -12 522 720 ;
199
+ C -1 ; WX 624 ; N Agrave ; B -58 0 623 890 ;
200
+ C -1 ; WX 533 ; N Scaron ; B 34 -15 561 888 ;
201
+ C -1 ; WX 794 ; N Ugrave ; B 131 -15 880 890 ;
202
+ C -1 ; WX 596 ; N Edieresis ; B 3 0 657 848 ;
203
+ C -1 ; WX 794 ; N Uacute ; B 131 -15 880 890 ;
204
+ C -1 ; WX 537 ; N otilde ; B 49 -12 525 682 ;
205
+ C -1 ; WX 618 ; N ntilde ; B 63 -12 600 682 ;
206
+ C -1 ; WX 468 ; N ydieresis ; B -40 -242 513 682 ;
207
+ C -1 ; WX 624 ; N Aacute ; B -58 0 642 890 ;
208
+ C -1 ; WX 537 ; N eth ; B 47 -12 521 742 ;
209
+ C -1 ; WX 561 ; N acircumflex ; B 31 -12 563 720 ;
210
+ C -1 ; WX 561 ; N aring ; B 31 -12 563 752 ;
211
+ C -1 ; WX 753 ; N Ograve ; B 79 -15 754 890 ;
212
+ C -1 ; WX 441 ; N ccedilla ; B 46 -230 465 502 ;
213
+ C -1 ; WX 570 ; N multiply ; B 88 22 532 478 ;
214
+ C -1 ; WX 570 ; N divide ; B 58 25 542 475 ;
215
+ C -1 ; WX 370 ; N twosuperior ; B 35 272 399 680 ;
216
+ C -1 ; WX 763 ; N Ntilde ; B -4 0 855 842 ;
217
+ C -1 ; WX 618 ; N ugrave ; B 89 -12 609 723 ;
218
+ C -1 ; WX 794 ; N Ucircumflex ; B 131 -15 880 876 ;
219
+ C -1 ; WX 624 ; N Atilde ; B -58 0 623 842 ;
220
+ C -1 ; WX 468 ; N zcaron ; B 4 -12 484 731 ;
221
+ C -1 ; WX 317 ; N idieresis ; B 79 -12 398 682 ;
222
+ C -1 ; WX 624 ; N Acircumflex ; B -58 0 623 876 ;
223
+ C -1 ; WX 345 ; N Icircumflex ; B 5 0 453 876 ;
224
+ C -1 ; WX 591 ; N Yacute ; B 96 0 744 890 ;
225
+ C -1 ; WX 753 ; N Oacute ; B 79 -15 754 890 ;
226
+ C -1 ; WX 624 ; N Adieresis ; B -58 0 623 848 ;
227
+ C -1 ; WX 622 ; N Zcaron ; B -20 0 703 888 ;
228
+ C -1 ; WX 561 ; N agrave ; B 31 -12 563 723 ;
229
+ C -1 ; WX 370 ; N threesuperior ; B 59 265 389 680 ;
230
+ C -1 ; WX 537 ; N ograve ; B 49 -12 522 723 ;
231
+ C -1 ; WX 890 ; N threequarters ; B 105 -24 816 698 ;
232
+ C -1 ; WX 770 ; N Eth ; B 12 0 774 692 ;
233
+ C -1 ; WX 570 ; N plusminus ; B 58 0 542 556 ;
234
+ C -1 ; WX 618 ; N udieresis ; B 89 -12 609 682 ;
235
+ C -1 ; WX 453 ; N edieresis ; B 45 -12 490 682 ;
236
+ C -1 ; WX 561 ; N aacute ; B 31 -12 571 723 ;
237
+ C -1 ; WX 317 ; N igrave ; B 55 -12 299 723 ;
238
+ C -1 ; WX 345 ; N Idieresis ; B 5 0 461 848 ;
239
+ C -1 ; WX 561 ; N adieresis ; B 31 -12 563 682 ;
240
+ C -1 ; WX 345 ; N Iacute ; B 5 0 506 890 ;
241
+ C -1 ; WX 836 ; N copyright ; B 91 -15 819 707 ;
242
+ C -1 ; WX 345 ; N Igrave ; B 5 0 428 890 ;
243
+ C -1 ; WX 661 ; N Ccedilla ; B 79 -230 723 707 ;
244
+ C -1 ; WX 389 ; N scaron ; B 19 -12 457 731 ;
245
+ C -1 ; WX 453 ; N egrave ; B 45 -12 471 723 ;
246
+ C -1 ; WX 753 ; N Ocircumflex ; B 79 -15 754 876 ;
247
+ C -1 ; WX 604 ; N Thorn ; B 5 0 616 692 ;
248
+ C -1 ; WX 561 ; N atilde ; B 31 -12 563 682 ;
249
+ C -1 ; WX 794 ; N Udieresis ; B 131 -15 880 848 ;
250
+ C -1 ; WX 453 ; N ecircumflex ; B 45 -12 475 720 ;
251
+ EndCharMetrics
252
+ StartKernData
253
+ StartKernPairs 690
254
+
255
+ KPX A y -20
256
+ KPX A x 10
257
+ KPX A w -30
258
+ KPX A v -30
259
+ KPX A u -10
260
+ KPX A t -6
261
+ KPX A s 15
262
+ KPX A r -12
263
+ KPX A quoteright -110
264
+ KPX A quotedblright -110
265
+ KPX A q 10
266
+ KPX A p -12
267
+ KPX A o -10
268
+ KPX A n -18
269
+ KPX A m -18
270
+ KPX A l -18
271
+ KPX A j 6
272
+ KPX A h -6
273
+ KPX A d 10
274
+ KPX A c -6
275
+ KPX A b -6
276
+ KPX A a 12
277
+ KPX A Y -76
278
+ KPX A X -8
279
+ KPX A W -80
280
+ KPX A V -90
281
+ KPX A U -60
282
+ KPX A T -72
283
+ KPX A Q -30
284
+ KPX A O -30
285
+ KPX A G -30
286
+ KPX A C -30
287
+
288
+ KPX B y -6
289
+ KPX B u -20
290
+ KPX B r -15
291
+ KPX B quoteright -40
292
+ KPX B quotedblright -30
293
+ KPX B o 6
294
+ KPX B l -20
295
+ KPX B k -15
296
+ KPX B i -12
297
+ KPX B h -15
298
+ KPX B e 6
299
+ KPX B a 12
300
+ KPX B W -20
301
+ KPX B V -50
302
+ KPX B U -50
303
+ KPX B T -20
304
+
305
+ KPX C z -6
306
+ KPX C y -18
307
+ KPX C u -18
308
+ KPX C quotedblright 20
309
+ KPX C i -5
310
+ KPX C e -6
311
+ KPX C a -6
312
+
313
+ KPX D y 18
314
+ KPX D u -10
315
+ KPX D quoteright -40
316
+ KPX D quotedblright -50
317
+ KPX D period -30
318
+ KPX D o 6
319
+ KPX D i 6
320
+ KPX D h -25
321
+ KPX D e 6
322
+ KPX D comma -20
323
+ KPX D a 6
324
+ KPX D Y -70
325
+ KPX D W -50
326
+ KPX D V -60
327
+
328
+ KPX E z -6
329
+ KPX E y -18
330
+ KPX E x 5
331
+ KPX E w -20
332
+ KPX E v -18
333
+ KPX E u -24
334
+ KPX E t -18
335
+ KPX E s 5
336
+ KPX E r -6
337
+ KPX E quoteright 10
338
+ KPX E quotedblright 10
339
+ KPX E q 10
340
+ KPX E period 10
341
+ KPX E p -12
342
+ KPX E o -6
343
+ KPX E n -12
344
+ KPX E m -12
345
+ KPX E l -12
346
+ KPX E k -10
347
+ KPX E j -6
348
+ KPX E i -12
349
+ KPX E g -12
350
+ KPX E e 5
351
+ KPX E d 10
352
+ KPX E comma 10
353
+ KPX E b -6
354
+
355
+ KPX F y -12
356
+ KPX F u -30
357
+ KPX F r -18
358
+ KPX F quoteright 15
359
+ KPX F quotedblright 35
360
+ KPX F period -180
361
+ KPX F o -30
362
+ KPX F l -6
363
+ KPX F i -12
364
+ KPX F e -30
365
+ KPX F comma -170
366
+ KPX F a -30
367
+ KPX F A -45
368
+
369
+ KPX G y -16
370
+ KPX G u -22
371
+ KPX G r -22
372
+ KPX G quoteright -20
373
+ KPX G quotedblright -20
374
+ KPX G o 10
375
+ KPX G n -22
376
+ KPX G l -24
377
+ KPX G i -12
378
+ KPX G h -18
379
+ KPX G e 10
380
+ KPX G a 5
381
+
382
+ KPX H y -18
383
+ KPX H u -30
384
+ KPX H quoteright 10
385
+ KPX H quotedblright 10
386
+ KPX H o -12
387
+ KPX H i -12
388
+ KPX H e -12
389
+ KPX H a -12
390
+
391
+ KPX I z -20
392
+ KPX I y -6
393
+ KPX I x -6
394
+ KPX I w -30
395
+ KPX I v -30
396
+ KPX I u -30
397
+ KPX I t -18
398
+ KPX I s -18
399
+ KPX I r -12
400
+ KPX I quoteright 10
401
+ KPX I quotedblright 10
402
+ KPX I p -18
403
+ KPX I o -12
404
+ KPX I n -18
405
+ KPX I m -18
406
+ KPX I l -6
407
+ KPX I k -6
408
+ KPX I g -12
409
+ KPX I f -6
410
+ KPX I d -6
411
+ KPX I c -12
412
+ KPX I b -6
413
+ KPX I a -6
414
+
415
+ KPX J y -12
416
+ KPX J u -36
417
+ KPX J quoteright 6
418
+ KPX J quotedblright 15
419
+ KPX J o -36
420
+ KPX J i -30
421
+ KPX J e -36
422
+ KPX J braceright 10
423
+ KPX J a -36
424
+
425
+ KPX K y -40
426
+ KPX K w -30
427
+ KPX K v -20
428
+ KPX K u -24
429
+ KPX K r -12
430
+ KPX K quoteright 25
431
+ KPX K quotedblright 40
432
+ KPX K o -24
433
+ KPX K n -18
434
+ KPX K i -6
435
+ KPX K h 6
436
+ KPX K e -12
437
+ KPX K a -6
438
+ KPX K Q -24
439
+ KPX K O -24
440
+ KPX K G -24
441
+ KPX K C -24
442
+
443
+ KPX L y -55
444
+ KPX L w -30
445
+ KPX L u -18
446
+ KPX L quoteright -110
447
+ KPX L quotedblright -110
448
+ KPX L l -16
449
+ KPX L j -18
450
+ KPX L i -18
451
+ KPX L a 10
452
+ KPX L Y -80
453
+ KPX L W -90
454
+ KPX L V -110
455
+ KPX L U -42
456
+ KPX L T -80
457
+ KPX L Q -48
458
+ KPX L O -48
459
+ KPX L G -48
460
+ KPX L C -48
461
+ KPX L A 30
462
+
463
+ KPX M y -18
464
+ KPX M u -24
465
+ KPX M quoteright 6
466
+ KPX M quotedblright 15
467
+ KPX M o -25
468
+ KPX M n -12
469
+ KPX M j -18
470
+ KPX M i -12
471
+ KPX M e -20
472
+ KPX M d -10
473
+ KPX M c -20
474
+ KPX M a -6
475
+
476
+ KPX N y -18
477
+ KPX N u -24
478
+ KPX N quoteright 10
479
+ KPX N quotedblright 10
480
+ KPX N o -25
481
+ KPX N i -12
482
+ KPX N e -20
483
+ KPX N a -22
484
+
485
+ KPX O z -6
486
+ KPX O y 12
487
+ KPX O w -10
488
+ KPX O v -10
489
+ KPX O u -6
490
+ KPX O t -6
491
+ KPX O s -6
492
+ KPX O r -6
493
+ KPX O quoteright -40
494
+ KPX O quotedblright -40
495
+ KPX O q 5
496
+ KPX O period -20
497
+ KPX O p -6
498
+ KPX O n -6
499
+ KPX O m -6
500
+ KPX O l -20
501
+ KPX O k -10
502
+ KPX O j -6
503
+ KPX O h -10
504
+ KPX O g -6
505
+ KPX O e 5
506
+ KPX O d 6
507
+ KPX O comma -10
508
+ KPX O c 5
509
+ KPX O b -6
510
+ KPX O a 5
511
+ KPX O Y -75
512
+ KPX O X -30
513
+ KPX O W -40
514
+ KPX O V -60
515
+ KPX O T -48
516
+ KPX O A -18
517
+
518
+ KPX P y 6
519
+ KPX P u -18
520
+ KPX P t -6
521
+ KPX P s -24
522
+ KPX P r -6
523
+ KPX P period -220
524
+ KPX P o -24
525
+ KPX P n -12
526
+ KPX P l -25
527
+ KPX P h -15
528
+ KPX P e -24
529
+ KPX P comma -220
530
+ KPX P a -24
531
+ KPX P I -30
532
+ KPX P H -30
533
+ KPX P E -30
534
+ KPX P A -75
535
+
536
+ KPX Q u -6
537
+ KPX Q quoteright -40
538
+ KPX Q quotedblright -50
539
+ KPX Q a -6
540
+ KPX Q Y -70
541
+ KPX Q X -12
542
+ KPX Q W -35
543
+ KPX Q V -60
544
+ KPX Q U -35
545
+ KPX Q T -36
546
+ KPX Q A -18
547
+
548
+ KPX R y -14
549
+ KPX R u -12
550
+ KPX R quoteright -30
551
+ KPX R quotedblright -20
552
+ KPX R o -12
553
+ KPX R hyphen -20
554
+ KPX R e -12
555
+ KPX R Y -50
556
+ KPX R W -30
557
+ KPX R V -40
558
+ KPX R U -40
559
+ KPX R T -30
560
+ KPX R Q -10
561
+ KPX R O -10
562
+ KPX R G -10
563
+ KPX R C -10
564
+ KPX R A -6
565
+
566
+ KPX S y -30
567
+ KPX S w -30
568
+ KPX S v -30
569
+ KPX S u -18
570
+ KPX S t -30
571
+ KPX S r -20
572
+ KPX S quoteright -38
573
+ KPX S quotedblright -30
574
+ KPX S p -18
575
+ KPX S n -24
576
+ KPX S m -24
577
+ KPX S l -30
578
+ KPX S k -24
579
+ KPX S j -25
580
+ KPX S i -30
581
+ KPX S h -30
582
+ KPX S e -6
583
+
584
+ KPX T z -70
585
+ KPX T y -60
586
+ KPX T w -64
587
+ KPX T u -74
588
+ KPX T semicolon -36
589
+ KPX T s -72
590
+ KPX T r -64
591
+ KPX T quoteright 45
592
+ KPX T quotedblright 50
593
+ KPX T period -100
594
+ KPX T parenright 54
595
+ KPX T o -90
596
+ KPX T m -64
597
+ KPX T i -34
598
+ KPX T hyphen -100
599
+ KPX T endash -60
600
+ KPX T emdash -60
601
+ KPX T e -90
602
+ KPX T comma -110
603
+ KPX T colon -10
604
+ KPX T bracketright 45
605
+ KPX T braceright 54
606
+ KPX T a -90
607
+ KPX T Y 12
608
+ KPX T X 18
609
+ KPX T W 6
610
+ KPX T T 18
611
+ KPX T Q -12
612
+ KPX T O -12
613
+ KPX T G -12
614
+ KPX T C -12
615
+ KPX T A -56
616
+
617
+ KPX U z -30
618
+ KPX U x -40
619
+ KPX U t -24
620
+ KPX U s -30
621
+ KPX U r -30
622
+ KPX U quoteright 10
623
+ KPX U quotedblright 10
624
+ KPX U p -40
625
+ KPX U n -45
626
+ KPX U m -45
627
+ KPX U l -12
628
+ KPX U k -12
629
+ KPX U i -24
630
+ KPX U h -6
631
+ KPX U g -30
632
+ KPX U d -40
633
+ KPX U c -35
634
+ KPX U b -6
635
+ KPX U a -40
636
+ KPX U A -45
637
+
638
+ KPX V y -46
639
+ KPX V u -42
640
+ KPX V semicolon -35
641
+ KPX V r -50
642
+ KPX V quoteright 75
643
+ KPX V quotedblright 70
644
+ KPX V period -130
645
+ KPX V parenright 64
646
+ KPX V o -62
647
+ KPX V i -10
648
+ KPX V hyphen -60
649
+ KPX V endash -20
650
+ KPX V emdash -20
651
+ KPX V e -52
652
+ KPX V comma -120
653
+ KPX V colon -18
654
+ KPX V bracketright 64
655
+ KPX V braceright 64
656
+ KPX V a -60
657
+ KPX V T 6
658
+ KPX V A -70
659
+
660
+ KPX W y -42
661
+ KPX W u -56
662
+ KPX W t -20
663
+ KPX W semicolon -28
664
+ KPX W r -40
665
+ KPX W quoteright 55
666
+ KPX W quotedblright 60
667
+ KPX W period -108
668
+ KPX W parenright 64
669
+ KPX W o -60
670
+ KPX W m -35
671
+ KPX W i -10
672
+ KPX W hyphen -40
673
+ KPX W endash -2
674
+ KPX W emdash -10
675
+ KPX W e -54
676
+ KPX W d -50
677
+ KPX W comma -108
678
+ KPX W colon -28
679
+ KPX W bracketright 55
680
+ KPX W braceright 64
681
+ KPX W a -60
682
+ KPX W T 12
683
+ KPX W Q -10
684
+ KPX W O -10
685
+ KPX W G -10
686
+ KPX W C -10
687
+ KPX W A -58
688
+
689
+ KPX X y -35
690
+ KPX X u -30
691
+ KPX X r -6
692
+ KPX X quoteright 35
693
+ KPX X quotedblright 15
694
+ KPX X i -6
695
+ KPX X e -10
696
+ KPX X a 5
697
+ KPX X Y -6
698
+ KPX X W -6
699
+ KPX X Q -30
700
+ KPX X O -30
701
+ KPX X G -30
702
+ KPX X C -30
703
+ KPX X A -18
704
+
705
+ KPX Y v -50
706
+ KPX Y u -58
707
+ KPX Y t -32
708
+ KPX Y semicolon -36
709
+ KPX Y quoteright 65
710
+ KPX Y quotedblright 70
711
+ KPX Y q -100
712
+ KPX Y period -90
713
+ KPX Y parenright 60
714
+ KPX Y o -72
715
+ KPX Y l 10
716
+ KPX Y hyphen -95
717
+ KPX Y endash -20
718
+ KPX Y emdash -20
719
+ KPX Y e -72
720
+ KPX Y d -80
721
+ KPX Y comma -80
722
+ KPX Y colon -36
723
+ KPX Y bracketright 64
724
+ KPX Y braceright 75
725
+ KPX Y a -82
726
+ KPX Y Y 12
727
+ KPX Y X 12
728
+ KPX Y W 12
729
+ KPX Y V 6
730
+ KPX Y T 25
731
+ KPX Y Q -5
732
+ KPX Y O -5
733
+ KPX Y G -5
734
+ KPX Y C -5
735
+ KPX Y A -36
736
+
737
+ KPX Z y -36
738
+ KPX Z w -36
739
+ KPX Z u -12
740
+ KPX Z quoteright 10
741
+ KPX Z quotedblright 10
742
+ KPX Z o -6
743
+ KPX Z i -12
744
+ KPX Z e -6
745
+ KPX Z a -6
746
+ KPX Z Q -30
747
+ KPX Z O -30
748
+ KPX Z G -30
749
+ KPX Z C -30
750
+ KPX Z A 12
751
+
752
+ KPX a quoteright -40
753
+ KPX a quotedblright -40
754
+
755
+ KPX b y -6
756
+ KPX b w -15
757
+ KPX b v -15
758
+ KPX b quoteright -50
759
+ KPX b quotedblright -50
760
+ KPX b period -40
761
+ KPX b comma -30
762
+
763
+ KPX braceleft Y 64
764
+ KPX braceleft W 64
765
+ KPX braceleft V 64
766
+ KPX braceleft T 54
767
+ KPX braceleft J 80
768
+
769
+ KPX bracketleft Y 64
770
+ KPX bracketleft W 64
771
+ KPX bracketleft V 64
772
+ KPX bracketleft T 54
773
+ KPX bracketleft J 80
774
+
775
+ KPX c quoteright -20
776
+ KPX c quotedblright -20
777
+
778
+ KPX colon space -30
779
+
780
+ KPX comma space -40
781
+ KPX comma quoteright -80
782
+ KPX comma quotedblright -80
783
+
784
+ KPX d quoteright -12
785
+ KPX d quotedblright -12
786
+
787
+ KPX e x -10
788
+ KPX e w -10
789
+ KPX e quoteright -30
790
+ KPX e quotedblright -30
791
+
792
+ KPX f quoteright 110
793
+ KPX f quotedblright 110
794
+ KPX f period -20
795
+ KPX f parenright 100
796
+ KPX f comma -20
797
+ KPX f bracketright 90
798
+ KPX f braceright 90
799
+
800
+ KPX g y 30
801
+ KPX g p 12
802
+ KPX g f 42
803
+
804
+ KPX h quoteright -80
805
+ KPX h quotedblright -80
806
+
807
+ KPX j quoteright -20
808
+ KPX j quotedblright -20
809
+ KPX j period -35
810
+ KPX j comma -20
811
+
812
+ KPX k quoteright -30
813
+ KPX k quotedblright -50
814
+
815
+ KPX m quoteright -80
816
+ KPX m quotedblright -80
817
+
818
+ KPX n quoteright -80
819
+ KPX n quotedblright -80
820
+
821
+ KPX o z -10
822
+ KPX o y -20
823
+ KPX o x -20
824
+ KPX o w -30
825
+ KPX o v -35
826
+ KPX o quoteright -60
827
+ KPX o quotedblright -50
828
+ KPX o period -30
829
+ KPX o comma -20
830
+
831
+ KPX p z -10
832
+ KPX p w -15
833
+ KPX p quoteright -50
834
+ KPX p quotedblright -70
835
+ KPX p period -30
836
+ KPX p comma -20
837
+
838
+ KPX parenleft Y 75
839
+ KPX parenleft W 75
840
+ KPX parenleft V 75
841
+ KPX parenleft T 64
842
+ KPX parenleft J 80
843
+
844
+ KPX period space -40
845
+ KPX period quoteright -80
846
+ KPX period quotedblright -80
847
+
848
+ KPX q quoteright -20
849
+ KPX q quotedblright -30
850
+ KPX q period -20
851
+ KPX q comma -10
852
+
853
+ KPX quotedblleft z -30
854
+ KPX quotedblleft x -40
855
+ KPX quotedblleft w -12
856
+ KPX quotedblleft v -12
857
+ KPX quotedblleft u -12
858
+ KPX quotedblleft t -12
859
+ KPX quotedblleft s -30
860
+ KPX quotedblleft r -12
861
+ KPX quotedblleft q -40
862
+ KPX quotedblleft p -12
863
+ KPX quotedblleft o -30
864
+ KPX quotedblleft n -12
865
+ KPX quotedblleft m -12
866
+ KPX quotedblleft l 10
867
+ KPX quotedblleft k 10
868
+ KPX quotedblleft h 10
869
+ KPX quotedblleft g -30
870
+ KPX quotedblleft e -40
871
+ KPX quotedblleft d -40
872
+ KPX quotedblleft c -40
873
+ KPX quotedblleft b 24
874
+ KPX quotedblleft a -60
875
+ KPX quotedblleft Y 12
876
+ KPX quotedblleft X 28
877
+ KPX quotedblleft W 28
878
+ KPX quotedblleft V 28
879
+ KPX quotedblleft T 36
880
+ KPX quotedblleft A -90
881
+
882
+ KPX quotedblright space -40
883
+ KPX quotedblright period -100
884
+ KPX quotedblright comma -100
885
+
886
+ KPX quoteleft z -30
887
+ KPX quoteleft y -10
888
+ KPX quoteleft x -40
889
+ KPX quoteleft w -12
890
+ KPX quoteleft v -12
891
+ KPX quoteleft u -12
892
+ KPX quoteleft t -12
893
+ KPX quoteleft s -30
894
+ KPX quoteleft r -12
895
+ KPX quoteleft quoteleft -18
896
+ KPX quoteleft q -30
897
+ KPX quoteleft p -12
898
+ KPX quoteleft o -30
899
+ KPX quoteleft n -12
900
+ KPX quoteleft m -12
901
+ KPX quoteleft l 10
902
+ KPX quoteleft k 10
903
+ KPX quoteleft h 10
904
+ KPX quoteleft g -30
905
+ KPX quoteleft e -30
906
+ KPX quoteleft d -30
907
+ KPX quoteleft c -30
908
+ KPX quoteleft b 24
909
+ KPX quoteleft a -45
910
+ KPX quoteleft Y 12
911
+ KPX quoteleft X 28
912
+ KPX quoteleft W 28
913
+ KPX quoteleft V 28
914
+ KPX quoteleft T 36
915
+ KPX quoteleft A -90
916
+
917
+ KPX quoteright v -35
918
+ KPX quoteright t -35
919
+ KPX quoteright space -40
920
+ KPX quoteright s -55
921
+ KPX quoteright r -25
922
+ KPX quoteright quoteright -18
923
+ KPX quoteright period -100
924
+ KPX quoteright m -25
925
+ KPX quoteright l -12
926
+ KPX quoteright d -70
927
+ KPX quoteright comma -100
928
+
929
+ KPX r y 18
930
+ KPX r w 6
931
+ KPX r v 6
932
+ KPX r t 8
933
+ KPX r quotedblright -15
934
+ KPX r q -24
935
+ KPX r period -120
936
+ KPX r o -6
937
+ KPX r l -20
938
+ KPX r k -20
939
+ KPX r hyphen -30
940
+ KPX r h -20
941
+ KPX r f 8
942
+ KPX r emdash -20
943
+ KPX r e -26
944
+ KPX r d -26
945
+ KPX r comma -110
946
+ KPX r c -12
947
+ KPX r a -20
948
+
949
+ KPX s quoteright -40
950
+ KPX s quotedblright -45
951
+
952
+ KPX semicolon space -30
953
+
954
+ KPX space quotesinglbase -30
955
+ KPX space quoteleft -40
956
+ KPX space quotedblleft -40
957
+ KPX space quotedblbase -30
958
+ KPX space Y -70
959
+ KPX space W -70
960
+ KPX space V -70
961
+
962
+ KPX t quoteright 10
963
+ KPX t quotedblright -10
964
+
965
+ KPX u quoteright -55
966
+ KPX u quotedblright -50
967
+
968
+ KPX v quoteright -20
969
+ KPX v quotedblright -30
970
+ KPX v q -6
971
+ KPX v period -70
972
+ KPX v o -6
973
+ KPX v e -6
974
+ KPX v d -6
975
+ KPX v comma -70
976
+ KPX v c -6
977
+ KPX v a -6
978
+
979
+ KPX w quoteright -20
980
+ KPX w quotedblright -30
981
+ KPX w period -62
982
+ KPX w comma -62
983
+
984
+ KPX x y 12
985
+ KPX x w -6
986
+ KPX x quoteright -40
987
+ KPX x quotedblright -50
988
+ KPX x q -6
989
+ KPX x o -6
990
+ KPX x e -6
991
+ KPX x d -6
992
+ KPX x c -6
993
+
994
+ KPX y quoteright -10
995
+ KPX y quotedblright -20
996
+ KPX y period -70
997
+ KPX y emdash 40
998
+ KPX y comma -60
999
+
1000
+ KPX z quoteright -40
1001
+ KPX z quotedblright -50
1002
+ KPX z o -6
1003
+ KPX z e -6
1004
+ KPX z d -6
1005
+ KPX z c -6
1006
+ EndKernPairs
1007
+ EndKernData
1008
+ EndFontMetrics
shared/package-files/8b/8bb850c565aa389fdc16f3a46965ad23d82adff60f2393fc2762b63185e8e6c9/blob ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2010-2020 Benjamin Peterson
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ the Software, and to permit persons to whom the Software is furnished to do so,
8
+ subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
shared/package-files/8b/8bba1a38cadd44be6132d04665742d0768d1fe020372a96d73424c64f7931cc6/blob ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Optional, Union, overload
3
+ from typing_extensions import Literal
4
+
5
+ if sys.platform == "win32":
6
+ SND_FILENAME: int
7
+ SND_ALIAS: int
8
+ SND_LOOP: int
9
+ SND_MEMORY: int
10
+ SND_PURGE: int
11
+ SND_ASYNC: int
12
+ SND_NODEFAULT: int
13
+ SND_NOSTOP: int
14
+ SND_NOWAIT: int
15
+
16
+ MB_ICONASTERISK: int
17
+ MB_ICONEXCLAMATION: int
18
+ MB_ICONHAND: int
19
+ MB_ICONQUESTION: int
20
+ MB_OK: int
21
+ def Beep(frequency: int, duration: int) -> None: ...
22
+ # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible
23
+ @overload
24
+ def PlaySound(sound: Optional[bytes], flags: Literal[4]) -> None: ...
25
+ @overload
26
+ def PlaySound(sound: Optional[Union[str, bytes]], flags: int) -> None: ...
27
+ def MessageBeep(type: int = ...) -> None: ...
shared/package-files/8b/8bbbffb486494564490858800c2c1538ea7fb7d568fda669fdc10bd2570e049f/blob ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .cache import Cache as Cache
2
+ from .decorators import cached as cached, cachedmethod as cachedmethod
3
+ from .lfu import LFUCache as LFUCache
4
+ from .lru import LRUCache as LRUCache
5
+ from .rr import RRCache as RRCache
6
+ from .ttl import TTLCache as TTLCache
shared/package-files/8b/8bbc55b991109d8aee328e317ef188d22ce8cc8d6a26f70f3bc0ebeca454d158/blob ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.lexers.fortran
3
+ ~~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Lexers for Fortran languages.
6
+
7
+ :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import re
12
+
13
+ from pygments.lexer import RegexLexer, bygroups, include, words, using, default
14
+ from pygments.token import Text, Comment, Operator, Keyword, Name, String, \
15
+ Number, Punctuation, Generic
16
+
17
+ __all__ = ['FortranLexer', 'FortranFixedLexer']
18
+
19
+
20
+ class FortranLexer(RegexLexer):
21
+ """
22
+ Lexer for FORTRAN 90 code.
23
+
24
+ .. versionadded:: 0.10
25
+ """
26
+ name = 'Fortran'
27
+ url = 'https://fortran-lang.org/'
28
+ aliases = ['fortran', 'f90']
29
+ filenames = ['*.f03', '*.f90', '*.F03', '*.F90']
30
+ mimetypes = ['text/x-fortran']
31
+ flags = re.IGNORECASE | re.MULTILINE
32
+
33
+ # Data Types: INTEGER, REAL, COMPLEX, LOGICAL, CHARACTER and DOUBLE PRECISION
34
+ # Operators: **, *, +, -, /, <, >, <=, >=, ==, /=
35
+ # Logical (?): NOT, AND, OR, EQV, NEQV
36
+
37
+ # Builtins:
38
+ # http://gcc.gnu.org/onlinedocs/gcc-3.4.6/g77/Table-of-Intrinsic-Functions.html
39
+
40
+ tokens = {
41
+ 'root': [
42
+ (r'^#.*\n', Comment.Preproc),
43
+ (r'!.*\n', Comment),
44
+ include('strings'),
45
+ include('core'),
46
+ (r'[a-z][\w$]*', Name),
47
+ include('nums'),
48
+ (r'[\s]+', Text.Whitespace),
49
+ ],
50
+ 'core': [
51
+ # Statements
52
+
53
+ (r'\b(DO)(\s+)(CONCURRENT)\b', bygroups(Keyword, Text.Whitespace, Keyword)),
54
+ (r'\b(GO)(\s*)(TO)\b', bygroups(Keyword, Text.Whitespace, Keyword)),
55
+
56
+ (words((
57
+ 'ABSTRACT', 'ACCEPT', 'ALL', 'ALLSTOP', 'ALLOCATABLE', 'ALLOCATE',
58
+ 'ARRAY', 'ASSIGN', 'ASSOCIATE', 'ASYNCHRONOUS', 'BACKSPACE', 'BIND',
59
+ 'BLOCK', 'BLOCKDATA', 'BYTE', 'CALL', 'CASE', 'CLASS', 'CLOSE',
60
+ 'CODIMENSION', 'COMMON', 'CONTIGUOUS', 'CONTAINS',
61
+ 'CONTINUE', 'CRITICAL', 'CYCLE', 'DATA', 'DEALLOCATE', 'DECODE',
62
+ 'DEFERRED', 'DIMENSION', 'DO', 'ELEMENTAL', 'ELSE', 'ENCODE', 'END',
63
+ 'ENDASSOCIATE', 'ENDBLOCK', 'ENDDO', 'ENDENUM', 'ENDFORALL',
64
+ 'ENDFUNCTION', 'ENDIF', 'ENDINTERFACE', 'ENDMODULE', 'ENDPROGRAM',
65
+ 'ENDSELECT', 'ENDSUBMODULE', 'ENDSUBROUTINE', 'ENDTYPE', 'ENDWHERE',
66
+ 'ENTRY', 'ENUM', 'ENUMERATOR', 'EQUIVALENCE', 'ERROR STOP', 'EXIT',
67
+ 'EXTENDS', 'EXTERNAL', 'EXTRINSIC', 'FILE', 'FINAL', 'FORALL', 'FORMAT',
68
+ 'FUNCTION', 'GENERIC', 'IF', 'IMAGES', 'IMPLICIT',
69
+ 'IMPORT', 'IMPURE', 'INCLUDE', 'INQUIRE', 'INTENT', 'INTERFACE',
70
+ 'INTRINSIC', 'IS', 'LOCK', 'MEMORY', 'MODULE', 'NAMELIST', 'NULLIFY',
71
+ 'NONE', 'NON_INTRINSIC', 'NON_OVERRIDABLE', 'NOPASS', 'ONLY', 'OPEN',
72
+ 'OPTIONAL', 'OPTIONS', 'PARAMETER', 'PASS', 'PAUSE', 'POINTER', 'PRINT',
73
+ 'PRIVATE', 'PROGRAM', 'PROCEDURE', 'PROTECTED', 'PUBLIC', 'PURE', 'READ',
74
+ 'RECURSIVE', 'RESULT', 'RETURN', 'REWIND', 'SAVE', 'SELECT', 'SEQUENCE',
75
+ 'STOP', 'SUBMODULE', 'SUBROUTINE', 'SYNC', 'SYNCALL', 'SYNCIMAGES',
76
+ 'SYNCMEMORY', 'TARGET', 'THEN', 'TYPE', 'UNLOCK', 'USE', 'VALUE',
77
+ 'VOLATILE', 'WHERE', 'WRITE', 'WHILE'), prefix=r'\b', suffix=r'\s*\b'),
78
+ Keyword),
79
+
80
+ # Data Types
81
+ (words((
82
+ 'CHARACTER', 'COMPLEX', 'DOUBLE PRECISION', 'DOUBLE COMPLEX', 'INTEGER',
83
+ 'LOGICAL', 'REAL', 'C_INT', 'C_SHORT', 'C_LONG', 'C_LONG_LONG',
84
+ 'C_SIGNED_CHAR', 'C_SIZE_T', 'C_INT8_T', 'C_INT16_T', 'C_INT32_T',
85
+ 'C_INT64_T', 'C_INT_LEAST8_T', 'C_INT_LEAST16_T', 'C_INT_LEAST32_T',
86
+ 'C_INT_LEAST64_T', 'C_INT_FAST8_T', 'C_INT_FAST16_T', 'C_INT_FAST32_T',
87
+ 'C_INT_FAST64_T', 'C_INTMAX_T', 'C_INTPTR_T', 'C_FLOAT', 'C_DOUBLE',
88
+ 'C_LONG_DOUBLE', 'C_FLOAT_COMPLEX', 'C_DOUBLE_COMPLEX',
89
+ 'C_LONG_DOUBLE_COMPLEX', 'C_BOOL', 'C_CHAR', 'C_PTR', 'C_FUNPTR'),
90
+ prefix=r'\b', suffix=r'\s*\b'),
91
+ Keyword.Type),
92
+
93
+ # Operators
94
+ (r'(\*\*|\*|\+|-|\/|<|>|<=|>=|==|\/=|=)', Operator),
95
+
96
+ (r'(::)', Keyword.Declaration),
97
+
98
+ (r'[()\[\],:&%;.]', Punctuation),
99
+ # Intrinsics
100
+ (words((
101
+ 'Abort', 'Abs', 'Access', 'AChar', 'ACos', 'ACosH', 'AdjustL',
102
+ 'AdjustR', 'AImag', 'AInt', 'Alarm', 'All', 'Allocated', 'ALog',
103
+ 'AMax', 'AMin', 'AMod', 'And', 'ANInt', 'Any', 'ASin', 'ASinH',
104
+ 'Associated', 'ATan', 'ATanH', 'Atomic_Define', 'Atomic_Ref',
105
+ 'BesJ', 'BesJN', 'Bessel_J0', 'Bessel_J1', 'Bessel_JN', 'Bessel_Y0',
106
+ 'Bessel_Y1', 'Bessel_YN', 'BesY', 'BesYN', 'BGE', 'BGT', 'BLE',
107
+ 'BLT', 'Bit_Size', 'BTest', 'CAbs', 'CCos', 'Ceiling', 'CExp',
108
+ 'Char', 'ChDir', 'ChMod', 'CLog', 'Cmplx', 'Command_Argument_Count',
109
+ 'Complex', 'Conjg', 'Cos', 'CosH', 'Count', 'CPU_Time', 'CShift',
110
+ 'CSin', 'CSqRt', 'CTime', 'C_Loc', 'C_Associated',
111
+ 'C_Null_Ptr', 'C_Null_Funptr', 'C_F_Pointer', 'C_F_ProcPointer',
112
+ 'C_Null_Char', 'C_Alert', 'C_Backspace', 'C_Form_Feed', 'C_FunLoc',
113
+ 'C_Sizeof', 'C_New_Line', 'C_Carriage_Return',
114
+ 'C_Horizontal_Tab', 'C_Vertical_Tab', 'DAbs', 'DACos', 'DASin',
115
+ 'DATan', 'Date_and_Time', 'DbesJ', 'DbesJN', 'DbesY',
116
+ 'DbesYN', 'Dble', 'DCos', 'DCosH', 'DDiM', 'DErF',
117
+ 'DErFC', 'DExp', 'Digits', 'DiM', 'DInt', 'DLog', 'DMax',
118
+ 'DMin', 'DMod', 'DNInt', 'Dot_Product', 'DProd', 'DSign', 'DSinH',
119
+ 'DShiftL', 'DShiftR', 'DSin', 'DSqRt', 'DTanH', 'DTan', 'DTime',
120
+ 'EOShift', 'Epsilon', 'ErF', 'ErFC', 'ErFC_Scaled', 'ETime',
121
+ 'Execute_Command_Line', 'Exit', 'Exp', 'Exponent', 'Extends_Type_Of',
122
+ 'FDate', 'FGet', 'FGetC', 'FindLoc', 'Float', 'Floor', 'Flush',
123
+ 'FNum', 'FPutC', 'FPut', 'Fraction', 'FSeek', 'FStat', 'FTell',
124
+ 'Gamma', 'GError', 'GetArg', 'Get_Command', 'Get_Command_Argument',
125
+ 'Get_Environment_Variable', 'GetCWD', 'GetEnv', 'GetGId', 'GetLog',
126
+ 'GetPId', 'GetUId', 'GMTime', 'HostNm', 'Huge', 'Hypot', 'IAbs',
127
+ 'IAChar', 'IAll', 'IAnd', 'IAny', 'IArgC', 'IBClr', 'IBits',
128
+ 'IBSet', 'IChar', 'IDate', 'IDiM', 'IDInt', 'IDNInt', 'IEOr',
129
+ 'IErrNo', 'IFix', 'Imag', 'ImagPart', 'Image_Index', 'Index',
130
+ 'Int', 'IOr', 'IParity', 'IRand', 'IsaTty', 'IShft', 'IShftC',
131
+ 'ISign', 'Iso_C_Binding', 'Is_Contiguous', 'Is_Iostat_End',
132
+ 'Is_Iostat_Eor', 'ITime', 'Kill', 'Kind', 'LBound', 'LCoBound',
133
+ 'Len', 'Len_Trim', 'LGe', 'LGt', 'Link', 'LLe', 'LLt', 'LnBlnk',
134
+ 'Loc', 'Log', 'Log_Gamma', 'Logical', 'Long', 'LShift', 'LStat',
135
+ 'LTime', 'MaskL', 'MaskR', 'MatMul', 'Max', 'MaxExponent',
136
+ 'MaxLoc', 'MaxVal', 'MClock', 'Merge', 'Merge_Bits', 'Move_Alloc',
137
+ 'Min', 'MinExponent', 'MinLoc', 'MinVal', 'Mod', 'Modulo', 'MvBits',
138
+ 'Nearest', 'New_Line', 'NInt', 'Norm2', 'Not', 'Null', 'Num_Images',
139
+ 'Or', 'Pack', 'Parity', 'PError', 'Precision', 'Present', 'Product',
140
+ 'Radix', 'Rand', 'Random_Number', 'Random_Seed', 'Range', 'Real',
141
+ 'RealPart', 'Rename', 'Repeat', 'Reshape', 'RRSpacing', 'RShift',
142
+ 'Same_Type_As', 'Scale', 'Scan', 'Second', 'Selected_Char_Kind',
143
+ 'Selected_Int_Kind', 'Selected_Real_Kind', 'Set_Exponent', 'Shape',
144
+ 'ShiftA', 'ShiftL', 'ShiftR', 'Short', 'Sign', 'Signal', 'SinH',
145
+ 'Sin', 'Sleep', 'Sngl', 'Spacing', 'Spread', 'SqRt', 'SRand',
146
+ 'Stat', 'Storage_Size', 'Sum', 'SymLnk', 'System', 'System_Clock',
147
+ 'Tan', 'TanH', 'Time', 'This_Image', 'Tiny', 'TrailZ', 'Transfer',
148
+ 'Transpose', 'Trim', 'TtyNam', 'UBound', 'UCoBound', 'UMask',
149
+ 'Unlink', 'Unpack', 'Verify', 'XOr', 'ZAbs', 'ZCos', 'ZExp',
150
+ 'ZLog', 'ZSin', 'ZSqRt'), prefix=r'\b', suffix=r'\s*\b'),
151
+ Name.Builtin),
152
+
153
+ # Booleans
154
+ (r'\.(true|false)\.', Name.Builtin),
155
+ # Comparing Operators
156
+ (r'\.(eq|ne|lt|le|gt|ge|not|and|or|eqv|neqv)\.', Operator.Word),
157
+ ],
158
+
159
+ 'strings': [
160
+ (r'"(\\[0-7]+|\\[^0-7]|[^"\\])*"', String.Double),
161
+ (r"'(\\[0-7]+|\\[^0-7]|[^'\\])*'", String.Single),
162
+ ],
163
+
164
+ 'nums': [
165
+ (r'\d+(?![.e])(_([1-9]|[a-z]\w*))?', Number.Integer),
166
+ (r'[+-]?\d*\.\d+([ed][-+]?\d+)?(_([1-9]|[a-z]\w*))?', Number.Float),
167
+ (r'[+-]?\d+\.\d*([ed][-+]?\d+)?(_([1-9]|[a-z]\w*))?', Number.Float),
168
+ (r'[+-]?\d+(\.\d*)?[ed][-+]?\d+(_([1-9]|[a-z]\w*))?', Number.Float),
169
+ ],
170
+ }
171
+
172
+
173
+ class FortranFixedLexer(RegexLexer):
174
+ """
175
+ Lexer for fixed format Fortran.
176
+
177
+ .. versionadded:: 2.1
178
+ """
179
+ name = 'FortranFixed'
180
+ aliases = ['fortranfixed']
181
+ filenames = ['*.f', '*.F']
182
+
183
+ flags = re.IGNORECASE
184
+
185
+ def _lex_fortran(self, match, ctx=None):
186
+ """Lex a line just as free form fortran without line break."""
187
+ lexer = FortranLexer()
188
+ text = match.group(0) + "\n"
189
+ for index, token, value in lexer.get_tokens_unprocessed(text):
190
+ value = value.replace('\n', '')
191
+ if value != '':
192
+ yield index, token, value
193
+
194
+ tokens = {
195
+ 'root': [
196
+ (r'[C*].*\n', Comment),
197
+ (r'#.*\n', Comment.Preproc),
198
+ (r' {0,4}!.*\n', Comment),
199
+ (r'(.{5})', Name.Label, 'cont-char'),
200
+ (r'.*\n', using(FortranLexer)),
201
+ ],
202
+ 'cont-char': [
203
+ (' ', Text, 'code'),
204
+ ('0', Comment, 'code'),
205
+ ('.', Generic.Strong, 'code'),
206
+ ],
207
+ 'code': [
208
+ (r'(.{66})(.*)(\n)',
209
+ bygroups(_lex_fortran, Comment, Text.Whitespace), 'root'),
210
+ (r'(.*)(\n)', bygroups(_lex_fortran, Text.Whitespace), 'root'),
211
+ default('root'),
212
+ ]
213
+ }
shared/package-files/8b/8bc0648758f4ee980fea922fcc5c45219eee0254757d03826c81e1eefd38c70f/blob ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from ._typedefs cimport intp_t
2
+
3
+ from cython cimport floating
4
+
5
+ cdef int simultaneous_sort(
6
+ floating *dist,
7
+ intp_t *idx,
8
+ intp_t size,
9
+ ) noexcept nogil
shared/package-files/8b/8bc0e900307c66122e70a73c96df497d86d000d46f47aeeee7da107f9c229ef8/blob ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if defined(DETECT_FEATURES) && defined(__INTEL_COMPILER)
2
+ /*
3
+ * Unlike GCC and CLANG, Intel Compiler exposes all supported intrinsics,
4
+ * whether or not the build options for those features are specified.
5
+ * Therefore, we must test #definitions of CPU features when option native/host
6
+ * is enabled via `--cpu-baseline` or through env var `CFLAGS` otherwise
7
+ * the test will be broken and leads to enable all possible features.
8
+ */
9
+ #if !defined(__AVX512FP16__)
10
+ #error "HOST/ARCH doesn't support Sapphire Rapids AVX512FP16 features"
11
+ #endif
12
+ #endif
13
+
14
+ #include <immintrin.h>
15
+
16
+ int main(int argc, char **argv)
17
+ {
18
+ /* clang has a bug regarding our spr coode, see gh-23730. */
19
+ #if __clang__
20
+ #error
21
+ #endif
22
+ __m512h a = _mm512_loadu_ph((void*)argv[argc-1]);
23
+ __m512h temp = _mm512_fmadd_ph(a, a, a);
24
+ _mm512_storeu_ph((void*)(argv[argc-1]), temp);
25
+ return 0;
26
+ }
shared/package-files/8b/8bc152afd712148ae1d7a3bc87b7289bc2cab5df67b0b63cc221214a9935fda6/blob ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Charset-Normalizer
3
+ ~~~~~~~~~~~~~~
4
+ The Real First Universal Charset Detector.
5
+ A library that helps you read text from an unknown charset encoding.
6
+ Motivated by chardet, This package is trying to resolve the issue by taking a new approach.
7
+ All IANA character set names for which the Python core library provides codecs are supported.
8
+
9
+ Basic usage:
10
+ >>> from charset_normalizer import from_bytes
11
+ >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието трябва да бъде безплатно, поне що се отнася до началното и основното образование.'.encode('utf_8'))
12
+ >>> "utf_8" in results
13
+ True
14
+ >>> best_result = results.best()
15
+ >>> str(best_result)
16
+ 'Bсеки човек има право на образование. Oбразованието трябва да бъде безплатно, поне що се отнася до началното и основното образование.'
17
+
18
+ Others methods and usages are available - see the full documentation
19
+ at <https://github.com/Ousret/charset_normalizer>.
20
+ :copyright: (c) 2021 by Ahmed TAHRI
21
+ :license: MIT, see LICENSE for more details.
22
+ """
23
+ from charset_normalizer.api import from_fp, from_path, from_bytes, normalize
24
+ from charset_normalizer.legacy import detect
25
+ from charset_normalizer.version import __version__, VERSION
26
+ from charset_normalizer.models import CharsetMatch, CharsetMatches
27
+
28
+ # Backward-compatible v1 imports
29
+ from charset_normalizer.models import CharsetNormalizerMatch
30
+ import charset_normalizer.api as CharsetDetector
31
+ CharsetNormalizerMatches = CharsetDetector
shared/package-files/8b/8bc19c6d27178483db3047bbbae3205ea87f714da6666d9fea1b29220996e6e3/blob ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.crypto.crypto import (cycle_list,
2
+ encipher_shift, encipher_affine, encipher_substitution,
3
+ check_and_join, encipher_vigenere, decipher_vigenere, bifid5_square,
4
+ bifid6_square, encipher_hill, decipher_hill,
5
+ encipher_bifid5, encipher_bifid6, decipher_bifid5,
6
+ decipher_bifid6, encipher_kid_rsa, decipher_kid_rsa,
7
+ kid_rsa_private_key, kid_rsa_public_key, decipher_rsa, rsa_private_key,
8
+ rsa_public_key, encipher_rsa, lfsr_connection_polynomial,
9
+ lfsr_autocorrelation, lfsr_sequence, encode_morse, decode_morse,
10
+ elgamal_private_key, elgamal_public_key, decipher_elgamal,
11
+ encipher_elgamal, dh_private_key, dh_public_key, dh_shared_key,
12
+ padded_key, encipher_bifid, decipher_bifid, bifid_square, bifid5,
13
+ bifid6, bifid10, decipher_gm, encipher_gm, gm_public_key,
14
+ gm_private_key, bg_private_key, bg_public_key, encipher_bg, decipher_bg,
15
+ encipher_rot13, decipher_rot13, encipher_atbash, decipher_atbash,
16
+ encipher_railfence, decipher_railfence)
17
+
18
+ __all__ = [
19
+ 'cycle_list', 'encipher_shift', 'encipher_affine',
20
+ 'encipher_substitution', 'check_and_join', 'encipher_vigenere',
21
+ 'decipher_vigenere', 'bifid5_square', 'bifid6_square', 'encipher_hill',
22
+ 'decipher_hill', 'encipher_bifid5', 'encipher_bifid6', 'decipher_bifid5',
23
+ 'decipher_bifid6', 'encipher_kid_rsa', 'decipher_kid_rsa',
24
+ 'kid_rsa_private_key', 'kid_rsa_public_key', 'decipher_rsa',
25
+ 'rsa_private_key', 'rsa_public_key', 'encipher_rsa',
26
+ 'lfsr_connection_polynomial', 'lfsr_autocorrelation', 'lfsr_sequence',
27
+ 'encode_morse', 'decode_morse', 'elgamal_private_key',
28
+ 'elgamal_public_key', 'decipher_elgamal', 'encipher_elgamal',
29
+ 'dh_private_key', 'dh_public_key', 'dh_shared_key', 'padded_key',
30
+ 'encipher_bifid', 'decipher_bifid', 'bifid_square', 'bifid5', 'bifid6',
31
+ 'bifid10', 'decipher_gm', 'encipher_gm', 'gm_public_key',
32
+ 'gm_private_key', 'bg_private_key', 'bg_public_key', 'encipher_bg',
33
+ 'decipher_bg', 'encipher_rot13', 'decipher_rot13', 'encipher_atbash',
34
+ 'decipher_atbash', 'encipher_railfence', 'decipher_railfence',
35
+ ]
shared/package-files/8b/8bc4ba21bd4e4237082c0fa5e2093392d3197b5f1369e50d238f4f2d1a7a3815/blob ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import warnings
3
+ import re
4
+ import textwrap
5
+ import email.message
6
+
7
+ from ._text import FoldedCase
8
+ from ._compat import pypy_partial
9
+
10
+
11
+ # Do not remove prior to 2024-01-01 or Python 3.14
12
+ _warn = functools.partial(
13
+ warnings.warn,
14
+ "Implicit None on return values is deprecated and will raise KeyErrors.",
15
+ DeprecationWarning,
16
+ stacklevel=pypy_partial(2),
17
+ )
18
+
19
+
20
+ class Message(email.message.Message):
21
+ multiple_use_keys = set(
22
+ map(
23
+ FoldedCase,
24
+ [
25
+ 'Classifier',
26
+ 'Obsoletes-Dist',
27
+ 'Platform',
28
+ 'Project-URL',
29
+ 'Provides-Dist',
30
+ 'Provides-Extra',
31
+ 'Requires-Dist',
32
+ 'Requires-External',
33
+ 'Supported-Platform',
34
+ 'Dynamic',
35
+ ],
36
+ )
37
+ )
38
+ """
39
+ Keys that may be indicated multiple times per PEP 566.
40
+ """
41
+
42
+ def __new__(cls, orig: email.message.Message):
43
+ res = super().__new__(cls)
44
+ vars(res).update(vars(orig))
45
+ return res
46
+
47
+ def __init__(self, *args, **kwargs):
48
+ self._headers = self._repair_headers()
49
+
50
+ # suppress spurious error from mypy
51
+ def __iter__(self):
52
+ return super().__iter__()
53
+
54
+ def __getitem__(self, item):
55
+ """
56
+ Warn users that a ``KeyError`` can be expected when a
57
+ mising key is supplied. Ref python/importlib_metadata#371.
58
+ """
59
+ res = super().__getitem__(item)
60
+ if res is None:
61
+ _warn()
62
+ return res
63
+
64
+ def _repair_headers(self):
65
+ def redent(value):
66
+ "Correct for RFC822 indentation"
67
+ if not value or '\n' not in value:
68
+ return value
69
+ return textwrap.dedent(' ' * 8 + value)
70
+
71
+ headers = [(key, redent(value)) for key, value in vars(self)['_headers']]
72
+ if self._payload:
73
+ headers.append(('Description', self.get_payload()))
74
+ return headers
75
+
76
+ @property
77
+ def json(self):
78
+ """
79
+ Convert PackageMetadata to a JSON-compatible format
80
+ per PEP 0566.
81
+ """
82
+
83
+ def transform(key):
84
+ value = self.get_all(key) if key in self.multiple_use_keys else self[key]
85
+ if key == 'Keywords':
86
+ value = re.split(r'\s+', value)
87
+ tk = key.lower().replace('-', '_')
88
+ return tk, value
89
+
90
+ return dict(map(transform, map(FoldedCase, self)))