s42chen commited on
Commit
4b936ae
·
verified ·
1 Parent(s): 5dee802

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

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 +5 -0
  2. shared/package-files/00/001cf5f5504a7c67b0758dfd4089c6f5071c827d4c4d85776d3e4f87b4c2cb66/blob +2 -0
  3. shared/package-files/00/001df83b40d5ec09447fd6786eb9c269d790539fae030856470e4565ab3ae430/blob +698 -0
  4. shared/package-files/00/0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28/blob +3 -0
  5. shared/package-files/00/0024252ffc037f100c09dddc0581ca67e8dbc7f57d367bf0c44fee2990462cc6/blob +323 -0
  6. shared/package-files/00/002490ed9be1b821e7bd5e069af46e2966796c12d5ceaee7719ef9a225b22dd3/blob +6 -0
  7. shared/package-files/00/00276baf2735e9b1915b1901993d86dd2ed9542921648c08e66b97019299e174/blob +423 -0
  8. shared/package-files/00/00296106cebefe5167bdd513b6e0ca2a6369d5175ffc26cb3a8f816423c9a142/blob +20 -0
  9. shared/package-files/00/002c55da2ea23c393e6ba2ff06ce23af254a6093041944e2b442184e36c97ace/blob +9 -0
  10. shared/package-files/00/002c817cb823dff5c6fa2039a26103ad7a833347102b38bc87c1d10489f31ba4/blob +63 -0
  11. shared/package-files/00/002cd5b3d209638942d9241be9fac755ee1d19de982c5203e54030e01b996bb7/blob +77 -0
  12. shared/package-files/00/00314591621e2b81b12f88e07c416168c2f9e6bf1406d10c076bc586bf6f3dd5/blob +113 -0
  13. shared/package-files/00/0031606ea5313c5e9b70243b8c97945a8592388e70f333037cc63eeb21e6416e/blob +164 -0
  14. shared/package-files/00/00323b115fc2338ced202a6a1ea7aaf0b23e59d07a717d2db5ab5d45d8dbb140/blob +112 -0
  15. shared/package-files/00/00329ec9a1b2285e43c01344d2c444e69bd6f9b4a414c25f06e873677adc78fe/blob +6 -0
  16. shared/package-files/00/0035359859fbca5f644ed4233a47cfb63a6690147f8bfea1c1b5645a1e6a666c/blob +84 -0
  17. shared/package-files/00/0035e986d00e45897712abc4e6ab3fbb7d81fd300b2923ad178de338b9a8c51c/blob +85 -0
  18. shared/package-files/00/003919ccfac5d0d91a0e489eaa5788f5497f09903fd2ae8319145ba82d6df63c/blob +23 -0
  19. shared/package-files/00/003a32bd1889775f1c7405d2d01cdef524ebe07e4347fcd5dd8ba009920ea628/blob +27 -0
  20. shared/package-files/00/003dc07b4b624fd9a7dab96312bbdf0847c41b44e50197cbfe7b9f42e8670c17/blob +433 -0
  21. shared/package-files/00/00416a0d488c68cdaa9f2f1ff590f227807dda2acd8fba1254b8d076cc2c6fdd/blob +28 -0
  22. shared/package-files/00/0041d46d458301b27ecb872c1b017dfb423a8cc7f355bd0076fbcf02d81b09f5/blob +78 -0
  23. shared/package-files/00/0043db8cea50b491a93a3c2bae2fbac15da0cd422f359e44215255b1312eb219/blob +20 -0
  24. shared/package-files/00/0044e23094d2e3a3ff97226409f39e7547a72fbb333129ef0ece163b42789de5/blob +113 -0
  25. shared/package-files/00/004558d2aa27cb210c82fe03a3674836baea500c149365d84aa1cceb9d2ecde9/blob +330 -0
  26. shared/package-files/00/00463fe3819a889b13c931e466a1b6246895a053a9369301f786520f69c9f1f0/blob +228 -0
  27. shared/package-files/00/0047fd967fa3e4c988310d094d03e19d9c1b361f36ca749446c58f68a68d8a78/blob +434 -0
  28. shared/package-files/00/004ee94fea0838b1b92b372c5e2b12f832662b273d321a2910be2c135afa92f9/blob +21 -0
  29. shared/package-files/00/00595c205d02a130f617f8f98b500778e149cefc849fb678c30d9ac5d4f40f71/blob +104 -0
  30. shared/package-files/00/00599b73d4a67e0a505743c3f61097ba4b5109190dbc31794b567bcf7d44db11/blob +85 -0
  31. shared/package-files/00/0060dbf4b6a0e180e9e33d2c0120e7f9ac20fa61d3882e7349a21958775ec7f8/blob +22 -0
  32. shared/package-files/00/0063fed96e58e85fa8878f6acdd4a75b947f82e6018d06d17411858b1bea968e/blob +50 -0
  33. shared/package-files/00/006942ebd5efa62509d8a788b3de96a2880017919d405bf8f1cd41527391e2d9/blob +42 -0
  34. shared/package-files/00/006d3a694562d4bb7fdc50f26e67a97d55937270221dff7328a0803d0b011074/blob +231 -0
  35. shared/package-files/00/006e4ddaad8ae86e219508336081d540eb437d60b514d215f76a64ba973b1b73/blob +974 -0
  36. shared/package-files/00/006fc7f4bc50db6692f9823d09a03031dc6f3881feb24da82d3ee690ea645382/blob +26 -0
  37. shared/package-files/00/00747ae5e774dcd581ea82bc6284d062ddc08029347cc935efd351704e567e64/blob +79 -0
  38. shared/package-files/00/0074a85fc2e4588b7b4469490e693ae290ef996aba18287e0fb5f0136977f360/blob +146 -0
  39. shared/package-files/00/0076fa231bdbcf039b03630c36c86000136ac8ccf3e41aa6080b9e8bbb993e0b/blob +24 -0
  40. shared/package-files/00/007879f48b3ee1689559ddbaca8be73ccde15ea292fb2c7b2167d7492d0d6611/blob +71 -0
  41. shared/package-files/00/007a806377cd7d6f29e3152ee2d4b79ae360ee897c6bbe75bfbb58ca2eecadda/blob +1158 -0
  42. shared/package-files/00/007b4b4429d075e6397d074c248b6780debb3c1565c569f612aff4b9ae159492/blob +105 -0
  43. shared/package-files/00/007bc30a58fa40a996e772047120de4eaf31f5110e4f9c3b5f93fcdfbe2eaca1/blob +21 -0
  44. shared/package-files/00/007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003/blob +3 -0
  45. shared/package-files/00/007c797f91b0f387ba6c88c56859ecebbbb6a888d34644952179c8dcd9859cfb/blob +28 -0
  46. shared/package-files/00/007c7f5b6c46e0911ccf5c4aa0de53c021d513af943b63e2301cb29e47784cf1/blob +0 -0
  47. shared/package-files/00/00802e742f5fefce24704cee868f0689753adef8f64e1462b4ace797b22692ae/blob +3 -0
  48. shared/package-files/00/0081cfe13348b3509eaa122039b1f26344b69cd181a3a70808bff78694738fda/blob +521 -0
  49. shared/package-files/00/00846343a0d9b42f0a65d83ae1122c698f533ef9883999234e7dc130c74e99fc/blob +22 -0
  50. shared/package-files/00/00861efb625e1476b20218687baea5dc22afeb7d05aa1012f468c5ff6deb8784/blob +39 -0
.gitattributes CHANGED
@@ -59,3 +59,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  plots/all-task-progression.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
  plots/all-task-progression.pdf filter=lfs diff=lfs merge=lfs -text
62
+ shared/package-files/00/0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28/blob filter=lfs diff=lfs merge=lfs -text
63
+ shared/package-files/00/007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003/blob filter=lfs diff=lfs merge=lfs -text
64
+ shared/package-files/00/00a16df76cb2ba5d643c2536ffa3a63735da528cc101cbfd3f87ec553ae37efe/blob filter=lfs diff=lfs merge=lfs -text
65
+ shared/package-files/01/01b20c23e9ca7c868b86b6bd109e153f4e21bd6aeec88522ef93976c6f4c2e7d/blob filter=lfs diff=lfs merge=lfs -text
66
+ shared/package-files/01/01e0d376352c8f8de9e5e13cf97756480f3a3a3244ea4d681b96c966af352e17/blob filter=lfs diff=lfs merge=lfs -text
shared/package-files/00/001cf5f5504a7c67b0758dfd4089c6f5071c827d4c4d85776d3e4f87b4c2cb66/blob ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ This is the sample data needed for some of matplotlib's examples and
2
+ docs. See matplotlib.cbook.get_sample_data for more info.
shared/package-files/00/001df83b40d5ec09447fd6786eb9c269d790539fae030856470e4565ab3ae430/blob ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mpmath import *
2
+ from mpmath.libmp import round_up, from_float, mpf_zeta_int
3
+
4
+ def test_zeta_int_bug():
5
+ assert mpf_zeta_int(0, 10) == from_float(-0.5)
6
+
7
+ def test_bernoulli():
8
+ assert bernfrac(0) == (1,1)
9
+ assert bernfrac(1) == (-1,2)
10
+ assert bernfrac(2) == (1,6)
11
+ assert bernfrac(3) == (0,1)
12
+ assert bernfrac(4) == (-1,30)
13
+ assert bernfrac(5) == (0,1)
14
+ assert bernfrac(6) == (1,42)
15
+ assert bernfrac(8) == (-1,30)
16
+ assert bernfrac(10) == (5,66)
17
+ assert bernfrac(12) == (-691,2730)
18
+ assert bernfrac(18) == (43867,798)
19
+ p, q = bernfrac(228)
20
+ assert p % 10**10 == 164918161
21
+ assert q == 625170
22
+ p, q = bernfrac(1000)
23
+ assert p % 10**10 == 7950421099
24
+ assert q == 342999030
25
+ mp.dps = 15
26
+ assert bernoulli(0) == 1
27
+ assert bernoulli(1) == -0.5
28
+ assert bernoulli(2).ae(1./6)
29
+ assert bernoulli(3) == 0
30
+ assert bernoulli(4).ae(-1./30)
31
+ assert bernoulli(5) == 0
32
+ assert bernoulli(6).ae(1./42)
33
+ assert str(bernoulli(10)) == '0.0757575757575758'
34
+ assert str(bernoulli(234)) == '7.62772793964344e+267'
35
+ assert str(bernoulli(10**5)) == '-5.82229431461335e+376755'
36
+ assert str(bernoulli(10**8+2)) == '1.19570355039953e+676752584'
37
+
38
+ mp.dps = 50
39
+ assert str(bernoulli(10)) == '0.075757575757575757575757575757575757575757575757576'
40
+ assert str(bernoulli(234)) == '7.6277279396434392486994969020496121553385863373331e+267'
41
+ assert str(bernoulli(10**5)) == '-5.8222943146133508236497045360612887555320691004308e+376755'
42
+ assert str(bernoulli(10**8+2)) == '1.1957035503995297272263047884604346914602088317782e+676752584'
43
+
44
+ mp.dps = 1000
45
+ assert bernoulli(10).ae(mpf(5)/66)
46
+
47
+ mp.dps = 50000
48
+ assert bernoulli(10).ae(mpf(5)/66)
49
+
50
+ mp.dps = 15
51
+
52
+ def test_bernpoly_eulerpoly():
53
+ mp.dps = 15
54
+ assert bernpoly(0,-1).ae(1)
55
+ assert bernpoly(0,0).ae(1)
56
+ assert bernpoly(0,'1/2').ae(1)
57
+ assert bernpoly(0,'3/4').ae(1)
58
+ assert bernpoly(0,1).ae(1)
59
+ assert bernpoly(0,2).ae(1)
60
+ assert bernpoly(1,-1).ae('-3/2')
61
+ assert bernpoly(1,0).ae('-1/2')
62
+ assert bernpoly(1,'1/2').ae(0)
63
+ assert bernpoly(1,'3/4').ae('1/4')
64
+ assert bernpoly(1,1).ae('1/2')
65
+ assert bernpoly(1,2).ae('3/2')
66
+ assert bernpoly(2,-1).ae('13/6')
67
+ assert bernpoly(2,0).ae('1/6')
68
+ assert bernpoly(2,'1/2').ae('-1/12')
69
+ assert bernpoly(2,'3/4').ae('-1/48')
70
+ assert bernpoly(2,1).ae('1/6')
71
+ assert bernpoly(2,2).ae('13/6')
72
+ assert bernpoly(3,-1).ae(-3)
73
+ assert bernpoly(3,0).ae(0)
74
+ assert bernpoly(3,'1/2').ae(0)
75
+ assert bernpoly(3,'3/4').ae('-3/64')
76
+ assert bernpoly(3,1).ae(0)
77
+ assert bernpoly(3,2).ae(3)
78
+ assert bernpoly(4,-1).ae('119/30')
79
+ assert bernpoly(4,0).ae('-1/30')
80
+ assert bernpoly(4,'1/2').ae('7/240')
81
+ assert bernpoly(4,'3/4').ae('7/3840')
82
+ assert bernpoly(4,1).ae('-1/30')
83
+ assert bernpoly(4,2).ae('119/30')
84
+ assert bernpoly(5,-1).ae(-5)
85
+ assert bernpoly(5,0).ae(0)
86
+ assert bernpoly(5,'1/2').ae(0)
87
+ assert bernpoly(5,'3/4').ae('25/1024')
88
+ assert bernpoly(5,1).ae(0)
89
+ assert bernpoly(5,2).ae(5)
90
+ assert bernpoly(10,-1).ae('665/66')
91
+ assert bernpoly(10,0).ae('5/66')
92
+ assert bernpoly(10,'1/2').ae('-2555/33792')
93
+ assert bernpoly(10,'3/4').ae('-2555/34603008')
94
+ assert bernpoly(10,1).ae('5/66')
95
+ assert bernpoly(10,2).ae('665/66')
96
+ assert bernpoly(11,-1).ae(-11)
97
+ assert bernpoly(11,0).ae(0)
98
+ assert bernpoly(11,'1/2').ae(0)
99
+ assert bernpoly(11,'3/4').ae('-555731/4194304')
100
+ assert bernpoly(11,1).ae(0)
101
+ assert bernpoly(11,2).ae(11)
102
+ assert eulerpoly(0,-1).ae(1)
103
+ assert eulerpoly(0,0).ae(1)
104
+ assert eulerpoly(0,'1/2').ae(1)
105
+ assert eulerpoly(0,'3/4').ae(1)
106
+ assert eulerpoly(0,1).ae(1)
107
+ assert eulerpoly(0,2).ae(1)
108
+ assert eulerpoly(1,-1).ae('-3/2')
109
+ assert eulerpoly(1,0).ae('-1/2')
110
+ assert eulerpoly(1,'1/2').ae(0)
111
+ assert eulerpoly(1,'3/4').ae('1/4')
112
+ assert eulerpoly(1,1).ae('1/2')
113
+ assert eulerpoly(1,2).ae('3/2')
114
+ assert eulerpoly(2,-1).ae(2)
115
+ assert eulerpoly(2,0).ae(0)
116
+ assert eulerpoly(2,'1/2').ae('-1/4')
117
+ assert eulerpoly(2,'3/4').ae('-3/16')
118
+ assert eulerpoly(2,1).ae(0)
119
+ assert eulerpoly(2,2).ae(2)
120
+ assert eulerpoly(3,-1).ae('-9/4')
121
+ assert eulerpoly(3,0).ae('1/4')
122
+ assert eulerpoly(3,'1/2').ae(0)
123
+ assert eulerpoly(3,'3/4').ae('-11/64')
124
+ assert eulerpoly(3,1).ae('-1/4')
125
+ assert eulerpoly(3,2).ae('9/4')
126
+ assert eulerpoly(4,-1).ae(2)
127
+ assert eulerpoly(4,0).ae(0)
128
+ assert eulerpoly(4,'1/2').ae('5/16')
129
+ assert eulerpoly(4,'3/4').ae('57/256')
130
+ assert eulerpoly(4,1).ae(0)
131
+ assert eulerpoly(4,2).ae(2)
132
+ assert eulerpoly(5,-1).ae('-3/2')
133
+ assert eulerpoly(5,0).ae('-1/2')
134
+ assert eulerpoly(5,'1/2').ae(0)
135
+ assert eulerpoly(5,'3/4').ae('361/1024')
136
+ assert eulerpoly(5,1).ae('1/2')
137
+ assert eulerpoly(5,2).ae('3/2')
138
+ assert eulerpoly(10,-1).ae(2)
139
+ assert eulerpoly(10,0).ae(0)
140
+ assert eulerpoly(10,'1/2').ae('-50521/1024')
141
+ assert eulerpoly(10,'3/4').ae('-36581523/1048576')
142
+ assert eulerpoly(10,1).ae(0)
143
+ assert eulerpoly(10,2).ae(2)
144
+ assert eulerpoly(11,-1).ae('-699/4')
145
+ assert eulerpoly(11,0).ae('691/4')
146
+ assert eulerpoly(11,'1/2').ae(0)
147
+ assert eulerpoly(11,'3/4').ae('-512343611/4194304')
148
+ assert eulerpoly(11,1).ae('-691/4')
149
+ assert eulerpoly(11,2).ae('699/4')
150
+ # Potential accuracy issues
151
+ assert bernpoly(10000,10000).ae('5.8196915936323387117e+39999')
152
+ assert bernpoly(200,17.5).ae(3.8048418524583064909e244)
153
+ assert eulerpoly(200,17.5).ae(-3.7309911582655785929e275)
154
+
155
+ def test_gamma():
156
+ mp.dps = 15
157
+ assert gamma(0.25).ae(3.6256099082219083119)
158
+ assert gamma(0.0001).ae(9999.4228832316241908)
159
+ assert gamma(300).ae('1.0201917073881354535e612')
160
+ assert gamma(-0.5).ae(-3.5449077018110320546)
161
+ assert gamma(-7.43).ae(0.00026524416464197007186)
162
+ #assert gamma(Rational(1,2)) == gamma(0.5)
163
+ #assert gamma(Rational(-7,3)).ae(gamma(mpf(-7)/3))
164
+ assert gamma(1+1j).ae(0.49801566811835604271 - 0.15494982830181068512j)
165
+ assert gamma(-1+0.01j).ae(-0.422733904013474115 + 99.985883082635367436j)
166
+ assert gamma(20+30j).ae(-1453876687.5534810 + 1163777777.8031573j)
167
+ # Should always give exact factorials when they can
168
+ # be represented as mpfs under the current working precision
169
+ fact = 1
170
+ for i in range(1, 18):
171
+ assert gamma(i) == fact
172
+ fact *= i
173
+ for dps in [170, 600]:
174
+ fact = 1
175
+ mp.dps = dps
176
+ for i in range(1, 105):
177
+ assert gamma(i) == fact
178
+ fact *= i
179
+ mp.dps = 100
180
+ assert gamma(0.5).ae(sqrt(pi))
181
+ mp.dps = 15
182
+ assert factorial(0) == fac(0) == 1
183
+ assert factorial(3) == 6
184
+ assert isnan(gamma(nan))
185
+ assert gamma(1100).ae('4.8579168073569433667e2866')
186
+ assert rgamma(0) == 0
187
+ assert rgamma(-1) == 0
188
+ assert rgamma(2) == 1.0
189
+ assert rgamma(3) == 0.5
190
+ assert loggamma(2+8j).ae(-8.5205176753667636926 + 10.8569497125597429366j)
191
+ assert loggamma('1e10000').ae('2.302485092994045684017991e10004')
192
+ assert loggamma('1e10000j').ae(mpc('-1.570796326794896619231322e10000','2.302485092994045684017991e10004'))
193
+
194
+ def test_fac2():
195
+ mp.dps = 15
196
+ assert [fac2(n) for n in range(10)] == [1,1,2,3,8,15,48,105,384,945]
197
+ assert fac2(-5).ae(1./3)
198
+ assert fac2(-11).ae(-1./945)
199
+ assert fac2(50).ae(5.20469842636666623e32)
200
+ assert fac2(0.5+0.75j).ae(0.81546769394688069176-0.34901016085573266889j)
201
+ assert fac2(inf) == inf
202
+ assert isnan(fac2(-inf))
203
+
204
+ def test_gamma_quotients():
205
+ mp.dps = 15
206
+ h = 1e-8
207
+ ep = 1e-4
208
+ G = gamma
209
+ assert gammaprod([-1],[-3,-4]) == 0
210
+ assert gammaprod([-1,0],[-5]) == inf
211
+ assert abs(gammaprod([-1],[-2]) - G(-1+h)/G(-2+h)) < 1e-4
212
+ assert abs(gammaprod([-4,-3],[-2,0]) - G(-4+h)*G(-3+h)/G(-2+h)/G(0+h)) < 1e-4
213
+ assert rf(3,0) == 1
214
+ assert rf(2.5,1) == 2.5
215
+ assert rf(-5,2) == 20
216
+ assert rf(j,j).ae(gamma(2*j)/gamma(j))
217
+ assert rf('-255.5815971722918','-0.5119253100282322').ae('-0.1952720278805729485') # issue 421
218
+ assert ff(-2,0) == 1
219
+ assert ff(-2,1) == -2
220
+ assert ff(4,3) == 24
221
+ assert ff(3,4) == 0
222
+ assert binomial(0,0) == 1
223
+ assert binomial(1,0) == 1
224
+ assert binomial(0,-1) == 0
225
+ assert binomial(3,2) == 3
226
+ assert binomial(5,2) == 10
227
+ assert binomial(5,3) == 10
228
+ assert binomial(5,5) == 1
229
+ assert binomial(-1,0) == 1
230
+ assert binomial(-2,-4) == 3
231
+ assert binomial(4.5, 1.5) == 6.5625
232
+ assert binomial(1100,1) == 1100
233
+ assert binomial(1100,2) == 604450
234
+ assert beta(1,1) == 1
235
+ assert beta(0,0) == inf
236
+ assert beta(3,0) == inf
237
+ assert beta(-1,-1) == inf
238
+ assert beta(1.5,1).ae(2/3.)
239
+ assert beta(1.5,2.5).ae(pi/16)
240
+ assert (10**15*beta(10,100)).ae(2.3455339739604649879)
241
+ assert beta(inf,inf) == 0
242
+ assert isnan(beta(-inf,inf))
243
+ assert isnan(beta(-3,inf))
244
+ assert isnan(beta(0,inf))
245
+ assert beta(inf,0.5) == beta(0.5,inf) == 0
246
+ assert beta(inf,-1.5) == inf
247
+ assert beta(inf,-0.5) == -inf
248
+ assert beta(1+2j,-1-j/2).ae(1.16396542451069943086+0.08511695947832914640j)
249
+ assert beta(-0.5,0.5) == 0
250
+ assert beta(-3,3).ae(-1/3.)
251
+ assert beta('-255.5815971722918','-0.5119253100282322').ae('18.157330562703710339') # issue 421
252
+
253
+ def test_zeta():
254
+ mp.dps = 15
255
+ assert zeta(2).ae(pi**2 / 6)
256
+ assert zeta(2.0).ae(pi**2 / 6)
257
+ assert zeta(mpc(2)).ae(pi**2 / 6)
258
+ assert zeta(100).ae(1)
259
+ assert zeta(0).ae(-0.5)
260
+ assert zeta(0.5).ae(-1.46035450880958681)
261
+ assert zeta(-1).ae(-mpf(1)/12)
262
+ assert zeta(-2) == 0
263
+ assert zeta(-3).ae(mpf(1)/120)
264
+ assert zeta(-4) == 0
265
+ assert zeta(-100) == 0
266
+ assert isnan(zeta(nan))
267
+ assert zeta(1e-30).ae(-0.5)
268
+ assert zeta(-1e-30).ae(-0.5)
269
+ # Zeros in the critical strip
270
+ assert zeta(mpc(0.5, 14.1347251417346937904)).ae(0)
271
+ assert zeta(mpc(0.5, 21.0220396387715549926)).ae(0)
272
+ assert zeta(mpc(0.5, 25.0108575801456887632)).ae(0)
273
+ assert zeta(mpc(1e-30,1e-40)).ae(-0.5)
274
+ assert zeta(mpc(-1e-30,1e-40)).ae(-0.5)
275
+ mp.dps = 50
276
+ im = '236.5242296658162058024755079556629786895294952121891237'
277
+ assert zeta(mpc(0.5, im)).ae(0, 1e-46)
278
+ mp.dps = 15
279
+ # Complex reflection formula
280
+ assert (zeta(-60+3j) / 10**34).ae(8.6270183987866146+15.337398548226238j)
281
+ # issue #358
282
+ assert zeta(0,0.5) == 0
283
+ assert zeta(0,0) == 0.5
284
+ assert zeta(0,0.5,1).ae(-0.34657359027997265)
285
+ # see issue #390
286
+ assert zeta(-1.5,0.5j).ae(-0.13671400162512768475 + 0.11411333638426559139j)
287
+
288
+ def test_altzeta():
289
+ mp.dps = 15
290
+ assert altzeta(-2) == 0
291
+ assert altzeta(-4) == 0
292
+ assert altzeta(-100) == 0
293
+ assert altzeta(0) == 0.5
294
+ assert altzeta(-1) == 0.25
295
+ assert altzeta(-3) == -0.125
296
+ assert altzeta(-5) == 0.25
297
+ assert altzeta(-21) == 1180529130.25
298
+ assert altzeta(1).ae(log(2))
299
+ assert altzeta(2).ae(pi**2/12)
300
+ assert altzeta(10).ae(73*pi**10/6842880)
301
+ assert altzeta(50) < 1
302
+ assert altzeta(60, rounding='d') < 1
303
+ assert altzeta(60, rounding='u') == 1
304
+ assert altzeta(10000, rounding='d') < 1
305
+ assert altzeta(10000, rounding='u') == 1
306
+ assert altzeta(3+0j) == altzeta(3)
307
+ s = 3+4j
308
+ assert altzeta(s).ae((1-2**(1-s))*zeta(s))
309
+ s = -3+4j
310
+ assert altzeta(s).ae((1-2**(1-s))*zeta(s))
311
+ assert altzeta(-100.5).ae(4.58595480083585913e+108)
312
+ assert altzeta(1.3).ae(0.73821404216623045)
313
+ assert altzeta(1e-30).ae(0.5)
314
+ assert altzeta(-1e-30).ae(0.5)
315
+ assert altzeta(mpc(1e-30,1e-40)).ae(0.5)
316
+ assert altzeta(mpc(-1e-30,1e-40)).ae(0.5)
317
+
318
+ def test_zeta_huge():
319
+ mp.dps = 15
320
+ assert zeta(inf) == 1
321
+ mp.dps = 50
322
+ assert zeta(100).ae('1.0000000000000000000000000000007888609052210118073522')
323
+ assert zeta(40*pi).ae('1.0000000000000000000000000000000000000148407238666182')
324
+ mp.dps = 10000
325
+ v = zeta(33000)
326
+ mp.dps = 15
327
+ assert str(v-1) == '1.02363019598118e-9934'
328
+ assert zeta(pi*1000, rounding=round_up) > 1
329
+ assert zeta(3000, rounding=round_up) > 1
330
+ assert zeta(pi*1000) == 1
331
+ assert zeta(3000) == 1
332
+
333
+ def test_zeta_negative():
334
+ mp.dps = 150
335
+ a = -pi*10**40
336
+ mp.dps = 15
337
+ assert str(zeta(a)) == '2.55880492708712e+1233536161668617575553892558646631323374078'
338
+ mp.dps = 50
339
+ assert str(zeta(a)) == '2.5588049270871154960875033337384432038436330847333e+1233536161668617575553892558646631323374078'
340
+ mp.dps = 15
341
+
342
+ def test_polygamma():
343
+ mp.dps = 15
344
+ psi0 = lambda z: psi(0,z)
345
+ psi1 = lambda z: psi(1,z)
346
+ assert psi0(3) == psi(0,3) == digamma(3)
347
+ #assert psi2(3) == psi(2,3) == tetragamma(3)
348
+ #assert psi3(3) == psi(3,3) == pentagamma(3)
349
+ assert psi0(pi).ae(0.97721330794200673)
350
+ assert psi0(-pi).ae(7.8859523853854902)
351
+ assert psi0(-pi+1).ae(7.5676424992016996)
352
+ assert psi0(pi+j).ae(1.04224048313859376 + 0.35853686544063749j)
353
+ assert psi0(-pi-j).ae(1.3404026194821986 - 2.8824392476809402j)
354
+ assert findroot(psi0, 1).ae(1.4616321449683622)
355
+ assert psi0(1e-10).ae(-10000000000.57722)
356
+ assert psi0(1e-40).ae(-1.000000000000000e+40)
357
+ assert psi0(1e-10+1e-10j).ae(-5000000000.577215 + 5000000000.000000j)
358
+ assert psi0(1e-40+1e-40j).ae(-5.000000000000000e+39 + 5.000000000000000e+39j)
359
+ assert psi0(inf) == inf
360
+ assert psi1(inf) == 0
361
+ assert psi(2,inf) == 0
362
+ assert psi1(pi).ae(0.37424376965420049)
363
+ assert psi1(-pi).ae(53.030438740085385)
364
+ assert psi1(pi+j).ae(0.32935710377142464 - 0.12222163911221135j)
365
+ assert psi1(-pi-j).ae(-0.30065008356019703 + 0.01149892486928227j)
366
+ assert (10**6*psi(4,1+10*pi*j)).ae(-6.1491803479004446 - 0.3921316371664063j)
367
+ assert psi0(1+10*pi*j).ae(3.4473994217222650 + 1.5548808324857071j)
368
+ assert isnan(psi0(nan))
369
+ assert isnan(psi0(-inf))
370
+ assert psi0(-100.5).ae(4.615124601338064)
371
+ assert psi0(3+0j).ae(psi0(3))
372
+ assert psi0(-100+3j).ae(4.6106071768714086321+3.1117510556817394626j)
373
+ assert isnan(psi(2,mpc(0,inf)))
374
+ assert isnan(psi(2,mpc(0,nan)))
375
+ assert isnan(psi(2,mpc(0,-inf)))
376
+ assert isnan(psi(2,mpc(1,inf)))
377
+ assert isnan(psi(2,mpc(1,nan)))
378
+ assert isnan(psi(2,mpc(1,-inf)))
379
+ assert isnan(psi(2,mpc(inf,inf)))
380
+ assert isnan(psi(2,mpc(nan,nan)))
381
+ assert isnan(psi(2,mpc(-inf,-inf)))
382
+ mp.dps = 30
383
+ # issue #534
384
+ assert digamma(-0.75+1j).ae(mpc('0.46317279488182026118963809283042317', '2.4821070143037957102007677817351115'))
385
+ mp.dps = 15
386
+
387
+ def test_polygamma_high_prec():
388
+ mp.dps = 100
389
+ assert str(psi(0,pi)) == "0.9772133079420067332920694864061823436408346099943256380095232865318105924777141317302075654362928734"
390
+ assert str(psi(10,pi)) == "-12.98876181434889529310283769414222588307175962213707170773803550518307617769657562747174101900659238"
391
+
392
+ def test_polygamma_identities():
393
+ mp.dps = 15
394
+ psi0 = lambda z: psi(0,z)
395
+ psi1 = lambda z: psi(1,z)
396
+ psi2 = lambda z: psi(2,z)
397
+ assert psi0(0.5).ae(-euler-2*log(2))
398
+ assert psi0(1).ae(-euler)
399
+ assert psi1(0.5).ae(0.5*pi**2)
400
+ assert psi1(1).ae(pi**2/6)
401
+ assert psi1(0.25).ae(pi**2 + 8*catalan)
402
+ assert psi2(1).ae(-2*apery)
403
+ mp.dps = 20
404
+ u = -182*apery+4*sqrt(3)*pi**3
405
+ mp.dps = 15
406
+ assert psi(2,5/6.).ae(u)
407
+ assert psi(3,0.5).ae(pi**4)
408
+
409
+ def test_foxtrot_identity():
410
+ # A test of the complex digamma function.
411
+ # See http://mathworld.wolfram.com/FoxTrotSeries.html and
412
+ # http://mathworld.wolfram.com/DigammaFunction.html
413
+ psi0 = lambda z: psi(0,z)
414
+ mp.dps = 50
415
+ a = (-1)**fraction(1,3)
416
+ b = (-1)**fraction(2,3)
417
+ x = -psi0(0.5*a) - psi0(-0.5*b) + psi0(0.5*(1+a)) + psi0(0.5*(1-b))
418
+ y = 2*pi*sech(0.5*sqrt(3)*pi)
419
+ assert x.ae(y)
420
+ mp.dps = 15
421
+
422
+ def test_polygamma_high_order():
423
+ mp.dps = 100
424
+ assert str(psi(50, pi)) == "-1344100348958402765749252447726432491812.641985273160531055707095989227897753035823152397679626136483"
425
+ assert str(psi(50, pi + 14*e)) == "-0.00000000000000000189793739550804321623512073101895801993019919886375952881053090844591920308111549337295143780341396"
426
+ assert str(psi(50, pi + 14*e*j)) == ("(-0.0000000000000000522516941152169248975225472155683565752375889510631513244785"
427
+ "9377385233700094871256507814151956624433 - 0.00000000000000001813157041407010184"
428
+ "702414110218205348527862196327980417757665282244728963891298080199341480881811613j)")
429
+ mp.dps = 15
430
+ assert str(psi(50, pi)) == "-1.34410034895841e+39"
431
+ assert str(psi(50, pi + 14*e)) == "-1.89793739550804e-18"
432
+ assert str(psi(50, pi + 14*e*j)) == "(-5.2251694115217e-17 - 1.81315704140701e-17j)"
433
+
434
+ def test_harmonic():
435
+ mp.dps = 15
436
+ assert harmonic(0) == 0
437
+ assert harmonic(1) == 1
438
+ assert harmonic(2) == 1.5
439
+ assert harmonic(3).ae(1. + 1./2 + 1./3)
440
+ assert harmonic(10**10).ae(23.603066594891989701)
441
+ assert harmonic(10**1000).ae(2303.162308658947)
442
+ assert harmonic(0.5).ae(2-2*log(2))
443
+ assert harmonic(inf) == inf
444
+ assert harmonic(2+0j) == 1.5+0j
445
+ assert harmonic(1+2j).ae(1.4918071802755104+0.92080728264223022j)
446
+
447
+ def test_gamma_huge_1():
448
+ mp.dps = 500
449
+ x = mpf(10**10) / 7
450
+ mp.dps = 15
451
+ assert str(gamma(x)) == "6.26075321389519e+12458010678"
452
+ mp.dps = 50
453
+ assert str(gamma(x)) == "6.2607532138951929201303779291707455874010420783933e+12458010678"
454
+ mp.dps = 15
455
+
456
+ def test_gamma_huge_2():
457
+ mp.dps = 500
458
+ x = mpf(10**100) / 19
459
+ mp.dps = 15
460
+ assert str(gamma(x)) == (\
461
+ "1.82341134776679e+5172997469323364168990133558175077136829182824042201886051511"
462
+ "9656908623426021308685461258226190190661")
463
+ mp.dps = 50
464
+ assert str(gamma(x)) == (\
465
+ "1.82341134776678875374414910350027596939980412984e+5172997469323364168990133558"
466
+ "1750771368291828240422018860515119656908623426021308685461258226190190661")
467
+
468
+ def test_gamma_huge_3():
469
+ mp.dps = 500
470
+ x = 10**80 // 3 + 10**70*j / 7
471
+ mp.dps = 15
472
+ y = gamma(x)
473
+ assert str(y.real) == (\
474
+ "-6.82925203918106e+2636286142112569524501781477865238132302397236429627932441916"
475
+ "056964386399485392600")
476
+ assert str(y.imag) == (\
477
+ "8.54647143678418e+26362861421125695245017814778652381323023972364296279324419160"
478
+ "56964386399485392600")
479
+ mp.dps = 50
480
+ y = gamma(x)
481
+ assert str(y.real) == (\
482
+ "-6.8292520391810548460682736226799637356016538421817e+26362861421125695245017814"
483
+ "77865238132302397236429627932441916056964386399485392600")
484
+ assert str(y.imag) == (\
485
+ "8.5464714367841748507479306948130687511711420234015e+263628614211256952450178147"
486
+ "7865238132302397236429627932441916056964386399485392600")
487
+
488
+ def test_gamma_huge_4():
489
+ x = 3200+11500j
490
+ mp.dps = 15
491
+ assert str(gamma(x)) == \
492
+ "(8.95783268539713e+5164 - 1.94678798329735e+5164j)"
493
+ mp.dps = 50
494
+ assert str(gamma(x)) == (\
495
+ "(8.9578326853971339570292952697675570822206567327092e+5164"
496
+ " - 1.9467879832973509568895402139429643650329524144794e+51"
497
+ "64j)")
498
+ mp.dps = 15
499
+
500
+ def test_gamma_huge_5():
501
+ mp.dps = 500
502
+ x = 10**60 * j / 3
503
+ mp.dps = 15
504
+ y = gamma(x)
505
+ assert str(y.real) == "-3.27753899634941e-227396058973640224580963937571892628368354580620654233316839"
506
+ assert str(y.imag) == "-7.1519888950416e-227396058973640224580963937571892628368354580620654233316841"
507
+ mp.dps = 50
508
+ y = gamma(x)
509
+ assert str(y.real) == (\
510
+ "-3.2775389963494132168950056995974690946983219123935e-22739605897364022458096393"
511
+ "7571892628368354580620654233316839")
512
+ assert str(y.imag) == (\
513
+ "-7.1519888950415979749736749222530209713136588885897e-22739605897364022458096393"
514
+ "7571892628368354580620654233316841")
515
+ mp.dps = 15
516
+
517
+ def test_gamma_huge_7():
518
+ mp.dps = 100
519
+ a = 3 + j/mpf(10)**1000
520
+ mp.dps = 15
521
+ y = gamma(a)
522
+ assert str(y.real) == "2.0"
523
+ # wrong
524
+ #assert str(y.imag) == "2.16735365342606e-1000"
525
+ assert str(y.imag) == "1.84556867019693e-1000"
526
+ mp.dps = 50
527
+ y = gamma(a)
528
+ assert str(y.real) == "2.0"
529
+ #assert str(y.imag) == "2.1673536534260596065418805612488708028522563689298e-1000"
530
+ assert str(y.imag) == "1.8455686701969342787869758198351951379156813281202e-1000"
531
+
532
+ def test_stieltjes():
533
+ mp.dps = 15
534
+ assert stieltjes(0).ae(+euler)
535
+ mp.dps = 25
536
+ assert stieltjes(1).ae('-0.07281584548367672486058637587')
537
+ assert stieltjes(2).ae('-0.009690363192872318484530386035')
538
+ assert stieltjes(3).ae('0.002053834420303345866160046543')
539
+ assert stieltjes(4).ae('0.002325370065467300057468170178')
540
+ mp.dps = 15
541
+ assert stieltjes(1).ae(-0.07281584548367672486058637587)
542
+ assert stieltjes(2).ae(-0.009690363192872318484530386035)
543
+ assert stieltjes(3).ae(0.002053834420303345866160046543)
544
+ assert stieltjes(4).ae(0.0023253700654673000574681701775)
545
+
546
+ def test_barnesg():
547
+ mp.dps = 15
548
+ assert barnesg(0) == barnesg(-1) == 0
549
+ assert [superfac(i) for i in range(8)] == [1, 1, 2, 12, 288, 34560, 24883200, 125411328000]
550
+ assert str(superfac(1000)) == '3.24570818422368e+1177245'
551
+ assert isnan(barnesg(nan))
552
+ assert isnan(superfac(nan))
553
+ assert isnan(hyperfac(nan))
554
+ assert barnesg(inf) == inf
555
+ assert superfac(inf) == inf
556
+ assert hyperfac(inf) == inf
557
+ assert isnan(superfac(-inf))
558
+ assert barnesg(0.7).ae(0.8068722730141471)
559
+ assert barnesg(2+3j).ae(-0.17810213864082169+0.04504542715447838j)
560
+ assert [hyperfac(n) for n in range(7)] == [1, 1, 4, 108, 27648, 86400000, 4031078400000]
561
+ assert [hyperfac(n) for n in range(0,-7,-1)] == [1,1,-1,-4,108,27648,-86400000]
562
+ a = barnesg(-3+0j)
563
+ assert a == 0 and isinstance(a, mpc)
564
+ a = hyperfac(-3+0j)
565
+ assert a == -4 and isinstance(a, mpc)
566
+
567
+ def test_polylog():
568
+ mp.dps = 15
569
+ zs = [mpmathify(z) for z in [0, 0.5, 0.99, 4, -0.5, -4, 1j, 3+4j]]
570
+ for z in zs: assert polylog(1, z).ae(-log(1-z))
571
+ for z in zs: assert polylog(0, z).ae(z/(1-z))
572
+ for z in zs: assert polylog(-1, z).ae(z/(1-z)**2)
573
+ for z in zs: assert polylog(-2, z).ae(z*(1+z)/(1-z)**3)
574
+ for z in zs: assert polylog(-3, z).ae(z*(1+4*z+z**2)/(1-z)**4)
575
+ assert polylog(3, 7).ae(5.3192579921456754382-5.9479244480803301023j)
576
+ assert polylog(3, -7).ae(-4.5693548977219423182)
577
+ assert polylog(2, 0.9).ae(1.2997147230049587252)
578
+ assert polylog(2, -0.9).ae(-0.75216317921726162037)
579
+ assert polylog(2, 0.9j).ae(-0.17177943786580149299+0.83598828572550503226j)
580
+ assert polylog(2, 1.1).ae(1.9619991013055685931-0.2994257606855892575j)
581
+ assert polylog(2, -1.1).ae(-0.89083809026228260587)
582
+ assert polylog(2, 1.1*sqrt(j)).ae(0.58841571107611387722+1.09962542118827026011j)
583
+ assert polylog(-2, 0.9).ae(1710)
584
+ assert polylog(-2, -0.9).ae(-90/6859.)
585
+ assert polylog(3, 0.9).ae(1.0496589501864398696)
586
+ assert polylog(-3, 0.9).ae(48690)
587
+ assert polylog(-3, -4).ae(-0.0064)
588
+ assert polylog(0.5+j/3, 0.5+j/2).ae(0.31739144796565650535 + 0.99255390416556261437j)
589
+ assert polylog(3+4j,1).ae(zeta(3+4j))
590
+ assert polylog(3+4j,-1).ae(-altzeta(3+4j))
591
+ # issue 390
592
+ assert polylog(1.5, -48.910886523731889).ae(-6.272992229311817)
593
+ assert polylog(1.5, 200).ae(-8.349608319033686529 - 8.159694826434266042j)
594
+ assert polylog(-2+0j, -2).ae(mpf(1)/13.5)
595
+ assert polylog(-2+0j, 1.25).ae(-180)
596
+
597
+ def test_bell_polyexp():
598
+ mp.dps = 15
599
+ # TODO: more tests for polyexp
600
+ assert (polyexp(0,1e-10)*10**10).ae(1.00000000005)
601
+ assert (polyexp(1,1e-10)*10**10).ae(1.0000000001)
602
+ assert polyexp(5,3j).ae(-607.7044517476176454+519.962786482001476087j)
603
+ assert polyexp(-1,3.5).ae(12.09537536175543444)
604
+ # bell(0,x) = 1
605
+ assert bell(0,0) == 1
606
+ assert bell(0,1) == 1
607
+ assert bell(0,2) == 1
608
+ assert bell(0,inf) == 1
609
+ assert bell(0,-inf) == 1
610
+ assert isnan(bell(0,nan))
611
+ # bell(1,x) = x
612
+ assert bell(1,4) == 4
613
+ assert bell(1,0) == 0
614
+ assert bell(1,inf) == inf
615
+ assert bell(1,-inf) == -inf
616
+ assert isnan(bell(1,nan))
617
+ # bell(2,x) = x*(1+x)
618
+ assert bell(2,-1) == 0
619
+ assert bell(2,0) == 0
620
+ # large orders / arguments
621
+ assert bell(10) == 115975
622
+ assert bell(10,1) == 115975
623
+ assert bell(10, -8) == 11054008
624
+ assert bell(5,-50) == -253087550
625
+ assert bell(50,-50).ae('3.4746902914629720259e74')
626
+ mp.dps = 80
627
+ assert bell(50,-50) == 347469029146297202586097646631767227177164818163463279814268368579055777450
628
+ assert bell(40,50) == 5575520134721105844739265207408344706846955281965031698187656176321717550
629
+ assert bell(74) == 5006908024247925379707076470957722220463116781409659160159536981161298714301202
630
+ mp.dps = 15
631
+ assert bell(10,20j) == 7504528595600+15649605360020j
632
+ # continuity of the generalization
633
+ assert bell(0.5,0).ae(sinc(pi*0.5))
634
+
635
+ def test_primezeta():
636
+ mp.dps = 15
637
+ assert primezeta(0.9).ae(1.8388316154446882243 + 3.1415926535897932385j)
638
+ assert primezeta(4).ae(0.076993139764246844943)
639
+ assert primezeta(1) == inf
640
+ assert primezeta(inf) == 0
641
+ assert isnan(primezeta(nan))
642
+
643
+ def test_rs_zeta():
644
+ mp.dps = 15
645
+ assert zeta(0.5+100000j).ae(1.0730320148577531321 + 5.7808485443635039843j)
646
+ assert zeta(0.75+100000j).ae(1.837852337251873704 + 1.9988492668661145358j)
647
+ assert zeta(0.5+1000000j, derivative=3).ae(1647.7744105852674733 - 1423.1270943036622097j)
648
+ assert zeta(1+1000000j, derivative=3).ae(3.4085866124523582894 - 18.179184721525947301j)
649
+ assert zeta(1+1000000j, derivative=1).ae(-0.10423479366985452134 - 0.74728992803359056244j)
650
+ assert zeta(0.5-1000000j, derivative=1).ae(11.636804066002521459 + 17.127254072212996004j)
651
+ # Additional sanity tests using fp arithmetic.
652
+ # Some more high-precision tests are found in the docstrings
653
+ def ae(x, y, tol=1e-6):
654
+ return abs(x-y) < tol*abs(y)
655
+ assert ae(fp.zeta(0.5-100000j), 1.0730320148577531321 - 5.7808485443635039843j)
656
+ assert ae(fp.zeta(0.75-100000j), 1.837852337251873704 - 1.9988492668661145358j)
657
+ assert ae(fp.zeta(0.5+1e6j), 0.076089069738227100006 + 2.8051021010192989554j)
658
+ assert ae(fp.zeta(0.5+1e6j, derivative=1), 11.636804066002521459 - 17.127254072212996004j)
659
+ assert ae(fp.zeta(1+1e6j), 0.94738726251047891048 + 0.59421999312091832833j)
660
+ assert ae(fp.zeta(1+1e6j, derivative=1), -0.10423479366985452134 - 0.74728992803359056244j)
661
+ assert ae(fp.zeta(0.5+100000j, derivative=1), 10.766962036817482375 - 30.92705282105996714j)
662
+ assert ae(fp.zeta(0.5+100000j, derivative=2), -119.40515625740538429 + 217.14780631141830251j)
663
+ assert ae(fp.zeta(0.5+100000j, derivative=3), 1129.7550282628460881 - 1685.4736895169690346j)
664
+ assert ae(fp.zeta(0.5+100000j, derivative=4), -10407.160819314958615 + 13777.786698628045085j)
665
+ assert ae(fp.zeta(0.75+100000j, derivative=1), -0.41742276699594321475 - 6.4453816275049955949j)
666
+ assert ae(fp.zeta(0.75+100000j, derivative=2), -9.214314279161977266 + 35.07290795337967899j)
667
+ assert ae(fp.zeta(0.75+100000j, derivative=3), 110.61331857820103469 - 236.87847130518129926j)
668
+ assert ae(fp.zeta(0.75+100000j, derivative=4), -1054.334275898559401 + 1769.9177890161596383j)
669
+
670
+ def test_siegelz():
671
+ mp.dps = 15
672
+ assert siegelz(100000).ae(5.87959246868176504171)
673
+ assert siegelz(100000, derivative=2).ae(-54.1172711010126452832)
674
+ assert siegelz(100000, derivative=3).ae(-278.930831343966552538)
675
+ assert siegelz(100000+j,derivative=1).ae(678.214511857070283307-379.742160779916375413j)
676
+
677
+
678
+
679
+ def test_zeta_near_1():
680
+ # Test for a former bug in mpf_zeta and mpc_zeta
681
+ mp.dps = 15
682
+ s1 = fadd(1, '1e-10', exact=True)
683
+ s2 = fadd(1, '-1e-10', exact=True)
684
+ s3 = fadd(1, '1e-10j', exact=True)
685
+ assert zeta(s1).ae(1.000000000057721566490881444e10)
686
+ assert zeta(s2).ae(-9.99999999942278433510574872e9)
687
+ z = zeta(s3)
688
+ assert z.real.ae(0.57721566490153286060)
689
+ assert z.imag.ae(-9.9999999999999999999927184e9)
690
+ mp.dps = 30
691
+ s1 = fadd(1, '1e-50', exact=True)
692
+ s2 = fadd(1, '-1e-50', exact=True)
693
+ s3 = fadd(1, '1e-50j', exact=True)
694
+ assert zeta(s1).ae('1e50')
695
+ assert zeta(s2).ae('-1e50')
696
+ z = zeta(s3)
697
+ assert z.real.ae('0.57721566490153286060651209008240243104215933593992')
698
+ assert z.imag.ae('-1e50')
shared/package-files/00/0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0023a9045c7afbcf2ba8cc23f8b4b492ac32204bf9c367d18d9a3b5b6d802e28
3
+ size 354880
shared/package-files/00/0024252ffc037f100c09dddc0581ca67e8dbc7f57d367bf0c44fee2990462cc6/blob ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # Torch
4
+ import torch
5
+ import torch.cuda
6
+ import torch.jit
7
+ import torch.jit._logging
8
+ import torch.jit.frontend
9
+ import torch.jit.quantized
10
+
11
+ # Testing utils
12
+ from torch.testing._internal.common_dtype import floating_and_complex_types_and
13
+ from torch.testing._internal.common_utils import TestCase, \
14
+ freeze_rng_state, TemporaryFileName, enable_profiling_mode_for_profiling_tests, is_iterable_of_tensors
15
+ from torch.testing._internal.common_utils import enable_profiling_mode # noqa: F401
16
+
17
+ # Standard library
18
+ from itertools import chain
19
+ from typing import List, Union
20
+ from torch._C import TensorType
21
+
22
+ import io
23
+
24
+ def check_output_types(self, func, ref_outputs, args, kwargs):
25
+ graph = getattr(func, 'last_graph', None)
26
+ types = [o.type() for o in graph.outputs()]
27
+ self.assertTrue(len(types) == 1)
28
+ t = types[0]
29
+ torch._C._jit_assert_is_instance(ref_outputs, t)
30
+
31
+ # Test names in this set are only checked for a single derivative
32
+ nn_functional_single_grad = frozenset('test_nn_' + name for name in [
33
+ 'pdist',
34
+ 'multilabel_margin_loss',
35
+ 'max_unpool3d',
36
+ 'multi_margin_loss',
37
+ 'binary_cross_entropy',
38
+ 'binary_cross_entropy_size_average',
39
+ 'ctc_loss',
40
+ 'grid_sample',
41
+ ])
42
+
43
+ def check_against_reference(self, func, reference_func, output_func, args, kwargs=None,
44
+ allow_unused=True, check_types=True, no_grad=False, no_gradgrad=False):
45
+ """Verifies a function performs identically to some reference implementation.
46
+
47
+ Commonly, this is used to verify that a JIT implementation
48
+ (output_func) matches the behavior of the eager implementation
49
+ (reference_func).
50
+ """
51
+ kwargs = kwargs if kwargs else {}
52
+
53
+ def allSum(vs):
54
+ if isinstance(vs, torch.Tensor):
55
+ vs = (vs,)
56
+ return sum((i + 1) * v.sum().abs() if v.dtype.is_complex else (i + 1) * v.sum()
57
+ for i, v in enumerate(vs)
58
+ if v is not None and v.dtype in floating_and_complex_types_and(torch.half, torch.bfloat16))
59
+
60
+ def clone_tensor(t, preserve_requires_grad):
61
+ require_grad = preserve_requires_grad and t.requires_grad
62
+ return t.detach().clone().requires_grad_(require_grad)
63
+
64
+ def clone_inputs(preserve_requires_grad: bool):
65
+ inputs: List[Union[torch.Tensor, List[torch.Tensor]]] = []
66
+
67
+ for arg in args:
68
+ if isinstance(arg, torch.Tensor):
69
+ inputs.append(clone_tensor(arg, preserve_requires_grad))
70
+ elif is_iterable_of_tensors(arg):
71
+ inputs.append([clone_tensor(t, preserve_requires_grad) for t in arg])
72
+ else:
73
+ inputs.append(arg)
74
+
75
+ return inputs
76
+
77
+ # Returns tensors in args that requires_grad, including tensors in TensorList args
78
+ def get_recording_tensors(args):
79
+ recording_tensors: List[torch.Tensor] = []
80
+
81
+ for arg in args:
82
+ if isinstance(arg, torch.Tensor) and arg.requires_grad:
83
+ recording_tensors.append(arg)
84
+ elif is_iterable_of_tensors(arg):
85
+ recording_tensors.extend(filter(lambda t: t.requires_grad, arg))
86
+
87
+ return recording_tensors
88
+
89
+ # test no gradients case
90
+ nograd_inputs = clone_inputs(preserve_requires_grad=False)
91
+ outputs = self.runAndSaveRNG(reference_func, nograd_inputs, kwargs)
92
+ with enable_profiling_mode_for_profiling_tests():
93
+ outputs_test = self.runAndSaveRNG(func, nograd_inputs, kwargs)
94
+ self.assertEqual(outputs, outputs_test)
95
+
96
+ if check_types:
97
+ check_output_types(self, func, outputs_test, nograd_inputs, kwargs)
98
+
99
+ if no_grad:
100
+ # skip grad tests
101
+ return
102
+
103
+ with enable_profiling_mode_for_profiling_tests():
104
+ # test single grad case
105
+ recording_inputs = clone_inputs(preserve_requires_grad=True)
106
+ recording_tensors = get_recording_tensors(recording_inputs)
107
+ outputs = output_func(self.runAndSaveRNG(reference_func, recording_inputs, kwargs))
108
+ grads = torch.autograd.grad(allSum(outputs), recording_tensors,
109
+ allow_unused=allow_unused)
110
+ outputs_test = output_func(self.runAndSaveRNG(func, recording_inputs, kwargs))
111
+ grads_test = torch.autograd.grad(allSum(outputs_test), recording_tensors,
112
+ allow_unused=allow_unused)
113
+ self.assertEqual(outputs, outputs_test)
114
+ self.assertEqual(grads, grads_test)
115
+ # test the grad grad case
116
+ if self._testMethodName in nn_functional_single_grad or no_gradgrad:
117
+ return
118
+
119
+ outputs = output_func(self.runAndSaveRNG(reference_func, recording_inputs, kwargs))
120
+ l1 = allSum(outputs)
121
+ grads = torch.autograd.grad(l1, recording_tensors, create_graph=True,
122
+ allow_unused=allow_unused)
123
+
124
+ l2 = (allSum(grads) * l1)
125
+ grads2 = torch.autograd.grad(l2, recording_tensors, allow_unused=allow_unused)
126
+ recording_inputs = clone_inputs(preserve_requires_grad=True)
127
+ recording_tensors = get_recording_tensors(recording_inputs)
128
+ outputs_test = output_func(self.runAndSaveRNG(func, recording_inputs, kwargs))
129
+ l1_test = allSum(outputs_test)
130
+ grads_test = torch.autograd.grad(
131
+ l1_test, recording_tensors, create_graph=True, allow_unused=allow_unused)
132
+
133
+ l2_test = (allSum(grads_test) * l1_test)
134
+ grads2_test = torch.autograd.grad(l2_test, recording_tensors, allow_unused=allow_unused)
135
+
136
+ self.assertEqual(outputs, outputs_test)
137
+ self.assertEqual(grads, grads_test)
138
+ for g2, g2_test in zip(grads2, grads2_test):
139
+ if g2 is None and g2_test is None:
140
+ continue
141
+ self.assertEqual(g2, g2_test, atol=5e-4, rtol=1e-4)
142
+
143
+ class JitCommonTestCase(TestCase):
144
+ def createFunctionFromGraph(self, trace):
145
+ graph = trace if isinstance(trace, torch._C.Graph) else trace.graph()
146
+ return torch._C._create_function_from_graph("forward", graph)
147
+
148
+ def assertExportImport(self, trace, inputs):
149
+ m = self.createFunctionFromGraph(trace)
150
+ self.assertExportImportModule(m, inputs)
151
+
152
+ def assertExportImportModule(self, m, inputs):
153
+ m_import = self.getExportImportCopy(m)
154
+ a = self.runAndSaveRNG(m, inputs)
155
+ b = self.runAndSaveRNG(m_import, inputs)
156
+ self.assertEqual(a, b, "Results of original model and "
157
+ "exported/imported version of model differed")
158
+
159
+ def runAndSaveRNG(self, func, inputs, kwargs=None):
160
+ kwargs = kwargs if kwargs else {}
161
+ with freeze_rng_state():
162
+ results = func(*inputs, **kwargs)
163
+ return results
164
+
165
+ def getExportImportCopy(self, m, also_test_file=True, map_location=None):
166
+ buffer = io.BytesIO()
167
+ torch.jit.save(m, buffer)
168
+ buffer.seek(0)
169
+ imported = torch.jit.load(buffer, map_location=map_location)
170
+
171
+ if not also_test_file:
172
+ return imported
173
+
174
+ with TemporaryFileName() as fname:
175
+ torch.jit.save(imported, fname)
176
+ return torch.jit.load(fname, map_location=map_location)
177
+
178
+ def autoDiffErrorMessage(self, should_autodiff_node, nodes_not_in_diff_graph,
179
+ fusion_nodes_not_found, non_fusible_nodes_being_fused,
180
+ fusion_nodes_found, nodes_in_diff_graph):
181
+ err_msg = "\nFailure in testing nodes' autodifferentiation. "
182
+ if should_autodiff_node:
183
+ err_msg += "One or more nodes were expected to be autodiffed, " \
184
+ "but were not found in specified fusible/nonfusible " \
185
+ "DifferentiableGraph groups. \nSpecifically:"
186
+ # The node is intended to appear in a differentiable graph but doesn't
187
+ diff_nodes_missing = []
188
+ # The node is intended to appear in a differentiable graph
189
+ # outside of a fusion group but instead is in a fusion group
190
+ diff_nodes_in_fusion = []
191
+ # The node is intended to appear in a fusion group but doesn't
192
+ fusion_nodes_missing = []
193
+ # The node is intended to appear in a fusion group but instead
194
+ # is just in an outer differentiable graph
195
+ fusion_nodes_in_diff = []
196
+ for node in nodes_not_in_diff_graph:
197
+ if node in non_fusible_nodes_being_fused:
198
+ diff_nodes_in_fusion.append(node)
199
+ else:
200
+ diff_nodes_missing.append(node)
201
+ for node in fusion_nodes_not_found:
202
+ if node in nodes_in_diff_graph:
203
+ fusion_nodes_in_diff.append(node)
204
+ else:
205
+ fusion_nodes_missing.append(node)
206
+ if len(diff_nodes_missing) > 0:
207
+ err_msg += f"\n {diff_nodes_missing} were not in one of the " \
208
+ "DifferentiableGraphs when they were expected to be. " \
209
+ "Did you intend for these nodes to be autodiffed? " \
210
+ "If not, remove them from the list of nonfusible nodes."
211
+ if len(diff_nodes_in_fusion) > 0:
212
+ err_msg += f"\n {diff_nodes_in_fusion} were found in one of the FusionGroups " \
213
+ "when they were expected to be just in a DifferentiableGraph. If it was " \
214
+ "intended for these nodes to be in FusionGroups, reclassify these nodes as " \
215
+ "fusible nodes. If these nodes were not intended to be fused, your " \
216
+ "autodifferentiation logic might be wrong."
217
+ if len(fusion_nodes_missing) > 0:
218
+ err_msg += f"\n {fusion_nodes_missing} were not in one of the FusionGroups " \
219
+ "of the DifferentiableGraphs when they were expected to be. " \
220
+ "They were also not found in an outer DifferentiableGraph. Did you " \
221
+ "intend for these nodes to be autodifferentiated? If not, you should " \
222
+ "remove these nodes from the test's fusible nodes. Otherwise your " \
223
+ "autodifferentiation logic might be wrong."
224
+ if len(fusion_nodes_in_diff) > 0:
225
+ err_msg += f"\n {fusion_nodes_in_diff} were not in one of the FusionGroups " \
226
+ "of the DifferentiableGraphs when they were expected to be, " \
227
+ "instead they were found just in an outer DifferentiableGraph. " \
228
+ "Did you intend for these nodes to be fused? If not, you should " \
229
+ "move these nodes into the test's nonfusible nodes. Otherwise your " \
230
+ "autodifferentiation logic might be wrong."
231
+ else:
232
+ err_msg += "One or more nodes were not expected to be autodiffed " \
233
+ "but were found in a DifferentiableGraph or in a FusionGroup " \
234
+ "of a DifferentiableGraph. Did you intend for these nodes to be " \
235
+ "autodiffed? If so, change this test to expect autodifferentiation. " \
236
+ "\nSpecifically:"
237
+ if len(fusion_nodes_found) > 0:
238
+ err_msg += f"\n {fusion_nodes_found} were not expected to be in " \
239
+ "one of the DifferentiableGraphs, but appeared in a FusionGroup " \
240
+ "of a DifferentiableGraph. "
241
+ if len(nodes_in_diff_graph) > 0:
242
+ err_msg += f"\n {nodes_in_diff_graph} were not expected to " \
243
+ "be in one of the DifferentiableGraphs but were."
244
+ return err_msg
245
+
246
+ def assertAutodiffNode(self, graph, should_autodiff_node, nonfusible_nodes, fusible_nodes):
247
+ diff_nodes = graph.findAllNodes('prim::DifferentiableGraph')
248
+ diff_subgraphs = [node.g('Subgraph') for node in diff_nodes]
249
+
250
+ # Note: currently no tests have fusible_nodes
251
+ fusion_nodes = list(chain.from_iterable([g.findAllNodes('prim::FusionGroup') for g in diff_subgraphs]))
252
+ fusion_subgraphs = [node.g('Subgraph') for node in fusion_nodes]
253
+
254
+ # For any non-fusible node, it must show up in one of the DifferentiableGraphs.
255
+ nodes_in_diff_graph = []
256
+ nodes_not_in_diff_graph = []
257
+ non_fusible_nodes_being_fused = []
258
+ for node in nonfusible_nodes:
259
+ if any(g.findNode(node) is not None for g in diff_subgraphs):
260
+ nodes_in_diff_graph.append(node)
261
+ else:
262
+ nodes_not_in_diff_graph.append(node)
263
+ if any(g.findNode(node) is not None for g in fusion_subgraphs):
264
+ non_fusible_nodes_being_fused.append(node)
265
+ found_all_nonfusible_nodes = len(nodes_in_diff_graph) == len(nonfusible_nodes)
266
+
267
+ # For any fusible node, it must show up in one of the FusionGroups in one of the DifferentiableGraphs.
268
+ fusion_nodes_found = []
269
+ fusion_nodes_not_found = []
270
+ for node in fusible_nodes:
271
+ if any(g.findNode(node) is not None for g in fusion_subgraphs):
272
+ fusion_nodes_found.append(node)
273
+ else:
274
+ fusion_nodes_not_found.append(node)
275
+ found_all_fusible_nodes = len(fusion_nodes_found) == len(fusible_nodes)
276
+
277
+ if should_autodiff_node is not None:
278
+ err_msg = self.autoDiffErrorMessage(should_autodiff_node,
279
+ nodes_not_in_diff_graph,
280
+ fusion_nodes_not_found,
281
+ non_fusible_nodes_being_fused,
282
+ fusion_nodes_found,
283
+ nodes_in_diff_graph)
284
+ self.assertEqual(should_autodiff_node,
285
+ found_all_nonfusible_nodes and found_all_fusible_nodes, err_msg)
286
+
287
+ def checkShapeAnalysis(self, out_sizes: Union[List[int], List[List[int]]],
288
+ traced_graph, assert_propagation, constant_prop=True):
289
+ # repropagte input shapes provided by tracing,
290
+ prev_symbolic_shapes_test_enabled = torch._C._jit_symbolic_shapes_test_mode_enabled()
291
+ for enable_test_mode in [True, False]:
292
+ # here we are testing allowing/disallowing substituting in complete shapes as constants,
293
+ # disallowing constants helps stress test partial eval and substitution pipeline
294
+ torch._C._jit_set_symbolic_shapes_test_mode(enable_test_mode)
295
+ torch._C._jit_erase_non_input_shape_information(traced_graph)
296
+ if constant_prop:
297
+ torch._C._jit_pass_constant_propagation(traced_graph)
298
+ torch._C._jit_pass_propagate_shapes_on_graph(traced_graph)
299
+ # Add sizes to default tensor type to avoid checking something out of scope
300
+ # and difficulties with tracer leaving in other parts of tensor type
301
+ output = next(traced_graph.outputs()).type()
302
+
303
+ def test_type(type, actual_size):
304
+ sizes = type.symbolic_sizes()
305
+ out_type = TensorType.get().with_sizes(sizes)
306
+ actual_type = TensorType.get().with_sizes(actual_size)
307
+
308
+ # always check actual shape is a subtype of the output
309
+ self.assertTrue(actual_type.isSubtypeOf(out_type))
310
+
311
+ # and then if assertion flag is provided, check shape analysis
312
+ # is successful
313
+ if assert_propagation:
314
+ self.assertEqual(out_type.sizes(), actual_size)
315
+
316
+ if output.isSubtypeOf(torch._C.TensorType.get()):
317
+ test_type(output, out_sizes)
318
+ else:
319
+ tuple_elements = output.elements()
320
+ for i in range(len(tuple_elements)):
321
+ test_type(tuple_elements[i], out_sizes[i])
322
+
323
+ torch._C._jit_set_symbolic_shapes_test_mode(prev_symbolic_shapes_test_enabled)
shared/package-files/00/002490ed9be1b821e7bd5e069af46e2966796c12d5ceaee7719ef9a225b22dd3/blob ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ class CudaSupportError(RuntimeError):
2
+ pass
3
+
4
+
5
+ class NvrtcError(Exception):
6
+ pass
shared/package-files/00/00276baf2735e9b1915b1901993d86dd2ed9542921648c08e66b97019299e174/blob ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ from typing import Iterator, List, Optional, Sequence, Set, Tuple, Union
4
+
5
+ from torchgen.model import (
6
+ BackendIndex,
7
+ FunctionSchema,
8
+ NativeFunction,
9
+ NativeFunctionsGroup,
10
+ NativeFunctionsViewGroup,
11
+ )
12
+
13
+ from .types_base import Binding, CType, Expr
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class CppSignature:
18
+ """
19
+ A CppSignature represents a single overload in the C++ API. For
20
+ any given function schema, there may be multiple CppSignatures
21
+ corresponding to it, based on how we desugar to C++. See also
22
+ CppSignatureGroup.
23
+ """
24
+
25
+ # The schema this signature is derived from
26
+ func: FunctionSchema
27
+
28
+ # Is this a C++ signature for a method, i.e. Tensor::my_op(...)?
29
+ method: bool
30
+
31
+ # Is this a faithful C++ signature (i.e. following the JIT schema) or a convenience API
32
+ # (i.e. with a potential TensorOptions argument and out arguments in the front)
33
+ faithful: bool
34
+
35
+ # Is this a symint C++ signature. For BC reasons, functions that take
36
+ # SymInts still present as int64_t in C++, and the SymInt variant is
37
+ # offered at a different overload name
38
+ #
39
+ # NB: If a function RETURNS a SymInt, this is ALWAYS false
40
+ symint: bool
41
+
42
+ # The set of C++ arguments which should not have defaults applied to them
43
+ cpp_no_default_args: Set[str]
44
+
45
+ # Is this a fallback C++ binding? Fallback bindings are enabled by
46
+ # manual_cpp_binding: True and are alternate, non-public API that
47
+ # lets manual C++ binding implementors access the binding that would
48
+ # have been automatically generated
49
+ fallback_binding: bool = False
50
+
51
+ # Return the unpacked argument structure of this signature,
52
+ # discarding information about which arguments are semantically
53
+ # related to each other.
54
+ def arguments(self) -> Sequence[Binding]:
55
+ return cpp.arguments(
56
+ self.func.arguments,
57
+ faithful=self.faithful,
58
+ symint=self.symint,
59
+ method=self.method,
60
+ cpp_no_default_args=self.cpp_no_default_args,
61
+ )
62
+
63
+ def name(self, *, suppress_symint_suffix: bool = False) -> str:
64
+ n = cpp.name(
65
+ self.func,
66
+ faithful_name_for_out_overloads=self.faithful,
67
+ symint_overload=False if suppress_symint_suffix else self.symint,
68
+ )
69
+ if self.fallback_binding:
70
+ n = f"__dispatch_{n}"
71
+ return n
72
+
73
+ # Render the C++ declaration for this signature
74
+ def decl(
75
+ self,
76
+ *,
77
+ name: Optional[str] = None,
78
+ prefix: str = "",
79
+ is_redispatching_fn: bool = False,
80
+ suppress_symint_suffix: bool = False,
81
+ ) -> str:
82
+ returns_type = cpp.returns_type(
83
+ self.func.returns, symint=self.symint
84
+ ).cpp_type()
85
+ cpp_args = [a.decl() for a in self.arguments()]
86
+ if is_redispatching_fn:
87
+ cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args
88
+ cpp_args_str = ", ".join(cpp_args)
89
+ if name is None:
90
+ name = prefix + self.name(suppress_symint_suffix=suppress_symint_suffix)
91
+ return f"{returns_type} {name}({cpp_args_str})"
92
+
93
+ # Render the C++ definition for this signature, not including
94
+ # the body (with curly braces)
95
+ def defn(
96
+ self,
97
+ *,
98
+ name: Optional[str] = None,
99
+ prefix: str = "",
100
+ is_redispatching_fn: bool = False,
101
+ ) -> str:
102
+ returns_type = cpp.returns_type(
103
+ self.func.returns, symint=self.symint
104
+ ).cpp_type()
105
+ cpp_args = [a.defn() for a in self.arguments()]
106
+ if is_redispatching_fn:
107
+ cpp_args = ["c10::DispatchKeySet dispatchKeySet"] + cpp_args
108
+ cpp_args_str = ", ".join(cpp_args)
109
+ if name is None:
110
+ name = prefix + self.name()
111
+ return f"{returns_type} {name}({cpp_args_str})"
112
+
113
+ def ptr_type(self) -> str:
114
+ args_types_str = ", ".join(a.type for a in self.arguments())
115
+ return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_types_str})"
116
+
117
+ # Return the C++ function type, e.g., something like int(bool)
118
+ def type(self) -> str:
119
+ args_types_str = ", ".join(a.type for a in self.arguments())
120
+ return f"{cpp.returns_type(self.func.returns, symint=self.symint).cpp_type()} ({args_types_str})"
121
+
122
+
123
+ # Represents group of all CppSignatures associated with a
124
+ # FunctionSchema. Right now, that's the regular, user-visible
125
+ # signature, as well as a "faithful" signature which doesn't
126
+ # have grouping.
127
+ @dataclass(frozen=True)
128
+ class CppSignatureGroup:
129
+ func: FunctionSchema
130
+ signature: CppSignature
131
+ faithful_signature: Optional[CppSignature]
132
+ symint_signature: Optional[CppSignature]
133
+ symint_faithful_signature: Optional[CppSignature]
134
+
135
+ def most_faithful_signature(self) -> CppSignature:
136
+ if self.faithful_signature:
137
+ return self.faithful_signature
138
+ else:
139
+ return self.signature
140
+
141
+ def signatures(self, *, symint: bool = True) -> Iterator[CppSignature]:
142
+ yield self.signature
143
+ if self.faithful_signature:
144
+ yield self.faithful_signature
145
+ if symint:
146
+ if self.symint_signature:
147
+ yield self.symint_signature
148
+ if self.symint_faithful_signature:
149
+ yield self.symint_faithful_signature
150
+
151
+ @staticmethod
152
+ def from_native_function(
153
+ f: NativeFunction, *, method: bool, fallback_binding: bool = False
154
+ ) -> "CppSignatureGroup":
155
+ func = f.func
156
+
157
+ def make_sig(*, faithful: bool, symint: bool) -> CppSignature:
158
+ return CppSignature(
159
+ func=func,
160
+ faithful=faithful,
161
+ symint=symint,
162
+ method=method,
163
+ fallback_binding=fallback_binding,
164
+ cpp_no_default_args=f.cpp_no_default_args,
165
+ )
166
+
167
+ def make_sigs(*, symint: bool) -> Tuple[CppSignature, Optional[CppSignature]]:
168
+ faithful_signature: Optional[CppSignature] = None
169
+ if func.arguments.tensor_options is not None or len(func.arguments.out) > 0:
170
+ faithful_signature = make_sig(faithful=True, symint=symint)
171
+ signature = make_sig(faithful=False, symint=symint)
172
+ return signature, faithful_signature
173
+
174
+ signature, faithful_signature = make_sigs(symint=False)
175
+ symint_signature: Optional[CppSignature] = None
176
+ symint_faithful_signature: Optional[CppSignature] = None
177
+ if func.has_symint():
178
+ symint_signature, symint_faithful_signature = make_sigs(symint=True)
179
+
180
+ return CppSignatureGroup(
181
+ func=func,
182
+ signature=signature,
183
+ faithful_signature=faithful_signature,
184
+ symint_signature=symint_signature,
185
+ symint_faithful_signature=symint_faithful_signature,
186
+ )
187
+
188
+
189
+ @dataclass(frozen=True)
190
+ class DispatcherSignature:
191
+ # The schema this signature is derived from
192
+ func: FunctionSchema
193
+
194
+ # Allows you to prepend an arbitrary prefix to the signature name.
195
+ # This is useful for parts of the codegen that generate wrappers around kernels,
196
+ # and need to avoid naming collisions.
197
+ prefix: str = ""
198
+
199
+ symint: bool = True
200
+
201
+ def arguments(self) -> List[Binding]:
202
+ return dispatcher.arguments(self.func, symint=self.symint)
203
+
204
+ def name(self) -> str:
205
+ return self.prefix + dispatcher.name(self.func)
206
+
207
+ def decl(self, name: Optional[str] = None) -> str:
208
+ args_str = ", ".join(a.decl() for a in self.arguments())
209
+ if name is None:
210
+ name = self.name()
211
+ return f"{self.returns_type().cpp_type()} {name}({args_str})"
212
+
213
+ def defn(
214
+ self, name: Optional[str] = None, *, is_redispatching_fn: bool = False
215
+ ) -> str:
216
+ args = [a.defn() for a in self.arguments()]
217
+ if is_redispatching_fn:
218
+ args = ["c10::DispatchKeySet dispatchKeySet"] + args
219
+ args_str = ", ".join(args)
220
+ if name is None:
221
+ name = self.name()
222
+ return f"{self.returns_type().cpp_type()} {name}({args_str})"
223
+
224
+ def exprs(self) -> List[Expr]:
225
+ return [Expr(a.name, a.nctype) for a in self.arguments()]
226
+
227
+ def returns_type(self) -> CType:
228
+ return dispatcher.returns_type(self.func.returns, symint=self.symint)
229
+
230
+ def ptr_type(self) -> str:
231
+ dispatcher_args_types_str = ", ".join(a.type for a in self.arguments())
232
+ return f"{self.returns_type().cpp_type()} (*)({dispatcher_args_types_str})"
233
+
234
+ # Return the C++ function type, e.g., something like int(bool)
235
+ def type(self) -> str:
236
+ dispatcher_args_types_str = ", ".join(a.type for a in self.arguments())
237
+ return f"{self.returns_type().cpp_type()} ({dispatcher_args_types_str})"
238
+
239
+ @staticmethod
240
+ def from_schema(
241
+ func: FunctionSchema, *, prefix: str = "", symint: bool = True
242
+ ) -> "DispatcherSignature":
243
+ return DispatcherSignature(func, prefix, symint)
244
+
245
+
246
+ @dataclass(frozen=True)
247
+ class NativeSignature:
248
+ # The schema this signature is derived from
249
+ func: FunctionSchema
250
+
251
+ symint: bool
252
+
253
+ prefix: str = ""
254
+
255
+ def name(self) -> str:
256
+ return self.prefix + native.name(self.func)
257
+
258
+ def decl(self, name: Optional[str] = None) -> str:
259
+ args_str = ", ".join(a.decl() for a in self.arguments())
260
+ if name is None:
261
+ name = self.name()
262
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})"
263
+
264
+ def defn(self, name: Optional[str] = None) -> str:
265
+ args_str = ", ".join(a.defn() for a in self.arguments())
266
+ if name is None:
267
+ name = self.name()
268
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} {name}({args_str})"
269
+
270
+ def ptr_type(self) -> str:
271
+ # don't include defaults in type signature!
272
+ args_str = ", ".join(a.defn() for a in self.arguments())
273
+ return f"{native.returns_type(self.func.returns, symint=self.symint).cpp_type()} (*)({args_str})"
274
+
275
+ def arguments(self) -> List[Binding]:
276
+ return native.arguments(self.func, symint=self.symint)
277
+
278
+ def returns_type(self) -> CType:
279
+ return native.returns_type(self.func.returns, symint=self.symint)
280
+
281
+ def dispatcher_exprs(self) -> List[Expr]:
282
+ return translate.translate(
283
+ self.arguments(), dispatcher.arguments(self.func), method=False
284
+ )
285
+
286
+
287
+ @dataclass(frozen=True)
288
+ class ViewInverseSignature:
289
+ g: NativeFunctionsViewGroup
290
+
291
+ def name(self) -> str:
292
+ return functionalization.reverse_name(self.g.view, include_namespace=False)
293
+
294
+ def decl(self) -> str:
295
+ return_type = functionalization.returns_type(self.g.view.func)
296
+ decls = [
297
+ a.decl()
298
+ for a in functionalization.inner_arguments(
299
+ self.g.view.func, is_reverse=True
300
+ )
301
+ ]
302
+ return f"static {return_type.cpp_type()} {self.name()}({', '.join(decls)});"
303
+
304
+
305
+ @dataclass(frozen=True)
306
+ class FunctionalizationLambda:
307
+ g: NativeFunctionsViewGroup
308
+
309
+ # are we generating the forward lambda or the reverse lambda?
310
+ is_reverse: bool
311
+
312
+ def captures(self) -> List[Expr]:
313
+ # The lambda lives inside of a kernel following the dispatcher API, so its outer context is the dispatcher arguments
314
+ # We also need to read the "reapply views" TLS at the time that the functionalization kernel was executed,
315
+ # and plumb it into the lambda.
316
+ outer_ctx = dispatcher.arguments(self.g.view.func) + [
317
+ functionalization.reapply_views_binding,
318
+ functionalization.inverse_return_mode_binding,
319
+ ]
320
+ capture_bindings = functionalization.capture_arguments(
321
+ self.g.view.func, is_reverse=self.is_reverse
322
+ )
323
+ # allow_expensive_conversions is set because we want to convert
324
+ # some reference types (IntArrayRef) to value types (vector<int64_t>).
325
+ capture_exprs = translate.translate(
326
+ outer_ctx, capture_bindings, method=False, allow_expensive_conversions=True
327
+ )
328
+ return capture_exprs
329
+
330
+ def decl(self) -> str:
331
+ return_type = functionalization.returns_type(self.g.view.func)
332
+ capture_str = ", ".join(
333
+ f"{val.type.name} = {val.expr}" for val in self.captures()
334
+ )
335
+ decls = [
336
+ a.decl()
337
+ for a in functionalization.outer_arguments(is_reverse=self.is_reverse)
338
+ ]
339
+ return f"[{capture_str}]({', '.join(decls)}) -> {return_type.cpp_type()}"
340
+
341
+ def inner_call(self, *, reapply_views: Optional[bool] = None) -> str:
342
+ inner_call_name = functionalization.name(
343
+ self.g,
344
+ is_reverse=self.is_reverse,
345
+ include_namespace=True,
346
+ reapply_views=reapply_views,
347
+ )
348
+
349
+ arg_ctx = functionalization.outer_arguments(is_reverse=self.is_reverse)
350
+ capture_ctx = functionalization.capture_arguments(
351
+ self.g.view.func, is_reverse=self.is_reverse
352
+ )
353
+ full_ctx = arg_ctx + capture_ctx
354
+
355
+ assert self.g.view_copy is not None
356
+ call_bindings = functionalization.inner_arguments(
357
+ self.g.view_copy.func, is_reverse=self.is_reverse
358
+ )
359
+ maybe_index = functionalization.inner_call_index(self.g.view_copy.func)
360
+ call_exprs = [
361
+ e.expr for e in translate.translate(full_ctx, call_bindings, method=False)
362
+ ]
363
+ if not self.is_reverse and maybe_index is not None:
364
+ return f'{inner_call_name}({", ".join(call_exprs)})[{maybe_index.name}];'
365
+ else:
366
+ return f'{inner_call_name}({", ".join(call_exprs)});'
367
+
368
+ @staticmethod
369
+ def from_func(
370
+ g: NativeFunctionsViewGroup, *, is_reverse: bool
371
+ ) -> "FunctionalizationLambda":
372
+ return FunctionalizationLambda(g, is_reverse)
373
+
374
+
375
+ @dataclass(frozen=True)
376
+ class StructuredImplSignature:
377
+ g: NativeFunctionsGroup
378
+ name: str
379
+
380
+ def defn(self, name: Optional[str] = None) -> str:
381
+ args_str = ", ".join(a.defn() for a in self.arguments())
382
+ return f"TORCH_IMPL_FUNC({self.name})({args_str})"
383
+
384
+ def arguments(self) -> List[Binding]:
385
+ return structured.impl_arguments(self.g)
386
+
387
+
388
+ # Helper functions
389
+
390
+
391
+ def kernel_signature(
392
+ f: NativeFunction, backend_index: BackendIndex, *, prefix: str = ""
393
+ ) -> Union["NativeSignature", "DispatcherSignature"]:
394
+ # Note [External Backends Follow Dispatcher API]
395
+ # Kernel signatures for in-tree backends follow the "native" API,
396
+ # while kernels for out-of-tree backends follow the dispatcher API.
397
+ # See the comments in `native.py` for details, but historically there have been
398
+ # some small differences in schema convention between them and the Dispatcher API.
399
+ # Any differences that require translating between the two will results in a runtime cost,
400
+ # so we'd like to keep the differences as small as possible.
401
+ # With external backends, we'd like to enforce that they write their kernels with schemas
402
+ # that match the Dispatcher API directly, if they can.
403
+ meta = backend_index.get_kernel(f)
404
+ symint = meta is not None and meta.supports_symint()
405
+ if symint:
406
+ assert (
407
+ f.func.has_symint()
408
+ ), f"attempted to define symint kernel for {backend_index.dispatch_key} without SymInt in schema"
409
+ if backend_index.external:
410
+ return DispatcherSignature.from_schema(f.func, prefix=prefix, symint=symint)
411
+ else:
412
+ return NativeSignature(f.func, prefix=prefix, symint=symint)
413
+
414
+
415
+ # Functions only, no types
416
+ from torchgen.api import (
417
+ cpp,
418
+ dispatcher,
419
+ functionalization,
420
+ native,
421
+ structured,
422
+ translate,
423
+ )
shared/package-files/00/00296106cebefe5167bdd513b6e0ca2a6369d5175ffc26cb3a8f816423c9a142/blob ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+
5
+ namespace c10 {
6
+
7
+ // RAII thread local guard that tracks whether code is being executed in
8
+ // `at::parallel_for` or `at::parallel_reduce` loop function.
9
+ class C10_API ParallelGuard {
10
+ public:
11
+ static bool is_enabled();
12
+
13
+ ParallelGuard(bool state);
14
+ ~ParallelGuard();
15
+
16
+ private:
17
+ bool previous_state_;
18
+ };
19
+
20
+ } // namespace c10
shared/package-files/00/002c55da2ea23c393e6ba2ff06ce23af254a6093041944e2b442184e36c97ace/blob ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ MODULE string_test
2
+
3
+ character(len=8) :: string
4
+ character string77 * 8
5
+
6
+ character(len=12), dimension(5,7) :: strarr
7
+ character strarr77(5,7) * 12
8
+
9
+ END MODULE string_test
shared/package-files/00/002c817cb823dff5c6fa2039a26103ad7a833347102b38bc87c1d10489f31ba4/blob ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stuff that differs in different Python versions and platform
2
+ distributions."""
3
+
4
+ import logging
5
+ import os
6
+ import sys
7
+
8
+ __all__ = ["get_path_uid", "stdlib_pkgs", "WINDOWS"]
9
+
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def has_tls() -> bool:
15
+ try:
16
+ import _ssl # noqa: F401 # ignore unused
17
+
18
+ return True
19
+ except ImportError:
20
+ pass
21
+
22
+ from pip._vendor.urllib3.util import IS_PYOPENSSL
23
+
24
+ return IS_PYOPENSSL
25
+
26
+
27
+ def get_path_uid(path: str) -> int:
28
+ """
29
+ Return path's uid.
30
+
31
+ Does not follow symlinks:
32
+ https://github.com/pypa/pip/pull/935#discussion_r5307003
33
+
34
+ Placed this function in compat due to differences on AIX and
35
+ Jython, that should eventually go away.
36
+
37
+ :raises OSError: When path is a symlink or can't be read.
38
+ """
39
+ if hasattr(os, "O_NOFOLLOW"):
40
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
41
+ file_uid = os.fstat(fd).st_uid
42
+ os.close(fd)
43
+ else: # AIX and Jython
44
+ # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW
45
+ if not os.path.islink(path):
46
+ # older versions of Jython don't have `os.fstat`
47
+ file_uid = os.stat(path).st_uid
48
+ else:
49
+ # raise OSError for parity with os.O_NOFOLLOW above
50
+ raise OSError(f"{path} is a symlink; Will not return uid for symlinks")
51
+ return file_uid
52
+
53
+
54
+ # packages in the stdlib that may have installation metadata, but should not be
55
+ # considered 'installed'. this theoretically could be determined based on
56
+ # dist.location (py27:`sysconfig.get_paths()['stdlib']`,
57
+ # py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may
58
+ # make this ineffective, so hard-coding
59
+ stdlib_pkgs = {"python", "wsgiref", "argparse"}
60
+
61
+
62
+ # windows detection, covers cpython and ironpython
63
+ WINDOWS = sys.platform.startswith("win") or (sys.platform == "cli" and os.name == "nt")
shared/package-files/00/002cd5b3d209638942d9241be9fac755ee1d19de982c5203e54030e01b996bb7/blob ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ NA,
6
+ Categorical,
7
+ Series,
8
+ )
9
+ import pandas._testing as tm
10
+
11
+
12
+ @pytest.mark.parametrize(
13
+ "keep, expected",
14
+ [
15
+ ("first", Series([False, False, True, False, True], name="name")),
16
+ ("last", Series([True, True, False, False, False], name="name")),
17
+ (False, Series([True, True, True, False, True], name="name")),
18
+ ],
19
+ )
20
+ def test_duplicated_keep(keep, expected):
21
+ ser = Series(["a", "b", "b", "c", "a"], name="name")
22
+
23
+ result = ser.duplicated(keep=keep)
24
+ tm.assert_series_equal(result, expected)
25
+
26
+
27
+ @pytest.mark.parametrize(
28
+ "keep, expected",
29
+ [
30
+ ("first", Series([False, False, True, False, True])),
31
+ ("last", Series([True, True, False, False, False])),
32
+ (False, Series([True, True, True, False, True])),
33
+ ],
34
+ )
35
+ def test_duplicated_nan_none(keep, expected):
36
+ ser = Series([np.nan, 3, 3, None, np.nan], dtype=object)
37
+
38
+ result = ser.duplicated(keep=keep)
39
+ tm.assert_series_equal(result, expected)
40
+
41
+
42
+ def test_duplicated_categorical_bool_na(nulls_fixture):
43
+ # GH#44351
44
+ ser = Series(
45
+ Categorical(
46
+ [True, False, True, False, nulls_fixture],
47
+ categories=[True, False],
48
+ ordered=True,
49
+ )
50
+ )
51
+ result = ser.duplicated()
52
+ expected = Series([False, False, True, True, False])
53
+ tm.assert_series_equal(result, expected)
54
+
55
+
56
+ @pytest.mark.parametrize(
57
+ "keep, vals",
58
+ [
59
+ ("last", [True, True, False]),
60
+ ("first", [False, True, True]),
61
+ (False, [True, True, True]),
62
+ ],
63
+ )
64
+ def test_duplicated_mask(keep, vals):
65
+ # GH#48150
66
+ ser = Series([1, 2, NA, NA, NA], dtype="Int64")
67
+ result = ser.duplicated(keep=keep)
68
+ expected = Series([False, False] + vals)
69
+ tm.assert_series_equal(result, expected)
70
+
71
+
72
+ def test_duplicated_mask_no_duplicated_na(keep):
73
+ # GH#48150
74
+ ser = Series([1, 2, NA], dtype="Int64")
75
+ result = ser.duplicated(keep=keep)
76
+ expected = Series([False, False, False])
77
+ tm.assert_series_equal(result, expected)
shared/package-files/00/00314591621e2b81b12f88e07c416168c2f9e6bf1406d10c076bc586bf6f3dd5/blob ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/upsample_bilinear2d_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::upsample_bilinear2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
26
+ inline at::Tensor upsample_bilinear2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, c10::optional<at::ArrayRef<double>> scale_factors) {
27
+ return at::_ops::upsample_bilinear2d_vec::call(input, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, align_corners, scale_factors);
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ at::Tensor upsample_bilinear2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, c10::optional<at::ArrayRef<double>> scale_factors) {
32
+ return at::_ops::upsample_bilinear2d_vec::call(input, output_size.has_value() ? c10::make_optional(c10::fromIntArrayRefSlow(*output_size)) : c10::nullopt, align_corners, scale_factors);
33
+ }
34
+ }
35
+
36
+ // aten::upsample_bilinear2d.vec(Tensor input, SymInt[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor
37
+ inline at::Tensor upsample_bilinear2d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional<at::ArrayRef<double>> scale_factors) {
38
+ return at::_ops::upsample_bilinear2d_vec::call(input, output_size, align_corners, scale_factors);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ at::Tensor upsample_bilinear2d(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional<at::ArrayRef<double>> scale_factors) {
43
+ return at::_ops::upsample_bilinear2d_vec::call(input, output_size, align_corners, scale_factors);
44
+ }
45
+ }
46
+
47
+ // aten::upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
48
+ inline at::Tensor & upsample_bilinear2d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt) {
49
+ return at::_ops::upsample_bilinear2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out);
50
+ }
51
+ namespace symint {
52
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
53
+ at::Tensor & upsample_bilinear2d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt) {
54
+ return at::_ops::upsample_bilinear2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out);
55
+ }
56
+ }
57
+
58
+ // aten::upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
59
+ inline at::Tensor & upsample_bilinear2d_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional<double> scales_h, c10::optional<double> scales_w, at::Tensor & out) {
60
+ return at::_ops::upsample_bilinear2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out);
61
+ }
62
+ namespace symint {
63
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
64
+ at::Tensor & upsample_bilinear2d_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional<double> scales_h, c10::optional<double> scales_w, at::Tensor & out) {
65
+ return at::_ops::upsample_bilinear2d_out::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w, out);
66
+ }
67
+ }
68
+
69
+ // aten::upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
70
+ inline at::Tensor & upsample_bilinear2d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt) {
71
+ return at::_ops::upsample_bilinear2d_out::call(self, output_size, align_corners, scales_h, scales_w, out);
72
+ }
73
+ namespace symint {
74
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
75
+ at::Tensor & upsample_bilinear2d_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt) {
76
+ return at::_ops::upsample_bilinear2d_out::call(self, output_size, align_corners, scales_h, scales_w, out);
77
+ }
78
+ }
79
+
80
+ // aten::upsample_bilinear2d.out(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!)
81
+ inline at::Tensor & upsample_bilinear2d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional<double> scales_h, c10::optional<double> scales_w, at::Tensor & out) {
82
+ return at::_ops::upsample_bilinear2d_out::call(self, output_size, align_corners, scales_h, scales_w, out);
83
+ }
84
+ namespace symint {
85
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
86
+ at::Tensor & upsample_bilinear2d_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional<double> scales_h, c10::optional<double> scales_w, at::Tensor & out) {
87
+ return at::_ops::upsample_bilinear2d_out::call(self, output_size, align_corners, scales_h, scales_w, out);
88
+ }
89
+ }
90
+
91
+ // aten::upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
92
+ inline at::Tensor upsample_bilinear2d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt) {
93
+ return at::_ops::upsample_bilinear2d::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w);
94
+ }
95
+ namespace symint {
96
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
97
+ at::Tensor upsample_bilinear2d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt) {
98
+ return at::_ops::upsample_bilinear2d::call(self, c10::fromIntArrayRefSlow(output_size), align_corners, scales_h, scales_w);
99
+ }
100
+ }
101
+
102
+ // aten::upsample_bilinear2d(Tensor self, SymInt[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor
103
+ inline at::Tensor upsample_bilinear2d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt) {
104
+ return at::_ops::upsample_bilinear2d::call(self, output_size, align_corners, scales_h, scales_w);
105
+ }
106
+ namespace symint {
107
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
108
+ at::Tensor upsample_bilinear2d(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional<double> scales_h=c10::nullopt, c10::optional<double> scales_w=c10::nullopt) {
109
+ return at::_ops::upsample_bilinear2d::call(self, output_size, align_corners, scales_h, scales_w);
110
+ }
111
+ }
112
+
113
+ }
shared/package-files/00/0031606ea5313c5e9b70243b8c97945a8592388e70f333037cc63eeb21e6416e/blob ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utilities for generating random numbers, random sequences, and
3
+ random selections.
4
+ """
5
+
6
+ import networkx as nx
7
+ from networkx.utils import py_random_state
8
+
9
+ __all__ = [
10
+ "powerlaw_sequence",
11
+ "zipf_rv",
12
+ "cumulative_distribution",
13
+ "discrete_sequence",
14
+ "random_weighted_sample",
15
+ "weighted_choice",
16
+ ]
17
+
18
+
19
+ # The same helpers for choosing random sequences from distributions
20
+ # uses Python's random module
21
+ # https://docs.python.org/3/library/random.html
22
+
23
+
24
+ @py_random_state(2)
25
+ def powerlaw_sequence(n, exponent=2.0, seed=None):
26
+ """
27
+ Return sample sequence of length n from a power law distribution.
28
+ """
29
+ return [seed.paretovariate(exponent - 1) for i in range(n)]
30
+
31
+
32
+ @py_random_state(2)
33
+ def zipf_rv(alpha, xmin=1, seed=None):
34
+ r"""Returns a random value chosen from the Zipf distribution.
35
+
36
+ The return value is an integer drawn from the probability distribution
37
+
38
+ .. math::
39
+
40
+ p(x)=\frac{x^{-\alpha}}{\zeta(\alpha, x_{\min})},
41
+
42
+ where $\zeta(\alpha, x_{\min})$ is the Hurwitz zeta function.
43
+
44
+ Parameters
45
+ ----------
46
+ alpha : float
47
+ Exponent value of the distribution
48
+ xmin : int
49
+ Minimum value
50
+ seed : integer, random_state, or None (default)
51
+ Indicator of random number generation state.
52
+ See :ref:`Randomness<randomness>`.
53
+
54
+ Returns
55
+ -------
56
+ x : int
57
+ Random value from Zipf distribution
58
+
59
+ Raises
60
+ ------
61
+ ValueError:
62
+ If xmin < 1 or
63
+ If alpha <= 1
64
+
65
+ Notes
66
+ -----
67
+ The rejection algorithm generates random values for a the power-law
68
+ distribution in uniformly bounded expected time dependent on
69
+ parameters. See [1]_ for details on its operation.
70
+
71
+ Examples
72
+ --------
73
+ >>> nx.utils.zipf_rv(alpha=2, xmin=3, seed=42)
74
+ 8
75
+
76
+ References
77
+ ----------
78
+ .. [1] Luc Devroye, Non-Uniform Random Variate Generation,
79
+ Springer-Verlag, New York, 1986.
80
+ """
81
+ if xmin < 1:
82
+ raise ValueError("xmin < 1")
83
+ if alpha <= 1:
84
+ raise ValueError("a <= 1.0")
85
+ a1 = alpha - 1.0
86
+ b = 2**a1
87
+ while True:
88
+ u = 1.0 - seed.random() # u in (0,1]
89
+ v = seed.random() # v in [0,1)
90
+ x = int(xmin * u ** -(1.0 / a1))
91
+ t = (1.0 + (1.0 / x)) ** a1
92
+ if v * x * (t - 1.0) / (b - 1.0) <= t / b:
93
+ break
94
+ return x
95
+
96
+
97
+ def cumulative_distribution(distribution):
98
+ """Returns normalized cumulative distribution from discrete distribution."""
99
+
100
+ cdf = [0.0]
101
+ psum = sum(distribution)
102
+ for i in range(0, len(distribution)):
103
+ cdf.append(cdf[i] + distribution[i] / psum)
104
+ return cdf
105
+
106
+
107
+ @py_random_state(3)
108
+ def discrete_sequence(n, distribution=None, cdistribution=None, seed=None):
109
+ """
110
+ Return sample sequence of length n from a given discrete distribution
111
+ or discrete cumulative distribution.
112
+
113
+ One of the following must be specified.
114
+
115
+ distribution = histogram of values, will be normalized
116
+
117
+ cdistribution = normalized discrete cumulative distribution
118
+
119
+ """
120
+ import bisect
121
+
122
+ if cdistribution is not None:
123
+ cdf = cdistribution
124
+ elif distribution is not None:
125
+ cdf = cumulative_distribution(distribution)
126
+ else:
127
+ raise nx.NetworkXError(
128
+ "discrete_sequence: distribution or cdistribution missing"
129
+ )
130
+
131
+ # get a uniform random number
132
+ inputseq = [seed.random() for i in range(n)]
133
+
134
+ # choose from CDF
135
+ seq = [bisect.bisect_left(cdf, s) - 1 for s in inputseq]
136
+ return seq
137
+
138
+
139
+ @py_random_state(2)
140
+ def random_weighted_sample(mapping, k, seed=None):
141
+ """Returns k items without replacement from a weighted sample.
142
+
143
+ The input is a dictionary of items with weights as values.
144
+ """
145
+ if k > len(mapping):
146
+ raise ValueError("sample larger than population")
147
+ sample = set()
148
+ while len(sample) < k:
149
+ sample.add(weighted_choice(mapping, seed))
150
+ return list(sample)
151
+
152
+
153
+ @py_random_state(1)
154
+ def weighted_choice(mapping, seed=None):
155
+ """Returns a single element from a weighted sample.
156
+
157
+ The input is a dictionary of items with weights as values.
158
+ """
159
+ # use roulette method
160
+ rnd = seed.random() * sum(mapping.values())
161
+ for k, w in mapping.items():
162
+ rnd -= w
163
+ if rnd < 0:
164
+ return k
shared/package-files/00/00323b115fc2338ced202a6a1ea7aaf0b23e59d07a717d2db5ab5d45d8dbb140/blob ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pytest
3
+
4
+ import numpy as np
5
+
6
+ from . import util
7
+
8
+
9
+ class TestParameters(util.F2PyTest):
10
+ # Check that intent(in out) translates as intent(inout)
11
+ sources = [
12
+ util.getpath("tests", "src", "parameter", "constant_real.f90"),
13
+ util.getpath("tests", "src", "parameter", "constant_integer.f90"),
14
+ util.getpath("tests", "src", "parameter", "constant_both.f90"),
15
+ util.getpath("tests", "src", "parameter", "constant_compound.f90"),
16
+ util.getpath("tests", "src", "parameter", "constant_non_compound.f90"),
17
+ ]
18
+
19
+ @pytest.mark.slow
20
+ def test_constant_real_single(self):
21
+ # non-contiguous should raise error
22
+ x = np.arange(6, dtype=np.float32)[::2]
23
+ pytest.raises(ValueError, self.module.foo_single, x)
24
+
25
+ # check values with contiguous array
26
+ x = np.arange(3, dtype=np.float32)
27
+ self.module.foo_single(x)
28
+ assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])
29
+
30
+ @pytest.mark.slow
31
+ def test_constant_real_double(self):
32
+ # non-contiguous should raise error
33
+ x = np.arange(6, dtype=np.float64)[::2]
34
+ pytest.raises(ValueError, self.module.foo_double, x)
35
+
36
+ # check values with contiguous array
37
+ x = np.arange(3, dtype=np.float64)
38
+ self.module.foo_double(x)
39
+ assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])
40
+
41
+ @pytest.mark.slow
42
+ def test_constant_compound_int(self):
43
+ # non-contiguous should raise error
44
+ x = np.arange(6, dtype=np.int32)[::2]
45
+ pytest.raises(ValueError, self.module.foo_compound_int, x)
46
+
47
+ # check values with contiguous array
48
+ x = np.arange(3, dtype=np.int32)
49
+ self.module.foo_compound_int(x)
50
+ assert np.allclose(x, [0 + 1 + 2 * 6, 1, 2])
51
+
52
+ @pytest.mark.slow
53
+ def test_constant_non_compound_int(self):
54
+ # check values
55
+ x = np.arange(4, dtype=np.int32)
56
+ self.module.foo_non_compound_int(x)
57
+ assert np.allclose(x, [0 + 1 + 2 + 3 * 4, 1, 2, 3])
58
+
59
+ @pytest.mark.slow
60
+ def test_constant_integer_int(self):
61
+ # non-contiguous should raise error
62
+ x = np.arange(6, dtype=np.int32)[::2]
63
+ pytest.raises(ValueError, self.module.foo_int, x)
64
+
65
+ # check values with contiguous array
66
+ x = np.arange(3, dtype=np.int32)
67
+ self.module.foo_int(x)
68
+ assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])
69
+
70
+ @pytest.mark.slow
71
+ def test_constant_integer_long(self):
72
+ # non-contiguous should raise error
73
+ x = np.arange(6, dtype=np.int64)[::2]
74
+ pytest.raises(ValueError, self.module.foo_long, x)
75
+
76
+ # check values with contiguous array
77
+ x = np.arange(3, dtype=np.int64)
78
+ self.module.foo_long(x)
79
+ assert np.allclose(x, [0 + 1 + 2 * 3, 1, 2])
80
+
81
+ @pytest.mark.slow
82
+ def test_constant_both(self):
83
+ # non-contiguous should raise error
84
+ x = np.arange(6, dtype=np.float64)[::2]
85
+ pytest.raises(ValueError, self.module.foo, x)
86
+
87
+ # check values with contiguous array
88
+ x = np.arange(3, dtype=np.float64)
89
+ self.module.foo(x)
90
+ assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
91
+
92
+ @pytest.mark.slow
93
+ def test_constant_no(self):
94
+ # non-contiguous should raise error
95
+ x = np.arange(6, dtype=np.float64)[::2]
96
+ pytest.raises(ValueError, self.module.foo_no, x)
97
+
98
+ # check values with contiguous array
99
+ x = np.arange(3, dtype=np.float64)
100
+ self.module.foo_no(x)
101
+ assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
102
+
103
+ @pytest.mark.slow
104
+ def test_constant_sum(self):
105
+ # non-contiguous should raise error
106
+ x = np.arange(6, dtype=np.float64)[::2]
107
+ pytest.raises(ValueError, self.module.foo_sum, x)
108
+
109
+ # check values with contiguous array
110
+ x = np.arange(3, dtype=np.float64)
111
+ self.module.foo_sum(x)
112
+ assert np.allclose(x, [0 + 1 * 3 * 3 + 2 * 3 * 3, 1 * 3, 2 * 3])
shared/package-files/00/00329ec9a1b2285e43c01344d2c444e69bd6f9b4a414c25f06e873677adc78fe/blob ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.35.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py2-none-any
5
+ Tag: py3-none-any
6
+
shared/package-files/00/0035359859fbca5f644ed4233a47cfb63a6690147f8bfea1c1b5645a1e6a666c/blob ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for the :mod:`networkx.algorithms.community.centrality`
2
+ module.
3
+
4
+ """
5
+ from operator import itemgetter
6
+
7
+ import networkx as nx
8
+
9
+
10
+ def set_of_sets(iterable):
11
+ return set(map(frozenset, iterable))
12
+
13
+
14
+ def validate_communities(result, expected):
15
+ assert set_of_sets(result) == set_of_sets(expected)
16
+
17
+
18
+ def validate_possible_communities(result, *expected):
19
+ assert any(set_of_sets(result) == set_of_sets(p) for p in expected)
20
+
21
+
22
+ class TestGirvanNewman:
23
+ """Unit tests for the
24
+ :func:`networkx.algorithms.community.centrality.girvan_newman`
25
+ function.
26
+
27
+ """
28
+
29
+ def test_no_edges(self):
30
+ G = nx.empty_graph(3)
31
+ communities = list(nx.community.girvan_newman(G))
32
+ assert len(communities) == 1
33
+ validate_communities(communities[0], [{0}, {1}, {2}])
34
+
35
+ def test_undirected(self):
36
+ # Start with the graph .-.-.-.
37
+ G = nx.path_graph(4)
38
+ communities = list(nx.community.girvan_newman(G))
39
+ assert len(communities) == 3
40
+ # After one removal, we get the graph .-. .-.
41
+ validate_communities(communities[0], [{0, 1}, {2, 3}])
42
+ # After the next, we get the graph .-. . ., but there are two
43
+ # symmetric possible versions.
44
+ validate_possible_communities(
45
+ communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}]
46
+ )
47
+ # After the last removal, we always get the empty graph.
48
+ validate_communities(communities[2], [{0}, {1}, {2}, {3}])
49
+
50
+ def test_directed(self):
51
+ G = nx.DiGraph(nx.path_graph(4))
52
+ communities = list(nx.community.girvan_newman(G))
53
+ assert len(communities) == 3
54
+ validate_communities(communities[0], [{0, 1}, {2, 3}])
55
+ validate_possible_communities(
56
+ communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}]
57
+ )
58
+ validate_communities(communities[2], [{0}, {1}, {2}, {3}])
59
+
60
+ def test_selfloops(self):
61
+ G = nx.path_graph(4)
62
+ G.add_edge(0, 0)
63
+ G.add_edge(2, 2)
64
+ communities = list(nx.community.girvan_newman(G))
65
+ assert len(communities) == 3
66
+ validate_communities(communities[0], [{0, 1}, {2, 3}])
67
+ validate_possible_communities(
68
+ communities[1], [{0}, {1}, {2, 3}], [{0, 1}, {2}, {3}]
69
+ )
70
+ validate_communities(communities[2], [{0}, {1}, {2}, {3}])
71
+
72
+ def test_most_valuable_edge(self):
73
+ G = nx.Graph()
74
+ G.add_weighted_edges_from([(0, 1, 3), (1, 2, 2), (2, 3, 1)])
75
+ # Let the most valuable edge be the one with the highest weight.
76
+
77
+ def heaviest(G):
78
+ return max(G.edges(data="weight"), key=itemgetter(2))[:2]
79
+
80
+ communities = list(nx.community.girvan_newman(G, heaviest))
81
+ assert len(communities) == 3
82
+ validate_communities(communities[0], [{0}, {1, 2, 3}])
83
+ validate_communities(communities[1], [{0}, {1}, {2, 3}])
84
+ validate_communities(communities[2], [{0}, {1}, {2}, {3}])
shared/package-files/00/0035e986d00e45897712abc4e6ab3fbb7d81fd300b2923ad178de338b9a8c51c/blob ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import (
2
+ Literal as L,
3
+ Any,
4
+ overload,
5
+ TypeVar,
6
+ Protocol,
7
+ )
8
+
9
+ from numpy import generic
10
+
11
+ from numpy._typing import (
12
+ ArrayLike,
13
+ NDArray,
14
+ _ArrayLikeInt,
15
+ _ArrayLike,
16
+ )
17
+
18
+ _SCT = TypeVar("_SCT", bound=generic)
19
+
20
+ class _ModeFunc(Protocol):
21
+ def __call__(
22
+ self,
23
+ vector: NDArray[Any],
24
+ iaxis_pad_width: tuple[int, int],
25
+ iaxis: int,
26
+ kwargs: dict[str, Any],
27
+ /,
28
+ ) -> None: ...
29
+
30
+ _ModeKind = L[
31
+ "constant",
32
+ "edge",
33
+ "linear_ramp",
34
+ "maximum",
35
+ "mean",
36
+ "median",
37
+ "minimum",
38
+ "reflect",
39
+ "symmetric",
40
+ "wrap",
41
+ "empty",
42
+ ]
43
+
44
+ __all__: list[str]
45
+
46
+ # TODO: In practice each keyword argument is exclusive to one or more
47
+ # specific modes. Consider adding more overloads to express this in the future.
48
+
49
+ # Expand `**kwargs` into explicit keyword-only arguments
50
+ @overload
51
+ def pad(
52
+ array: _ArrayLike[_SCT],
53
+ pad_width: _ArrayLikeInt,
54
+ mode: _ModeKind = ...,
55
+ *,
56
+ stat_length: None | _ArrayLikeInt = ...,
57
+ constant_values: ArrayLike = ...,
58
+ end_values: ArrayLike = ...,
59
+ reflect_type: L["odd", "even"] = ...,
60
+ ) -> NDArray[_SCT]: ...
61
+ @overload
62
+ def pad(
63
+ array: ArrayLike,
64
+ pad_width: _ArrayLikeInt,
65
+ mode: _ModeKind = ...,
66
+ *,
67
+ stat_length: None | _ArrayLikeInt = ...,
68
+ constant_values: ArrayLike = ...,
69
+ end_values: ArrayLike = ...,
70
+ reflect_type: L["odd", "even"] = ...,
71
+ ) -> NDArray[Any]: ...
72
+ @overload
73
+ def pad(
74
+ array: _ArrayLike[_SCT],
75
+ pad_width: _ArrayLikeInt,
76
+ mode: _ModeFunc,
77
+ **kwargs: Any,
78
+ ) -> NDArray[_SCT]: ...
79
+ @overload
80
+ def pad(
81
+ array: ArrayLike,
82
+ pad_width: _ArrayLikeInt,
83
+ mode: _ModeFunc,
84
+ **kwargs: Any,
85
+ ) -> NDArray[Any]: ...
shared/package-files/00/003919ccfac5d0d91a0e489eaa5788f5497f09903fd2ae8319145ba82d6df63c/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 int64_t output_nr(const at::Tensor & self);
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
shared/package-files/00/003a32bd1889775f1c7405d2d01cdef524ebe07e4347fcd5dd8ba009920ea628/blob ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.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/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured_igammac : public TensorIteratorBase {
21
+
22
+
23
+ void meta(const at::Tensor & self, const at::Tensor & other);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
shared/package-files/00/003dc07b4b624fd9a7dab96312bbdf0847c41b44e50197cbfe7b9f42e8670c17/blob ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import warnings
3
+ import numpy as np
4
+ from numpy.testing import (assert_array_equal, assert_allclose,
5
+ suppress_warnings)
6
+ from copy import deepcopy
7
+ from scipy.stats.sampling import FastGeneratorInversion
8
+ from scipy import stats
9
+
10
+
11
+ def test_bad_args():
12
+ # loc and scale must be scalar
13
+ with pytest.raises(ValueError, match="loc must be scalar"):
14
+ FastGeneratorInversion(stats.norm(loc=(1.2, 1.3)))
15
+ with pytest.raises(ValueError, match="scale must be scalar"):
16
+ FastGeneratorInversion(stats.norm(scale=[1.5, 5.7]))
17
+
18
+ with pytest.raises(ValueError, match="'test' cannot be used to seed"):
19
+ FastGeneratorInversion(stats.norm(), random_state="test")
20
+
21
+ msg = "Each of the 1 shape parameters must be a scalar"
22
+ with pytest.raises(ValueError, match=msg):
23
+ FastGeneratorInversion(stats.gamma([1.3, 2.5]))
24
+
25
+ with pytest.raises(ValueError, match="`dist` must be a frozen"):
26
+ FastGeneratorInversion("xy")
27
+
28
+ with pytest.raises(ValueError, match="Distribution 'truncnorm' is not"):
29
+ FastGeneratorInversion(stats.truncnorm(1.3, 4.5))
30
+
31
+
32
+ def test_random_state():
33
+ # fixed seed
34
+ gen = FastGeneratorInversion(stats.norm(), random_state=68734509)
35
+ x1 = gen.rvs(size=10)
36
+ gen.random_state = 68734509
37
+ x2 = gen.rvs(size=10)
38
+ assert_array_equal(x1, x2)
39
+
40
+ # Generator
41
+ urng = np.random.default_rng(20375857)
42
+ gen = FastGeneratorInversion(stats.norm(), random_state=urng)
43
+ x1 = gen.rvs(size=10)
44
+ gen.random_state = np.random.default_rng(20375857)
45
+ x2 = gen.rvs(size=10)
46
+ assert_array_equal(x1, x2)
47
+
48
+ # RandomState
49
+ urng = np.random.RandomState(2364)
50
+ gen = FastGeneratorInversion(stats.norm(), random_state=urng)
51
+ x1 = gen.rvs(size=10)
52
+ gen.random_state = np.random.RandomState(2364)
53
+ x2 = gen.rvs(size=10)
54
+ assert_array_equal(x1, x2)
55
+
56
+ # if evaluate_error is called, it must not interfere with the random_state
57
+ # used by rvs
58
+ gen = FastGeneratorInversion(stats.norm(), random_state=68734509)
59
+ x1 = gen.rvs(size=10)
60
+ _ = gen.evaluate_error(size=5) # this will generate 5 uniform rvs
61
+ x2 = gen.rvs(size=10)
62
+ gen.random_state = 68734509
63
+ x3 = gen.rvs(size=20)
64
+ assert_array_equal(x2, x3[10:])
65
+
66
+
67
+ dists_with_params = [
68
+ ("alpha", (3.5,)),
69
+ ("anglit", ()),
70
+ ("argus", (3.5,)),
71
+ ("argus", (5.1,)),
72
+ ("beta", (1.5, 0.9)),
73
+ ("cosine", ()),
74
+ ("betaprime", (2.5, 3.3)),
75
+ ("bradford", (1.2,)),
76
+ ("burr", (1.3, 2.4)),
77
+ ("burr12", (0.7, 1.2)),
78
+ ("cauchy", ()),
79
+ ("chi2", (3.5,)),
80
+ ("chi", (4.5,)),
81
+ ("crystalball", (0.7, 1.2)),
82
+ ("expon", ()),
83
+ ("gamma", (1.5,)),
84
+ ("gennorm", (2.7,)),
85
+ ("gumbel_l", ()),
86
+ ("gumbel_r", ()),
87
+ ("hypsecant", ()),
88
+ ("invgauss", (3.1,)),
89
+ ("invweibull", (1.5,)),
90
+ ("laplace", ()),
91
+ ("logistic", ()),
92
+ ("maxwell", ()),
93
+ ("moyal", ()),
94
+ ("norm", ()),
95
+ ("pareto", (1.3,)),
96
+ ("powerlaw", (7.6,)),
97
+ ("rayleigh", ()),
98
+ ("semicircular", ()),
99
+ ("t", (5.7,)),
100
+ ("wald", ()),
101
+ ("weibull_max", (2.4,)),
102
+ ("weibull_min", (1.2,)),
103
+ ]
104
+
105
+
106
+ @pytest.mark.parametrize(("distname, args"), dists_with_params)
107
+ def test_rvs_and_ppf(distname, args):
108
+ # check sample against rvs generated by rv_continuous
109
+ urng = np.random.default_rng(9807324628097097)
110
+ rng1 = getattr(stats, distname)(*args)
111
+ rvs1 = rng1.rvs(size=500, random_state=urng)
112
+ rng2 = FastGeneratorInversion(rng1, random_state=urng)
113
+ rvs2 = rng2.rvs(size=500)
114
+ assert stats.cramervonmises_2samp(rvs1, rvs2).pvalue > 0.01
115
+
116
+ # check ppf
117
+ q = [0.001, 0.1, 0.5, 0.9, 0.999]
118
+ assert_allclose(rng1.ppf(q), rng2.ppf(q), atol=1e-10)
119
+
120
+
121
+ @pytest.mark.parametrize(("distname, args"), dists_with_params)
122
+ def test_u_error(distname, args):
123
+ # check sample against rvs generated by rv_continuous
124
+ dist = getattr(stats, distname)(*args)
125
+ with suppress_warnings() as sup:
126
+ # filter the warnings thrown by UNU.RAN
127
+ sup.filter(RuntimeWarning)
128
+ rng = FastGeneratorInversion(dist)
129
+ u_error, x_error = rng.evaluate_error(
130
+ size=10_000, random_state=9807324628097097, x_error=False
131
+ )
132
+ assert u_error <= 1e-10
133
+
134
+
135
+ @pytest.mark.xslow
136
+ @pytest.mark.xfail(reason="geninvgauss CDF is not accurate")
137
+ def test_geninvgauss_uerror():
138
+ dist = stats.geninvgauss(3.2, 1.5)
139
+ rng = FastGeneratorInversion(dist)
140
+ err = rng.evaluate_error(size=10_000, random_state=67982)
141
+ assert err[0] < 1e-10
142
+
143
+
144
+ # TODO: add more distributions
145
+ @pytest.mark.fail_slow(5)
146
+ @pytest.mark.parametrize(("distname, args"), [("beta", (0.11, 0.11))])
147
+ def test_error_extreme_params(distname, args):
148
+ # take extreme parameters where u-error might not be below the tolerance
149
+ # due to limitations of floating point arithmetic
150
+ with suppress_warnings() as sup:
151
+ # filter the warnings thrown by UNU.RAN for such extreme parameters
152
+ sup.filter(RuntimeWarning)
153
+ dist = getattr(stats, distname)(*args)
154
+ rng = FastGeneratorInversion(dist)
155
+ u_error, x_error = rng.evaluate_error(
156
+ size=10_000, random_state=980732462809709732623, x_error=True
157
+ )
158
+ if u_error >= 2.5 * 1e-10:
159
+ assert x_error < 1e-9
160
+
161
+
162
+ def test_evaluate_error_inputs():
163
+ gen = FastGeneratorInversion(stats.norm())
164
+ with pytest.raises(ValueError, match="size must be an integer"):
165
+ gen.evaluate_error(size=3.5)
166
+ with pytest.raises(ValueError, match="size must be an integer"):
167
+ gen.evaluate_error(size=(3, 3))
168
+
169
+
170
+ def test_rvs_ppf_loc_scale():
171
+ loc, scale = 3.5, 2.3
172
+ dist = stats.norm(loc=loc, scale=scale)
173
+ rng = FastGeneratorInversion(dist, random_state=1234)
174
+ r = rng.rvs(size=1000)
175
+ r_rescaled = (r - loc) / scale
176
+ assert stats.cramervonmises(r_rescaled, "norm").pvalue > 0.01
177
+ q = [0.001, 0.1, 0.5, 0.9, 0.999]
178
+ assert_allclose(rng._ppf(q), rng.ppf(q), atol=1e-10)
179
+
180
+
181
+ def test_domain():
182
+ # only a basic check that the domain argument is passed to the
183
+ # UNU.RAN generators
184
+ rng = FastGeneratorInversion(stats.norm(), domain=(-1, 1))
185
+ r = rng.rvs(size=100)
186
+ assert -1 <= r.min() < r.max() <= 1
187
+
188
+ # if loc and scale are used, new domain is loc + scale*domain
189
+ loc, scale = 3.5, 1.3
190
+ dist = stats.norm(loc=loc, scale=scale)
191
+ rng = FastGeneratorInversion(dist, domain=(-1.5, 2))
192
+ r = rng.rvs(size=100)
193
+ lb, ub = loc - scale * 1.5, loc + scale * 2
194
+ assert lb <= r.min() < r.max() <= ub
195
+
196
+
197
+ @pytest.mark.parametrize(("distname, args, expected"),
198
+ [("beta", (3.5, 2.5), (0, 1)),
199
+ ("norm", (), (-np.inf, np.inf))])
200
+ def test_support(distname, args, expected):
201
+ # test that the support is updated if truncation and loc/scale are applied
202
+ # use beta distribution since it is a transformed betaprime distribution,
203
+ # so it is important that the correct support is considered
204
+ # (i.e., the support of beta is (0,1), while betaprime is (0, inf))
205
+ dist = getattr(stats, distname)(*args)
206
+ rng = FastGeneratorInversion(dist)
207
+ assert_array_equal(rng.support(), expected)
208
+ rng.loc = 1
209
+ rng.scale = 2
210
+ assert_array_equal(rng.support(), 1 + 2*np.array(expected))
211
+
212
+
213
+ @pytest.mark.parametrize(("distname, args"),
214
+ [("beta", (3.5, 2.5)), ("norm", ())])
215
+ def test_support_truncation(distname, args):
216
+ # similar test for truncation
217
+ dist = getattr(stats, distname)(*args)
218
+ rng = FastGeneratorInversion(dist, domain=(0.5, 0.7))
219
+ assert_array_equal(rng.support(), (0.5, 0.7))
220
+ rng.loc = 1
221
+ rng.scale = 2
222
+ assert_array_equal(rng.support(), (1 + 2 * 0.5, 1 + 2 * 0.7))
223
+
224
+
225
+ def test_domain_shift_truncation():
226
+ # center of norm is zero, it should be shifted to the left endpoint of
227
+ # domain. if this was not the case, PINV in UNURAN would raise a warning
228
+ # as the center is not inside the domain
229
+ with warnings.catch_warnings():
230
+ warnings.simplefilter("error")
231
+ rng = FastGeneratorInversion(stats.norm(), domain=(1, 2))
232
+ r = rng.rvs(size=100)
233
+ assert 1 <= r.min() < r.max() <= 2
234
+
235
+
236
+ def test_non_rvs_methods_with_domain():
237
+ # as a first step, compare truncated normal against stats.truncnorm
238
+ rng = FastGeneratorInversion(stats.norm(), domain=(2.3, 3.2))
239
+ trunc_norm = stats.truncnorm(2.3, 3.2)
240
+ # take values that are inside and outside the domain
241
+ x = (2.0, 2.4, 3.0, 3.4)
242
+ p = (0.01, 0.5, 0.99)
243
+ assert_allclose(rng._cdf(x), trunc_norm.cdf(x))
244
+ assert_allclose(rng._ppf(p), trunc_norm.ppf(p))
245
+ loc, scale = 2, 3
246
+ rng.loc = 2
247
+ rng.scale = 3
248
+ trunc_norm = stats.truncnorm(2.3, 3.2, loc=loc, scale=scale)
249
+ x = np.array(x) * scale + loc
250
+ assert_allclose(rng._cdf(x), trunc_norm.cdf(x))
251
+ assert_allclose(rng._ppf(p), trunc_norm.ppf(p))
252
+
253
+ # do another sanity check with beta distribution
254
+ # in that case, it is important to use the correct domain since beta
255
+ # is a transformation of betaprime which has a different support
256
+ rng = FastGeneratorInversion(stats.beta(2.5, 3.5), domain=(0.3, 0.7))
257
+ rng.loc = 2
258
+ rng.scale = 2.5
259
+ # the support is 2.75, , 3.75 (2 + 2.5 * 0.3, 2 + 2.5 * 0.7)
260
+ assert_array_equal(rng.support(), (2.75, 3.75))
261
+ x = np.array([2.74, 2.76, 3.74, 3.76])
262
+ # the cdf needs to be zero outside of the domain
263
+ y_cdf = rng._cdf(x)
264
+ assert_array_equal((y_cdf[0], y_cdf[3]), (0, 1))
265
+ assert np.min(y_cdf[1:3]) > 0
266
+ # ppf needs to map 0 and 1 to the boundaries
267
+ assert_allclose(rng._ppf(y_cdf), (2.75, 2.76, 3.74, 3.75))
268
+
269
+
270
+ def test_non_rvs_methods_without_domain():
271
+ norm_dist = stats.norm()
272
+ rng = FastGeneratorInversion(norm_dist)
273
+ x = np.linspace(-3, 3, num=10)
274
+ p = (0.01, 0.5, 0.99)
275
+ assert_allclose(rng._cdf(x), norm_dist.cdf(x))
276
+ assert_allclose(rng._ppf(p), norm_dist.ppf(p))
277
+ loc, scale = 0.5, 1.3
278
+ rng.loc = loc
279
+ rng.scale = scale
280
+ norm_dist = stats.norm(loc=loc, scale=scale)
281
+ assert_allclose(rng._cdf(x), norm_dist.cdf(x))
282
+ assert_allclose(rng._ppf(p), norm_dist.ppf(p))
283
+
284
+ @pytest.mark.parametrize(("domain, x"),
285
+ [(None, 0.5),
286
+ ((0, 1), 0.5),
287
+ ((0, 1), 1.5)])
288
+ def test_scalar_inputs(domain, x):
289
+ """ pdf, cdf etc should map scalar values to scalars. check with and
290
+ w/o domain since domain impacts pdf, cdf etc
291
+ Take x inside and outside of domain """
292
+ rng = FastGeneratorInversion(stats.norm(), domain=domain)
293
+ assert np.isscalar(rng._cdf(x))
294
+ assert np.isscalar(rng._ppf(0.5))
295
+
296
+
297
+ def test_domain_argus_large_chi():
298
+ # for large chi, the Gamma distribution is used and the domain has to be
299
+ # transformed. this is a test to ensure that the transformation works
300
+ chi, lb, ub = 5.5, 0.25, 0.75
301
+ rng = FastGeneratorInversion(stats.argus(chi), domain=(lb, ub))
302
+ rng.random_state = 4574
303
+ r = rng.rvs(size=500)
304
+ assert lb <= r.min() < r.max() <= ub
305
+ # perform goodness of fit test with conditional cdf
306
+ cdf = stats.argus(chi).cdf
307
+ prob = cdf(ub) - cdf(lb)
308
+ assert stats.cramervonmises(r, lambda x: cdf(x) / prob).pvalue > 0.05
309
+
310
+
311
+ def test_setting_loc_scale():
312
+ rng = FastGeneratorInversion(stats.norm(), random_state=765765864)
313
+ r1 = rng.rvs(size=1000)
314
+ rng.loc = 3.0
315
+ rng.scale = 2.5
316
+ r2 = rng.rvs(1000)
317
+ # rescaled r2 should be again standard normal
318
+ assert stats.cramervonmises_2samp(r1, (r2 - 3) / 2.5).pvalue > 0.05
319
+ # reset values to default loc=0, scale=1
320
+ rng.loc = 0
321
+ rng.scale = 1
322
+ r2 = rng.rvs(1000)
323
+ assert stats.cramervonmises_2samp(r1, r2).pvalue > 0.05
324
+
325
+
326
+ def test_ignore_shape_range():
327
+ msg = "No generator is defined for the shape parameters"
328
+ with pytest.raises(ValueError, match=msg):
329
+ rng = FastGeneratorInversion(stats.t(0.03))
330
+ rng = FastGeneratorInversion(stats.t(0.03), ignore_shape_range=True)
331
+ # we can ignore the recommended range of shape parameters
332
+ # but u-error can be expected to be too large in that case
333
+ u_err, _ = rng.evaluate_error(size=1000, random_state=234)
334
+ assert u_err >= 1e-6
335
+
336
+ @pytest.mark.xfail_on_32bit(
337
+ "NumericalInversePolynomial.qrvs fails for Win 32-bit"
338
+ )
339
+ class TestQRVS:
340
+ def test_input_validation(self):
341
+ gen = FastGeneratorInversion(stats.norm())
342
+
343
+ match = "`qmc_engine` must be an instance of..."
344
+ with pytest.raises(ValueError, match=match):
345
+ gen.qrvs(qmc_engine=0)
346
+
347
+ match = "`d` must be consistent with dimension of `qmc_engine`."
348
+ with pytest.raises(ValueError, match=match):
349
+ gen.qrvs(d=3, qmc_engine=stats.qmc.Halton(2))
350
+
351
+ qrngs = [None, stats.qmc.Sobol(1, seed=0), stats.qmc.Halton(3, seed=0)]
352
+ # `size=None` should not add anything to the shape, `size=1` should
353
+ sizes = [
354
+ (None, tuple()),
355
+ (1, (1,)),
356
+ (4, (4,)),
357
+ ((4,), (4,)),
358
+ ((2, 4), (2, 4)),
359
+ ]
360
+ # Neither `d=None` nor `d=1` should add anything to the shape
361
+ ds = [(None, tuple()), (1, tuple()), (3, (3,))]
362
+
363
+ @pytest.mark.parametrize("qrng", qrngs)
364
+ @pytest.mark.parametrize("size_in, size_out", sizes)
365
+ @pytest.mark.parametrize("d_in, d_out", ds)
366
+ def test_QRVS_shape_consistency(self, qrng, size_in, size_out,
367
+ d_in, d_out):
368
+ gen = FastGeneratorInversion(stats.norm())
369
+
370
+ # If d and qrng.d are inconsistent, an error is raised
371
+ if d_in is not None and qrng is not None and qrng.d != d_in:
372
+ match = "`d` must be consistent with dimension of `qmc_engine`."
373
+ with pytest.raises(ValueError, match=match):
374
+ gen.qrvs(size_in, d=d_in, qmc_engine=qrng)
375
+ return
376
+
377
+ # Sometimes d is really determined by qrng
378
+ if d_in is None and qrng is not None and qrng.d != 1:
379
+ d_out = (qrng.d,)
380
+
381
+ shape_expected = size_out + d_out
382
+
383
+ qrng2 = deepcopy(qrng)
384
+ qrvs = gen.qrvs(size=size_in, d=d_in, qmc_engine=qrng)
385
+ if size_in is not None:
386
+ assert qrvs.shape == shape_expected
387
+
388
+ if qrng2 is not None:
389
+ uniform = qrng2.random(np.prod(size_in) or 1)
390
+ qrvs2 = stats.norm.ppf(uniform).reshape(shape_expected)
391
+ assert_allclose(qrvs, qrvs2, atol=1e-12)
392
+
393
+ def test_QRVS_size_tuple(self):
394
+ # QMCEngine samples are always of shape (n, d). When `size` is a tuple,
395
+ # we set `n = prod(size)` in the call to qmc_engine.random, transform
396
+ # the sample, and reshape it to the final dimensions. When we reshape,
397
+ # we need to be careful, because the _columns_ of the sample returned
398
+ # by a QMCEngine are "independent"-ish, but the elements within the
399
+ # columns are not. We need to make sure that this doesn't get mixed up
400
+ # by reshaping: qrvs[..., i] should remain "independent"-ish of
401
+ # qrvs[..., i+1], but the elements within qrvs[..., i] should be
402
+ # transformed from the same low-discrepancy sequence.
403
+
404
+ gen = FastGeneratorInversion(stats.norm())
405
+
406
+ size = (3, 4)
407
+ d = 5
408
+ qrng = stats.qmc.Halton(d, seed=0)
409
+ qrng2 = stats.qmc.Halton(d, seed=0)
410
+
411
+ uniform = qrng2.random(np.prod(size))
412
+
413
+ qrvs = gen.qrvs(size=size, d=d, qmc_engine=qrng)
414
+ qrvs2 = stats.norm.ppf(uniform)
415
+
416
+ for i in range(d):
417
+ sample = qrvs[..., i]
418
+ sample2 = qrvs2[:, i].reshape(size)
419
+ assert_allclose(sample, sample2, atol=1e-12)
420
+
421
+
422
+ def test_burr_overflow():
423
+ # this case leads to an overflow error if math.exp is used
424
+ # in the definition of the burr pdf instead of np.exp
425
+ # a direct implementation of the PDF as x**(-c-1) / (1+x**(-c))**(d+1)
426
+ # also leads to an overflow error in the setup
427
+ args = (1.89128135, 0.30195177)
428
+ with suppress_warnings() as sup:
429
+ # filter potential overflow warning
430
+ sup.filter(RuntimeWarning)
431
+ gen = FastGeneratorInversion(stats.burr(*args))
432
+ u_error, _ = gen.evaluate_error(random_state=4326)
433
+ assert u_error <= 1e-10
shared/package-files/00/00416a0d488c68cdaa9f2f1ff590f227807dda2acd8fba1254b8d076cc2c6fdd/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 reflection_pad1d_backward(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding);
21
+ TORCH_API at::Tensor reflection_pad1d_backward_symint(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding);
22
+ TORCH_API at::Tensor & reflection_pad1d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding);
23
+ TORCH_API at::Tensor & reflection_pad1d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef padding, at::Tensor & grad_input);
24
+ TORCH_API at::Tensor & reflection_pad1d_backward_symint_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding);
25
+ TORCH_API at::Tensor & reflection_pad1d_backward_symint_outf(const at::Tensor & grad_output, const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & grad_input);
26
+
27
+ } // namespace cpu
28
+ } // namespace at
shared/package-files/00/0041d46d458301b27ecb872c1b017dfb423a8cc7f355bd0076fbcf02d81b09f5/blob ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ import contextlib
4
+ import functools
5
+ import inspect
6
+
7
+ import torch
8
+
9
+
10
+ # Test whether hardware BF32 math mode enabled. It is enabled only on:
11
+ # - MKLDNN is available
12
+ # - BF16 is supported by MKLDNN
13
+ def bf32_is_not_fp32():
14
+ if not torch.backends.mkldnn.is_available():
15
+ return False
16
+ if not torch.ops.mkldnn._is_mkldnn_bf16_supported():
17
+ return False
18
+ return True
19
+
20
+
21
+ @contextlib.contextmanager
22
+ def bf32_off():
23
+ old_matmul_precision = torch.get_float32_matmul_precision()
24
+ try:
25
+ torch.set_float32_matmul_precision("highest")
26
+ yield
27
+ finally:
28
+ torch.set_float32_matmul_precision(old_matmul_precision)
29
+
30
+
31
+ @contextlib.contextmanager
32
+ def bf32_on(self, bf32_precision=1e-5):
33
+ old_matmul_precision = torch.get_float32_matmul_precision()
34
+ old_precision = self.precision
35
+ try:
36
+ torch.set_float32_matmul_precision("medium")
37
+ self.precision = bf32_precision
38
+ yield
39
+ finally:
40
+ torch.set_float32_matmul_precision(old_matmul_precision)
41
+ self.precision = old_precision
42
+
43
+
44
+ # This is a wrapper that wraps a test to run this test twice, one with
45
+ # allow_bf32=True, another with allow_bf32=False. When running with
46
+ # allow_bf32=True, it will use reduced precision as specified by the
47
+ # argument
48
+ def bf32_on_and_off(bf32_precision=1e-5):
49
+ def with_bf32_disabled(self, function_call):
50
+ with bf32_off():
51
+ function_call()
52
+
53
+ def with_bf32_enabled(self, function_call):
54
+ with bf32_on(self, bf32_precision):
55
+ function_call()
56
+
57
+ def wrapper(f):
58
+ params = inspect.signature(f).parameters
59
+ arg_names = tuple(params.keys())
60
+
61
+ @functools.wraps(f)
62
+ def wrapped(*args, **kwargs):
63
+ for k, v in zip(arg_names, args):
64
+ kwargs[k] = v
65
+ cond = bf32_is_not_fp32()
66
+ if "device" in kwargs:
67
+ cond = cond and (torch.device(kwargs["device"]).type == "cpu")
68
+ if "dtype" in kwargs:
69
+ cond = cond and (kwargs["dtype"] == torch.float)
70
+ if cond:
71
+ with_bf32_disabled(kwargs["self"], lambda: f(**kwargs))
72
+ with_bf32_enabled(kwargs["self"], lambda: f(**kwargs))
73
+ else:
74
+ f(**kwargs)
75
+
76
+ return wrapped
77
+
78
+ return wrapper
shared/package-files/00/0043db8cea50b491a93a3c2bae2fbac15da0cd422f359e44215255b1312eb219/blob ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Iterable, Optional, Type, Union, TypeVar
2
+
3
+ from django.utils.deprecation import MiddlewareMixin
4
+ from django.views.generic.base import View
5
+
6
+ _T = TypeVar("_T", bound=Union[View, Callable]) # Any callable
7
+
8
+ class classonlymethod(classmethod): ...
9
+
10
+ def method_decorator(decorator: Union[Callable, Iterable[Callable]], name: str = ...) -> Callable[[_T], _T]: ...
11
+ def decorator_from_middleware_with_args(middleware_class: type) -> Callable: ...
12
+ def decorator_from_middleware(middleware_class: type) -> Callable: ...
13
+ def available_attrs(fn: Callable): ...
14
+ def make_middleware_decorator(middleware_class: Type[MiddlewareMixin]) -> Callable: ...
15
+
16
+ class classproperty:
17
+ fget: Optional[Callable] = ...
18
+ def __init__(self, method: Optional[Callable] = ...) -> None: ...
19
+ def __get__(self, instance: Any, cls: Optional[type] = ...) -> Any: ...
20
+ def getter(self, method: Callable) -> classproperty: ...
shared/package-files/00/0044e23094d2e3a3ff97226409f39e7547a72fbb333129ef0ece163b42789de5/blob ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ from typing import Any, List, Tuple, cast
3
+ import random
4
+ import torch
5
+ import time
6
+ from torch.utils.benchmark import Timer
7
+
8
+ def extract_ir(filename: str) -> List[str]:
9
+ BEGIN = "<GRAPH_EXPORT>"
10
+ END = "</GRAPH_EXPORT>"
11
+ pfx = None
12
+ current = ""
13
+ graphs = []
14
+ with open(filename) as f:
15
+ split_strs = f.read().split(BEGIN)
16
+ for i, split_str in enumerate(split_strs):
17
+ if i == 0:
18
+ continue
19
+ end_loc = split_str.find(END)
20
+ if end_loc == -1:
21
+ continue
22
+ s = split_str[:end_loc]
23
+ pfx = split_strs[i - 1].splitlines()[-1]
24
+ lines = [x[len(pfx):] for x in s.splitlines(keepends=True)]
25
+ graphs.append(''.join(lines))
26
+
27
+ return graphs
28
+
29
+
30
+ def make_tensor_from_type(inp_type: torch._C.TensorType):
31
+ size = inp_type.sizes()
32
+ stride = inp_type.strides()
33
+ device = inp_type.device()
34
+ dtype = inp_type.dtype()
35
+ assert size is not None
36
+ assert stride is not None
37
+ assert device is not None
38
+ assert dtype is not None
39
+ return torch.empty_strided(size=size, stride=stride, device=device, dtype=dtype)
40
+
41
+ def load_graph_and_inputs(ir: str) -> Tuple[Any, List[Any]]:
42
+ graph = torch._C.parse_ir(ir, parse_tensor_constants=True)
43
+ graph.makeMultiOutputIntoTuple()
44
+ inputs = []
45
+ for inp in graph.inputs():
46
+ if isinstance(inp.type(), torch._C.FloatType):
47
+ inputs.append(random.uniform(.1, 100))
48
+ elif isinstance(inp.type(), torch._C.IntType):
49
+ inputs.append(random.randint(1, 100))
50
+ elif isinstance(inp.type(), torch._C.TensorType):
51
+ tensorType = cast(torch._C.TensorType, inp.type())
52
+ inputs.append(make_tensor_from_type(tensorType))
53
+ elif isinstance(inp.type(), torch._C.BoolType):
54
+ inputs.append(random.randint(0, 1) == 1)
55
+ else:
56
+ raise NotImplementedError(f"A default value is not implemented for type {inp.type()}")
57
+
58
+ func = torch._C._create_function_from_graph("forward", graph)
59
+ torch._C._jit_pass_erase_shape_information(func.graph)
60
+ return (func, inputs)
61
+
62
+ def time_cuda(fn, inputs, test_runs):
63
+ t = Timer(stmt="fn(*inputs)", globals={"fn": fn, "inputs" : inputs})
64
+ times = t.blocked_autorange()
65
+ return times.median * 1000 # time in ms
66
+
67
+ def time_cpu(fn, inputs, test_runs):
68
+ s = time.perf_counter()
69
+ for _ in range(test_runs):
70
+ fn(*inputs)
71
+ e = time.perf_counter()
72
+ return (e - s) / test_runs * 1000 # time in ms
73
+
74
+ def run_test(ir, inputs, *, warmup_runs=10, test_runs=20) -> float:
75
+ graph, _ = load_graph_and_inputs(ir)
76
+ for _ in range(warmup_runs):
77
+ graph(*inputs)
78
+
79
+ is_cpu = None
80
+ for input in inputs:
81
+ if isinstance(input, torch.Tensor):
82
+ is_cpu = input.device.type == "cpu"
83
+ break
84
+ assert is_cpu is not None
85
+
86
+ out = time_cpu(graph, inputs, test_runs) if is_cpu else time_cuda(graph, inputs, test_runs)
87
+ return out
88
+
89
+ @contextmanager
90
+ def no_fuser(*args, **kwargs):
91
+ old_optimize = torch._C._get_graph_executor_optimize(False)
92
+ try:
93
+ yield
94
+ finally:
95
+ torch._C._get_graph_executor_optimize(old_optimize)
96
+
97
+ def run_baseline_no_fusion(ir, inputs) -> float:
98
+ with no_fuser():
99
+ return run_test(ir, inputs)
100
+
101
+
102
+ def run_nnc(ir, inputs, dynamic) -> float:
103
+ try:
104
+ strat = [("DYNAMIC", 10)] if dynamic else [("STATIC", 10)]
105
+ old_strat = torch.jit.set_fusion_strategy(strat)
106
+ with torch.jit.fuser("fuser1"):
107
+ return run_test(ir, inputs)
108
+ finally:
109
+ torch.jit.set_fusion_strategy(old_strat)
110
+
111
+ def run_nvfuser(ir, inputs) -> float:
112
+ with torch.jit.fuser("fuser2"):
113
+ return run_test(ir, inputs)
shared/package-files/00/004558d2aa27cb210c82fe03a3674836baea500c149365d84aa1cceb9d2ecde9/blob ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.util
3
+ ~~~~~~~~~~~~~
4
+
5
+ Utility functions.
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
+ from io import TextIOWrapper
13
+
14
+
15
+ split_path_re = re.compile(r'[/\\ ]')
16
+ doctype_lookup_re = re.compile(r'''
17
+ <!DOCTYPE\s+(
18
+ [a-zA-Z_][a-zA-Z0-9]*
19
+ (?: \s+ # optional in HTML5
20
+ [a-zA-Z_][a-zA-Z0-9]*\s+
21
+ "[^"]*")?
22
+ )
23
+ [^>]*>
24
+ ''', re.DOTALL | re.MULTILINE | re.VERBOSE)
25
+ tag_re = re.compile(r'<(.+?)(\s.*?)?>.*?</.+?>',
26
+ re.IGNORECASE | re.DOTALL | re.MULTILINE)
27
+ xml_decl_re = re.compile(r'\s*<\?xml[^>]*\?>', re.I)
28
+
29
+
30
+ class ClassNotFound(ValueError):
31
+ """Raised if one of the lookup functions didn't find a matching class."""
32
+
33
+
34
+ class OptionError(Exception):
35
+ """
36
+ This exception will be raised by all option processing functions if
37
+ the type or value of the argument is not correct.
38
+ """
39
+
40
+ def get_choice_opt(options, optname, allowed, default=None, normcase=False):
41
+ """
42
+ If the key `optname` from the dictionary is not in the sequence
43
+ `allowed`, raise an error, otherwise return it.
44
+ """
45
+ string = options.get(optname, default)
46
+ if normcase:
47
+ string = string.lower()
48
+ if string not in allowed:
49
+ raise OptionError('Value for option %s must be one of %s' %
50
+ (optname, ', '.join(map(str, allowed))))
51
+ return string
52
+
53
+
54
+ def get_bool_opt(options, optname, default=None):
55
+ """
56
+ Intuitively, this is `options.get(optname, default)`, but restricted to
57
+ Boolean value. The Booleans can be represented as string, in order to accept
58
+ Boolean value from the command line arguments. If the key `optname` is
59
+ present in the dictionary `options` and is not associated with a Boolean,
60
+ raise an `OptionError`. If it is absent, `default` is returned instead.
61
+
62
+ The valid string values for ``True`` are ``1``, ``yes``, ``true`` and
63
+ ``on``, the ones for ``False`` are ``0``, ``no``, ``false`` and ``off``
64
+ (matched case-insensitively).
65
+ """
66
+ string = options.get(optname, default)
67
+ if isinstance(string, bool):
68
+ return string
69
+ elif isinstance(string, int):
70
+ return bool(string)
71
+ elif not isinstance(string, str):
72
+ raise OptionError('Invalid type %r for option %s; use '
73
+ '1/0, yes/no, true/false, on/off' % (
74
+ string, optname))
75
+ elif string.lower() in ('1', 'yes', 'true', 'on'):
76
+ return True
77
+ elif string.lower() in ('0', 'no', 'false', 'off'):
78
+ return False
79
+ else:
80
+ raise OptionError('Invalid value %r for option %s; use '
81
+ '1/0, yes/no, true/false, on/off' % (
82
+ string, optname))
83
+
84
+
85
+ def get_int_opt(options, optname, default=None):
86
+ """As :func:`get_bool_opt`, but interpret the value as an integer."""
87
+ string = options.get(optname, default)
88
+ try:
89
+ return int(string)
90
+ except TypeError:
91
+ raise OptionError('Invalid type %r for option %s; you '
92
+ 'must give an integer value' % (
93
+ string, optname))
94
+ except ValueError:
95
+ raise OptionError('Invalid value %r for option %s; you '
96
+ 'must give an integer value' % (
97
+ string, optname))
98
+
99
+ def get_list_opt(options, optname, default=None):
100
+ """
101
+ If the key `optname` from the dictionary `options` is a string,
102
+ split it at whitespace and return it. If it is already a list
103
+ or a tuple, it is returned as a list.
104
+ """
105
+ val = options.get(optname, default)
106
+ if isinstance(val, str):
107
+ return val.split()
108
+ elif isinstance(val, (list, tuple)):
109
+ return list(val)
110
+ else:
111
+ raise OptionError('Invalid type %r for option %s; you '
112
+ 'must give a list value' % (
113
+ val, optname))
114
+
115
+
116
+ def docstring_headline(obj):
117
+ if not obj.__doc__:
118
+ return ''
119
+ res = []
120
+ for line in obj.__doc__.strip().splitlines():
121
+ if line.strip():
122
+ res.append(" " + line.strip())
123
+ else:
124
+ break
125
+ return ''.join(res).lstrip()
126
+
127
+
128
+ def make_analysator(f):
129
+ """Return a static text analyser function that returns float values."""
130
+ def text_analyse(text):
131
+ try:
132
+ rv = f(text)
133
+ except Exception:
134
+ return 0.0
135
+ if not rv:
136
+ return 0.0
137
+ try:
138
+ return min(1.0, max(0.0, float(rv)))
139
+ except (ValueError, TypeError):
140
+ return 0.0
141
+ text_analyse.__doc__ = f.__doc__
142
+ return staticmethod(text_analyse)
143
+
144
+
145
+ def shebang_matches(text, regex):
146
+ r"""Check if the given regular expression matches the last part of the
147
+ shebang if one exists.
148
+
149
+ >>> from pygments.util import shebang_matches
150
+ >>> shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?')
151
+ True
152
+ >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?')
153
+ True
154
+ >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?')
155
+ False
156
+ >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?')
157
+ False
158
+ >>> shebang_matches('#!/usr/bin/startsomethingwith python',
159
+ ... r'python(2\.\d)?')
160
+ True
161
+
162
+ It also checks for common windows executable file extensions::
163
+
164
+ >>> shebang_matches('#!C:\\Python2.4\\Python.exe', r'python(2\.\d)?')
165
+ True
166
+
167
+ Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does
168
+ the same as ``'perl -e'``)
169
+
170
+ Note that this method automatically searches the whole string (eg:
171
+ the regular expression is wrapped in ``'^$'``)
172
+ """
173
+ index = text.find('\n')
174
+ if index >= 0:
175
+ first_line = text[:index].lower()
176
+ else:
177
+ first_line = text.lower()
178
+ if first_line.startswith('#!'):
179
+ try:
180
+ found = [x for x in split_path_re.split(first_line[2:].strip())
181
+ if x and not x.startswith('-')][-1]
182
+ except IndexError:
183
+ return False
184
+ regex = re.compile(r'^%s(\.(exe|cmd|bat|bin))?$' % regex, re.IGNORECASE)
185
+ if regex.search(found) is not None:
186
+ return True
187
+ return False
188
+
189
+
190
+ def doctype_matches(text, regex):
191
+ """Check if the doctype matches a regular expression (if present).
192
+
193
+ Note that this method only checks the first part of a DOCTYPE.
194
+ eg: 'html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
195
+ """
196
+ m = doctype_lookup_re.search(text)
197
+ if m is None:
198
+ return False
199
+ doctype = m.group(1)
200
+ return re.compile(regex, re.I).match(doctype.strip()) is not None
201
+
202
+
203
+ def html_doctype_matches(text):
204
+ """Check if the file looks like it has a html doctype."""
205
+ return doctype_matches(text, r'html')
206
+
207
+
208
+ _looks_like_xml_cache = {}
209
+
210
+
211
+ def looks_like_xml(text):
212
+ """Check if a doctype exists or if we have some tags."""
213
+ if xml_decl_re.match(text):
214
+ return True
215
+ key = hash(text)
216
+ try:
217
+ return _looks_like_xml_cache[key]
218
+ except KeyError:
219
+ m = doctype_lookup_re.search(text)
220
+ if m is not None:
221
+ return True
222
+ rv = tag_re.search(text[:1000]) is not None
223
+ _looks_like_xml_cache[key] = rv
224
+ return rv
225
+
226
+
227
+ def surrogatepair(c):
228
+ """Given a unicode character code with length greater than 16 bits,
229
+ return the two 16 bit surrogate pair.
230
+ """
231
+ # From example D28 of:
232
+ # http://www.unicode.org/book/ch03.pdf
233
+ return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))
234
+
235
+
236
+ def format_lines(var_name, seq, raw=False, indent_level=0):
237
+ """Formats a sequence of strings for output."""
238
+ lines = []
239
+ base_indent = ' ' * indent_level * 4
240
+ inner_indent = ' ' * (indent_level + 1) * 4
241
+ lines.append(base_indent + var_name + ' = (')
242
+ if raw:
243
+ # These should be preformatted reprs of, say, tuples.
244
+ for i in seq:
245
+ lines.append(inner_indent + i + ',')
246
+ else:
247
+ for i in seq:
248
+ # Force use of single quotes
249
+ r = repr(i + '"')
250
+ lines.append(inner_indent + r[:-2] + r[-1] + ',')
251
+ lines.append(base_indent + ')')
252
+ return '\n'.join(lines)
253
+
254
+
255
+ def duplicates_removed(it, already_seen=()):
256
+ """
257
+ Returns a list with duplicates removed from the iterable `it`.
258
+
259
+ Order is preserved.
260
+ """
261
+ lst = []
262
+ seen = set()
263
+ for i in it:
264
+ if i in seen or i in already_seen:
265
+ continue
266
+ lst.append(i)
267
+ seen.add(i)
268
+ return lst
269
+
270
+
271
+ class Future:
272
+ """Generic class to defer some work.
273
+
274
+ Handled specially in RegexLexerMeta, to support regex string construction at
275
+ first use.
276
+ """
277
+ def get(self):
278
+ raise NotImplementedError
279
+
280
+
281
+ def guess_decode(text):
282
+ """Decode *text* with guessed encoding.
283
+
284
+ First try UTF-8; this should fail for non-UTF-8 encodings.
285
+ Then try the preferred locale encoding.
286
+ Fall back to latin-1, which always works.
287
+ """
288
+ try:
289
+ text = text.decode('utf-8')
290
+ return text, 'utf-8'
291
+ except UnicodeDecodeError:
292
+ try:
293
+ import locale
294
+ prefencoding = locale.getpreferredencoding()
295
+ text = text.decode()
296
+ return text, prefencoding
297
+ except (UnicodeDecodeError, LookupError):
298
+ text = text.decode('latin1')
299
+ return text, 'latin1'
300
+
301
+
302
+ def guess_decode_from_terminal(text, term):
303
+ """Decode *text* coming from terminal *term*.
304
+
305
+ First try the terminal encoding, if given.
306
+ Then try UTF-8. Then try the preferred locale encoding.
307
+ Fall back to latin-1, which always works.
308
+ """
309
+ if getattr(term, 'encoding', None):
310
+ try:
311
+ text = text.decode(term.encoding)
312
+ except UnicodeDecodeError:
313
+ pass
314
+ else:
315
+ return text, term.encoding
316
+ return guess_decode(text)
317
+
318
+
319
+ def terminal_encoding(term):
320
+ """Return our best guess of encoding for the given *term*."""
321
+ if getattr(term, 'encoding', None):
322
+ return term.encoding
323
+ import locale
324
+ return locale.getpreferredencoding()
325
+
326
+
327
+ class UnclosingTextIOWrapper(TextIOWrapper):
328
+ # Don't close underlying buffer on destruction.
329
+ def close(self):
330
+ self.flush()
shared/package-files/00/00463fe3819a889b13c931e466a1b6246895a053a9369301f786520f69c9f1f0/blob ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Adapted from CPython3.7 Objects/dict-common.h */
2
+ #include "cext.h"
3
+
4
+ #ifndef NUMBA_DICT_COMMON_H
5
+ #define NUMBA_DICT_COMMON_H
6
+
7
+ typedef struct {
8
+ /* Uses Py_ssize_t instead of Py_hash_t to guarantee word size alignment */
9
+ Py_ssize_t hash;
10
+ char keyvalue[];
11
+ } NB_DictEntry;
12
+
13
+
14
+ typedef int (*dict_key_comparator_t)(const char *lhs, const char *rhs);
15
+ typedef void (*dict_refcount_op_t)(const void*);
16
+
17
+
18
+ typedef struct {
19
+ dict_key_comparator_t key_equal;
20
+ dict_refcount_op_t key_incref;
21
+ dict_refcount_op_t key_decref;
22
+ dict_refcount_op_t value_incref;
23
+ dict_refcount_op_t value_decref;
24
+ } type_based_methods_table;
25
+
26
+
27
+ typedef struct {
28
+ /* hash table size */
29
+ Py_ssize_t size;
30
+ /* Usable size of the hash table.
31
+ Also, size of the entries */
32
+ Py_ssize_t usable;
33
+ /* hash table used entries */
34
+ Py_ssize_t nentries;
35
+ /* Entry info
36
+ - key_size is the sizeof key type
37
+ - val_size is the sizeof value type
38
+ - entry_size is key_size + val_size + alignment
39
+ */
40
+ Py_ssize_t key_size, val_size, entry_size;
41
+ /* Byte offset from indices to the first entry. */
42
+ Py_ssize_t entry_offset;
43
+
44
+ /* Method table for type-dependent operations. */
45
+ type_based_methods_table methods;
46
+
47
+ /* hash table */
48
+ char indices[];
49
+ } NB_DictKeys;
50
+
51
+
52
+ typedef struct {
53
+ /* num of elements in the hashtable */
54
+ Py_ssize_t used;
55
+ NB_DictKeys *keys;
56
+ } NB_Dict;
57
+
58
+
59
+ typedef struct {
60
+ /* parent dictionary */
61
+ NB_Dict *parent;
62
+ /* parent keys object */
63
+ NB_DictKeys *parent_keys;
64
+ /* dict size */
65
+ Py_ssize_t size;
66
+ /* iterator position; indicates the next position to read */
67
+ Py_ssize_t pos;
68
+ } NB_DictIter;
69
+
70
+
71
+
72
+ /* A test function for the dict
73
+ Returns 0 for OK; 1 for failure.
74
+ */
75
+ NUMBA_EXPORT_FUNC(int)
76
+ numba_test_dict(void);
77
+
78
+ /* Allocate a new dict
79
+ Parameters
80
+ - NB_Dict **out
81
+ Output for the new dictionary.
82
+ - Py_ssize_t size
83
+ Hashtable size. Must be power of two.
84
+ - Py_ssize_t key_size
85
+ Size of a key entry.
86
+ - Py_ssize_t val_size
87
+ Size of a value entry.
88
+ */
89
+ NUMBA_EXPORT_FUNC(int)
90
+ numba_dict_new(NB_Dict **out, Py_ssize_t size, Py_ssize_t key_size, Py_ssize_t val_size);
91
+
92
+ /* Allocate a new dict with enough space to hold n_keys without resizing.
93
+ Parameters
94
+ - NB_Dict **out
95
+ Output for the new dictionary.
96
+ - Py_ssize_t n_keys
97
+ The number of keys to fit without needing resize.
98
+ - Py_ssize_t key_size
99
+ Size of a key entry.
100
+ - Py_ssize_t val_size
101
+ Size of a value entry.
102
+ */
103
+ NUMBA_EXPORT_FUNC(int)
104
+ numba_dict_new_sized(NB_Dict** out, Py_ssize_t n_keys, Py_ssize_t key_size, Py_ssize_t val_size);
105
+
106
+ /* Free a dict */
107
+ NUMBA_EXPORT_FUNC(void)
108
+ numba_dict_free(NB_Dict *d);
109
+
110
+ /* Returns length of a dict */
111
+ NUMBA_EXPORT_FUNC(Py_ssize_t)
112
+ numba_dict_length(NB_Dict *d);
113
+
114
+ /* Set the method table for type specific operations
115
+ */
116
+ NUMBA_EXPORT_FUNC(void)
117
+ numba_dict_set_method_table(NB_Dict *d, type_based_methods_table *methods);
118
+
119
+ /* Lookup a key
120
+
121
+ Parameters
122
+ - NB_Dict *d
123
+ The dictionary object.
124
+ - const char *key_bytes
125
+ The key as a byte buffer.
126
+ - Py_hash_t hash
127
+ The precomputed hash of the key.
128
+ - char *oldval_bytes
129
+ An output parameter to store the associated value if the key is found.
130
+ Must point to memory of sufficient size to store the value.
131
+ */
132
+ NUMBA_EXPORT_FUNC(Py_ssize_t)
133
+ numba_dict_lookup(NB_Dict *d, const char *key_bytes, Py_hash_t hash, char *oldval_bytes);
134
+
135
+ /* Resize the dict to at least *minsize*.
136
+ */
137
+ NUMBA_EXPORT_FUNC(int)
138
+ numba_dict_resize(NB_Dict *d, Py_ssize_t minsize);
139
+
140
+ /* Insert to the dict
141
+
142
+ Parameters
143
+ - NB_Dict *d
144
+ The dictionary object.
145
+ - const char *key_bytes
146
+ The key as a byte buffer.
147
+ - Py_hash_t hash
148
+ The precomputed hash of key.
149
+ - const char *val_bytes
150
+ The value as a byte buffer.
151
+ - char *oldval_bytes
152
+ An output buffer to store the replaced value.
153
+ Must point to memory of sufficient size to store the value.
154
+
155
+ Returns
156
+ - < 0 for error
157
+ - 0 for ok
158
+ - 1 for ok and oldval_bytes has a copy of the replaced value.
159
+ */
160
+ NUMBA_EXPORT_FUNC(int)
161
+ numba_dict_insert(NB_Dict *d, const char *key_bytes, Py_hash_t hash, const char *val_bytes, char *oldval_bytes);
162
+
163
+ /* Same as numba_dict_insert() but oldval_bytes is not needed */
164
+ NUMBA_EXPORT_FUNC(int)
165
+ numba_dict_insert_ez(NB_Dict *d, const char *key_bytes, Py_hash_t hash, const char *val_bytes);
166
+
167
+ /* Delete an entry from the dict
168
+ Parameters
169
+ - NB_Dict *d
170
+ The dictionary
171
+ - Py_hash_t hash
172
+ Precomputed hash of the key to be deleted
173
+ - Py_ssize_t ix
174
+ Precomputed entry index of the key to be deleted.
175
+ Usually results of numba_dict_lookup().
176
+ */
177
+ NUMBA_EXPORT_FUNC(int)
178
+ numba_dict_delitem(NB_Dict *d, Py_hash_t hash, Py_ssize_t ix);
179
+
180
+ /* Remove an item from the dict
181
+ Parameters
182
+ - NB_Dict *d
183
+ The dictionary
184
+ - char *key_bytes
185
+ Output. The key as a byte buffer
186
+ - char *val_bytes
187
+ Output. The value as a byte buffer
188
+ */
189
+ NUMBA_EXPORT_FUNC(int)
190
+ numba_dict_popitem(NB_Dict *d, char *key_bytes, char *val_bytes);
191
+
192
+ /* Returns the sizeof a dictionary iterator
193
+ */
194
+ NUMBA_EXPORT_FUNC(size_t)
195
+ numba_dict_iter_sizeof(void);
196
+
197
+ /* Fill a NB_DictIter for a dictionary to begin iteration
198
+ Parameters
199
+ - NB_DictIter *it
200
+ Output. Must points to memory of size at least `numba_dict_iter_sizeof()`.
201
+ - NB_Dict *d
202
+ The dictionary to be iterated.
203
+ */
204
+ NUMBA_EXPORT_FUNC(void)
205
+ numba_dict_iter(NB_DictIter *it, NB_Dict *d);
206
+
207
+ /* Advance the iterator
208
+ Parameters
209
+ - NB_DictIter *it
210
+ The iterator
211
+ - const char **key_ptr
212
+ Output pointer for the key. Points to data in the dictionary.
213
+ - const char **val_ptr
214
+ Output pointer for the key. Points to data in the dictionary.
215
+
216
+ Returns
217
+ - 0 for success; valid key_ptr and val_ptr
218
+ - ERR_ITER_EXHAUSTED for end of iterator.
219
+ - ERR_DICT_MUTATED for detected dictionary mutation.
220
+ */
221
+ NUMBA_EXPORT_FUNC(int)
222
+ numba_dict_iter_next(NB_DictIter *it, const char **key_ptr, const char **val_ptr);
223
+
224
+
225
+ NUMBA_EXPORT_FUNC(void)
226
+ numba_dict_dump(NB_Dict *);
227
+
228
+ #endif
shared/package-files/00/0047fd967fa3e4c988310d094d03e19d9c1b361f36ca749446c58f68a68d8a78/blob ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ import datetime
19
+ import pytest
20
+
21
+ import pyarrow as pa
22
+
23
+
24
+ @pytest.mark.gandiva
25
+ def test_tree_exp_builder():
26
+ import pyarrow.gandiva as gandiva
27
+
28
+ builder = gandiva.TreeExprBuilder()
29
+
30
+ field_a = pa.field('a', pa.int32())
31
+ field_b = pa.field('b', pa.int32())
32
+
33
+ schema = pa.schema([field_a, field_b])
34
+
35
+ field_result = pa.field('res', pa.int32())
36
+
37
+ node_a = builder.make_field(field_a)
38
+ node_b = builder.make_field(field_b)
39
+
40
+ assert node_a.return_type() == field_a.type
41
+
42
+ condition = builder.make_function("greater_than", [node_a, node_b],
43
+ pa.bool_())
44
+ if_node = builder.make_if(condition, node_a, node_b, pa.int32())
45
+
46
+ expr = builder.make_expression(if_node, field_result)
47
+
48
+ assert expr.result().type == pa.int32()
49
+
50
+ config = gandiva.Configuration(dump_ir=True)
51
+ projector = gandiva.make_projector(
52
+ schema, [expr], pa.default_memory_pool(), "NONE", config)
53
+
54
+ # Gandiva generates compute kernel function named `@expr_X`
55
+ assert projector.llvm_ir.find("@expr_") != -1
56
+
57
+ a = pa.array([10, 12, -20, 5], type=pa.int32())
58
+ b = pa.array([5, 15, 15, 17], type=pa.int32())
59
+ e = pa.array([10, 15, 15, 17], type=pa.int32())
60
+ input_batch = pa.RecordBatch.from_arrays([a, b], names=['a', 'b'])
61
+
62
+ r, = projector.evaluate(input_batch)
63
+ assert r.equals(e)
64
+
65
+
66
+ @pytest.mark.gandiva
67
+ def test_table():
68
+ import pyarrow.gandiva as gandiva
69
+
70
+ table = pa.Table.from_arrays([pa.array([1.0, 2.0]), pa.array([3.0, 4.0])],
71
+ ['a', 'b'])
72
+
73
+ builder = gandiva.TreeExprBuilder()
74
+ node_a = builder.make_field(table.schema.field("a"))
75
+ node_b = builder.make_field(table.schema.field("b"))
76
+
77
+ sum = builder.make_function("add", [node_a, node_b], pa.float64())
78
+
79
+ field_result = pa.field("c", pa.float64())
80
+ expr = builder.make_expression(sum, field_result)
81
+
82
+ projector = gandiva.make_projector(
83
+ table.schema, [expr], pa.default_memory_pool())
84
+
85
+ # TODO: Add .evaluate function which can take Tables instead of
86
+ # RecordBatches
87
+ r, = projector.evaluate(table.to_batches()[0])
88
+
89
+ e = pa.array([4.0, 6.0])
90
+ assert r.equals(e)
91
+
92
+
93
+ @pytest.mark.gandiva
94
+ def test_filter():
95
+ import pyarrow.gandiva as gandiva
96
+
97
+ table = pa.Table.from_arrays([pa.array([1.0 * i for i in range(10000)])],
98
+ ['a'])
99
+
100
+ builder = gandiva.TreeExprBuilder()
101
+ node_a = builder.make_field(table.schema.field("a"))
102
+ thousand = builder.make_literal(1000.0, pa.float64())
103
+ cond = builder.make_function("less_than", [node_a, thousand], pa.bool_())
104
+ condition = builder.make_condition(cond)
105
+
106
+ assert condition.result().type == pa.bool_()
107
+
108
+ config = gandiva.Configuration(dump_ir=True)
109
+ filter = gandiva.make_filter(table.schema, condition, config)
110
+ # Gandiva generates compute kernel function named `@expr_X`
111
+ assert filter.llvm_ir.find("@expr_") != -1
112
+
113
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
114
+ assert result.to_array().equals(pa.array(range(1000), type=pa.uint32()))
115
+
116
+
117
+ @pytest.mark.gandiva
118
+ def test_in_expr():
119
+ import pyarrow.gandiva as gandiva
120
+
121
+ arr = pa.array(["ga", "an", "nd", "di", "iv", "va"])
122
+ table = pa.Table.from_arrays([arr], ["a"])
123
+
124
+ # string
125
+ builder = gandiva.TreeExprBuilder()
126
+ node_a = builder.make_field(table.schema.field("a"))
127
+ cond = builder.make_in_expression(node_a, ["an", "nd"], pa.string())
128
+ condition = builder.make_condition(cond)
129
+ filter = gandiva.make_filter(table.schema, condition)
130
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
131
+ assert result.to_array().equals(pa.array([1, 2], type=pa.uint32()))
132
+
133
+ # int32
134
+ arr = pa.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 4])
135
+ table = pa.Table.from_arrays([arr.cast(pa.int32())], ["a"])
136
+ node_a = builder.make_field(table.schema.field("a"))
137
+ cond = builder.make_in_expression(node_a, [1, 5], pa.int32())
138
+ condition = builder.make_condition(cond)
139
+ filter = gandiva.make_filter(table.schema, condition)
140
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
141
+ assert result.to_array().equals(pa.array([1, 3, 4, 8], type=pa.uint32()))
142
+
143
+ # int64
144
+ arr = pa.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 4])
145
+ table = pa.Table.from_arrays([arr], ["a"])
146
+ node_a = builder.make_field(table.schema.field("a"))
147
+ cond = builder.make_in_expression(node_a, [1, 5], pa.int64())
148
+ condition = builder.make_condition(cond)
149
+ filter = gandiva.make_filter(table.schema, condition)
150
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
151
+ assert result.to_array().equals(pa.array([1, 3, 4, 8], type=pa.uint32()))
152
+
153
+
154
+ @pytest.mark.skip(reason="Gandiva C++ did not have *real* binary, "
155
+ "time and date support.")
156
+ def test_in_expr_todo():
157
+ import pyarrow.gandiva as gandiva
158
+ # TODO: Implement reasonable support for timestamp, time & date.
159
+ # Current exceptions:
160
+ # pyarrow.lib.ArrowException: ExpressionValidationError:
161
+ # Evaluation expression for IN clause returns XXXX values are of typeXXXX
162
+
163
+ # binary
164
+ arr = pa.array([b"ga", b"an", b"nd", b"di", b"iv", b"va"])
165
+ table = pa.Table.from_arrays([arr], ["a"])
166
+
167
+ builder = gandiva.TreeExprBuilder()
168
+ node_a = builder.make_field(table.schema.field("a"))
169
+ cond = builder.make_in_expression(node_a, [b'an', b'nd'], pa.binary())
170
+ condition = builder.make_condition(cond)
171
+
172
+ filter = gandiva.make_filter(table.schema, condition)
173
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
174
+ assert result.to_array().equals(pa.array([1, 2], type=pa.uint32()))
175
+
176
+ # timestamp
177
+ datetime_1 = datetime.datetime.utcfromtimestamp(1542238951.621877)
178
+ datetime_2 = datetime.datetime.utcfromtimestamp(1542238911.621877)
179
+ datetime_3 = datetime.datetime.utcfromtimestamp(1542238051.621877)
180
+
181
+ arr = pa.array([datetime_1, datetime_2, datetime_3])
182
+ table = pa.Table.from_arrays([arr], ["a"])
183
+
184
+ builder = gandiva.TreeExprBuilder()
185
+ node_a = builder.make_field(table.schema.field("a"))
186
+ cond = builder.make_in_expression(node_a, [datetime_2], pa.timestamp('ms'))
187
+ condition = builder.make_condition(cond)
188
+
189
+ filter = gandiva.make_filter(table.schema, condition)
190
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
191
+ assert list(result.to_array()) == [1]
192
+
193
+ # time
194
+ time_1 = datetime_1.time()
195
+ time_2 = datetime_2.time()
196
+ time_3 = datetime_3.time()
197
+
198
+ arr = pa.array([time_1, time_2, time_3])
199
+ table = pa.Table.from_arrays([arr], ["a"])
200
+
201
+ builder = gandiva.TreeExprBuilder()
202
+ node_a = builder.make_field(table.schema.field("a"))
203
+ cond = builder.make_in_expression(node_a, [time_2], pa.time64('ms'))
204
+ condition = builder.make_condition(cond)
205
+
206
+ filter = gandiva.make_filter(table.schema, condition)
207
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
208
+ assert list(result.to_array()) == [1]
209
+
210
+ # date
211
+ date_1 = datetime_1.date()
212
+ date_2 = datetime_2.date()
213
+ date_3 = datetime_3.date()
214
+
215
+ arr = pa.array([date_1, date_2, date_3])
216
+ table = pa.Table.from_arrays([arr], ["a"])
217
+
218
+ builder = gandiva.TreeExprBuilder()
219
+ node_a = builder.make_field(table.schema.field("a"))
220
+ cond = builder.make_in_expression(node_a, [date_2], pa.date32())
221
+ condition = builder.make_condition(cond)
222
+
223
+ filter = gandiva.make_filter(table.schema, condition)
224
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
225
+ assert list(result.to_array()) == [1]
226
+
227
+
228
+ @pytest.mark.gandiva
229
+ def test_boolean():
230
+ import pyarrow.gandiva as gandiva
231
+
232
+ table = pa.Table.from_arrays([
233
+ pa.array([1., 31., 46., 3., 57., 44., 22.]),
234
+ pa.array([5., 45., 36., 73., 83., 23., 76.])],
235
+ ['a', 'b'])
236
+
237
+ builder = gandiva.TreeExprBuilder()
238
+ node_a = builder.make_field(table.schema.field("a"))
239
+ node_b = builder.make_field(table.schema.field("b"))
240
+ fifty = builder.make_literal(50.0, pa.float64())
241
+ eleven = builder.make_literal(11.0, pa.float64())
242
+
243
+ cond_1 = builder.make_function("less_than", [node_a, fifty], pa.bool_())
244
+ cond_2 = builder.make_function("greater_than", [node_a, node_b],
245
+ pa.bool_())
246
+ cond_3 = builder.make_function("less_than", [node_b, eleven], pa.bool_())
247
+ cond = builder.make_or([builder.make_and([cond_1, cond_2]), cond_3])
248
+ condition = builder.make_condition(cond)
249
+
250
+ filter = gandiva.make_filter(table.schema, condition)
251
+ result = filter.evaluate(table.to_batches()[0], pa.default_memory_pool())
252
+ assert result.to_array().equals(pa.array([0, 2, 5], type=pa.uint32()))
253
+
254
+
255
+ @pytest.mark.gandiva
256
+ def test_literals():
257
+ import pyarrow.gandiva as gandiva
258
+
259
+ builder = gandiva.TreeExprBuilder()
260
+
261
+ builder.make_literal(True, pa.bool_())
262
+ builder.make_literal(0, pa.uint8())
263
+ builder.make_literal(1, pa.uint16())
264
+ builder.make_literal(2, pa.uint32())
265
+ builder.make_literal(3, pa.uint64())
266
+ builder.make_literal(4, pa.int8())
267
+ builder.make_literal(5, pa.int16())
268
+ builder.make_literal(6, pa.int32())
269
+ builder.make_literal(7, pa.int64())
270
+ builder.make_literal(8.0, pa.float32())
271
+ builder.make_literal(9.0, pa.float64())
272
+ builder.make_literal("hello", pa.string())
273
+ builder.make_literal(b"world", pa.binary())
274
+
275
+ builder.make_literal(True, "bool")
276
+ builder.make_literal(0, "uint8")
277
+ builder.make_literal(1, "uint16")
278
+ builder.make_literal(2, "uint32")
279
+ builder.make_literal(3, "uint64")
280
+ builder.make_literal(4, "int8")
281
+ builder.make_literal(5, "int16")
282
+ builder.make_literal(6, "int32")
283
+ builder.make_literal(7, "int64")
284
+ builder.make_literal(8.0, "float32")
285
+ builder.make_literal(9.0, "float64")
286
+ builder.make_literal("hello", "string")
287
+ builder.make_literal(b"world", "binary")
288
+
289
+ with pytest.raises(TypeError):
290
+ builder.make_literal("hello", pa.int64())
291
+ with pytest.raises(TypeError):
292
+ builder.make_literal(True, None)
293
+
294
+
295
+ @pytest.mark.gandiva
296
+ def test_regex():
297
+ import pyarrow.gandiva as gandiva
298
+
299
+ elements = ["park", "sparkle", "bright spark and fire", "spark"]
300
+ data = pa.array(elements, type=pa.string())
301
+ table = pa.Table.from_arrays([data], names=['a'])
302
+
303
+ builder = gandiva.TreeExprBuilder()
304
+ node_a = builder.make_field(table.schema.field("a"))
305
+ regex = builder.make_literal("%spark%", pa.string())
306
+ like = builder.make_function("like", [node_a, regex], pa.bool_())
307
+
308
+ field_result = pa.field("b", pa.bool_())
309
+ expr = builder.make_expression(like, field_result)
310
+
311
+ projector = gandiva.make_projector(
312
+ table.schema, [expr], pa.default_memory_pool())
313
+
314
+ r, = projector.evaluate(table.to_batches()[0])
315
+ b = pa.array([False, True, True, True], type=pa.bool_())
316
+ assert r.equals(b)
317
+
318
+
319
+ @pytest.mark.gandiva
320
+ def test_get_registered_function_signatures():
321
+ import pyarrow.gandiva as gandiva
322
+ signatures = gandiva.get_registered_function_signatures()
323
+
324
+ assert type(signatures[0].return_type()) is pa.DataType
325
+ assert type(signatures[0].param_types()) is list
326
+ assert hasattr(signatures[0], "name")
327
+
328
+
329
+ @pytest.mark.gandiva
330
+ def test_filter_project():
331
+ import pyarrow.gandiva as gandiva
332
+ mpool = pa.default_memory_pool()
333
+ # Create a table with some sample data
334
+ array0 = pa.array([10, 12, -20, 5, 21, 29], pa.int32())
335
+ array1 = pa.array([5, 15, 15, 17, 12, 3], pa.int32())
336
+ array2 = pa.array([1, 25, 11, 30, -21, None], pa.int32())
337
+
338
+ table = pa.Table.from_arrays([array0, array1, array2], ['a', 'b', 'c'])
339
+
340
+ field_result = pa.field("res", pa.int32())
341
+
342
+ builder = gandiva.TreeExprBuilder()
343
+ node_a = builder.make_field(table.schema.field("a"))
344
+ node_b = builder.make_field(table.schema.field("b"))
345
+ node_c = builder.make_field(table.schema.field("c"))
346
+
347
+ greater_than_function = builder.make_function("greater_than",
348
+ [node_a, node_b], pa.bool_())
349
+ filter_condition = builder.make_condition(
350
+ greater_than_function)
351
+
352
+ project_condition = builder.make_function("less_than",
353
+ [node_b, node_c], pa.bool_())
354
+ if_node = builder.make_if(project_condition,
355
+ node_b, node_c, pa.int32())
356
+ expr = builder.make_expression(if_node, field_result)
357
+
358
+ # Build a filter for the expressions.
359
+ filter = gandiva.make_filter(table.schema, filter_condition)
360
+
361
+ # Build a projector for the expressions.
362
+ projector = gandiva.make_projector(
363
+ table.schema, [expr], mpool, "UINT32")
364
+
365
+ # Evaluate filter
366
+ selection_vector = filter.evaluate(table.to_batches()[0], mpool)
367
+
368
+ # Evaluate project
369
+ r, = projector.evaluate(
370
+ table.to_batches()[0], selection_vector)
371
+
372
+ exp = pa.array([1, -21, None], pa.int32())
373
+ assert r.equals(exp)
374
+
375
+
376
+ @pytest.mark.gandiva
377
+ def test_to_string():
378
+ import pyarrow.gandiva as gandiva
379
+ builder = gandiva.TreeExprBuilder()
380
+
381
+ assert str(builder.make_literal(2.0, pa.float64())
382
+ ).startswith('(const double) 2 raw(')
383
+ assert str(builder.make_literal(2, pa.int64())) == '(const int64) 2'
384
+ assert str(builder.make_field(pa.field('x', pa.float64()))) == '(double) x'
385
+ assert str(builder.make_field(pa.field('y', pa.string()))) == '(string) y'
386
+
387
+ field_z = builder.make_field(pa.field('z', pa.bool_()))
388
+ func_node = builder.make_function('not', [field_z], pa.bool_())
389
+ assert str(func_node) == 'bool not((bool) z)'
390
+
391
+ field_y = builder.make_field(pa.field('y', pa.bool_()))
392
+ and_node = builder.make_and([func_node, field_y])
393
+ assert str(and_node) == 'bool not((bool) z) && (bool) y'
394
+
395
+
396
+ @pytest.mark.gandiva
397
+ def test_rejects_none():
398
+ import pyarrow.gandiva as gandiva
399
+
400
+ builder = gandiva.TreeExprBuilder()
401
+
402
+ field_x = pa.field('x', pa.int32())
403
+ schema = pa.schema([field_x])
404
+ literal_true = builder.make_literal(True, pa.bool_())
405
+
406
+ with pytest.raises(TypeError):
407
+ builder.make_field(None)
408
+
409
+ with pytest.raises(TypeError):
410
+ builder.make_if(literal_true, None, None, None)
411
+
412
+ with pytest.raises(TypeError):
413
+ builder.make_and([literal_true, None])
414
+
415
+ with pytest.raises(TypeError):
416
+ builder.make_or([None, literal_true])
417
+
418
+ with pytest.raises(TypeError):
419
+ builder.make_in_expression(None, [1, 2, 3], pa.int32())
420
+
421
+ with pytest.raises(TypeError):
422
+ builder.make_expression(None, field_x)
423
+
424
+ with pytest.raises(TypeError):
425
+ builder.make_condition(None)
426
+
427
+ with pytest.raises(TypeError):
428
+ builder.make_function('less_than', [literal_true, None], pa.bool_())
429
+
430
+ with pytest.raises(TypeError):
431
+ gandiva.make_projector(schema, [None])
432
+
433
+ with pytest.raises(TypeError):
434
+ gandiva.make_filter(schema, None)
shared/package-files/00/004ee94fea0838b1b92b372c5e2b12f832662b273d321a2910be2c135afa92f9/blob ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+
3
+ from .core import MaskedTensor
4
+
5
+ __all__ = [
6
+ "as_masked_tensor",
7
+ "masked_tensor",
8
+ ]
9
+
10
+
11
+ """"
12
+ These two factory functions are intended to mirror
13
+ torch.tensor - guaranteed to be a leaf node
14
+ torch.as_tensor - differentiable constructor that preserves the autograd history
15
+ """
16
+
17
+ def masked_tensor(data, mask, requires_grad=False):
18
+ return MaskedTensor(data, mask, requires_grad)
19
+
20
+ def as_masked_tensor(data, mask):
21
+ return MaskedTensor._from_values(data, mask)
shared/package-files/00/00595c205d02a130f617f8f98b500778e149cefc849fb678c30d9ac5d4f40f71/blob ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import networkx as nx
4
+
5
+
6
+ class TestAverageNeighbor:
7
+ def test_degree_p4(self):
8
+ G = nx.path_graph(4)
9
+ answer = {0: 2, 1: 1.5, 2: 1.5, 3: 2}
10
+ nd = nx.average_neighbor_degree(G)
11
+ assert nd == answer
12
+
13
+ D = G.to_directed()
14
+ nd = nx.average_neighbor_degree(D)
15
+ assert nd == answer
16
+
17
+ D = nx.DiGraph(G.edges(data=True))
18
+ nd = nx.average_neighbor_degree(D)
19
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
20
+ nd = nx.average_neighbor_degree(D, "in", "out")
21
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
22
+ nd = nx.average_neighbor_degree(D, "out", "in")
23
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
24
+ nd = nx.average_neighbor_degree(D, "in", "in")
25
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
26
+
27
+ def test_degree_p4_weighted(self):
28
+ G = nx.path_graph(4)
29
+ G[1][2]["weight"] = 4
30
+ answer = {0: 2, 1: 1.8, 2: 1.8, 3: 2}
31
+ nd = nx.average_neighbor_degree(G, weight="weight")
32
+ assert nd == answer
33
+
34
+ D = G.to_directed()
35
+ nd = nx.average_neighbor_degree(D, weight="weight")
36
+ assert nd == answer
37
+
38
+ D = nx.DiGraph(G.edges(data=True))
39
+ print(D.edges(data=True))
40
+ nd = nx.average_neighbor_degree(D, weight="weight")
41
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
42
+ nd = nx.average_neighbor_degree(D, "out", "out", weight="weight")
43
+ assert nd == {0: 1, 1: 1, 2: 0, 3: 0}
44
+ nd = nx.average_neighbor_degree(D, "in", "in", weight="weight")
45
+ assert nd == {0: 0, 1: 0, 2: 1, 3: 1}
46
+ nd = nx.average_neighbor_degree(D, "in", "out", weight="weight")
47
+ assert nd == {0: 0, 1: 1, 2: 1, 3: 1}
48
+ nd = nx.average_neighbor_degree(D, "out", "in", weight="weight")
49
+ assert nd == {0: 1, 1: 1, 2: 1, 3: 0}
50
+
51
+ D = G.to_directed()
52
+ nd = nx.average_neighbor_degree(D, weight="weight")
53
+ assert nd == answer
54
+ nd = nx.average_neighbor_degree(D, source="out", target="out", weight="weight")
55
+ assert nd == answer
56
+
57
+ D = G.to_directed()
58
+ nd = nx.average_neighbor_degree(D, source="in", target="in", weight="weight")
59
+ assert nd == answer
60
+
61
+ def test_degree_k4(self):
62
+ G = nx.complete_graph(4)
63
+ answer = {0: 3, 1: 3, 2: 3, 3: 3}
64
+ nd = nx.average_neighbor_degree(G)
65
+ assert nd == answer
66
+
67
+ D = G.to_directed()
68
+ nd = nx.average_neighbor_degree(D)
69
+ assert nd == answer
70
+
71
+ D = G.to_directed()
72
+ nd = nx.average_neighbor_degree(D)
73
+ assert nd == answer
74
+
75
+ D = G.to_directed()
76
+ nd = nx.average_neighbor_degree(D, source="in", target="in")
77
+ assert nd == answer
78
+
79
+ def test_degree_k4_nodes(self):
80
+ G = nx.complete_graph(4)
81
+ answer = {1: 3.0, 2: 3.0}
82
+ nd = nx.average_neighbor_degree(G, nodes=[1, 2])
83
+ assert nd == answer
84
+
85
+ def test_degree_barrat(self):
86
+ G = nx.star_graph(5)
87
+ G.add_edges_from([(5, 6), (5, 7), (5, 8), (5, 9)])
88
+ G[0][5]["weight"] = 5
89
+ nd = nx.average_neighbor_degree(G)[5]
90
+ assert nd == 1.8
91
+ nd = nx.average_neighbor_degree(G, weight="weight")[5]
92
+ assert nd == pytest.approx(3.222222, abs=1e-5)
93
+
94
+ def test_error_invalid_source_target(self):
95
+ G = nx.path_graph(4)
96
+ with pytest.raises(nx.NetworkXError):
97
+ nx.average_neighbor_degree(G, "error")
98
+ with pytest.raises(nx.NetworkXError):
99
+ nx.average_neighbor_degree(G, "in", "error")
100
+ G = G.to_directed()
101
+ with pytest.raises(nx.NetworkXError):
102
+ nx.average_neighbor_degree(G, "error")
103
+ with pytest.raises(nx.NetworkXError):
104
+ nx.average_neighbor_degree(G, "in", "error")
shared/package-files/00/00599b73d4a67e0a505743c3f61097ba4b5109190dbc31794b567bcf7d44db11/blob ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas import (
4
+ DataFrame,
5
+ date_range,
6
+ )
7
+ import pandas._testing as tm
8
+
9
+
10
+ class TestEquals:
11
+ def test_dataframe_not_equal(self):
12
+ # see GH#28839
13
+ df1 = DataFrame({"a": [1, 2], "b": ["s", "d"]})
14
+ df2 = DataFrame({"a": ["s", "d"], "b": [1, 2]})
15
+ assert df1.equals(df2) is False
16
+
17
+ def test_equals_different_blocks(self, using_array_manager, using_infer_string):
18
+ # GH#9330
19
+ df0 = DataFrame({"A": ["x", "y"], "B": [1, 2], "C": ["w", "z"]})
20
+ df1 = df0.reset_index()[["A", "B", "C"]]
21
+ if not using_array_manager and not using_infer_string:
22
+ # this assert verifies that the above operations have
23
+ # induced a block rearrangement
24
+ assert df0._mgr.blocks[0].dtype != df1._mgr.blocks[0].dtype
25
+
26
+ # do the real tests
27
+ tm.assert_frame_equal(df0, df1)
28
+ assert df0.equals(df1)
29
+ assert df1.equals(df0)
30
+
31
+ def test_equals(self):
32
+ # Add object dtype column with nans
33
+ index = np.random.default_rng(2).random(10)
34
+ df1 = DataFrame(
35
+ np.random.default_rng(2).random(10), index=index, columns=["floats"]
36
+ )
37
+ df1["text"] = "the sky is so blue. we could use more chocolate.".split()
38
+ df1["start"] = date_range("2000-1-1", periods=10, freq="min")
39
+ df1["end"] = date_range("2000-1-1", periods=10, freq="D")
40
+ df1["diff"] = df1["end"] - df1["start"]
41
+ # Explicitly cast to object, to avoid implicit cast when setting np.nan
42
+ df1["bool"] = (np.arange(10) % 3 == 0).astype(object)
43
+ df1.loc[::2] = np.nan
44
+ df2 = df1.copy()
45
+ assert df1["text"].equals(df2["text"])
46
+ assert df1["start"].equals(df2["start"])
47
+ assert df1["end"].equals(df2["end"])
48
+ assert df1["diff"].equals(df2["diff"])
49
+ assert df1["bool"].equals(df2["bool"])
50
+ assert df1.equals(df2)
51
+ assert not df1.equals(object)
52
+
53
+ # different dtype
54
+ different = df1.copy()
55
+ different["floats"] = different["floats"].astype("float32")
56
+ assert not df1.equals(different)
57
+
58
+ # different index
59
+ different_index = -index
60
+ different = df2.set_index(different_index)
61
+ assert not df1.equals(different)
62
+
63
+ # different columns
64
+ different = df2.copy()
65
+ different.columns = df2.columns[::-1]
66
+ assert not df1.equals(different)
67
+
68
+ # DatetimeIndex
69
+ index = date_range("2000-1-1", periods=10, freq="min")
70
+ df1 = df1.set_index(index)
71
+ df2 = df1.copy()
72
+ assert df1.equals(df2)
73
+
74
+ # MultiIndex
75
+ df3 = df1.set_index(["text"], append=True)
76
+ df2 = df1.set_index(["text"], append=True)
77
+ assert df3.equals(df2)
78
+
79
+ df2 = df1.set_index(["floats"], append=True)
80
+ assert not df3.equals(df2)
81
+
82
+ # NaN in index
83
+ df3 = df1.set_index(["floats"], append=True)
84
+ df2 = df1.set_index(["floats"], append=True)
85
+ assert df3.equals(df2)
shared/package-files/00/0060dbf4b6a0e180e9e33d2c0120e7f9ac20fa61d3882e7349a21958775ec7f8/blob ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 relu6(const at::Tensor & self);
20
+ TORCH_API at::Tensor & relu6_(at::Tensor & self);
21
+ } // namespace native
22
+ } // namespace at
shared/package-files/00/0063fed96e58e85fa8878f6acdd4a75b947f82e6018d06d17411858b1bea968e/blob ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API scatter_reduce_two {
18
+ using schema = at::Tensor (const at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::scatter_reduce")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "two")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "scatter_reduce.two(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self);
26
+ };
27
+
28
+ struct TORCH_API scatter_reduce__two {
29
+ using schema = at::Tensor & (at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, bool);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::scatter_reduce_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "two")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "scatter_reduce_.two(Tensor(a!) self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True) -> Tensor(a!)")
35
+ static at::Tensor & call(at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self);
37
+ };
38
+
39
+ struct TORCH_API scatter_reduce_two_out {
40
+ using schema = at::Tensor & (const at::Tensor &, int64_t, const at::Tensor &, const at::Tensor &, c10::string_view, bool, at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::scatter_reduce")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "two_out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "scatter_reduce.two_out(Tensor self, int dim, Tensor index, Tensor src, str reduce, *, bool include_self=True, Tensor(a!) out) -> Tensor(a!)")
46
+ static at::Tensor & call(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self, at::Tensor & out);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self, at::Tensor & out);
48
+ };
49
+
50
+ }} // namespace at::_ops
shared/package-files/00/006942ebd5efa62509d8a788b3de96a2880017919d405bf8f1cd41527391e2d9/blob ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The k-nearest neighbors algorithms."""
2
+
3
+ # Authors: The scikit-learn developers
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+
6
+ from ._ball_tree import BallTree
7
+ from ._base import VALID_METRICS, VALID_METRICS_SPARSE, sort_graph_by_row_values
8
+ from ._classification import KNeighborsClassifier, RadiusNeighborsClassifier
9
+ from ._graph import (
10
+ KNeighborsTransformer,
11
+ RadiusNeighborsTransformer,
12
+ kneighbors_graph,
13
+ radius_neighbors_graph,
14
+ )
15
+ from ._kd_tree import KDTree
16
+ from ._kde import KernelDensity
17
+ from ._lof import LocalOutlierFactor
18
+ from ._nca import NeighborhoodComponentsAnalysis
19
+ from ._nearest_centroid import NearestCentroid
20
+ from ._regression import KNeighborsRegressor, RadiusNeighborsRegressor
21
+ from ._unsupervised import NearestNeighbors
22
+
23
+ __all__ = [
24
+ "VALID_METRICS",
25
+ "VALID_METRICS_SPARSE",
26
+ "BallTree",
27
+ "KDTree",
28
+ "KNeighborsClassifier",
29
+ "KNeighborsRegressor",
30
+ "KNeighborsTransformer",
31
+ "KernelDensity",
32
+ "LocalOutlierFactor",
33
+ "NearestCentroid",
34
+ "NearestNeighbors",
35
+ "NeighborhoodComponentsAnalysis",
36
+ "RadiusNeighborsClassifier",
37
+ "RadiusNeighborsRegressor",
38
+ "RadiusNeighborsTransformer",
39
+ "kneighbors_graph",
40
+ "radius_neighbors_graph",
41
+ "sort_graph_by_row_values",
42
+ ]
shared/package-files/00/006d3a694562d4bb7fdc50f26e67a97d55937270221dff7328a0803d0b011074/blob ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import operator
3
+ import traceback
4
+ from functools import partial
5
+ from typing import Callable, Dict, List, NamedTuple, Set
6
+
7
+ import sympy
8
+
9
+ import torch
10
+ import torch.fx
11
+ from torch._export.pass_base import _ExportPassBaseDeprecatedDoNotUse, ProxyValue, PassResult
12
+ from torch.utils._sympy.value_ranges import ValueRanges
13
+ from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
14
+
15
+
16
+ __all__ = ["InputDim"]
17
+
18
+
19
+ class InputDim(NamedTuple):
20
+ input_name: str
21
+ dim: int
22
+
23
+
24
+ def _convert_to_int(val):
25
+ # Convert simple sympy Integers into concrete int
26
+ if val == sympy.oo:
27
+ return math.inf
28
+ if val == -sympy.oo:
29
+ return -math.inf
30
+ if isinstance(val, sympy.Integer):
31
+ return int(val)
32
+ raise RuntimeError(
33
+ "Export constraints cannot be non-integer expressions"
34
+ )
35
+
36
+
37
+ def _convert_range_to_int(range: ValueRanges):
38
+ assert isinstance(range, ValueRanges)
39
+ min_val = _convert_to_int(range.lower)
40
+ max_val = _convert_to_int(range.upper)
41
+ return min_val, max_val
42
+
43
+
44
+ class _AddRuntimeAssertionsForInlineConstraintsPass(_ExportPassBaseDeprecatedDoNotUse):
45
+ def __init__(
46
+ self,
47
+ range_constraints: Dict[sympy.Symbol, ValueRanges],
48
+ ):
49
+ super().__init__()
50
+ self.range_constraints: Dict[sympy.Symbol, ValueRanges] = range_constraints
51
+ self._asserts_generated_unbacked_symbols: Set[sympy.Symbol] = set()
52
+ self.counter = 0
53
+
54
+ def _assert_range_constraint(self, proxy, lower, upper, assert_msg):
55
+ if lower > -math.inf:
56
+ self._insert_assert_async(operator.ge, proxy, lower, assert_msg)
57
+
58
+ if upper < math.inf:
59
+ self._insert_assert_async(operator.le, proxy, upper, assert_msg)
60
+
61
+ def _insert_assert_async(self, operator, lower, upper, assert_msg):
62
+ """
63
+ Inserts assert_async call_function nodes in the graph. This function is
64
+ called **during** the interpreter-based pass.
65
+ """
66
+ self.counter += 1
67
+ cmp = super().call_operator(operator, (lower, upper), {}, self._create_dummy_node_metadata())
68
+ cmp_tensor = super().call_operator(torch.ops.aten.scalar_tensor.default, (cmp,), {}, self._create_dummy_node_metadata())
69
+ super().call_operator(
70
+ torch.ops.aten._assert_async.msg,
71
+ (cmp_tensor, assert_msg),
72
+ {},
73
+ self._create_dummy_node_metadata(),
74
+ )
75
+
76
+ def call_operator(self, op, args, kwargs, meta) -> ProxyValue:
77
+ ret = super().call_operator(op, args, kwargs, meta)
78
+ if "val" not in meta:
79
+ return ret
80
+
81
+ val = meta["val"]
82
+
83
+ # In general, we may have to deal the case such as: ret[1].shape[0].
84
+ # We need first find out what symbols require assertion, then we need to follow the path
85
+ # from ret to the symbol, construct the proxies along the way and construct the messages
86
+ # piece-wise at the same time.
87
+ #
88
+ # We use post-order traversal to collect all the proxies callbacks needed, construct
89
+ # the error message callbacks, and at the top-level traversal tree we execute all the callbacks.
90
+ # We need the callbacks because, in order to call the function to create a proxy for shape[0], we
91
+ # need the proxy for shape, which further requires the proxy for ret[1], etc.
92
+ def add_assertions(val):
93
+ call_backs: List[Callable] = []
94
+ messages: List[str] = []
95
+ if isinstance(val, (torch.SymInt, torch.SymFloat, torch.SymBool)):
96
+ symbol = val.node.expr
97
+ if symbol in self.existing_inline_assertions:
98
+ return call_backs, messages
99
+ if isinstance(symbol, sympy.Symbol) and free_unbacked_symbols(symbol):
100
+ if symbol in self._asserts_generated_unbacked_symbols:
101
+ return call_backs, messages
102
+ # We only care about unbacked symints for these inline
103
+ # constraints, which are prefixed with 'u'
104
+ constraint = self.range_constraints[symbol]
105
+ min_val, max_val = _convert_range_to_int(constraint)
106
+ assert_msg = f" is outside of inline constraint [{min_val}, {max_val}]."
107
+ call_backs.append(
108
+ partial(self._assert_range_constraint, lower=min_val, upper=max_val)
109
+ )
110
+ messages.append(assert_msg)
111
+ self._asserts_generated_unbacked_symbols.add(symbol)
112
+
113
+ elif isinstance(val, torch.Tensor):
114
+ for i, sym in enumerate(val.shape):
115
+ cbs, msgs = add_assertions(sym)
116
+ for cb, msg in zip(cbs, msgs):
117
+ def sym_size_cb(proxy, assert_msg, dim):
118
+ dim_proxy = super(
119
+ _AddRuntimeAssertionsForInlineConstraintsPass,
120
+ self
121
+ ).call_operator(
122
+ torch.ops.aten.sym_size.int,
123
+ (proxy, dim),
124
+ {},
125
+ self._create_dummy_node_metadata(),
126
+ )
127
+ cb(proxy=dim_proxy, assert_msg=assert_msg)
128
+ call_backs.append(partial(sym_size_cb, dim=i))
129
+ messages.append(f".shape[{i}]" + msg)
130
+ return call_backs, messages
131
+
132
+ callbacks, messages = add_assertions(val)
133
+ for cb, msg in zip(callbacks, messages):
134
+ cb(proxy=ret, assert_msg=f"{ret.node}" + msg)
135
+ return ret
136
+
137
+ def call(self, graph_module):
138
+ self.existing_inline_assertions = _get_existing_inline_assertions(
139
+ graph_module, self.range_constraints
140
+ )
141
+
142
+ # Add runtime asserts for inline constraints
143
+ val = super().call(graph_module)
144
+
145
+ # Sometimes this pass would return a wrong graph where we have mismatched
146
+ # node names in signature. Before we fix it, let's just skip it.
147
+ if self.counter == 0 and type(self) is _AddRuntimeAssertionsForInlineConstraintsPass:
148
+ return PassResult(graph_module, False)
149
+
150
+ # Populate the stack trace with dummy vals to respect IR
151
+ for node in val.graph_module.graph.nodes:
152
+ if not node.meta.get("stack_trace", None):
153
+ node.meta["stack_trace"] = "".join(traceback.format_stack(limit=1))
154
+
155
+ return PassResult(val.graph_module, val.modified)
156
+
157
+
158
+ def _get_existing_inline_assertions(
159
+ graph_module: torch.fx.GraphModule,
160
+ range_constraints: Dict[sympy.Symbol, ValueRanges],
161
+ ) -> Dict[sympy.Symbol, ValueRanges]:
162
+ existing_inline_assertions: Dict[sympy.Symbol, ValueRanges] = {}
163
+
164
+ for module in graph_module.modules():
165
+ if not isinstance(module, torch.fx.GraphModule):
166
+ continue
167
+
168
+ # Find all the existing inline assertions. They will look something like:
169
+ # %_local_scalar_dense = call_function[target=torch.ops.aten._local_scalar_dense.default](args = (%arg1_1,), kwargs = {})
170
+ # %ge = call_function[target=operator.ge](args = (%_local_scalar_dense, 0), kwargs = {})
171
+ # %scalar_tensor = call_function[target=torch.ops.aten.scalar_tensor.default](args = (%ge,), kwargs = {})
172
+ # %_assert_async = call_function[target=torch.ops.aten._assert_async.msg](args = (%scalar_tensor, "..."), kwargs = {})
173
+ for node in module.graph.nodes:
174
+ if node.target != torch.ops.aten._assert_async.msg:
175
+ continue
176
+
177
+ scalar_tensor_arg = node.args[0]
178
+ if not (
179
+ scalar_tensor_arg.op == "call_function" and
180
+ scalar_tensor_arg.target == torch.ops.aten.scalar_tensor.default
181
+ ):
182
+ continue
183
+
184
+ compare_arg = scalar_tensor_arg.args[0]
185
+ if not (
186
+ compare_arg.op == "call_function" and
187
+ compare_arg.target in (operator.le, operator.ge) and
188
+ len(compare_arg.args) == 2
189
+ ):
190
+ continue
191
+
192
+ compare_op = compare_arg.target
193
+ maybe_symint_arg, compare_int = compare_arg.args
194
+
195
+ # x >= 0 will sometimes be canonicalized to -x <= 0, so in some
196
+ # cases the operation before the comparison is to multiply by -1. We
197
+ # can undo the canonicalization here
198
+ if (
199
+ maybe_symint_arg.op == "call_function" and
200
+ maybe_symint_arg.target == operator.mul and
201
+ maybe_symint_arg.args[0] == -1
202
+ ):
203
+ maybe_symint_arg = maybe_symint_arg.args[1]
204
+ compare_op = operator.ge
205
+ compare_int = -1 * compare_int
206
+
207
+ if not (
208
+ "val" in maybe_symint_arg.meta and
209
+ isinstance(maybe_symint_arg.meta["val"], torch.SymInt)
210
+ ):
211
+ continue
212
+
213
+ symint = maybe_symint_arg.meta["val"].node.expr
214
+ if not isinstance(symint, sympy.Symbol):
215
+ continue
216
+
217
+ if symint not in range_constraints:
218
+ raise RuntimeError(f"Unable to find symint {symint} in {range_constraints}")
219
+
220
+ found_range = existing_inline_assertions.get(symint, ValueRanges(-math.inf, math.inf))
221
+
222
+ if compare_arg.target == operator.le:
223
+ existing_inline_assertions[symint] = ValueRanges(
224
+ lower=found_range.lower, upper=compare_int
225
+ )
226
+ elif compare_arg.target == operator.ge:
227
+ existing_inline_assertions[symint] = ValueRanges(
228
+ lower=compare_int, upper=found_range.upper
229
+ )
230
+
231
+ return existing_inline_assertions
shared/package-files/00/006e4ddaad8ae86e219508336081d540eb437d60b514d215f76a64ba973b1b73/blob ADDED
@@ -0,0 +1,974 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ # Copyright (c) 2013, Mahmoud Hashemi
4
+ #
5
+ # Redistribution and use in source and binary forms, with or without
6
+ # modification, are permitted provided that the following conditions are
7
+ # met:
8
+ #
9
+ # * Redistributions of source code must retain the above copyright
10
+ # notice, this list of conditions and the following disclaimer.
11
+ #
12
+ # * Redistributions in binary form must reproduce the above
13
+ # copyright notice, this list of conditions and the following
14
+ # disclaimer in the documentation and/or other materials provided
15
+ # with the distribution.
16
+ #
17
+ # * The names of the contributors may not be used to endorse or
18
+ # promote products derived from this software without specific
19
+ # prior written permission.
20
+ #
21
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24
+ # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25
+ # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
+ # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
+ # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28
+ # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29
+ # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30
+ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
+
33
+ """\
34
+
35
+ The :class:`set` type brings the practical expressiveness of
36
+ set theory to Python. It has a very rich API overall, but lacks a
37
+ couple of fundamental features. For one, sets are not ordered. On top
38
+ of this, sets are not indexable, i.e, ``my_set[8]`` will raise an
39
+ :exc:`TypeError`. The :class:`IndexedSet` type remedies both of these
40
+ issues without compromising on the excellent complexity
41
+ characteristics of Python's built-in set implementation.
42
+ """
43
+
44
+ from __future__ import print_function
45
+
46
+ from bisect import bisect_left
47
+ from itertools import chain, islice
48
+ import operator
49
+
50
+ try:
51
+ from collections.abc import MutableSet
52
+ except ImportError:
53
+ from collections import MutableSet
54
+
55
+ try:
56
+ from typeutils import make_sentinel
57
+ _MISSING = make_sentinel(var_name='_MISSING')
58
+ except ImportError:
59
+ _MISSING = object()
60
+
61
+
62
+ __all__ = ['IndexedSet', 'complement']
63
+
64
+
65
+ _COMPACTION_FACTOR = 8
66
+
67
+ # TODO: inherit from set()
68
+ # TODO: .discard_many(), .remove_many()
69
+ # TODO: raise exception on non-set params?
70
+ # TODO: technically reverse operators should probably reverse the
71
+ # order of the 'other' inputs and put self last (to try and maintain
72
+ # insertion order)
73
+
74
+
75
+ class IndexedSet(MutableSet):
76
+ """``IndexedSet`` is a :class:`collections.MutableSet` that maintains
77
+ insertion order and uniqueness of inserted elements. It's a hybrid
78
+ type, mostly like an OrderedSet, but also :class:`list`-like, in
79
+ that it supports indexing and slicing.
80
+
81
+ Args:
82
+ other (iterable): An optional iterable used to initialize the set.
83
+
84
+ >>> x = IndexedSet(list(range(4)) + list(range(8)))
85
+ >>> x
86
+ IndexedSet([0, 1, 2, 3, 4, 5, 6, 7])
87
+ >>> x - set(range(2))
88
+ IndexedSet([2, 3, 4, 5, 6, 7])
89
+ >>> x[-1]
90
+ 7
91
+ >>> fcr = IndexedSet('freecreditreport.com')
92
+ >>> ''.join(fcr[:fcr.index('.')])
93
+ 'frecditpo'
94
+
95
+ Standard set operators and interoperation with :class:`set` are
96
+ all supported:
97
+
98
+ >>> fcr & set('cash4gold.com')
99
+ IndexedSet(['c', 'd', 'o', '.', 'm'])
100
+
101
+ As you can see, the ``IndexedSet`` is almost like a ``UniqueList``,
102
+ retaining only one copy of a given value, in the order it was
103
+ first added. For the curious, the reason why IndexedSet does not
104
+ support setting items based on index (i.e, ``__setitem__()``),
105
+ consider the following dilemma::
106
+
107
+ my_indexed_set = [A, B, C, D]
108
+ my_indexed_set[2] = A
109
+
110
+ At this point, a set requires only one *A*, but a :class:`list` would
111
+ overwrite *C*. Overwriting *C* would change the length of the list,
112
+ meaning that ``my_indexed_set[2]`` would not be *A*, as expected with a
113
+ list, but rather *D*. So, no ``__setitem__()``.
114
+
115
+ Otherwise, the API strives to be as complete a union of the
116
+ :class:`list` and :class:`set` APIs as possible.
117
+ """
118
+ def __init__(self, other=None):
119
+ self.item_index_map = dict()
120
+ self.item_list = []
121
+ self.dead_indices = []
122
+ self._compactions = 0
123
+ self._c_max_size = 0
124
+ if other:
125
+ self.update(other)
126
+
127
+ # internal functions
128
+ @property
129
+ def _dead_index_count(self):
130
+ return len(self.item_list) - len(self.item_index_map)
131
+
132
+ def _compact(self):
133
+ if not self.dead_indices:
134
+ return
135
+ self._compactions += 1
136
+ dead_index_count = self._dead_index_count
137
+ items, index_map = self.item_list, self.item_index_map
138
+ self._c_max_size = max(self._c_max_size, len(items))
139
+ for i, item in enumerate(self):
140
+ items[i] = item
141
+ index_map[item] = i
142
+ del items[-dead_index_count:]
143
+ del self.dead_indices[:]
144
+
145
+ def _cull(self):
146
+ ded = self.dead_indices
147
+ if not ded:
148
+ return
149
+ items, ii_map = self.item_list, self.item_index_map
150
+ if not ii_map:
151
+ del items[:]
152
+ del ded[:]
153
+ elif len(ded) > 384:
154
+ self._compact()
155
+ elif self._dead_index_count > (len(items) / _COMPACTION_FACTOR):
156
+ self._compact()
157
+ elif items[-1] is _MISSING: # get rid of dead right hand side
158
+ num_dead = 1
159
+ while items[-(num_dead + 1)] is _MISSING:
160
+ num_dead += 1
161
+ if ded and ded[-1][1] == len(items):
162
+ del ded[-1]
163
+ del items[-num_dead:]
164
+
165
+ def _get_real_index(self, index):
166
+ if index < 0:
167
+ index += len(self)
168
+ if not self.dead_indices:
169
+ return index
170
+ real_index = index
171
+ for d_start, d_stop in self.dead_indices:
172
+ if real_index < d_start:
173
+ break
174
+ real_index += d_stop - d_start
175
+ return real_index
176
+
177
+ def _get_apparent_index(self, index):
178
+ if index < 0:
179
+ index += len(self)
180
+ if not self.dead_indices:
181
+ return index
182
+ apparent_index = index
183
+ for d_start, d_stop in self.dead_indices:
184
+ if index < d_start:
185
+ break
186
+ apparent_index -= d_stop - d_start
187
+ return apparent_index
188
+
189
+ def _add_dead(self, start, stop=None):
190
+ # TODO: does not handle when the new interval subsumes
191
+ # multiple existing intervals
192
+ dints = self.dead_indices
193
+ if stop is None:
194
+ stop = start + 1
195
+ cand_int = [start, stop]
196
+ if not dints:
197
+ dints.append(cand_int)
198
+ return
199
+ int_idx = bisect_left(dints, cand_int)
200
+ dint = dints[int_idx - 1]
201
+ d_start, d_stop = dint
202
+ if start <= d_start <= stop:
203
+ dint[0] = start
204
+ elif start <= d_stop <= stop:
205
+ dint[1] = stop
206
+ else:
207
+ dints.insert(int_idx, cand_int)
208
+ return
209
+
210
+ # common operations (shared by set and list)
211
+ def __len__(self):
212
+ return len(self.item_index_map)
213
+
214
+ def __contains__(self, item):
215
+ return item in self.item_index_map
216
+
217
+ def __iter__(self):
218
+ return (item for item in self.item_list if item is not _MISSING)
219
+
220
+ def __reversed__(self):
221
+ item_list = self.item_list
222
+ return (item for item in reversed(item_list) if item is not _MISSING)
223
+
224
+ def __repr__(self):
225
+ return '%s(%r)' % (self.__class__.__name__, list(self))
226
+
227
+ def __eq__(self, other):
228
+ if isinstance(other, IndexedSet):
229
+ return len(self) == len(other) and list(self) == list(other)
230
+ return set(self) == set(other)
231
+
232
+ @classmethod
233
+ def from_iterable(cls, it):
234
+ "from_iterable(it) -> create a set from an iterable"
235
+ return cls(it)
236
+
237
+ # set operations
238
+ def add(self, item):
239
+ "add(item) -> add item to the set"
240
+ if item not in self.item_index_map:
241
+ self.item_index_map[item] = len(self.item_list)
242
+ self.item_list.append(item)
243
+
244
+ def remove(self, item):
245
+ "remove(item) -> remove item from the set, raises if not present"
246
+ try:
247
+ didx = self.item_index_map.pop(item)
248
+ except KeyError:
249
+ raise KeyError(item)
250
+ self.item_list[didx] = _MISSING
251
+ self._add_dead(didx)
252
+ self._cull()
253
+
254
+ def discard(self, item):
255
+ "discard(item) -> discard item from the set (does not raise)"
256
+ try:
257
+ self.remove(item)
258
+ except KeyError:
259
+ pass
260
+
261
+ def clear(self):
262
+ "clear() -> empty the set"
263
+ del self.item_list[:]
264
+ del self.dead_indices[:]
265
+ self.item_index_map.clear()
266
+
267
+ def isdisjoint(self, other):
268
+ "isdisjoint(other) -> return True if no overlap with other"
269
+ iim = self.item_index_map
270
+ for k in other:
271
+ if k in iim:
272
+ return False
273
+ return True
274
+
275
+ def issubset(self, other):
276
+ "issubset(other) -> return True if other contains this set"
277
+ if len(other) < len(self):
278
+ return False
279
+ for k in self.item_index_map:
280
+ if k not in other:
281
+ return False
282
+ return True
283
+
284
+ def issuperset(self, other):
285
+ "issuperset(other) -> return True if set contains other"
286
+ if len(other) > len(self):
287
+ return False
288
+ iim = self.item_index_map
289
+ for k in other:
290
+ if k not in iim:
291
+ return False
292
+ return True
293
+
294
+ def union(self, *others):
295
+ "union(*others) -> return a new set containing this set and others"
296
+ return self.from_iterable(chain(self, *others))
297
+
298
+ def iter_intersection(self, *others):
299
+ "iter_intersection(*others) -> iterate over elements also in others"
300
+ for k in self:
301
+ for other in others:
302
+ if k not in other:
303
+ break
304
+ else:
305
+ yield k
306
+ return
307
+
308
+ def intersection(self, *others):
309
+ "intersection(*others) -> get a set with overlap of this and others"
310
+ if len(others) == 1:
311
+ other = others[0]
312
+ return self.from_iterable(k for k in self if k in other)
313
+ return self.from_iterable(self.iter_intersection(*others))
314
+
315
+ def iter_difference(self, *others):
316
+ "iter_difference(*others) -> iterate over elements not in others"
317
+ for k in self:
318
+ for other in others:
319
+ if k in other:
320
+ break
321
+ else:
322
+ yield k
323
+ return
324
+
325
+ def difference(self, *others):
326
+ "difference(*others) -> get a new set with elements not in others"
327
+ if len(others) == 1:
328
+ other = others[0]
329
+ return self.from_iterable(k for k in self if k not in other)
330
+ return self.from_iterable(self.iter_difference(*others))
331
+
332
+ def symmetric_difference(self, *others):
333
+ "symmetric_difference(*others) -> XOR set of this and others"
334
+ ret = self.union(*others)
335
+ return ret.difference(self.intersection(*others))
336
+
337
+ __or__ = __ror__ = union
338
+ __and__ = __rand__ = intersection
339
+ __sub__ = difference
340
+ __xor__ = __rxor__ = symmetric_difference
341
+
342
+ def __rsub__(self, other):
343
+ vals = [x for x in other if x not in self]
344
+ return type(other)(vals)
345
+
346
+ # in-place set operations
347
+ def update(self, *others):
348
+ "update(*others) -> add values from one or more iterables"
349
+ if not others:
350
+ return # raise?
351
+ elif len(others) == 1:
352
+ other = others[0]
353
+ else:
354
+ other = chain(others)
355
+ for o in other:
356
+ self.add(o)
357
+
358
+ def intersection_update(self, *others):
359
+ "intersection_update(*others) -> discard self.difference(*others)"
360
+ for val in self.difference(*others):
361
+ self.discard(val)
362
+
363
+ def difference_update(self, *others):
364
+ "difference_update(*others) -> discard self.intersection(*others)"
365
+ if self in others:
366
+ self.clear()
367
+ for val in self.intersection(*others):
368
+ self.discard(val)
369
+
370
+ def symmetric_difference_update(self, other): # note singular 'other'
371
+ "symmetric_difference_update(other) -> in-place XOR with other"
372
+ if self is other:
373
+ self.clear()
374
+ for val in other:
375
+ if val in self:
376
+ self.discard(val)
377
+ else:
378
+ self.add(val)
379
+
380
+ def __ior__(self, *others):
381
+ self.update(*others)
382
+ return self
383
+
384
+ def __iand__(self, *others):
385
+ self.intersection_update(*others)
386
+ return self
387
+
388
+ def __isub__(self, *others):
389
+ self.difference_update(*others)
390
+ return self
391
+
392
+ def __ixor__(self, *others):
393
+ self.symmetric_difference_update(*others)
394
+ return self
395
+
396
+ def iter_slice(self, start, stop, step=None):
397
+ "iterate over a slice of the set"
398
+ iterable = self
399
+ if start is not None:
400
+ start = self._get_real_index(start)
401
+ if stop is not None:
402
+ stop = self._get_real_index(stop)
403
+ if step is not None and step < 0:
404
+ step = -step
405
+ iterable = reversed(self)
406
+ return islice(iterable, start, stop, step)
407
+
408
+ # list operations
409
+ def __getitem__(self, index):
410
+ try:
411
+ start, stop, step = index.start, index.stop, index.step
412
+ except AttributeError:
413
+ index = operator.index(index)
414
+ else:
415
+ iter_slice = self.iter_slice(start, stop, step)
416
+ return self.from_iterable(iter_slice)
417
+ if index < 0:
418
+ index += len(self)
419
+ real_index = self._get_real_index(index)
420
+ try:
421
+ ret = self.item_list[real_index]
422
+ except IndexError:
423
+ raise IndexError('IndexedSet index out of range')
424
+ return ret
425
+
426
+ def pop(self, index=None):
427
+ "pop(index) -> remove the item at a given index (-1 by default)"
428
+ item_index_map = self.item_index_map
429
+ len_self = len(item_index_map)
430
+ if index is None or index == -1 or index == len_self - 1:
431
+ ret = self.item_list.pop()
432
+ del item_index_map[ret]
433
+ else:
434
+ real_index = self._get_real_index(index)
435
+ ret = self.item_list[real_index]
436
+ self.item_list[real_index] = _MISSING
437
+ del item_index_map[ret]
438
+ self._add_dead(real_index)
439
+ self._cull()
440
+ return ret
441
+
442
+ def count(self, val):
443
+ "count(val) -> count number of instances of value (0 or 1)"
444
+ if val in self.item_index_map:
445
+ return 1
446
+ return 0
447
+
448
+ def reverse(self):
449
+ "reverse() -> reverse the contents of the set in-place"
450
+ reversed_list = list(reversed(self))
451
+ self.item_list[:] = reversed_list
452
+ for i, item in enumerate(self.item_list):
453
+ self.item_index_map[item] = i
454
+ del self.dead_indices[:]
455
+
456
+ def sort(self, **kwargs):
457
+ "sort() -> sort the contents of the set in-place"
458
+ sorted_list = sorted(self, **kwargs)
459
+ if sorted_list == self.item_list:
460
+ return
461
+ self.item_list[:] = sorted_list
462
+ for i, item in enumerate(self.item_list):
463
+ self.item_index_map[item] = i
464
+ del self.dead_indices[:]
465
+
466
+ def index(self, val):
467
+ "index(val) -> get the index of a value, raises if not present"
468
+ try:
469
+ return self._get_apparent_index(self.item_index_map[val])
470
+ except KeyError:
471
+ cn = self.__class__.__name__
472
+ raise ValueError('%r is not in %s' % (val, cn))
473
+
474
+
475
+ def complement(wrapped):
476
+ """Given a :class:`set`, convert it to a **complement set**.
477
+
478
+ Whereas a :class:`set` keeps track of what it contains, a
479
+ `complement set
480
+ <https://en.wikipedia.org/wiki/Complement_(set_theory)>`_ keeps
481
+ track of what it does *not* contain. For example, look what
482
+ happens when we intersect a normal set with a complement set::
483
+
484
+ >>> list(set(range(5)) & complement(set([2, 3])))
485
+ [0, 1, 4]
486
+
487
+ We get the everything in the left that wasn't in the right,
488
+ because intersecting with a complement is the same as subtracting
489
+ a normal set.
490
+
491
+ Args:
492
+ wrapped (set): A set or any other iterable which should be
493
+ turned into a complement set.
494
+
495
+ All set methods and operators are supported by complement sets,
496
+ between other :func:`complement`-wrapped sets and/or regular
497
+ :class:`set` objects.
498
+
499
+ Because a complement set only tracks what elements are *not* in
500
+ the set, functionality based on set contents is unavailable:
501
+ :func:`len`, :func:`iter` (and for loops), and ``.pop()``. But a
502
+ complement set can always be turned back into a regular set by
503
+ complementing it again:
504
+
505
+ >>> s = set(range(5))
506
+ >>> complement(complement(s)) == s
507
+ True
508
+
509
+ .. note::
510
+
511
+ An empty complement set corresponds to the concept of a
512
+ `universal set <https://en.wikipedia.org/wiki/Universal_set>`_
513
+ from mathematics.
514
+
515
+ Complement sets by example
516
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
517
+
518
+ Many uses of sets can be expressed more simply by using a
519
+ complement. Rather than trying to work out in your head the proper
520
+ way to invert an expression, you can just throw a complement on
521
+ the set. Consider this example of a name filter::
522
+
523
+ >>> class NamesFilter(object):
524
+ ... def __init__(self, allowed):
525
+ ... self._allowed = allowed
526
+ ...
527
+ ... def filter(self, names):
528
+ ... return [name for name in names if name in self._allowed]
529
+ >>> NamesFilter(set(['alice', 'bob'])).filter(['alice', 'bob', 'carol'])
530
+ ['alice', 'bob']
531
+
532
+ What if we want to just express "let all the names through"?
533
+
534
+ We could try to enumerate all of the expected names::
535
+
536
+ ``NamesFilter({'alice', 'bob', 'carol'})``
537
+
538
+ But this is very brittle -- what if at some point over this
539
+ object is changed to filter ``['alice', 'bob', 'carol', 'dan']``?
540
+
541
+ Even worse, what about the poor programmer who next works
542
+ on this piece of code? They cannot tell whether the purpose
543
+ of the large allowed set was "allow everything", or if 'dan'
544
+ was excluded for some subtle reason.
545
+
546
+ A complement set lets the programmer intention be expressed
547
+ succinctly and directly::
548
+
549
+ NamesFilter(complement(set()))
550
+
551
+ Not only is this code short and robust, it is easy to understand
552
+ the intention.
553
+
554
+ """
555
+ if type(wrapped) is _ComplementSet:
556
+ return wrapped.complemented()
557
+ if type(wrapped) is frozenset:
558
+ return _ComplementSet(excluded=wrapped)
559
+ return _ComplementSet(excluded=set(wrapped))
560
+
561
+
562
+ def _norm_args_typeerror(other):
563
+ '''normalize args and raise type-error if there is a problem'''
564
+ if type(other) in (set, frozenset):
565
+ inc, exc = other, None
566
+ elif type(other) is _ComplementSet:
567
+ inc, exc = other._included, other._excluded
568
+ else:
569
+ raise TypeError('argument must be another set or complement(set)')
570
+ return inc, exc
571
+
572
+
573
+ def _norm_args_notimplemented(other):
574
+ '''normalize args and return NotImplemented (for overloaded operators)'''
575
+ if type(other) in (set, frozenset):
576
+ inc, exc = other, None
577
+ elif type(other) is _ComplementSet:
578
+ inc, exc = other._included, other._excluded
579
+ else:
580
+ return NotImplemented, None
581
+ return inc, exc
582
+
583
+
584
+ class _ComplementSet(object):
585
+ """
586
+ helper class for complement() that implements the set methods
587
+ """
588
+ __slots__ = ('_included', '_excluded')
589
+
590
+ def __init__(self, included=None, excluded=None):
591
+ if included is None:
592
+ assert type(excluded) in (set, frozenset)
593
+ elif excluded is None:
594
+ assert type(included) in (set, frozenset)
595
+ else:
596
+ raise ValueError('one of included or excluded must be a set')
597
+ self._included, self._excluded = included, excluded
598
+
599
+ def __repr__(self):
600
+ if self._included is None:
601
+ return 'complement({0})'.format(repr(self._excluded))
602
+ return 'complement(complement({0}))'.format(repr(self._included))
603
+
604
+ def complemented(self):
605
+ '''return a complement of the current set'''
606
+ if type(self._included) is frozenset or type(self._excluded) is frozenset:
607
+ return _ComplementSet(included=self._excluded, excluded=self._included)
608
+ return _ComplementSet(
609
+ included=None if self._excluded is None else set(self._excluded),
610
+ excluded=None if self._included is None else set(self._included))
611
+
612
+ __invert__ = complemented
613
+
614
+ def complement(self):
615
+ '''convert the current set to its complement in-place'''
616
+ self._included, self._excluded = self._excluded, self._included
617
+
618
+ def __contains__(self, item):
619
+ if self._included is None:
620
+ return not item in self._excluded
621
+ return item in self._included
622
+
623
+ def add(self, item):
624
+ if self._included is None:
625
+ if item in self._excluded:
626
+ self._excluded.remove(item)
627
+ else:
628
+ self._included.add(item)
629
+
630
+ def remove(self, item):
631
+ if self._included is None:
632
+ self._excluded.add(item)
633
+ else:
634
+ self._included.remove(item)
635
+
636
+ def pop(self):
637
+ if self._included is None:
638
+ raise NotImplementedError # self.missing.add(random.choice(gc.objects()))
639
+ return self._included.pop()
640
+
641
+ def intersection(self, other):
642
+ try:
643
+ return self & other
644
+ except NotImplementedError:
645
+ raise TypeError('argument must be another set or complement(set)')
646
+
647
+ def __and__(self, other):
648
+ inc, exc = _norm_args_notimplemented(other)
649
+ if inc is NotImplemented:
650
+ return NotImplemented
651
+ if self._included is None:
652
+ if exc is None: # - +
653
+ return _ComplementSet(included=inc - self._excluded)
654
+ else: # - -
655
+ return _ComplementSet(excluded=self._excluded.union(other._excluded))
656
+ else:
657
+ if inc is None: # + -
658
+ return _ComplementSet(included=exc - self._included)
659
+ else: # + +
660
+ return _ComplementSet(included=self._included.intersection(inc))
661
+
662
+ __rand__ = __and__
663
+
664
+ def __iand__(self, other):
665
+ inc, exc = _norm_args_notimplemented(other)
666
+ if inc is NotImplemented:
667
+ return NotImplemented
668
+ if self._included is None:
669
+ if exc is None: # - +
670
+ self._excluded = inc - self._excluded # TODO: do this in place?
671
+ else: # - -
672
+ self._excluded |= exc
673
+ else:
674
+ if inc is None: # + -
675
+ self._included -= exc
676
+ self._included, self._excluded = None, self._included
677
+ else: # + +
678
+ self._included &= inc
679
+ return self
680
+
681
+ def union(self, other):
682
+ try:
683
+ return self | other
684
+ except NotImplementedError:
685
+ raise TypeError('argument must be another set or complement(set)')
686
+
687
+ def __or__(self, other):
688
+ inc, exc = _norm_args_notimplemented(other)
689
+ if inc is NotImplemented:
690
+ return NotImplemented
691
+ if self._included is None:
692
+ if exc is None: # - +
693
+ return _ComplementSet(excluded=self._excluded - inc)
694
+ else: # - -
695
+ return _ComplementSet(excluded=self._excluded.intersection(exc))
696
+ else:
697
+ if inc is None: # + -
698
+ return _ComplementSet(excluded=exc - self._included)
699
+ else: # + +
700
+ return _ComplementSet(included=self._included.union(inc))
701
+
702
+ __ror__ = __or__
703
+
704
+ def __ior__(self, other):
705
+ inc, exc = _norm_args_notimplemented(other)
706
+ if inc is NotImplemented:
707
+ return NotImplemented
708
+ if self._included is None:
709
+ if exc is None: # - +
710
+ self._excluded -= inc
711
+ else: # - -
712
+ self._excluded &= exc
713
+ else:
714
+ if inc is None: # + -
715
+ self._included, self._excluded = None, exc - self._included # TODO: do this in place?
716
+ else: # + +
717
+ self._included |= inc
718
+ return self
719
+
720
+ def update(self, items):
721
+ if type(items) in (set, frozenset):
722
+ inc, exc = items, None
723
+ elif type(items) is _ComplementSet:
724
+ inc, exc = items._included, items._excluded
725
+ else:
726
+ inc, exc = frozenset(items), None
727
+ if self._included is None:
728
+ if exc is None: # - +
729
+ self._excluded &= inc
730
+ else: # - -
731
+ self._excluded.discard(exc)
732
+ else:
733
+ if inc is None: # + -
734
+ self._included &= exc
735
+ self._included, self._excluded = None, self._excluded
736
+ else: # + +
737
+ self._included.update(inc)
738
+
739
+ def discard(self, items):
740
+ if type(items) in (set, frozenset):
741
+ inc, exc = items, None
742
+ elif type(items) is _ComplementSet:
743
+ inc, exc = items._included, items._excluded
744
+ else:
745
+ inc, exc = frozenset(items), None
746
+ if self._included is None:
747
+ if exc is None: # - +
748
+ self._excluded.update(inc)
749
+ else: # - -
750
+ self._included, self._excluded = exc - self._excluded, None
751
+ else:
752
+ if inc is None: # + -
753
+ self._included &= exc
754
+ else: # + +
755
+ self._included.discard(inc)
756
+
757
+ def symmetric_difference(self, other):
758
+ try:
759
+ return self ^ other
760
+ except NotImplementedError:
761
+ raise TypeError('argument must be another set or complement(set)')
762
+
763
+ def __xor__(self, other):
764
+ inc, exc = _norm_args_notimplemented(other)
765
+ if inc is NotImplemented:
766
+ return NotImplemented
767
+ if inc is NotImplemented:
768
+ return NotImplemented
769
+ if self._included is None:
770
+ if exc is None: # - +
771
+ return _ComplementSet(excluded=self._excluded - inc)
772
+ else: # - -
773
+ return _ComplementSet(included=self._excluded.symmetric_difference(exc))
774
+ else:
775
+ if inc is None: # + -
776
+ return _ComplementSet(excluded=exc - self._included)
777
+ else: # + +
778
+ return _ComplementSet(included=self._included.symmetric_difference(inc))
779
+
780
+ __rxor__ = __xor__
781
+
782
+ def symmetric_difference_update(self, other):
783
+ inc, exc = _norm_args_typeerror(other)
784
+ if self._included is None:
785
+ if exc is None: # - +
786
+ self._excluded |= inc
787
+ else: # - -
788
+ self._excluded.symmetric_difference_update(exc)
789
+ self._included, self._excluded = self._excluded, None
790
+ else:
791
+ if inc is None: # + -
792
+ self._included |= exc
793
+ self._included, self._excluded = None, self._included
794
+ else: # + +
795
+ self._included.symmetric_difference_update(inc)
796
+
797
+ def isdisjoint(self, other):
798
+ inc, exc = _norm_args_typeerror(other)
799
+ if inc is NotImplemented:
800
+ return NotImplemented
801
+ if self._included is None:
802
+ if exc is None: # - +
803
+ return inc.issubset(self._excluded)
804
+ else: # - -
805
+ return False
806
+ else:
807
+ if inc is None: # + -
808
+ return self._included.issubset(exc)
809
+ else: # + +
810
+ return self._included.isdisjoint(inc)
811
+
812
+ def issubset(self, other):
813
+ '''everything missing from other is also missing from self'''
814
+ try:
815
+ return self <= other
816
+ except NotImplementedError:
817
+ raise TypeError('argument must be another set or complement(set)')
818
+
819
+ def __le__(self, other):
820
+ inc, exc = _norm_args_notimplemented(other)
821
+ if inc is NotImplemented:
822
+ return NotImplemented
823
+ if inc is NotImplemented:
824
+ return NotImplemented
825
+ if self._included is None:
826
+ if exc is None: # - +
827
+ return False
828
+ else: # - -
829
+ return self._excluded.issupserset(exc)
830
+ else:
831
+ if inc is None: # + -
832
+ return self._included.isdisjoint(exc)
833
+ else: # + +
834
+ return self._included.issubset(inc)
835
+
836
+ def __lt__(self, other):
837
+ inc, exc = _norm_args_notimplemented(other)
838
+ if inc is NotImplemented:
839
+ return NotImplemented
840
+ if inc is NotImplemented:
841
+ return NotImplemented
842
+ if self._included is None:
843
+ if exc is None: # - +
844
+ return False
845
+ else: # - -
846
+ return self._excluded > exc
847
+ else:
848
+ if inc is None: # + -
849
+ return self._included.isdisjoint(exc)
850
+ else: # + +
851
+ return self._included < inc
852
+
853
+ def issuperset(self, other):
854
+ '''everything missing from self is also missing from super'''
855
+ try:
856
+ return self >= other
857
+ except NotImplementedError:
858
+ raise TypeError('argument must be another set or complement(set)')
859
+
860
+ def __ge__(self, other):
861
+ inc, exc = _norm_args_notimplemented(other)
862
+ if inc is NotImplemented:
863
+ return NotImplemented
864
+ if self._included is None:
865
+ if exc is None: # - +
866
+ return not self._excluded.intersection(inc)
867
+ else: # - -
868
+ return self._excluded.issubset(exc)
869
+ else:
870
+ if inc is None: # + -
871
+ return False
872
+ else: # + +
873
+ return self._included.issupserset(inc)
874
+
875
+ def __gt__(self, other):
876
+ inc, exc = _norm_args_notimplemented(other)
877
+ if inc is NotImplemented:
878
+ return NotImplemented
879
+ if self._included is None:
880
+ if exc is None: # - +
881
+ return not self._excluded.intersection(inc)
882
+ else: # - -
883
+ return self._excluded < exc
884
+ else:
885
+ if inc is None: # + -
886
+ return False
887
+ else: # + +
888
+ return self._included > inc
889
+
890
+ def difference(self, other):
891
+ try:
892
+ return self - other
893
+ except NotImplementedError:
894
+ raise TypeError('argument must be another set or complement(set)')
895
+
896
+ def __sub__(self, other):
897
+ inc, exc = _norm_args_notimplemented(other)
898
+ if inc is NotImplemented:
899
+ return NotImplemented
900
+ if self._included is None:
901
+ if exc is None: # - +
902
+ return _ComplementSet(excluded=self._excluded | inc)
903
+ else: # - -
904
+ return _ComplementSet(included=exc - self._excluded)
905
+ else:
906
+ if inc is None: # + -
907
+ return _ComplementSet(included=self._included & exc)
908
+ else: # + +
909
+ return _ComplementSet(included=self._included.difference(inc))
910
+
911
+ def __rsub__(self, other):
912
+ inc, exc = _norm_args_notimplemented(other)
913
+ if inc is NotImplemented:
914
+ return NotImplemented
915
+ # rsub, so the expression being evaluated is "other - self"
916
+ if self._included is None:
917
+ if exc is None: # - +
918
+ return _ComplementSet(included=inc & self._excluded)
919
+ else: # - -
920
+ return _ComplementSet(included=self._excluded - exc)
921
+ else:
922
+ if inc is None: # + -
923
+ return _ComplementSet(excluded=exc | self._included)
924
+ else: # + +
925
+ return _ComplementSet(included=inc.difference(self._included))
926
+
927
+ def difference_update(self, other):
928
+ try:
929
+ self -= other
930
+ except NotImplementedError:
931
+ raise TypeError('argument must be another set or complement(set)')
932
+
933
+ def __isub__(self, other):
934
+ inc, exc = _norm_args_notimplemented(other)
935
+ if inc is NotImplemented:
936
+ return NotImplemented
937
+ if self._included is None:
938
+ if exc is None: # - +
939
+ self._excluded |= inc
940
+ else: # - -
941
+ self._included, self._excluded = exc - self._excluded, None
942
+ else:
943
+ if inc is None: # + -
944
+ self._included &= exc
945
+ else: # + +
946
+ self._included.difference_update(inc)
947
+ return self
948
+
949
+ def __eq__(self, other):
950
+ return (
951
+ type(self) is type(other)
952
+ and self._included == other._included
953
+ and self._excluded == other._excluded) or (
954
+ type(other) in (set, frozenset) and self._included == other)
955
+
956
+ def __hash__(self):
957
+ return hash(self._included) ^ hash(self._excluded)
958
+
959
+ def __len__(self):
960
+ if self._included is not None:
961
+ return len(self._included)
962
+ raise NotImplementedError('complemented sets have undefined length')
963
+
964
+ def __iter__(self):
965
+ if self._included is not None:
966
+ return iter(self._included)
967
+ raise NotImplementedError('complemented sets have undefined contents')
968
+
969
+ def __bool__(self):
970
+ if self._included is not None:
971
+ return bool(self._included)
972
+ return True
973
+
974
+ __nonzero__ = __bool__ # py2 compat
shared/package-files/00/006fc7f4bc50db6692f9823d09a03031dc6f3881feb24da82d3ee690ea645382/blob ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 at::Tensor sqrt(const at::Tensor & self);
21
+ TORCH_API at::Tensor & sqrt_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & sqrt_outf(const at::Tensor & self, at::Tensor & out);
23
+ TORCH_API at::Tensor & sqrt_(at::Tensor & self);
24
+
25
+ } // namespace cuda
26
+ } // namespace at
shared/package-files/00/00747ae5e774dcd581ea82bc6284d062ddc08029347cc935efd351704e567e64/blob ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABCMeta, abstractmethod
2
+ from typing import Optional
3
+
4
+ from cryptography.hazmat.backends.interfaces import DHBackend
5
+ from cryptography.hazmat.primitives.serialization import (
6
+ Encoding,
7
+ KeySerializationEncryption,
8
+ ParameterFormat,
9
+ PrivateFormat,
10
+ PublicFormat,
11
+ )
12
+
13
+ class DHParameters(metaclass=ABCMeta):
14
+ @abstractmethod
15
+ def generate_private_key(self) -> DHPrivateKey: ...
16
+ @abstractmethod
17
+ def parameter_bytes(self, encoding: Encoding, format: ParameterFormat) -> bytes: ...
18
+ @abstractmethod
19
+ def parameter_numbers(self) -> DHParameterNumbers: ...
20
+
21
+ DHParametersWithSerialization = DHParameters
22
+
23
+ class DHParameterNumbers(object):
24
+ @property
25
+ def p(self) -> int: ...
26
+ @property
27
+ def g(self) -> int: ...
28
+ @property
29
+ def q(self) -> int: ...
30
+ def __init__(self, p: int, g: int, q: Optional[int]) -> None: ...
31
+ def parameters(self, backend: Optional[DHBackend] = ...) -> DHParameters: ...
32
+
33
+ class DHPrivateKey(metaclass=ABCMeta):
34
+ key_size: int
35
+ @abstractmethod
36
+ def exchange(self, peer_public_key: DHPublicKey) -> bytes: ...
37
+ @abstractmethod
38
+ def parameters(self) -> DHParameters: ...
39
+ @abstractmethod
40
+ def public_key(self) -> DHPublicKey: ...
41
+
42
+ class DHPrivateKeyWithSerialization(DHPrivateKey):
43
+ @abstractmethod
44
+ def private_bytes(
45
+ self, encoding: Encoding, format: PrivateFormat, encryption_algorithm: KeySerializationEncryption
46
+ ) -> bytes: ...
47
+ @abstractmethod
48
+ def private_numbers(self) -> DHPrivateNumbers: ...
49
+
50
+ class DHPrivateNumbers(object):
51
+ @property
52
+ def public_numbers(self) -> DHPublicNumbers: ...
53
+ @property
54
+ def x(self) -> int: ...
55
+ def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: ...
56
+ def private_key(self, backend: Optional[DHBackend] = ...) -> DHPrivateKey: ...
57
+
58
+ class DHPublicKey(metaclass=ABCMeta):
59
+ @property
60
+ @abstractmethod
61
+ def key_size(self) -> int: ...
62
+ @abstractmethod
63
+ def parameters(self) -> DHParameters: ...
64
+ @abstractmethod
65
+ def public_bytes(self, encoding: Encoding, format: PublicFormat) -> bytes: ...
66
+ @abstractmethod
67
+ def public_numbers(self) -> DHPublicNumbers: ...
68
+
69
+ DHPublicKeyWithSerialization = DHPublicKey
70
+
71
+ class DHPublicNumbers(object):
72
+ @property
73
+ def parameter_numbers(self) -> DHParameterNumbers: ...
74
+ @property
75
+ def y(self) -> int: ...
76
+ def __init__(self, y: int, parameter_numbers: DHParameterNumbers) -> None: ...
77
+ def public_key(self, backend: Optional[DHBackend] = ...) -> DHPublicKey: ...
78
+
79
+ def generate_parameters(generator: int, key_size: int, backend: Optional[DHBackend] = ...) -> DHParameters: ...
shared/package-files/00/0074a85fc2e4588b7b4469490e693ae290ef996aba18287e0fb5f0136977f360/blob ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._optical_flow import FlyingChairs, FlyingThings3D, HD1K, KittiFlow, Sintel
2
+ from ._stereo_matching import (
3
+ CarlaStereo,
4
+ CREStereo,
5
+ ETH3DStereo,
6
+ FallingThingsStereo,
7
+ InStereo2k,
8
+ Kitti2012Stereo,
9
+ Kitti2015Stereo,
10
+ Middlebury2014Stereo,
11
+ SceneFlowStereo,
12
+ SintelStereo,
13
+ )
14
+ from .caltech import Caltech101, Caltech256
15
+ from .celeba import CelebA
16
+ from .cifar import CIFAR10, CIFAR100
17
+ from .cityscapes import Cityscapes
18
+ from .clevr import CLEVRClassification
19
+ from .coco import CocoCaptions, CocoDetection
20
+ from .country211 import Country211
21
+ from .dtd import DTD
22
+ from .eurosat import EuroSAT
23
+ from .fakedata import FakeData
24
+ from .fer2013 import FER2013
25
+ from .fgvc_aircraft import FGVCAircraft
26
+ from .flickr import Flickr30k, Flickr8k
27
+ from .flowers102 import Flowers102
28
+ from .folder import DatasetFolder, ImageFolder
29
+ from .food101 import Food101
30
+ from .gtsrb import GTSRB
31
+ from .hmdb51 import HMDB51
32
+ from .imagenet import ImageNet
33
+ from .imagenette import Imagenette
34
+ from .inaturalist import INaturalist
35
+ from .kinetics import Kinetics
36
+ from .kitti import Kitti
37
+ from .lfw import LFWPairs, LFWPeople
38
+ from .lsun import LSUN, LSUNClass
39
+ from .mnist import EMNIST, FashionMNIST, KMNIST, MNIST, QMNIST
40
+ from .moving_mnist import MovingMNIST
41
+ from .omniglot import Omniglot
42
+ from .oxford_iiit_pet import OxfordIIITPet
43
+ from .pcam import PCAM
44
+ from .phototour import PhotoTour
45
+ from .places365 import Places365
46
+ from .rendered_sst2 import RenderedSST2
47
+ from .sbd import SBDataset
48
+ from .sbu import SBU
49
+ from .semeion import SEMEION
50
+ from .stanford_cars import StanfordCars
51
+ from .stl10 import STL10
52
+ from .sun397 import SUN397
53
+ from .svhn import SVHN
54
+ from .ucf101 import UCF101
55
+ from .usps import USPS
56
+ from .vision import VisionDataset
57
+ from .voc import VOCDetection, VOCSegmentation
58
+ from .widerface import WIDERFace
59
+
60
+ __all__ = (
61
+ "LSUN",
62
+ "LSUNClass",
63
+ "ImageFolder",
64
+ "DatasetFolder",
65
+ "FakeData",
66
+ "CocoCaptions",
67
+ "CocoDetection",
68
+ "CIFAR10",
69
+ "CIFAR100",
70
+ "EMNIST",
71
+ "FashionMNIST",
72
+ "QMNIST",
73
+ "MNIST",
74
+ "KMNIST",
75
+ "StanfordCars",
76
+ "STL10",
77
+ "SUN397",
78
+ "SVHN",
79
+ "PhotoTour",
80
+ "SEMEION",
81
+ "Omniglot",
82
+ "SBU",
83
+ "Flickr8k",
84
+ "Flickr30k",
85
+ "Flowers102",
86
+ "VOCSegmentation",
87
+ "VOCDetection",
88
+ "Cityscapes",
89
+ "ImageNet",
90
+ "Caltech101",
91
+ "Caltech256",
92
+ "CelebA",
93
+ "WIDERFace",
94
+ "SBDataset",
95
+ "VisionDataset",
96
+ "USPS",
97
+ "Kinetics",
98
+ "HMDB51",
99
+ "UCF101",
100
+ "Places365",
101
+ "Kitti",
102
+ "INaturalist",
103
+ "LFWPeople",
104
+ "LFWPairs",
105
+ "KittiFlow",
106
+ "Sintel",
107
+ "FlyingChairs",
108
+ "FlyingThings3D",
109
+ "HD1K",
110
+ "Food101",
111
+ "DTD",
112
+ "FER2013",
113
+ "GTSRB",
114
+ "CLEVRClassification",
115
+ "OxfordIIITPet",
116
+ "PCAM",
117
+ "Country211",
118
+ "FGVCAircraft",
119
+ "EuroSAT",
120
+ "RenderedSST2",
121
+ "Kitti2012Stereo",
122
+ "Kitti2015Stereo",
123
+ "CarlaStereo",
124
+ "Middlebury2014Stereo",
125
+ "CREStereo",
126
+ "FallingThingsStereo",
127
+ "SceneFlowStereo",
128
+ "SintelStereo",
129
+ "InStereo2k",
130
+ "ETH3DStereo",
131
+ "wrap_dataset_for_transforms_v2",
132
+ "Imagenette",
133
+ )
134
+
135
+
136
+ # We override current module's attributes to handle the import:
137
+ # from torchvision.datasets import wrap_dataset_for_transforms_v2
138
+ # without a cyclic error.
139
+ # Ref: https://peps.python.org/pep-0562/
140
+ def __getattr__(name):
141
+ if name in ("wrap_dataset_for_transforms_v2",):
142
+ from torchvision.tv_tensors._dataset_wrapper import wrap_dataset_for_transforms_v2
143
+
144
+ return wrap_dataset_for_transforms_v2
145
+
146
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
shared/package-files/00/0076fa231bdbcf039b03630c36c86000136ac8ccf3e41aa6080b9e8bbb993e0b/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 compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor conv_transpose2d(const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1);
21
+ TORCH_API at::Tensor conv_transpose2d_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1));
22
+
23
+ } // namespace compositeimplicitautograd
24
+ } // namespace at
shared/package-files/00/007879f48b3ee1689559ddbaca8be73ccde15ea292fb2c7b2167d7492d0d6611/blob ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
2
+
3
+ # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
4
+ #
5
+ # Permission to use, copy, modify, and distribute this software and its
6
+ # documentation for any purpose with or without fee is hereby granted,
7
+ # provided that the above copyright notice and this permission notice
8
+ # appear in all copies.
9
+ #
10
+ # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11
+ # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
+ # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13
+ # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
+ # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
+ # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16
+ # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
+
18
+ import struct
19
+
20
+ import dns.exception
21
+ import dns.immutable
22
+ import dns.rdata
23
+ import dns.tokenizer
24
+
25
+
26
+ @dns.immutable.immutable
27
+ class CAA(dns.rdata.Rdata):
28
+ """CAA (Certification Authority Authorization) record"""
29
+
30
+ # see: RFC 6844
31
+
32
+ __slots__ = ["flags", "tag", "value"]
33
+
34
+ def __init__(self, rdclass, rdtype, flags, tag, value):
35
+ super().__init__(rdclass, rdtype)
36
+ self.flags = self._as_uint8(flags)
37
+ self.tag = self._as_bytes(tag, True, 255)
38
+ if not tag.isalnum():
39
+ raise ValueError("tag is not alphanumeric")
40
+ self.value = self._as_bytes(value)
41
+
42
+ def to_text(self, origin=None, relativize=True, **kw):
43
+ return '%u %s "%s"' % (
44
+ self.flags,
45
+ dns.rdata._escapify(self.tag),
46
+ dns.rdata._escapify(self.value),
47
+ )
48
+
49
+ @classmethod
50
+ def from_text(
51
+ cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None
52
+ ):
53
+ flags = tok.get_uint8()
54
+ tag = tok.get_string().encode()
55
+ value = tok.get_string().encode()
56
+ return cls(rdclass, rdtype, flags, tag, value)
57
+
58
+ def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
59
+ file.write(struct.pack("!B", self.flags))
60
+ l = len(self.tag)
61
+ assert l < 256
62
+ file.write(struct.pack("!B", l))
63
+ file.write(self.tag)
64
+ file.write(self.value)
65
+
66
+ @classmethod
67
+ def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
68
+ flags = parser.get_uint8()
69
+ tag = parser.get_counted_bytes()
70
+ value = parser.get_remaining()
71
+ return cls(rdclass, rdtype, flags, tag, value)
shared/package-files/00/007a806377cd7d6f29e3152ee2d4b79ae360ee897c6bbe75bfbb58ca2eecadda/blob ADDED
@@ -0,0 +1,1158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ date,
3
+ datetime,
4
+ timedelta,
5
+ )
6
+ import re
7
+
8
+ import numpy as np
9
+ import pytest
10
+
11
+ from pandas._libs.tslibs import iNaT
12
+ from pandas._libs.tslibs.ccalendar import (
13
+ DAYS,
14
+ MONTHS,
15
+ )
16
+ from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
17
+ from pandas._libs.tslibs.parsing import DateParseError
18
+ from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
19
+ from pandas.compat import PY314
20
+
21
+ from pandas import (
22
+ NaT,
23
+ Period,
24
+ Timedelta,
25
+ Timestamp,
26
+ offsets,
27
+ )
28
+ import pandas._testing as tm
29
+
30
+ bday_msg = "Period with BDay freq is deprecated"
31
+
32
+
33
+ class TestPeriodDisallowedFreqs:
34
+ @pytest.mark.parametrize(
35
+ "freq, freq_msg",
36
+ [
37
+ (offsets.BYearBegin(), "BYearBegin"),
38
+ (offsets.YearBegin(2), "YearBegin"),
39
+ (offsets.QuarterBegin(startingMonth=12), "QuarterBegin"),
40
+ (offsets.BusinessMonthEnd(2), "BusinessMonthEnd"),
41
+ ],
42
+ )
43
+ def test_offsets_not_supported(self, freq, freq_msg):
44
+ # GH#55785
45
+ msg = re.escape(f"{freq} is not supported as period frequency")
46
+ with pytest.raises(ValueError, match=msg):
47
+ Period(year=2014, freq=freq)
48
+
49
+ def test_custom_business_day_freq_raises(self):
50
+ # GH#52534
51
+ msg = "C is not supported as period frequency"
52
+ with pytest.raises(ValueError, match=msg):
53
+ Period("2023-04-10", freq="C")
54
+ msg = f"{offsets.CustomBusinessDay().base} is not supported as period frequency"
55
+ with pytest.raises(ValueError, match=msg):
56
+ Period("2023-04-10", freq=offsets.CustomBusinessDay())
57
+
58
+ def test_invalid_frequency_error_message(self):
59
+ msg = "WOM-1MON is not supported as period frequency"
60
+ with pytest.raises(ValueError, match=msg):
61
+ Period("2012-01-02", freq="WOM-1MON")
62
+
63
+ def test_invalid_frequency_period_error_message(self):
64
+ msg = "for Period, please use 'M' instead of 'ME'"
65
+ with pytest.raises(ValueError, match=msg):
66
+ Period("2012-01-02", freq="ME")
67
+
68
+
69
+ class TestPeriodConstruction:
70
+ def test_from_td64nat_raises(self):
71
+ # GH#44507
72
+ td = NaT.to_numpy("m8[ns]")
73
+
74
+ msg = "Value must be Period, string, integer, or datetime"
75
+ with pytest.raises(ValueError, match=msg):
76
+ Period(td)
77
+
78
+ with pytest.raises(ValueError, match=msg):
79
+ Period(td, freq="D")
80
+
81
+ def test_construction(self):
82
+ i1 = Period("1/1/2005", freq="M")
83
+ i2 = Period("Jan 2005")
84
+
85
+ assert i1 == i2
86
+
87
+ # GH#54105 - Period can be confusingly instantiated with lowercase freq
88
+ # TODO: raise in the future an error when passing lowercase freq
89
+ i1 = Period("2005", freq="Y")
90
+ i2 = Period("2005")
91
+
92
+ assert i1 == i2
93
+
94
+ i4 = Period("2005", freq="M")
95
+ assert i1 != i4
96
+
97
+ i1 = Period.now(freq="Q")
98
+ i2 = Period(datetime.now(), freq="Q")
99
+
100
+ assert i1 == i2
101
+
102
+ # Pass in freq as a keyword argument sometimes as a test for
103
+ # https://github.com/pandas-dev/pandas/issues/53369
104
+ i1 = Period.now(freq="D")
105
+ i2 = Period(datetime.now(), freq="D")
106
+ i3 = Period.now(offsets.Day())
107
+
108
+ assert i1 == i2
109
+ assert i1 == i3
110
+
111
+ i1 = Period("1982", freq="min")
112
+ msg = "'MIN' is deprecated and will be removed in a future version."
113
+ with tm.assert_produces_warning(FutureWarning, match=msg):
114
+ i2 = Period("1982", freq="MIN")
115
+ assert i1 == i2
116
+
117
+ i1 = Period(year=2005, month=3, day=1, freq="D")
118
+ i2 = Period("3/1/2005", freq="D")
119
+ assert i1 == i2
120
+
121
+ i3 = Period(year=2005, month=3, day=1, freq="d")
122
+ assert i1 == i3
123
+
124
+ i1 = Period("2007-01-01 09:00:00.001")
125
+ expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq="ms")
126
+ assert i1 == expected
127
+
128
+ expected = Period("2007-01-01 09:00:00.001", freq="ms")
129
+ assert i1 == expected
130
+
131
+ i1 = Period("2007-01-01 09:00:00.00101")
132
+ expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1010), freq="us")
133
+ assert i1 == expected
134
+
135
+ expected = Period("2007-01-01 09:00:00.00101", freq="us")
136
+ assert i1 == expected
137
+
138
+ msg = "Must supply freq for ordinal value"
139
+ with pytest.raises(ValueError, match=msg):
140
+ Period(ordinal=200701)
141
+
142
+ msg = "Invalid frequency: X"
143
+ with pytest.raises(ValueError, match=msg):
144
+ Period("2007-1-1", freq="X")
145
+
146
+ def test_tuple_freq_disallowed(self):
147
+ # GH#34703 tuple freq disallowed
148
+ with pytest.raises(TypeError, match="pass as a string instead"):
149
+ Period("1982", freq=("Min", 1))
150
+
151
+ with pytest.raises(TypeError, match="pass as a string instead"):
152
+ Period("2006-12-31", ("w", 1))
153
+
154
+ def test_construction_from_timestamp_nanos(self):
155
+ # GH#46811 don't drop nanos from Timestamp
156
+ ts = Timestamp("2022-04-20 09:23:24.123456789")
157
+ per = Period(ts, freq="ns")
158
+
159
+ # should losslessly round-trip, not lose the 789
160
+ rt = per.to_timestamp()
161
+ assert rt == ts
162
+
163
+ # same thing but from a datetime64 object
164
+ dt64 = ts.asm8
165
+ per2 = Period(dt64, freq="ns")
166
+ rt2 = per2.to_timestamp()
167
+ assert rt2.asm8 == dt64
168
+
169
+ def test_construction_bday(self):
170
+ # Biz day construction, roll forward if non-weekday
171
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
172
+ i1 = Period("3/10/12", freq="B")
173
+ i2 = Period("3/10/12", freq="D")
174
+ assert i1 == i2.asfreq("B")
175
+ i2 = Period("3/11/12", freq="D")
176
+ assert i1 == i2.asfreq("B")
177
+ i2 = Period("3/12/12", freq="D")
178
+ assert i1 == i2.asfreq("B")
179
+
180
+ i3 = Period("3/10/12", freq="b")
181
+ assert i1 == i3
182
+
183
+ i1 = Period(year=2012, month=3, day=10, freq="B")
184
+ i2 = Period("3/12/12", freq="B")
185
+ assert i1 == i2
186
+
187
+ def test_construction_quarter(self):
188
+ i1 = Period(year=2005, quarter=1, freq="Q")
189
+ i2 = Period("1/1/2005", freq="Q")
190
+ assert i1 == i2
191
+
192
+ i1 = Period(year=2005, quarter=3, freq="Q")
193
+ i2 = Period("9/1/2005", freq="Q")
194
+ assert i1 == i2
195
+
196
+ i1 = Period("2005Q1")
197
+ i2 = Period(year=2005, quarter=1, freq="Q")
198
+ i3 = Period("2005q1")
199
+ assert i1 == i2
200
+ assert i1 == i3
201
+
202
+ i1 = Period("05Q1")
203
+ assert i1 == i2
204
+ lower = Period("05q1")
205
+ assert i1 == lower
206
+
207
+ i1 = Period("1Q2005")
208
+ assert i1 == i2
209
+ lower = Period("1q2005")
210
+ assert i1 == lower
211
+
212
+ i1 = Period("1Q05")
213
+ assert i1 == i2
214
+ lower = Period("1q05")
215
+ assert i1 == lower
216
+
217
+ i1 = Period("4Q1984")
218
+ assert i1.year == 1984
219
+ lower = Period("4q1984")
220
+ assert i1 == lower
221
+
222
+ def test_construction_month(self):
223
+ expected = Period("2007-01", freq="M")
224
+ i1 = Period("200701", freq="M")
225
+ assert i1 == expected
226
+
227
+ i1 = Period("200701", freq="M")
228
+ assert i1 == expected
229
+
230
+ i1 = Period(200701, freq="M")
231
+ assert i1 == expected
232
+
233
+ i1 = Period(ordinal=200701, freq="M")
234
+ assert i1.year == 18695
235
+
236
+ i1 = Period(datetime(2007, 1, 1), freq="M")
237
+ i2 = Period("200701", freq="M")
238
+ assert i1 == i2
239
+
240
+ i1 = Period(date(2007, 1, 1), freq="M")
241
+ i2 = Period(datetime(2007, 1, 1), freq="M")
242
+ i3 = Period(np.datetime64("2007-01-01"), freq="M")
243
+ i4 = Period("2007-01-01 00:00:00", freq="M")
244
+ i5 = Period("2007-01-01 00:00:00.000", freq="M")
245
+ assert i1 == i2
246
+ assert i1 == i3
247
+ assert i1 == i4
248
+ assert i1 == i5
249
+
250
+ def test_period_constructor_offsets(self):
251
+ assert Period("1/1/2005", freq=offsets.MonthEnd()) == Period(
252
+ "1/1/2005", freq="M"
253
+ )
254
+ assert Period("2005", freq=offsets.YearEnd()) == Period("2005", freq="Y")
255
+ assert Period("2005", freq=offsets.MonthEnd()) == Period("2005", freq="M")
256
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
257
+ assert Period("3/10/12", freq=offsets.BusinessDay()) == Period(
258
+ "3/10/12", freq="B"
259
+ )
260
+ assert Period("3/10/12", freq=offsets.Day()) == Period("3/10/12", freq="D")
261
+
262
+ assert Period(
263
+ year=2005, quarter=1, freq=offsets.QuarterEnd(startingMonth=12)
264
+ ) == Period(year=2005, quarter=1, freq="Q")
265
+ assert Period(
266
+ year=2005, quarter=2, freq=offsets.QuarterEnd(startingMonth=12)
267
+ ) == Period(year=2005, quarter=2, freq="Q")
268
+
269
+ assert Period(year=2005, month=3, day=1, freq=offsets.Day()) == Period(
270
+ year=2005, month=3, day=1, freq="D"
271
+ )
272
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
273
+ assert Period(year=2012, month=3, day=10, freq=offsets.BDay()) == Period(
274
+ year=2012, month=3, day=10, freq="B"
275
+ )
276
+
277
+ expected = Period("2005-03-01", freq="3D")
278
+ assert Period(year=2005, month=3, day=1, freq=offsets.Day(3)) == expected
279
+ assert Period(year=2005, month=3, day=1, freq="3D") == expected
280
+
281
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
282
+ assert Period(year=2012, month=3, day=10, freq=offsets.BDay(3)) == Period(
283
+ year=2012, month=3, day=10, freq="3B"
284
+ )
285
+
286
+ assert Period(200701, freq=offsets.MonthEnd()) == Period(200701, freq="M")
287
+
288
+ i1 = Period(ordinal=200701, freq=offsets.MonthEnd())
289
+ i2 = Period(ordinal=200701, freq="M")
290
+ assert i1 == i2
291
+ assert i1.year == 18695
292
+ assert i2.year == 18695
293
+
294
+ i1 = Period(datetime(2007, 1, 1), freq="M")
295
+ i2 = Period("200701", freq="M")
296
+ assert i1 == i2
297
+
298
+ i1 = Period(date(2007, 1, 1), freq="M")
299
+ i2 = Period(datetime(2007, 1, 1), freq="M")
300
+ i3 = Period(np.datetime64("2007-01-01"), freq="M")
301
+ i4 = Period("2007-01-01 00:00:00", freq="M")
302
+ i5 = Period("2007-01-01 00:00:00.000", freq="M")
303
+ assert i1 == i2
304
+ assert i1 == i3
305
+ assert i1 == i4
306
+ assert i1 == i5
307
+
308
+ i1 = Period("2007-01-01 09:00:00.001")
309
+ expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1000), freq="ms")
310
+ assert i1 == expected
311
+
312
+ expected = Period("2007-01-01 09:00:00.001", freq="ms")
313
+ assert i1 == expected
314
+
315
+ i1 = Period("2007-01-01 09:00:00.00101")
316
+ expected = Period(datetime(2007, 1, 1, 9, 0, 0, 1010), freq="us")
317
+ assert i1 == expected
318
+
319
+ expected = Period("2007-01-01 09:00:00.00101", freq="us")
320
+ assert i1 == expected
321
+
322
+ def test_invalid_arguments(self):
323
+ msg = "Must supply freq for datetime value"
324
+ with pytest.raises(ValueError, match=msg):
325
+ Period(datetime.now())
326
+ with pytest.raises(ValueError, match=msg):
327
+ Period(datetime.now().date())
328
+
329
+ msg = "Value must be Period, string, integer, or datetime"
330
+ with pytest.raises(ValueError, match=msg):
331
+ Period(1.6, freq="D")
332
+ msg = "Ordinal must be an integer"
333
+ with pytest.raises(ValueError, match=msg):
334
+ Period(ordinal=1.6, freq="D")
335
+ msg = "Only value or ordinal but not both should be given but not both"
336
+ with pytest.raises(ValueError, match=msg):
337
+ Period(ordinal=2, value=1, freq="D")
338
+
339
+ msg = "If value is None, freq cannot be None"
340
+ with pytest.raises(ValueError, match=msg):
341
+ Period(month=1)
342
+
343
+ msg = '^Given date string "-2000" not likely a datetime$'
344
+ with pytest.raises(ValueError, match=msg):
345
+ Period("-2000", "Y")
346
+ if PY314:
347
+ msg = "day 0 must be in range 1..31 for month 1 in year 1: 0"
348
+ else:
349
+ msg = "day is out of range for month"
350
+ with pytest.raises(DateParseError, match=msg):
351
+ Period("0", "Y")
352
+ msg = "Unknown datetime string format, unable to parse"
353
+ with pytest.raises(DateParseError, match=msg):
354
+ Period("1/1/-2000", "Y")
355
+
356
+ def test_constructor_corner(self):
357
+ expected = Period("2007-01", freq="2M")
358
+ assert Period(year=2007, month=1, freq="2M") == expected
359
+
360
+ assert Period(None) is NaT
361
+
362
+ p = Period("2007-01-01", freq="D")
363
+
364
+ result = Period(p, freq="Y")
365
+ exp = Period("2007", freq="Y")
366
+ assert result == exp
367
+
368
+ def test_constructor_infer_freq(self):
369
+ p = Period("2007-01-01")
370
+ assert p.freq == "D"
371
+
372
+ p = Period("2007-01-01 07")
373
+ assert p.freq == "h"
374
+
375
+ p = Period("2007-01-01 07:10")
376
+ assert p.freq == "min"
377
+
378
+ p = Period("2007-01-01 07:10:15")
379
+ assert p.freq == "s"
380
+
381
+ p = Period("2007-01-01 07:10:15.123")
382
+ assert p.freq == "ms"
383
+
384
+ # We see that there are 6 digits after the decimal, so get microsecond
385
+ # even though they are all zeros.
386
+ p = Period("2007-01-01 07:10:15.123000")
387
+ assert p.freq == "us"
388
+
389
+ p = Period("2007-01-01 07:10:15.123400")
390
+ assert p.freq == "us"
391
+
392
+ def test_multiples(self):
393
+ result1 = Period("1989", freq="2Y")
394
+ result2 = Period("1989", freq="Y")
395
+ assert result1.ordinal == result2.ordinal
396
+ assert result1.freqstr == "2Y-DEC"
397
+ assert result2.freqstr == "Y-DEC"
398
+ assert result1.freq == offsets.YearEnd(2)
399
+ assert result2.freq == offsets.YearEnd()
400
+
401
+ assert (result1 + 1).ordinal == result1.ordinal + 2
402
+ assert (1 + result1).ordinal == result1.ordinal + 2
403
+ assert (result1 - 1).ordinal == result2.ordinal - 2
404
+ assert (-1 + result1).ordinal == result2.ordinal - 2
405
+
406
+ @pytest.mark.parametrize("month", MONTHS)
407
+ def test_period_cons_quarterly(self, month):
408
+ # bugs in scikits.timeseries
409
+ freq = f"Q-{month}"
410
+ exp = Period("1989Q3", freq=freq)
411
+ assert "1989Q3" in str(exp)
412
+ stamp = exp.to_timestamp("D", how="end")
413
+ p = Period(stamp, freq=freq)
414
+ assert p == exp
415
+
416
+ stamp = exp.to_timestamp("3D", how="end")
417
+ p = Period(stamp, freq=freq)
418
+ assert p == exp
419
+
420
+ @pytest.mark.parametrize("month", MONTHS)
421
+ def test_period_cons_annual(self, month):
422
+ # bugs in scikits.timeseries
423
+ freq = f"Y-{month}"
424
+ exp = Period("1989", freq=freq)
425
+ stamp = exp.to_timestamp("D", how="end") + timedelta(days=30)
426
+ p = Period(stamp, freq=freq)
427
+
428
+ assert p == exp + 1
429
+ assert isinstance(p, Period)
430
+
431
+ @pytest.mark.parametrize("day", DAYS)
432
+ @pytest.mark.parametrize("num", range(10, 17))
433
+ def test_period_cons_weekly(self, num, day):
434
+ daystr = f"2011-02-{num}"
435
+ freq = f"W-{day}"
436
+
437
+ result = Period(daystr, freq=freq)
438
+ expected = Period(daystr, freq="D").asfreq(freq)
439
+ assert result == expected
440
+ assert isinstance(result, Period)
441
+
442
+ def test_parse_week_str_roundstrip(self):
443
+ # GH#50803
444
+ per = Period("2017-01-23/2017-01-29")
445
+ assert per.freq.freqstr == "W-SUN"
446
+
447
+ per = Period("2017-01-24/2017-01-30")
448
+ assert per.freq.freqstr == "W-MON"
449
+
450
+ msg = "Could not parse as weekly-freq Period"
451
+ with pytest.raises(ValueError, match=msg):
452
+ # not 6 days apart
453
+ Period("2016-01-23/2017-01-29")
454
+
455
+ def test_period_from_ordinal(self):
456
+ p = Period("2011-01", freq="M")
457
+ res = Period._from_ordinal(p.ordinal, freq=p.freq)
458
+ assert p == res
459
+ assert isinstance(res, Period)
460
+
461
+ @pytest.mark.parametrize("freq", ["Y", "M", "D", "h"])
462
+ def test_construct_from_nat_string_and_freq(self, freq):
463
+ per = Period("NaT", freq=freq)
464
+ assert per is NaT
465
+
466
+ per = Period("NaT", freq="2" + freq)
467
+ assert per is NaT
468
+
469
+ per = Period("NaT", freq="3" + freq)
470
+ assert per is NaT
471
+
472
+ def test_period_cons_nat(self):
473
+ p = Period("nat", freq="W-SUN")
474
+ assert p is NaT
475
+
476
+ p = Period(iNaT, freq="D")
477
+ assert p is NaT
478
+
479
+ p = Period(iNaT, freq="3D")
480
+ assert p is NaT
481
+
482
+ p = Period(iNaT, freq="1D1h")
483
+ assert p is NaT
484
+
485
+ p = Period("NaT")
486
+ assert p is NaT
487
+
488
+ p = Period(iNaT)
489
+ assert p is NaT
490
+
491
+ def test_period_cons_mult(self):
492
+ p1 = Period("2011-01", freq="3M")
493
+ p2 = Period("2011-01", freq="M")
494
+ assert p1.ordinal == p2.ordinal
495
+
496
+ assert p1.freq == offsets.MonthEnd(3)
497
+ assert p1.freqstr == "3M"
498
+
499
+ assert p2.freq == offsets.MonthEnd()
500
+ assert p2.freqstr == "M"
501
+
502
+ result = p1 + 1
503
+ assert result.ordinal == (p2 + 3).ordinal
504
+
505
+ assert result.freq == p1.freq
506
+ assert result.freqstr == "3M"
507
+
508
+ result = p1 - 1
509
+ assert result.ordinal == (p2 - 3).ordinal
510
+ assert result.freq == p1.freq
511
+ assert result.freqstr == "3M"
512
+
513
+ msg = "Frequency must be positive, because it represents span: -3M"
514
+ with pytest.raises(ValueError, match=msg):
515
+ Period("2011-01", freq="-3M")
516
+
517
+ msg = "Frequency must be positive, because it represents span: 0M"
518
+ with pytest.raises(ValueError, match=msg):
519
+ Period("2011-01", freq="0M")
520
+
521
+ def test_period_cons_combined(self):
522
+ p = [
523
+ (
524
+ Period("2011-01", freq="1D1h"),
525
+ Period("2011-01", freq="1h1D"),
526
+ Period("2011-01", freq="h"),
527
+ ),
528
+ (
529
+ Period(ordinal=1, freq="1D1h"),
530
+ Period(ordinal=1, freq="1h1D"),
531
+ Period(ordinal=1, freq="h"),
532
+ ),
533
+ ]
534
+
535
+ for p1, p2, p3 in p:
536
+ assert p1.ordinal == p3.ordinal
537
+ assert p2.ordinal == p3.ordinal
538
+
539
+ assert p1.freq == offsets.Hour(25)
540
+ assert p1.freqstr == "25h"
541
+
542
+ assert p2.freq == offsets.Hour(25)
543
+ assert p2.freqstr == "25h"
544
+
545
+ assert p3.freq == offsets.Hour()
546
+ assert p3.freqstr == "h"
547
+
548
+ result = p1 + 1
549
+ assert result.ordinal == (p3 + 25).ordinal
550
+ assert result.freq == p1.freq
551
+ assert result.freqstr == "25h"
552
+
553
+ result = p2 + 1
554
+ assert result.ordinal == (p3 + 25).ordinal
555
+ assert result.freq == p2.freq
556
+ assert result.freqstr == "25h"
557
+
558
+ result = p1 - 1
559
+ assert result.ordinal == (p3 - 25).ordinal
560
+ assert result.freq == p1.freq
561
+ assert result.freqstr == "25h"
562
+
563
+ result = p2 - 1
564
+ assert result.ordinal == (p3 - 25).ordinal
565
+ assert result.freq == p2.freq
566
+ assert result.freqstr == "25h"
567
+
568
+ msg = "Frequency must be positive, because it represents span: -25h"
569
+ with pytest.raises(ValueError, match=msg):
570
+ Period("2011-01", freq="-1D1h")
571
+ with pytest.raises(ValueError, match=msg):
572
+ Period("2011-01", freq="-1h1D")
573
+ with pytest.raises(ValueError, match=msg):
574
+ Period(ordinal=1, freq="-1D1h")
575
+ with pytest.raises(ValueError, match=msg):
576
+ Period(ordinal=1, freq="-1h1D")
577
+
578
+ msg = "Frequency must be positive, because it represents span: 0D"
579
+ with pytest.raises(ValueError, match=msg):
580
+ Period("2011-01", freq="0D0h")
581
+ with pytest.raises(ValueError, match=msg):
582
+ Period(ordinal=1, freq="0D0h")
583
+
584
+ # You can only combine together day and intraday offsets
585
+ msg = "Invalid frequency: 1W1D"
586
+ with pytest.raises(ValueError, match=msg):
587
+ Period("2011-01", freq="1W1D")
588
+ msg = "Invalid frequency: 1D1W"
589
+ with pytest.raises(ValueError, match=msg):
590
+ Period("2011-01", freq="1D1W")
591
+
592
+ @pytest.mark.parametrize("day", ["1970/01/01 ", "2020-12-31 ", "1981/09/13 "])
593
+ @pytest.mark.parametrize("hour", ["00:00:00", "00:00:01", "23:59:59", "12:00:59"])
594
+ @pytest.mark.parametrize(
595
+ "sec_float, expected",
596
+ [
597
+ (".000000001", 1),
598
+ (".000000999", 999),
599
+ (".123456789", 789),
600
+ (".999999999", 999),
601
+ (".999999000", 0),
602
+ # Test femtoseconds, attoseconds, picoseconds are dropped like Timestamp
603
+ (".999999001123", 1),
604
+ (".999999001123456", 1),
605
+ (".999999001123456789", 1),
606
+ ],
607
+ )
608
+ def test_period_constructor_nanosecond(self, day, hour, sec_float, expected):
609
+ # GH 34621
610
+
611
+ assert Period(day + hour + sec_float).start_time.nanosecond == expected
612
+
613
+ @pytest.mark.parametrize("hour", range(24))
614
+ def test_period_large_ordinal(self, hour):
615
+ # Issue #36430
616
+ # Integer overflow for Period over the maximum timestamp
617
+ p = Period(ordinal=2562048 + hour, freq="1h")
618
+ assert p.hour == hour
619
+
620
+
621
+ class TestPeriodMethods:
622
+ def test_round_trip(self):
623
+ p = Period("2000Q1")
624
+ new_p = tm.round_trip_pickle(p)
625
+ assert new_p == p
626
+
627
+ def test_hash(self):
628
+ assert hash(Period("2011-01", freq="M")) == hash(Period("2011-01", freq="M"))
629
+
630
+ assert hash(Period("2011-01-01", freq="D")) != hash(Period("2011-01", freq="M"))
631
+
632
+ assert hash(Period("2011-01", freq="3M")) != hash(Period("2011-01", freq="2M"))
633
+
634
+ assert hash(Period("2011-01", freq="M")) != hash(Period("2011-02", freq="M"))
635
+
636
+ # --------------------------------------------------------------
637
+ # to_timestamp
638
+
639
+ def test_to_timestamp_mult(self):
640
+ p = Period("2011-01", freq="M")
641
+ assert p.to_timestamp(how="S") == Timestamp("2011-01-01")
642
+ expected = Timestamp("2011-02-01") - Timedelta(1, "ns")
643
+ assert p.to_timestamp(how="E") == expected
644
+
645
+ p = Period("2011-01", freq="3M")
646
+ assert p.to_timestamp(how="S") == Timestamp("2011-01-01")
647
+ expected = Timestamp("2011-04-01") - Timedelta(1, "ns")
648
+ assert p.to_timestamp(how="E") == expected
649
+
650
+ @pytest.mark.filterwarnings(
651
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
652
+ )
653
+ def test_to_timestamp(self):
654
+ p = Period("1982", freq="Y")
655
+ start_ts = p.to_timestamp(how="S")
656
+ aliases = ["s", "StarT", "BEGIn"]
657
+ for a in aliases:
658
+ assert start_ts == p.to_timestamp("D", how=a)
659
+ # freq with mult should not affect to the result
660
+ assert start_ts == p.to_timestamp("3D", how=a)
661
+
662
+ end_ts = p.to_timestamp(how="E")
663
+ aliases = ["e", "end", "FINIsH"]
664
+ for a in aliases:
665
+ assert end_ts == p.to_timestamp("D", how=a)
666
+ assert end_ts == p.to_timestamp("3D", how=a)
667
+
668
+ from_lst = ["Y", "Q", "M", "W", "B", "D", "h", "Min", "s"]
669
+
670
+ def _ex(p):
671
+ if p.freq == "B":
672
+ return p.start_time + Timedelta(days=1, nanoseconds=-1)
673
+ return Timestamp((p + p.freq).start_time._value - 1)
674
+
675
+ for fcode in from_lst:
676
+ p = Period("1982", freq=fcode)
677
+ result = p.to_timestamp().to_period(fcode)
678
+ assert result == p
679
+
680
+ assert p.start_time == p.to_timestamp(how="S")
681
+
682
+ assert p.end_time == _ex(p)
683
+
684
+ # Frequency other than daily
685
+
686
+ p = Period("1985", freq="Y")
687
+
688
+ result = p.to_timestamp("h", how="end")
689
+ expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")
690
+ assert result == expected
691
+ result = p.to_timestamp("3h", how="end")
692
+ assert result == expected
693
+
694
+ result = p.to_timestamp("min", how="end")
695
+ expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")
696
+ assert result == expected
697
+ result = p.to_timestamp("2min", how="end")
698
+ assert result == expected
699
+
700
+ result = p.to_timestamp(how="end")
701
+ expected = Timestamp(1986, 1, 1) - Timedelta(1, "ns")
702
+ assert result == expected
703
+
704
+ expected = datetime(1985, 1, 1)
705
+ result = p.to_timestamp("h", how="start")
706
+ assert result == expected
707
+ result = p.to_timestamp("min", how="start")
708
+ assert result == expected
709
+ result = p.to_timestamp("s", how="start")
710
+ assert result == expected
711
+ result = p.to_timestamp("3h", how="start")
712
+ assert result == expected
713
+ result = p.to_timestamp("5s", how="start")
714
+ assert result == expected
715
+
716
+ def test_to_timestamp_business_end(self):
717
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
718
+ per = Period("1990-01-05", "B") # Friday
719
+ result = per.to_timestamp("B", how="E")
720
+
721
+ expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1)
722
+ assert result == expected
723
+
724
+ @pytest.mark.parametrize(
725
+ "ts, expected",
726
+ [
727
+ ("1970-01-01 00:00:00", 0),
728
+ ("1970-01-01 00:00:00.000001", 1),
729
+ ("1970-01-01 00:00:00.00001", 10),
730
+ ("1970-01-01 00:00:00.499", 499000),
731
+ ("1999-12-31 23:59:59.999", 999000),
732
+ ("1999-12-31 23:59:59.999999", 999999),
733
+ ("2050-12-31 23:59:59.5", 500000),
734
+ ("2050-12-31 23:59:59.500001", 500001),
735
+ ("2050-12-31 23:59:59.123456", 123456),
736
+ ],
737
+ )
738
+ @pytest.mark.parametrize("freq", [None, "us", "ns"])
739
+ def test_to_timestamp_microsecond(self, ts, expected, freq):
740
+ # GH 24444
741
+ result = Period(ts).to_timestamp(freq=freq).microsecond
742
+ assert result == expected
743
+
744
+ # --------------------------------------------------------------
745
+ # Rendering: __repr__, strftime, etc
746
+
747
+ @pytest.mark.parametrize(
748
+ "str_ts,freq,str_res,str_freq",
749
+ (
750
+ ("Jan-2000", None, "2000-01", "M"),
751
+ ("2000-12-15", None, "2000-12-15", "D"),
752
+ (
753
+ "2000-12-15 13:45:26.123456789",
754
+ "ns",
755
+ "2000-12-15 13:45:26.123456789",
756
+ "ns",
757
+ ),
758
+ ("2000-12-15 13:45:26.123456789", "us", "2000-12-15 13:45:26.123456", "us"),
759
+ ("2000-12-15 13:45:26.123456", None, "2000-12-15 13:45:26.123456", "us"),
760
+ ("2000-12-15 13:45:26.123456789", "ms", "2000-12-15 13:45:26.123", "ms"),
761
+ ("2000-12-15 13:45:26.123", None, "2000-12-15 13:45:26.123", "ms"),
762
+ ("2000-12-15 13:45:26", "s", "2000-12-15 13:45:26", "s"),
763
+ ("2000-12-15 13:45:26", "min", "2000-12-15 13:45", "min"),
764
+ ("2000-12-15 13:45:26", "h", "2000-12-15 13:00", "h"),
765
+ ("2000-12-15", "Y", "2000", "Y-DEC"),
766
+ ("2000-12-15", "Q", "2000Q4", "Q-DEC"),
767
+ ("2000-12-15", "M", "2000-12", "M"),
768
+ ("2000-12-15", "W", "2000-12-11/2000-12-17", "W-SUN"),
769
+ ("2000-12-15", "D", "2000-12-15", "D"),
770
+ ("2000-12-15", "B", "2000-12-15", "B"),
771
+ ),
772
+ )
773
+ @pytest.mark.filterwarnings(
774
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
775
+ )
776
+ def test_repr(self, str_ts, freq, str_res, str_freq):
777
+ p = Period(str_ts, freq=freq)
778
+ assert str(p) == str_res
779
+ assert repr(p) == f"Period('{str_res}', '{str_freq}')"
780
+
781
+ def test_repr_nat(self):
782
+ p = Period("nat", freq="M")
783
+ assert repr(NaT) in repr(p)
784
+
785
+ def test_strftime(self):
786
+ # GH#3363
787
+ p = Period("2000-1-1 12:34:12", freq="s")
788
+ res = p.strftime("%Y-%m-%d %H:%M:%S")
789
+ assert res == "2000-01-01 12:34:12"
790
+ assert isinstance(res, str)
791
+
792
+
793
+ class TestPeriodProperties:
794
+ """Test properties such as year, month, weekday, etc...."""
795
+
796
+ @pytest.mark.parametrize("freq", ["Y", "M", "D", "h"])
797
+ def test_is_leap_year(self, freq):
798
+ # GH 13727
799
+ p = Period("2000-01-01 00:00:00", freq=freq)
800
+ assert p.is_leap_year
801
+ assert isinstance(p.is_leap_year, bool)
802
+
803
+ p = Period("1999-01-01 00:00:00", freq=freq)
804
+ assert not p.is_leap_year
805
+
806
+ p = Period("2004-01-01 00:00:00", freq=freq)
807
+ assert p.is_leap_year
808
+
809
+ p = Period("2100-01-01 00:00:00", freq=freq)
810
+ assert not p.is_leap_year
811
+
812
+ def test_quarterly_negative_ordinals(self):
813
+ p = Period(ordinal=-1, freq="Q-DEC")
814
+ assert p.year == 1969
815
+ assert p.quarter == 4
816
+ assert isinstance(p, Period)
817
+
818
+ p = Period(ordinal=-2, freq="Q-DEC")
819
+ assert p.year == 1969
820
+ assert p.quarter == 3
821
+ assert isinstance(p, Period)
822
+
823
+ p = Period(ordinal=-2, freq="M")
824
+ assert p.year == 1969
825
+ assert p.month == 11
826
+ assert isinstance(p, Period)
827
+
828
+ def test_freq_str(self):
829
+ i1 = Period("1982", freq="Min")
830
+ assert i1.freq == offsets.Minute()
831
+ assert i1.freqstr == "min"
832
+
833
+ @pytest.mark.filterwarnings(
834
+ "ignore:Period with BDay freq is deprecated:FutureWarning"
835
+ )
836
+ def test_period_deprecated_freq(self):
837
+ cases = {
838
+ "M": ["MTH", "MONTH", "MONTHLY", "Mth", "month", "monthly"],
839
+ "B": ["BUS", "BUSINESS", "BUSINESSLY", "WEEKDAY", "bus"],
840
+ "D": ["DAY", "DLY", "DAILY", "Day", "Dly", "Daily"],
841
+ "h": ["HR", "HOUR", "HRLY", "HOURLY", "hr", "Hour", "HRly"],
842
+ "min": ["minute", "MINUTE", "MINUTELY", "minutely"],
843
+ "s": ["sec", "SEC", "SECOND", "SECONDLY", "second"],
844
+ "ms": ["MILLISECOND", "MILLISECONDLY", "millisecond"],
845
+ "us": ["MICROSECOND", "MICROSECONDLY", "microsecond"],
846
+ "ns": ["NANOSECOND", "NANOSECONDLY", "nanosecond"],
847
+ }
848
+
849
+ msg = INVALID_FREQ_ERR_MSG
850
+ for exp, freqs in cases.items():
851
+ for freq in freqs:
852
+ with pytest.raises(ValueError, match=msg):
853
+ Period("2016-03-01 09:00", freq=freq)
854
+ with pytest.raises(ValueError, match=msg):
855
+ Period(ordinal=1, freq=freq)
856
+
857
+ # check supported freq-aliases still works
858
+ p1 = Period("2016-03-01 09:00", freq=exp)
859
+ p2 = Period(ordinal=1, freq=exp)
860
+ assert isinstance(p1, Period)
861
+ assert isinstance(p2, Period)
862
+
863
+ @staticmethod
864
+ def _period_constructor(bound, offset):
865
+ return Period(
866
+ year=bound.year,
867
+ month=bound.month,
868
+ day=bound.day,
869
+ hour=bound.hour,
870
+ minute=bound.minute,
871
+ second=bound.second + offset,
872
+ freq="us",
873
+ )
874
+
875
+ @pytest.mark.parametrize("bound, offset", [(Timestamp.min, -1), (Timestamp.max, 1)])
876
+ @pytest.mark.parametrize("period_property", ["start_time", "end_time"])
877
+ def test_outer_bounds_start_and_end_time(self, bound, offset, period_property):
878
+ # GH #13346
879
+ period = TestPeriodProperties._period_constructor(bound, offset)
880
+ with pytest.raises(OutOfBoundsDatetime, match="Out of bounds nanosecond"):
881
+ getattr(period, period_property)
882
+
883
+ @pytest.mark.parametrize("bound, offset", [(Timestamp.min, -1), (Timestamp.max, 1)])
884
+ @pytest.mark.parametrize("period_property", ["start_time", "end_time"])
885
+ def test_inner_bounds_start_and_end_time(self, bound, offset, period_property):
886
+ # GH #13346
887
+ period = TestPeriodProperties._period_constructor(bound, -offset)
888
+ expected = period.to_timestamp().round(freq="s")
889
+ assert getattr(period, period_property).round(freq="s") == expected
890
+ expected = (bound - offset * Timedelta(1, unit="s")).floor("s")
891
+ assert getattr(period, period_property).floor("s") == expected
892
+
893
+ def test_start_time(self):
894
+ freq_lst = ["Y", "Q", "M", "D", "h", "min", "s"]
895
+ xp = datetime(2012, 1, 1)
896
+ for f in freq_lst:
897
+ p = Period("2012", freq=f)
898
+ assert p.start_time == xp
899
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
900
+ assert Period("2012", freq="B").start_time == datetime(2012, 1, 2)
901
+ assert Period("2012", freq="W").start_time == datetime(2011, 12, 26)
902
+
903
+ def test_end_time(self):
904
+ p = Period("2012", freq="Y")
905
+
906
+ def _ex(*args):
907
+ return Timestamp(Timestamp(datetime(*args)).as_unit("ns")._value - 1)
908
+
909
+ xp = _ex(2013, 1, 1)
910
+ assert xp == p.end_time
911
+
912
+ p = Period("2012", freq="Q")
913
+ xp = _ex(2012, 4, 1)
914
+ assert xp == p.end_time
915
+
916
+ p = Period("2012", freq="M")
917
+ xp = _ex(2012, 2, 1)
918
+ assert xp == p.end_time
919
+
920
+ p = Period("2012", freq="D")
921
+ xp = _ex(2012, 1, 2)
922
+ assert xp == p.end_time
923
+
924
+ p = Period("2012", freq="h")
925
+ xp = _ex(2012, 1, 1, 1)
926
+ assert xp == p.end_time
927
+
928
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
929
+ p = Period("2012", freq="B")
930
+ xp = _ex(2012, 1, 3)
931
+ assert xp == p.end_time
932
+
933
+ p = Period("2012", freq="W")
934
+ xp = _ex(2012, 1, 2)
935
+ assert xp == p.end_time
936
+
937
+ # Test for GH 11738
938
+ p = Period("2012", freq="15D")
939
+ xp = _ex(2012, 1, 16)
940
+ assert xp == p.end_time
941
+
942
+ p = Period("2012", freq="1D1h")
943
+ xp = _ex(2012, 1, 2, 1)
944
+ assert xp == p.end_time
945
+
946
+ p = Period("2012", freq="1h1D")
947
+ xp = _ex(2012, 1, 2, 1)
948
+ assert xp == p.end_time
949
+
950
+ def test_end_time_business_friday(self):
951
+ # GH#34449
952
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
953
+ per = Period("1990-01-05", "B")
954
+ result = per.end_time
955
+
956
+ expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1)
957
+ assert result == expected
958
+
959
+ def test_anchor_week_end_time(self):
960
+ def _ex(*args):
961
+ return Timestamp(Timestamp(datetime(*args)).as_unit("ns")._value - 1)
962
+
963
+ p = Period("2013-1-1", "W-SAT")
964
+ xp = _ex(2013, 1, 6)
965
+ assert p.end_time == xp
966
+
967
+ def test_properties_annually(self):
968
+ # Test properties on Periods with annually frequency.
969
+ a_date = Period(freq="Y", year=2007)
970
+ assert a_date.year == 2007
971
+
972
+ def test_properties_quarterly(self):
973
+ # Test properties on Periods with daily frequency.
974
+ qedec_date = Period(freq="Q-DEC", year=2007, quarter=1)
975
+ qejan_date = Period(freq="Q-JAN", year=2007, quarter=1)
976
+ qejun_date = Period(freq="Q-JUN", year=2007, quarter=1)
977
+ #
978
+ for x in range(3):
979
+ for qd in (qedec_date, qejan_date, qejun_date):
980
+ assert (qd + x).qyear == 2007
981
+ assert (qd + x).quarter == x + 1
982
+
983
+ def test_properties_monthly(self):
984
+ # Test properties on Periods with daily frequency.
985
+ m_date = Period(freq="M", year=2007, month=1)
986
+ for x in range(11):
987
+ m_ival_x = m_date + x
988
+ assert m_ival_x.year == 2007
989
+ if 1 <= x + 1 <= 3:
990
+ assert m_ival_x.quarter == 1
991
+ elif 4 <= x + 1 <= 6:
992
+ assert m_ival_x.quarter == 2
993
+ elif 7 <= x + 1 <= 9:
994
+ assert m_ival_x.quarter == 3
995
+ elif 10 <= x + 1 <= 12:
996
+ assert m_ival_x.quarter == 4
997
+ assert m_ival_x.month == x + 1
998
+
999
+ def test_properties_weekly(self):
1000
+ # Test properties on Periods with daily frequency.
1001
+ w_date = Period(freq="W", year=2007, month=1, day=7)
1002
+ #
1003
+ assert w_date.year == 2007
1004
+ assert w_date.quarter == 1
1005
+ assert w_date.month == 1
1006
+ assert w_date.week == 1
1007
+ assert (w_date - 1).week == 52
1008
+ assert w_date.days_in_month == 31
1009
+ assert Period(freq="W", year=2012, month=2, day=1).days_in_month == 29
1010
+
1011
+ def test_properties_weekly_legacy(self):
1012
+ # Test properties on Periods with daily frequency.
1013
+ w_date = Period(freq="W", year=2007, month=1, day=7)
1014
+ assert w_date.year == 2007
1015
+ assert w_date.quarter == 1
1016
+ assert w_date.month == 1
1017
+ assert w_date.week == 1
1018
+ assert (w_date - 1).week == 52
1019
+ assert w_date.days_in_month == 31
1020
+
1021
+ exp = Period(freq="W", year=2012, month=2, day=1)
1022
+ assert exp.days_in_month == 29
1023
+
1024
+ msg = INVALID_FREQ_ERR_MSG
1025
+ with pytest.raises(ValueError, match=msg):
1026
+ Period(freq="WK", year=2007, month=1, day=7)
1027
+
1028
+ def test_properties_daily(self):
1029
+ # Test properties on Periods with daily frequency.
1030
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
1031
+ b_date = Period(freq="B", year=2007, month=1, day=1)
1032
+ #
1033
+ assert b_date.year == 2007
1034
+ assert b_date.quarter == 1
1035
+ assert b_date.month == 1
1036
+ assert b_date.day == 1
1037
+ assert b_date.weekday == 0
1038
+ assert b_date.dayofyear == 1
1039
+ assert b_date.days_in_month == 31
1040
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
1041
+ assert Period(freq="B", year=2012, month=2, day=1).days_in_month == 29
1042
+
1043
+ d_date = Period(freq="D", year=2007, month=1, day=1)
1044
+
1045
+ assert d_date.year == 2007
1046
+ assert d_date.quarter == 1
1047
+ assert d_date.month == 1
1048
+ assert d_date.day == 1
1049
+ assert d_date.weekday == 0
1050
+ assert d_date.dayofyear == 1
1051
+ assert d_date.days_in_month == 31
1052
+ assert Period(freq="D", year=2012, month=2, day=1).days_in_month == 29
1053
+
1054
+ def test_properties_hourly(self):
1055
+ # Test properties on Periods with hourly frequency.
1056
+ h_date1 = Period(freq="h", year=2007, month=1, day=1, hour=0)
1057
+ h_date2 = Period(freq="2h", year=2007, month=1, day=1, hour=0)
1058
+
1059
+ for h_date in [h_date1, h_date2]:
1060
+ assert h_date.year == 2007
1061
+ assert h_date.quarter == 1
1062
+ assert h_date.month == 1
1063
+ assert h_date.day == 1
1064
+ assert h_date.weekday == 0
1065
+ assert h_date.dayofyear == 1
1066
+ assert h_date.hour == 0
1067
+ assert h_date.days_in_month == 31
1068
+ assert (
1069
+ Period(freq="h", year=2012, month=2, day=1, hour=0).days_in_month == 29
1070
+ )
1071
+
1072
+ def test_properties_minutely(self):
1073
+ # Test properties on Periods with minutely frequency.
1074
+ t_date = Period(freq="Min", year=2007, month=1, day=1, hour=0, minute=0)
1075
+ #
1076
+ assert t_date.quarter == 1
1077
+ assert t_date.month == 1
1078
+ assert t_date.day == 1
1079
+ assert t_date.weekday == 0
1080
+ assert t_date.dayofyear == 1
1081
+ assert t_date.hour == 0
1082
+ assert t_date.minute == 0
1083
+ assert t_date.days_in_month == 31
1084
+ assert (
1085
+ Period(freq="D", year=2012, month=2, day=1, hour=0, minute=0).days_in_month
1086
+ == 29
1087
+ )
1088
+
1089
+ def test_properties_secondly(self):
1090
+ # Test properties on Periods with secondly frequency.
1091
+ s_date = Period(
1092
+ freq="Min", year=2007, month=1, day=1, hour=0, minute=0, second=0
1093
+ )
1094
+ #
1095
+ assert s_date.year == 2007
1096
+ assert s_date.quarter == 1
1097
+ assert s_date.month == 1
1098
+ assert s_date.day == 1
1099
+ assert s_date.weekday == 0
1100
+ assert s_date.dayofyear == 1
1101
+ assert s_date.hour == 0
1102
+ assert s_date.minute == 0
1103
+ assert s_date.second == 0
1104
+ assert s_date.days_in_month == 31
1105
+ assert (
1106
+ Period(
1107
+ freq="Min", year=2012, month=2, day=1, hour=0, minute=0, second=0
1108
+ ).days_in_month
1109
+ == 29
1110
+ )
1111
+
1112
+
1113
+ class TestPeriodComparisons:
1114
+ def test_sort_periods(self):
1115
+ jan = Period("2000-01", "M")
1116
+ feb = Period("2000-02", "M")
1117
+ mar = Period("2000-03", "M")
1118
+ periods = [mar, jan, feb]
1119
+ correctPeriods = [jan, feb, mar]
1120
+ assert sorted(periods) == correctPeriods
1121
+
1122
+
1123
+ def test_period_immutable():
1124
+ # see gh-17116
1125
+ msg = "not writable"
1126
+
1127
+ per = Period("2014Q1")
1128
+ with pytest.raises(AttributeError, match=msg):
1129
+ per.ordinal = 14
1130
+
1131
+ freq = per.freq
1132
+ with pytest.raises(AttributeError, match=msg):
1133
+ per.freq = 2 * freq
1134
+
1135
+
1136
+ def test_small_year_parsing():
1137
+ per1 = Period("0001-01-07", "D")
1138
+ assert per1.year == 1
1139
+ assert per1.day == 7
1140
+
1141
+
1142
+ def test_negone_ordinals():
1143
+ freqs = ["Y", "M", "Q", "D", "h", "min", "s"]
1144
+
1145
+ period = Period(ordinal=-1, freq="D")
1146
+ for freq in freqs:
1147
+ repr(period.asfreq(freq))
1148
+
1149
+ for freq in freqs:
1150
+ period = Period(ordinal=-1, freq=freq)
1151
+ repr(period)
1152
+ assert period.year == 1969
1153
+
1154
+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):
1155
+ period = Period(ordinal=-1, freq="B")
1156
+ repr(period)
1157
+ period = Period(ordinal=-1, freq="W")
1158
+ repr(period)
shared/package-files/00/007b4b4429d075e6397d074c248b6780debb3c1565c569f612aff4b9ae159492/blob ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.lexers.graph
3
+ ~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Lexers for graph query 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, include, bygroups, using, this, words
14
+ from pygments.token import Keyword, Punctuation, Comment, Operator, Name,\
15
+ String, Number, Whitespace
16
+
17
+
18
+ __all__ = ['CypherLexer']
19
+
20
+
21
+ class CypherLexer(RegexLexer):
22
+ """
23
+ For Cypher Query Language
24
+
25
+ For the Cypher version in Neo4j 3.3
26
+
27
+ .. versionadded:: 2.0
28
+ """
29
+ name = 'Cypher'
30
+ url = 'https://neo4j.com/docs/developer-manual/3.3/cypher/'
31
+ aliases = ['cypher']
32
+ filenames = ['*.cyp', '*.cypher']
33
+
34
+ flags = re.MULTILINE | re.IGNORECASE
35
+
36
+ tokens = {
37
+ 'root': [
38
+ include('comment'),
39
+ include('clauses'),
40
+ include('keywords'),
41
+ include('relations'),
42
+ include('strings'),
43
+ include('whitespace'),
44
+ include('barewords'),
45
+ ],
46
+ 'comment': [
47
+ (r'^.*//.*$', Comment.Single),
48
+ ],
49
+ 'keywords': [
50
+ (r'(create|order|match|limit|set|skip|start|return|with|where|'
51
+ r'delete|foreach|not|by|true|false)\b', Keyword),
52
+ ],
53
+ 'clauses': [
54
+ # based on https://neo4j.com/docs/cypher-refcard/3.3/
55
+ (r'(create)(\s+)(index|unique)\b',
56
+ bygroups(Keyword, Whitespace, Keyword)),
57
+ (r'(drop)(\s+)(contraint|index)(\s+)(on)\b',
58
+ bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
59
+ (r'(ends)(\s+)(with)\b',
60
+ bygroups(Keyword, Whitespace, Keyword)),
61
+ (r'(is)(\s+)(node)(\s+)(key)\b',
62
+ bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
63
+ (r'(is)(\s+)(null|unique)\b',
64
+ bygroups(Keyword, Whitespace, Keyword)),
65
+ (r'(load)(\s+)(csv)(\s+)(from)\b',
66
+ bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
67
+ (r'(on)(\s+)(match|create)\b',
68
+ bygroups(Keyword, Whitespace, Keyword)),
69
+ (r'(optional)(\s+)(match)\b',
70
+ bygroups(Keyword, Whitespace, Keyword)),
71
+ (r'(order)(\s+)(by)\b',
72
+ bygroups(Keyword, Whitespace, Keyword)),
73
+ (r'(starts)(\s+)(with)\b',
74
+ bygroups(Keyword, Whitespace, Keyword)),
75
+ (r'(union)(\s+)(all)\b',
76
+ bygroups(Keyword, Whitespace, Keyword)),
77
+ (r'(using)(\s+)(periodic)(\s+)(commit)\b',
78
+ bygroups(Keyword, Whitespace, Keyword, Whitespace, Keyword)),
79
+ (words((
80
+ 'all', 'any', 'as', 'asc', 'ascending', 'assert', 'call', 'case', 'create',
81
+ 'delete', 'desc', 'descending', 'distinct', 'end', 'fieldterminator',
82
+ 'foreach', 'in', 'limit', 'match', 'merge', 'none', 'not', 'null',
83
+ 'remove', 'return', 'set', 'skip', 'single', 'start', 'then', 'union',
84
+ 'unwind', 'yield', 'where', 'when', 'with'), suffix=r'\b'), Keyword),
85
+ ],
86
+ 'relations': [
87
+ (r'(-\[)(.*?)(\]->)', bygroups(Operator, using(this), Operator)),
88
+ (r'(<-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)),
89
+ (r'(-\[)(.*?)(\]-)', bygroups(Operator, using(this), Operator)),
90
+ (r'-->|<--|\[|\]', Operator),
91
+ (r'<|>|<>|=|<=|=>|\(|\)|\||:|,|;', Punctuation),
92
+ (r'[.*{}]', Punctuation),
93
+ ],
94
+ 'strings': [
95
+ (r'"(?:\\[tbnrf\'"\\]|[^\\"])*"', String),
96
+ (r'`(?:``|[^`])+`', Name.Variable),
97
+ ],
98
+ 'whitespace': [
99
+ (r'\s+', Whitespace),
100
+ ],
101
+ 'barewords': [
102
+ (r'[a-z]\w*', Name),
103
+ (r'\d+', Number),
104
+ ],
105
+ }
shared/package-files/00/007bc30a58fa40a996e772047120de4eaf31f5110e4f9c3b5f93fcdfbe2eaca1/blob ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT)
2
+
3
+ Copyright 2016, latex2sympy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
shared/package-files/00/007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:007c7273f4f4d627c319bd19a7be1e7c291bf3de21e62e9ea14cb159d8dda003
3
+ size 458840
shared/package-files/00/007c797f91b0f387ba6c88c56859ecebbbb6a888d34644952179c8dcd9859cfb/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _has_compatible_shallow_copy_type {
18
+ using schema = bool (const at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_has_compatible_shallow_copy_type")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_has_compatible_shallow_copy_type(Tensor self, Tensor from) -> bool")
24
+ static bool call(const at::Tensor & self, const at::Tensor & from);
25
+ static bool redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & from);
26
+ };
27
+
28
+ }} // namespace at::_ops
shared/package-files/00/007c7f5b6c46e0911ccf5c4aa0de53c021d513af943b63e2301cb29e47784cf1/blob ADDED
Binary file (1.44 kB). View file
 
shared/package-files/00/00802e742f5fefce24704cee868f0689753adef8f64e1462b4ace797b22692ae/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from pandas.io.sas.sasreader import read_sas
2
+
3
+ __all__ = ["read_sas"]
shared/package-files/00/0081cfe13348b3509eaa122039b1f26344b69cd181a3a70808bff78694738fda/blob ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ import numpy as np
4
+
5
+ __all__ = [
6
+ 'geterr',
7
+ 'seterr',
8
+ 'errstate',
9
+ 'agm',
10
+ 'airy',
11
+ 'airye',
12
+ 'bdtr',
13
+ 'bdtrc',
14
+ 'bdtri',
15
+ 'bdtrik',
16
+ 'bdtrin',
17
+ 'bei',
18
+ 'beip',
19
+ 'ber',
20
+ 'berp',
21
+ 'besselpoly',
22
+ 'beta',
23
+ 'betainc',
24
+ 'betaincc',
25
+ 'betainccinv',
26
+ 'betaincinv',
27
+ 'betaln',
28
+ 'binom',
29
+ 'boxcox',
30
+ 'boxcox1p',
31
+ 'btdtria',
32
+ 'btdtrib',
33
+ 'cbrt',
34
+ 'chdtr',
35
+ 'chdtrc',
36
+ 'chdtri',
37
+ 'chdtriv',
38
+ 'chndtr',
39
+ 'chndtridf',
40
+ 'chndtrinc',
41
+ 'chndtrix',
42
+ 'cosdg',
43
+ 'cosm1',
44
+ 'cotdg',
45
+ 'dawsn',
46
+ 'ellipe',
47
+ 'ellipeinc',
48
+ 'ellipj',
49
+ 'ellipk',
50
+ 'ellipkinc',
51
+ 'ellipkm1',
52
+ 'elliprc',
53
+ 'elliprd',
54
+ 'elliprf',
55
+ 'elliprg',
56
+ 'elliprj',
57
+ 'entr',
58
+ 'erf',
59
+ 'erfc',
60
+ 'erfcinv',
61
+ 'erfcx',
62
+ 'erfi',
63
+ 'erfinv',
64
+ 'eval_chebyc',
65
+ 'eval_chebys',
66
+ 'eval_chebyt',
67
+ 'eval_chebyu',
68
+ 'eval_gegenbauer',
69
+ 'eval_genlaguerre',
70
+ 'eval_hermite',
71
+ 'eval_hermitenorm',
72
+ 'eval_jacobi',
73
+ 'eval_laguerre',
74
+ 'eval_legendre',
75
+ 'eval_sh_chebyt',
76
+ 'eval_sh_chebyu',
77
+ 'eval_sh_jacobi',
78
+ 'eval_sh_legendre',
79
+ 'exp1',
80
+ 'exp10',
81
+ 'exp2',
82
+ 'expi',
83
+ 'expit',
84
+ 'expm1',
85
+ 'expn',
86
+ 'exprel',
87
+ 'fdtr',
88
+ 'fdtrc',
89
+ 'fdtri',
90
+ 'fdtridfd',
91
+ 'fresnel',
92
+ 'gamma',
93
+ 'gammainc',
94
+ 'gammaincc',
95
+ 'gammainccinv',
96
+ 'gammaincinv',
97
+ 'gammaln',
98
+ 'gammasgn',
99
+ 'gdtr',
100
+ 'gdtrc',
101
+ 'gdtria',
102
+ 'gdtrib',
103
+ 'gdtrix',
104
+ 'hankel1',
105
+ 'hankel1e',
106
+ 'hankel2',
107
+ 'hankel2e',
108
+ 'huber',
109
+ 'hyp0f1',
110
+ 'hyp1f1',
111
+ 'hyp2f1',
112
+ 'hyperu',
113
+ 'i0',
114
+ 'i0e',
115
+ 'i1',
116
+ 'i1e',
117
+ 'inv_boxcox',
118
+ 'inv_boxcox1p',
119
+ 'it2i0k0',
120
+ 'it2j0y0',
121
+ 'it2struve0',
122
+ 'itairy',
123
+ 'iti0k0',
124
+ 'itj0y0',
125
+ 'itmodstruve0',
126
+ 'itstruve0',
127
+ 'iv',
128
+ 'ive',
129
+ 'j0',
130
+ 'j1',
131
+ 'jn',
132
+ 'jv',
133
+ 'jve',
134
+ 'k0',
135
+ 'k0e',
136
+ 'k1',
137
+ 'k1e',
138
+ 'kei',
139
+ 'keip',
140
+ 'kelvin',
141
+ 'ker',
142
+ 'kerp',
143
+ 'kl_div',
144
+ 'kn',
145
+ 'kolmogi',
146
+ 'kolmogorov',
147
+ 'kv',
148
+ 'kve',
149
+ 'log1p',
150
+ 'log_expit',
151
+ 'log_ndtr',
152
+ 'log_wright_bessel',
153
+ 'loggamma',
154
+ 'logit',
155
+ 'lpmv',
156
+ 'mathieu_a',
157
+ 'mathieu_b',
158
+ 'mathieu_cem',
159
+ 'mathieu_modcem1',
160
+ 'mathieu_modcem2',
161
+ 'mathieu_modsem1',
162
+ 'mathieu_modsem2',
163
+ 'mathieu_sem',
164
+ 'modfresnelm',
165
+ 'modfresnelp',
166
+ 'modstruve',
167
+ 'nbdtr',
168
+ 'nbdtrc',
169
+ 'nbdtri',
170
+ 'nbdtrik',
171
+ 'nbdtrin',
172
+ 'ncfdtr',
173
+ 'ncfdtri',
174
+ 'ncfdtridfd',
175
+ 'ncfdtridfn',
176
+ 'ncfdtrinc',
177
+ 'nctdtr',
178
+ 'nctdtridf',
179
+ 'nctdtrinc',
180
+ 'nctdtrit',
181
+ 'ndtr',
182
+ 'ndtri',
183
+ 'ndtri_exp',
184
+ 'nrdtrimn',
185
+ 'nrdtrisd',
186
+ 'obl_ang1',
187
+ 'obl_ang1_cv',
188
+ 'obl_cv',
189
+ 'obl_rad1',
190
+ 'obl_rad1_cv',
191
+ 'obl_rad2',
192
+ 'obl_rad2_cv',
193
+ 'owens_t',
194
+ 'pbdv',
195
+ 'pbvv',
196
+ 'pbwa',
197
+ 'pdtr',
198
+ 'pdtrc',
199
+ 'pdtri',
200
+ 'pdtrik',
201
+ 'poch',
202
+ 'powm1',
203
+ 'pro_ang1',
204
+ 'pro_ang1_cv',
205
+ 'pro_cv',
206
+ 'pro_rad1',
207
+ 'pro_rad1_cv',
208
+ 'pro_rad2',
209
+ 'pro_rad2_cv',
210
+ 'pseudo_huber',
211
+ 'psi',
212
+ 'radian',
213
+ 'rel_entr',
214
+ 'rgamma',
215
+ 'round',
216
+ 'shichi',
217
+ 'sici',
218
+ 'sindg',
219
+ 'smirnov',
220
+ 'smirnovi',
221
+ 'spence',
222
+ 'sph_harm',
223
+ 'stdtr',
224
+ 'stdtridf',
225
+ 'stdtrit',
226
+ 'struve',
227
+ 'tandg',
228
+ 'tklmbda',
229
+ 'voigt_profile',
230
+ 'wofz',
231
+ 'wright_bessel',
232
+ 'wrightomega',
233
+ 'xlog1py',
234
+ 'xlogy',
235
+ 'y0',
236
+ 'y1',
237
+ 'yn',
238
+ 'yv',
239
+ 'yve',
240
+ 'zetac'
241
+ ]
242
+
243
+ def geterr() -> dict[str, str]: ...
244
+ def seterr(**kwargs: str) -> dict[str, str]: ...
245
+
246
+ class errstate:
247
+ def __init__(self, **kargs: str) -> None: ...
248
+ def __enter__(self) -> None: ...
249
+ def __exit__(
250
+ self,
251
+ exc_type: Any, # Unused
252
+ exc_value: Any, # Unused
253
+ traceback: Any, # Unused
254
+ ) -> None: ...
255
+
256
+ _cosine_cdf: np.ufunc
257
+ _cosine_invcdf: np.ufunc
258
+ _cospi: np.ufunc
259
+ _ellip_harm: np.ufunc
260
+ _factorial: np.ufunc
261
+ _igam_fac: np.ufunc
262
+ _kolmogc: np.ufunc
263
+ _kolmogci: np.ufunc
264
+ _kolmogp: np.ufunc
265
+ _lambertw: np.ufunc
266
+ _lanczos_sum_expg_scaled: np.ufunc
267
+ _lgam1p: np.ufunc
268
+ _log1pmx: np.ufunc
269
+ _riemann_zeta: np.ufunc
270
+ _scaled_exp1: np.ufunc
271
+ _sf_error_test_function: np.ufunc
272
+ _sinpi: np.ufunc
273
+ _smirnovc: np.ufunc
274
+ _smirnovci: np.ufunc
275
+ _smirnovp: np.ufunc
276
+ _spherical_in: np.ufunc
277
+ _spherical_in_d: np.ufunc
278
+ _spherical_jn: np.ufunc
279
+ _spherical_jn_d: np.ufunc
280
+ _spherical_kn: np.ufunc
281
+ _spherical_kn_d: np.ufunc
282
+ _spherical_yn: np.ufunc
283
+ _spherical_yn_d: np.ufunc
284
+ _stirling2_inexact: np.ufunc
285
+ _struve_asymp_large_z: np.ufunc
286
+ _struve_bessel_series: np.ufunc
287
+ _struve_power_series: np.ufunc
288
+ _zeta: np.ufunc
289
+ agm: np.ufunc
290
+ airy: np.ufunc
291
+ airye: np.ufunc
292
+ bdtr: np.ufunc
293
+ bdtrc: np.ufunc
294
+ bdtri: np.ufunc
295
+ bdtrik: np.ufunc
296
+ bdtrin: np.ufunc
297
+ bei: np.ufunc
298
+ beip: np.ufunc
299
+ ber: np.ufunc
300
+ berp: np.ufunc
301
+ besselpoly: np.ufunc
302
+ beta: np.ufunc
303
+ betainc: np.ufunc
304
+ betaincc: np.ufunc
305
+ betainccinv: np.ufunc
306
+ betaincinv: np.ufunc
307
+ betaln: np.ufunc
308
+ binom: np.ufunc
309
+ boxcox1p: np.ufunc
310
+ boxcox: np.ufunc
311
+ btdtria: np.ufunc
312
+ btdtrib: np.ufunc
313
+ cbrt: np.ufunc
314
+ chdtr: np.ufunc
315
+ chdtrc: np.ufunc
316
+ chdtri: np.ufunc
317
+ chdtriv: np.ufunc
318
+ chndtr: np.ufunc
319
+ chndtridf: np.ufunc
320
+ chndtrinc: np.ufunc
321
+ chndtrix: np.ufunc
322
+ cosdg: np.ufunc
323
+ cosm1: np.ufunc
324
+ cotdg: np.ufunc
325
+ dawsn: np.ufunc
326
+ ellipe: np.ufunc
327
+ ellipeinc: np.ufunc
328
+ ellipj: np.ufunc
329
+ ellipk: np.ufunc
330
+ ellipkinc: np.ufunc
331
+ ellipkm1: np.ufunc
332
+ elliprc: np.ufunc
333
+ elliprd: np.ufunc
334
+ elliprf: np.ufunc
335
+ elliprg: np.ufunc
336
+ elliprj: np.ufunc
337
+ entr: np.ufunc
338
+ erf: np.ufunc
339
+ erfc: np.ufunc
340
+ erfcinv: np.ufunc
341
+ erfcx: np.ufunc
342
+ erfi: np.ufunc
343
+ erfinv: np.ufunc
344
+ eval_chebyc: np.ufunc
345
+ eval_chebys: np.ufunc
346
+ eval_chebyt: np.ufunc
347
+ eval_chebyu: np.ufunc
348
+ eval_gegenbauer: np.ufunc
349
+ eval_genlaguerre: np.ufunc
350
+ eval_hermite: np.ufunc
351
+ eval_hermitenorm: np.ufunc
352
+ eval_jacobi: np.ufunc
353
+ eval_laguerre: np.ufunc
354
+ eval_legendre: np.ufunc
355
+ eval_sh_chebyt: np.ufunc
356
+ eval_sh_chebyu: np.ufunc
357
+ eval_sh_jacobi: np.ufunc
358
+ eval_sh_legendre: np.ufunc
359
+ exp10: np.ufunc
360
+ exp1: np.ufunc
361
+ exp2: np.ufunc
362
+ expi: np.ufunc
363
+ expit: np.ufunc
364
+ expm1: np.ufunc
365
+ expn: np.ufunc
366
+ exprel: np.ufunc
367
+ fdtr: np.ufunc
368
+ fdtrc: np.ufunc
369
+ fdtri: np.ufunc
370
+ fdtridfd: np.ufunc
371
+ fresnel: np.ufunc
372
+ gamma: np.ufunc
373
+ gammainc: np.ufunc
374
+ gammaincc: np.ufunc
375
+ gammainccinv: np.ufunc
376
+ gammaincinv: np.ufunc
377
+ gammaln: np.ufunc
378
+ gammasgn: np.ufunc
379
+ gdtr: np.ufunc
380
+ gdtrc: np.ufunc
381
+ gdtria: np.ufunc
382
+ gdtrib: np.ufunc
383
+ gdtrix: np.ufunc
384
+ hankel1: np.ufunc
385
+ hankel1e: np.ufunc
386
+ hankel2: np.ufunc
387
+ hankel2e: np.ufunc
388
+ huber: np.ufunc
389
+ hyp0f1: np.ufunc
390
+ hyp1f1: np.ufunc
391
+ hyp2f1: np.ufunc
392
+ hyperu: np.ufunc
393
+ i0: np.ufunc
394
+ i0e: np.ufunc
395
+ i1: np.ufunc
396
+ i1e: np.ufunc
397
+ inv_boxcox1p: np.ufunc
398
+ inv_boxcox: np.ufunc
399
+ it2i0k0: np.ufunc
400
+ it2j0y0: np.ufunc
401
+ it2struve0: np.ufunc
402
+ itairy: np.ufunc
403
+ iti0k0: np.ufunc
404
+ itj0y0: np.ufunc
405
+ itmodstruve0: np.ufunc
406
+ itstruve0: np.ufunc
407
+ iv: np.ufunc
408
+ ive: np.ufunc
409
+ j0: np.ufunc
410
+ j1: np.ufunc
411
+ jn: np.ufunc
412
+ jv: np.ufunc
413
+ jve: np.ufunc
414
+ k0: np.ufunc
415
+ k0e: np.ufunc
416
+ k1: np.ufunc
417
+ k1e: np.ufunc
418
+ kei: np.ufunc
419
+ keip: np.ufunc
420
+ kelvin: np.ufunc
421
+ ker: np.ufunc
422
+ kerp: np.ufunc
423
+ kl_div: np.ufunc
424
+ kn: np.ufunc
425
+ kolmogi: np.ufunc
426
+ kolmogorov: np.ufunc
427
+ kv: np.ufunc
428
+ kve: np.ufunc
429
+ log1p: np.ufunc
430
+ log_expit: np.ufunc
431
+ log_ndtr: np.ufunc
432
+ log_wright_bessel: np.ufunc
433
+ loggamma: np.ufunc
434
+ logit: np.ufunc
435
+ lpmv: np.ufunc
436
+ mathieu_a: np.ufunc
437
+ mathieu_b: np.ufunc
438
+ mathieu_cem: np.ufunc
439
+ mathieu_modcem1: np.ufunc
440
+ mathieu_modcem2: np.ufunc
441
+ mathieu_modsem1: np.ufunc
442
+ mathieu_modsem2: np.ufunc
443
+ mathieu_sem: np.ufunc
444
+ modfresnelm: np.ufunc
445
+ modfresnelp: np.ufunc
446
+ modstruve: np.ufunc
447
+ nbdtr: np.ufunc
448
+ nbdtrc: np.ufunc
449
+ nbdtri: np.ufunc
450
+ nbdtrik: np.ufunc
451
+ nbdtrin: np.ufunc
452
+ ncfdtr: np.ufunc
453
+ ncfdtri: np.ufunc
454
+ ncfdtridfd: np.ufunc
455
+ ncfdtridfn: np.ufunc
456
+ ncfdtrinc: np.ufunc
457
+ nctdtr: np.ufunc
458
+ nctdtridf: np.ufunc
459
+ nctdtrinc: np.ufunc
460
+ nctdtrit: np.ufunc
461
+ ndtr: np.ufunc
462
+ ndtri: np.ufunc
463
+ ndtri_exp: np.ufunc
464
+ nrdtrimn: np.ufunc
465
+ nrdtrisd: np.ufunc
466
+ obl_ang1: np.ufunc
467
+ obl_ang1_cv: np.ufunc
468
+ obl_cv: np.ufunc
469
+ obl_rad1: np.ufunc
470
+ obl_rad1_cv: np.ufunc
471
+ obl_rad2: np.ufunc
472
+ obl_rad2_cv: np.ufunc
473
+ owens_t: np.ufunc
474
+ pbdv: np.ufunc
475
+ pbvv: np.ufunc
476
+ pbwa: np.ufunc
477
+ pdtr: np.ufunc
478
+ pdtrc: np.ufunc
479
+ pdtri: np.ufunc
480
+ pdtrik: np.ufunc
481
+ poch: np.ufunc
482
+ powm1: np.ufunc
483
+ pro_ang1: np.ufunc
484
+ pro_ang1_cv: np.ufunc
485
+ pro_cv: np.ufunc
486
+ pro_rad1: np.ufunc
487
+ pro_rad1_cv: np.ufunc
488
+ pro_rad2: np.ufunc
489
+ pro_rad2_cv: np.ufunc
490
+ pseudo_huber: np.ufunc
491
+ psi: np.ufunc
492
+ radian: np.ufunc
493
+ rel_entr: np.ufunc
494
+ rgamma: np.ufunc
495
+ round: np.ufunc
496
+ shichi: np.ufunc
497
+ sici: np.ufunc
498
+ sindg: np.ufunc
499
+ smirnov: np.ufunc
500
+ smirnovi: np.ufunc
501
+ spence: np.ufunc
502
+ sph_harm: np.ufunc
503
+ stdtr: np.ufunc
504
+ stdtridf: np.ufunc
505
+ stdtrit: np.ufunc
506
+ struve: np.ufunc
507
+ tandg: np.ufunc
508
+ tklmbda: np.ufunc
509
+ voigt_profile: np.ufunc
510
+ wofz: np.ufunc
511
+ wright_bessel: np.ufunc
512
+ wrightomega: np.ufunc
513
+ xlog1py: np.ufunc
514
+ xlogy: np.ufunc
515
+ y0: np.ufunc
516
+ y1: np.ufunc
517
+ yn: np.ufunc
518
+ yv: np.ufunc
519
+ yve: np.ufunc
520
+ zetac: np.ufunc
521
+
shared/package-files/00/00846343a0d9b42f0a65d83ae1122c698f533ef9883999234e7dc130c74e99fc/blob ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 smooth_l1_loss_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta);
20
+ TORCH_API at::Tensor & smooth_l1_loss_backward_out(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & target, int64_t reduction, double beta, at::Tensor & grad_input);
21
+ } // namespace native
22
+ } // namespace at
shared/package-files/00/00861efb625e1476b20218687baea5dc22afeb7d05aa1012f468c5ff6deb8784/blob ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API special_airy_ai {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_airy_ai")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_airy_ai(Tensor x) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & x);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x);
26
+ };
27
+
28
+ struct TORCH_API special_airy_ai_out {
29
+ using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_airy_ai")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_airy_ai.out(Tensor x, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & x, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & x, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops