s42chen commited on
Commit
47e8b09
·
verified ·
1 Parent(s): b6fa4a1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. shared/package-files/3f/3f051948b4ef2c722e1d1eec2f3a4e234c9dec9301a6ad0461c8452bd0386d8e/_n_a_m_e.py +1241 -0
  2. shared/package-files/3f/3f0701b7b41a26021e5c42616abc1af3eed301b0685d6d237010f4511b8abf81/import_export_constants.h +21 -0
  3. shared/package-files/3f/3f0849c019b6924e2e33285d3b96ab42cf0896a497daf37486f53323b607aabc/test_angle_helper.py +141 -0
  4. shared/package-files/3f/3f0a29b3c98805781fc6f1cef60f53138080ec928b041eabba9cd21fadab2253/special_chebyshev_polynomial_t_cpu_dispatch.h +25 -0
  5. shared/package-files/3f/3f0c7dd171fb611445e039b5994341b483fcc5bfb9783c138ba6f0975c7893fa/modulefinder.pyi +76 -0
  6. shared/package-files/3f/3f1770af1d7447fa2bb0b54836ca02b32f932fa6bde84ba646c10d7f61b5d411/watchers.pyi +21 -0
  7. shared/package-files/3f/3f17cf8f6c84fd5daec324800208078d605c416fe1a9ed9303cce8621833e768/expand_copy_compositeexplicitautograd_dispatch.h +26 -0
  8. shared/package-files/3f/3f1863a3715b06b6dd8332b0f9b69d9b23b68b33bd60345737a58731891ecce4/origibmpc3 +0 -0
  9. shared/package-files/3f/3f1863a3715b06b6dd8332b0f9b69d9b23b68b33bd60345737a58731891ecce4/origpc3 +0 -0
  10. shared/package-files/3f/3f18d84ca22ea2ae382d3d92d891d6395f013850f4012aa3ab44b95417869053/X25.py +57 -0
  11. shared/package-files/3f/3f203a60ce527ca9d886ec763c05bf5b340621abb2f3f6b9564c016eec66b56b/datetime_registry.py +91 -0
  12. shared/package-files/3f/3f224d332f251c3b4aa5f1647349e433c1788cd2d9002e253d008dd4a9b86e98/errors.py +77 -0
  13. shared/package-files/3f/3f22b374b305c5881a2f615bf3c1d445c4ea33498cdb69914d034ab914f7b303/floor_divide_native.h +29 -0
  14. shared/package-files/3f/3f24a323933d367910f328abfb21f8d17891ef3867d941015de7293a5ba84ebc/LICENSE.txt +81 -0
  15. shared/package-files/3f/3f28597226b21f0aa459545533ee759220df1e1f79dd8f700630917241f54bf9/hardswish_backward_cuda_dispatch.h +23 -0
  16. shared/package-files/3f/3f2866cf8afd17df6d19aa655401db9eb1ea43afecdeb504e87cfa74cc87abd0/gcd_meta.h +27 -0
  17. shared/package-files/3f/3f28bd06e089bef590b9ed8c247d8bb1bf9f7caffd30a8d15468d8e4dbef8644/__init__.py +9 -0
  18. shared/package-files/3f/3f2a94602715ad97cc647a4fafd9d40f9dd91c9efb92c02ce197acb0fa72bf34/reflection_pad3d_native.h +26 -0
  19. shared/package-files/3f/3f2c9ab1b2e024418ffcff6c31631228cd9c561934c85ea9d2f1afb4c132b46f/rrt.py +33 -0
  20. shared/package-files/3f/3f2d3210d3e5c56a9f73bd34aed5cfbf6653acbf2d9e1d4747e2bfbd695b08a5/_ufuncs_cxx.pyx +466 -0
  21. shared/package-files/3f/3f2d5ce52bd7158adca0d27ea5e7848bc172626b819d0ad02b50cd64167e5509/Macros.h +546 -0
  22. shared/package-files/3f/3f2feb5d16c34cfd194ab341d8ee539a1e55f06e55f558971ff615e4f4d7f71c/backend_agg.py +528 -0
  23. shared/package-files/3f/3f30a4950dc015072ad42e81dc87c2814e75e74cdaf4334b4aa258db6f5e727d/aaa-20 +0 -0
  24. shared/package-files/3f/3f30f43004cc3632e33e2f465b919018be94a9cd944feb8fc27ce18bb4e4247f/kauers.py +51 -0
  25. shared/package-files/3f/3f33e456c34305487ac20cc566fabf60d6dad9b766c123bf1fc0542bd671032b/test_rolling.py +1979 -0
  26. shared/package-files/3f/3f34940216f1c7741230839d0db514a6ba364dbdea6ef5831723fcffa19f783d/_geometry.py +1401 -0
  27. shared/package-files/3f/3f37d7921a6eb05206570af356ca8b8258e5c9b37dd8e794d3f137ac7ba9da6d/forth.py +179 -0
  28. shared/package-files/3f/3f38e62c706da46eb935fcc8dacbe8937e5ea5d114ccee32bee39de85b413c2b/_nested_tensor_strides_compositeexplicitautograd_dispatch.h +24 -0
  29. shared/package-files/3f/3f39e95c3c5008c8c2f055fabd7abca29072ab93d8d49125c796e5bba908b6d0/functional.h +4 -0
  30. shared/package-files/3f/3f3c3ddcaf67201276f1ceba6be1959964a264e698c2d3990757ba3f4dda74e2/httplib.pyi +218 -0
  31. shared/package-files/3f/3f3d54d1819fbf94f2d77d432b9a777d8d0d9e91dfe745dd072406479a291f69/oshorts.py +22 -0
  32. shared/package-files/3f/3f3e14914d6ac7be766ed26d7853b2ac95507f7522634274525c681842344ecd/luarocks.py +393 -0
  33. shared/package-files/3f/3f3f193da2c9794d59bf040f0d0a9d350ecac123caea0d008628ea3ec8acbbb1/linalg_qr_ops.h +39 -0
  34. shared/package-files/3f/3f3feab50db45dcee100212f6e4da83500c4298c1b836f5ab79e1b85c017861e/_foreach_sinh_ops.h +50 -0
  35. shared/package-files/3f/3f42eca19e398012fb7242f896a42deed75bac70f8c6555885f7e684779e4ff5/top_level.txt +1 -0
  36. shared/package-files/3f/3f4337f6250bb1b9aed7b73d2be62f57f79998d119726f0579a06559f76432b3/special_ndtri_native.h +23 -0
  37. shared/package-files/3f/3f4bf12367dc9ddca6d545354b7ed703343342793263b62a00a9b19b6e3f82e8/_win32_console.py +662 -0
  38. shared/package-files/3f/3f4fd44aa7e975b4761bab0889d600f0494cf3e58376eedfbadaca12099e9555/patch.py +111 -0
  39. shared/package-files/3f/3f510f3d5da0e74593b7c51a5feea41684d9335c55aa8e92d87e8527a65dd5e7/filesave.pdf +70 -0
  40. shared/package-files/3f/3f5264efd080601f392fe3b729124aa6caafc15260aaa27fbb8e0d8a0196b1a0/test_polysys.py +178 -0
  41. shared/package-files/3f/3f5726aab02371a09d39b90d6757ba1e9fff669c41021431d22222a4e556f238/__init__.py +4 -0
  42. shared/package-files/3f/3f589029f5e5ec8bade99e58f7b4261abfd4aa2019eaa47e7a844cb5869c19f0/abc.py +111 -0
  43. shared/package-files/3f/3f58ae9d9d901b4bc5a5bd5038dfb80e7d7df52fc8e6ba697dda099a78cd0224/Types.h +12 -0
  44. shared/package-files/3f/3f5b5005469cead828149e0137c8962e3674655a1e8118cadfa572862cace2c3/vi200-rv +0 -0
  45. shared/package-files/3f/3f5e7fde03397994186fff8addcef4c4a75e20633cd6ee5602456163c7a2e0dd/fitpack2.py +29 -0
  46. shared/package-files/3f/3f5f0b88547cf2a3a5296b3712ae9ba7f2b7b22e9598dbf2d36918b084f7b473/Parallel-inl.h +93 -0
  47. shared/package-files/3f/3f5f56f73665f2d37410af8f6848b68081472f009baee4cc1149bbfc02c61fd4/test_astype.py +95 -0
  48. shared/package-files/3f/3f5f901d3e1aef5874bdb4513c722da054932f24b31f4ded8d7bc1b841dd2457/daft_extension.py +12 -0
  49. shared/package-files/3f/3f6006921760dd92ea5da41d7fcca875b96b0697601106412ca3cbd666f19857/sankey.pyi +61 -0
  50. shared/package-files/3f/3f60186df29e6686acbbd200e4b9d05d832f2abe26727e21492ac3f5885f4d70/special_laguerre_polynomial_l_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
shared/package-files/3f/3f051948b4ef2c722e1d1eec2f3a4e234c9dec9301a6ad0461c8452bd0386d8e/_n_a_m_e.py ADDED
@@ -0,0 +1,1241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ from __future__ import annotations
3
+
4
+ from fontTools.misc import sstruct
5
+ from fontTools.misc.textTools import (
6
+ bytechr,
7
+ byteord,
8
+ bytesjoin,
9
+ strjoin,
10
+ tobytes,
11
+ tostr,
12
+ safeEval,
13
+ )
14
+ from fontTools.misc.encodingTools import getEncoding
15
+ from fontTools.ttLib import newTable
16
+ from fontTools.ttLib.ttVisitor import TTVisitor
17
+ from fontTools import ttLib
18
+ import fontTools.ttLib.tables.otTables as otTables
19
+ from fontTools.ttLib.tables import C_P_A_L_
20
+ from . import DefaultTable
21
+ import struct
22
+ import logging
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+ nameRecordFormat = """
27
+ > # big endian
28
+ platformID: H
29
+ platEncID: H
30
+ langID: H
31
+ nameID: H
32
+ length: H
33
+ offset: H
34
+ """
35
+
36
+ nameRecordSize = sstruct.calcsize(nameRecordFormat)
37
+
38
+
39
+ class table__n_a_m_e(DefaultTable.DefaultTable):
40
+ """Naming table
41
+
42
+ The ``name`` table is used to store a variety of strings that can be
43
+ associated with user-facing font information. Records in the ``name``
44
+ table can be tagged with language tags to support multilingual naming
45
+ and can support platform-specific character-encoding variants.
46
+
47
+ See also https://learn.microsoft.com/en-us/typography/opentype/spec/name
48
+ """
49
+
50
+ dependencies = ["ltag"]
51
+
52
+ def __init__(self, tag=None):
53
+ super().__init__(tag)
54
+ self.names = []
55
+
56
+ def decompile(self, data, ttFont):
57
+ format, n, stringOffset = struct.unpack(b">HHH", data[:6])
58
+ expectedStringOffset = 6 + n * nameRecordSize
59
+ if stringOffset != expectedStringOffset:
60
+ log.error(
61
+ "'name' table stringOffset incorrect. Expected: %s; Actual: %s",
62
+ expectedStringOffset,
63
+ stringOffset,
64
+ )
65
+ stringData = data[stringOffset:]
66
+ data = data[6:]
67
+ self.names: list[NameRecord] = []
68
+ for i in range(n):
69
+ if len(data) < 12:
70
+ log.error("skipping malformed name record #%d", i)
71
+ continue
72
+ name, data = sstruct.unpack2(nameRecordFormat, data, NameRecord())
73
+ name.string = stringData[name.offset : name.offset + name.length]
74
+ if name.offset + name.length > len(stringData):
75
+ log.error("skipping malformed name record #%d", i)
76
+ continue
77
+ assert len(name.string) == name.length
78
+ # if (name.platEncID, name.platformID) in ((0, 0), (1, 3)):
79
+ # if len(name.string) % 2:
80
+ # print "2-byte string doesn't have even length!"
81
+ # print name.__dict__
82
+ del name.offset, name.length
83
+ self.names.append(name)
84
+
85
+ def compile(self, ttFont):
86
+ names = self.names
87
+ names.sort() # sort according to the spec; see NameRecord.__lt__()
88
+ stringData = b""
89
+ format = 0
90
+ n = len(names)
91
+ stringOffset = 6 + n * sstruct.calcsize(nameRecordFormat)
92
+ data = struct.pack(b">HHH", format, n, stringOffset)
93
+ lastoffset = 0
94
+ done = {} # remember the data so we can reuse the "pointers"
95
+ for name in names:
96
+ string = name.toBytes()
97
+ if string in done:
98
+ name.offset, name.length = done[string]
99
+ else:
100
+ name.offset, name.length = done[string] = len(stringData), len(string)
101
+ stringData = bytesjoin([stringData, string])
102
+ data = data + sstruct.pack(nameRecordFormat, name)
103
+ return data + stringData
104
+
105
+ def toXML(self, writer, ttFont):
106
+ for name in self.names:
107
+ name.toXML(writer, ttFont)
108
+
109
+ def fromXML(self, name, attrs, content, ttFont):
110
+ if name != "namerecord":
111
+ return # ignore unknown tags
112
+ name = NameRecord()
113
+ self.names.append(name)
114
+ name.fromXML(name, attrs, content, ttFont)
115
+
116
+ def getName(
117
+ self, nameID: int, platformID: int, platEncID: int, langID: int | None = None
118
+ ) -> "NameRecord | None":
119
+ for namerecord in self.names:
120
+ if (
121
+ namerecord.nameID == nameID
122
+ and namerecord.platformID == platformID
123
+ and namerecord.platEncID == platEncID
124
+ ):
125
+ if langID is None or namerecord.langID == langID:
126
+ return namerecord
127
+ return None # not found
128
+
129
+ def getDebugName(self, nameID: int) -> str | None:
130
+ englishName: str | None = None
131
+ someName: str | None = None
132
+ for name in self.names:
133
+ if name.nameID != nameID:
134
+ continue
135
+ try:
136
+ unistr = name.toUnicode()
137
+ except UnicodeDecodeError:
138
+ continue
139
+
140
+ someName = unistr
141
+ if (name.platformID, name.langID) in ((1, 0), (3, 0x409)):
142
+ englishName = unistr
143
+ break
144
+ if englishName:
145
+ return englishName
146
+ elif someName:
147
+ return someName
148
+ else:
149
+ return None
150
+
151
+ def getFirstDebugName(self, nameIDs):
152
+ for nameID in nameIDs:
153
+ name = self.getDebugName(nameID)
154
+ if name is not None:
155
+ return name
156
+ return None
157
+
158
+ def getBestFamilyName(self):
159
+ # 21 = WWS Family Name
160
+ # 16 = Typographic Family Name
161
+ # 1 = Family Name
162
+ return self.getFirstDebugName((21, 16, 1))
163
+
164
+ def getBestSubFamilyName(self):
165
+ # 22 = WWS SubFamily Name
166
+ # 17 = Typographic SubFamily Name
167
+ # 2 = SubFamily Name
168
+ return self.getFirstDebugName((22, 17, 2))
169
+
170
+ def getBestFullName(self):
171
+ # 4 = Full Name
172
+ # 6 = PostScript Name
173
+ for nameIDs in ((21, 22), (16, 17), (1, 2), (4,), (6,)):
174
+ if len(nameIDs) == 2:
175
+ name_fam = self.getDebugName(nameIDs[0])
176
+ name_subfam = self.getDebugName(nameIDs[1])
177
+ if None in [name_fam, name_subfam]:
178
+ continue # if any is None, skip
179
+ name = f"{name_fam} {name_subfam}"
180
+ if name_subfam.lower() == "regular":
181
+ name = f"{name_fam}"
182
+ return name
183
+ else:
184
+ name = self.getDebugName(nameIDs[0])
185
+ if name is not None:
186
+ return name
187
+ return None
188
+
189
+ def setName(self, string, nameID, platformID, platEncID, langID):
190
+ """Set the 'string' for the name record identified by 'nameID', 'platformID',
191
+ 'platEncID' and 'langID'. If a record with that nameID doesn't exist, create it
192
+ and append to the name table.
193
+
194
+ 'string' can be of type `str` (`unicode` in PY2) or `bytes`. In the latter case,
195
+ it is assumed to be already encoded with the correct plaform-specific encoding
196
+ identified by the (platformID, platEncID, langID) triplet. A warning is issued
197
+ to prevent unexpected results.
198
+ """
199
+ if not isinstance(string, str):
200
+ if isinstance(string, bytes):
201
+ log.warning(
202
+ "name string is bytes, ensure it's correctly encoded: %r", string
203
+ )
204
+ else:
205
+ raise TypeError(
206
+ "expected unicode or bytes, found %s: %r"
207
+ % (type(string).__name__, string)
208
+ )
209
+ namerecord = self.getName(nameID, platformID, platEncID, langID)
210
+ if namerecord:
211
+ namerecord.string = string
212
+ else:
213
+ self.names.append(makeName(string, nameID, platformID, platEncID, langID))
214
+
215
+ def removeNames(self, nameID=None, platformID=None, platEncID=None, langID=None):
216
+ """Remove any name records identified by the given combination of 'nameID',
217
+ 'platformID', 'platEncID' and 'langID'.
218
+ """
219
+ args = {
220
+ argName: argValue
221
+ for argName, argValue in (
222
+ ("nameID", nameID),
223
+ ("platformID", platformID),
224
+ ("platEncID", platEncID),
225
+ ("langID", langID),
226
+ )
227
+ if argValue is not None
228
+ }
229
+ if not args:
230
+ # no arguments, nothing to do
231
+ return
232
+ self.names = [
233
+ rec
234
+ for rec in self.names
235
+ if any(
236
+ argValue != getattr(rec, argName) for argName, argValue in args.items()
237
+ )
238
+ ]
239
+
240
+ @staticmethod
241
+ def removeUnusedNames(ttFont):
242
+ """Remove any name records which are not in NameID range 0-255 and not utilized
243
+ within the font itself."""
244
+ visitor = NameRecordVisitor()
245
+ visitor.visit(ttFont)
246
+ toDelete = set()
247
+ for record in ttFont["name"].names:
248
+ # Name IDs 26 to 255, inclusive, are reserved for future standard names.
249
+ # https://learn.microsoft.com/en-us/typography/opentype/spec/name#name-ids
250
+ if record.nameID < 256:
251
+ continue
252
+ if record.nameID not in visitor.seen:
253
+ toDelete.add(record.nameID)
254
+
255
+ for nameID in toDelete:
256
+ ttFont["name"].removeNames(nameID)
257
+ return toDelete
258
+
259
+ def _findUnusedNameID(self, minNameID=256):
260
+ """Finds an unused name id.
261
+
262
+ The nameID is assigned in the range between 'minNameID' and 32767 (inclusive),
263
+ following the last nameID in the name table.
264
+ """
265
+ names = self.names
266
+ nameID = 1 + max([n.nameID for n in names] + [minNameID - 1])
267
+ if nameID > 32767:
268
+ raise ValueError("nameID must be less than 32768")
269
+ return nameID
270
+
271
+ def findMultilingualName(
272
+ self, names, windows=True, mac=True, minNameID=0, ttFont=None
273
+ ):
274
+ """Return the name ID of an existing multilingual name that
275
+ matches the 'names' dictionary, or None if not found.
276
+
277
+ 'names' is a dictionary with the name in multiple languages,
278
+ such as {'en': 'Pale', 'de': 'Blaß', 'de-CH': 'Blass'}.
279
+ The keys can be arbitrary IETF BCP 47 language codes;
280
+ the values are Unicode strings.
281
+
282
+ If 'windows' is True, the returned name ID is guaranteed
283
+ exist for all requested languages for platformID=3 and
284
+ platEncID=1.
285
+ If 'mac' is True, the returned name ID is guaranteed to exist
286
+ for all requested languages for platformID=1 and platEncID=0.
287
+
288
+ The returned name ID will not be less than the 'minNameID'
289
+ argument.
290
+ """
291
+ # Gather the set of requested
292
+ # (string, platformID, platEncID, langID)
293
+ # tuples
294
+ reqNameSet = set()
295
+ for lang, name in sorted(names.items()):
296
+ if windows:
297
+ windowsName = _makeWindowsName(name, None, lang)
298
+ if windowsName is not None:
299
+ reqNameSet.add(
300
+ (
301
+ windowsName.string,
302
+ windowsName.platformID,
303
+ windowsName.platEncID,
304
+ windowsName.langID,
305
+ )
306
+ )
307
+ if mac:
308
+ macName = _makeMacName(name, None, lang, ttFont)
309
+ if macName is not None:
310
+ reqNameSet.add(
311
+ (
312
+ macName.string,
313
+ macName.platformID,
314
+ macName.platEncID,
315
+ macName.langID,
316
+ )
317
+ )
318
+
319
+ # Collect matching name IDs
320
+ matchingNames = dict()
321
+ for name in self.names:
322
+ try:
323
+ key = (name.toUnicode(), name.platformID, name.platEncID, name.langID)
324
+ except UnicodeDecodeError:
325
+ continue
326
+ if key in reqNameSet and name.nameID >= minNameID:
327
+ nameSet = matchingNames.setdefault(name.nameID, set())
328
+ nameSet.add(key)
329
+
330
+ # Return the first name ID that defines all requested strings
331
+ for nameID, nameSet in sorted(matchingNames.items()):
332
+ if nameSet == reqNameSet:
333
+ return nameID
334
+
335
+ return None # not found
336
+
337
+ def addMultilingualName(
338
+ self, names, ttFont=None, nameID=None, windows=True, mac=True, minNameID=0
339
+ ):
340
+ """Add a multilingual name, returning its name ID
341
+
342
+ 'names' is a dictionary with the name in multiple languages,
343
+ such as {'en': 'Pale', 'de': 'Blaß', 'de-CH': 'Blass'}.
344
+ The keys can be arbitrary IETF BCP 47 language codes;
345
+ the values are Unicode strings.
346
+
347
+ 'ttFont' is the TTFont to which the names are added, or None.
348
+ If present, the font's 'ltag' table can get populated
349
+ to store exotic language codes, which allows encoding
350
+ names that otherwise cannot get encoded at all.
351
+
352
+ 'nameID' is the name ID to be used, or None to let the library
353
+ find an existing set of name records that match, or pick an
354
+ unused name ID.
355
+
356
+ If 'windows' is True, a platformID=3 name record will be added.
357
+ If 'mac' is True, a platformID=1 name record will be added.
358
+
359
+ If the 'nameID' argument is None, the created nameID will not
360
+ be less than the 'minNameID' argument.
361
+ """
362
+ if nameID is None:
363
+ # Reuse nameID if possible
364
+ nameID = self.findMultilingualName(
365
+ names, windows=windows, mac=mac, minNameID=minNameID, ttFont=ttFont
366
+ )
367
+ if nameID is not None:
368
+ return nameID
369
+ nameID = self._findUnusedNameID()
370
+ # TODO: Should minimize BCP 47 language codes.
371
+ # https://github.com/fonttools/fonttools/issues/930
372
+ for lang, name in sorted(names.items()):
373
+ if windows:
374
+ windowsName = _makeWindowsName(name, nameID, lang)
375
+ if windowsName is not None:
376
+ self.names.append(windowsName)
377
+ else:
378
+ # We cannot not make a Windows name: make sure we add a
379
+ # Mac name as a fallback. This can happen for exotic
380
+ # BCP47 language tags that have no Windows language code.
381
+ mac = True
382
+ if mac:
383
+ macName = _makeMacName(name, nameID, lang, ttFont)
384
+ if macName is not None:
385
+ self.names.append(macName)
386
+ return nameID
387
+
388
+ def addName(self, string, platforms=((1, 0, 0), (3, 1, 0x409)), minNameID=255):
389
+ """Add a new name record containing 'string' for each (platformID, platEncID,
390
+ langID) tuple specified in the 'platforms' list.
391
+
392
+ The nameID is assigned in the range between 'minNameID'+1 and 32767 (inclusive),
393
+ following the last nameID in the name table.
394
+ If no 'platforms' are specified, two English name records are added, one for the
395
+ Macintosh (platformID=0), and one for the Windows platform (3).
396
+
397
+ The 'string' must be a Unicode string, so it can be encoded with different,
398
+ platform-specific encodings.
399
+
400
+ Return the new nameID.
401
+ """
402
+ assert (
403
+ len(platforms) > 0
404
+ ), "'platforms' must contain at least one (platformID, platEncID, langID) tuple"
405
+ if not isinstance(string, str):
406
+ raise TypeError(
407
+ "expected str, found %s: %r" % (type(string).__name__, string)
408
+ )
409
+ nameID = self._findUnusedNameID(minNameID + 1)
410
+ for platformID, platEncID, langID in platforms:
411
+ self.names.append(makeName(string, nameID, platformID, platEncID, langID))
412
+ return nameID
413
+
414
+
415
+ def makeName(string, nameID, platformID, platEncID, langID):
416
+ name = NameRecord()
417
+ name.string, name.nameID, name.platformID, name.platEncID, name.langID = (
418
+ string,
419
+ nameID,
420
+ platformID,
421
+ platEncID,
422
+ langID,
423
+ )
424
+ return name
425
+
426
+
427
+ def _makeWindowsName(name, nameID, language):
428
+ """Create a NameRecord for the Microsoft Windows platform
429
+
430
+ 'language' is an arbitrary IETF BCP 47 language identifier such
431
+ as 'en', 'de-CH', 'de-AT-1901', or 'fa-Latn'. If Microsoft Windows
432
+ does not support the desired language, the result will be None.
433
+ Future versions of fonttools might return a NameRecord for the
434
+ OpenType 'name' table format 1, but this is not implemented yet.
435
+ """
436
+ langID = _WINDOWS_LANGUAGE_CODES.get(language.lower())
437
+ if langID is not None:
438
+ return makeName(name, nameID, 3, 1, langID)
439
+ else:
440
+ log.warning(
441
+ "cannot add Windows name in language %s "
442
+ "because fonttools does not yet support "
443
+ "name table format 1" % language
444
+ )
445
+ return None
446
+
447
+
448
+ def _makeMacName(name, nameID, language, font=None):
449
+ """Create a NameRecord for Apple platforms
450
+
451
+ 'language' is an arbitrary IETF BCP 47 language identifier such
452
+ as 'en', 'de-CH', 'de-AT-1901', or 'fa-Latn'. When possible, we
453
+ create a Macintosh NameRecord that is understood by old applications
454
+ (platform ID 1 and an old-style Macintosh language enum). If this
455
+ is not possible, we create a Unicode NameRecord (platform ID 0)
456
+ whose language points to the font’s 'ltag' table. The latter
457
+ can encode any string in any language, but legacy applications
458
+ might not recognize the format (in which case they will ignore
459
+ those names).
460
+
461
+ 'font' should be the TTFont for which you want to create a name.
462
+ If 'font' is None, we only return NameRecords for legacy Macintosh;
463
+ in that case, the result will be None for names that need to
464
+ be encoded with an 'ltag' table.
465
+
466
+ See the section “The language identifier” in Apple’s specification:
467
+ https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html
468
+ """
469
+ macLang = _MAC_LANGUAGE_CODES.get(language.lower())
470
+ macScript = _MAC_LANGUAGE_TO_SCRIPT.get(macLang)
471
+ if macLang is not None and macScript is not None:
472
+ encoding = getEncoding(1, macScript, macLang, default="ascii")
473
+ # Check if we can actually encode this name. If we can't,
474
+ # for example because we have no support for the legacy
475
+ # encoding, or because the name string contains Unicode
476
+ # characters that the legacy encoding cannot represent,
477
+ # we fall back to encoding the name in Unicode and put
478
+ # the language tag into the ltag table.
479
+ try:
480
+ _ = tobytes(name, encoding, errors="strict")
481
+ return makeName(name, nameID, 1, macScript, macLang)
482
+ except UnicodeEncodeError:
483
+ pass
484
+ if font is not None:
485
+ ltag = font.tables.get("ltag")
486
+ if ltag is None:
487
+ ltag = font["ltag"] = newTable("ltag")
488
+ # 0 = Unicode; 4 = “Unicode 2.0 or later semantics (non-BMP characters allowed)”
489
+ # “The preferred platform-specific code for Unicode would be 3 or 4.”
490
+ # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html
491
+ return makeName(name, nameID, 0, 4, ltag.addTag(language))
492
+ else:
493
+ log.warning(
494
+ "cannot store language %s into 'ltag' table "
495
+ "without having access to the TTFont object" % language
496
+ )
497
+ return None
498
+
499
+
500
+ class NameRecord(object):
501
+ def getEncoding(self, default="ascii"):
502
+ """Returns the Python encoding name for this name entry based on its platformID,
503
+ platEncID, and langID. If encoding for these values is not known, by default
504
+ 'ascii' is returned. That can be overriden by passing a value to the default
505
+ argument.
506
+ """
507
+ return getEncoding(self.platformID, self.platEncID, self.langID, default)
508
+
509
+ def encodingIsUnicodeCompatible(self):
510
+ return self.getEncoding(None) in ["utf_16_be", "ucs2be", "ascii", "latin1"]
511
+
512
+ def __str__(self):
513
+ return self.toStr(errors="backslashreplace")
514
+
515
+ def isUnicode(self):
516
+ return self.platformID == 0 or (
517
+ self.platformID == 3 and self.platEncID in [0, 1, 10]
518
+ )
519
+
520
+ def toUnicode(self, errors: str = "strict") -> str:
521
+ """
522
+ If self.string is a Unicode string, return it; otherwise try decoding the
523
+ bytes in self.string to a Unicode string using the encoding of this
524
+ entry as returned by self.getEncoding(); Note that self.getEncoding()
525
+ returns 'ascii' if the encoding is unknown to the library.
526
+
527
+ Certain heuristics are performed to recover data from bytes that are
528
+ ill-formed in the chosen encoding, or that otherwise look misencoded
529
+ (mostly around bad UTF-16BE encoded bytes, or bytes that look like UTF-16BE
530
+ but marked otherwise). If the bytes are ill-formed and the heuristics fail,
531
+ the error is handled according to the errors parameter to this function, which is
532
+ passed to the underlying decode() function; by default it throws a
533
+ UnicodeDecodeError exception.
534
+
535
+ Note: The mentioned heuristics mean that roundtripping a font to XML and back
536
+ to binary might recover some misencoded data whereas just loading the font
537
+ and saving it back will not change them.
538
+ """
539
+
540
+ def isascii(b: int) -> bool:
541
+ return (b >= 0x20 and b <= 0x7E) or b in [0x09, 0x0A, 0x0D]
542
+
543
+ encoding = self.getEncoding()
544
+ string = self.string
545
+
546
+ if (
547
+ isinstance(string, bytes)
548
+ and encoding == "utf_16_be"
549
+ and len(string) % 2 == 1
550
+ ):
551
+ # Recover badly encoded UTF-16 strings that have an odd number of bytes:
552
+ # - If the last byte is zero, drop it. Otherwise,
553
+ # - If all the odd bytes are zero and all the even bytes are ASCII,
554
+ # prepend one zero byte. Otherwise,
555
+ # - If first byte is zero and all other bytes are ASCII, insert zero
556
+ # bytes between consecutive ASCII bytes.
557
+ #
558
+ # (Yes, I've seen all of these in the wild... sigh)
559
+ if byteord(string[-1]) == 0:
560
+ string = string[:-1]
561
+ elif all(
562
+ byteord(b) == 0 if i % 2 else isascii(byteord(b))
563
+ for i, b in enumerate(string)
564
+ ):
565
+ string = b"\0" + string
566
+ elif byteord(string[0]) == 0 and all(
567
+ isascii(byteord(b)) for b in string[1:]
568
+ ):
569
+ string = bytesjoin(b"\0" + bytechr(byteord(b)) for b in string[1:])
570
+
571
+ string = tostr(string, encoding=encoding, errors=errors)
572
+
573
+ # If decoded strings still looks like UTF-16BE, it suggests a double-encoding.
574
+ # Fix it up.
575
+ if all(
576
+ ord(c) == 0 if i % 2 == 0 else isascii(ord(c)) for i, c in enumerate(string)
577
+ ):
578
+ # If string claims to be Mac encoding, but looks like UTF-16BE with ASCII text,
579
+ # narrow it down.
580
+ string = "".join(c for c in string[1::2])
581
+
582
+ return string
583
+
584
+ def toBytes(self, errors="strict"):
585
+ """If self.string is a bytes object, return it; otherwise try encoding
586
+ the Unicode string in self.string to bytes using the encoding of this
587
+ entry as returned by self.getEncoding(); Note that self.getEncoding()
588
+ returns 'ascii' if the encoding is unknown to the library.
589
+
590
+ If the Unicode string cannot be encoded to bytes in the chosen encoding,
591
+ the error is handled according to the errors parameter to this function,
592
+ which is passed to the underlying encode() function; by default it throws a
593
+ UnicodeEncodeError exception.
594
+ """
595
+ return tobytes(self.string, encoding=self.getEncoding(), errors=errors)
596
+
597
+ toStr = toUnicode
598
+
599
+ def toXML(self, writer, ttFont):
600
+ try:
601
+ unistr = self.toUnicode()
602
+ except UnicodeDecodeError:
603
+ unistr = None
604
+ attrs = [
605
+ ("nameID", self.nameID),
606
+ ("platformID", self.platformID),
607
+ ("platEncID", self.platEncID),
608
+ ("langID", hex(self.langID)),
609
+ ]
610
+
611
+ if unistr is None or not self.encodingIsUnicodeCompatible():
612
+ attrs.append(("unicode", unistr is not None))
613
+
614
+ writer.begintag("namerecord", attrs)
615
+ writer.newline()
616
+ if unistr is not None:
617
+ writer.write(unistr)
618
+ else:
619
+ writer.write8bit(self.string)
620
+ writer.newline()
621
+ writer.endtag("namerecord")
622
+ writer.newline()
623
+
624
+ def fromXML(self, name, attrs, content, ttFont):
625
+ self.nameID = safeEval(attrs["nameID"])
626
+ self.platformID = safeEval(attrs["platformID"])
627
+ self.platEncID = safeEval(attrs["platEncID"])
628
+ self.langID = safeEval(attrs["langID"])
629
+ s = strjoin(content).strip()
630
+ encoding = self.getEncoding()
631
+ if self.encodingIsUnicodeCompatible() or safeEval(
632
+ attrs.get("unicode", "False")
633
+ ):
634
+ self.string = s.encode(encoding)
635
+ else:
636
+ # This is the inverse of write8bit...
637
+ self.string = s.encode("latin1")
638
+
639
+ def __lt__(self, other):
640
+ if type(self) != type(other):
641
+ return NotImplemented
642
+
643
+ try:
644
+ selfTuple = (
645
+ self.platformID,
646
+ self.platEncID,
647
+ self.langID,
648
+ self.nameID,
649
+ )
650
+ otherTuple = (
651
+ other.platformID,
652
+ other.platEncID,
653
+ other.langID,
654
+ other.nameID,
655
+ )
656
+ except AttributeError:
657
+ # This can only happen for
658
+ # 1) an object that is not a NameRecord, or
659
+ # 2) an unlikely incomplete NameRecord object which has not been
660
+ # fully populated
661
+ return NotImplemented
662
+
663
+ try:
664
+ # Include the actual NameRecord string in the comparison tuples
665
+ selfTuple = selfTuple + (self.toBytes(),)
666
+ otherTuple = otherTuple + (other.toBytes(),)
667
+ except UnicodeEncodeError as e:
668
+ # toBytes caused an encoding error in either of the two, so content
669
+ # to sorting based on IDs only
670
+ log.error("NameRecord sorting failed to encode: %s" % e)
671
+
672
+ # Implemented so that list.sort() sorts according to the spec by using
673
+ # the order of the tuple items and their comparison
674
+ return selfTuple < otherTuple
675
+
676
+ def __repr__(self):
677
+ return "<NameRecord NameID=%d; PlatformID=%d; LanguageID=%d>" % (
678
+ self.nameID,
679
+ self.platformID,
680
+ self.langID,
681
+ )
682
+
683
+
684
+ # Windows language ID → IETF BCP-47 language tag
685
+ #
686
+ # While Microsoft indicates a region/country for all its language
687
+ # IDs, we follow Unicode practice by omitting “most likely subtags”
688
+ # as per Unicode CLDR. For example, English is simply “en” and not
689
+ # “en-Latn” because according to Unicode, the default script
690
+ # for English is Latin.
691
+ #
692
+ # http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html
693
+ # http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
694
+ _WINDOWS_LANGUAGES = {
695
+ 0x0436: "af",
696
+ 0x041C: "sq",
697
+ 0x0484: "gsw",
698
+ 0x045E: "am",
699
+ 0x1401: "ar-DZ",
700
+ 0x3C01: "ar-BH",
701
+ 0x0C01: "ar",
702
+ 0x0801: "ar-IQ",
703
+ 0x2C01: "ar-JO",
704
+ 0x3401: "ar-KW",
705
+ 0x3001: "ar-LB",
706
+ 0x1001: "ar-LY",
707
+ 0x1801: "ary",
708
+ 0x2001: "ar-OM",
709
+ 0x4001: "ar-QA",
710
+ 0x0401: "ar-SA",
711
+ 0x2801: "ar-SY",
712
+ 0x1C01: "aeb",
713
+ 0x3801: "ar-AE",
714
+ 0x2401: "ar-YE",
715
+ 0x042B: "hy",
716
+ 0x044D: "as",
717
+ 0x082C: "az-Cyrl",
718
+ 0x042C: "az",
719
+ 0x046D: "ba",
720
+ 0x042D: "eu",
721
+ 0x0423: "be",
722
+ 0x0845: "bn",
723
+ 0x0445: "bn-IN",
724
+ 0x201A: "bs-Cyrl",
725
+ 0x141A: "bs",
726
+ 0x047E: "br",
727
+ 0x0402: "bg",
728
+ 0x0403: "ca",
729
+ 0x0C04: "zh-HK",
730
+ 0x1404: "zh-MO",
731
+ 0x0804: "zh",
732
+ 0x1004: "zh-SG",
733
+ 0x0404: "zh-TW",
734
+ 0x0483: "co",
735
+ 0x041A: "hr",
736
+ 0x101A: "hr-BA",
737
+ 0x0405: "cs",
738
+ 0x0406: "da",
739
+ 0x048C: "prs",
740
+ 0x0465: "dv",
741
+ 0x0813: "nl-BE",
742
+ 0x0413: "nl",
743
+ 0x0C09: "en-AU",
744
+ 0x2809: "en-BZ",
745
+ 0x1009: "en-CA",
746
+ 0x2409: "en-029",
747
+ 0x4009: "en-IN",
748
+ 0x1809: "en-IE",
749
+ 0x2009: "en-JM",
750
+ 0x4409: "en-MY",
751
+ 0x1409: "en-NZ",
752
+ 0x3409: "en-PH",
753
+ 0x4809: "en-SG",
754
+ 0x1C09: "en-ZA",
755
+ 0x2C09: "en-TT",
756
+ 0x0809: "en-GB",
757
+ 0x0409: "en",
758
+ 0x3009: "en-ZW",
759
+ 0x0425: "et",
760
+ 0x0438: "fo",
761
+ 0x0464: "fil",
762
+ 0x040B: "fi",
763
+ 0x080C: "fr-BE",
764
+ 0x0C0C: "fr-CA",
765
+ 0x040C: "fr",
766
+ 0x140C: "fr-LU",
767
+ 0x180C: "fr-MC",
768
+ 0x100C: "fr-CH",
769
+ 0x0462: "fy",
770
+ 0x0456: "gl",
771
+ 0x0437: "ka",
772
+ 0x0C07: "de-AT",
773
+ 0x0407: "de",
774
+ 0x1407: "de-LI",
775
+ 0x1007: "de-LU",
776
+ 0x0807: "de-CH",
777
+ 0x0408: "el",
778
+ 0x046F: "kl",
779
+ 0x0447: "gu",
780
+ 0x0468: "ha",
781
+ 0x040D: "he",
782
+ 0x0439: "hi",
783
+ 0x040E: "hu",
784
+ 0x040F: "is",
785
+ 0x0470: "ig",
786
+ 0x0421: "id",
787
+ 0x045D: "iu",
788
+ 0x085D: "iu-Latn",
789
+ 0x083C: "ga",
790
+ 0x0434: "xh",
791
+ 0x0435: "zu",
792
+ 0x0410: "it",
793
+ 0x0810: "it-CH",
794
+ 0x0411: "ja",
795
+ 0x044B: "kn",
796
+ 0x043F: "kk",
797
+ 0x0453: "km",
798
+ 0x0486: "quc",
799
+ 0x0487: "rw",
800
+ 0x0441: "sw",
801
+ 0x0457: "kok",
802
+ 0x0412: "ko",
803
+ 0x0440: "ky",
804
+ 0x0454: "lo",
805
+ 0x0426: "lv",
806
+ 0x0427: "lt",
807
+ 0x082E: "dsb",
808
+ 0x046E: "lb",
809
+ 0x042F: "mk",
810
+ 0x083E: "ms-BN",
811
+ 0x043E: "ms",
812
+ 0x044C: "ml",
813
+ 0x043A: "mt",
814
+ 0x0481: "mi",
815
+ 0x047A: "arn",
816
+ 0x044E: "mr",
817
+ 0x047C: "moh",
818
+ 0x0450: "mn",
819
+ 0x0850: "mn-CN",
820
+ 0x0461: "ne",
821
+ 0x0414: "nb",
822
+ 0x0814: "nn",
823
+ 0x0482: "oc",
824
+ 0x0448: "or",
825
+ 0x0463: "ps",
826
+ 0x0415: "pl",
827
+ 0x0416: "pt",
828
+ 0x0816: "pt-PT",
829
+ 0x0446: "pa",
830
+ 0x046B: "qu-BO",
831
+ 0x086B: "qu-EC",
832
+ 0x0C6B: "qu",
833
+ 0x0418: "ro",
834
+ 0x0417: "rm",
835
+ 0x0419: "ru",
836
+ 0x243B: "smn",
837
+ 0x103B: "smj-NO",
838
+ 0x143B: "smj",
839
+ 0x0C3B: "se-FI",
840
+ 0x043B: "se",
841
+ 0x083B: "se-SE",
842
+ 0x203B: "sms",
843
+ 0x183B: "sma-NO",
844
+ 0x1C3B: "sms",
845
+ 0x044F: "sa",
846
+ 0x1C1A: "sr-Cyrl-BA",
847
+ 0x0C1A: "sr",
848
+ 0x181A: "sr-Latn-BA",
849
+ 0x081A: "sr-Latn",
850
+ 0x046C: "nso",
851
+ 0x0432: "tn",
852
+ 0x045B: "si",
853
+ 0x041B: "sk",
854
+ 0x0424: "sl",
855
+ 0x2C0A: "es-AR",
856
+ 0x400A: "es-BO",
857
+ 0x340A: "es-CL",
858
+ 0x240A: "es-CO",
859
+ 0x140A: "es-CR",
860
+ 0x1C0A: "es-DO",
861
+ 0x300A: "es-EC",
862
+ 0x440A: "es-SV",
863
+ 0x100A: "es-GT",
864
+ 0x480A: "es-HN",
865
+ 0x080A: "es-MX",
866
+ 0x4C0A: "es-NI",
867
+ 0x180A: "es-PA",
868
+ 0x3C0A: "es-PY",
869
+ 0x280A: "es-PE",
870
+ 0x500A: "es-PR",
871
+ # Microsoft has defined two different language codes for
872
+ # “Spanish with modern sorting” and “Spanish with traditional
873
+ # sorting”. This makes sense for collation APIs, and it would be
874
+ # possible to express this in BCP 47 language tags via Unicode
875
+ # extensions (eg., “es-u-co-trad” is “Spanish with traditional
876
+ # sorting”). However, for storing names in fonts, this distinction
877
+ # does not make sense, so we use “es” in both cases.
878
+ 0x0C0A: "es",
879
+ 0x040A: "es",
880
+ 0x540A: "es-US",
881
+ 0x380A: "es-UY",
882
+ 0x200A: "es-VE",
883
+ 0x081D: "sv-FI",
884
+ 0x041D: "sv",
885
+ 0x045A: "syr",
886
+ 0x0428: "tg",
887
+ 0x085F: "tzm",
888
+ 0x0449: "ta",
889
+ 0x0444: "tt",
890
+ 0x044A: "te",
891
+ 0x041E: "th",
892
+ 0x0451: "bo",
893
+ 0x041F: "tr",
894
+ 0x0442: "tk",
895
+ 0x0480: "ug",
896
+ 0x0422: "uk",
897
+ 0x042E: "hsb",
898
+ 0x0420: "ur",
899
+ 0x0843: "uz-Cyrl",
900
+ 0x0443: "uz",
901
+ 0x042A: "vi",
902
+ 0x0452: "cy",
903
+ 0x0488: "wo",
904
+ 0x0485: "sah",
905
+ 0x0478: "ii",
906
+ 0x046A: "yo",
907
+ }
908
+
909
+
910
+ _MAC_LANGUAGES = {
911
+ 0: "en",
912
+ 1: "fr",
913
+ 2: "de",
914
+ 3: "it",
915
+ 4: "nl",
916
+ 5: "sv",
917
+ 6: "es",
918
+ 7: "da",
919
+ 8: "pt",
920
+ 9: "no",
921
+ 10: "he",
922
+ 11: "ja",
923
+ 12: "ar",
924
+ 13: "fi",
925
+ 14: "el",
926
+ 15: "is",
927
+ 16: "mt",
928
+ 17: "tr",
929
+ 18: "hr",
930
+ 19: "zh-Hant",
931
+ 20: "ur",
932
+ 21: "hi",
933
+ 22: "th",
934
+ 23: "ko",
935
+ 24: "lt",
936
+ 25: "pl",
937
+ 26: "hu",
938
+ 27: "es",
939
+ 28: "lv",
940
+ 29: "se",
941
+ 30: "fo",
942
+ 31: "fa",
943
+ 32: "ru",
944
+ 33: "zh",
945
+ 34: "nl-BE",
946
+ 35: "ga",
947
+ 36: "sq",
948
+ 37: "ro",
949
+ 38: "cz",
950
+ 39: "sk",
951
+ 40: "sl",
952
+ 41: "yi",
953
+ 42: "sr",
954
+ 43: "mk",
955
+ 44: "bg",
956
+ 45: "uk",
957
+ 46: "be",
958
+ 47: "uz",
959
+ 48: "kk",
960
+ 49: "az-Cyrl",
961
+ 50: "az-Arab",
962
+ 51: "hy",
963
+ 52: "ka",
964
+ 53: "mo",
965
+ 54: "ky",
966
+ 55: "tg",
967
+ 56: "tk",
968
+ 57: "mn-CN",
969
+ 58: "mn",
970
+ 59: "ps",
971
+ 60: "ks",
972
+ 61: "ku",
973
+ 62: "sd",
974
+ 63: "bo",
975
+ 64: "ne",
976
+ 65: "sa",
977
+ 66: "mr",
978
+ 67: "bn",
979
+ 68: "as",
980
+ 69: "gu",
981
+ 70: "pa",
982
+ 71: "or",
983
+ 72: "ml",
984
+ 73: "kn",
985
+ 74: "ta",
986
+ 75: "te",
987
+ 76: "si",
988
+ 77: "my",
989
+ 78: "km",
990
+ 79: "lo",
991
+ 80: "vi",
992
+ 81: "id",
993
+ 82: "tl",
994
+ 83: "ms",
995
+ 84: "ms-Arab",
996
+ 85: "am",
997
+ 86: "ti",
998
+ 87: "om",
999
+ 88: "so",
1000
+ 89: "sw",
1001
+ 90: "rw",
1002
+ 91: "rn",
1003
+ 92: "ny",
1004
+ 93: "mg",
1005
+ 94: "eo",
1006
+ 128: "cy",
1007
+ 129: "eu",
1008
+ 130: "ca",
1009
+ 131: "la",
1010
+ 132: "qu",
1011
+ 133: "gn",
1012
+ 134: "ay",
1013
+ 135: "tt",
1014
+ 136: "ug",
1015
+ 137: "dz",
1016
+ 138: "jv",
1017
+ 139: "su",
1018
+ 140: "gl",
1019
+ 141: "af",
1020
+ 142: "br",
1021
+ 143: "iu",
1022
+ 144: "gd",
1023
+ 145: "gv",
1024
+ 146: "ga",
1025
+ 147: "to",
1026
+ 148: "el-polyton",
1027
+ 149: "kl",
1028
+ 150: "az",
1029
+ 151: "nn",
1030
+ }
1031
+
1032
+
1033
+ _WINDOWS_LANGUAGE_CODES = {
1034
+ lang.lower(): code for code, lang in _WINDOWS_LANGUAGES.items()
1035
+ }
1036
+ _MAC_LANGUAGE_CODES = {lang.lower(): code for code, lang in _MAC_LANGUAGES.items()}
1037
+
1038
+
1039
+ # MacOS language ID → MacOS script ID
1040
+ #
1041
+ # Note that the script ID is not sufficient to determine what encoding
1042
+ # to use in TrueType files. For some languages, MacOS used a modification
1043
+ # of a mainstream script. For example, an Icelandic name would be stored
1044
+ # with smRoman in the TrueType naming table, but the actual encoding
1045
+ # is a special Icelandic version of the normal Macintosh Roman encoding.
1046
+ # As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal
1047
+ # Syllables but MacOS had run out of available script codes, so this was
1048
+ # done as a (pretty radical) “modification” of Ethiopic.
1049
+ #
1050
+ # http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
1051
+ _MAC_LANGUAGE_TO_SCRIPT = {
1052
+ 0: 0, # langEnglish → smRoman
1053
+ 1: 0, # langFrench → smRoman
1054
+ 2: 0, # langGerman → smRoman
1055
+ 3: 0, # langItalian → smRoman
1056
+ 4: 0, # langDutch → smRoman
1057
+ 5: 0, # langSwedish → smRoman
1058
+ 6: 0, # langSpanish → smRoman
1059
+ 7: 0, # langDanish → smRoman
1060
+ 8: 0, # langPortuguese → smRoman
1061
+ 9: 0, # langNorwegian → smRoman
1062
+ 10: 5, # langHebrew → smHebrew
1063
+ 11: 1, # langJapanese → smJapanese
1064
+ 12: 4, # langArabic → smArabic
1065
+ 13: 0, # langFinnish → smRoman
1066
+ 14: 6, # langGreek → smGreek
1067
+ 15: 0, # langIcelandic → smRoman (modified)
1068
+ 16: 0, # langMaltese → smRoman
1069
+ 17: 0, # langTurkish → smRoman (modified)
1070
+ 18: 0, # langCroatian → smRoman (modified)
1071
+ 19: 2, # langTradChinese → smTradChinese
1072
+ 20: 4, # langUrdu → smArabic
1073
+ 21: 9, # langHindi → smDevanagari
1074
+ 22: 21, # langThai → smThai
1075
+ 23: 3, # langKorean → smKorean
1076
+ 24: 29, # langLithuanian → smCentralEuroRoman
1077
+ 25: 29, # langPolish → smCentralEuroRoman
1078
+ 26: 29, # langHungarian → smCentralEuroRoman
1079
+ 27: 29, # langEstonian → smCentralEuroRoman
1080
+ 28: 29, # langLatvian → smCentralEuroRoman
1081
+ 29: 0, # langSami → smRoman
1082
+ 30: 0, # langFaroese → smRoman (modified)
1083
+ 31: 4, # langFarsi → smArabic (modified)
1084
+ 32: 7, # langRussian → smCyrillic
1085
+ 33: 25, # langSimpChinese → smSimpChinese
1086
+ 34: 0, # langFlemish → smRoman
1087
+ 35: 0, # langIrishGaelic → smRoman (modified)
1088
+ 36: 0, # langAlbanian → smRoman
1089
+ 37: 0, # langRomanian → smRoman (modified)
1090
+ 38: 29, # langCzech → smCentralEuroRoman
1091
+ 39: 29, # langSlovak → smCentralEuroRoman
1092
+ 40: 0, # langSlovenian → smRoman (modified)
1093
+ 41: 5, # langYiddish → smHebrew
1094
+ 42: 7, # langSerbian → smCyrillic
1095
+ 43: 7, # langMacedonian → smCyrillic
1096
+ 44: 7, # langBulgarian → smCyrillic
1097
+ 45: 7, # langUkrainian → smCyrillic (modified)
1098
+ 46: 7, # langByelorussian → smCyrillic
1099
+ 47: 7, # langUzbek → smCyrillic
1100
+ 48: 7, # langKazakh → smCyrillic
1101
+ 49: 7, # langAzerbaijani → smCyrillic
1102
+ 50: 4, # langAzerbaijanAr → smArabic
1103
+ 51: 24, # langArmenian → smArmenian
1104
+ 52: 23, # langGeorgian → smGeorgian
1105
+ 53: 7, # langMoldavian → smCyrillic
1106
+ 54: 7, # langKirghiz → smCyrillic
1107
+ 55: 7, # langTajiki → smCyrillic
1108
+ 56: 7, # langTurkmen → smCyrillic
1109
+ 57: 27, # langMongolian → smMongolian
1110
+ 58: 7, # langMongolianCyr → smCyrillic
1111
+ 59: 4, # langPashto → smArabic
1112
+ 60: 4, # langKurdish → smArabic
1113
+ 61: 4, # langKashmiri → smArabic
1114
+ 62: 4, # langSindhi → smArabic
1115
+ 63: 26, # langTibetan → smTibetan
1116
+ 64: 9, # langNepali → smDevanagari
1117
+ 65: 9, # langSanskrit → smDevanagari
1118
+ 66: 9, # langMarathi → smDevanagari
1119
+ 67: 13, # langBengali → smBengali
1120
+ 68: 13, # langAssamese → smBengali
1121
+ 69: 11, # langGujarati → smGujarati
1122
+ 70: 10, # langPunjabi → smGurmukhi
1123
+ 71: 12, # langOriya → smOriya
1124
+ 72: 17, # langMalayalam → smMalayalam
1125
+ 73: 16, # langKannada → smKannada
1126
+ 74: 14, # langTamil → smTamil
1127
+ 75: 15, # langTelugu → smTelugu
1128
+ 76: 18, # langSinhalese → smSinhalese
1129
+ 77: 19, # langBurmese → smBurmese
1130
+ 78: 20, # langKhmer → smKhmer
1131
+ 79: 22, # langLao → smLao
1132
+ 80: 30, # langVietnamese → smVietnamese
1133
+ 81: 0, # langIndonesian → smRoman
1134
+ 82: 0, # langTagalog → smRoman
1135
+ 83: 0, # langMalayRoman → smRoman
1136
+ 84: 4, # langMalayArabic → smArabic
1137
+ 85: 28, # langAmharic → smEthiopic
1138
+ 86: 28, # langTigrinya → smEthiopic
1139
+ 87: 28, # langOromo → smEthiopic
1140
+ 88: 0, # langSomali → smRoman
1141
+ 89: 0, # langSwahili → smRoman
1142
+ 90: 0, # langKinyarwanda → smRoman
1143
+ 91: 0, # langRundi → smRoman
1144
+ 92: 0, # langNyanja → smRoman
1145
+ 93: 0, # langMalagasy → smRoman
1146
+ 94: 0, # langEsperanto → smRoman
1147
+ 128: 0, # langWelsh → smRoman (modified)
1148
+ 129: 0, # langBasque → smRoman
1149
+ 130: 0, # langCatalan → smRoman
1150
+ 131: 0, # langLatin → smRoman
1151
+ 132: 0, # langQuechua → smRoman
1152
+ 133: 0, # langGuarani → smRoman
1153
+ 134: 0, # langAymara → smRoman
1154
+ 135: 7, # langTatar → smCyrillic
1155
+ 136: 4, # langUighur → smArabic
1156
+ 137: 26, # langDzongkha → smTibetan
1157
+ 138: 0, # langJavaneseRom → smRoman
1158
+ 139: 0, # langSundaneseRom → smRoman
1159
+ 140: 0, # langGalician → smRoman
1160
+ 141: 0, # langAfrikaans → smRoman
1161
+ 142: 0, # langBreton → smRoman (modified)
1162
+ 143: 28, # langInuktitut → smEthiopic (modified)
1163
+ 144: 0, # langScottishGaelic → smRoman (modified)
1164
+ 145: 0, # langManxGaelic → smRoman (modified)
1165
+ 146: 0, # langIrishGaelicScript → smRoman (modified)
1166
+ 147: 0, # langTongan → smRoman
1167
+ 148: 6, # langGreekAncient → smRoman
1168
+ 149: 0, # langGreenlandic → smRoman
1169
+ 150: 0, # langAzerbaijanRoman → smRoman
1170
+ 151: 0, # langNynorsk → smRoman
1171
+ }
1172
+
1173
+
1174
+ class NameRecordVisitor(TTVisitor):
1175
+ # Font tables that have NameIDs we need to collect.
1176
+ TABLES = ("GSUB", "GPOS", "fvar", "CPAL", "STAT")
1177
+
1178
+ def __init__(self):
1179
+ self.seen = set()
1180
+
1181
+
1182
+ @NameRecordVisitor.register_attrs(
1183
+ (
1184
+ (otTables.FeatureParamsSize, ("SubfamilyNameID",)),
1185
+ (otTables.FeatureParamsStylisticSet, ("UINameID",)),
1186
+ (otTables.STAT, ("ElidedFallbackNameID",)),
1187
+ (otTables.AxisRecord, ("AxisNameID",)),
1188
+ (otTables.AxisValue, ("ValueNameID",)),
1189
+ (otTables.FeatureName, ("FeatureNameID",)),
1190
+ (otTables.Setting, ("SettingNameID",)),
1191
+ )
1192
+ )
1193
+ def visit(visitor, obj, attr, value):
1194
+ visitor.seen.add(value)
1195
+
1196
+
1197
+ @NameRecordVisitor.register(otTables.FeatureParamsCharacterVariants)
1198
+ def visit(visitor, obj):
1199
+ for attr in ("FeatUILabelNameID", "FeatUITooltipTextNameID", "SampleTextNameID"):
1200
+ value = getattr(obj, attr)
1201
+ visitor.seen.add(value)
1202
+ # also include the sequence of UI strings for individual variants, if any
1203
+ if obj.FirstParamUILabelNameID == 0 or obj.NumNamedParameters == 0:
1204
+ return
1205
+ visitor.seen.update(
1206
+ range(
1207
+ obj.FirstParamUILabelNameID,
1208
+ obj.FirstParamUILabelNameID + obj.NumNamedParameters,
1209
+ )
1210
+ )
1211
+
1212
+
1213
+ @NameRecordVisitor.register(ttLib.getTableClass("fvar"))
1214
+ def visit(visitor, obj):
1215
+ for inst in obj.instances:
1216
+ if inst.postscriptNameID != 0xFFFF:
1217
+ visitor.seen.add(inst.postscriptNameID)
1218
+ visitor.seen.add(inst.subfamilyNameID)
1219
+
1220
+ for axis in obj.axes:
1221
+ visitor.seen.add(axis.axisNameID)
1222
+
1223
+
1224
+ @NameRecordVisitor.register(ttLib.getTableClass("CPAL"))
1225
+ def visit(visitor, obj):
1226
+ if obj.version == 1:
1227
+ visitor.seen.update(obj.paletteLabels)
1228
+ visitor.seen.update(obj.paletteEntryLabels)
1229
+
1230
+
1231
+ @NameRecordVisitor.register(ttLib.TTFont)
1232
+ def visit(visitor, font, *args, **kwargs):
1233
+ if hasattr(visitor, "font"):
1234
+ return False
1235
+
1236
+ visitor.font = font
1237
+ for tag in visitor.TABLES:
1238
+ if tag in font:
1239
+ visitor.visit(font[tag], *args, **kwargs)
1240
+ del visitor.font
1241
+ return False
shared/package-files/3f/3f0701b7b41a26021e5c42616abc1af3eed301b0685d6d237010f4511b8abf81/import_export_constants.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <cstddef>
3
+
4
+ namespace torch {
5
+ namespace jit {
6
+ constexpr size_t BYTECODE_INDEX_INSTRUCTION = 0;
7
+ constexpr size_t BYTECODE_INDEX_OPERATOR = 1;
8
+ constexpr size_t BYTECODE_INDEX_CONSTANT = 2;
9
+ constexpr size_t BYTECODE_INDEX_TYPE = 3;
10
+ constexpr size_t BYTECODE_INDEX_REGISTER_SIZE = 4;
11
+
12
+ constexpr size_t BYTECODE_INDEX_SCHEMA_ARGUMENTS = 0;
13
+ constexpr size_t BYTECODE_INDEX_SCHEMA_RETURNS = 1;
14
+
15
+ constexpr size_t BYTECODE_INDEX_ARGUMENT_NAME = 0;
16
+ constexpr size_t BYTECODE_INDEX_ARGUMENT_TYPE = 1;
17
+ constexpr size_t BYTECODE_INDEX_ARGUMENT_DEFAULT_VALUE = 2;
18
+
19
+ constexpr size_t BYTECODE_INDEX_MODULE_DEBUG_HANDLES = 0;
20
+ } // namespace jit
21
+ } // namespace torch
shared/package-files/3f/3f0849c019b6924e2e33285d3b96ab42cf0896a497daf37486f53323b607aabc/test_angle_helper.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from mpl_toolkits.axisartist.angle_helper import (
7
+ FormatterDMS, FormatterHMS, select_step, select_step24, select_step360)
8
+
9
+
10
+ _MS_RE = (
11
+ r'''\$ # Mathtext
12
+ (
13
+ # The sign sometimes appears on a 0 when a fraction is shown.
14
+ # Check later that there's only one.
15
+ (?P<degree_sign>-)?
16
+ (?P<degree>[0-9.]+) # Degrees value
17
+ {degree} # Degree symbol (to be replaced by format.)
18
+ )?
19
+ (
20
+ (?(degree)\\,) # Separator if degrees are also visible.
21
+ (?P<minute_sign>-)?
22
+ (?P<minute>[0-9.]+) # Minutes value
23
+ {minute} # Minute symbol (to be replaced by format.)
24
+ )?
25
+ (
26
+ (?(minute)\\,) # Separator if minutes are also visible.
27
+ (?P<second_sign>-)?
28
+ (?P<second>[0-9.]+) # Seconds value
29
+ {second} # Second symbol (to be replaced by format.)
30
+ )?
31
+ \$ # Mathtext
32
+ '''
33
+ )
34
+ DMS_RE = re.compile(_MS_RE.format(degree=re.escape(FormatterDMS.deg_mark),
35
+ minute=re.escape(FormatterDMS.min_mark),
36
+ second=re.escape(FormatterDMS.sec_mark)),
37
+ re.VERBOSE)
38
+ HMS_RE = re.compile(_MS_RE.format(degree=re.escape(FormatterHMS.deg_mark),
39
+ minute=re.escape(FormatterHMS.min_mark),
40
+ second=re.escape(FormatterHMS.sec_mark)),
41
+ re.VERBOSE)
42
+
43
+
44
+ def dms2float(degrees, minutes=0, seconds=0):
45
+ return degrees + minutes / 60.0 + seconds / 3600.0
46
+
47
+
48
+ @pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [
49
+ ((-180, 180, 10), {'hour': False}, np.arange(-180, 181, 30), 1.0),
50
+ ((-12, 12, 10), {'hour': True}, np.arange(-12, 13, 2), 1.0)
51
+ ])
52
+ def test_select_step(args, kwargs, expected_levels, expected_factor):
53
+ levels, n, factor = select_step(*args, **kwargs)
54
+
55
+ assert n == len(levels)
56
+ np.testing.assert_array_equal(levels, expected_levels)
57
+ assert factor == expected_factor
58
+
59
+
60
+ @pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [
61
+ ((-180, 180, 10), {}, np.arange(-180, 181, 30), 1.0),
62
+ ((-12, 12, 10), {}, np.arange(-750, 751, 150), 60.0)
63
+ ])
64
+ def test_select_step24(args, kwargs, expected_levels, expected_factor):
65
+ levels, n, factor = select_step24(*args, **kwargs)
66
+
67
+ assert n == len(levels)
68
+ np.testing.assert_array_equal(levels, expected_levels)
69
+ assert factor == expected_factor
70
+
71
+
72
+ @pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [
73
+ ((dms2float(20, 21.2), dms2float(21, 33.3), 5), {},
74
+ np.arange(1215, 1306, 15), 60.0),
75
+ ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=33.3), 5), {},
76
+ np.arange(73820, 73835, 2), 3600.0),
77
+ ((dms2float(20, 21.2), dms2float(20, 53.3), 5), {},
78
+ np.arange(1220, 1256, 5), 60.0),
79
+ ((21.2, 33.3, 5), {},
80
+ np.arange(20, 35, 2), 1.0),
81
+ ((dms2float(20, 21.2), dms2float(21, 33.3), 5), {},
82
+ np.arange(1215, 1306, 15), 60.0),
83
+ ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=33.3), 5), {},
84
+ np.arange(73820, 73835, 2), 3600.0),
85
+ ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=21.4), 5), {},
86
+ np.arange(7382120, 7382141, 5), 360000.0),
87
+ # test threshold factor
88
+ ((dms2float(20.5, seconds=11.2), dms2float(20.5, seconds=53.3), 5),
89
+ {'threshold_factor': 60}, np.arange(12301, 12310), 600.0),
90
+ ((dms2float(20.5, seconds=11.2), dms2float(20.5, seconds=53.3), 5),
91
+ {'threshold_factor': 1}, np.arange(20502, 20517, 2), 1000.0),
92
+ ])
93
+ def test_select_step360(args, kwargs, expected_levels, expected_factor):
94
+ levels, n, factor = select_step360(*args, **kwargs)
95
+
96
+ assert n == len(levels)
97
+ np.testing.assert_array_equal(levels, expected_levels)
98
+ assert factor == expected_factor
99
+
100
+
101
+ @pytest.mark.parametrize('Formatter, regex',
102
+ [(FormatterDMS, DMS_RE),
103
+ (FormatterHMS, HMS_RE)],
104
+ ids=['Degree/Minute/Second', 'Hour/Minute/Second'])
105
+ @pytest.mark.parametrize('direction, factor, values', [
106
+ ("left", 60, [0, -30, -60]),
107
+ ("left", 600, [12301, 12302, 12303]),
108
+ ("left", 3600, [0, -30, -60]),
109
+ ("left", 36000, [738210, 738215, 738220]),
110
+ ("left", 360000, [7382120, 7382125, 7382130]),
111
+ ("left", 1., [45, 46, 47]),
112
+ ("left", 10., [452, 453, 454]),
113
+ ])
114
+ def test_formatters(Formatter, regex, direction, factor, values):
115
+ fmt = Formatter()
116
+ result = fmt(direction, factor, values)
117
+
118
+ prev_degree = prev_minute = prev_second = None
119
+ for tick, value in zip(result, values):
120
+ m = regex.match(tick)
121
+ assert m is not None, f'{tick!r} is not an expected tick format.'
122
+
123
+ sign = sum(m.group(sign + '_sign') is not None
124
+ for sign in ('degree', 'minute', 'second'))
125
+ assert sign <= 1, f'Only one element of tick {tick!r} may have a sign.'
126
+ sign = 1 if sign == 0 else -1
127
+
128
+ degree = float(m.group('degree') or prev_degree or 0)
129
+ minute = float(m.group('minute') or prev_minute or 0)
130
+ second = float(m.group('second') or prev_second or 0)
131
+ if Formatter == FormatterHMS:
132
+ # 360 degrees as plot range -> 24 hours as labelled range
133
+ expected_value = pytest.approx((value // 15) / factor)
134
+ else:
135
+ expected_value = pytest.approx(value / factor)
136
+ assert sign * dms2float(degree, minute, second) == expected_value, \
137
+ f'{tick!r} does not match expected tick value.'
138
+
139
+ prev_degree = degree
140
+ prev_minute = minute
141
+ prev_second = second
shared/package-files/3f/3f0a29b3c98805781fc6f1cef60f53138080ec928b041eabba9cd21fadab2253/special_chebyshev_polynomial_t_cpu_dispatch.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor special_chebyshev_polynomial_t(const at::Tensor & x, const at::Tensor & n);
21
+ TORCH_API at::Tensor & special_chebyshev_polynomial_t_out(at::Tensor & out, const at::Tensor & x, const at::Tensor & n);
22
+ TORCH_API at::Tensor & special_chebyshev_polynomial_t_outf(const at::Tensor & x, const at::Tensor & n, at::Tensor & out);
23
+
24
+ } // namespace cpu
25
+ } // namespace at
shared/package-files/3f/3f0c7dd171fb611445e039b5994341b483fcc5bfb9783c138ba6f0975c7893fa/modulefinder.pyi ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from types import CodeType
3
+ from typing import IO, Any, Container, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple
4
+
5
+ LOAD_CONST: int # undocumented
6
+ IMPORT_NAME: int # undocumented
7
+ STORE_NAME: int # undocumented
8
+ STORE_GLOBAL: int # undocumented
9
+ STORE_OPS: Tuple[int, int] # undocumented
10
+ EXTENDED_ARG: int # undocumented
11
+
12
+ packagePathMap: Dict[str, List[str]] # undocumented
13
+
14
+ def AddPackagePath(packagename: str, path: str) -> None: ...
15
+
16
+ replacePackageMap: Dict[str, str] # undocumented
17
+
18
+ def ReplacePackage(oldname: str, newname: str) -> None: ...
19
+
20
+ class Module: # undocumented
21
+ def __init__(self, name: str, file: Optional[str] = ..., path: Optional[str] = ...) -> None: ...
22
+ def __repr__(self) -> str: ...
23
+
24
+ class ModuleFinder:
25
+
26
+ modules: Dict[str, Module]
27
+ path: List[str] # undocumented
28
+ badmodules: Dict[str, Dict[str, int]] # undocumented
29
+ debug: int # undocumented
30
+ indent: int # undocumented
31
+ excludes: Container[str] # undocumented
32
+ replace_paths: Sequence[Tuple[str, str]] # undocumented
33
+
34
+ if sys.version_info >= (3, 8):
35
+ def __init__(
36
+ self,
37
+ path: Optional[List[str]] = ...,
38
+ debug: int = ...,
39
+ excludes: Optional[Container[str]] = ...,
40
+ replace_paths: Optional[Sequence[Tuple[str, str]]] = ...,
41
+ ) -> None: ...
42
+ else:
43
+ def __init__(
44
+ self,
45
+ path: Optional[List[str]] = ...,
46
+ debug: int = ...,
47
+ excludes: Container[str] = ...,
48
+ replace_paths: Sequence[Tuple[str, str]] = ...,
49
+ ) -> None: ...
50
+ def msg(self, level: int, str: str, *args: Any) -> None: ... # undocumented
51
+ def msgin(self, *args: Any) -> None: ... # undocumented
52
+ def msgout(self, *args: Any) -> None: ... # undocumented
53
+ def run_script(self, pathname: str) -> None: ...
54
+ def load_file(self, pathname: str) -> None: ... # undocumented
55
+ def import_hook(
56
+ self, name: str, caller: Optional[Module] = ..., fromlist: Optional[List[str]] = ..., level: int = ...
57
+ ) -> Optional[Module]: ... # undocumented
58
+ def determine_parent(self, caller: Optional[Module], level: int = ...) -> Optional[Module]: ... # undocumented
59
+ def find_head_package(self, parent: Module, name: str) -> Tuple[Module, str]: ... # undocumented
60
+ def load_tail(self, q: Module, tail: str) -> Module: ... # undocumented
61
+ def ensure_fromlist(self, m: Module, fromlist: Iterable[str], recursive: int = ...) -> None: ... # undocumented
62
+ def find_all_submodules(self, m: Module) -> Iterable[str]: ... # undocumented
63
+ def import_module(self, partname: str, fqname: str, parent: Module) -> Optional[Module]: ... # undocumented
64
+ def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: Tuple[str, str, str]) -> Module: ... # undocumented
65
+ if sys.version_info >= (3, 6):
66
+ def scan_opcodes(self, co: CodeType) -> Iterator[Tuple[str, Tuple[Any, ...]]]: ... # undocumented
67
+ def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented
68
+ def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented
69
+ def add_module(self, fqname: str) -> Module: ... # undocumented
70
+ def find_module(
71
+ self, name: str, path: Optional[str], parent: Optional[Module] = ...
72
+ ) -> Tuple[Optional[IO[Any]], Optional[str], Tuple[str, str, int]]: ... # undocumented
73
+ def report(self) -> None: ...
74
+ def any_missing(self) -> List[str]: ... # undocumented
75
+ def any_missing_maybe(self) -> Tuple[List[str], List[str]]: ... # undocumented
76
+ def replace_paths_in_code(self, co: CodeType) -> CodeType: ... # undocumented
shared/package-files/3f/3f1770af1d7447fa2bb0b54836ca02b32f932fa6bde84ba646c10d7f61b5d411/watchers.pyi ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ log: Any
4
+
5
+ class DataWatch:
6
+ def __init__(self, client, path, func=..., *args, **kwargs) -> None: ...
7
+ def __call__(self, func): ...
8
+
9
+ class ChildrenWatch:
10
+ def __init__(self, client, path, func=..., allow_session_lost=..., send_event=...) -> None: ...
11
+ def __call__(self, func): ...
12
+
13
+ class PatientChildrenWatch:
14
+ client: Any
15
+ path: Any
16
+ children: Any
17
+ time_boundary: Any
18
+ children_changed: Any
19
+ def __init__(self, client, path, time_boundary=...) -> None: ...
20
+ asy: Any
21
+ def start(self): ...
shared/package-files/3f/3f17cf8f6c84fd5daec324800208078d605c416fe1a9ed9303cce8621833e768/expand_copy_compositeexplicitautograd_dispatch.h 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 compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & expand_copy_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef size, bool implicit=false);
21
+ TORCH_API at::Tensor & expand_copy_outf(const at::Tensor & self, at::IntArrayRef size, bool implicit, at::Tensor & out);
22
+ TORCH_API at::Tensor & expand_copy_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef size, bool implicit=false);
23
+ TORCH_API at::Tensor & expand_copy_symint_outf(const at::Tensor & self, c10::SymIntArrayRef size, bool implicit, at::Tensor & out);
24
+
25
+ } // namespace compositeexplicitautograd
26
+ } // namespace at
shared/package-files/3f/3f1863a3715b06b6dd8332b0f9b69d9b23b68b33bd60345737a58731891ecce4/origibmpc3 ADDED
Binary file (564 Bytes). View file
 
shared/package-files/3f/3f1863a3715b06b6dd8332b0f9b69d9b23b68b33bd60345737a58731891ecce4/origpc3 ADDED
Binary file (564 Bytes). View file
 
shared/package-files/3f/3f18d84ca22ea2ae382d3d92d891d6395f013850f4012aa3ab44b95417869053/X25.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 X25(dns.rdata.Rdata):
28
+ """X25 record"""
29
+
30
+ # see RFC 1183
31
+
32
+ __slots__ = ["address"]
33
+
34
+ def __init__(self, rdclass, rdtype, address):
35
+ super().__init__(rdclass, rdtype)
36
+ self.address = self._as_bytes(address, True, 255)
37
+
38
+ def to_text(self, origin=None, relativize=True, **kw):
39
+ return '"%s"' % dns.rdata._escapify(self.address)
40
+
41
+ @classmethod
42
+ def from_text(
43
+ cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None
44
+ ):
45
+ address = tok.get_string()
46
+ return cls(rdclass, rdtype, address)
47
+
48
+ def _to_wire(self, file, compress=None, origin=None, canonicalize=False):
49
+ l = len(self.address)
50
+ assert l < 256
51
+ file.write(struct.pack("!B", l))
52
+ file.write(self.address)
53
+
54
+ @classmethod
55
+ def from_wire_parser(cls, rdclass, rdtype, parser, origin=None):
56
+ address = parser.get_counted_bytes()
57
+ return cls(rdclass, rdtype, address)
shared/package-files/3f/3f203a60ce527ca9d886ec763c05bf5b340621abb2f3f6b9564c016eec66b56b/datetime_registry.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numba.core.pythonapi import box, unbox, NativeValue
2
+ from numba.core.types import UniTuple, BaseTuple, Number, Boolean
3
+ from numba.np.types import NPDatetime, NPTimedelta
4
+ from numba.core.extending import overload
5
+ from numba.cpython.builtins import max_vararg, min_vararg, cast_int
6
+ from numba.core import errors
7
+
8
+
9
+ @box(NPDatetime)
10
+ def box_npdatetime(typ, val, c):
11
+ return c.pyapi.create_np_datetime(val, typ.unit_code)
12
+
13
+
14
+ @unbox(NPDatetime)
15
+ def unbox_npdatetime(typ, obj, c):
16
+ val = c.pyapi.extract_np_datetime(obj)
17
+ return NativeValue(val, is_error=c.pyapi.c_api_error())
18
+
19
+
20
+ @box(NPTimedelta)
21
+ def box_nptimedelta(typ, val, c):
22
+ return c.pyapi.create_np_timedelta(val, typ.unit_code)
23
+
24
+
25
+ @unbox(NPTimedelta)
26
+ def unbox_nptimedelta(typ, obj, c):
27
+ val = c.pyapi.extract_np_timedelta(obj)
28
+ return NativeValue(val, is_error=c.pyapi.c_api_error())
29
+
30
+
31
+ @overload(max)
32
+ def ol_max_datetime(*x):
33
+ if len(x) == 1 and (
34
+ (isinstance(x[0], UniTuple) and isinstance(
35
+ x[0].dtype, (NPDatetime, NPTimedelta, Number, Boolean)))
36
+
37
+ or (isinstance(x[0], BaseTuple) and all(
38
+ isinstance(ty, (NPDatetime, NPTimedelta,
39
+ Number, Boolean)) for ty in x[0].types))
40
+ ):
41
+ def impl(*x):
42
+ return max_vararg(x[0])
43
+ return impl
44
+ else:
45
+ for ty in x:
46
+ if not isinstance(ty, (NPDatetime, NPTimedelta, Number, Boolean)):
47
+ return None
48
+
49
+ def impl(*x):
50
+ return max_vararg(x)
51
+ return impl
52
+
53
+
54
+ @overload(min)
55
+ def ol_min_datetime(*x):
56
+ if len(x) == 1 and (
57
+ (isinstance(x[0], UniTuple) and isinstance(
58
+ x[0].dtype, (NPDatetime, NPTimedelta, Number, Boolean)))
59
+
60
+ or (isinstance(x[0], BaseTuple) and all(
61
+ isinstance(ty, (NPDatetime, NPTimedelta,
62
+ Number, Boolean)) for ty in x[0].types))
63
+ ):
64
+ def impl(*x):
65
+ return min_vararg(x[0])
66
+ return impl
67
+ else:
68
+ for ty in x:
69
+ if not isinstance(ty, (NPDatetime, NPTimedelta, Number, Boolean)):
70
+ return None
71
+
72
+ def impl(*x):
73
+ return min_vararg(x)
74
+ return impl
75
+
76
+
77
+ @overload(int)
78
+ def ol_int(x):
79
+ if not isinstance(x, (NPDatetime, NPTimedelta)):
80
+ return
81
+
82
+ if isinstance(x, NPDatetime) and x.unit != 'ns':
83
+ raise errors.NumbaTypeError(
84
+ "Only datetime64[ns] can be converted,"
85
+ f" but got datetime64[{x.unit}]"
86
+ )
87
+
88
+ def impl(x):
89
+ return cast_int(x)
90
+
91
+ return impl
shared/package-files/3f/3f224d332f251c3b4aa5f1647349e433c1788cd2d9002e253d008dd4a9b86e98/errors.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ class Error(Exception):
17
+ """Base Cu2Qu exception class for all other errors."""
18
+
19
+
20
+ class ApproxNotFoundError(Error):
21
+ def __init__(self, curve):
22
+ message = "no approximation found: %s" % curve
23
+ super().__init__(message)
24
+ self.curve = curve
25
+
26
+
27
+ class UnequalZipLengthsError(Error):
28
+ pass
29
+
30
+
31
+ class IncompatibleGlyphsError(Error):
32
+ def __init__(self, glyphs):
33
+ assert len(glyphs) > 1
34
+ self.glyphs = glyphs
35
+ names = set(repr(g.name) for g in glyphs)
36
+ if len(names) > 1:
37
+ self.combined_name = "{%s}" % ", ".join(sorted(names))
38
+ else:
39
+ self.combined_name = names.pop()
40
+
41
+ def __repr__(self):
42
+ return "<%s %s>" % (type(self).__name__, self.combined_name)
43
+
44
+
45
+ class IncompatibleSegmentNumberError(IncompatibleGlyphsError):
46
+ def __str__(self):
47
+ return "Glyphs named %s have different number of segments" % (
48
+ self.combined_name
49
+ )
50
+
51
+
52
+ class IncompatibleSegmentTypesError(IncompatibleGlyphsError):
53
+ def __init__(self, glyphs, segments):
54
+ IncompatibleGlyphsError.__init__(self, glyphs)
55
+ self.segments = segments
56
+
57
+ def __str__(self):
58
+ lines = []
59
+ ndigits = len(str(max(self.segments)))
60
+ for i, tags in sorted(self.segments.items()):
61
+ lines.append(
62
+ "%s: (%s)" % (str(i).rjust(ndigits), ", ".join(repr(t) for t in tags))
63
+ )
64
+ return "Glyphs named %s have incompatible segment types:\n %s" % (
65
+ self.combined_name,
66
+ "\n ".join(lines),
67
+ )
68
+
69
+
70
+ class IncompatibleFontsError(Error):
71
+ def __init__(self, glyph_errors):
72
+ self.glyph_errors = glyph_errors
73
+
74
+ def __str__(self):
75
+ return "fonts contains incompatible glyphs: %s" % (
76
+ ", ".join(repr(g) for g in sorted(self.glyph_errors.keys()))
77
+ )
shared/package-files/3f/3f22b374b305c5881a2f615bf3c1d445c4ea33498cdb69914d034ab914f7b303/floor_divide_native.h ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 floor_divide(const at::Tensor & self, const at::Tensor & other);
20
+ TORCH_API at::Tensor & floor_divide_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
21
+ TORCH_API at::Tensor & floor_divide_(at::Tensor & self, const at::Tensor & other);
22
+ TORCH_API at::Tensor floor_divide_sparse(const at::Tensor & self, const at::Tensor & other);
23
+ TORCH_API at::Tensor & floor_divide_out_sparse_zerodim(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
24
+ TORCH_API at::Tensor & floor_divide_sparse_(at::Tensor & self, const at::Tensor & other);
25
+ TORCH_API at::Tensor floor_divide(const at::Tensor & self, const at::Scalar & other);
26
+ TORCH_API at::Tensor & floor_divide_Scalar_out(const at::Tensor & self, const at::Scalar & other, at::Tensor & out);
27
+ TORCH_API at::Tensor & floor_divide_(at::Tensor & self, const at::Scalar & other);
28
+ } // namespace native
29
+ } // namespace at
shared/package-files/3f/3f24a323933d367910f328abfb21f8d17891ef3867d941015de7293a5ba84ebc/LICENSE.txt ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The bulk of Patsy is distributed under a simple 2-clause BSD license:
2
+
3
+ Copyright (C) 2011-2012, Patsy Developers. All rights reserved.
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
+ 1. Redistributions of source code must retain the above copyright
10
+ notice, this list of conditions and the following disclaimer.
11
+
12
+ 2. 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
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+
29
+ The module patsy.compat contains code derived from the Python
30
+ standard library, and is covered by the following license:
31
+
32
+ PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
33
+ --------------------------------------------
34
+
35
+ 1. This LICENSE AGREEMENT is between the Python Software Foundation
36
+ ("PSF"), and the Individual or Organization ("Licensee") accessing and
37
+ otherwise using this software ("Python") in source or binary form and
38
+ its associated documentation.
39
+
40
+ 2. Subject to the terms and conditions of this License Agreement, PSF hereby
41
+ grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
42
+ analyze, test, perform and/or display publicly, prepare derivative works,
43
+ distribute, and otherwise use Python alone or in any derivative version,
44
+ provided, however, that PSF's License Agreement and PSF's notice of copyright,
45
+ i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
46
+ 2011, 2012 Python Software Foundation; All Rights Reserved" are retained in Python
47
+ alone or in any derivative version prepared by Licensee.
48
+
49
+ 3. In the event Licensee prepares a derivative work that is based on
50
+ or incorporates Python or any part thereof, and wants to make
51
+ the derivative work available to others as provided herein, then
52
+ Licensee hereby agrees to include in any such work a brief summary of
53
+ the changes made to Python.
54
+
55
+ 4. PSF is making Python available to Licensee on an "AS IS"
56
+ basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
57
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
58
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
59
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
60
+ INFRINGE ANY THIRD PARTY RIGHTS.
61
+
62
+ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
63
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
64
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
65
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
66
+
67
+ 6. This License Agreement will automatically terminate upon a material
68
+ breach of its terms and conditions.
69
+
70
+ 7. Nothing in this License Agreement shall be deemed to create any
71
+ relationship of agency, partnership, or joint venture between PSF and
72
+ Licensee. This License Agreement does not grant permission to use PSF
73
+ trademarks or trade name in a trademark sense to endorse or promote
74
+ products or services of Licensee, or any third party.
75
+
76
+ 8. By copying, installing or otherwise using Python, Licensee
77
+ agrees to be bound by the terms and conditions of this License
78
+ Agreement.
79
+
80
+ As per item (3), we are required to provide a brief summary of
81
+ changes. For this, see comments in patsy/compat.py.
shared/package-files/3f/3f28597226b21f0aa459545533ee759220df1e1f79dd8f700630917241f54bf9/hardswish_backward_cuda_dispatch.h 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 cuda {
19
+
20
+ TORCH_API at::Tensor hardswish_backward(const at::Tensor & grad_output, const at::Tensor & self);
21
+
22
+ } // namespace cuda
23
+ } // namespace at
shared/package-files/3f/3f2866cf8afd17df6d19aa655401db9eb1ea43afecdeb504e87cfa74cc87abd0/gcd_meta.h 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_gcd : 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/3f/3f28bd06e089bef590b9ed8c247d8bb1bf9f7caffd30a8d15468d8e4dbef8644/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Re-export symbols for wider use. We configure mypy and flake8 to be aware that
2
+ # this file does this.
3
+
4
+ from jedi.inference.value.module import ModuleValue
5
+ from jedi.inference.value.klass import ClassValue
6
+ from jedi.inference.value.function import FunctionValue, \
7
+ MethodValue
8
+ from jedi.inference.value.instance import AnonymousInstance, BoundMethod, \
9
+ CompiledInstance, AbstractInstanceValue, TreeInstance
shared/package-files/3f/3f2a94602715ad97cc647a4fafd9d40f9dd91c9efb92c02ce197acb0fa72bf34/reflection_pad3d_native.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #include <ATen/ops/reflection_pad3d_meta.h>
16
+
17
+ namespace at {
18
+ namespace native {
19
+ struct TORCH_API structured_reflection_pad3d_out_cpu : public at::meta::structured_reflection_pad3d {
20
+ void impl(const at::Tensor & self, at::ArrayRef<int64_t> padding, const at::Tensor & out);
21
+ };
22
+ struct TORCH_API structured_reflection_pad3d_out_cuda : public at::meta::structured_reflection_pad3d {
23
+ void impl(const at::Tensor & self, at::ArrayRef<int64_t> padding, const at::Tensor & out);
24
+ };
25
+ } // namespace native
26
+ } // namespace at
shared/package-files/3f/3f2c9ab1b2e024418ffcff6c31631228cd9c561934c85ea9d2f1afb4c132b46f/rrt.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.styles.rrt
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ pygments "rrt" theme, based on Zap and Emacs defaults.
6
+
7
+ :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ from pygments.style import Style
12
+ from pygments.token import Token, Comment, Name, Keyword, String
13
+
14
+
15
+ class RrtStyle(Style):
16
+ """
17
+ Minimalistic "rrt" theme, based on Zap and Emacs defaults.
18
+ """
19
+
20
+ background_color = '#000000'
21
+ highlight_color = '#0000ff'
22
+
23
+ styles = {
24
+ Token: '#dddddd',
25
+ Comment: '#00ff00',
26
+ Name.Function: '#ffff00',
27
+ Name.Variable: '#eedd82',
28
+ Name.Constant: '#7fffd4',
29
+ Keyword: '#ff0000',
30
+ Comment.Preproc: '#e5e5e5',
31
+ String: '#87ceeb',
32
+ Keyword.Type: '#ee82ee',
33
+ }
shared/package-files/3f/3f2d3210d3e5c56a9f73bd34aed5cfbf6653acbf2d9e1d4747e2bfbd695b08a5/_ufuncs_cxx.pyx ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is automatically generated by _generate_pyx.py.
2
+ # Do not edit manually!
3
+
4
+ from libc.math cimport NAN
5
+
6
+ include "_ufuncs_extra_code_common.pxi"
7
+
8
+ cdef extern from r"_ufuncs_cxx_defs.h":
9
+ cdef float _func_beta_pdf_float "beta_pdf_float"(float, float, float) noexcept nogil
10
+ cdef void *_export_beta_pdf_float = <void*>_func_beta_pdf_float
11
+ cdef extern from r"_ufuncs_cxx_defs.h":
12
+ cdef double _func_beta_pdf_double "beta_pdf_double"(double, double, double) noexcept nogil
13
+ cdef void *_export_beta_pdf_double = <void*>_func_beta_pdf_double
14
+ cdef extern from r"_ufuncs_cxx_defs.h":
15
+ cdef float _func_beta_ppf_float "beta_ppf_float"(float, float, float) noexcept nogil
16
+ cdef void *_export_beta_ppf_float = <void*>_func_beta_ppf_float
17
+ cdef extern from r"_ufuncs_cxx_defs.h":
18
+ cdef double _func_beta_ppf_double "beta_ppf_double"(double, double, double) noexcept nogil
19
+ cdef void *_export_beta_ppf_double = <void*>_func_beta_ppf_double
20
+ cdef extern from r"_ufuncs_cxx_defs.h":
21
+ cdef float _func_binom_cdf_float "binom_cdf_float"(float, float, float) noexcept nogil
22
+ cdef void *_export_binom_cdf_float = <void*>_func_binom_cdf_float
23
+ cdef extern from r"_ufuncs_cxx_defs.h":
24
+ cdef double _func_binom_cdf_double "binom_cdf_double"(double, double, double) noexcept nogil
25
+ cdef void *_export_binom_cdf_double = <void*>_func_binom_cdf_double
26
+ cdef extern from r"_ufuncs_cxx_defs.h":
27
+ cdef float _func_binom_isf_float "binom_isf_float"(float, float, float) noexcept nogil
28
+ cdef void *_export_binom_isf_float = <void*>_func_binom_isf_float
29
+ cdef extern from r"_ufuncs_cxx_defs.h":
30
+ cdef double _func_binom_isf_double "binom_isf_double"(double, double, double) noexcept nogil
31
+ cdef void *_export_binom_isf_double = <void*>_func_binom_isf_double
32
+ cdef extern from r"_ufuncs_cxx_defs.h":
33
+ cdef float _func_binom_pmf_float "binom_pmf_float"(float, float, float) noexcept nogil
34
+ cdef void *_export_binom_pmf_float = <void*>_func_binom_pmf_float
35
+ cdef extern from r"_ufuncs_cxx_defs.h":
36
+ cdef double _func_binom_pmf_double "binom_pmf_double"(double, double, double) noexcept nogil
37
+ cdef void *_export_binom_pmf_double = <void*>_func_binom_pmf_double
38
+ cdef extern from r"_ufuncs_cxx_defs.h":
39
+ cdef float _func_binom_ppf_float "binom_ppf_float"(float, float, float) noexcept nogil
40
+ cdef void *_export_binom_ppf_float = <void*>_func_binom_ppf_float
41
+ cdef extern from r"_ufuncs_cxx_defs.h":
42
+ cdef double _func_binom_ppf_double "binom_ppf_double"(double, double, double) noexcept nogil
43
+ cdef void *_export_binom_ppf_double = <void*>_func_binom_ppf_double
44
+ cdef extern from r"_ufuncs_cxx_defs.h":
45
+ cdef float _func_binom_sf_float "binom_sf_float"(float, float, float) noexcept nogil
46
+ cdef void *_export_binom_sf_float = <void*>_func_binom_sf_float
47
+ cdef extern from r"_ufuncs_cxx_defs.h":
48
+ cdef double _func_binom_sf_double "binom_sf_double"(double, double, double) noexcept nogil
49
+ cdef void *_export_binom_sf_double = <void*>_func_binom_sf_double
50
+ cdef extern from r"_ufuncs_cxx_defs.h":
51
+ cdef float _func_cauchy_isf_float "cauchy_isf_float"(float, float, float) noexcept nogil
52
+ cdef void *_export_cauchy_isf_float = <void*>_func_cauchy_isf_float
53
+ cdef extern from r"_ufuncs_cxx_defs.h":
54
+ cdef double _func_cauchy_isf_double "cauchy_isf_double"(double, double, double) noexcept nogil
55
+ cdef void *_export_cauchy_isf_double = <void*>_func_cauchy_isf_double
56
+ cdef extern from r"_ufuncs_cxx_defs.h":
57
+ cdef float _func_cauchy_ppf_float "cauchy_ppf_float"(float, float, float) noexcept nogil
58
+ cdef void *_export_cauchy_ppf_float = <void*>_func_cauchy_ppf_float
59
+ cdef extern from r"_ufuncs_cxx_defs.h":
60
+ cdef double _func_cauchy_ppf_double "cauchy_ppf_double"(double, double, double) noexcept nogil
61
+ cdef void *_export_cauchy_ppf_double = <void*>_func_cauchy_ppf_double
62
+ cdef extern from r"_ufuncs_cxx_defs.h":
63
+ cdef float _func_hypergeom_cdf_float "hypergeom_cdf_float"(float, float, float, float) noexcept nogil
64
+ cdef void *_export_hypergeom_cdf_float = <void*>_func_hypergeom_cdf_float
65
+ cdef extern from r"_ufuncs_cxx_defs.h":
66
+ cdef double _func_hypergeom_cdf_double "hypergeom_cdf_double"(double, double, double, double) noexcept nogil
67
+ cdef void *_export_hypergeom_cdf_double = <void*>_func_hypergeom_cdf_double
68
+ cdef extern from r"_ufuncs_cxx_defs.h":
69
+ cdef float _func_hypergeom_mean_float "hypergeom_mean_float"(float, float, float) noexcept nogil
70
+ cdef void *_export_hypergeom_mean_float = <void*>_func_hypergeom_mean_float
71
+ cdef extern from r"_ufuncs_cxx_defs.h":
72
+ cdef double _func_hypergeom_mean_double "hypergeom_mean_double"(double, double, double) noexcept nogil
73
+ cdef void *_export_hypergeom_mean_double = <void*>_func_hypergeom_mean_double
74
+ cdef extern from r"_ufuncs_cxx_defs.h":
75
+ cdef float _func_hypergeom_pmf_float "hypergeom_pmf_float"(float, float, float, float) noexcept nogil
76
+ cdef void *_export_hypergeom_pmf_float = <void*>_func_hypergeom_pmf_float
77
+ cdef extern from r"_ufuncs_cxx_defs.h":
78
+ cdef double _func_hypergeom_pmf_double "hypergeom_pmf_double"(double, double, double, double) noexcept nogil
79
+ cdef void *_export_hypergeom_pmf_double = <void*>_func_hypergeom_pmf_double
80
+ cdef extern from r"_ufuncs_cxx_defs.h":
81
+ cdef float _func_hypergeom_sf_float "hypergeom_sf_float"(float, float, float, float) noexcept nogil
82
+ cdef void *_export_hypergeom_sf_float = <void*>_func_hypergeom_sf_float
83
+ cdef extern from r"_ufuncs_cxx_defs.h":
84
+ cdef double _func_hypergeom_sf_double "hypergeom_sf_double"(double, double, double, double) noexcept nogil
85
+ cdef void *_export_hypergeom_sf_double = <void*>_func_hypergeom_sf_double
86
+ cdef extern from r"_ufuncs_cxx_defs.h":
87
+ cdef float _func_hypergeom_skewness_float "hypergeom_skewness_float"(float, float, float) noexcept nogil
88
+ cdef void *_export_hypergeom_skewness_float = <void*>_func_hypergeom_skewness_float
89
+ cdef extern from r"_ufuncs_cxx_defs.h":
90
+ cdef double _func_hypergeom_skewness_double "hypergeom_skewness_double"(double, double, double) noexcept nogil
91
+ cdef void *_export_hypergeom_skewness_double = <void*>_func_hypergeom_skewness_double
92
+ cdef extern from r"_ufuncs_cxx_defs.h":
93
+ cdef float _func_hypergeom_variance_float "hypergeom_variance_float"(float, float, float) noexcept nogil
94
+ cdef void *_export_hypergeom_variance_float = <void*>_func_hypergeom_variance_float
95
+ cdef extern from r"_ufuncs_cxx_defs.h":
96
+ cdef double _func_hypergeom_variance_double "hypergeom_variance_double"(double, double, double) noexcept nogil
97
+ cdef void *_export_hypergeom_variance_double = <void*>_func_hypergeom_variance_double
98
+ cdef extern from r"_ufuncs_cxx_defs.h":
99
+ cdef float _func_invgauss_isf_float "invgauss_isf_float"(float, float, float) noexcept nogil
100
+ cdef void *_export_invgauss_isf_float = <void*>_func_invgauss_isf_float
101
+ cdef extern from r"_ufuncs_cxx_defs.h":
102
+ cdef double _func_invgauss_isf_double "invgauss_isf_double"(double, double, double) noexcept nogil
103
+ cdef void *_export_invgauss_isf_double = <void*>_func_invgauss_isf_double
104
+ cdef extern from r"_ufuncs_cxx_defs.h":
105
+ cdef float _func_invgauss_ppf_float "invgauss_ppf_float"(float, float, float) noexcept nogil
106
+ cdef void *_export_invgauss_ppf_float = <void*>_func_invgauss_ppf_float
107
+ cdef extern from r"_ufuncs_cxx_defs.h":
108
+ cdef double _func_invgauss_ppf_double "invgauss_ppf_double"(double, double, double) noexcept nogil
109
+ cdef void *_export_invgauss_ppf_double = <void*>_func_invgauss_ppf_double
110
+ cdef extern from r"_ufuncs_cxx_defs.h":
111
+ cdef float _func_landau_cdf_float "landau_cdf_float"(float, float, float) noexcept nogil
112
+ cdef void *_export_landau_cdf_float = <void*>_func_landau_cdf_float
113
+ cdef extern from r"_ufuncs_cxx_defs.h":
114
+ cdef double _func_landau_cdf_double "landau_cdf_double"(double, double, double) noexcept nogil
115
+ cdef void *_export_landau_cdf_double = <void*>_func_landau_cdf_double
116
+ cdef extern from r"_ufuncs_cxx_defs.h":
117
+ cdef float _func_landau_isf_float "landau_isf_float"(float, float, float) noexcept nogil
118
+ cdef void *_export_landau_isf_float = <void*>_func_landau_isf_float
119
+ cdef extern from r"_ufuncs_cxx_defs.h":
120
+ cdef double _func_landau_isf_double "landau_isf_double"(double, double, double) noexcept nogil
121
+ cdef void *_export_landau_isf_double = <void*>_func_landau_isf_double
122
+ cdef extern from r"_ufuncs_cxx_defs.h":
123
+ cdef float _func_landau_pdf_float "landau_pdf_float"(float, float, float) noexcept nogil
124
+ cdef void *_export_landau_pdf_float = <void*>_func_landau_pdf_float
125
+ cdef extern from r"_ufuncs_cxx_defs.h":
126
+ cdef double _func_landau_pdf_double "landau_pdf_double"(double, double, double) noexcept nogil
127
+ cdef void *_export_landau_pdf_double = <void*>_func_landau_pdf_double
128
+ cdef extern from r"_ufuncs_cxx_defs.h":
129
+ cdef float _func_landau_ppf_float "landau_ppf_float"(float, float, float) noexcept nogil
130
+ cdef void *_export_landau_ppf_float = <void*>_func_landau_ppf_float
131
+ cdef extern from r"_ufuncs_cxx_defs.h":
132
+ cdef double _func_landau_ppf_double "landau_ppf_double"(double, double, double) noexcept nogil
133
+ cdef void *_export_landau_ppf_double = <void*>_func_landau_ppf_double
134
+ cdef extern from r"_ufuncs_cxx_defs.h":
135
+ cdef float _func_landau_sf_float "landau_sf_float"(float, float, float) noexcept nogil
136
+ cdef void *_export_landau_sf_float = <void*>_func_landau_sf_float
137
+ cdef extern from r"_ufuncs_cxx_defs.h":
138
+ cdef double _func_landau_sf_double "landau_sf_double"(double, double, double) noexcept nogil
139
+ cdef void *_export_landau_sf_double = <void*>_func_landau_sf_double
140
+ cdef extern from r"_ufuncs_cxx_defs.h":
141
+ cdef float _func_nbinom_cdf_float "nbinom_cdf_float"(float, float, float) noexcept nogil
142
+ cdef void *_export_nbinom_cdf_float = <void*>_func_nbinom_cdf_float
143
+ cdef extern from r"_ufuncs_cxx_defs.h":
144
+ cdef double _func_nbinom_cdf_double "nbinom_cdf_double"(double, double, double) noexcept nogil
145
+ cdef void *_export_nbinom_cdf_double = <void*>_func_nbinom_cdf_double
146
+ cdef extern from r"_ufuncs_cxx_defs.h":
147
+ cdef float _func_nbinom_isf_float "nbinom_isf_float"(float, float, float) noexcept nogil
148
+ cdef void *_export_nbinom_isf_float = <void*>_func_nbinom_isf_float
149
+ cdef extern from r"_ufuncs_cxx_defs.h":
150
+ cdef double _func_nbinom_isf_double "nbinom_isf_double"(double, double, double) noexcept nogil
151
+ cdef void *_export_nbinom_isf_double = <void*>_func_nbinom_isf_double
152
+ cdef extern from r"_ufuncs_cxx_defs.h":
153
+ cdef float _func_nbinom_kurtosis_excess_float "nbinom_kurtosis_excess_float"(float, float) noexcept nogil
154
+ cdef void *_export_nbinom_kurtosis_excess_float = <void*>_func_nbinom_kurtosis_excess_float
155
+ cdef extern from r"_ufuncs_cxx_defs.h":
156
+ cdef double _func_nbinom_kurtosis_excess_double "nbinom_kurtosis_excess_double"(double, double) noexcept nogil
157
+ cdef void *_export_nbinom_kurtosis_excess_double = <void*>_func_nbinom_kurtosis_excess_double
158
+ cdef extern from r"_ufuncs_cxx_defs.h":
159
+ cdef float _func_nbinom_mean_float "nbinom_mean_float"(float, float) noexcept nogil
160
+ cdef void *_export_nbinom_mean_float = <void*>_func_nbinom_mean_float
161
+ cdef extern from r"_ufuncs_cxx_defs.h":
162
+ cdef double _func_nbinom_mean_double "nbinom_mean_double"(double, double) noexcept nogil
163
+ cdef void *_export_nbinom_mean_double = <void*>_func_nbinom_mean_double
164
+ cdef extern from r"_ufuncs_cxx_defs.h":
165
+ cdef float _func_nbinom_pmf_float "nbinom_pmf_float"(float, float, float) noexcept nogil
166
+ cdef void *_export_nbinom_pmf_float = <void*>_func_nbinom_pmf_float
167
+ cdef extern from r"_ufuncs_cxx_defs.h":
168
+ cdef double _func_nbinom_pmf_double "nbinom_pmf_double"(double, double, double) noexcept nogil
169
+ cdef void *_export_nbinom_pmf_double = <void*>_func_nbinom_pmf_double
170
+ cdef extern from r"_ufuncs_cxx_defs.h":
171
+ cdef float _func_nbinom_ppf_float "nbinom_ppf_float"(float, float, float) noexcept nogil
172
+ cdef void *_export_nbinom_ppf_float = <void*>_func_nbinom_ppf_float
173
+ cdef extern from r"_ufuncs_cxx_defs.h":
174
+ cdef double _func_nbinom_ppf_double "nbinom_ppf_double"(double, double, double) noexcept nogil
175
+ cdef void *_export_nbinom_ppf_double = <void*>_func_nbinom_ppf_double
176
+ cdef extern from r"_ufuncs_cxx_defs.h":
177
+ cdef float _func_nbinom_sf_float "nbinom_sf_float"(float, float, float) noexcept nogil
178
+ cdef void *_export_nbinom_sf_float = <void*>_func_nbinom_sf_float
179
+ cdef extern from r"_ufuncs_cxx_defs.h":
180
+ cdef double _func_nbinom_sf_double "nbinom_sf_double"(double, double, double) noexcept nogil
181
+ cdef void *_export_nbinom_sf_double = <void*>_func_nbinom_sf_double
182
+ cdef extern from r"_ufuncs_cxx_defs.h":
183
+ cdef float _func_nbinom_skewness_float "nbinom_skewness_float"(float, float) noexcept nogil
184
+ cdef void *_export_nbinom_skewness_float = <void*>_func_nbinom_skewness_float
185
+ cdef extern from r"_ufuncs_cxx_defs.h":
186
+ cdef double _func_nbinom_skewness_double "nbinom_skewness_double"(double, double) noexcept nogil
187
+ cdef void *_export_nbinom_skewness_double = <void*>_func_nbinom_skewness_double
188
+ cdef extern from r"_ufuncs_cxx_defs.h":
189
+ cdef float _func_nbinom_variance_float "nbinom_variance_float"(float, float) noexcept nogil
190
+ cdef void *_export_nbinom_variance_float = <void*>_func_nbinom_variance_float
191
+ cdef extern from r"_ufuncs_cxx_defs.h":
192
+ cdef double _func_nbinom_variance_double "nbinom_variance_double"(double, double) noexcept nogil
193
+ cdef void *_export_nbinom_variance_double = <void*>_func_nbinom_variance_double
194
+ cdef extern from r"_ufuncs_cxx_defs.h":
195
+ cdef float _func_ncf_isf_float "ncf_isf_float"(float, float, float, float) noexcept nogil
196
+ cdef void *_export_ncf_isf_float = <void*>_func_ncf_isf_float
197
+ cdef extern from r"_ufuncs_cxx_defs.h":
198
+ cdef double _func_ncf_isf_double "ncf_isf_double"(double, double, double, double) noexcept nogil
199
+ cdef void *_export_ncf_isf_double = <void*>_func_ncf_isf_double
200
+ cdef extern from r"_ufuncs_cxx_defs.h":
201
+ cdef float _func_ncf_kurtosis_excess_float "ncf_kurtosis_excess_float"(float, float, float) noexcept nogil
202
+ cdef void *_export_ncf_kurtosis_excess_float = <void*>_func_ncf_kurtosis_excess_float
203
+ cdef extern from r"_ufuncs_cxx_defs.h":
204
+ cdef double _func_ncf_kurtosis_excess_double "ncf_kurtosis_excess_double"(double, double, double) noexcept nogil
205
+ cdef void *_export_ncf_kurtosis_excess_double = <void*>_func_ncf_kurtosis_excess_double
206
+ cdef extern from r"_ufuncs_cxx_defs.h":
207
+ cdef float _func_ncf_mean_float "ncf_mean_float"(float, float, float) noexcept nogil
208
+ cdef void *_export_ncf_mean_float = <void*>_func_ncf_mean_float
209
+ cdef extern from r"_ufuncs_cxx_defs.h":
210
+ cdef double _func_ncf_mean_double "ncf_mean_double"(double, double, double) noexcept nogil
211
+ cdef void *_export_ncf_mean_double = <void*>_func_ncf_mean_double
212
+ cdef extern from r"_ufuncs_cxx_defs.h":
213
+ cdef float _func_ncf_pdf_float "ncf_pdf_float"(float, float, float, float) noexcept nogil
214
+ cdef void *_export_ncf_pdf_float = <void*>_func_ncf_pdf_float
215
+ cdef extern from r"_ufuncs_cxx_defs.h":
216
+ cdef double _func_ncf_pdf_double "ncf_pdf_double"(double, double, double, double) noexcept nogil
217
+ cdef void *_export_ncf_pdf_double = <void*>_func_ncf_pdf_double
218
+ cdef extern from r"_ufuncs_cxx_defs.h":
219
+ cdef float _func_ncf_sf_float "ncf_sf_float"(float, float, float, float) noexcept nogil
220
+ cdef void *_export_ncf_sf_float = <void*>_func_ncf_sf_float
221
+ cdef extern from r"_ufuncs_cxx_defs.h":
222
+ cdef double _func_ncf_sf_double "ncf_sf_double"(double, double, double, double) noexcept nogil
223
+ cdef void *_export_ncf_sf_double = <void*>_func_ncf_sf_double
224
+ cdef extern from r"_ufuncs_cxx_defs.h":
225
+ cdef float _func_ncf_skewness_float "ncf_skewness_float"(float, float, float) noexcept nogil
226
+ cdef void *_export_ncf_skewness_float = <void*>_func_ncf_skewness_float
227
+ cdef extern from r"_ufuncs_cxx_defs.h":
228
+ cdef double _func_ncf_skewness_double "ncf_skewness_double"(double, double, double) noexcept nogil
229
+ cdef void *_export_ncf_skewness_double = <void*>_func_ncf_skewness_double
230
+ cdef extern from r"_ufuncs_cxx_defs.h":
231
+ cdef float _func_ncf_variance_float "ncf_variance_float"(float, float, float) noexcept nogil
232
+ cdef void *_export_ncf_variance_float = <void*>_func_ncf_variance_float
233
+ cdef extern from r"_ufuncs_cxx_defs.h":
234
+ cdef double _func_ncf_variance_double "ncf_variance_double"(double, double, double) noexcept nogil
235
+ cdef void *_export_ncf_variance_double = <void*>_func_ncf_variance_double
236
+ cdef extern from r"_ufuncs_cxx_defs.h":
237
+ cdef float _func_nct_isf_float "nct_isf_float"(float, float, float) noexcept nogil
238
+ cdef void *_export_nct_isf_float = <void*>_func_nct_isf_float
239
+ cdef extern from r"_ufuncs_cxx_defs.h":
240
+ cdef double _func_nct_isf_double "nct_isf_double"(double, double, double) noexcept nogil
241
+ cdef void *_export_nct_isf_double = <void*>_func_nct_isf_double
242
+ cdef extern from r"_ufuncs_cxx_defs.h":
243
+ cdef float _func_nct_kurtosis_excess_float "nct_kurtosis_excess_float"(float, float) noexcept nogil
244
+ cdef void *_export_nct_kurtosis_excess_float = <void*>_func_nct_kurtosis_excess_float
245
+ cdef extern from r"_ufuncs_cxx_defs.h":
246
+ cdef double _func_nct_kurtosis_excess_double "nct_kurtosis_excess_double"(double, double) noexcept nogil
247
+ cdef void *_export_nct_kurtosis_excess_double = <void*>_func_nct_kurtosis_excess_double
248
+ cdef extern from r"_ufuncs_cxx_defs.h":
249
+ cdef float _func_nct_mean_float "nct_mean_float"(float, float) noexcept nogil
250
+ cdef void *_export_nct_mean_float = <void*>_func_nct_mean_float
251
+ cdef extern from r"_ufuncs_cxx_defs.h":
252
+ cdef double _func_nct_mean_double "nct_mean_double"(double, double) noexcept nogil
253
+ cdef void *_export_nct_mean_double = <void*>_func_nct_mean_double
254
+ cdef extern from r"_ufuncs_cxx_defs.h":
255
+ cdef float _func_nct_pdf_float "nct_pdf_float"(float, float, float) noexcept nogil
256
+ cdef void *_export_nct_pdf_float = <void*>_func_nct_pdf_float
257
+ cdef extern from r"_ufuncs_cxx_defs.h":
258
+ cdef double _func_nct_pdf_double "nct_pdf_double"(double, double, double) noexcept nogil
259
+ cdef void *_export_nct_pdf_double = <void*>_func_nct_pdf_double
260
+ cdef extern from r"_ufuncs_cxx_defs.h":
261
+ cdef float _func_nct_ppf_float "nct_ppf_float"(float, float, float) noexcept nogil
262
+ cdef void *_export_nct_ppf_float = <void*>_func_nct_ppf_float
263
+ cdef extern from r"_ufuncs_cxx_defs.h":
264
+ cdef double _func_nct_ppf_double "nct_ppf_double"(double, double, double) noexcept nogil
265
+ cdef void *_export_nct_ppf_double = <void*>_func_nct_ppf_double
266
+ cdef extern from r"_ufuncs_cxx_defs.h":
267
+ cdef float _func_nct_sf_float "nct_sf_float"(float, float, float) noexcept nogil
268
+ cdef void *_export_nct_sf_float = <void*>_func_nct_sf_float
269
+ cdef extern from r"_ufuncs_cxx_defs.h":
270
+ cdef double _func_nct_sf_double "nct_sf_double"(double, double, double) noexcept nogil
271
+ cdef void *_export_nct_sf_double = <void*>_func_nct_sf_double
272
+ cdef extern from r"_ufuncs_cxx_defs.h":
273
+ cdef float _func_nct_skewness_float "nct_skewness_float"(float, float) noexcept nogil
274
+ cdef void *_export_nct_skewness_float = <void*>_func_nct_skewness_float
275
+ cdef extern from r"_ufuncs_cxx_defs.h":
276
+ cdef double _func_nct_skewness_double "nct_skewness_double"(double, double) noexcept nogil
277
+ cdef void *_export_nct_skewness_double = <void*>_func_nct_skewness_double
278
+ cdef extern from r"_ufuncs_cxx_defs.h":
279
+ cdef float _func_nct_variance_float "nct_variance_float"(float, float) noexcept nogil
280
+ cdef void *_export_nct_variance_float = <void*>_func_nct_variance_float
281
+ cdef extern from r"_ufuncs_cxx_defs.h":
282
+ cdef double _func_nct_variance_double "nct_variance_double"(double, double) noexcept nogil
283
+ cdef void *_export_nct_variance_double = <void*>_func_nct_variance_double
284
+ cdef extern from r"_ufuncs_cxx_defs.h":
285
+ cdef float _func_ncx2_cdf_float "ncx2_cdf_float"(float, float, float) noexcept nogil
286
+ cdef void *_export_ncx2_cdf_float = <void*>_func_ncx2_cdf_float
287
+ cdef extern from r"_ufuncs_cxx_defs.h":
288
+ cdef double _func_ncx2_cdf_double "ncx2_cdf_double"(double, double, double) noexcept nogil
289
+ cdef void *_export_ncx2_cdf_double = <void*>_func_ncx2_cdf_double
290
+ cdef extern from r"_ufuncs_cxx_defs.h":
291
+ cdef float _func_ncx2_isf_float "ncx2_isf_float"(float, float, float) noexcept nogil
292
+ cdef void *_export_ncx2_isf_float = <void*>_func_ncx2_isf_float
293
+ cdef extern from r"_ufuncs_cxx_defs.h":
294
+ cdef double _func_ncx2_isf_double "ncx2_isf_double"(double, double, double) noexcept nogil
295
+ cdef void *_export_ncx2_isf_double = <void*>_func_ncx2_isf_double
296
+ cdef extern from r"_ufuncs_cxx_defs.h":
297
+ cdef float _func_ncx2_pdf_float "ncx2_pdf_float"(float, float, float) noexcept nogil
298
+ cdef void *_export_ncx2_pdf_float = <void*>_func_ncx2_pdf_float
299
+ cdef extern from r"_ufuncs_cxx_defs.h":
300
+ cdef double _func_ncx2_pdf_double "ncx2_pdf_double"(double, double, double) noexcept nogil
301
+ cdef void *_export_ncx2_pdf_double = <void*>_func_ncx2_pdf_double
302
+ cdef extern from r"_ufuncs_cxx_defs.h":
303
+ cdef float _func_ncx2_ppf_float "ncx2_ppf_float"(float, float, float) noexcept nogil
304
+ cdef void *_export_ncx2_ppf_float = <void*>_func_ncx2_ppf_float
305
+ cdef extern from r"_ufuncs_cxx_defs.h":
306
+ cdef double _func_ncx2_ppf_double "ncx2_ppf_double"(double, double, double) noexcept nogil
307
+ cdef void *_export_ncx2_ppf_double = <void*>_func_ncx2_ppf_double
308
+ cdef extern from r"_ufuncs_cxx_defs.h":
309
+ cdef float _func_ncx2_sf_float "ncx2_sf_float"(float, float, float) noexcept nogil
310
+ cdef void *_export_ncx2_sf_float = <void*>_func_ncx2_sf_float
311
+ cdef extern from r"_ufuncs_cxx_defs.h":
312
+ cdef double _func_ncx2_sf_double "ncx2_sf_double"(double, double, double) noexcept nogil
313
+ cdef void *_export_ncx2_sf_double = <void*>_func_ncx2_sf_double
314
+ cdef extern from r"_ufuncs_cxx_defs.h":
315
+ cdef float _func_skewnorm_cdf_float "skewnorm_cdf_float"(float, float, float, float) noexcept nogil
316
+ cdef void *_export_skewnorm_cdf_float = <void*>_func_skewnorm_cdf_float
317
+ cdef extern from r"_ufuncs_cxx_defs.h":
318
+ cdef double _func_skewnorm_cdf_double "skewnorm_cdf_double"(double, double, double, double) noexcept nogil
319
+ cdef void *_export_skewnorm_cdf_double = <void*>_func_skewnorm_cdf_double
320
+ cdef extern from r"_ufuncs_cxx_defs.h":
321
+ cdef float _func_skewnorm_isf_float "skewnorm_isf_float"(float, float, float, float) noexcept nogil
322
+ cdef void *_export_skewnorm_isf_float = <void*>_func_skewnorm_isf_float
323
+ cdef extern from r"_ufuncs_cxx_defs.h":
324
+ cdef double _func_skewnorm_isf_double "skewnorm_isf_double"(double, double, double, double) noexcept nogil
325
+ cdef void *_export_skewnorm_isf_double = <void*>_func_skewnorm_isf_double
326
+ cdef extern from r"_ufuncs_cxx_defs.h":
327
+ cdef float _func_skewnorm_ppf_float "skewnorm_ppf_float"(float, float, float, float) noexcept nogil
328
+ cdef void *_export_skewnorm_ppf_float = <void*>_func_skewnorm_ppf_float
329
+ cdef extern from r"_ufuncs_cxx_defs.h":
330
+ cdef double _func_skewnorm_ppf_double "skewnorm_ppf_double"(double, double, double, double) noexcept nogil
331
+ cdef void *_export_skewnorm_ppf_double = <void*>_func_skewnorm_ppf_double
332
+ cdef extern from r"_ufuncs_cxx_defs.h":
333
+ cdef double _func__stirling2_inexact "_stirling2_inexact"(double, double) noexcept nogil
334
+ cdef void *_export__stirling2_inexact = <void*>_func__stirling2_inexact
335
+ cdef extern from r"_ufuncs_cxx_defs.h":
336
+ cdef float _func_ibeta_float "ibeta_float"(float, float, float) noexcept nogil
337
+ cdef void *_export_ibeta_float = <void*>_func_ibeta_float
338
+ cdef extern from r"_ufuncs_cxx_defs.h":
339
+ cdef double _func_ibeta_double "ibeta_double"(double, double, double) noexcept nogil
340
+ cdef void *_export_ibeta_double = <void*>_func_ibeta_double
341
+ cdef extern from r"_ufuncs_cxx_defs.h":
342
+ cdef float _func_ibetac_float "ibetac_float"(float, float, float) noexcept nogil
343
+ cdef void *_export_ibetac_float = <void*>_func_ibetac_float
344
+ cdef extern from r"_ufuncs_cxx_defs.h":
345
+ cdef double _func_ibetac_double "ibetac_double"(double, double, double) noexcept nogil
346
+ cdef void *_export_ibetac_double = <void*>_func_ibetac_double
347
+ cdef extern from r"_ufuncs_cxx_defs.h":
348
+ cdef float _func_ibetac_inv_float "ibetac_inv_float"(float, float, float) noexcept nogil
349
+ cdef void *_export_ibetac_inv_float = <void*>_func_ibetac_inv_float
350
+ cdef extern from r"_ufuncs_cxx_defs.h":
351
+ cdef double _func_ibetac_inv_double "ibetac_inv_double"(double, double, double) noexcept nogil
352
+ cdef void *_export_ibetac_inv_double = <void*>_func_ibetac_inv_double
353
+ cdef extern from r"_ufuncs_cxx_defs.h":
354
+ cdef float _func_ibeta_inv_float "ibeta_inv_float"(float, float, float) noexcept nogil
355
+ cdef void *_export_ibeta_inv_float = <void*>_func_ibeta_inv_float
356
+ cdef extern from r"_ufuncs_cxx_defs.h":
357
+ cdef double _func_ibeta_inv_double "ibeta_inv_double"(double, double, double) noexcept nogil
358
+ cdef void *_export_ibeta_inv_double = <void*>_func_ibeta_inv_double
359
+ cdef extern from r"_ufuncs_cxx_defs.h":
360
+ cdef double _func_faddeeva_dawsn "faddeeva_dawsn"(double) noexcept nogil
361
+ cdef void *_export_faddeeva_dawsn = <void*>_func_faddeeva_dawsn
362
+ cdef extern from r"_ufuncs_cxx_defs.h":
363
+ cdef double complex _func_faddeeva_dawsn_complex "faddeeva_dawsn_complex"(double complex) noexcept nogil
364
+ cdef void *_export_faddeeva_dawsn_complex = <void*>_func_faddeeva_dawsn_complex
365
+ cdef extern from r"_ufuncs_cxx_defs.h":
366
+ cdef double _func_fellint_RC "fellint_RC"(double, double) noexcept nogil
367
+ cdef void *_export_fellint_RC = <void*>_func_fellint_RC
368
+ cdef extern from r"_ufuncs_cxx_defs.h":
369
+ cdef double complex _func_cellint_RC "cellint_RC"(double complex, double complex) noexcept nogil
370
+ cdef void *_export_cellint_RC = <void*>_func_cellint_RC
371
+ cdef extern from r"_ufuncs_cxx_defs.h":
372
+ cdef double _func_fellint_RD "fellint_RD"(double, double, double) noexcept nogil
373
+ cdef void *_export_fellint_RD = <void*>_func_fellint_RD
374
+ cdef extern from r"_ufuncs_cxx_defs.h":
375
+ cdef double complex _func_cellint_RD "cellint_RD"(double complex, double complex, double complex) noexcept nogil
376
+ cdef void *_export_cellint_RD = <void*>_func_cellint_RD
377
+ cdef extern from r"_ufuncs_cxx_defs.h":
378
+ cdef double _func_fellint_RF "fellint_RF"(double, double, double) noexcept nogil
379
+ cdef void *_export_fellint_RF = <void*>_func_fellint_RF
380
+ cdef extern from r"_ufuncs_cxx_defs.h":
381
+ cdef double complex _func_cellint_RF "cellint_RF"(double complex, double complex, double complex) noexcept nogil
382
+ cdef void *_export_cellint_RF = <void*>_func_cellint_RF
383
+ cdef extern from r"_ufuncs_cxx_defs.h":
384
+ cdef double _func_fellint_RG "fellint_RG"(double, double, double) noexcept nogil
385
+ cdef void *_export_fellint_RG = <void*>_func_fellint_RG
386
+ cdef extern from r"_ufuncs_cxx_defs.h":
387
+ cdef double complex _func_cellint_RG "cellint_RG"(double complex, double complex, double complex) noexcept nogil
388
+ cdef void *_export_cellint_RG = <void*>_func_cellint_RG
389
+ cdef extern from r"_ufuncs_cxx_defs.h":
390
+ cdef double _func_fellint_RJ "fellint_RJ"(double, double, double, double) noexcept nogil
391
+ cdef void *_export_fellint_RJ = <void*>_func_fellint_RJ
392
+ cdef extern from r"_ufuncs_cxx_defs.h":
393
+ cdef double complex _func_cellint_RJ "cellint_RJ"(double complex, double complex, double complex, double complex) noexcept nogil
394
+ cdef void *_export_cellint_RJ = <void*>_func_cellint_RJ
395
+ cdef extern from r"_ufuncs_cxx_defs.h":
396
+ cdef double complex _func_faddeeva_erf "faddeeva_erf"(double complex) noexcept nogil
397
+ cdef void *_export_faddeeva_erf = <void*>_func_faddeeva_erf
398
+ cdef extern from r"_ufuncs_cxx_defs.h":
399
+ cdef double complex _func_faddeeva_erfc_complex "faddeeva_erfc_complex"(double complex) noexcept nogil
400
+ cdef void *_export_faddeeva_erfc_complex = <void*>_func_faddeeva_erfc_complex
401
+ cdef extern from r"_ufuncs_cxx_defs.h":
402
+ cdef double _func_faddeeva_erfcx "faddeeva_erfcx"(double) noexcept nogil
403
+ cdef void *_export_faddeeva_erfcx = <void*>_func_faddeeva_erfcx
404
+ cdef extern from r"_ufuncs_cxx_defs.h":
405
+ cdef double complex _func_faddeeva_erfcx_complex "faddeeva_erfcx_complex"(double complex) noexcept nogil
406
+ cdef void *_export_faddeeva_erfcx_complex = <void*>_func_faddeeva_erfcx_complex
407
+ cdef extern from r"_ufuncs_cxx_defs.h":
408
+ cdef double _func_faddeeva_erfi "faddeeva_erfi"(double) noexcept nogil
409
+ cdef void *_export_faddeeva_erfi = <void*>_func_faddeeva_erfi
410
+ cdef extern from r"_ufuncs_cxx_defs.h":
411
+ cdef double complex _func_faddeeva_erfi_complex "faddeeva_erfi_complex"(double complex) noexcept nogil
412
+ cdef void *_export_faddeeva_erfi_complex = <void*>_func_faddeeva_erfi_complex
413
+ cdef extern from r"_ufuncs_cxx_defs.h":
414
+ cdef float _func_erfinv_float "erfinv_float"(float) noexcept nogil
415
+ cdef void *_export_erfinv_float = <void*>_func_erfinv_float
416
+ cdef extern from r"_ufuncs_cxx_defs.h":
417
+ cdef double _func_erfinv_double "erfinv_double"(double) noexcept nogil
418
+ cdef void *_export_erfinv_double = <void*>_func_erfinv_double
419
+ cdef extern from r"_ufuncs_cxx_defs.h":
420
+ cdef double _func_hyp1f1_double "hyp1f1_double"(double, double, double) noexcept nogil
421
+ cdef void *_export_hyp1f1_double = <void*>_func_hyp1f1_double
422
+ cdef extern from r"_ufuncs_cxx_defs.h":
423
+ cdef double _func_faddeeva_log_ndtr "faddeeva_log_ndtr"(double) noexcept nogil
424
+ cdef void *_export_faddeeva_log_ndtr = <void*>_func_faddeeva_log_ndtr
425
+ cdef extern from r"_ufuncs_cxx_defs.h":
426
+ cdef double complex _func_faddeeva_log_ndtr_complex "faddeeva_log_ndtr_complex"(double complex) noexcept nogil
427
+ cdef void *_export_faddeeva_log_ndtr_complex = <void*>_func_faddeeva_log_ndtr_complex
428
+ cdef extern from r"_ufuncs_cxx_defs.h":
429
+ cdef float _func_ncf_cdf_float "ncf_cdf_float"(float, float, float, float) noexcept nogil
430
+ cdef void *_export_ncf_cdf_float = <void*>_func_ncf_cdf_float
431
+ cdef extern from r"_ufuncs_cxx_defs.h":
432
+ cdef double _func_ncf_cdf_double "ncf_cdf_double"(double, double, double, double) noexcept nogil
433
+ cdef void *_export_ncf_cdf_double = <void*>_func_ncf_cdf_double
434
+ cdef extern from r"_ufuncs_cxx_defs.h":
435
+ cdef float _func_ncf_ppf_float "ncf_ppf_float"(float, float, float, float) noexcept nogil
436
+ cdef void *_export_ncf_ppf_float = <void*>_func_ncf_ppf_float
437
+ cdef extern from r"_ufuncs_cxx_defs.h":
438
+ cdef double _func_ncf_ppf_double "ncf_ppf_double"(double, double, double, double) noexcept nogil
439
+ cdef void *_export_ncf_ppf_double = <void*>_func_ncf_ppf_double
440
+ cdef extern from r"_ufuncs_cxx_defs.h":
441
+ cdef float _func_nct_cdf_float "nct_cdf_float"(float, float, float) noexcept nogil
442
+ cdef void *_export_nct_cdf_float = <void*>_func_nct_cdf_float
443
+ cdef extern from r"_ufuncs_cxx_defs.h":
444
+ cdef double _func_nct_cdf_double "nct_cdf_double"(double, double, double) noexcept nogil
445
+ cdef void *_export_nct_cdf_double = <void*>_func_nct_cdf_double
446
+ cdef extern from r"_ufuncs_cxx_defs.h":
447
+ cdef double complex _func_faddeeva_ndtr "faddeeva_ndtr"(double complex) noexcept nogil
448
+ cdef void *_export_faddeeva_ndtr = <void*>_func_faddeeva_ndtr
449
+ cdef extern from r"_ufuncs_cxx_defs.h":
450
+ cdef float _func_powm1_float "powm1_float"(float, float) noexcept nogil
451
+ cdef void *_export_powm1_float = <void*>_func_powm1_float
452
+ cdef extern from r"_ufuncs_cxx_defs.h":
453
+ cdef double _func_powm1_double "powm1_double"(double, double) noexcept nogil
454
+ cdef void *_export_powm1_double = <void*>_func_powm1_double
455
+ cdef extern from r"_ufuncs_cxx_defs.h":
456
+ cdef double _func_faddeeva_voigt_profile "faddeeva_voigt_profile"(double, double, double) noexcept nogil
457
+ cdef void *_export_faddeeva_voigt_profile = <void*>_func_faddeeva_voigt_profile
458
+ cdef extern from r"_ufuncs_cxx_defs.h":
459
+ cdef double complex _func_faddeeva_w "faddeeva_w"(double complex) noexcept nogil
460
+ cdef void *_export_faddeeva_w = <void*>_func_faddeeva_w
461
+ cdef extern from r"_ufuncs_cxx_defs.h":
462
+ cdef double complex _func_wrightomega "wrightomega"(double complex) noexcept nogil
463
+ cdef void *_export_wrightomega = <void*>_func_wrightomega
464
+ cdef extern from r"_ufuncs_cxx_defs.h":
465
+ cdef double _func_wrightomega_real "wrightomega_real"(double) noexcept nogil
466
+ cdef void *_export_wrightomega_real = <void*>_func_wrightomega_real
shared/package-files/3f/3f2d5ce52bd7158adca0d27ea5e7848bc172626b819d0ad02b50cd64167e5509/Macros.h ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_MACROS_MACROS_H_
2
+ #define C10_MACROS_MACROS_H_
3
+ #include <cassert>
4
+
5
+ /* Main entry for c10/macros.
6
+ *
7
+ * In your code, include c10/macros/Macros.h directly, instead of individual
8
+ * files in this folder.
9
+ */
10
+
11
+ // For build systems that do not directly depend on CMake and directly build
12
+ // from the source directory (such as Buck), one may not have a cmake_macros.h
13
+ // file at all. In this case, the build system is responsible for providing
14
+ // correct macro definitions corresponding to the cmake_macros.h.in file.
15
+ //
16
+ // In such scenarios, one should define the macro
17
+ // C10_USING_CUSTOM_GENERATED_MACROS
18
+ // to inform this header that it does not need to include the cmake_macros.h
19
+ // file.
20
+
21
+ #ifndef C10_USING_CUSTOM_GENERATED_MACROS
22
+ #include <c10/macros/cmake_macros.h>
23
+ #endif // C10_USING_CUSTOM_GENERATED_MACROS
24
+
25
+ #include <c10/macros/Export.h>
26
+
27
+ #if defined(__clang__)
28
+ #define __ubsan_ignore_float_divide_by_zero__ \
29
+ __attribute__((no_sanitize("float-divide-by-zero")))
30
+ #define __ubsan_ignore_undefined__ __attribute__((no_sanitize("undefined")))
31
+ #define __ubsan_ignore_signed_int_overflow__ \
32
+ __attribute__((no_sanitize("signed-integer-overflow")))
33
+ #define __ubsan_ignore_pointer_overflow__ \
34
+ __attribute__((no_sanitize("pointer-overflow")))
35
+ #define __ubsan_ignore_function__ __attribute__((no_sanitize("function")))
36
+ #else
37
+ #define __ubsan_ignore_float_divide_by_zero__
38
+ #define __ubsan_ignore_undefined__
39
+ #define __ubsan_ignore_signed_int_overflow__
40
+ #define __ubsan_ignore_pointer_overflow__
41
+ #define __ubsan_ignore_function__
42
+ #endif
43
+
44
+ // Detect address sanitizer as some stuff doesn't work with it
45
+ #undef C10_ASAN_ENABLED
46
+
47
+ // for clang
48
+ #if defined(__has_feature)
49
+ #if ((__has_feature(address_sanitizer)))
50
+ #define C10_ASAN_ENABLED 1
51
+ #endif
52
+ #endif
53
+
54
+ // for gcc
55
+ #if defined(__SANITIZE_ADDRESS__)
56
+ #if __SANITIZE_ADDRESS__
57
+ #if !defined(C10_ASAN_ENABLED)
58
+ #define C10_ASAN_ENABLED 1
59
+ #endif
60
+ #endif
61
+ #endif
62
+
63
+ #if !defined(C10_ASAN_ENABLED)
64
+ #define C10_ASAN_ENABLED 0
65
+ #endif
66
+
67
+ // Disable the copy and assignment operator for a class. Note that this will
68
+ // disable the usage of the class in std containers.
69
+ #define C10_DISABLE_COPY_AND_ASSIGN(classname) \
70
+ classname(const classname&) = delete; \
71
+ classname& operator=(const classname&) = delete
72
+
73
+ #define C10_CONCATENATE_IMPL(s1, s2) s1##s2
74
+ #define C10_CONCATENATE(s1, s2) C10_CONCATENATE_IMPL(s1, s2)
75
+
76
+ #define C10_MACRO_EXPAND(args) args
77
+
78
+ #define C10_STRINGIZE_IMPL(x) #x
79
+ #define C10_STRINGIZE(x) C10_STRINGIZE_IMPL(x)
80
+
81
+ /**
82
+ * C10_ANONYMOUS_VARIABLE(str) introduces an identifier starting with
83
+ * str and ending with a number that varies with the line.
84
+ */
85
+ #ifdef __COUNTER__
86
+ #define C10_UID __COUNTER__
87
+ #define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __COUNTER__)
88
+ #else
89
+ #define C10_UID __LINE__
90
+ #define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __LINE__)
91
+ #endif
92
+
93
+ #ifdef __has_cpp_attribute
94
+ #define C10_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
95
+ #else
96
+ #define C10_HAS_CPP_ATTRIBUTE(x) (0)
97
+ #endif
98
+
99
+ /// C10_NODISCARD - Warn if a type or return value is discarded.
100
+
101
+ // Technically, we should check if __cplusplus > 201402L here, because
102
+ // [[nodiscard]] is only defined in C++17. However, some compilers
103
+ // we care about don't advertise being C++17 (e.g., clang), but
104
+ // support the attribute anyway. In fact, this is not just a good idea,
105
+ // it's the law: clang::warn_unused_result doesn't work on nvcc + clang
106
+ // and the best workaround for this case is to use [[nodiscard]]
107
+ // instead; see https://github.com/pytorch/pytorch/issues/13118
108
+ //
109
+ // Note to future editors: if you have noticed that a compiler is
110
+ // misbehaving (e.g., it advertises support, but the support doesn't
111
+ // actually work, or it is emitting warnings). Some compilers which
112
+ // are strict about the matter include MSVC, which will complain:
113
+ //
114
+ // error C2429: attribute 'nodiscard' requires compiler flag '/std:c++latest'
115
+ //
116
+ // Exhibits:
117
+ // - MSVC 19.14: https://godbolt.org/z/Dzd7gn (requires /std:c++latest)
118
+ // - Clang 8.0.0: https://godbolt.org/z/3PYL4Z (always advertises support)
119
+ // - gcc 8.3: https://godbolt.org/z/4tLMQS (always advertises support)
120
+ #if C10_HAS_CPP_ATTRIBUTE(nodiscard)
121
+ #define C10_NODISCARD [[nodiscard]]
122
+ // Workaround for llvm.org/PR23435, since clang 3.6 and below emit a spurious
123
+ // error when __has_cpp_attribute is given a scoped attribute in C mode.
124
+ #elif __cplusplus && C10_HAS_CPP_ATTRIBUTE(clang::warn_unused_result)
125
+ // TODO: It's possible this is still triggering
126
+ // https://github.com/pytorch/pytorch/issues/13118 on Windows; if it is, better
127
+ // fix it.
128
+ #define C10_NODISCARD [[clang::warn_unused_result]]
129
+ #else
130
+ #define C10_NODISCARD
131
+ #endif
132
+
133
+ // suppress an unused variable.
134
+ #if defined(_MSC_VER) && !defined(__clang__)
135
+ #define C10_UNUSED __pragma(warning(suppress : 4100 4101))
136
+ #else
137
+ #define C10_UNUSED __attribute__((__unused__))
138
+ #endif //_MSC_VER
139
+
140
+ #if !defined(__has_attribute)
141
+ #define __has_attribute(x) 0
142
+ #endif
143
+
144
+ // Direct port of LLVM_ATTRIBUTE_USED.
145
+ #if __has_attribute(used)
146
+ #define C10_USED __attribute__((__used__))
147
+ #else
148
+ #define C10_USED
149
+ #endif
150
+
151
+ #define C10_RESTRICT __restrict
152
+
153
+ // Simply define the namespace, in case a dependent library want to refer to
154
+ // the c10 namespace but not any nontrivial files.
155
+ namespace c10 {}
156
+ namespace c10::cuda {}
157
+ namespace c10::hip {}
158
+ namespace c10::xpu {}
159
+
160
+ // Since C10 is the core library for caffe2 (and aten), we will simply reroute
161
+ // all abstractions defined in c10 to be available in caffe2 as well.
162
+ // This is only for backwards compatibility. Please use the symbols from the
163
+ // c10 namespace where possible.
164
+ namespace caffe2 {
165
+ using namespace c10;
166
+ }
167
+ namespace at {
168
+ using namespace c10;
169
+ }
170
+ namespace at::cuda {
171
+ using namespace c10::cuda;
172
+ } // namespace at::cuda
173
+
174
+ // WARNING!!! THIS IS A GIANT HACK!!!
175
+ // This line means you cannot simultaneously include c10/hip
176
+ // and c10/cuda and then use them from the at::cuda namespace.
177
+ // This is true in practice, because HIPIFY works inplace on
178
+ // files in ATen/cuda, so it assumes that c10::hip is available
179
+ // from at::cuda. This namespace makes that happen. When
180
+ // HIPIFY is no longer out-of-place, we can switch the cuda
181
+ // here to hip and everyone is happy.
182
+ namespace at::cuda {
183
+ using namespace c10::hip;
184
+ } // namespace at::cuda
185
+
186
+ namespace at::xpu {
187
+ using namespace c10::xpu;
188
+ } // namespace at::xpu
189
+
190
+ // C10_LIKELY/C10_UNLIKELY
191
+ //
192
+ // These macros provide parentheses, so you can use these macros as:
193
+ //
194
+ // if C10_LIKELY(some_expr) {
195
+ // ...
196
+ // }
197
+ //
198
+ // NB: static_cast to boolean is mandatory in C++, because __builtin_expect
199
+ // takes a long argument, which means you may trigger the wrong conversion
200
+ // without it.
201
+ //
202
+ #if defined(__GNUC__) || defined(__ICL) || defined(__clang__)
203
+ #define C10_LIKELY(expr) (__builtin_expect(static_cast<bool>(expr), 1))
204
+ #define C10_UNLIKELY(expr) (__builtin_expect(static_cast<bool>(expr), 0))
205
+ #else
206
+ #define C10_LIKELY(expr) (expr)
207
+ #define C10_UNLIKELY(expr) (expr)
208
+ #endif
209
+
210
+ /// C10_NOINLINE - Functions whose declaration is annotated with this will not
211
+ /// be inlined.
212
+ #ifdef __GNUC__
213
+ #define C10_NOINLINE __attribute__((noinline))
214
+ #elif _MSC_VER
215
+ #define C10_NOINLINE __declspec(noinline)
216
+ #else
217
+ #define C10_NOINLINE
218
+ #endif
219
+
220
+ #if defined(_MSC_VER)
221
+ #define C10_ALWAYS_INLINE __forceinline
222
+ #elif __has_attribute(always_inline) || defined(__GNUC__)
223
+ #define C10_ALWAYS_INLINE __attribute__((__always_inline__)) inline
224
+ #else
225
+ #define C10_ALWAYS_INLINE inline
226
+ #endif
227
+
228
+ #if defined(_MSC_VER)
229
+ #define C10_ATTR_VISIBILITY_HIDDEN
230
+ #elif defined(__GNUC__)
231
+ #define C10_ATTR_VISIBILITY_HIDDEN __attribute__((__visibility__("hidden")))
232
+ #else
233
+ #define C10_ATTR_VISIBILITY_HIDDEN
234
+ #endif
235
+
236
+ #define C10_ERASE C10_ALWAYS_INLINE C10_ATTR_VISIBILITY_HIDDEN
237
+
238
+ #include <cstdint>
239
+
240
+ #ifdef __HIPCC__
241
+ // Unlike CUDA, HIP requires a HIP header to be included for __host__ to work.
242
+ // We do this #include here so that C10_HOST_DEVICE and friends will Just Work.
243
+ // See https://github.com/ROCm-Developer-Tools/HIP/issues/441
244
+ #include <hip/hip_runtime.h>
245
+ #endif
246
+
247
+ #if defined(__CUDACC__) || defined(__HIPCC__)
248
+ // Designates functions callable from the host (CPU) and the device (GPU)
249
+ #define C10_HOST_DEVICE __host__ __device__
250
+ #define C10_DEVICE __device__
251
+ #define C10_HOST __host__
252
+ // constants from
253
+ // (https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications)
254
+ // The maximum number of threads per multiprocessor is 1024 for Turing
255
+ // architecture (7.5), 1536 for Geforce Ampere (8.6)/Jetson Orin (8.7), and
256
+ // 2048 for all other architectures. You'll get warnings if you exceed these
257
+ // constants. Hence, the following macros adjust the input values from the user
258
+ // to resolve potential warnings.
259
+ #if __CUDA_ARCH__ == 750
260
+ constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1024;
261
+ #elif __CUDA_ARCH__ == 860 || __CUDA_ARCH__ == 870 || __CUDA_ARCH__ == 890
262
+ constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1536;
263
+ #else
264
+ constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 2048;
265
+ #endif
266
+ // CUDA_MAX_THREADS_PER_BLOCK is same for all architectures currently
267
+ constexpr uint32_t CUDA_MAX_THREADS_PER_BLOCK = 1024;
268
+ // CUDA_THREADS_PER_BLOCK_FALLBACK is the "canonical fallback" choice of block
269
+ // size. 256 is a good number for this fallback and should give good occupancy
270
+ // and versatility across all architectures.
271
+ constexpr uint32_t CUDA_THREADS_PER_BLOCK_FALLBACK = 256;
272
+ // NOTE: if you are thinking of constexpr-ify the inputs to launch bounds, it
273
+ // turns out that although __launch_bounds__ can take constexpr, it
274
+ // can't take a constexpr that has anything to do with templates.
275
+ // Currently we use launch_bounds that depend on template arguments in
276
+ // Loops.cuh, Reduce.cuh and LossCTC.cuh. Hence, C10_MAX_THREADS_PER_BLOCK
277
+ // and C10_MIN_BLOCKS_PER_SM are kept as macros.
278
+ // Suppose you were planning to write __launch_bounds__(a, b), based on your
279
+ // performance tuning on a modern GPU. Instead, you should write
280
+ // __launch_bounds__(C10_MAX_THREADS_PER_BLOCK(a), C10_MIN_BLOCKS_PER_SM(a, b)),
281
+ // which will also properly respect limits on old architectures.
282
+ #define C10_MAX_THREADS_PER_BLOCK(val) \
283
+ (((val) <= CUDA_MAX_THREADS_PER_BLOCK) ? (val) \
284
+ : CUDA_THREADS_PER_BLOCK_FALLBACK)
285
+ #define C10_MIN_BLOCKS_PER_SM(threads_per_block, blocks_per_sm) \
286
+ ((((threads_per_block) * (blocks_per_sm) <= CUDA_MAX_THREADS_PER_SM) \
287
+ ? (blocks_per_sm) \
288
+ : ((CUDA_MAX_THREADS_PER_SM + (threads_per_block)-1) / \
289
+ (threads_per_block))))
290
+ // C10_LAUNCH_BOUNDS is analogous to __launch_bounds__
291
+ #define C10_LAUNCH_BOUNDS_0 \
292
+ __launch_bounds__( \
293
+ 256, 4) // default launch bounds that should give good occupancy and
294
+ // versatility across all architectures.
295
+ #define C10_LAUNCH_BOUNDS_1(max_threads_per_block) \
296
+ __launch_bounds__((C10_MAX_THREADS_PER_BLOCK((max_threads_per_block))))
297
+ #define C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm) \
298
+ __launch_bounds__( \
299
+ (C10_MAX_THREADS_PER_BLOCK((max_threads_per_block))), \
300
+ (C10_MIN_BLOCKS_PER_SM((max_threads_per_block), (min_blocks_per_sm))))
301
+ #else
302
+ #define C10_HOST_DEVICE
303
+ #define C10_HOST
304
+ #define C10_DEVICE
305
+ #endif
306
+
307
+ #if defined(USE_ROCM)
308
+ #define C10_HIP_HOST_DEVICE __host__ __device__
309
+ #else
310
+ #define C10_HIP_HOST_DEVICE
311
+ #endif
312
+
313
+ #if defined(USE_ROCM)
314
+ #define C10_WARP_SIZE warpSize // = 64 or 32 (Defined in hip_runtime.h)
315
+ #else
316
+ #define C10_WARP_SIZE 32
317
+ #endif
318
+
319
+ #if defined(_MSC_VER) && _MSC_VER <= 1900
320
+ #define __func__ __FUNCTION__
321
+ #endif
322
+
323
+ // CUDA_KERNEL_ASSERT checks the assertion
324
+ // even when NDEBUG is defined. This is useful for important assertions in CUDA
325
+ // code that would otherwise be suppressed when building Release.
326
+ #if defined(__ANDROID__) || defined(__APPLE__) || defined(__FreeBSD__) || \
327
+ (defined(USE_ROCM) && ROCM_VERSION < 40100)
328
+ // Those platforms do not support assert()
329
+ #define CUDA_KERNEL_ASSERT(cond)
330
+ #define SYCL_KERNEL_ASSERT(cond)
331
+ #elif defined(_MSC_VER)
332
+ #if defined(NDEBUG)
333
+ extern "C" {
334
+ C10_IMPORT
335
+ #if defined(__SYCL_DEVICE_ONLY__)
336
+ extern SYCL_EXTERNAL void _wassert(
337
+ const wchar_t* wexpr,
338
+ const wchar_t* wfile,
339
+ unsigned line);
340
+ #else
341
+ #if defined(__CUDA_ARCH__)
342
+ __host__ __device__
343
+ #endif // __CUDA_ARCH__
344
+ void
345
+ _wassert(wchar_t const* _Message, wchar_t const* _File, unsigned _Line);
346
+ #endif // __SYCL_DEVICE_ONLY__
347
+ }
348
+ #endif // NDEBUG
349
+ #define CUDA_KERNEL_ASSERT(cond) \
350
+ if (C10_UNLIKELY(!(cond))) { \
351
+ (void)(_wassert( \
352
+ _CRT_WIDE(#cond), \
353
+ _CRT_WIDE(__FILE__), \
354
+ static_cast<unsigned>(__LINE__)), \
355
+ 0); \
356
+ }
357
+ #define SYCL_KERNEL_ASSERT(cond) \
358
+ if (C10_UNLIKELY(!(cond))) { \
359
+ (void)(_wassert( \
360
+ _CRT_WIDE(#cond), \
361
+ _CRT_WIDE(__FILE__), \
362
+ static_cast<unsigned>(__LINE__)), \
363
+ 0); \
364
+ }
365
+ #else // __APPLE__, _MSC_VER
366
+ #if defined(NDEBUG)
367
+ extern "C" {
368
+ #if defined(__SYCL_DEVICE_ONLY__)
369
+ extern SYCL_EXTERNAL void __assert_fail(
370
+ const char* expr,
371
+ const char* file,
372
+ unsigned int line,
373
+ const char* func);
374
+ #else // __SYCL_DEVICE_ONLY__
375
+ #if (defined(__CUDA_ARCH__) && !(defined(__clang__) && defined(__CUDA__)))
376
+ // CUDA supports __assert_fail function which are common for both device
377
+ // and host side code.
378
+ __host__ __device__
379
+ #endif
380
+
381
+ // This forward declaration matching the declaration of __assert_fail
382
+ // exactly how it is in glibc in case parts of the program are compiled with
383
+ // different NDEBUG settings. Otherwise we might get 'ambiguous declaration'
384
+ // error. Note: On ROCm - this declaration serves for host side compilation.
385
+ void
386
+ __assert_fail(
387
+ const char* assertion,
388
+ const char* file,
389
+ unsigned int line,
390
+ const char* function) noexcept __attribute__((__noreturn__));
391
+
392
+ #endif // __SYCL_DEVICE_ONLY__
393
+ }
394
+ #endif // NDEBUG
395
+ // ROCm disable kernel assert by default
396
+ #if !defined(C10_USE_ROCM_KERNEL_ASSERT) and defined(USE_ROCM)
397
+ #define CUDA_KERNEL_ASSERT(cond)
398
+ #define SYCL_KERNEL_ASSERT(cond)
399
+ #else
400
+ #define CUDA_KERNEL_ASSERT(cond) \
401
+ if (C10_UNLIKELY(!(cond))) { \
402
+ __assert_fail( \
403
+ #cond, __FILE__, static_cast<unsigned int>(__LINE__), __func__); \
404
+ }
405
+ #define SYCL_KERNEL_ASSERT(cond) \
406
+ if (C10_UNLIKELY(!(cond))) { \
407
+ __assert_fail( \
408
+ #cond, __FILE__, static_cast<unsigned int>(__LINE__), __func__); \
409
+ }
410
+ #endif // C10_USE_ROCM_KERNEL_ASSERT and USE_ROCM
411
+ #endif // __APPLE__
412
+
413
+ #ifdef __APPLE__
414
+ #include <TargetConditionals.h>
415
+ #endif
416
+
417
+ #if defined(__ANDROID__)
418
+ #define C10_ANDROID 1
419
+ #define C10_MOBILE 1
420
+ #elif ( \
421
+ defined(__APPLE__) && \
422
+ (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE))
423
+ #define C10_IOS 1
424
+ #define C10_MOBILE 1
425
+ #endif // ANDROID / IOS
426
+
427
+ #if defined(C10_MOBILE) && C10_MOBILE
428
+ #define C10_ALWAYS_INLINE_UNLESS_MOBILE inline
429
+ #else
430
+ #define C10_ALWAYS_INLINE_UNLESS_MOBILE C10_ALWAYS_INLINE
431
+ #endif
432
+
433
+ #if defined(__CUDA_ARCH__)
434
+ #if defined(_MSC_VER) && defined(__CUDACC__)
435
+ #define CONSTEXPR_EXCEPT_WIN_CUDA const
436
+ #define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA __host__
437
+
438
+ // Note [static constexpr char* members for windows NVCC]
439
+ // The Windows NVCC compiler doesn't handle static constexpr class members,
440
+ // although it's fixed in a later version.
441
+ // (see
442
+ // https://developercommunity.visualstudio.com/t/intellisense-error-c11-static-constexpr-member-ini/245425)
443
+ //
444
+ // If we want to ensure that our field is static under all builds, then we need
445
+ // to work around it specifically for windows NVCC by making it (a) const, (b)
446
+ // defined outside of the class definition We need to define it outside of the
447
+ // class definition because of the C++ standard; char* is not an integral type
448
+ // (see
449
+ // https://stackoverflow.com/questions/24278473/intellisense-a-member-of-type-const-char-const-cannot-have-an-in-class-in)
450
+ //
451
+ // So instead of this:
452
+ // struct Foo {
453
+ // static constexpr const char* name = "foo";
454
+ // }
455
+ // In Windows NVCC, we end up with this:
456
+ // struct Foo {
457
+ // static const char* name;
458
+ // }
459
+ // const char* Foo::name = "foo";
460
+ //
461
+ // This gives us a small perf hit for any code that wants to access these field
462
+ // members, but right now it isn't used in any perf-critical code paths.
463
+ #define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \
464
+ static const char* field;
465
+ #define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val) \
466
+ const char* cls::field = val;
467
+ #else
468
+ #define CONSTEXPR_EXCEPT_WIN_CUDA constexpr
469
+ #define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA __host__
470
+
471
+ #define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \
472
+ static constexpr const char* field = val;
473
+ #define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val)
474
+ #endif
475
+ #else
476
+ #if defined(_MSC_VER) && defined(__CUDACC__)
477
+ #define CONSTEXPR_EXCEPT_WIN_CUDA const
478
+ #define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA
479
+
480
+ #define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \
481
+ static const char* field;
482
+ #define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val) \
483
+ const char* cls::field = val;
484
+ #else
485
+ #define CONSTEXPR_EXCEPT_WIN_CUDA constexpr
486
+ #define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA constexpr
487
+
488
+ #define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \
489
+ static constexpr const char* field = val;
490
+ #define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val)
491
+ #endif
492
+ #endif
493
+
494
+ #ifndef HAS_DEMANGLE
495
+ #if defined(__ANDROID__) || defined(_WIN32) || defined(__EMSCRIPTEN__)
496
+ #define HAS_DEMANGLE 0
497
+ #elif defined(__APPLE__) && \
498
+ (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE)
499
+ #define HAS_DEMANGLE 0
500
+ #else
501
+ #define HAS_DEMANGLE 1
502
+ #endif
503
+ #endif // HAS_DEMANGLE
504
+
505
+ #define _C10_PRAGMA__(string) _Pragma(#string)
506
+ #define _C10_PRAGMA_(string) _C10_PRAGMA__(string)
507
+
508
+ #ifdef __clang__
509
+ #define C10_CLANG_DIAGNOSTIC_PUSH() _Pragma("clang diagnostic push")
510
+ #define C10_CLANG_DIAGNOSTIC_POP() _Pragma("clang diagnostic pop")
511
+ #define C10_CLANG_DIAGNOSTIC_IGNORE(flag) \
512
+ _C10_PRAGMA_(clang diagnostic ignored flag)
513
+ #define C10_CLANG_HAS_WARNING(flag) __has_warning(flag)
514
+ #else
515
+ #define C10_CLANG_DIAGNOSTIC_PUSH()
516
+ #define C10_CLANG_DIAGNOSTIC_POP()
517
+ #define C10_CLANG_DIAGNOSTIC_IGNORE(flag)
518
+ #define C10_CLANG_HAS_WARNING(flag) 0
519
+ #endif
520
+
521
+ #ifdef __clang__
522
+
523
+ #define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \
524
+ _C10_PRAGMA_(clang diagnostic push) \
525
+ _C10_PRAGMA_(clang diagnostic ignored "-Wunknown-warning-option") \
526
+ _C10_PRAGMA_(clang diagnostic ignored warning)
527
+
528
+ #define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(clang diagnostic pop)
529
+
530
+ #elif __GNUC__
531
+
532
+ #define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \
533
+ _C10_PRAGMA_(GCC diagnostic push) \
534
+ _C10_PRAGMA_(GCC diagnostic ignored "-Wpragmas") \
535
+ _C10_PRAGMA_(GCC diagnostic ignored warning)
536
+
537
+ #define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(GCC diagnostic pop)
538
+
539
+ #else
540
+
541
+ #define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning)
542
+ #define C10_DIAGNOSTIC_POP()
543
+
544
+ #endif
545
+
546
+ #endif // C10_MACROS_MACROS_H_
shared/package-files/3f/3f2feb5d16c34cfd194ab341d8ee539a1e55f06e55f558971ff615e4f4d7f71c/backend_agg.py ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ An `Anti-Grain Geometry`_ (AGG) backend.
3
+
4
+ Features that are implemented:
5
+
6
+ * capstyles and join styles
7
+ * dashes
8
+ * linewidth
9
+ * lines, rectangles, ellipses
10
+ * clipping to a rectangle
11
+ * output to RGBA and Pillow-supported image formats
12
+ * alpha blending
13
+ * DPI scaling properly - everything scales properly (dashes, linewidths, etc)
14
+ * draw polygon
15
+ * freetype2 w/ ft2font
16
+
17
+ Still TODO:
18
+
19
+ * integrate screen dpi w/ ppi and text
20
+
21
+ .. _Anti-Grain Geometry: http://agg.sourceforge.net/antigrain.com
22
+ """
23
+
24
+ from contextlib import nullcontext
25
+ from math import radians, cos, sin
26
+
27
+ import numpy as np
28
+
29
+ import matplotlib as mpl
30
+ from matplotlib import _api, cbook
31
+ from matplotlib.backend_bases import (
32
+ _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
33
+ from matplotlib.font_manager import fontManager as _fontManager, get_font
34
+ from matplotlib.ft2font import LoadFlags
35
+ from matplotlib.mathtext import MathTextParser
36
+ from matplotlib.path import Path
37
+ from matplotlib.transforms import Bbox, BboxBase
38
+ from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg
39
+
40
+
41
+ def get_hinting_flag():
42
+ mapping = {
43
+ 'default': LoadFlags.DEFAULT,
44
+ 'no_autohint': LoadFlags.NO_AUTOHINT,
45
+ 'force_autohint': LoadFlags.FORCE_AUTOHINT,
46
+ 'no_hinting': LoadFlags.NO_HINTING,
47
+ True: LoadFlags.FORCE_AUTOHINT,
48
+ False: LoadFlags.NO_HINTING,
49
+ 'either': LoadFlags.DEFAULT,
50
+ 'native': LoadFlags.NO_AUTOHINT,
51
+ 'auto': LoadFlags.FORCE_AUTOHINT,
52
+ 'none': LoadFlags.NO_HINTING,
53
+ }
54
+ return mapping[mpl.rcParams['text.hinting']]
55
+
56
+
57
+ class RendererAgg(RendererBase):
58
+ """
59
+ The renderer handles all the drawing primitives using a graphics
60
+ context instance that controls the colors/styles
61
+ """
62
+
63
+ def __init__(self, width, height, dpi):
64
+ super().__init__()
65
+
66
+ self.dpi = dpi
67
+ self.width = width
68
+ self.height = height
69
+ self._renderer = _RendererAgg(int(width), int(height), dpi)
70
+ self._filter_renderers = []
71
+
72
+ self._update_methods()
73
+ self.mathtext_parser = MathTextParser('agg')
74
+
75
+ self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
76
+
77
+ def __getstate__(self):
78
+ # We only want to preserve the init keywords of the Renderer.
79
+ # Anything else can be re-created.
80
+ return {'width': self.width, 'height': self.height, 'dpi': self.dpi}
81
+
82
+ def __setstate__(self, state):
83
+ self.__init__(state['width'], state['height'], state['dpi'])
84
+
85
+ def _update_methods(self):
86
+ self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles
87
+ self.draw_image = self._renderer.draw_image
88
+ self.draw_markers = self._renderer.draw_markers
89
+ self.draw_path_collection = self._renderer.draw_path_collection
90
+ self.draw_quad_mesh = self._renderer.draw_quad_mesh
91
+ self.copy_from_bbox = self._renderer.copy_from_bbox
92
+
93
+ def draw_path(self, gc, path, transform, rgbFace=None):
94
+ # docstring inherited
95
+ nmax = mpl.rcParams['agg.path.chunksize'] # here at least for testing
96
+ npts = path.vertices.shape[0]
97
+
98
+ if (npts > nmax > 100 and path.should_simplify and
99
+ rgbFace is None and gc.get_hatch() is None):
100
+ nch = np.ceil(npts / nmax)
101
+ chsize = int(np.ceil(npts / nch))
102
+ i0 = np.arange(0, npts, chsize)
103
+ i1 = np.zeros_like(i0)
104
+ i1[:-1] = i0[1:] - 1
105
+ i1[-1] = npts
106
+ for ii0, ii1 in zip(i0, i1):
107
+ v = path.vertices[ii0:ii1, :]
108
+ c = path.codes
109
+ if c is not None:
110
+ c = c[ii0:ii1]
111
+ c[0] = Path.MOVETO # move to end of last chunk
112
+ p = Path(v, c)
113
+ p.simplify_threshold = path.simplify_threshold
114
+ try:
115
+ self._renderer.draw_path(gc, p, transform, rgbFace)
116
+ except OverflowError:
117
+ msg = (
118
+ "Exceeded cell block limit in Agg.\n\n"
119
+ "Please reduce the value of "
120
+ f"rcParams['agg.path.chunksize'] (currently {nmax}) "
121
+ "or increase the path simplification threshold"
122
+ "(rcParams['path.simplify_threshold'] = "
123
+ f"{mpl.rcParams['path.simplify_threshold']:.2f} by "
124
+ "default and path.simplify_threshold = "
125
+ f"{path.simplify_threshold:.2f} on the input)."
126
+ )
127
+ raise OverflowError(msg) from None
128
+ else:
129
+ try:
130
+ self._renderer.draw_path(gc, path, transform, rgbFace)
131
+ except OverflowError:
132
+ cant_chunk = ''
133
+ if rgbFace is not None:
134
+ cant_chunk += "- cannot split filled path\n"
135
+ if gc.get_hatch() is not None:
136
+ cant_chunk += "- cannot split hatched path\n"
137
+ if not path.should_simplify:
138
+ cant_chunk += "- path.should_simplify is False\n"
139
+ if len(cant_chunk):
140
+ msg = (
141
+ "Exceeded cell block limit in Agg, however for the "
142
+ "following reasons:\n\n"
143
+ f"{cant_chunk}\n"
144
+ "we cannot automatically split up this path to draw."
145
+ "\n\nPlease manually simplify your path."
146
+ )
147
+
148
+ else:
149
+ inc_threshold = (
150
+ "or increase the path simplification threshold"
151
+ "(rcParams['path.simplify_threshold'] = "
152
+ f"{mpl.rcParams['path.simplify_threshold']} "
153
+ "by default and path.simplify_threshold "
154
+ f"= {path.simplify_threshold} "
155
+ "on the input)."
156
+ )
157
+ if nmax > 100:
158
+ msg = (
159
+ "Exceeded cell block limit in Agg. Please reduce "
160
+ "the value of rcParams['agg.path.chunksize'] "
161
+ f"(currently {nmax}) {inc_threshold}"
162
+ )
163
+ else:
164
+ msg = (
165
+ "Exceeded cell block limit in Agg. Please set "
166
+ "the value of rcParams['agg.path.chunksize'], "
167
+ f"(currently {nmax}) to be greater than 100 "
168
+ + inc_threshold
169
+ )
170
+
171
+ raise OverflowError(msg) from None
172
+
173
+ def draw_mathtext(self, gc, x, y, s, prop, angle):
174
+ """Draw mathtext using :mod:`matplotlib.mathtext`."""
175
+ ox, oy, width, height, descent, font_image = \
176
+ self.mathtext_parser.parse(s, self.dpi, prop,
177
+ antialiased=gc.get_antialiased())
178
+
179
+ xd = descent * sin(radians(angle))
180
+ yd = descent * cos(radians(angle))
181
+ x = round(x + ox + xd)
182
+ y = round(y - oy + yd)
183
+ self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
184
+
185
+ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
186
+ # docstring inherited
187
+ if ismath:
188
+ return self.draw_mathtext(gc, x, y, s, prop, angle)
189
+ font = self._prepare_font(prop)
190
+ # We pass '0' for angle here, since it will be rotated (in raster
191
+ # space) in the following call to draw_text_image).
192
+ font.set_text(s, 0, flags=get_hinting_flag())
193
+ font.draw_glyphs_to_bitmap(
194
+ antialiased=gc.get_antialiased())
195
+ d = font.get_descent() / 64.0
196
+ # The descent needs to be adjusted for the angle.
197
+ xo, yo = font.get_bitmap_offset()
198
+ xo /= 64.0
199
+ yo /= 64.0
200
+ xd = d * sin(radians(angle))
201
+ yd = d * cos(radians(angle))
202
+ x = round(x + xo + xd)
203
+ y = round(y + yo + yd)
204
+ self._renderer.draw_text_image(font, x, y + 1, angle, gc)
205
+
206
+ def get_text_width_height_descent(self, s, prop, ismath):
207
+ # docstring inherited
208
+
209
+ _api.check_in_list(["TeX", True, False], ismath=ismath)
210
+ if ismath == "TeX":
211
+ return super().get_text_width_height_descent(s, prop, ismath)
212
+
213
+ if ismath:
214
+ ox, oy, width, height, descent, font_image = \
215
+ self.mathtext_parser.parse(s, self.dpi, prop)
216
+ return width, height, descent
217
+
218
+ font = self._prepare_font(prop)
219
+ font.set_text(s, 0.0, flags=get_hinting_flag())
220
+ w, h = font.get_width_height() # width and height of unrotated string
221
+ d = font.get_descent()
222
+ w /= 64.0 # convert from subpixels
223
+ h /= 64.0
224
+ d /= 64.0
225
+ return w, h, d
226
+
227
+ def draw_tex(self, gc, x, y, s, prop, angle, *, mtext=None):
228
+ # docstring inherited
229
+ # todo, handle props, angle, origins
230
+ size = prop.get_size_in_points()
231
+
232
+ texmanager = self.get_texmanager()
233
+
234
+ Z = texmanager.get_grey(s, size, self.dpi)
235
+ Z = np.array(Z * 255.0, np.uint8)
236
+
237
+ w, h, d = self.get_text_width_height_descent(s, prop, ismath="TeX")
238
+ xd = d * sin(radians(angle))
239
+ yd = d * cos(radians(angle))
240
+ x = round(x + xd)
241
+ y = round(y + yd)
242
+ self._renderer.draw_text_image(Z, x, y, angle, gc)
243
+
244
+ def get_canvas_width_height(self):
245
+ # docstring inherited
246
+ return self.width, self.height
247
+
248
+ def _prepare_font(self, font_prop):
249
+ """
250
+ Get the `.FT2Font` for *font_prop*, clear its buffer, and set its size.
251
+ """
252
+ font = get_font(_fontManager._find_fonts_by_props(font_prop))
253
+ font.clear()
254
+ size = font_prop.get_size_in_points()
255
+ font.set_size(size, self.dpi)
256
+ return font
257
+
258
+ def points_to_pixels(self, points):
259
+ # docstring inherited
260
+ return points * self.dpi / 72
261
+
262
+ def buffer_rgba(self):
263
+ return memoryview(self._renderer)
264
+
265
+ def tostring_argb(self):
266
+ return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes()
267
+
268
+ def clear(self):
269
+ self._renderer.clear()
270
+
271
+ def option_image_nocomposite(self):
272
+ # docstring inherited
273
+
274
+ # It is generally faster to composite each image directly to
275
+ # the Figure, and there's no file size benefit to compositing
276
+ # with the Agg backend
277
+ return True
278
+
279
+ def option_scale_image(self):
280
+ # docstring inherited
281
+ return False
282
+
283
+ def restore_region(self, region, bbox=None, xy=None):
284
+ """
285
+ Restore the saved region. If bbox (instance of BboxBase, or
286
+ its extents) is given, only the region specified by the bbox
287
+ will be restored. *xy* (a pair of floats) optionally
288
+ specifies the new position (the LLC of the original region,
289
+ not the LLC of the bbox) where the region will be restored.
290
+
291
+ >>> region = renderer.copy_from_bbox()
292
+ >>> x1, y1, x2, y2 = region.get_extents()
293
+ >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
294
+ ... xy=(x1-dx, y1))
295
+
296
+ """
297
+ if bbox is not None or xy is not None:
298
+ if bbox is None:
299
+ x1, y1, x2, y2 = region.get_extents()
300
+ elif isinstance(bbox, BboxBase):
301
+ x1, y1, x2, y2 = bbox.extents
302
+ else:
303
+ x1, y1, x2, y2 = bbox
304
+
305
+ if xy is None:
306
+ ox, oy = x1, y1
307
+ else:
308
+ ox, oy = xy
309
+
310
+ # The incoming data is float, but the _renderer type-checking wants
311
+ # to see integers.
312
+ self._renderer.restore_region(region, int(x1), int(y1),
313
+ int(x2), int(y2), int(ox), int(oy))
314
+
315
+ else:
316
+ self._renderer.restore_region(region)
317
+
318
+ def start_filter(self):
319
+ """
320
+ Start filtering. It simply creates a new canvas (the old one is saved).
321
+ """
322
+ self._filter_renderers.append(self._renderer)
323
+ self._renderer = _RendererAgg(int(self.width), int(self.height),
324
+ self.dpi)
325
+ self._update_methods()
326
+
327
+ def stop_filter(self, post_processing):
328
+ """
329
+ Save the current canvas as an image and apply post processing.
330
+
331
+ The *post_processing* function::
332
+
333
+ def post_processing(image, dpi):
334
+ # ny, nx, depth = image.shape
335
+ # image (numpy array) has RGBA channels and has a depth of 4.
336
+ ...
337
+ # create a new_image (numpy array of 4 channels, size can be
338
+ # different). The resulting image may have offsets from
339
+ # lower-left corner of the original image
340
+ return new_image, offset_x, offset_y
341
+
342
+ The saved renderer is restored and the returned image from
343
+ post_processing is plotted (using draw_image) on it.
344
+ """
345
+ orig_img = np.asarray(self.buffer_rgba())
346
+ slice_y, slice_x = cbook._get_nonzero_slices(orig_img[..., 3])
347
+ cropped_img = orig_img[slice_y, slice_x]
348
+
349
+ self._renderer = self._filter_renderers.pop()
350
+ self._update_methods()
351
+
352
+ if cropped_img.size:
353
+ img, ox, oy = post_processing(cropped_img / 255, self.dpi)
354
+ gc = self.new_gc()
355
+ if img.dtype.kind == 'f':
356
+ img = np.asarray(img * 255., np.uint8)
357
+ self._renderer.draw_image(
358
+ gc, slice_x.start + ox, int(self.height) - slice_y.stop + oy,
359
+ img[::-1])
360
+
361
+
362
+ class FigureCanvasAgg(FigureCanvasBase):
363
+ # docstring inherited
364
+
365
+ _lastKey = None # Overwritten per-instance on the first draw.
366
+
367
+ def copy_from_bbox(self, bbox):
368
+ renderer = self.get_renderer()
369
+ return renderer.copy_from_bbox(bbox)
370
+
371
+ def restore_region(self, region, bbox=None, xy=None):
372
+ renderer = self.get_renderer()
373
+ return renderer.restore_region(region, bbox, xy)
374
+
375
+ def draw(self):
376
+ # docstring inherited
377
+ self.renderer = self.get_renderer()
378
+ self.renderer.clear()
379
+ # Acquire a lock on the shared font cache.
380
+ with (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
381
+ else nullcontext()):
382
+ self.figure.draw(self.renderer)
383
+ # A GUI class may be need to update a window using this draw, so
384
+ # don't forget to call the superclass.
385
+ super().draw()
386
+
387
+ def get_renderer(self):
388
+ w, h = self.figure.bbox.size
389
+ key = w, h, self.figure.dpi
390
+ reuse_renderer = (self._lastKey == key)
391
+ if not reuse_renderer:
392
+ self.renderer = RendererAgg(w, h, self.figure.dpi)
393
+ self._lastKey = key
394
+ return self.renderer
395
+
396
+ def tostring_argb(self):
397
+ """
398
+ Get the image as ARGB `bytes`.
399
+
400
+ `draw` must be called at least once before this function will work and
401
+ to update the renderer for any subsequent changes to the Figure.
402
+ """
403
+ return self.renderer.tostring_argb()
404
+
405
+ def buffer_rgba(self):
406
+ """
407
+ Get the image as a `memoryview` to the renderer's buffer.
408
+
409
+ `draw` must be called at least once before this function will work and
410
+ to update the renderer for any subsequent changes to the Figure.
411
+ """
412
+ return self.renderer.buffer_rgba()
413
+
414
+ def print_raw(self, filename_or_obj, *, metadata=None):
415
+ if metadata is not None:
416
+ raise ValueError("metadata not supported for raw/rgba")
417
+ FigureCanvasAgg.draw(self)
418
+ renderer = self.get_renderer()
419
+ with cbook.open_file_cm(filename_or_obj, "wb") as fh:
420
+ fh.write(renderer.buffer_rgba())
421
+
422
+ print_rgba = print_raw
423
+
424
+ def _print_pil(self, filename_or_obj, fmt, pil_kwargs, metadata=None):
425
+ """
426
+ Draw the canvas, then save it using `.image.imsave` (to which
427
+ *pil_kwargs* and *metadata* are forwarded).
428
+ """
429
+ FigureCanvasAgg.draw(self)
430
+ mpl.image.imsave(
431
+ filename_or_obj, self.buffer_rgba(), format=fmt, origin="upper",
432
+ dpi=self.figure.dpi, metadata=metadata, pil_kwargs=pil_kwargs)
433
+
434
+ def print_png(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
435
+ """
436
+ Write the figure to a PNG file.
437
+
438
+ Parameters
439
+ ----------
440
+ filename_or_obj : str or path-like or file-like
441
+ The file to write to.
442
+
443
+ metadata : dict, optional
444
+ Metadata in the PNG file as key-value pairs of bytes or latin-1
445
+ encodable strings.
446
+ According to the PNG specification, keys must be shorter than 79
447
+ chars.
448
+
449
+ The `PNG specification`_ defines some common keywords that may be
450
+ used as appropriate:
451
+
452
+ - Title: Short (one line) title or caption for image.
453
+ - Author: Name of image's creator.
454
+ - Description: Description of image (possibly long).
455
+ - Copyright: Copyright notice.
456
+ - Creation Time: Time of original image creation
457
+ (usually RFC 1123 format).
458
+ - Software: Software used to create the image.
459
+ - Disclaimer: Legal disclaimer.
460
+ - Warning: Warning of nature of content.
461
+ - Source: Device used to create the image.
462
+ - Comment: Miscellaneous comment;
463
+ conversion from other image format.
464
+
465
+ Other keywords may be invented for other purposes.
466
+
467
+ If 'Software' is not given, an autogenerated value for Matplotlib
468
+ will be used. This can be removed by setting it to *None*.
469
+
470
+ For more details see the `PNG specification`_.
471
+
472
+ .. _PNG specification: \
473
+ https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
474
+
475
+ pil_kwargs : dict, optional
476
+ Keyword arguments passed to `PIL.Image.Image.save`.
477
+
478
+ If the 'pnginfo' key is present, it completely overrides
479
+ *metadata*, including the default 'Software' key.
480
+ """
481
+ self._print_pil(filename_or_obj, "png", pil_kwargs, metadata)
482
+
483
+ def print_to_buffer(self):
484
+ FigureCanvasAgg.draw(self)
485
+ renderer = self.get_renderer()
486
+ return (bytes(renderer.buffer_rgba()),
487
+ (int(renderer.width), int(renderer.height)))
488
+
489
+ # Note that these methods should typically be called via savefig() and
490
+ # print_figure(), and the latter ensures that `self.figure.dpi` already
491
+ # matches the dpi kwarg (if any).
492
+
493
+ def print_jpg(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
494
+ # savefig() has already applied savefig.facecolor; we now set it to
495
+ # white to make imsave() blend semi-transparent figures against an
496
+ # assumed white background.
497
+ with mpl.rc_context({"savefig.facecolor": "white"}):
498
+ self._print_pil(filename_or_obj, "jpeg", pil_kwargs, metadata)
499
+
500
+ print_jpeg = print_jpg
501
+
502
+ def print_tif(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
503
+ self._print_pil(filename_or_obj, "tiff", pil_kwargs, metadata)
504
+
505
+ print_tiff = print_tif
506
+
507
+ def print_webp(self, filename_or_obj, *, metadata=None, pil_kwargs=None):
508
+ self._print_pil(filename_or_obj, "webp", pil_kwargs, metadata)
509
+
510
+ print_jpg.__doc__, print_tif.__doc__, print_webp.__doc__ = map(
511
+ """
512
+ Write the figure to a {} file.
513
+
514
+ Parameters
515
+ ----------
516
+ filename_or_obj : str or path-like or file-like
517
+ The file to write to.
518
+ pil_kwargs : dict, optional
519
+ Additional keyword arguments that are passed to
520
+ `PIL.Image.Image.save` when saving the figure.
521
+ """.format, ["JPEG", "TIFF", "WebP"])
522
+
523
+
524
+ @_Backend.export
525
+ class _BackendAgg(_Backend):
526
+ backend_version = 'v2.2'
527
+ FigureCanvas = FigureCanvasAgg
528
+ FigureManager = FigureManagerBase
shared/package-files/3f/3f30a4950dc015072ad42e81dc87c2814e75e74cdaf4334b4aa258db6f5e727d/aaa-20 ADDED
Binary file (1.26 kB). View file
 
shared/package-files/3f/3f30f43004cc3632e33e2f465b919018be94a9cd944feb8fc27ce18bb4e4247f/kauers.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def finite_diff(expression, variable, increment=1):
2
+ """
3
+ Takes as input a polynomial expression and the variable used to construct
4
+ it and returns the difference between function's value when the input is
5
+ incremented to 1 and the original function value. If you want an increment
6
+ other than one supply it as a third argument.
7
+
8
+ Examples
9
+ ========
10
+
11
+ >>> from sympy.abc import x, y, z
12
+ >>> from sympy.series.kauers import finite_diff
13
+ >>> finite_diff(x**2, x)
14
+ 2*x + 1
15
+ >>> finite_diff(y**3 + 2*y**2 + 3*y + 4, y)
16
+ 3*y**2 + 7*y + 6
17
+ >>> finite_diff(x**2 + 3*x + 8, x, 2)
18
+ 4*x + 10
19
+ >>> finite_diff(z**3 + 8*z, z, 3)
20
+ 9*z**2 + 27*z + 51
21
+ """
22
+ expression = expression.expand()
23
+ expression2 = expression.subs(variable, variable + increment)
24
+ expression2 = expression2.expand()
25
+ return expression2 - expression
26
+
27
+ def finite_diff_kauers(sum):
28
+ """
29
+ Takes as input a Sum instance and returns the difference between the sum
30
+ with the upper index incremented by 1 and the original sum. For example,
31
+ if S(n) is a sum, then finite_diff_kauers will return S(n + 1) - S(n).
32
+
33
+ Examples
34
+ ========
35
+
36
+ >>> from sympy.series.kauers import finite_diff_kauers
37
+ >>> from sympy import Sum
38
+ >>> from sympy.abc import x, y, m, n, k
39
+ >>> finite_diff_kauers(Sum(k, (k, 1, n)))
40
+ n + 1
41
+ >>> finite_diff_kauers(Sum(1/k, (k, 1, n)))
42
+ 1/(n + 1)
43
+ >>> finite_diff_kauers(Sum((x*y**2), (x, 1, n), (y, 1, m)))
44
+ (m + 1)**2*(n + 1)
45
+ >>> finite_diff_kauers(Sum((x*y), (x, 1, m), (y, 1, n)))
46
+ (m + 1)*(n + 1)
47
+ """
48
+ function = sum.function
49
+ for l in sum.limits:
50
+ function = function.subs(l[0], l[- 1] + 1)
51
+ return function
shared/package-files/3f/3f33e456c34305487ac20cc566fabf60d6dad9b766c123bf1fc0542bd671032b/test_rolling.py ADDED
@@ -0,0 +1,1979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import (
2
+ datetime,
3
+ timedelta,
4
+ )
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas.compat import (
10
+ IS64,
11
+ is_platform_arm,
12
+ is_platform_power,
13
+ )
14
+
15
+ from pandas import (
16
+ DataFrame,
17
+ DatetimeIndex,
18
+ MultiIndex,
19
+ Series,
20
+ Timedelta,
21
+ Timestamp,
22
+ date_range,
23
+ period_range,
24
+ to_datetime,
25
+ to_timedelta,
26
+ )
27
+ import pandas._testing as tm
28
+ from pandas.api.indexers import BaseIndexer
29
+ from pandas.core.indexers.objects import VariableOffsetWindowIndexer
30
+
31
+ from pandas.tseries.offsets import BusinessDay
32
+
33
+
34
+ def test_doc_string():
35
+ df = DataFrame({"B": [0, 1, 2, np.nan, 4]})
36
+ df
37
+ df.rolling(2).sum()
38
+ df.rolling(2, min_periods=1).sum()
39
+
40
+
41
+ def test_constructor(frame_or_series):
42
+ # GH 12669
43
+
44
+ c = frame_or_series(range(5)).rolling
45
+
46
+ # valid
47
+ c(0)
48
+ c(window=2)
49
+ c(window=2, min_periods=1)
50
+ c(window=2, min_periods=1, center=True)
51
+ c(window=2, min_periods=1, center=False)
52
+
53
+ # GH 13383
54
+
55
+ msg = "window must be an integer 0 or greater"
56
+
57
+ with pytest.raises(ValueError, match=msg):
58
+ c(-1)
59
+
60
+
61
+ @pytest.mark.parametrize("w", [2.0, "foo", np.array([2])])
62
+ def test_invalid_constructor(frame_or_series, w):
63
+ # not valid
64
+
65
+ c = frame_or_series(range(5)).rolling
66
+
67
+ msg = "|".join(
68
+ [
69
+ "window must be an integer",
70
+ "passed window foo is not compatible with a datetimelike index",
71
+ ]
72
+ )
73
+ with pytest.raises(ValueError, match=msg):
74
+ c(window=w)
75
+
76
+ msg = "min_periods must be an integer"
77
+ with pytest.raises(ValueError, match=msg):
78
+ c(window=2, min_periods=w)
79
+
80
+ msg = "center must be a boolean"
81
+ with pytest.raises(ValueError, match=msg):
82
+ c(window=2, min_periods=1, center=w)
83
+
84
+
85
+ @pytest.mark.parametrize(
86
+ "window",
87
+ [
88
+ timedelta(days=3),
89
+ Timedelta(days=3),
90
+ "3D",
91
+ VariableOffsetWindowIndexer(
92
+ index=date_range("2015-12-25", periods=5), offset=BusinessDay(1)
93
+ ),
94
+ ],
95
+ )
96
+ def test_freq_window_not_implemented(window):
97
+ # GH 15354
98
+ df = DataFrame(
99
+ np.arange(10),
100
+ index=date_range("2015-12-24", periods=10, freq="D"),
101
+ )
102
+ with pytest.raises(
103
+ NotImplementedError, match="^step (not implemented|is not supported)"
104
+ ):
105
+ df.rolling(window, step=3).sum()
106
+
107
+
108
+ @pytest.mark.parametrize("agg", ["cov", "corr"])
109
+ def test_step_not_implemented_for_cov_corr(agg):
110
+ # GH 15354
111
+ roll = DataFrame(range(2)).rolling(1, step=2)
112
+ with pytest.raises(NotImplementedError, match="step not implemented"):
113
+ getattr(roll, agg)()
114
+
115
+
116
+ @pytest.mark.parametrize("window", [timedelta(days=3), Timedelta(days=3)])
117
+ def test_constructor_with_timedelta_window(window):
118
+ # GH 15440
119
+ n = 10
120
+ df = DataFrame(
121
+ {"value": np.arange(n)},
122
+ index=date_range("2015-12-24", periods=n, freq="D"),
123
+ )
124
+ expected_data = np.append([0.0, 1.0], np.arange(3.0, 27.0, 3))
125
+
126
+ result = df.rolling(window=window).sum()
127
+ expected = DataFrame(
128
+ {"value": expected_data},
129
+ index=date_range("2015-12-24", periods=n, freq="D"),
130
+ )
131
+ tm.assert_frame_equal(result, expected)
132
+ expected = df.rolling("3D").sum()
133
+ tm.assert_frame_equal(result, expected)
134
+
135
+
136
+ @pytest.mark.parametrize("window", [timedelta(days=3), Timedelta(days=3), "3D"])
137
+ def test_constructor_timedelta_window_and_minperiods(window, raw):
138
+ # GH 15305
139
+ n = 10
140
+ df = DataFrame(
141
+ {"value": np.arange(n)},
142
+ index=date_range("2017-08-08", periods=n, freq="D"),
143
+ )
144
+ expected = DataFrame(
145
+ {"value": np.append([np.nan, 1.0], np.arange(3.0, 27.0, 3))},
146
+ index=date_range("2017-08-08", periods=n, freq="D"),
147
+ )
148
+ result_roll_sum = df.rolling(window=window, min_periods=2).sum()
149
+ result_roll_generic = df.rolling(window=window, min_periods=2).apply(sum, raw=raw)
150
+ tm.assert_frame_equal(result_roll_sum, expected)
151
+ tm.assert_frame_equal(result_roll_generic, expected)
152
+
153
+
154
+ def test_closed_fixed(closed, arithmetic_win_operators):
155
+ # GH 34315
156
+ func_name = arithmetic_win_operators
157
+ df_fixed = DataFrame({"A": [0, 1, 2, 3, 4]})
158
+ df_time = DataFrame({"A": [0, 1, 2, 3, 4]}, index=date_range("2020", periods=5))
159
+
160
+ result = getattr(
161
+ df_fixed.rolling(2, closed=closed, min_periods=1),
162
+ func_name,
163
+ )()
164
+ expected = getattr(
165
+ df_time.rolling("2D", closed=closed, min_periods=1),
166
+ func_name,
167
+ )().reset_index(drop=True)
168
+
169
+ tm.assert_frame_equal(result, expected)
170
+
171
+
172
+ @pytest.mark.parametrize(
173
+ "closed, window_selections",
174
+ [
175
+ (
176
+ "both",
177
+ [
178
+ [True, True, False, False, False],
179
+ [True, True, True, False, False],
180
+ [False, True, True, True, False],
181
+ [False, False, True, True, True],
182
+ [False, False, False, True, True],
183
+ ],
184
+ ),
185
+ (
186
+ "left",
187
+ [
188
+ [True, False, False, False, False],
189
+ [True, True, False, False, False],
190
+ [False, True, True, False, False],
191
+ [False, False, True, True, False],
192
+ [False, False, False, True, True],
193
+ ],
194
+ ),
195
+ (
196
+ "right",
197
+ [
198
+ [True, True, False, False, False],
199
+ [False, True, True, False, False],
200
+ [False, False, True, True, False],
201
+ [False, False, False, True, True],
202
+ [False, False, False, False, True],
203
+ ],
204
+ ),
205
+ (
206
+ "neither",
207
+ [
208
+ [True, False, False, False, False],
209
+ [False, True, False, False, False],
210
+ [False, False, True, False, False],
211
+ [False, False, False, True, False],
212
+ [False, False, False, False, True],
213
+ ],
214
+ ),
215
+ ],
216
+ )
217
+ def test_datetimelike_centered_selections(
218
+ closed, window_selections, arithmetic_win_operators
219
+ ):
220
+ # GH 34315
221
+ func_name = arithmetic_win_operators
222
+ df_time = DataFrame(
223
+ {"A": [0.0, 1.0, 2.0, 3.0, 4.0]}, index=date_range("2020", periods=5)
224
+ )
225
+
226
+ expected = DataFrame(
227
+ {"A": [getattr(df_time["A"].iloc[s], func_name)() for s in window_selections]},
228
+ index=date_range("2020", periods=5),
229
+ )
230
+
231
+ if func_name == "sem":
232
+ kwargs = {"ddof": 0}
233
+ else:
234
+ kwargs = {}
235
+
236
+ result = getattr(
237
+ df_time.rolling("2D", closed=closed, min_periods=1, center=True),
238
+ func_name,
239
+ )(**kwargs)
240
+
241
+ tm.assert_frame_equal(result, expected, check_dtype=False)
242
+
243
+
244
+ @pytest.mark.parametrize(
245
+ "window,closed,expected",
246
+ [
247
+ ("3s", "right", [3.0, 3.0, 3.0]),
248
+ ("3s", "both", [3.0, 3.0, 3.0]),
249
+ ("3s", "left", [3.0, 3.0, 3.0]),
250
+ ("3s", "neither", [3.0, 3.0, 3.0]),
251
+ ("2s", "right", [3.0, 2.0, 2.0]),
252
+ ("2s", "both", [3.0, 3.0, 3.0]),
253
+ ("2s", "left", [1.0, 3.0, 3.0]),
254
+ ("2s", "neither", [1.0, 2.0, 2.0]),
255
+ ],
256
+ )
257
+ def test_datetimelike_centered_offset_covers_all(
258
+ window, closed, expected, frame_or_series
259
+ ):
260
+ # GH 42753
261
+
262
+ index = [
263
+ Timestamp("20130101 09:00:01"),
264
+ Timestamp("20130101 09:00:02"),
265
+ Timestamp("20130101 09:00:02"),
266
+ ]
267
+ df = frame_or_series([1, 1, 1], index=index)
268
+
269
+ result = df.rolling(window, closed=closed, center=True).sum()
270
+ expected = frame_or_series(expected, index=index)
271
+ tm.assert_equal(result, expected)
272
+
273
+
274
+ @pytest.mark.parametrize(
275
+ "window,closed,expected",
276
+ [
277
+ ("2D", "right", [4, 4, 4, 4, 4, 4, 2, 2]),
278
+ ("2D", "left", [2, 2, 4, 4, 4, 4, 4, 4]),
279
+ ("2D", "both", [4, 4, 6, 6, 6, 6, 4, 4]),
280
+ ("2D", "neither", [2, 2, 2, 2, 2, 2, 2, 2]),
281
+ ],
282
+ )
283
+ def test_datetimelike_nonunique_index_centering(
284
+ window, closed, expected, frame_or_series
285
+ ):
286
+ index = DatetimeIndex(
287
+ [
288
+ "2020-01-01",
289
+ "2020-01-01",
290
+ "2020-01-02",
291
+ "2020-01-02",
292
+ "2020-01-03",
293
+ "2020-01-03",
294
+ "2020-01-04",
295
+ "2020-01-04",
296
+ ]
297
+ )
298
+
299
+ df = frame_or_series([1] * 8, index=index, dtype=float)
300
+ expected = frame_or_series(expected, index=index, dtype=float)
301
+
302
+ result = df.rolling(window, center=True, closed=closed).sum()
303
+
304
+ tm.assert_equal(result, expected)
305
+
306
+
307
+ @pytest.mark.parametrize(
308
+ "closed,expected",
309
+ [
310
+ ("left", [np.nan, np.nan, 1, 1, 1, 10, 14, 14, 18, 21]),
311
+ ("neither", [np.nan, np.nan, 1, 1, 1, 9, 5, 5, 13, 8]),
312
+ ("right", [0, 1, 3, 6, 10, 14, 11, 18, 21, 17]),
313
+ ("both", [0, 1, 3, 6, 10, 15, 20, 27, 26, 30]),
314
+ ],
315
+ )
316
+ def test_variable_window_nonunique(closed, expected, frame_or_series):
317
+ # GH 20712
318
+ index = DatetimeIndex(
319
+ [
320
+ "2011-01-01",
321
+ "2011-01-01",
322
+ "2011-01-02",
323
+ "2011-01-02",
324
+ "2011-01-02",
325
+ "2011-01-03",
326
+ "2011-01-04",
327
+ "2011-01-04",
328
+ "2011-01-05",
329
+ "2011-01-06",
330
+ ]
331
+ )
332
+
333
+ df = frame_or_series(range(10), index=index, dtype=float)
334
+ expected = frame_or_series(expected, index=index, dtype=float)
335
+
336
+ result = df.rolling("2D", closed=closed).sum()
337
+
338
+ tm.assert_equal(result, expected)
339
+
340
+
341
+ @pytest.mark.parametrize(
342
+ "closed,expected",
343
+ [
344
+ ("left", [np.nan, np.nan, 1, 1, 1, 10, 15, 15, 18, 21]),
345
+ ("neither", [np.nan, np.nan, 1, 1, 1, 10, 15, 15, 13, 8]),
346
+ ("right", [0, 1, 3, 6, 10, 15, 21, 28, 21, 17]),
347
+ ("both", [0, 1, 3, 6, 10, 15, 21, 28, 26, 30]),
348
+ ],
349
+ )
350
+ def test_variable_offset_window_nonunique(closed, expected, frame_or_series):
351
+ # GH 20712
352
+ index = DatetimeIndex(
353
+ [
354
+ "2011-01-01",
355
+ "2011-01-01",
356
+ "2011-01-02",
357
+ "2011-01-02",
358
+ "2011-01-02",
359
+ "2011-01-03",
360
+ "2011-01-04",
361
+ "2011-01-04",
362
+ "2011-01-05",
363
+ "2011-01-06",
364
+ ]
365
+ )
366
+
367
+ df = frame_or_series(range(10), index=index, dtype=float)
368
+ expected = frame_or_series(expected, index=index, dtype=float)
369
+
370
+ offset = BusinessDay(2)
371
+ indexer = VariableOffsetWindowIndexer(index=index, offset=offset)
372
+ result = df.rolling(indexer, closed=closed, min_periods=1).sum()
373
+
374
+ tm.assert_equal(result, expected)
375
+
376
+
377
+ def test_even_number_window_alignment():
378
+ # see discussion in GH 38780
379
+ s = Series(range(3), index=date_range(start="2020-01-01", freq="D", periods=3))
380
+
381
+ # behavior of index- and datetime-based windows differs here!
382
+ # s.rolling(window=2, min_periods=1, center=True).mean()
383
+
384
+ result = s.rolling(window="2D", min_periods=1, center=True).mean()
385
+
386
+ expected = Series([0.5, 1.5, 2], index=s.index)
387
+
388
+ tm.assert_series_equal(result, expected)
389
+
390
+
391
+ def test_closed_fixed_binary_col(center, step):
392
+ # GH 34315
393
+ data = [0, 1, 1, 0, 0, 1, 0, 1]
394
+ df = DataFrame(
395
+ {"binary_col": data},
396
+ index=date_range(start="2020-01-01", freq="min", periods=len(data)),
397
+ )
398
+
399
+ if center:
400
+ expected_data = [2 / 3, 0.5, 0.4, 0.5, 0.428571, 0.5, 0.571429, 0.5]
401
+ else:
402
+ expected_data = [np.nan, 0, 0.5, 2 / 3, 0.5, 0.4, 0.5, 0.428571]
403
+
404
+ expected = DataFrame(
405
+ expected_data,
406
+ columns=["binary_col"],
407
+ index=date_range(start="2020-01-01", freq="min", periods=len(expected_data)),
408
+ )[::step]
409
+
410
+ rolling = df.rolling(
411
+ window=len(df), closed="left", min_periods=1, center=center, step=step
412
+ )
413
+ result = rolling.mean()
414
+ tm.assert_frame_equal(result, expected)
415
+
416
+
417
+ @pytest.mark.parametrize("closed", ["neither", "left"])
418
+ def test_closed_empty(closed, arithmetic_win_operators):
419
+ # GH 26005
420
+ func_name = arithmetic_win_operators
421
+ ser = Series(data=np.arange(5), index=date_range("2000", periods=5, freq="2D"))
422
+ roll = ser.rolling("1D", closed=closed)
423
+
424
+ result = getattr(roll, func_name)()
425
+ expected = Series([np.nan] * 5, index=ser.index)
426
+ tm.assert_series_equal(result, expected)
427
+
428
+
429
+ @pytest.mark.parametrize("func", ["min", "max"])
430
+ def test_closed_one_entry(func):
431
+ # GH24718
432
+ ser = Series(data=[2], index=date_range("2000", periods=1))
433
+ result = getattr(ser.rolling("10D", closed="left"), func)()
434
+ tm.assert_series_equal(result, Series([np.nan], index=ser.index))
435
+
436
+
437
+ @pytest.mark.parametrize("func", ["min", "max"])
438
+ def test_closed_one_entry_groupby(func):
439
+ # GH24718
440
+ ser = DataFrame(
441
+ data={"A": [1, 1, 2], "B": [3, 2, 1]},
442
+ index=date_range("2000", periods=3),
443
+ )
444
+ result = getattr(
445
+ ser.groupby("A", sort=False)["B"].rolling("10D", closed="left"), func
446
+ )()
447
+ exp_idx = MultiIndex.from_arrays(arrays=[[1, 1, 2], ser.index], names=("A", None))
448
+ expected = Series(data=[np.nan, 3, np.nan], index=exp_idx, name="B")
449
+ tm.assert_series_equal(result, expected)
450
+
451
+
452
+ @pytest.mark.parametrize("input_dtype", ["int", "float"])
453
+ @pytest.mark.parametrize(
454
+ "func,closed,expected",
455
+ [
456
+ ("min", "right", [0.0, 0, 0, 1, 2, 3, 4, 5, 6, 7]),
457
+ ("min", "both", [0.0, 0, 0, 0, 1, 2, 3, 4, 5, 6]),
458
+ ("min", "neither", [np.nan, 0, 0, 1, 2, 3, 4, 5, 6, 7]),
459
+ ("min", "left", [np.nan, 0, 0, 0, 1, 2, 3, 4, 5, 6]),
460
+ ("max", "right", [0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
461
+ ("max", "both", [0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
462
+ ("max", "neither", [np.nan, 0, 1, 2, 3, 4, 5, 6, 7, 8]),
463
+ ("max", "left", [np.nan, 0, 1, 2, 3, 4, 5, 6, 7, 8]),
464
+ ],
465
+ )
466
+ def test_closed_min_max_datetime(input_dtype, func, closed, expected):
467
+ # see gh-21704
468
+ ser = Series(
469
+ data=np.arange(10).astype(input_dtype),
470
+ index=date_range("2000", periods=10),
471
+ )
472
+
473
+ result = getattr(ser.rolling("3D", closed=closed), func)()
474
+ expected = Series(expected, index=ser.index)
475
+ tm.assert_series_equal(result, expected)
476
+
477
+
478
+ def test_closed_uneven():
479
+ # see gh-21704
480
+ ser = Series(data=np.arange(10), index=date_range("2000", periods=10))
481
+
482
+ # uneven
483
+ ser = ser.drop(index=ser.index[[1, 5]])
484
+ result = ser.rolling("3D", closed="left").min()
485
+ expected = Series([np.nan, 0, 0, 2, 3, 4, 6, 6], index=ser.index)
486
+ tm.assert_series_equal(result, expected)
487
+
488
+
489
+ @pytest.mark.parametrize(
490
+ "func,closed,expected",
491
+ [
492
+ ("min", "right", [np.nan, 0, 0, 1, 2, 3, 4, 5, np.nan, np.nan]),
493
+ ("min", "both", [np.nan, 0, 0, 0, 1, 2, 3, 4, 5, np.nan]),
494
+ ("min", "neither", [np.nan, np.nan, 0, 1, 2, 3, 4, 5, np.nan, np.nan]),
495
+ ("min", "left", [np.nan, np.nan, 0, 0, 1, 2, 3, 4, 5, np.nan]),
496
+ ("max", "right", [np.nan, 1, 2, 3, 4, 5, 6, 6, np.nan, np.nan]),
497
+ ("max", "both", [np.nan, 1, 2, 3, 4, 5, 6, 6, 6, np.nan]),
498
+ ("max", "neither", [np.nan, np.nan, 1, 2, 3, 4, 5, 6, np.nan, np.nan]),
499
+ ("max", "left", [np.nan, np.nan, 1, 2, 3, 4, 5, 6, 6, np.nan]),
500
+ ],
501
+ )
502
+ def test_closed_min_max_minp(func, closed, expected):
503
+ # see gh-21704
504
+ ser = Series(data=np.arange(10), index=date_range("2000", periods=10))
505
+ # Explicit cast to float to avoid implicit cast when setting nan
506
+ ser = ser.astype("float")
507
+ ser[ser.index[-3:]] = np.nan
508
+ result = getattr(ser.rolling("3D", min_periods=2, closed=closed), func)()
509
+ expected = Series(expected, index=ser.index)
510
+ tm.assert_series_equal(result, expected)
511
+
512
+
513
+ @pytest.mark.parametrize(
514
+ "closed,expected",
515
+ [
516
+ ("right", [0, 0.5, 1, 2, 3, 4, 5, 6, 7, 8]),
517
+ ("both", [0, 0.5, 1, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]),
518
+ ("neither", [np.nan, 0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5]),
519
+ ("left", [np.nan, 0, 0.5, 1, 2, 3, 4, 5, 6, 7]),
520
+ ],
521
+ )
522
+ def test_closed_median_quantile(closed, expected):
523
+ # GH 26005
524
+ ser = Series(data=np.arange(10), index=date_range("2000", periods=10))
525
+ roll = ser.rolling("3D", closed=closed)
526
+ expected = Series(expected, index=ser.index)
527
+
528
+ result = roll.median()
529
+ tm.assert_series_equal(result, expected)
530
+
531
+ result = roll.quantile(0.5)
532
+ tm.assert_series_equal(result, expected)
533
+
534
+
535
+ @pytest.mark.parametrize("roller", ["1s", 1])
536
+ def tests_empty_df_rolling(roller):
537
+ # GH 15819 Verifies that datetime and integer rolling windows can be
538
+ # applied to empty DataFrames
539
+ expected = DataFrame()
540
+ result = DataFrame().rolling(roller).sum()
541
+ tm.assert_frame_equal(result, expected)
542
+
543
+ # Verifies that datetime and integer rolling windows can be applied to
544
+ # empty DataFrames with datetime index
545
+ expected = DataFrame(index=DatetimeIndex([]))
546
+ result = DataFrame(index=DatetimeIndex([])).rolling(roller).sum()
547
+ tm.assert_frame_equal(result, expected)
548
+
549
+
550
+ def test_empty_window_median_quantile():
551
+ # GH 26005
552
+ expected = Series([np.nan, np.nan, np.nan])
553
+ roll = Series(np.arange(3)).rolling(0)
554
+
555
+ result = roll.median()
556
+ tm.assert_series_equal(result, expected)
557
+
558
+ result = roll.quantile(0.1)
559
+ tm.assert_series_equal(result, expected)
560
+
561
+
562
+ def test_missing_minp_zero():
563
+ # https://github.com/pandas-dev/pandas/pull/18921
564
+ # minp=0
565
+ x = Series([np.nan])
566
+ result = x.rolling(1, min_periods=0).sum()
567
+ expected = Series([0.0])
568
+ tm.assert_series_equal(result, expected)
569
+
570
+ # minp=1
571
+ result = x.rolling(1, min_periods=1).sum()
572
+ expected = Series([np.nan])
573
+ tm.assert_series_equal(result, expected)
574
+
575
+
576
+ def test_missing_minp_zero_variable():
577
+ # https://github.com/pandas-dev/pandas/pull/18921
578
+ x = Series(
579
+ [np.nan] * 4,
580
+ index=DatetimeIndex(["2017-01-01", "2017-01-04", "2017-01-06", "2017-01-07"]),
581
+ )
582
+ result = x.rolling(Timedelta("2d"), min_periods=0).sum()
583
+ expected = Series(0.0, index=x.index)
584
+ tm.assert_series_equal(result, expected)
585
+
586
+
587
+ def test_multi_index_names():
588
+ # GH 16789, 16825
589
+ cols = MultiIndex.from_product([["A", "B"], ["C", "D", "E"]], names=["1", "2"])
590
+ df = DataFrame(np.ones((10, 6)), columns=cols)
591
+ result = df.rolling(3).cov()
592
+
593
+ tm.assert_index_equal(result.columns, df.columns)
594
+ assert result.index.names == [None, "1", "2"]
595
+
596
+
597
+ def test_rolling_axis_sum(axis_frame):
598
+ # see gh-23372.
599
+ df = DataFrame(np.ones((10, 20)))
600
+ axis = df._get_axis_number(axis_frame)
601
+
602
+ if axis == 0:
603
+ msg = "The 'axis' keyword in DataFrame.rolling"
604
+ expected = DataFrame({i: [np.nan] * 2 + [3.0] * 8 for i in range(20)})
605
+ else:
606
+ # axis == 1
607
+ msg = "Support for axis=1 in DataFrame.rolling is deprecated"
608
+ expected = DataFrame([[np.nan] * 2 + [3.0] * 18] * 10)
609
+
610
+ with tm.assert_produces_warning(FutureWarning, match=msg):
611
+ result = df.rolling(3, axis=axis_frame).sum()
612
+ tm.assert_frame_equal(result, expected)
613
+
614
+
615
+ def test_rolling_axis_count(axis_frame):
616
+ # see gh-26055
617
+ df = DataFrame({"x": range(3), "y": range(3)})
618
+
619
+ axis = df._get_axis_number(axis_frame)
620
+
621
+ if axis in [0, "index"]:
622
+ msg = "The 'axis' keyword in DataFrame.rolling"
623
+ expected = DataFrame({"x": [1.0, 2.0, 2.0], "y": [1.0, 2.0, 2.0]})
624
+ else:
625
+ msg = "Support for axis=1 in DataFrame.rolling is deprecated"
626
+ expected = DataFrame({"x": [1.0, 1.0, 1.0], "y": [2.0, 2.0, 2.0]})
627
+
628
+ with tm.assert_produces_warning(FutureWarning, match=msg):
629
+ result = df.rolling(2, axis=axis_frame, min_periods=0).count()
630
+ tm.assert_frame_equal(result, expected)
631
+
632
+
633
+ def test_readonly_array():
634
+ # GH-27766
635
+ arr = np.array([1, 3, np.nan, 3, 5])
636
+ arr.setflags(write=False)
637
+ result = Series(arr).rolling(2).mean()
638
+ expected = Series([np.nan, 2, np.nan, np.nan, 4])
639
+ tm.assert_series_equal(result, expected)
640
+
641
+
642
+ def test_rolling_datetime(axis_frame, tz_naive_fixture):
643
+ # GH-28192
644
+ tz = tz_naive_fixture
645
+ df = DataFrame(
646
+ {i: [1] * 2 for i in date_range("2019-8-01", "2019-08-03", freq="D", tz=tz)}
647
+ )
648
+
649
+ if axis_frame in [0, "index"]:
650
+ msg = "The 'axis' keyword in DataFrame.rolling"
651
+ with tm.assert_produces_warning(FutureWarning, match=msg):
652
+ result = df.T.rolling("2D", axis=axis_frame).sum().T
653
+ else:
654
+ msg = "Support for axis=1 in DataFrame.rolling"
655
+ with tm.assert_produces_warning(FutureWarning, match=msg):
656
+ result = df.rolling("2D", axis=axis_frame).sum()
657
+ expected = DataFrame(
658
+ {
659
+ **{
660
+ i: [1.0] * 2
661
+ for i in date_range("2019-8-01", periods=1, freq="D", tz=tz)
662
+ },
663
+ **{
664
+ i: [2.0] * 2
665
+ for i in date_range("2019-8-02", "2019-8-03", freq="D", tz=tz)
666
+ },
667
+ }
668
+ )
669
+ tm.assert_frame_equal(result, expected)
670
+
671
+
672
+ @pytest.mark.parametrize("center", [True, False])
673
+ def test_rolling_window_as_string(center):
674
+ # see gh-22590
675
+ date_today = datetime.now()
676
+ days = date_range(date_today, date_today + timedelta(365), freq="D")
677
+
678
+ data = np.ones(len(days))
679
+ df = DataFrame({"DateCol": days, "metric": data})
680
+
681
+ df.set_index("DateCol", inplace=True)
682
+ result = df.rolling(window="21D", min_periods=2, closed="left", center=center)[
683
+ "metric"
684
+ ].agg("max")
685
+
686
+ index = days.rename("DateCol")
687
+ index = index._with_freq(None)
688
+ expected_data = np.ones(len(days), dtype=np.float64)
689
+ if not center:
690
+ expected_data[:2] = np.nan
691
+ expected = Series(expected_data, index=index, name="metric")
692
+ tm.assert_series_equal(result, expected)
693
+
694
+
695
+ def test_min_periods1():
696
+ # GH#6795
697
+ df = DataFrame([0, 1, 2, 1, 0], columns=["a"])
698
+ result = df["a"].rolling(3, center=True, min_periods=1).max()
699
+ expected = Series([1.0, 2.0, 2.0, 2.0, 1.0], name="a")
700
+ tm.assert_series_equal(result, expected)
701
+
702
+
703
+ def test_rolling_count_with_min_periods(frame_or_series):
704
+ # GH 26996
705
+ result = frame_or_series(range(5)).rolling(3, min_periods=3).count()
706
+ expected = frame_or_series([np.nan, np.nan, 3.0, 3.0, 3.0])
707
+ tm.assert_equal(result, expected)
708
+
709
+
710
+ def test_rolling_count_default_min_periods_with_null_values(frame_or_series):
711
+ # GH 26996
712
+ values = [1, 2, 3, np.nan, 4, 5, 6]
713
+ expected_counts = [1.0, 2.0, 3.0, 2.0, 2.0, 2.0, 3.0]
714
+
715
+ # GH 31302
716
+ result = frame_or_series(values).rolling(3, min_periods=0).count()
717
+ expected = frame_or_series(expected_counts)
718
+ tm.assert_equal(result, expected)
719
+
720
+
721
+ @pytest.mark.parametrize(
722
+ "df,expected,window,min_periods",
723
+ [
724
+ (
725
+ DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
726
+ [
727
+ ({"A": [1], "B": [4]}, [0]),
728
+ ({"A": [1, 2], "B": [4, 5]}, [0, 1]),
729
+ ({"A": [1, 2, 3], "B": [4, 5, 6]}, [0, 1, 2]),
730
+ ],
731
+ 3,
732
+ None,
733
+ ),
734
+ (
735
+ DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
736
+ [
737
+ ({"A": [1], "B": [4]}, [0]),
738
+ ({"A": [1, 2], "B": [4, 5]}, [0, 1]),
739
+ ({"A": [2, 3], "B": [5, 6]}, [1, 2]),
740
+ ],
741
+ 2,
742
+ 1,
743
+ ),
744
+ (
745
+ DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
746
+ [
747
+ ({"A": [1], "B": [4]}, [0]),
748
+ ({"A": [1, 2], "B": [4, 5]}, [0, 1]),
749
+ ({"A": [2, 3], "B": [5, 6]}, [1, 2]),
750
+ ],
751
+ 2,
752
+ 2,
753
+ ),
754
+ (
755
+ DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
756
+ [
757
+ ({"A": [1], "B": [4]}, [0]),
758
+ ({"A": [2], "B": [5]}, [1]),
759
+ ({"A": [3], "B": [6]}, [2]),
760
+ ],
761
+ 1,
762
+ 1,
763
+ ),
764
+ (
765
+ DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}),
766
+ [
767
+ ({"A": [1], "B": [4]}, [0]),
768
+ ({"A": [2], "B": [5]}, [1]),
769
+ ({"A": [3], "B": [6]}, [2]),
770
+ ],
771
+ 1,
772
+ 0,
773
+ ),
774
+ (DataFrame({"A": [1], "B": [4]}), [], 2, None),
775
+ (DataFrame({"A": [1], "B": [4]}), [], 2, 1),
776
+ (DataFrame(), [({}, [])], 2, None),
777
+ (
778
+ DataFrame({"A": [1, np.nan, 3], "B": [np.nan, 5, 6]}),
779
+ [
780
+ ({"A": [1.0], "B": [np.nan]}, [0]),
781
+ ({"A": [1, np.nan], "B": [np.nan, 5]}, [0, 1]),
782
+ ({"A": [1, np.nan, 3], "B": [np.nan, 5, 6]}, [0, 1, 2]),
783
+ ],
784
+ 3,
785
+ 2,
786
+ ),
787
+ ],
788
+ )
789
+ def test_iter_rolling_dataframe(df, expected, window, min_periods):
790
+ # GH 11704
791
+ expected = [DataFrame(values, index=index) for (values, index) in expected]
792
+
793
+ for expected, actual in zip(expected, df.rolling(window, min_periods=min_periods)):
794
+ tm.assert_frame_equal(actual, expected)
795
+
796
+
797
+ @pytest.mark.parametrize(
798
+ "expected,window",
799
+ [
800
+ (
801
+ [
802
+ ({"A": [1], "B": [4]}, [0]),
803
+ ({"A": [1, 2], "B": [4, 5]}, [0, 1]),
804
+ ({"A": [2, 3], "B": [5, 6]}, [1, 2]),
805
+ ],
806
+ "2D",
807
+ ),
808
+ (
809
+ [
810
+ ({"A": [1], "B": [4]}, [0]),
811
+ ({"A": [1, 2], "B": [4, 5]}, [0, 1]),
812
+ ({"A": [1, 2, 3], "B": [4, 5, 6]}, [0, 1, 2]),
813
+ ],
814
+ "3D",
815
+ ),
816
+ (
817
+ [
818
+ ({"A": [1], "B": [4]}, [0]),
819
+ ({"A": [2], "B": [5]}, [1]),
820
+ ({"A": [3], "B": [6]}, [2]),
821
+ ],
822
+ "1D",
823
+ ),
824
+ ],
825
+ )
826
+ def test_iter_rolling_on_dataframe(expected, window):
827
+ # GH 11704, 40373
828
+ df = DataFrame(
829
+ {
830
+ "A": [1, 2, 3, 4, 5],
831
+ "B": [4, 5, 6, 7, 8],
832
+ "C": date_range(start="2016-01-01", periods=5, freq="D"),
833
+ }
834
+ )
835
+
836
+ expected = [
837
+ DataFrame(values, index=df.loc[index, "C"]) for (values, index) in expected
838
+ ]
839
+ for expected, actual in zip(expected, df.rolling(window, on="C")):
840
+ tm.assert_frame_equal(actual, expected)
841
+
842
+
843
+ def test_iter_rolling_on_dataframe_unordered():
844
+ # GH 43386
845
+ df = DataFrame({"a": ["x", "y", "x"], "b": [0, 1, 2]})
846
+ results = list(df.groupby("a").rolling(2))
847
+ expecteds = [df.iloc[idx, [1]] for idx in [[0], [0, 2], [1]]]
848
+ for result, expected in zip(results, expecteds):
849
+ tm.assert_frame_equal(result, expected)
850
+
851
+
852
+ @pytest.mark.parametrize(
853
+ "ser,expected,window, min_periods",
854
+ [
855
+ (
856
+ Series([1, 2, 3]),
857
+ [([1], [0]), ([1, 2], [0, 1]), ([1, 2, 3], [0, 1, 2])],
858
+ 3,
859
+ None,
860
+ ),
861
+ (
862
+ Series([1, 2, 3]),
863
+ [([1], [0]), ([1, 2], [0, 1]), ([1, 2, 3], [0, 1, 2])],
864
+ 3,
865
+ 1,
866
+ ),
867
+ (
868
+ Series([1, 2, 3]),
869
+ [([1], [0]), ([1, 2], [0, 1]), ([2, 3], [1, 2])],
870
+ 2,
871
+ 1,
872
+ ),
873
+ (
874
+ Series([1, 2, 3]),
875
+ [([1], [0]), ([1, 2], [0, 1]), ([2, 3], [1, 2])],
876
+ 2,
877
+ 2,
878
+ ),
879
+ (Series([1, 2, 3]), [([1], [0]), ([2], [1]), ([3], [2])], 1, 0),
880
+ (Series([1, 2, 3]), [([1], [0]), ([2], [1]), ([3], [2])], 1, 1),
881
+ (Series([1, 2]), [([1], [0]), ([1, 2], [0, 1])], 2, 0),
882
+ (Series([], dtype="int64"), [], 2, 1),
883
+ ],
884
+ )
885
+ def test_iter_rolling_series(ser, expected, window, min_periods):
886
+ # GH 11704
887
+ expected = [Series(values, index=index) for (values, index) in expected]
888
+
889
+ for expected, actual in zip(expected, ser.rolling(window, min_periods=min_periods)):
890
+ tm.assert_series_equal(actual, expected)
891
+
892
+
893
+ @pytest.mark.parametrize(
894
+ "expected,expected_index,window",
895
+ [
896
+ (
897
+ [[0], [1], [2], [3], [4]],
898
+ [
899
+ date_range("2020-01-01", periods=1, freq="D"),
900
+ date_range("2020-01-02", periods=1, freq="D"),
901
+ date_range("2020-01-03", periods=1, freq="D"),
902
+ date_range("2020-01-04", periods=1, freq="D"),
903
+ date_range("2020-01-05", periods=1, freq="D"),
904
+ ],
905
+ "1D",
906
+ ),
907
+ (
908
+ [[0], [0, 1], [1, 2], [2, 3], [3, 4]],
909
+ [
910
+ date_range("2020-01-01", periods=1, freq="D"),
911
+ date_range("2020-01-01", periods=2, freq="D"),
912
+ date_range("2020-01-02", periods=2, freq="D"),
913
+ date_range("2020-01-03", periods=2, freq="D"),
914
+ date_range("2020-01-04", periods=2, freq="D"),
915
+ ],
916
+ "2D",
917
+ ),
918
+ (
919
+ [[0], [0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4]],
920
+ [
921
+ date_range("2020-01-01", periods=1, freq="D"),
922
+ date_range("2020-01-01", periods=2, freq="D"),
923
+ date_range("2020-01-01", periods=3, freq="D"),
924
+ date_range("2020-01-02", periods=3, freq="D"),
925
+ date_range("2020-01-03", periods=3, freq="D"),
926
+ ],
927
+ "3D",
928
+ ),
929
+ ],
930
+ )
931
+ def test_iter_rolling_datetime(expected, expected_index, window):
932
+ # GH 11704
933
+ ser = Series(range(5), index=date_range(start="2020-01-01", periods=5, freq="D"))
934
+
935
+ expected = [
936
+ Series(values, index=idx) for (values, idx) in zip(expected, expected_index)
937
+ ]
938
+
939
+ for expected, actual in zip(expected, ser.rolling(window)):
940
+ tm.assert_series_equal(actual, expected)
941
+
942
+
943
+ @pytest.mark.parametrize(
944
+ "grouping,_index",
945
+ [
946
+ (
947
+ {"level": 0},
948
+ MultiIndex.from_tuples(
949
+ [(0, 0), (0, 0), (1, 1), (1, 1), (1, 1)], names=[None, None]
950
+ ),
951
+ ),
952
+ (
953
+ {"by": "X"},
954
+ MultiIndex.from_tuples(
955
+ [(0, 0), (1, 0), (2, 1), (3, 1), (4, 1)], names=["X", None]
956
+ ),
957
+ ),
958
+ ],
959
+ )
960
+ def test_rolling_positional_argument(grouping, _index, raw):
961
+ # GH 34605
962
+
963
+ def scaled_sum(*args):
964
+ if len(args) < 2:
965
+ raise ValueError("The function needs two arguments")
966
+ array, scale = args
967
+ return array.sum() / scale
968
+
969
+ df = DataFrame(data={"X": range(5)}, index=[0, 0, 1, 1, 1])
970
+
971
+ expected = DataFrame(data={"X": [0.0, 0.5, 1.0, 1.5, 2.0]}, index=_index)
972
+ # GH 40341
973
+ if "by" in grouping:
974
+ expected = expected.drop(columns="X", errors="ignore")
975
+ result = df.groupby(**grouping).rolling(1).apply(scaled_sum, raw=raw, args=(2,))
976
+ tm.assert_frame_equal(result, expected)
977
+
978
+
979
+ @pytest.mark.parametrize("add", [0.0, 2.0])
980
+ def test_rolling_numerical_accuracy_kahan_mean(add, unit):
981
+ # GH: 36031 implementing kahan summation
982
+ dti = DatetimeIndex(
983
+ [
984
+ Timestamp("19700101 09:00:00"),
985
+ Timestamp("19700101 09:00:03"),
986
+ Timestamp("19700101 09:00:06"),
987
+ ]
988
+ ).as_unit(unit)
989
+ df = DataFrame(
990
+ {"A": [3002399751580331.0 + add, -0.0, -0.0]},
991
+ index=dti,
992
+ )
993
+ result = (
994
+ df.resample("1s").ffill().rolling("3s", closed="left", min_periods=3).mean()
995
+ )
996
+ dates = date_range("19700101 09:00:00", periods=7, freq="s", unit=unit)
997
+ expected = DataFrame(
998
+ {
999
+ "A": [
1000
+ np.nan,
1001
+ np.nan,
1002
+ np.nan,
1003
+ 3002399751580330.5,
1004
+ 2001599834386887.25,
1005
+ 1000799917193443.625,
1006
+ 0.0,
1007
+ ]
1008
+ },
1009
+ index=dates,
1010
+ )
1011
+ tm.assert_frame_equal(result, expected)
1012
+
1013
+
1014
+ def test_rolling_numerical_accuracy_kahan_sum():
1015
+ # GH: 13254
1016
+ df = DataFrame([2.186, -1.647, 0.0, 0.0, 0.0, 0.0], columns=["x"])
1017
+ result = df["x"].rolling(3).sum()
1018
+ expected = Series([np.nan, np.nan, 0.539, -1.647, 0.0, 0.0], name="x")
1019
+ tm.assert_series_equal(result, expected)
1020
+
1021
+
1022
+ def test_rolling_numerical_accuracy_jump():
1023
+ # GH: 32761
1024
+ index = date_range(start="2020-01-01", end="2020-01-02", freq="60s").append(
1025
+ DatetimeIndex(["2020-01-03"])
1026
+ )
1027
+ data = np.random.default_rng(2).random(len(index))
1028
+
1029
+ df = DataFrame({"data": data}, index=index)
1030
+ result = df.rolling("60s").mean()
1031
+ tm.assert_frame_equal(result, df[["data"]])
1032
+
1033
+
1034
+ def test_rolling_numerical_accuracy_small_values():
1035
+ # GH: 10319
1036
+ s = Series(
1037
+ data=[0.00012456, 0.0003, -0.0, -0.0],
1038
+ index=date_range("1999-02-03", "1999-02-06"),
1039
+ )
1040
+ result = s.rolling(1).mean()
1041
+ tm.assert_series_equal(result, s)
1042
+
1043
+
1044
+ def test_rolling_numerical_too_large_numbers():
1045
+ # GH: 11645
1046
+ dates = date_range("2015-01-01", periods=10, freq="D")
1047
+ ds = Series(data=range(10), index=dates, dtype=np.float64)
1048
+ ds.iloc[2] = -9e33
1049
+ result = ds.rolling(5).mean()
1050
+ expected = Series(
1051
+ [
1052
+ np.nan,
1053
+ np.nan,
1054
+ np.nan,
1055
+ np.nan,
1056
+ -1.8e33,
1057
+ -1.8e33,
1058
+ -1.8e33,
1059
+ 5.0,
1060
+ 6.0,
1061
+ 7.0,
1062
+ ],
1063
+ index=dates,
1064
+ )
1065
+ tm.assert_series_equal(result, expected)
1066
+
1067
+
1068
+ @pytest.mark.parametrize(
1069
+ ("func", "value"),
1070
+ [("sum", 2.0), ("max", 1.0), ("min", 1.0), ("mean", 1.0), ("median", 1.0)],
1071
+ )
1072
+ def test_rolling_mixed_dtypes_axis_1(func, value):
1073
+ # GH: 20649
1074
+ df = DataFrame(1, index=[1, 2], columns=["a", "b", "c"])
1075
+ df["c"] = 1.0
1076
+ msg = "Support for axis=1 in DataFrame.rolling is deprecated"
1077
+ with tm.assert_produces_warning(FutureWarning, match=msg):
1078
+ roll = df.rolling(window=2, min_periods=1, axis=1)
1079
+ result = getattr(roll, func)()
1080
+ expected = DataFrame(
1081
+ {"a": [1.0, 1.0], "b": [value, value], "c": [value, value]},
1082
+ index=[1, 2],
1083
+ )
1084
+ tm.assert_frame_equal(result, expected)
1085
+
1086
+
1087
+ def test_rolling_axis_one_with_nan():
1088
+ # GH: 35596
1089
+ df = DataFrame(
1090
+ [
1091
+ [0, 1, 2, 4, np.nan, np.nan, np.nan],
1092
+ [0, 1, 2, np.nan, np.nan, np.nan, np.nan],
1093
+ [0, 2, 2, np.nan, 2, np.nan, 1],
1094
+ ]
1095
+ )
1096
+ msg = "Support for axis=1 in DataFrame.rolling is deprecated"
1097
+ with tm.assert_produces_warning(FutureWarning, match=msg):
1098
+ result = df.rolling(window=7, min_periods=1, axis="columns").sum()
1099
+ expected = DataFrame(
1100
+ [
1101
+ [0.0, 1.0, 3.0, 7.0, 7.0, 7.0, 7.0],
1102
+ [0.0, 1.0, 3.0, 3.0, 3.0, 3.0, 3.0],
1103
+ [0.0, 2.0, 4.0, 4.0, 6.0, 6.0, 7.0],
1104
+ ]
1105
+ )
1106
+ tm.assert_frame_equal(result, expected)
1107
+
1108
+
1109
+ @pytest.mark.parametrize(
1110
+ "value",
1111
+ ["test", to_datetime("2019-12-31"), to_timedelta("1 days 06:05:01.00003")],
1112
+ )
1113
+ def test_rolling_axis_1_non_numeric_dtypes(value):
1114
+ # GH: 20649
1115
+ df = DataFrame({"a": [1, 2]})
1116
+ df["b"] = value
1117
+ msg = "Support for axis=1 in DataFrame.rolling is deprecated"
1118
+ with tm.assert_produces_warning(FutureWarning, match=msg):
1119
+ result = df.rolling(window=2, min_periods=1, axis=1).sum()
1120
+ expected = DataFrame({"a": [1.0, 2.0]})
1121
+ tm.assert_frame_equal(result, expected)
1122
+
1123
+
1124
+ def test_rolling_on_df_transposed():
1125
+ # GH: 32724
1126
+ df = DataFrame({"A": [1, None], "B": [4, 5], "C": [7, 8]})
1127
+ expected = DataFrame({"A": [1.0, np.nan], "B": [5.0, 5.0], "C": [11.0, 13.0]})
1128
+ msg = "Support for axis=1 in DataFrame.rolling is deprecated"
1129
+ with tm.assert_produces_warning(FutureWarning, match=msg):
1130
+ result = df.rolling(min_periods=1, window=2, axis=1).sum()
1131
+ tm.assert_frame_equal(result, expected)
1132
+
1133
+ result = df.T.rolling(min_periods=1, window=2).sum().T
1134
+ tm.assert_frame_equal(result, expected)
1135
+
1136
+
1137
+ @pytest.mark.parametrize(
1138
+ ("index", "window"),
1139
+ [
1140
+ (
1141
+ period_range(start="2020-01-01 08:00", end="2020-01-01 08:08", freq="min"),
1142
+ "2min",
1143
+ ),
1144
+ (
1145
+ period_range(
1146
+ start="2020-01-01 08:00", end="2020-01-01 12:00", freq="30min"
1147
+ ),
1148
+ "1h",
1149
+ ),
1150
+ ],
1151
+ )
1152
+ @pytest.mark.parametrize(
1153
+ ("func", "values"),
1154
+ [
1155
+ ("min", [np.nan, 0, 0, 1, 2, 3, 4, 5, 6]),
1156
+ ("max", [np.nan, 0, 1, 2, 3, 4, 5, 6, 7]),
1157
+ ("sum", [np.nan, 0, 1, 3, 5, 7, 9, 11, 13]),
1158
+ ],
1159
+ )
1160
+ def test_rolling_period_index(index, window, func, values):
1161
+ # GH: 34225
1162
+ ds = Series([0, 1, 2, 3, 4, 5, 6, 7, 8], index=index)
1163
+ result = getattr(ds.rolling(window, closed="left"), func)()
1164
+ expected = Series(values, index=index)
1165
+ tm.assert_series_equal(result, expected)
1166
+
1167
+
1168
+ def test_rolling_sem(frame_or_series):
1169
+ # GH: 26476
1170
+ obj = frame_or_series([0, 1, 2])
1171
+ result = obj.rolling(2, min_periods=1).sem()
1172
+ if isinstance(result, DataFrame):
1173
+ result = Series(result[0].values)
1174
+ expected = Series([np.nan] + [0.7071067811865476] * 2)
1175
+ tm.assert_series_equal(result, expected)
1176
+
1177
+
1178
+ @pytest.mark.xfail(
1179
+ is_platform_arm() or is_platform_power(),
1180
+ reason="GH 38921",
1181
+ )
1182
+ @pytest.mark.parametrize(
1183
+ ("func", "third_value", "values"),
1184
+ [
1185
+ ("var", 1, [5e33, 0, 0.5, 0.5, 2, 0]),
1186
+ ("std", 1, [7.071068e16, 0, 0.7071068, 0.7071068, 1.414214, 0]),
1187
+ ("var", 2, [5e33, 0.5, 0, 0.5, 2, 0]),
1188
+ ("std", 2, [7.071068e16, 0.7071068, 0, 0.7071068, 1.414214, 0]),
1189
+ ],
1190
+ )
1191
+ def test_rolling_var_numerical_issues(func, third_value, values):
1192
+ # GH: 37051
1193
+ ds = Series([99999999999999999, 1, third_value, 2, 3, 1, 1])
1194
+ result = getattr(ds.rolling(2), func)()
1195
+ expected = Series([np.nan] + values)
1196
+ tm.assert_series_equal(result, expected)
1197
+ # GH 42064
1198
+ # new `roll_var` will output 0.0 correctly
1199
+ tm.assert_series_equal(result == 0, expected == 0)
1200
+
1201
+
1202
+ def test_timeoffset_as_window_parameter_for_corr(unit):
1203
+ # GH: 28266
1204
+ dti = DatetimeIndex(
1205
+ [
1206
+ Timestamp("20130101 09:00:00"),
1207
+ Timestamp("20130102 09:00:02"),
1208
+ Timestamp("20130103 09:00:03"),
1209
+ Timestamp("20130105 09:00:05"),
1210
+ Timestamp("20130106 09:00:06"),
1211
+ ]
1212
+ ).as_unit(unit)
1213
+ mi = MultiIndex.from_product([dti, ["B", "A"]])
1214
+
1215
+ exp = DataFrame(
1216
+ {
1217
+ "B": [
1218
+ np.nan,
1219
+ np.nan,
1220
+ 0.9999999999999998,
1221
+ -1.0,
1222
+ 1.0,
1223
+ -0.3273268353539892,
1224
+ 0.9999999999999998,
1225
+ 1.0,
1226
+ 0.9999999999999998,
1227
+ 1.0,
1228
+ ],
1229
+ "A": [
1230
+ np.nan,
1231
+ np.nan,
1232
+ -1.0,
1233
+ 1.0000000000000002,
1234
+ -0.3273268353539892,
1235
+ 0.9999999999999966,
1236
+ 1.0,
1237
+ 1.0000000000000002,
1238
+ 1.0,
1239
+ 1.0000000000000002,
1240
+ ],
1241
+ },
1242
+ index=mi,
1243
+ )
1244
+
1245
+ df = DataFrame(
1246
+ {"B": [0, 1, 2, 4, 3], "A": [7, 4, 6, 9, 3]},
1247
+ index=dti,
1248
+ )
1249
+
1250
+ res = df.rolling(window="3d").corr()
1251
+
1252
+ tm.assert_frame_equal(exp, res)
1253
+
1254
+
1255
+ @pytest.mark.parametrize("method", ["var", "sum", "mean", "skew", "kurt", "min", "max"])
1256
+ def test_rolling_decreasing_indices(method):
1257
+ """
1258
+ Make sure that decreasing indices give the same results as increasing indices.
1259
+
1260
+ GH 36933
1261
+ """
1262
+ df = DataFrame({"values": np.arange(-15, 10) ** 2})
1263
+ df_reverse = DataFrame({"values": df["values"][::-1]}, index=df.index[::-1])
1264
+
1265
+ increasing = getattr(df.rolling(window=5), method)()
1266
+ decreasing = getattr(df_reverse.rolling(window=5), method)()
1267
+
1268
+ assert np.abs(decreasing.values[::-1][:-4] - increasing.values[4:]).max() < 1e-12
1269
+
1270
+
1271
+ @pytest.mark.parametrize(
1272
+ "window,closed,expected",
1273
+ [
1274
+ ("2s", "right", [1.0, 3.0, 5.0, 3.0]),
1275
+ ("2s", "left", [0.0, 1.0, 3.0, 5.0]),
1276
+ ("2s", "both", [1.0, 3.0, 6.0, 5.0]),
1277
+ ("2s", "neither", [0.0, 1.0, 2.0, 3.0]),
1278
+ ("3s", "right", [1.0, 3.0, 6.0, 5.0]),
1279
+ ("3s", "left", [1.0, 3.0, 6.0, 5.0]),
1280
+ ("3s", "both", [1.0, 3.0, 6.0, 5.0]),
1281
+ ("3s", "neither", [1.0, 3.0, 6.0, 5.0]),
1282
+ ],
1283
+ )
1284
+ def test_rolling_decreasing_indices_centered(window, closed, expected, frame_or_series):
1285
+ """
1286
+ Ensure that a symmetrical inverted index return same result as non-inverted.
1287
+ """
1288
+ # GH 43927
1289
+
1290
+ index = date_range("2020", periods=4, freq="1s")
1291
+ df_inc = frame_or_series(range(4), index=index)
1292
+ df_dec = frame_or_series(range(4), index=index[::-1])
1293
+
1294
+ expected_inc = frame_or_series(expected, index=index)
1295
+ expected_dec = frame_or_series(expected, index=index[::-1])
1296
+
1297
+ result_inc = df_inc.rolling(window, closed=closed, center=True).sum()
1298
+ result_dec = df_dec.rolling(window, closed=closed, center=True).sum()
1299
+
1300
+ tm.assert_equal(result_inc, expected_inc)
1301
+ tm.assert_equal(result_dec, expected_dec)
1302
+
1303
+
1304
+ @pytest.mark.parametrize(
1305
+ "window,expected",
1306
+ [
1307
+ ("1ns", [1.0, 1.0, 1.0, 1.0]),
1308
+ ("3ns", [2.0, 3.0, 3.0, 2.0]),
1309
+ ],
1310
+ )
1311
+ def test_rolling_center_nanosecond_resolution(
1312
+ window, closed, expected, frame_or_series
1313
+ ):
1314
+ index = date_range("2020", periods=4, freq="1ns")
1315
+ df = frame_or_series([1, 1, 1, 1], index=index, dtype=float)
1316
+ expected = frame_or_series(expected, index=index, dtype=float)
1317
+ result = df.rolling(window, closed=closed, center=True).sum()
1318
+ tm.assert_equal(result, expected)
1319
+
1320
+
1321
+ @pytest.mark.parametrize(
1322
+ "method,expected",
1323
+ [
1324
+ (
1325
+ "var",
1326
+ [
1327
+ float("nan"),
1328
+ 43.0,
1329
+ float("nan"),
1330
+ 136.333333,
1331
+ 43.5,
1332
+ 94.966667,
1333
+ 182.0,
1334
+ 318.0,
1335
+ ],
1336
+ ),
1337
+ (
1338
+ "mean",
1339
+ [float("nan"), 7.5, float("nan"), 21.5, 6.0, 9.166667, 13.0, 17.5],
1340
+ ),
1341
+ (
1342
+ "sum",
1343
+ [float("nan"), 30.0, float("nan"), 86.0, 30.0, 55.0, 91.0, 140.0],
1344
+ ),
1345
+ (
1346
+ "skew",
1347
+ [
1348
+ float("nan"),
1349
+ 0.709296,
1350
+ float("nan"),
1351
+ 0.407073,
1352
+ 0.984656,
1353
+ 0.919184,
1354
+ 0.874674,
1355
+ 0.842418,
1356
+ ],
1357
+ ),
1358
+ (
1359
+ "kurt",
1360
+ [
1361
+ float("nan"),
1362
+ -0.5916711736073559,
1363
+ float("nan"),
1364
+ -1.0028993131317954,
1365
+ -0.06103844629409494,
1366
+ -0.254143227116194,
1367
+ -0.37362637362637585,
1368
+ -0.45439658241367054,
1369
+ ],
1370
+ ),
1371
+ ],
1372
+ )
1373
+ def test_rolling_non_monotonic(method, expected):
1374
+ """
1375
+ Make sure the (rare) branch of non-monotonic indices is covered by a test.
1376
+
1377
+ output from 1.1.3 is assumed to be the expected output. Output of sum/mean has
1378
+ manually been verified.
1379
+
1380
+ GH 36933.
1381
+ """
1382
+ # Based on an example found in computation.rst
1383
+ use_expanding = [True, False, True, False, True, True, True, True]
1384
+ df = DataFrame({"values": np.arange(len(use_expanding)) ** 2})
1385
+
1386
+ class CustomIndexer(BaseIndexer):
1387
+ def get_window_bounds(self, num_values, min_periods, center, closed, step):
1388
+ start = np.empty(num_values, dtype=np.int64)
1389
+ end = np.empty(num_values, dtype=np.int64)
1390
+ for i in range(num_values):
1391
+ if self.use_expanding[i]:
1392
+ start[i] = 0
1393
+ end[i] = i + 1
1394
+ else:
1395
+ start[i] = i
1396
+ end[i] = i + self.window_size
1397
+ return start, end
1398
+
1399
+ indexer = CustomIndexer(window_size=4, use_expanding=use_expanding)
1400
+
1401
+ result = getattr(df.rolling(indexer), method)()
1402
+ expected = DataFrame({"values": expected})
1403
+ tm.assert_frame_equal(result, expected)
1404
+
1405
+
1406
+ @pytest.mark.parametrize(
1407
+ ("index", "window"),
1408
+ [
1409
+ ([0, 1, 2, 3, 4], 2),
1410
+ (date_range("2001-01-01", freq="D", periods=5), "2D"),
1411
+ ],
1412
+ )
1413
+ def test_rolling_corr_timedelta_index(index, window):
1414
+ # GH: 31286
1415
+ x = Series([1, 2, 3, 4, 5], index=index)
1416
+ y = x.copy()
1417
+ x.iloc[0:2] = 0.0
1418
+ result = x.rolling(window).corr(y)
1419
+ expected = Series([np.nan, np.nan, 1, 1, 1], index=index)
1420
+ tm.assert_almost_equal(result, expected)
1421
+
1422
+
1423
+ def test_groupby_rolling_nan_included():
1424
+ # GH 35542
1425
+ data = {"group": ["g1", np.nan, "g1", "g2", np.nan], "B": [0, 1, 2, 3, 4]}
1426
+ df = DataFrame(data)
1427
+ result = df.groupby("group", dropna=False).rolling(1, min_periods=1).mean()
1428
+ expected = DataFrame(
1429
+ {"B": [0.0, 2.0, 3.0, 1.0, 4.0]},
1430
+ # GH-38057 from_tuples puts the NaNs in the codes, result expects them
1431
+ # to be in the levels, at the moment
1432
+ # index=MultiIndex.from_tuples(
1433
+ # [("g1", 0), ("g1", 2), ("g2", 3), (np.nan, 1), (np.nan, 4)],
1434
+ # names=["group", None],
1435
+ # ),
1436
+ index=MultiIndex(
1437
+ [["g1", "g2", np.nan], [0, 1, 2, 3, 4]],
1438
+ [[0, 0, 1, 2, 2], [0, 2, 3, 1, 4]],
1439
+ names=["group", None],
1440
+ ),
1441
+ )
1442
+ tm.assert_frame_equal(result, expected)
1443
+
1444
+
1445
+ @pytest.mark.parametrize("method", ["skew", "kurt"])
1446
+ def test_rolling_skew_kurt_numerical_stability(method):
1447
+ # GH#6929
1448
+ ser = Series(np.random.default_rng(2).random(10))
1449
+ ser_copy = ser.copy()
1450
+ expected = getattr(ser.rolling(3), method)()
1451
+ tm.assert_series_equal(ser, ser_copy)
1452
+ ser = ser + 50000
1453
+ result = getattr(ser.rolling(3), method)()
1454
+ tm.assert_series_equal(result, expected)
1455
+
1456
+
1457
+ @pytest.mark.parametrize(
1458
+ ("method", "values"),
1459
+ [
1460
+ ("skew", [2.0, 0.854563, 0.0, 1.999984]),
1461
+ ("kurt", [4.0, -1.289256, -1.2, 3.999946]),
1462
+ ],
1463
+ )
1464
+ def test_rolling_skew_kurt_large_value_range(method, values):
1465
+ # GH: 37557
1466
+ s = Series([3000000, 1, 1, 2, 3, 4, 999])
1467
+ result = getattr(s.rolling(4), method)()
1468
+ expected = Series([np.nan] * 3 + values)
1469
+ tm.assert_series_equal(result, expected)
1470
+
1471
+
1472
+ def test_invalid_method():
1473
+ with pytest.raises(ValueError, match="method must be 'table' or 'single"):
1474
+ Series(range(1)).rolling(1, method="foo")
1475
+
1476
+
1477
+ @pytest.mark.parametrize("window", [1, "1d"])
1478
+ def test_rolling_descending_date_order_with_offset(window, frame_or_series):
1479
+ # GH#40002
1480
+ idx = date_range(start="2020-01-01", end="2020-01-03", freq="1d")
1481
+ obj = frame_or_series(range(1, 4), index=idx)
1482
+ result = obj.rolling("1d", closed="left").sum()
1483
+ expected = frame_or_series([np.nan, 1, 2], index=idx)
1484
+ tm.assert_equal(result, expected)
1485
+
1486
+ result = obj.iloc[::-1].rolling("1d", closed="left").sum()
1487
+ idx = date_range(start="2020-01-03", end="2020-01-01", freq="-1d")
1488
+ expected = frame_or_series([np.nan, 3, 2], index=idx)
1489
+ tm.assert_equal(result, expected)
1490
+
1491
+
1492
+ def test_rolling_var_floating_artifact_precision():
1493
+ # GH 37051
1494
+ s = Series([7, 5, 5, 5])
1495
+ result = s.rolling(3).var()
1496
+ expected = Series([np.nan, np.nan, 4 / 3, 0])
1497
+ tm.assert_series_equal(result, expected, atol=1.0e-15, rtol=1.0e-15)
1498
+ # GH 42064
1499
+ # new `roll_var` will output 0.0 correctly
1500
+ tm.assert_series_equal(result == 0, expected == 0)
1501
+
1502
+
1503
+ def test_rolling_std_small_values():
1504
+ # GH 37051
1505
+ s = Series(
1506
+ [
1507
+ 0.00000054,
1508
+ 0.00000053,
1509
+ 0.00000054,
1510
+ ]
1511
+ )
1512
+ result = s.rolling(2).std()
1513
+ expected = Series([np.nan, 7.071068e-9, 7.071068e-9])
1514
+ tm.assert_series_equal(result, expected, atol=1.0e-15, rtol=1.0e-15)
1515
+
1516
+
1517
+ @pytest.mark.parametrize(
1518
+ "start, exp_values",
1519
+ [
1520
+ (1, [0.03, 0.0155, 0.0155, 0.011, 0.01025]),
1521
+ (2, [0.001, 0.001, 0.0015, 0.00366666]),
1522
+ ],
1523
+ )
1524
+ def test_rolling_mean_all_nan_window_floating_artifacts(start, exp_values):
1525
+ # GH#41053
1526
+ df = DataFrame(
1527
+ [
1528
+ 0.03,
1529
+ 0.03,
1530
+ 0.001,
1531
+ np.nan,
1532
+ 0.002,
1533
+ 0.008,
1534
+ np.nan,
1535
+ np.nan,
1536
+ np.nan,
1537
+ np.nan,
1538
+ np.nan,
1539
+ np.nan,
1540
+ 0.005,
1541
+ 0.2,
1542
+ ]
1543
+ )
1544
+
1545
+ values = exp_values + [
1546
+ 0.00366666,
1547
+ 0.005,
1548
+ 0.005,
1549
+ 0.008,
1550
+ np.nan,
1551
+ np.nan,
1552
+ 0.005,
1553
+ 0.102500,
1554
+ ]
1555
+ expected = DataFrame(
1556
+ values,
1557
+ index=list(range(start, len(values) + start)),
1558
+ )
1559
+ result = df.iloc[start:].rolling(5, min_periods=0).mean()
1560
+ tm.assert_frame_equal(result, expected)
1561
+
1562
+
1563
+ def test_rolling_sum_all_nan_window_floating_artifacts():
1564
+ # GH#41053
1565
+ df = DataFrame([0.002, 0.008, 0.005, np.nan, np.nan, np.nan])
1566
+ result = df.rolling(3, min_periods=0).sum()
1567
+ expected = DataFrame([0.002, 0.010, 0.015, 0.013, 0.005, 0.0])
1568
+ tm.assert_frame_equal(result, expected)
1569
+
1570
+
1571
+ def test_rolling_zero_window():
1572
+ # GH 22719
1573
+ s = Series(range(1))
1574
+ result = s.rolling(0).min()
1575
+ expected = Series([np.nan])
1576
+ tm.assert_series_equal(result, expected)
1577
+
1578
+
1579
+ def test_rolling_float_dtype(float_numpy_dtype):
1580
+ # GH#42452
1581
+ df = DataFrame({"A": range(5), "B": range(10, 15)}, dtype=float_numpy_dtype)
1582
+ expected = DataFrame(
1583
+ {"A": [np.nan] * 5, "B": range(10, 20, 2)},
1584
+ dtype=float_numpy_dtype,
1585
+ )
1586
+ msg = "Support for axis=1 in DataFrame.rolling is deprecated"
1587
+ with tm.assert_produces_warning(FutureWarning, match=msg):
1588
+ result = df.rolling(2, axis=1).sum()
1589
+ tm.assert_frame_equal(result, expected, check_dtype=False)
1590
+
1591
+
1592
+ def test_rolling_numeric_dtypes():
1593
+ # GH#41779
1594
+ df = DataFrame(np.arange(40).reshape(4, 10), columns=list("abcdefghij")).astype(
1595
+ {
1596
+ "a": "float16",
1597
+ "b": "float32",
1598
+ "c": "float64",
1599
+ "d": "int8",
1600
+ "e": "int16",
1601
+ "f": "int32",
1602
+ "g": "uint8",
1603
+ "h": "uint16",
1604
+ "i": "uint32",
1605
+ "j": "uint64",
1606
+ }
1607
+ )
1608
+ msg = "Support for axis=1 in DataFrame.rolling is deprecated"
1609
+ with tm.assert_produces_warning(FutureWarning, match=msg):
1610
+ result = df.rolling(window=2, min_periods=1, axis=1).min()
1611
+ expected = DataFrame(
1612
+ {
1613
+ "a": range(0, 40, 10),
1614
+ "b": range(0, 40, 10),
1615
+ "c": range(1, 40, 10),
1616
+ "d": range(2, 40, 10),
1617
+ "e": range(3, 40, 10),
1618
+ "f": range(4, 40, 10),
1619
+ "g": range(5, 40, 10),
1620
+ "h": range(6, 40, 10),
1621
+ "i": range(7, 40, 10),
1622
+ "j": range(8, 40, 10),
1623
+ },
1624
+ dtype="float64",
1625
+ )
1626
+ tm.assert_frame_equal(result, expected)
1627
+
1628
+
1629
+ @pytest.mark.parametrize("window", [1, 3, 10, 20])
1630
+ @pytest.mark.parametrize("method", ["min", "max", "average"])
1631
+ @pytest.mark.parametrize("pct", [True, False])
1632
+ @pytest.mark.parametrize("ascending", [True, False])
1633
+ @pytest.mark.parametrize("test_data", ["default", "duplicates", "nans"])
1634
+ def test_rank(window, method, pct, ascending, test_data):
1635
+ length = 20
1636
+ if test_data == "default":
1637
+ ser = Series(data=np.random.default_rng(2).random(length))
1638
+ elif test_data == "duplicates":
1639
+ ser = Series(data=np.random.default_rng(2).choice(3, length))
1640
+ elif test_data == "nans":
1641
+ ser = Series(
1642
+ data=np.random.default_rng(2).choice(
1643
+ [1.0, 0.25, 0.75, np.nan, np.inf, -np.inf], length
1644
+ )
1645
+ )
1646
+
1647
+ expected = ser.rolling(window).apply(
1648
+ lambda x: x.rank(method=method, pct=pct, ascending=ascending).iloc[-1]
1649
+ )
1650
+ result = ser.rolling(window).rank(method=method, pct=pct, ascending=ascending)
1651
+
1652
+ tm.assert_series_equal(result, expected)
1653
+
1654
+
1655
+ def test_rolling_quantile_np_percentile():
1656
+ # #9413: Tests that rolling window's quantile default behavior
1657
+ # is analogous to Numpy's percentile
1658
+ row = 10
1659
+ col = 5
1660
+ idx = date_range("20100101", periods=row, freq="B")
1661
+ df = DataFrame(
1662
+ np.random.default_rng(2).random(row * col).reshape((row, -1)), index=idx
1663
+ )
1664
+
1665
+ df_quantile = df.quantile([0.25, 0.5, 0.75], axis=0)
1666
+ np_percentile = np.percentile(df, [25, 50, 75], axis=0)
1667
+
1668
+ tm.assert_almost_equal(df_quantile.values, np.array(np_percentile))
1669
+
1670
+
1671
+ @pytest.mark.parametrize("quantile", [0.0, 0.1, 0.45, 0.5, 1])
1672
+ @pytest.mark.parametrize(
1673
+ "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"]
1674
+ )
1675
+ @pytest.mark.parametrize(
1676
+ "data",
1677
+ [
1678
+ [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0],
1679
+ [8.0, 1.0, 3.0, 4.0, 5.0, 2.0, 6.0, 7.0],
1680
+ [0.0, np.nan, 0.2, np.nan, 0.4],
1681
+ [np.nan, np.nan, np.nan, np.nan],
1682
+ [np.nan, 0.1, np.nan, 0.3, 0.4, 0.5],
1683
+ [0.5],
1684
+ [np.nan, 0.7, 0.6],
1685
+ ],
1686
+ )
1687
+ def test_rolling_quantile_interpolation_options(quantile, interpolation, data):
1688
+ # Tests that rolling window's quantile behavior is analogous to
1689
+ # Series' quantile for each interpolation option
1690
+ s = Series(data)
1691
+
1692
+ q1 = s.quantile(quantile, interpolation)
1693
+ q2 = s.expanding(min_periods=1).quantile(quantile, interpolation).iloc[-1]
1694
+
1695
+ if np.isnan(q1):
1696
+ assert np.isnan(q2)
1697
+ else:
1698
+ if not IS64:
1699
+ # Less precision on 32-bit
1700
+ assert np.allclose([q1], [q2], rtol=1e-07, atol=0)
1701
+ else:
1702
+ assert q1 == q2
1703
+
1704
+
1705
+ def test_invalid_quantile_value():
1706
+ data = np.arange(5)
1707
+ s = Series(data)
1708
+
1709
+ msg = "Interpolation 'invalid' is not supported"
1710
+ with pytest.raises(ValueError, match=msg):
1711
+ s.rolling(len(data), min_periods=1).quantile(0.5, interpolation="invalid")
1712
+
1713
+
1714
+ def test_rolling_quantile_param():
1715
+ ser = Series([0.0, 0.1, 0.5, 0.9, 1.0])
1716
+ msg = "quantile value -0.1 not in \\[0, 1\\]"
1717
+ with pytest.raises(ValueError, match=msg):
1718
+ ser.rolling(3).quantile(-0.1)
1719
+
1720
+ msg = "quantile value 10.0 not in \\[0, 1\\]"
1721
+ with pytest.raises(ValueError, match=msg):
1722
+ ser.rolling(3).quantile(10.0)
1723
+
1724
+ msg = "must be real number, not str"
1725
+ with pytest.raises(TypeError, match=msg):
1726
+ ser.rolling(3).quantile("foo")
1727
+
1728
+
1729
+ def test_rolling_std_1obs():
1730
+ vals = Series([1.0, 2.0, 3.0, 4.0, 5.0])
1731
+
1732
+ result = vals.rolling(1, min_periods=1).std()
1733
+ expected = Series([np.nan] * 5)
1734
+ tm.assert_series_equal(result, expected)
1735
+
1736
+ result = vals.rolling(1, min_periods=1).std(ddof=0)
1737
+ expected = Series([0.0] * 5)
1738
+ tm.assert_series_equal(result, expected)
1739
+
1740
+ result = Series([np.nan, np.nan, 3, 4, 5]).rolling(3, min_periods=2).std()
1741
+ assert np.isnan(result[2])
1742
+
1743
+
1744
+ def test_rolling_std_neg_sqrt():
1745
+ # unit test from Bottleneck
1746
+
1747
+ # Test move_nanstd for neg sqrt.
1748
+
1749
+ a = Series(
1750
+ [
1751
+ 0.0011448196318903589,
1752
+ 0.00028718669878572767,
1753
+ 0.00028718669878572767,
1754
+ 0.00028718669878572767,
1755
+ 0.00028718669878572767,
1756
+ ]
1757
+ )
1758
+ b = a.rolling(window=3).std()
1759
+ assert np.isfinite(b[2:]).all()
1760
+
1761
+ b = a.ewm(span=3).std()
1762
+ assert np.isfinite(b[2:]).all()
1763
+
1764
+
1765
+ def test_step_not_integer_raises():
1766
+ with pytest.raises(ValueError, match="step must be an integer"):
1767
+ DataFrame(range(2)).rolling(1, step="foo")
1768
+
1769
+
1770
+ def test_step_not_positive_raises():
1771
+ with pytest.raises(ValueError, match="step must be >= 0"):
1772
+ DataFrame(range(2)).rolling(1, step=-1)
1773
+
1774
+
1775
+ @pytest.mark.parametrize(
1776
+ ["values", "window", "min_periods", "expected"],
1777
+ [
1778
+ [
1779
+ [20, 10, 10, np.inf, 1, 1, 2, 3],
1780
+ 3,
1781
+ 1,
1782
+ [np.nan, 50, 100 / 3, 0, 40.5, 0, 1 / 3, 1],
1783
+ ],
1784
+ [
1785
+ [20, 10, 10, np.nan, 10, 1, 2, 3],
1786
+ 3,
1787
+ 1,
1788
+ [np.nan, 50, 100 / 3, 0, 0, 40.5, 73 / 3, 1],
1789
+ ],
1790
+ [
1791
+ [np.nan, 5, 6, 7, 5, 5, 5],
1792
+ 3,
1793
+ 3,
1794
+ [np.nan] * 3 + [1, 1, 4 / 3, 0],
1795
+ ],
1796
+ [
1797
+ [5, 7, 7, 7, np.nan, np.inf, 4, 3, 3, 3],
1798
+ 3,
1799
+ 3,
1800
+ [np.nan] * 2 + [4 / 3, 0] + [np.nan] * 4 + [1 / 3, 0],
1801
+ ],
1802
+ [
1803
+ [5, 7, 7, 7, np.nan, np.inf, 7, 3, 3, 3],
1804
+ 3,
1805
+ 3,
1806
+ [np.nan] * 2 + [4 / 3, 0] + [np.nan] * 4 + [16 / 3, 0],
1807
+ ],
1808
+ [
1809
+ [5, 7] * 4,
1810
+ 3,
1811
+ 3,
1812
+ [np.nan] * 2 + [4 / 3] * 6,
1813
+ ],
1814
+ [
1815
+ [5, 7, 5, np.nan, 7, 5, 7],
1816
+ 3,
1817
+ 2,
1818
+ [np.nan, 2, 4 / 3] + [2] * 3 + [4 / 3],
1819
+ ],
1820
+ ],
1821
+ )
1822
+ def test_rolling_var_same_value_count_logic(values, window, min_periods, expected):
1823
+ # GH 42064.
1824
+
1825
+ expected = Series(expected)
1826
+ sr = Series(values)
1827
+
1828
+ # With new algo implemented, result will be set to .0 in rolling var
1829
+ # if sufficient amount of consecutively same values are found.
1830
+ result_var = sr.rolling(window, min_periods=min_periods).var()
1831
+
1832
+ # use `assert_series_equal` twice to check for equality,
1833
+ # because `check_exact=True` will fail in 32-bit tests due to
1834
+ # precision loss.
1835
+
1836
+ # 1. result should be close to correct value
1837
+ # non-zero values can still differ slightly from "truth"
1838
+ # as the result of online algorithm
1839
+ tm.assert_series_equal(result_var, expected)
1840
+ # 2. zeros should be exactly the same since the new algo takes effect here
1841
+ tm.assert_series_equal(expected == 0, result_var == 0)
1842
+
1843
+ # std should also pass as it's just a sqrt of var
1844
+ result_std = sr.rolling(window, min_periods=min_periods).std()
1845
+ tm.assert_series_equal(result_std, np.sqrt(expected))
1846
+ tm.assert_series_equal(expected == 0, result_std == 0)
1847
+
1848
+
1849
+ def test_rolling_mean_sum_floating_artifacts():
1850
+ # GH 42064.
1851
+
1852
+ sr = Series([1 / 3, 4, 0, 0, 0, 0, 0])
1853
+ r = sr.rolling(3)
1854
+ result = r.mean()
1855
+ assert (result[-3:] == 0).all()
1856
+ result = r.sum()
1857
+ assert (result[-3:] == 0).all()
1858
+
1859
+
1860
+ def test_rolling_skew_kurt_floating_artifacts():
1861
+ # GH 42064 46431
1862
+
1863
+ sr = Series([1 / 3, 4, 0, 0, 0, 0, 0])
1864
+ r = sr.rolling(4)
1865
+ result = r.skew()
1866
+ assert (result[-2:] == 0).all()
1867
+ result = r.kurt()
1868
+ assert (result[-2:] == -3).all()
1869
+
1870
+
1871
+ def test_numeric_only_frame(arithmetic_win_operators, numeric_only):
1872
+ # GH#46560
1873
+ kernel = arithmetic_win_operators
1874
+ df = DataFrame({"a": [1], "b": 2, "c": 3})
1875
+ df["c"] = df["c"].astype(object)
1876
+ rolling = df.rolling(2, min_periods=1)
1877
+ op = getattr(rolling, kernel)
1878
+ result = op(numeric_only=numeric_only)
1879
+
1880
+ columns = ["a", "b"] if numeric_only else ["a", "b", "c"]
1881
+ expected = df[columns].agg([kernel]).reset_index(drop=True).astype(float)
1882
+ assert list(expected.columns) == columns
1883
+
1884
+ tm.assert_frame_equal(result, expected)
1885
+
1886
+
1887
+ @pytest.mark.parametrize("kernel", ["corr", "cov"])
1888
+ @pytest.mark.parametrize("use_arg", [True, False])
1889
+ def test_numeric_only_corr_cov_frame(kernel, numeric_only, use_arg):
1890
+ # GH#46560
1891
+ df = DataFrame({"a": [1, 2, 3], "b": 2, "c": 3})
1892
+ df["c"] = df["c"].astype(object)
1893
+ arg = (df,) if use_arg else ()
1894
+ rolling = df.rolling(2, min_periods=1)
1895
+ op = getattr(rolling, kernel)
1896
+ result = op(*arg, numeric_only=numeric_only)
1897
+
1898
+ # Compare result to op using float dtypes, dropping c when numeric_only is True
1899
+ columns = ["a", "b"] if numeric_only else ["a", "b", "c"]
1900
+ df2 = df[columns].astype(float)
1901
+ arg2 = (df2,) if use_arg else ()
1902
+ rolling2 = df2.rolling(2, min_periods=1)
1903
+ op2 = getattr(rolling2, kernel)
1904
+ expected = op2(*arg2, numeric_only=numeric_only)
1905
+
1906
+ tm.assert_frame_equal(result, expected)
1907
+
1908
+
1909
+ @pytest.mark.parametrize("dtype", [int, object])
1910
+ def test_numeric_only_series(arithmetic_win_operators, numeric_only, dtype):
1911
+ # GH#46560
1912
+ kernel = arithmetic_win_operators
1913
+ ser = Series([1], dtype=dtype)
1914
+ rolling = ser.rolling(2, min_periods=1)
1915
+ op = getattr(rolling, kernel)
1916
+ if numeric_only and dtype is object:
1917
+ msg = f"Rolling.{kernel} does not implement numeric_only"
1918
+ with pytest.raises(NotImplementedError, match=msg):
1919
+ op(numeric_only=numeric_only)
1920
+ else:
1921
+ result = op(numeric_only=numeric_only)
1922
+ expected = ser.agg([kernel]).reset_index(drop=True).astype(float)
1923
+ tm.assert_series_equal(result, expected)
1924
+
1925
+
1926
+ @pytest.mark.parametrize("kernel", ["corr", "cov"])
1927
+ @pytest.mark.parametrize("use_arg", [True, False])
1928
+ @pytest.mark.parametrize("dtype", [int, object])
1929
+ def test_numeric_only_corr_cov_series(kernel, use_arg, numeric_only, dtype):
1930
+ # GH#46560
1931
+ ser = Series([1, 2, 3], dtype=dtype)
1932
+ arg = (ser,) if use_arg else ()
1933
+ rolling = ser.rolling(2, min_periods=1)
1934
+ op = getattr(rolling, kernel)
1935
+ if numeric_only and dtype is object:
1936
+ msg = f"Rolling.{kernel} does not implement numeric_only"
1937
+ with pytest.raises(NotImplementedError, match=msg):
1938
+ op(*arg, numeric_only=numeric_only)
1939
+ else:
1940
+ result = op(*arg, numeric_only=numeric_only)
1941
+
1942
+ ser2 = ser.astype(float)
1943
+ arg2 = (ser2,) if use_arg else ()
1944
+ rolling2 = ser2.rolling(2, min_periods=1)
1945
+ op2 = getattr(rolling2, kernel)
1946
+ expected = op2(*arg2, numeric_only=numeric_only)
1947
+ tm.assert_series_equal(result, expected)
1948
+
1949
+
1950
+ @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"])
1951
+ @pytest.mark.parametrize("tz", [None, "UTC", "Europe/Prague"])
1952
+ def test_rolling_timedelta_window_non_nanoseconds(unit, tz):
1953
+ # Test Sum, GH#55106
1954
+ df_time = DataFrame(
1955
+ {"A": range(5)}, index=date_range("2013-01-01", freq="1s", periods=5, tz=tz)
1956
+ )
1957
+ sum_in_nanosecs = df_time.rolling("1s").sum()
1958
+ # microseconds / milliseconds should not break the correct rolling
1959
+ df_time.index = df_time.index.as_unit(unit)
1960
+ sum_in_microsecs = df_time.rolling("1s").sum()
1961
+ sum_in_microsecs.index = sum_in_microsecs.index.as_unit("ns")
1962
+ tm.assert_frame_equal(sum_in_nanosecs, sum_in_microsecs)
1963
+
1964
+ # Test max, GH#55026
1965
+ ref_dates = date_range("2023-01-01", "2023-01-10", unit="ns", tz=tz)
1966
+ ref_series = Series(0, index=ref_dates)
1967
+ ref_series.iloc[0] = 1
1968
+ ref_max_series = ref_series.rolling(Timedelta(days=4)).max()
1969
+
1970
+ dates = date_range("2023-01-01", "2023-01-10", unit=unit, tz=tz)
1971
+ series = Series(0, index=dates)
1972
+ series.iloc[0] = 1
1973
+ max_series = series.rolling(Timedelta(days=4)).max()
1974
+
1975
+ ref_df = DataFrame(ref_max_series)
1976
+ df = DataFrame(max_series)
1977
+ df.index = df.index.as_unit("ns")
1978
+
1979
+ tm.assert_frame_equal(ref_df, df)
shared/package-files/3f/3f34940216f1c7741230839d0db514a6ba364dbdea6ef5831723fcffa19f783d/_geometry.py ADDED
@@ -0,0 +1,1401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numbers
3
+ import warnings
4
+ from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Type, Union
5
+
6
+ import PIL.Image
7
+ import torch
8
+
9
+ from torchvision import transforms as _transforms, tv_tensors
10
+ from torchvision.ops.boxes import box_iou
11
+ from torchvision.transforms.functional import _get_perspective_coeffs
12
+ from torchvision.transforms.v2 import functional as F, InterpolationMode, Transform
13
+ from torchvision.transforms.v2.functional._utils import _FillType
14
+
15
+ from ._transform import _RandomApplyTransform
16
+ from ._utils import (
17
+ _check_padding_arg,
18
+ _check_padding_mode_arg,
19
+ _check_sequence_input,
20
+ _get_fill,
21
+ _setup_angle,
22
+ _setup_fill_arg,
23
+ _setup_number_or_seq,
24
+ _setup_size,
25
+ get_bounding_boxes,
26
+ has_all,
27
+ has_any,
28
+ is_pure_tensor,
29
+ query_size,
30
+ )
31
+
32
+
33
+ class RandomHorizontalFlip(_RandomApplyTransform):
34
+ """Horizontally flip the input with a given probability.
35
+
36
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
37
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
38
+ it can have arbitrary number of leading batch dimensions. For example,
39
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
40
+
41
+ Args:
42
+ p (float, optional): probability of the input being flipped. Default value is 0.5
43
+ """
44
+
45
+ _v1_transform_cls = _transforms.RandomHorizontalFlip
46
+
47
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
48
+ return self._call_kernel(F.horizontal_flip, inpt)
49
+
50
+
51
+ class RandomVerticalFlip(_RandomApplyTransform):
52
+ """Vertically flip the input with a given probability.
53
+
54
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
55
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
56
+ it can have arbitrary number of leading batch dimensions. For example,
57
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
58
+
59
+ Args:
60
+ p (float, optional): probability of the input being flipped. Default value is 0.5
61
+ """
62
+
63
+ _v1_transform_cls = _transforms.RandomVerticalFlip
64
+
65
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
66
+ return self._call_kernel(F.vertical_flip, inpt)
67
+
68
+
69
+ class Resize(Transform):
70
+ """Resize the input to the given size.
71
+
72
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
73
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
74
+ it can have arbitrary number of leading batch dimensions. For example,
75
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
76
+
77
+ Args:
78
+ size (sequence or int): Desired output size. If size is a sequence like
79
+ (h, w), output size will be matched to this. If size is an int,
80
+ smaller edge of the image will be matched to this number.
81
+ i.e, if height > width, then image will be rescaled to
82
+ (size * height / width, size).
83
+
84
+ .. note::
85
+ In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
86
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
87
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
88
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
89
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
90
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
91
+ max_size (int, optional): The maximum allowed for the longer edge of
92
+ the resized image. If the longer edge of the image is greater
93
+ than ``max_size`` after being resized according to ``size``,
94
+ ``size`` will be overruled so that the longer edge is equal to
95
+ ``max_size``.
96
+ As a result, the smaller edge may be shorter than ``size``. This
97
+ is only supported if ``size`` is an int (or a sequence of length
98
+ 1 in torchscript mode).
99
+ antialias (bool, optional): Whether to apply antialiasing.
100
+ It only affects **tensors** with bilinear or bicubic modes and it is
101
+ ignored otherwise: on PIL images, antialiasing is always applied on
102
+ bilinear or bicubic modes; on other modes (for PIL images and
103
+ tensors), antialiasing makes no sense and this parameter is ignored.
104
+ Possible values are:
105
+
106
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
107
+ Other mode aren't affected. This is probably what you want to use.
108
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
109
+ images are still antialiased on bilinear or bicubic modes, because
110
+ PIL doesn't support no antialias.
111
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
112
+ PIL images. This value exists for legacy reasons and you probably
113
+ don't want to use it unless you really know what you are doing.
114
+
115
+ The default value changed from ``None`` to ``True`` in
116
+ v0.17, for the PIL and Tensor backends to be consistent.
117
+ """
118
+
119
+ _v1_transform_cls = _transforms.Resize
120
+
121
+ def __init__(
122
+ self,
123
+ size: Union[int, Sequence[int]],
124
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
125
+ max_size: Optional[int] = None,
126
+ antialias: Optional[bool] = True,
127
+ ) -> None:
128
+ super().__init__()
129
+
130
+ if isinstance(size, int):
131
+ size = [size]
132
+ elif isinstance(size, Sequence) and len(size) in {1, 2}:
133
+ size = list(size)
134
+ else:
135
+ raise ValueError(
136
+ f"size can either be an integer or a sequence of one or two integers, but got {size} instead."
137
+ )
138
+ self.size = size
139
+
140
+ self.interpolation = interpolation
141
+ self.max_size = max_size
142
+ self.antialias = antialias
143
+
144
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
145
+ return self._call_kernel(
146
+ F.resize,
147
+ inpt,
148
+ self.size,
149
+ interpolation=self.interpolation,
150
+ max_size=self.max_size,
151
+ antialias=self.antialias,
152
+ )
153
+
154
+
155
+ class CenterCrop(Transform):
156
+ """Crop the input at the center.
157
+
158
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
159
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
160
+ it can have arbitrary number of leading batch dimensions. For example,
161
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
162
+
163
+ If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
164
+
165
+ Args:
166
+ size (sequence or int): Desired output size of the crop. If size is an
167
+ int instead of sequence like (h, w), a square crop (size, size) is
168
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
169
+ """
170
+
171
+ _v1_transform_cls = _transforms.CenterCrop
172
+
173
+ def __init__(self, size: Union[int, Sequence[int]]):
174
+ super().__init__()
175
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
176
+
177
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
178
+ return self._call_kernel(F.center_crop, inpt, output_size=self.size)
179
+
180
+
181
+ class RandomResizedCrop(Transform):
182
+ """Crop a random portion of the input and resize it to a given size.
183
+
184
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
185
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
186
+ it can have arbitrary number of leading batch dimensions. For example,
187
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
188
+
189
+ A crop of the original input is made: the crop has a random area (H * W)
190
+ and a random aspect ratio. This crop is finally resized to the given
191
+ size. This is popularly used to train the Inception networks.
192
+
193
+ Args:
194
+ size (int or sequence): expected output size of the crop, for each edge. If size is an
195
+ int instead of sequence like (h, w), a square output size ``(size, size)`` is
196
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
197
+
198
+ .. note::
199
+ In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
200
+ scale (tuple of float, optional): Specifies the lower and upper bounds for the random area of the crop,
201
+ before resizing. The scale is defined with respect to the area of the original image.
202
+ ratio (tuple of float, optional): lower and upper bounds for the random aspect ratio of the crop, before
203
+ resizing.
204
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
205
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
206
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
207
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
208
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
209
+ antialias (bool, optional): Whether to apply antialiasing.
210
+ It only affects **tensors** with bilinear or bicubic modes and it is
211
+ ignored otherwise: on PIL images, antialiasing is always applied on
212
+ bilinear or bicubic modes; on other modes (for PIL images and
213
+ tensors), antialiasing makes no sense and this parameter is ignored.
214
+ Possible values are:
215
+
216
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
217
+ Other mode aren't affected. This is probably what you want to use.
218
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
219
+ images are still antialiased on bilinear or bicubic modes, because
220
+ PIL doesn't support no antialias.
221
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
222
+ PIL images. This value exists for legacy reasons and you probably
223
+ don't want to use it unless you really know what you are doing.
224
+
225
+ The default value changed from ``None`` to ``True`` in
226
+ v0.17, for the PIL and Tensor backends to be consistent.
227
+ """
228
+
229
+ _v1_transform_cls = _transforms.RandomResizedCrop
230
+
231
+ def __init__(
232
+ self,
233
+ size: Union[int, Sequence[int]],
234
+ scale: Tuple[float, float] = (0.08, 1.0),
235
+ ratio: Tuple[float, float] = (3.0 / 4.0, 4.0 / 3.0),
236
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
237
+ antialias: Optional[bool] = True,
238
+ ) -> None:
239
+ super().__init__()
240
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
241
+
242
+ if not isinstance(scale, Sequence):
243
+ raise TypeError("Scale should be a sequence")
244
+ if not isinstance(ratio, Sequence):
245
+ raise TypeError("Ratio should be a sequence")
246
+ if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
247
+ warnings.warn("Scale and ratio should be of kind (min, max)")
248
+
249
+ self.scale = scale
250
+ self.ratio = ratio
251
+ self.interpolation = interpolation
252
+ self.antialias = antialias
253
+
254
+ self._log_ratio = torch.log(torch.tensor(self.ratio))
255
+
256
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
257
+ height, width = query_size(flat_inputs)
258
+ area = height * width
259
+
260
+ log_ratio = self._log_ratio
261
+ for _ in range(10):
262
+ target_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item()
263
+ aspect_ratio = torch.exp(
264
+ torch.empty(1).uniform_(
265
+ log_ratio[0], # type: ignore[arg-type]
266
+ log_ratio[1], # type: ignore[arg-type]
267
+ )
268
+ ).item()
269
+
270
+ w = int(round(math.sqrt(target_area * aspect_ratio)))
271
+ h = int(round(math.sqrt(target_area / aspect_ratio)))
272
+
273
+ if 0 < w <= width and 0 < h <= height:
274
+ i = torch.randint(0, height - h + 1, size=(1,)).item()
275
+ j = torch.randint(0, width - w + 1, size=(1,)).item()
276
+ break
277
+ else:
278
+ # Fallback to central crop
279
+ in_ratio = float(width) / float(height)
280
+ if in_ratio < min(self.ratio):
281
+ w = width
282
+ h = int(round(w / min(self.ratio)))
283
+ elif in_ratio > max(self.ratio):
284
+ h = height
285
+ w = int(round(h * max(self.ratio)))
286
+ else: # whole image
287
+ w = width
288
+ h = height
289
+ i = (height - h) // 2
290
+ j = (width - w) // 2
291
+
292
+ return dict(top=i, left=j, height=h, width=w)
293
+
294
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
295
+ return self._call_kernel(
296
+ F.resized_crop, inpt, **params, size=self.size, interpolation=self.interpolation, antialias=self.antialias
297
+ )
298
+
299
+
300
+ class FiveCrop(Transform):
301
+ """Crop the image or video into four corners and the central crop.
302
+
303
+ If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a
304
+ :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions.
305
+ For example, the image can have ``[..., C, H, W]`` shape.
306
+
307
+ .. Note::
308
+ This transform returns a tuple of images and there may be a mismatch in the number of
309
+ inputs and targets your Dataset returns. See below for an example of how to deal with
310
+ this.
311
+
312
+ Args:
313
+ size (sequence or int): Desired output size of the crop. If size is an ``int``
314
+ instead of sequence like (h, w), a square crop of size (size, size) is made.
315
+ If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
316
+
317
+ Example:
318
+ >>> class BatchMultiCrop(transforms.Transform):
319
+ ... def forward(self, sample: Tuple[Tuple[Union[tv_tensors.Image, tv_tensors.Video], ...], int]):
320
+ ... images_or_videos, labels = sample
321
+ ... batch_size = len(images_or_videos)
322
+ ... image_or_video = images_or_videos[0]
323
+ ... images_or_videos = tv_tensors.wrap(torch.stack(images_or_videos), like=image_or_video)
324
+ ... labels = torch.full((batch_size,), label, device=images_or_videos.device)
325
+ ... return images_or_videos, labels
326
+ ...
327
+ >>> image = tv_tensors.Image(torch.rand(3, 256, 256))
328
+ >>> label = 3
329
+ >>> transform = transforms.Compose([transforms.FiveCrop(224), BatchMultiCrop()])
330
+ >>> images, labels = transform(image, label)
331
+ >>> images.shape
332
+ torch.Size([5, 3, 224, 224])
333
+ >>> labels
334
+ tensor([3, 3, 3, 3, 3])
335
+ """
336
+
337
+ _v1_transform_cls = _transforms.FiveCrop
338
+
339
+ def __init__(self, size: Union[int, Sequence[int]]) -> None:
340
+ super().__init__()
341
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
342
+
343
+ def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any:
344
+ if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.Mask)):
345
+ warnings.warn(
346
+ f"{type(self).__name__}() is currently passing through inputs of type "
347
+ f"tv_tensors.{type(inpt).__name__}. This will likely change in the future."
348
+ )
349
+ return super()._call_kernel(functional, inpt, *args, **kwargs)
350
+
351
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
352
+ return self._call_kernel(F.five_crop, inpt, self.size)
353
+
354
+ def _check_inputs(self, flat_inputs: List[Any]) -> None:
355
+ if has_any(flat_inputs, tv_tensors.BoundingBoxes, tv_tensors.Mask):
356
+ raise TypeError(f"BoundingBoxes'es and Mask's are not supported by {type(self).__name__}()")
357
+
358
+
359
+ class TenCrop(Transform):
360
+ """Crop the image or video into four corners and the central crop plus the flipped version of
361
+ these (horizontal flipping is used by default).
362
+
363
+ If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a
364
+ :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions.
365
+ For example, the image can have ``[..., C, H, W]`` shape.
366
+
367
+ See :class:`~torchvision.transforms.v2.FiveCrop` for an example.
368
+
369
+ .. Note::
370
+ This transform returns a tuple of images and there may be a mismatch in the number of
371
+ inputs and targets your Dataset returns. See below for an example of how to deal with
372
+ this.
373
+
374
+ Args:
375
+ size (sequence or int): Desired output size of the crop. If size is an
376
+ int instead of sequence like (h, w), a square crop (size, size) is
377
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
378
+ vertical_flip (bool, optional): Use vertical flipping instead of horizontal
379
+ """
380
+
381
+ _v1_transform_cls = _transforms.TenCrop
382
+
383
+ def __init__(self, size: Union[int, Sequence[int]], vertical_flip: bool = False) -> None:
384
+ super().__init__()
385
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
386
+ self.vertical_flip = vertical_flip
387
+
388
+ def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any:
389
+ if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.Mask)):
390
+ warnings.warn(
391
+ f"{type(self).__name__}() is currently passing through inputs of type "
392
+ f"tv_tensors.{type(inpt).__name__}. This will likely change in the future."
393
+ )
394
+ return super()._call_kernel(functional, inpt, *args, **kwargs)
395
+
396
+ def _check_inputs(self, flat_inputs: List[Any]) -> None:
397
+ if has_any(flat_inputs, tv_tensors.BoundingBoxes, tv_tensors.Mask):
398
+ raise TypeError(f"BoundingBoxes'es and Mask's are not supported by {type(self).__name__}()")
399
+
400
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
401
+ return self._call_kernel(F.ten_crop, inpt, self.size, vertical_flip=self.vertical_flip)
402
+
403
+
404
+ class Pad(Transform):
405
+ """Pad the input on all sides with the given "pad" value.
406
+
407
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
408
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
409
+ it can have arbitrary number of leading batch dimensions. For example,
410
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
411
+
412
+ Args:
413
+ padding (int or sequence): Padding on each border. If a single int is provided this
414
+ is used to pad all borders. If sequence of length 2 is provided this is the padding
415
+ on left/right and top/bottom respectively. If a sequence of length 4 is provided
416
+ this is the padding for the left, top, right and bottom borders respectively.
417
+
418
+ .. note::
419
+ In torchscript mode padding as single int is not supported, use a sequence of
420
+ length 1: ``[padding, ]``.
421
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
422
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
423
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
424
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
425
+ ``Mask`` will be filled with 0.
426
+ padding_mode (str, optional): Type of padding. Should be: constant, edge, reflect or symmetric.
427
+ Default is "constant".
428
+
429
+ - constant: pads with a constant value, this value is specified with fill
430
+
431
+ - edge: pads with the last value at the edge of the image.
432
+
433
+ - reflect: pads with reflection of image without repeating the last value on the edge.
434
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
435
+ will result in [3, 2, 1, 2, 3, 4, 3, 2]
436
+
437
+ - symmetric: pads with reflection of image repeating the last value on the edge.
438
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
439
+ will result in [2, 1, 1, 2, 3, 4, 4, 3]
440
+ """
441
+
442
+ _v1_transform_cls = _transforms.Pad
443
+
444
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
445
+ params = super()._extract_params_for_v1_transform()
446
+
447
+ if not (params["fill"] is None or isinstance(params["fill"], (int, float))):
448
+ raise ValueError(f"{type(self).__name__}() can only be scripted for a scalar `fill`, but got {self.fill}.")
449
+
450
+ return params
451
+
452
+ def __init__(
453
+ self,
454
+ padding: Union[int, Sequence[int]],
455
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
456
+ padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant",
457
+ ) -> None:
458
+ super().__init__()
459
+
460
+ _check_padding_arg(padding)
461
+ _check_padding_mode_arg(padding_mode)
462
+
463
+ # This cast does Sequence[int] -> List[int] and is required to make mypy happy
464
+ if not isinstance(padding, int):
465
+ padding = list(padding)
466
+ self.padding = padding
467
+ self.fill = fill
468
+ self._fill = _setup_fill_arg(fill)
469
+ self.padding_mode = padding_mode
470
+
471
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
472
+ fill = _get_fill(self._fill, type(inpt))
473
+ return self._call_kernel(F.pad, inpt, padding=self.padding, fill=fill, padding_mode=self.padding_mode) # type: ignore[arg-type]
474
+
475
+
476
+ class RandomZoomOut(_RandomApplyTransform):
477
+ """ "Zoom out" transformation from
478
+ `"SSD: Single Shot MultiBox Detector" <https://arxiv.org/abs/1512.02325>`_.
479
+
480
+ This transformation randomly pads images, videos, bounding boxes and masks creating a zoom out effect.
481
+ Output spatial size is randomly sampled from original size up to a maximum size configured
482
+ with ``side_range`` parameter:
483
+
484
+ .. code-block:: python
485
+
486
+ r = uniform_sample(side_range[0], side_range[1])
487
+ output_width = input_width * r
488
+ output_height = input_height * r
489
+
490
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
491
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
492
+ it can have arbitrary number of leading batch dimensions. For example,
493
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
494
+
495
+ Args:
496
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
497
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
498
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
499
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
500
+ ``Mask`` will be filled with 0.
501
+ side_range (sequence of floats, optional): tuple of two floats defines minimum and maximum factors to
502
+ scale the input size.
503
+ p (float, optional): probability that the zoom operation will be performed.
504
+ """
505
+
506
+ def __init__(
507
+ self,
508
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
509
+ side_range: Sequence[float] = (1.0, 4.0),
510
+ p: float = 0.5,
511
+ ) -> None:
512
+ super().__init__(p=p)
513
+
514
+ self.fill = fill
515
+ self._fill = _setup_fill_arg(fill)
516
+
517
+ _check_sequence_input(side_range, "side_range", req_sizes=(2,))
518
+
519
+ self.side_range = side_range
520
+ if side_range[0] < 1.0 or side_range[0] > side_range[1]:
521
+ raise ValueError(f"Invalid side range provided {side_range}.")
522
+
523
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
524
+ orig_h, orig_w = query_size(flat_inputs)
525
+
526
+ r = self.side_range[0] + torch.rand(1) * (self.side_range[1] - self.side_range[0])
527
+ canvas_width = int(orig_w * r)
528
+ canvas_height = int(orig_h * r)
529
+
530
+ r = torch.rand(2)
531
+ left = int((canvas_width - orig_w) * r[0])
532
+ top = int((canvas_height - orig_h) * r[1])
533
+ right = canvas_width - (left + orig_w)
534
+ bottom = canvas_height - (top + orig_h)
535
+ padding = [left, top, right, bottom]
536
+
537
+ return dict(padding=padding)
538
+
539
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
540
+ fill = _get_fill(self._fill, type(inpt))
541
+ return self._call_kernel(F.pad, inpt, **params, fill=fill)
542
+
543
+
544
+ class RandomRotation(Transform):
545
+ """Rotate the input by angle.
546
+
547
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
548
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
549
+ it can have arbitrary number of leading batch dimensions. For example,
550
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
551
+
552
+ Args:
553
+ degrees (sequence or number): Range of degrees to select from.
554
+ If degrees is a number instead of sequence like (min, max), the range of degrees
555
+ will be (-degrees, +degrees).
556
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
557
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
558
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
559
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
560
+ expand (bool, optional): Optional expansion flag.
561
+ If true, expands the output to make it large enough to hold the entire rotated image.
562
+ If false or omitted, make the output image the same size as the input image.
563
+ Note that the expand flag assumes rotation around the center (see note below) and no translation.
564
+ center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
565
+ Default is the center of the image.
566
+
567
+ .. note::
568
+
569
+ In theory, setting ``center`` has no effect if ``expand=True``, since the image center will become the
570
+ center of rotation. In practice however, due to numerical precision, this can lead to off-by-one
571
+ differences of the resulting image size compared to using the image center in the first place. Thus, when
572
+ setting ``expand=True``, it's best to leave ``center=None`` (default).
573
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
574
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
575
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
576
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
577
+ ``Mask`` will be filled with 0.
578
+
579
+ .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
580
+
581
+ """
582
+
583
+ _v1_transform_cls = _transforms.RandomRotation
584
+
585
+ def __init__(
586
+ self,
587
+ degrees: Union[numbers.Number, Sequence],
588
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST,
589
+ expand: bool = False,
590
+ center: Optional[List[float]] = None,
591
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
592
+ ) -> None:
593
+ super().__init__()
594
+ self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
595
+ self.interpolation = interpolation
596
+ self.expand = expand
597
+
598
+ self.fill = fill
599
+ self._fill = _setup_fill_arg(fill)
600
+
601
+ if center is not None:
602
+ _check_sequence_input(center, "center", req_sizes=(2,))
603
+
604
+ self.center = center
605
+
606
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
607
+ angle = torch.empty(1).uniform_(self.degrees[0], self.degrees[1]).item()
608
+ return dict(angle=angle)
609
+
610
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
611
+ fill = _get_fill(self._fill, type(inpt))
612
+ return self._call_kernel(
613
+ F.rotate,
614
+ inpt,
615
+ **params,
616
+ interpolation=self.interpolation,
617
+ expand=self.expand,
618
+ center=self.center,
619
+ fill=fill,
620
+ )
621
+
622
+
623
+ class RandomAffine(Transform):
624
+ """Random affine transformation the input keeping center invariant.
625
+
626
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
627
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
628
+ it can have arbitrary number of leading batch dimensions. For example,
629
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
630
+
631
+ Args:
632
+ degrees (sequence or number): Range of degrees to select from.
633
+ If degrees is a number instead of sequence like (min, max), the range of degrees
634
+ will be (-degrees, +degrees). Set to 0 to deactivate rotations.
635
+ translate (tuple, optional): tuple of maximum absolute fraction for horizontal
636
+ and vertical translations. For example translate=(a, b), then horizontal shift
637
+ is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
638
+ randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
639
+ scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
640
+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.
641
+ shear (sequence or number, optional): Range of degrees to select from.
642
+ If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear)
643
+ will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the
644
+ range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values,
645
+ an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
646
+ Will not apply shear by default.
647
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
648
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
649
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
650
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
651
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
652
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
653
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
654
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
655
+ ``Mask`` will be filled with 0.
656
+ center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
657
+ Default is the center of the image.
658
+
659
+ .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
660
+
661
+ """
662
+
663
+ _v1_transform_cls = _transforms.RandomAffine
664
+
665
+ def __init__(
666
+ self,
667
+ degrees: Union[numbers.Number, Sequence],
668
+ translate: Optional[Sequence[float]] = None,
669
+ scale: Optional[Sequence[float]] = None,
670
+ shear: Optional[Union[int, float, Sequence[float]]] = None,
671
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST,
672
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
673
+ center: Optional[List[float]] = None,
674
+ ) -> None:
675
+ super().__init__()
676
+ self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
677
+ if translate is not None:
678
+ _check_sequence_input(translate, "translate", req_sizes=(2,))
679
+ for t in translate:
680
+ if not (0.0 <= t <= 1.0):
681
+ raise ValueError("translation values should be between 0 and 1")
682
+ self.translate = translate
683
+ if scale is not None:
684
+ _check_sequence_input(scale, "scale", req_sizes=(2,))
685
+ for s in scale:
686
+ if s <= 0:
687
+ raise ValueError("scale values should be positive")
688
+ self.scale = scale
689
+
690
+ if shear is not None:
691
+ self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4))
692
+ else:
693
+ self.shear = shear
694
+
695
+ self.interpolation = interpolation
696
+ self.fill = fill
697
+ self._fill = _setup_fill_arg(fill)
698
+
699
+ if center is not None:
700
+ _check_sequence_input(center, "center", req_sizes=(2,))
701
+
702
+ self.center = center
703
+
704
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
705
+ height, width = query_size(flat_inputs)
706
+
707
+ angle = torch.empty(1).uniform_(self.degrees[0], self.degrees[1]).item()
708
+ if self.translate is not None:
709
+ max_dx = float(self.translate[0] * width)
710
+ max_dy = float(self.translate[1] * height)
711
+ tx = int(round(torch.empty(1).uniform_(-max_dx, max_dx).item()))
712
+ ty = int(round(torch.empty(1).uniform_(-max_dy, max_dy).item()))
713
+ translate = (tx, ty)
714
+ else:
715
+ translate = (0, 0)
716
+
717
+ if self.scale is not None:
718
+ scale = torch.empty(1).uniform_(self.scale[0], self.scale[1]).item()
719
+ else:
720
+ scale = 1.0
721
+
722
+ shear_x = shear_y = 0.0
723
+ if self.shear is not None:
724
+ shear_x = torch.empty(1).uniform_(self.shear[0], self.shear[1]).item()
725
+ if len(self.shear) == 4:
726
+ shear_y = torch.empty(1).uniform_(self.shear[2], self.shear[3]).item()
727
+
728
+ shear = (shear_x, shear_y)
729
+ return dict(angle=angle, translate=translate, scale=scale, shear=shear)
730
+
731
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
732
+ fill = _get_fill(self._fill, type(inpt))
733
+ return self._call_kernel(
734
+ F.affine,
735
+ inpt,
736
+ **params,
737
+ interpolation=self.interpolation,
738
+ fill=fill,
739
+ center=self.center,
740
+ )
741
+
742
+
743
+ class RandomCrop(Transform):
744
+ """Crop the input at a random location.
745
+
746
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
747
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
748
+ it can have arbitrary number of leading batch dimensions. For example,
749
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
750
+
751
+ Args:
752
+ size (sequence or int): Desired output size of the crop. If size is an
753
+ int instead of sequence like (h, w), a square crop (size, size) is
754
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
755
+ padding (int or sequence, optional): Optional padding on each border
756
+ of the image. Default is None. If a single int is provided this
757
+ is used to pad all borders. If sequence of length 2 is provided this is the padding
758
+ on left/right and top/bottom respectively. If a sequence of length 4 is provided
759
+ this is the padding for the left, top, right and bottom borders respectively.
760
+
761
+ .. note::
762
+ In torchscript mode padding as single int is not supported, use a sequence of
763
+ length 1: ``[padding, ]``.
764
+ pad_if_needed (boolean, optional): It will pad the image if smaller than the
765
+ desired size to avoid raising an exception. Since cropping is done
766
+ after padding, the padding seems to be done at a random offset.
767
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
768
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
769
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
770
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
771
+ ``Mask`` will be filled with 0.
772
+ padding_mode (str, optional): Type of padding. Should be: constant, edge, reflect or symmetric.
773
+ Default is constant.
774
+
775
+ - constant: pads with a constant value, this value is specified with fill
776
+
777
+ - edge: pads with the last value at the edge of the image.
778
+
779
+ - reflect: pads with reflection of image without repeating the last value on the edge.
780
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
781
+ will result in [3, 2, 1, 2, 3, 4, 3, 2]
782
+
783
+ - symmetric: pads with reflection of image repeating the last value on the edge.
784
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
785
+ will result in [2, 1, 1, 2, 3, 4, 4, 3]
786
+ """
787
+
788
+ _v1_transform_cls = _transforms.RandomCrop
789
+
790
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
791
+ params = super()._extract_params_for_v1_transform()
792
+
793
+ if not (params["fill"] is None or isinstance(params["fill"], (int, float))):
794
+ raise ValueError(f"{type(self).__name__}() can only be scripted for a scalar `fill`, but got {self.fill}.")
795
+
796
+ padding = self.padding
797
+ if padding is not None:
798
+ pad_left, pad_right, pad_top, pad_bottom = padding
799
+ padding = [pad_left, pad_top, pad_right, pad_bottom]
800
+ params["padding"] = padding
801
+
802
+ return params
803
+
804
+ def __init__(
805
+ self,
806
+ size: Union[int, Sequence[int]],
807
+ padding: Optional[Union[int, Sequence[int]]] = None,
808
+ pad_if_needed: bool = False,
809
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
810
+ padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant",
811
+ ) -> None:
812
+ super().__init__()
813
+
814
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
815
+
816
+ if pad_if_needed or padding is not None:
817
+ if padding is not None:
818
+ _check_padding_arg(padding)
819
+ _check_padding_mode_arg(padding_mode)
820
+
821
+ self.padding = F._geometry._parse_pad_padding(padding) if padding else None # type: ignore[arg-type]
822
+ self.pad_if_needed = pad_if_needed
823
+ self.fill = fill
824
+ self._fill = _setup_fill_arg(fill)
825
+ self.padding_mode = padding_mode
826
+
827
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
828
+ padded_height, padded_width = query_size(flat_inputs)
829
+
830
+ if self.padding is not None:
831
+ pad_left, pad_right, pad_top, pad_bottom = self.padding
832
+ padded_height += pad_top + pad_bottom
833
+ padded_width += pad_left + pad_right
834
+ else:
835
+ pad_left = pad_right = pad_top = pad_bottom = 0
836
+
837
+ cropped_height, cropped_width = self.size
838
+
839
+ if self.pad_if_needed:
840
+ if padded_height < cropped_height:
841
+ diff = cropped_height - padded_height
842
+
843
+ pad_top += diff
844
+ pad_bottom += diff
845
+ padded_height += 2 * diff
846
+
847
+ if padded_width < cropped_width:
848
+ diff = cropped_width - padded_width
849
+
850
+ pad_left += diff
851
+ pad_right += diff
852
+ padded_width += 2 * diff
853
+
854
+ if padded_height < cropped_height or padded_width < cropped_width:
855
+ raise ValueError(
856
+ f"Required crop size {(cropped_height, cropped_width)} is larger than "
857
+ f"{'padded ' if self.padding is not None else ''}input image size {(padded_height, padded_width)}."
858
+ )
859
+
860
+ # We need a different order here than we have in self.padding since this padding will be parsed again in `F.pad`
861
+ padding = [pad_left, pad_top, pad_right, pad_bottom]
862
+ needs_pad = any(padding)
863
+
864
+ needs_vert_crop, top = (
865
+ (True, int(torch.randint(0, padded_height - cropped_height + 1, size=())))
866
+ if padded_height > cropped_height
867
+ else (False, 0)
868
+ )
869
+ needs_horz_crop, left = (
870
+ (True, int(torch.randint(0, padded_width - cropped_width + 1, size=())))
871
+ if padded_width > cropped_width
872
+ else (False, 0)
873
+ )
874
+
875
+ return dict(
876
+ needs_crop=needs_vert_crop or needs_horz_crop,
877
+ top=top,
878
+ left=left,
879
+ height=cropped_height,
880
+ width=cropped_width,
881
+ needs_pad=needs_pad,
882
+ padding=padding,
883
+ )
884
+
885
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
886
+ if params["needs_pad"]:
887
+ fill = _get_fill(self._fill, type(inpt))
888
+ inpt = self._call_kernel(F.pad, inpt, padding=params["padding"], fill=fill, padding_mode=self.padding_mode)
889
+
890
+ if params["needs_crop"]:
891
+ inpt = self._call_kernel(
892
+ F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"]
893
+ )
894
+
895
+ return inpt
896
+
897
+
898
+ class RandomPerspective(_RandomApplyTransform):
899
+ """Perform a random perspective transformation of the input with a given probability.
900
+
901
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
902
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
903
+ it can have arbitrary number of leading batch dimensions. For example,
904
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
905
+
906
+ Args:
907
+ distortion_scale (float, optional): argument to control the degree of distortion and ranges from 0 to 1.
908
+ Default is 0.5.
909
+ p (float, optional): probability of the input being transformed. Default is 0.5.
910
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
911
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
912
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
913
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
914
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
915
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
916
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
917
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
918
+ ``Mask`` will be filled with 0.
919
+ """
920
+
921
+ _v1_transform_cls = _transforms.RandomPerspective
922
+
923
+ def __init__(
924
+ self,
925
+ distortion_scale: float = 0.5,
926
+ p: float = 0.5,
927
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
928
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
929
+ ) -> None:
930
+ super().__init__(p=p)
931
+
932
+ if not (0 <= distortion_scale <= 1):
933
+ raise ValueError("Argument distortion_scale value should be between 0 and 1")
934
+
935
+ self.distortion_scale = distortion_scale
936
+ self.interpolation = interpolation
937
+ self.fill = fill
938
+ self._fill = _setup_fill_arg(fill)
939
+
940
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
941
+ height, width = query_size(flat_inputs)
942
+
943
+ distortion_scale = self.distortion_scale
944
+
945
+ half_height = height // 2
946
+ half_width = width // 2
947
+ bound_height = int(distortion_scale * half_height) + 1
948
+ bound_width = int(distortion_scale * half_width) + 1
949
+ topleft = [
950
+ int(torch.randint(0, bound_width, size=(1,))),
951
+ int(torch.randint(0, bound_height, size=(1,))),
952
+ ]
953
+ topright = [
954
+ int(torch.randint(width - bound_width, width, size=(1,))),
955
+ int(torch.randint(0, bound_height, size=(1,))),
956
+ ]
957
+ botright = [
958
+ int(torch.randint(width - bound_width, width, size=(1,))),
959
+ int(torch.randint(height - bound_height, height, size=(1,))),
960
+ ]
961
+ botleft = [
962
+ int(torch.randint(0, bound_width, size=(1,))),
963
+ int(torch.randint(height - bound_height, height, size=(1,))),
964
+ ]
965
+ startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]
966
+ endpoints = [topleft, topright, botright, botleft]
967
+ perspective_coeffs = _get_perspective_coeffs(startpoints, endpoints)
968
+ return dict(coefficients=perspective_coeffs)
969
+
970
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
971
+ fill = _get_fill(self._fill, type(inpt))
972
+ return self._call_kernel(
973
+ F.perspective,
974
+ inpt,
975
+ startpoints=None,
976
+ endpoints=None,
977
+ fill=fill,
978
+ interpolation=self.interpolation,
979
+ **params,
980
+ )
981
+
982
+
983
+ class ElasticTransform(Transform):
984
+ """Transform the input with elastic transformations.
985
+
986
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
987
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
988
+ it can have arbitrary number of leading batch dimensions. For example,
989
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
990
+
991
+ Given alpha and sigma, it will generate displacement
992
+ vectors for all pixels based on random offsets. Alpha controls the strength
993
+ and sigma controls the smoothness of the displacements.
994
+ The displacements are added to an identity grid and the resulting grid is
995
+ used to transform the input.
996
+
997
+ .. note::
998
+ Implementation to transform bounding boxes is approximative (not exact).
999
+ We construct an approximation of the inverse grid as ``inverse_grid = identity - displacement``.
1000
+ This is not an exact inverse of the grid used to transform images, i.e. ``grid = identity + displacement``.
1001
+ Our assumption is that ``displacement * displacement`` is small and can be ignored.
1002
+ Large displacements would lead to large errors in the approximation.
1003
+
1004
+ Applications:
1005
+ Randomly transforms the morphology of objects in images and produces a
1006
+ see-through-water-like effect.
1007
+
1008
+ Args:
1009
+ alpha (float or sequence of floats, optional): Magnitude of displacements. Default is 50.0.
1010
+ sigma (float or sequence of floats, optional): Smoothness of displacements. Default is 5.0.
1011
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
1012
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
1013
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
1014
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1015
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
1016
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
1017
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
1018
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
1019
+ ``Mask`` will be filled with 0.
1020
+ """
1021
+
1022
+ _v1_transform_cls = _transforms.ElasticTransform
1023
+
1024
+ def __init__(
1025
+ self,
1026
+ alpha: Union[float, Sequence[float]] = 50.0,
1027
+ sigma: Union[float, Sequence[float]] = 5.0,
1028
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
1029
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
1030
+ ) -> None:
1031
+ super().__init__()
1032
+ self.alpha = _setup_number_or_seq(alpha, "alpha")
1033
+ self.sigma = _setup_number_or_seq(sigma, "sigma")
1034
+
1035
+ self.interpolation = interpolation
1036
+ self.fill = fill
1037
+ self._fill = _setup_fill_arg(fill)
1038
+
1039
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1040
+ size = list(query_size(flat_inputs))
1041
+
1042
+ dx = torch.rand([1, 1] + size) * 2 - 1
1043
+ if self.sigma[0] > 0.0:
1044
+ kx = int(8 * self.sigma[0] + 1)
1045
+ # if kernel size is even we have to make it odd
1046
+ if kx % 2 == 0:
1047
+ kx += 1
1048
+ dx = self._call_kernel(F.gaussian_blur, dx, [kx, kx], list(self.sigma))
1049
+ dx = dx * self.alpha[0] / size[0]
1050
+
1051
+ dy = torch.rand([1, 1] + size) * 2 - 1
1052
+ if self.sigma[1] > 0.0:
1053
+ ky = int(8 * self.sigma[1] + 1)
1054
+ # if kernel size is even we have to make it odd
1055
+ if ky % 2 == 0:
1056
+ ky += 1
1057
+ dy = self._call_kernel(F.gaussian_blur, dy, [ky, ky], list(self.sigma))
1058
+ dy = dy * self.alpha[1] / size[1]
1059
+ displacement = torch.concat([dx, dy], 1).permute([0, 2, 3, 1]) # 1 x H x W x 2
1060
+ return dict(displacement=displacement)
1061
+
1062
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1063
+ fill = _get_fill(self._fill, type(inpt))
1064
+ return self._call_kernel(
1065
+ F.elastic,
1066
+ inpt,
1067
+ **params,
1068
+ fill=fill,
1069
+ interpolation=self.interpolation,
1070
+ )
1071
+
1072
+
1073
+ class RandomIoUCrop(Transform):
1074
+ """Random IoU crop transformation from
1075
+ `"SSD: Single Shot MultiBox Detector" <https://arxiv.org/abs/1512.02325>`_.
1076
+
1077
+ This transformation requires an image or video data and ``tv_tensors.BoundingBoxes`` in the input.
1078
+
1079
+ .. warning::
1080
+ In order to properly remove the bounding boxes below the IoU threshold, `RandomIoUCrop`
1081
+ must be followed by :class:`~torchvision.transforms.v2.SanitizeBoundingBoxes`, either immediately
1082
+ after or later in the transforms pipeline.
1083
+
1084
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
1085
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
1086
+ it can have arbitrary number of leading batch dimensions. For example,
1087
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
1088
+
1089
+ Args:
1090
+ min_scale (float, optional): Minimum factors to scale the input size.
1091
+ max_scale (float, optional): Maximum factors to scale the input size.
1092
+ min_aspect_ratio (float, optional): Minimum aspect ratio for the cropped image or video.
1093
+ max_aspect_ratio (float, optional): Maximum aspect ratio for the cropped image or video.
1094
+ sampler_options (list of float, optional): List of minimal IoU (Jaccard) overlap between all the boxes and
1095
+ a cropped image or video. Default, ``None`` which corresponds to ``[0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]``
1096
+ trials (int, optional): Number of trials to find a crop for a given value of minimal IoU (Jaccard) overlap.
1097
+ Default, 40.
1098
+ """
1099
+
1100
+ def __init__(
1101
+ self,
1102
+ min_scale: float = 0.3,
1103
+ max_scale: float = 1.0,
1104
+ min_aspect_ratio: float = 0.5,
1105
+ max_aspect_ratio: float = 2.0,
1106
+ sampler_options: Optional[List[float]] = None,
1107
+ trials: int = 40,
1108
+ ):
1109
+ super().__init__()
1110
+ # Configuration similar to https://github.com/weiliu89/caffe/blob/ssd/examples/ssd/ssd_coco.py#L89-L174
1111
+ self.min_scale = min_scale
1112
+ self.max_scale = max_scale
1113
+ self.min_aspect_ratio = min_aspect_ratio
1114
+ self.max_aspect_ratio = max_aspect_ratio
1115
+ if sampler_options is None:
1116
+ sampler_options = [0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]
1117
+ self.options = sampler_options
1118
+ self.trials = trials
1119
+
1120
+ def _check_inputs(self, flat_inputs: List[Any]) -> None:
1121
+ if not (
1122
+ has_all(flat_inputs, tv_tensors.BoundingBoxes)
1123
+ and has_any(flat_inputs, PIL.Image.Image, tv_tensors.Image, is_pure_tensor)
1124
+ ):
1125
+ raise TypeError(
1126
+ f"{type(self).__name__}() requires input sample to contain tensor or PIL images "
1127
+ "and bounding boxes. Sample can also contain masks."
1128
+ )
1129
+
1130
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1131
+ orig_h, orig_w = query_size(flat_inputs)
1132
+ bboxes = get_bounding_boxes(flat_inputs)
1133
+
1134
+ while True:
1135
+ # sample an option
1136
+ idx = int(torch.randint(low=0, high=len(self.options), size=(1,)))
1137
+ min_jaccard_overlap = self.options[idx]
1138
+ if min_jaccard_overlap >= 1.0: # a value larger than 1 encodes the leave as-is option
1139
+ return dict()
1140
+
1141
+ for _ in range(self.trials):
1142
+ # check the aspect ratio limitations
1143
+ r = self.min_scale + (self.max_scale - self.min_scale) * torch.rand(2)
1144
+ new_w = int(orig_w * r[0])
1145
+ new_h = int(orig_h * r[1])
1146
+ aspect_ratio = new_w / new_h
1147
+ if not (self.min_aspect_ratio <= aspect_ratio <= self.max_aspect_ratio):
1148
+ continue
1149
+
1150
+ # check for 0 area crops
1151
+ r = torch.rand(2)
1152
+ left = int((orig_w - new_w) * r[0])
1153
+ top = int((orig_h - new_h) * r[1])
1154
+ right = left + new_w
1155
+ bottom = top + new_h
1156
+ if left == right or top == bottom:
1157
+ continue
1158
+
1159
+ # check for any valid boxes with centers within the crop area
1160
+ xyxy_bboxes = F.convert_bounding_box_format(
1161
+ bboxes.as_subclass(torch.Tensor),
1162
+ bboxes.format,
1163
+ tv_tensors.BoundingBoxFormat.XYXY,
1164
+ )
1165
+ cx = 0.5 * (xyxy_bboxes[..., 0] + xyxy_bboxes[..., 2])
1166
+ cy = 0.5 * (xyxy_bboxes[..., 1] + xyxy_bboxes[..., 3])
1167
+ is_within_crop_area = (left < cx) & (cx < right) & (top < cy) & (cy < bottom)
1168
+ if not is_within_crop_area.any():
1169
+ continue
1170
+
1171
+ # check at least 1 box with jaccard limitations
1172
+ xyxy_bboxes = xyxy_bboxes[is_within_crop_area]
1173
+ ious = box_iou(
1174
+ xyxy_bboxes,
1175
+ torch.tensor([[left, top, right, bottom]], dtype=xyxy_bboxes.dtype, device=xyxy_bboxes.device),
1176
+ )
1177
+ if ious.max() < min_jaccard_overlap:
1178
+ continue
1179
+
1180
+ return dict(top=top, left=left, height=new_h, width=new_w, is_within_crop_area=is_within_crop_area)
1181
+
1182
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1183
+
1184
+ if len(params) < 1:
1185
+ return inpt
1186
+
1187
+ output = self._call_kernel(
1188
+ F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"]
1189
+ )
1190
+
1191
+ if isinstance(output, tv_tensors.BoundingBoxes):
1192
+ # We "mark" the invalid boxes as degenreate, and they can be
1193
+ # removed by a later call to SanitizeBoundingBoxes()
1194
+ output[~params["is_within_crop_area"]] = 0
1195
+
1196
+ return output
1197
+
1198
+
1199
+ class ScaleJitter(Transform):
1200
+ """Perform Large Scale Jitter on the input according to
1201
+ `"Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation" <https://arxiv.org/abs/2012.07177>`_.
1202
+
1203
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
1204
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
1205
+ it can have arbitrary number of leading batch dimensions. For example,
1206
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
1207
+
1208
+ Args:
1209
+ target_size (tuple of int): Target size. This parameter defines base scale for jittering,
1210
+ e.g. ``min(target_size[0] / width, target_size[1] / height)``.
1211
+ scale_range (tuple of float, optional): Minimum and maximum of the scale range. Default, ``(0.1, 2.0)``.
1212
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
1213
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
1214
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
1215
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
1216
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1217
+ antialias (bool, optional): Whether to apply antialiasing.
1218
+ It only affects **tensors** with bilinear or bicubic modes and it is
1219
+ ignored otherwise: on PIL images, antialiasing is always applied on
1220
+ bilinear or bicubic modes; on other modes (for PIL images and
1221
+ tensors), antialiasing makes no sense and this parameter is ignored.
1222
+ Possible values are:
1223
+
1224
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
1225
+ Other mode aren't affected. This is probably what you want to use.
1226
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
1227
+ images are still antialiased on bilinear or bicubic modes, because
1228
+ PIL doesn't support no antialias.
1229
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
1230
+ PIL images. This value exists for legacy reasons and you probably
1231
+ don't want to use it unless you really know what you are doing.
1232
+
1233
+ The default value changed from ``None`` to ``True`` in
1234
+ v0.17, for the PIL and Tensor backends to be consistent.
1235
+ """
1236
+
1237
+ def __init__(
1238
+ self,
1239
+ target_size: Tuple[int, int],
1240
+ scale_range: Tuple[float, float] = (0.1, 2.0),
1241
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
1242
+ antialias: Optional[bool] = True,
1243
+ ):
1244
+ super().__init__()
1245
+ self.target_size = target_size
1246
+ self.scale_range = scale_range
1247
+ self.interpolation = interpolation
1248
+ self.antialias = antialias
1249
+
1250
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1251
+ orig_height, orig_width = query_size(flat_inputs)
1252
+
1253
+ scale = self.scale_range[0] + torch.rand(1) * (self.scale_range[1] - self.scale_range[0])
1254
+ r = min(self.target_size[1] / orig_height, self.target_size[0] / orig_width) * scale
1255
+ new_width = int(orig_width * r)
1256
+ new_height = int(orig_height * r)
1257
+
1258
+ return dict(size=(new_height, new_width))
1259
+
1260
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1261
+ return self._call_kernel(
1262
+ F.resize, inpt, size=params["size"], interpolation=self.interpolation, antialias=self.antialias
1263
+ )
1264
+
1265
+
1266
+ class RandomShortestSize(Transform):
1267
+ """Randomly resize the input.
1268
+
1269
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
1270
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
1271
+ it can have arbitrary number of leading batch dimensions. For example,
1272
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
1273
+
1274
+ Args:
1275
+ min_size (int or sequence of int): Minimum spatial size. Single integer value or a sequence of integer values.
1276
+ max_size (int, optional): Maximum spatial size. Default, None.
1277
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
1278
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
1279
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
1280
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
1281
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1282
+ antialias (bool, optional): Whether to apply antialiasing.
1283
+ It only affects **tensors** with bilinear or bicubic modes and it is
1284
+ ignored otherwise: on PIL images, antialiasing is always applied on
1285
+ bilinear or bicubic modes; on other modes (for PIL images and
1286
+ tensors), antialiasing makes no sense and this parameter is ignored.
1287
+ Possible values are:
1288
+
1289
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
1290
+ Other mode aren't affected. This is probably what you want to use.
1291
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
1292
+ images are still antialiased on bilinear or bicubic modes, because
1293
+ PIL doesn't support no antialias.
1294
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
1295
+ PIL images. This value exists for legacy reasons and you probably
1296
+ don't want to use it unless you really know what you are doing.
1297
+
1298
+ The default value changed from ``None`` to ``True`` in
1299
+ v0.17, for the PIL and Tensor backends to be consistent.
1300
+ """
1301
+
1302
+ def __init__(
1303
+ self,
1304
+ min_size: Union[List[int], Tuple[int], int],
1305
+ max_size: Optional[int] = None,
1306
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
1307
+ antialias: Optional[bool] = True,
1308
+ ):
1309
+ super().__init__()
1310
+ self.min_size = [min_size] if isinstance(min_size, int) else list(min_size)
1311
+ self.max_size = max_size
1312
+ self.interpolation = interpolation
1313
+ self.antialias = antialias
1314
+
1315
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1316
+ orig_height, orig_width = query_size(flat_inputs)
1317
+
1318
+ min_size = self.min_size[int(torch.randint(len(self.min_size), ()))]
1319
+ r = min_size / min(orig_height, orig_width)
1320
+ if self.max_size is not None:
1321
+ r = min(r, self.max_size / max(orig_height, orig_width))
1322
+
1323
+ new_width = int(orig_width * r)
1324
+ new_height = int(orig_height * r)
1325
+
1326
+ return dict(size=(new_height, new_width))
1327
+
1328
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1329
+ return self._call_kernel(
1330
+ F.resize, inpt, size=params["size"], interpolation=self.interpolation, antialias=self.antialias
1331
+ )
1332
+
1333
+
1334
+ class RandomResize(Transform):
1335
+ """Randomly resize the input.
1336
+
1337
+ This transformation can be used together with ``RandomCrop`` as data augmentations to train
1338
+ models on image segmentation task.
1339
+
1340
+ Output spatial size is randomly sampled from the interval ``[min_size, max_size]``:
1341
+
1342
+ .. code-block:: python
1343
+
1344
+ size = uniform_sample(min_size, max_size)
1345
+ output_width = size
1346
+ output_height = size
1347
+
1348
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
1349
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
1350
+ it can have arbitrary number of leading batch dimensions. For example,
1351
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
1352
+
1353
+ Args:
1354
+ min_size (int): Minimum output size for random sampling
1355
+ max_size (int): Maximum output size for random sampling
1356
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
1357
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
1358
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
1359
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
1360
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1361
+ antialias (bool, optional): Whether to apply antialiasing.
1362
+ It only affects **tensors** with bilinear or bicubic modes and it is
1363
+ ignored otherwise: on PIL images, antialiasing is always applied on
1364
+ bilinear or bicubic modes; on other modes (for PIL images and
1365
+ tensors), antialiasing makes no sense and this parameter is ignored.
1366
+ Possible values are:
1367
+
1368
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
1369
+ Other mode aren't affected. This is probably what you want to use.
1370
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
1371
+ images are still antialiased on bilinear or bicubic modes, because
1372
+ PIL doesn't support no antialias.
1373
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
1374
+ PIL images. This value exists for legacy reasons and you probably
1375
+ don't want to use it unless you really know what you are doing.
1376
+
1377
+ The default value changed from ``None`` to ``True`` in
1378
+ v0.17, for the PIL and Tensor backends to be consistent.
1379
+ """
1380
+
1381
+ def __init__(
1382
+ self,
1383
+ min_size: int,
1384
+ max_size: int,
1385
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
1386
+ antialias: Optional[bool] = True,
1387
+ ) -> None:
1388
+ super().__init__()
1389
+ self.min_size = min_size
1390
+ self.max_size = max_size
1391
+ self.interpolation = interpolation
1392
+ self.antialias = antialias
1393
+
1394
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1395
+ size = int(torch.randint(self.min_size, self.max_size, ()))
1396
+ return dict(size=[size])
1397
+
1398
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1399
+ return self._call_kernel(
1400
+ F.resize, inpt, params["size"], interpolation=self.interpolation, antialias=self.antialias
1401
+ )
shared/package-files/3f/3f37d7921a6eb05206570af356ca8b8258e5c9b37dd8e794d3f137ac7ba9da6d/forth.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.lexers.forth
3
+ ~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Lexer for the Forth language.
6
+
7
+ :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+
11
+ import re
12
+
13
+ from pygments.lexer import RegexLexer, bygroups
14
+ from pygments.token import Text, Comment, Keyword, Name, String, Number, \
15
+ Whitespace
16
+
17
+
18
+ __all__ = ['ForthLexer']
19
+
20
+
21
+ class ForthLexer(RegexLexer):
22
+ """
23
+ Lexer for Forth files.
24
+
25
+ .. versionadded:: 2.2
26
+ """
27
+ name = 'Forth'
28
+ url = 'https://www.forth.com/forth/'
29
+ aliases = ['forth']
30
+ filenames = ['*.frt', '*.fs']
31
+ mimetypes = ['application/x-forth']
32
+
33
+ flags = re.IGNORECASE | re.MULTILINE
34
+
35
+ tokens = {
36
+ 'root': [
37
+ (r'\s+', Whitespace),
38
+ # All comment types
39
+ (r'\\.*?$', Comment.Single),
40
+ (r'\([\s].*?\)', Comment.Single),
41
+ # defining words. The next word is a new command name
42
+ (r'(:|variable|constant|value|buffer:)(\s+)',
43
+ bygroups(Keyword.Namespace, Whitespace), 'worddef'),
44
+ # strings are rather simple
45
+ (r'([.sc]")(\s+?)', bygroups(String, Whitespace), 'stringdef'),
46
+ # keywords from the various wordsets
47
+ # *** Wordset BLOCK
48
+ (r'(blk|block|buffer|evaluate|flush|load|save-buffers|update|'
49
+ # *** Wordset BLOCK-EXT
50
+ r'empty-buffers|list|refill|scr|thru|'
51
+ # *** Wordset CORE
52
+ r'\#s|\*\/mod|\+loop|\/mod|0<|0=|1\+|1-|2!|'
53
+ r'2\*|2\/|2@|2drop|2dup|2over|2swap|>body|'
54
+ r'>in|>number|>r|\?dup|abort|abort\"|abs|'
55
+ r'accept|align|aligned|allot|and|base|begin|'
56
+ r'bl|c!|c,|c@|cell\+|cells|char|char\+|'
57
+ r'chars|constant|count|cr|create|decimal|'
58
+ r'depth|do|does>|drop|dup|else|emit|environment\?|'
59
+ r'evaluate|execute|exit|fill|find|fm\/mod|'
60
+ r'here|hold|i|if|immediate|invert|j|key|'
61
+ r'leave|literal|loop|lshift|m\*|max|min|'
62
+ r'mod|move|negate|or|over|postpone|quit|'
63
+ r'r>|r@|recurse|repeat|rot|rshift|s\"|s>d|'
64
+ r'sign|sm\/rem|source|space|spaces|state|swap|'
65
+ r'then|type|u\.|u\<|um\*|um\/mod|unloop|until|'
66
+ r'variable|while|word|xor|\[char\]|\[\'\]|'
67
+ r'@|!|\#|<\#|\#>|:|;|\+|-|\*|\/|,|<|>|\|1\+|1-|\.|'
68
+ # *** Wordset CORE-EXT
69
+ r'\.r|0<>|'
70
+ r'0>|2>r|2r>|2r@|:noname|\?do|again|c\"|'
71
+ r'case|compile,|endcase|endof|erase|false|'
72
+ r'hex|marker|nip|of|pad|parse|pick|refill|'
73
+ r'restore-input|roll|save-input|source-id|to|'
74
+ r'true|tuck|u\.r|u>|unused|value|within|'
75
+ r'\[compile\]|'
76
+ # *** Wordset CORE-EXT-obsolescent
77
+ r'\#tib|convert|expect|query|span|'
78
+ r'tib|'
79
+ # *** Wordset DOUBLE
80
+ r'2constant|2literal|2variable|d\+|d-|'
81
+ r'd\.|d\.r|d0<|d0=|d2\*|d2\/|d<|d=|d>s|'
82
+ r'dabs|dmax|dmin|dnegate|m\*\/|m\+|'
83
+ # *** Wordset DOUBLE-EXT
84
+ r'2rot|du<|'
85
+ # *** Wordset EXCEPTION
86
+ r'catch|throw|'
87
+ # *** Wordset EXCEPTION-EXT
88
+ r'abort|abort\"|'
89
+ # *** Wordset FACILITY
90
+ r'at-xy|key\?|page|'
91
+ # *** Wordset FACILITY-EXT
92
+ r'ekey|ekey>char|ekey\?|emit\?|ms|time&date|'
93
+ # *** Wordset FILE
94
+ r'BIN|CLOSE-FILE|CREATE-FILE|DELETE-FILE|FILE-POSITION|'
95
+ r'FILE-SIZE|INCLUDE-FILE|INCLUDED|OPEN-FILE|R\/O|'
96
+ r'R\/W|READ-FILE|READ-LINE|REPOSITION-FILE|RESIZE-FILE|'
97
+ r'S\"|SOURCE-ID|W/O|WRITE-FILE|WRITE-LINE|'
98
+ # *** Wordset FILE-EXT
99
+ r'FILE-STATUS|FLUSH-FILE|REFILL|RENAME-FILE|'
100
+ # *** Wordset FLOAT
101
+ r'>float|d>f|'
102
+ r'f!|f\*|f\+|f-|f\/|f0<|f0=|f<|f>d|f@|'
103
+ r'falign|faligned|fconstant|fdepth|fdrop|fdup|'
104
+ r'fliteral|float\+|floats|floor|fmax|fmin|'
105
+ r'fnegate|fover|frot|fround|fswap|fvariable|'
106
+ r'represent|'
107
+ # *** Wordset FLOAT-EXT
108
+ r'df!|df@|dfalign|dfaligned|dfloat\+|'
109
+ r'dfloats|f\*\*|f\.|fabs|facos|facosh|falog|'
110
+ r'fasin|fasinh|fatan|fatan2|fatanh|fcos|fcosh|'
111
+ r'fe\.|fexp|fexpm1|fln|flnp1|flog|fs\.|fsin|'
112
+ r'fsincos|fsinh|fsqrt|ftan|ftanh|f~|precision|'
113
+ r'set-precision|sf!|sf@|sfalign|sfaligned|sfloat\+|'
114
+ r'sfloats|'
115
+ # *** Wordset LOCAL
116
+ r'\(local\)|to|'
117
+ # *** Wordset LOCAL-EXT
118
+ r'locals\||'
119
+ # *** Wordset MEMORY
120
+ r'allocate|free|resize|'
121
+ # *** Wordset SEARCH
122
+ r'definitions|find|forth-wordlist|get-current|'
123
+ r'get-order|search-wordlist|set-current|set-order|'
124
+ r'wordlist|'
125
+ # *** Wordset SEARCH-EXT
126
+ r'also|forth|only|order|previous|'
127
+ # *** Wordset STRING
128
+ r'-trailing|\/string|blank|cmove|cmove>|compare|'
129
+ r'search|sliteral|'
130
+ # *** Wordset TOOLS
131
+ r'.s|dump|see|words|'
132
+ # *** Wordset TOOLS-EXT
133
+ r';code|'
134
+ r'ahead|assembler|bye|code|cs-pick|cs-roll|'
135
+ r'editor|state|\[else\]|\[if\]|\[then\]|'
136
+ # *** Wordset TOOLS-EXT-obsolescent
137
+ r'forget|'
138
+ # Forth 2012
139
+ r'defer|defer@|defer!|action-of|begin-structure|field:|buffer:|'
140
+ r'parse-name|buffer:|traverse-wordlist|n>r|nr>|2value|fvalue|'
141
+ r'name>interpret|name>compile|name>string|'
142
+ r'cfield:|end-structure)(?!\S)', Keyword),
143
+
144
+ # Numbers
145
+ (r'(\$[0-9A-F]+)', Number.Hex),
146
+ (r'(\#|%|&|\-|\+)?[0-9]+', Number.Integer),
147
+ (r'(\#|%|&|\-|\+)?[0-9.]+', Keyword.Type),
148
+ # amforth specific
149
+ (r'(@i|!i|@e|!e|pause|noop|turnkey|sleep|'
150
+ r'itype|icompare|sp@|sp!|rp@|rp!|up@|up!|'
151
+ r'>a|a>|a@|a!|a@+|a@-|>b|b>|b@|b!|b@+|b@-|'
152
+ r'find-name|1ms|'
153
+ r'sp0|rp0|\(evaluate\)|int-trap|int!)(?!\S)',
154
+ Name.Constant),
155
+ # a proposal
156
+ (r'(do-recognizer|r:fail|recognizer:|get-recognizers|'
157
+ r'set-recognizers|r:float|r>comp|r>int|r>post|'
158
+ r'r:name|r:word|r:dnum|r:num|recognizer|forth-recognizer|'
159
+ r'rec:num|rec:float|rec:word)(?!\S)', Name.Decorator),
160
+ # defining words. The next word is a new command name
161
+ (r'(Evalue|Rvalue|Uvalue|Edefer|Rdefer|Udefer)(\s+)',
162
+ bygroups(Keyword.Namespace, Text), 'worddef'),
163
+
164
+ (r'\S+', Name.Function), # Anything else is executed
165
+
166
+ ],
167
+ 'worddef': [
168
+ (r'\S+', Name.Class, '#pop'),
169
+ ],
170
+ 'stringdef': [
171
+ (r'[^"]+', String, '#pop'),
172
+ ],
173
+ }
174
+
175
+ def analyse_text(text):
176
+ """Forth uses : COMMAND ; quite a lot in a single line, so we're trying
177
+ to find that."""
178
+ if re.search('\n:[^\n]+;\n', text):
179
+ return 0.3
shared/package-files/3f/3f38e62c706da46eb935fcc8dacbe8937e5ea5d114ccee32bee39de85b413c2b/_nested_tensor_strides_compositeexplicitautograd_dispatch.h 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 compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & _nested_tensor_strides_out(at::Tensor & out, const at::Tensor & self);
21
+ TORCH_API at::Tensor & _nested_tensor_strides_outf(const at::Tensor & self, at::Tensor & out);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
shared/package-files/3f/3f39e95c3c5008c8c2f055fabd7abca29072ab93d8d49125c796e5bba908b6d0/functional.h ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/cpu/vec/functional_base.h>
4
+ #include <ATen/cpu/vec/functional_bfloat16.h>
shared/package-files/3f/3f3c3ddcaf67201276f1ceba6be1959964a264e698c2d3990757ba3f4dda74e2/httplib.pyi ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mimetools
2
+ import ssl
3
+ from typing import Any, Dict, Optional, Protocol
4
+
5
+ class HTTPMessage(mimetools.Message):
6
+ def addcontinue(self, key: str, more: str) -> None: ...
7
+ dict: Dict[str, str]
8
+ def addheader(self, key: str, value: str) -> None: ...
9
+ unixfrom: str
10
+ headers: Any
11
+ status: str
12
+ seekable: bool
13
+ def readheaders(self) -> None: ...
14
+
15
+ class HTTPResponse:
16
+ fp: Any
17
+ debuglevel: Any
18
+ strict: Any
19
+ msg: Any
20
+ version: Any
21
+ status: Any
22
+ reason: Any
23
+ chunked: Any
24
+ chunk_left: Any
25
+ length: Any
26
+ will_close: Any
27
+ def __init__(
28
+ self, sock, debuglevel: int = ..., strict: int = ..., method: Optional[Any] = ..., buffering: bool = ...
29
+ ) -> None: ...
30
+ def begin(self): ...
31
+ def close(self): ...
32
+ def isclosed(self): ...
33
+ def read(self, amt: Optional[Any] = ...): ...
34
+ def fileno(self): ...
35
+ def getheader(self, name, default: Optional[Any] = ...): ...
36
+ def getheaders(self): ...
37
+
38
+ # This is an API stub only for HTTPConnection and HTTPSConnection, as used in
39
+ # urllib2.AbstractHTTPHandler.do_open, which takes either the class
40
+ # HTTPConnection or the class HTTPSConnection, *not* an instance of either
41
+ # class. do_open does not use all of the parameters of HTTPConnection.__init__
42
+ # or HTTPSConnection.__init__, so HTTPConnectionProtocol only implements the
43
+ # parameters that do_open does use.
44
+ class HTTPConnectionProtocol(Protocol):
45
+ def __call__(self, host: str, timeout: int = ..., **http_con_args: Any) -> HTTPConnection: ...
46
+
47
+ class HTTPConnection:
48
+ response_class: Any
49
+ default_port: Any
50
+ auto_open: Any
51
+ debuglevel: Any
52
+ strict: Any
53
+ timeout: Any
54
+ source_address: Any
55
+ sock: Any
56
+ host: str = ...
57
+ port: int = ...
58
+ def __init__(
59
+ self, host, port: Optional[Any] = ..., strict: Optional[Any] = ..., timeout=..., source_address: Optional[Any] = ...
60
+ ) -> None: ...
61
+ def set_tunnel(self, host, port: Optional[Any] = ..., headers: Optional[Any] = ...): ...
62
+ def set_debuglevel(self, level): ...
63
+ def connect(self): ...
64
+ def close(self): ...
65
+ def send(self, data): ...
66
+ def putrequest(self, method, url, skip_host: int = ..., skip_accept_encoding: int = ...): ...
67
+ def putheader(self, header, *values): ...
68
+ def endheaders(self, message_body: Optional[Any] = ...): ...
69
+ def request(self, method, url, body: Optional[Any] = ..., headers=...): ...
70
+ def getresponse(self, buffering: bool = ...): ...
71
+
72
+ class HTTP:
73
+ debuglevel: Any
74
+ def __init__(self, host: str = ..., port: Optional[Any] = ..., strict: Optional[Any] = ...) -> None: ...
75
+ def connect(self, host: Optional[Any] = ..., port: Optional[Any] = ...): ...
76
+ def getfile(self): ...
77
+ file: Any
78
+ headers: Any
79
+ def getreply(self, buffering: bool = ...): ...
80
+ def close(self): ...
81
+
82
+ class HTTPSConnection(HTTPConnection):
83
+ default_port: Any
84
+ key_file: Any
85
+ cert_file: Any
86
+ def __init__(
87
+ self,
88
+ host,
89
+ port: Optional[Any] = ...,
90
+ key_file: Optional[Any] = ...,
91
+ cert_file: Optional[Any] = ...,
92
+ strict: Optional[Any] = ...,
93
+ timeout=...,
94
+ source_address: Optional[Any] = ...,
95
+ context: Optional[Any] = ...,
96
+ ) -> None: ...
97
+ sock: Any
98
+ def connect(self): ...
99
+
100
+ class HTTPS(HTTP):
101
+ key_file: Any
102
+ cert_file: Any
103
+ def __init__(
104
+ self,
105
+ host: str = ...,
106
+ port: Optional[Any] = ...,
107
+ key_file: Optional[Any] = ...,
108
+ cert_file: Optional[Any] = ...,
109
+ strict: Optional[Any] = ...,
110
+ context: Optional[Any] = ...,
111
+ ) -> None: ...
112
+
113
+ class HTTPException(Exception): ...
114
+ class NotConnected(HTTPException): ...
115
+ class InvalidURL(HTTPException): ...
116
+
117
+ class UnknownProtocol(HTTPException):
118
+ args: Any
119
+ version: Any
120
+ def __init__(self, version) -> None: ...
121
+
122
+ class UnknownTransferEncoding(HTTPException): ...
123
+ class UnimplementedFileMode(HTTPException): ...
124
+
125
+ class IncompleteRead(HTTPException):
126
+ args: Any
127
+ partial: Any
128
+ expected: Any
129
+ def __init__(self, partial, expected: Optional[Any] = ...) -> None: ...
130
+
131
+ class ImproperConnectionState(HTTPException): ...
132
+ class CannotSendRequest(ImproperConnectionState): ...
133
+ class CannotSendHeader(ImproperConnectionState): ...
134
+ class ResponseNotReady(ImproperConnectionState): ...
135
+
136
+ class BadStatusLine(HTTPException):
137
+ args: Any
138
+ line: Any
139
+ def __init__(self, line) -> None: ...
140
+
141
+ class LineTooLong(HTTPException):
142
+ def __init__(self, line_type) -> None: ...
143
+
144
+ error: Any
145
+
146
+ class LineAndFileWrapper:
147
+ def __init__(self, line, file) -> None: ...
148
+ def __getattr__(self, attr): ...
149
+ def read(self, amt: Optional[Any] = ...): ...
150
+ def readline(self): ...
151
+ def readlines(self, size: Optional[Any] = ...): ...
152
+
153
+ # Constants
154
+
155
+ responses: Dict[int, str]
156
+
157
+ HTTP_PORT: int
158
+ HTTPS_PORT: int
159
+
160
+ # status codes
161
+ # informational
162
+ CONTINUE: int
163
+ SWITCHING_PROTOCOLS: int
164
+ PROCESSING: int
165
+
166
+ # successful
167
+ OK: int
168
+ CREATED: int
169
+ ACCEPTED: int
170
+ NON_AUTHORITATIVE_INFORMATION: int
171
+ NO_CONTENT: int
172
+ RESET_CONTENT: int
173
+ PARTIAL_CONTENT: int
174
+ MULTI_STATUS: int
175
+ IM_USED: int
176
+
177
+ # redirection
178
+ MULTIPLE_CHOICES: int
179
+ MOVED_PERMANENTLY: int
180
+ FOUND: int
181
+ SEE_OTHER: int
182
+ NOT_MODIFIED: int
183
+ USE_PROXY: int
184
+ TEMPORARY_REDIRECT: int
185
+
186
+ # client error
187
+ BAD_REQUEST: int
188
+ UNAUTHORIZED: int
189
+ PAYMENT_REQUIRED: int
190
+ FORBIDDEN: int
191
+ NOT_FOUND: int
192
+ METHOD_NOT_ALLOWED: int
193
+ NOT_ACCEPTABLE: int
194
+ PROXY_AUTHENTICATION_REQUIRED: int
195
+ REQUEST_TIMEOUT: int
196
+ CONFLICT: int
197
+ GONE: int
198
+ LENGTH_REQUIRED: int
199
+ PRECONDITION_FAILED: int
200
+ REQUEST_ENTITY_TOO_LARGE: int
201
+ REQUEST_URI_TOO_LONG: int
202
+ UNSUPPORTED_MEDIA_TYPE: int
203
+ REQUESTED_RANGE_NOT_SATISFIABLE: int
204
+ EXPECTATION_FAILED: int
205
+ UNPROCESSABLE_ENTITY: int
206
+ LOCKED: int
207
+ FAILED_DEPENDENCY: int
208
+ UPGRADE_REQUIRED: int
209
+
210
+ # server error
211
+ INTERNAL_SERVER_ERROR: int
212
+ NOT_IMPLEMENTED: int
213
+ BAD_GATEWAY: int
214
+ SERVICE_UNAVAILABLE: int
215
+ GATEWAY_TIMEOUT: int
216
+ HTTP_VERSION_NOT_SUPPORTED: int
217
+ INSUFFICIENT_STORAGE: int
218
+ NOT_EXTENDED: int
shared/package-files/3f/3f3d54d1819fbf94f2d77d432b9a777d8d0d9e91dfe745dd072406479a291f69/oshorts.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 57 consecutive daily overshorts from an underground gasoline tank at a filling
3
+ station in Colorado
4
+
5
+ Dataset described in [1]_ and included as a part of the ITSM2000 software [2]_.
6
+ Downloaded on April 22, 2019 from:
7
+ http://www.springer.com/cda/content/document/cda_downloaddocument/ITSM2000.zip
8
+
9
+ References
10
+ ----------
11
+ .. [1] Brockwell, Peter J., and Richard A. Davis. 2016.
12
+ Introduction to Time Series and Forecasting. Springer.
13
+ .. [2] Brockwell, Peter J., and Richard A. Davis. n.d. ITSM2000.
14
+ """
15
+
16
+ import pandas as pd
17
+
18
+ oshorts = pd.Series([
19
+ 78, -58, 53, -65, 13, -6, -16, -14, 3, -72, 89, -48, -14, 32, 56, -86,
20
+ -66, 50, 26, 59, -47, -83, 2, -1, 124, -106, 113, -76, -47, -32, 39,
21
+ -30, 6, -73, 18, 2, -24, 23, -38, 91, -56, -58, 1, 14, -4, 77, -127, 97,
22
+ 10, -28, -17, 23, -2, 48, -131, 65, -17])
shared/package-files/3f/3f3e14914d6ac7be766ed26d7853b2ac95507f7522634274525c681842344ecd/luarocks.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2014 Anaconda, Inc
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+ """
4
+ Tools for converting luarocks packages to conda recipes.
5
+ """
6
+
7
+ # TODO:
8
+ # - mingw32 support (really any windows support, completely untested)
9
+ # - replace manual "luajit -e require 'blah'" with built-in entry-point testing
10
+
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import tempfile
15
+ from glob import glob
16
+ from sys import platform as _platform
17
+
18
+ INDENT = "\n - "
19
+
20
+ rockspec_parser = """
21
+ local ok,cjson = pcall(require, "cjson")
22
+ if not ok then
23
+ print("ERROR: lua-cjson not installed. Use conda to install luarocks, "
24
+ "then run 'luarocks install lua-cjson'.")
25
+ os.exit()
26
+ end
27
+
28
+ local rockspecFile = "%s"
29
+ local origPackage = package
30
+ local ok, _ = pcall(dofile, rockspecFile)
31
+ if not ok then
32
+ print("ERROR: could not load rockspecFile " .. tostring(rockspecFile))
33
+ os.exit()
34
+ end
35
+
36
+ -- Resolve name clash
37
+ if origPackage == package then
38
+ package = nil
39
+ end
40
+ local out = {
41
+ rockspec_format=rockspec_format,
42
+ package=package,
43
+ version=version,
44
+ description=description,
45
+ supported_platforms=supported_platforms,
46
+ dependencies=dependencies,
47
+ external_dependencies=external_dependencies,
48
+ source=source,
49
+ build=build,
50
+ modules=modules,
51
+ }
52
+ print(cjson.encode(out))
53
+ """
54
+
55
+
56
+ LUAROCKS_META = """\
57
+ package:
58
+ name: {packagename}
59
+ version: "{version}"
60
+
61
+ source:
62
+ {usefile}fn: {filename}
63
+ {usefile}url: {url}
64
+ {usegit}git_url: {url}
65
+ {usegittag}git_tag: {gittag} # can also be a branch, but that is highly discouraged
66
+ {usegitrev}git_rev: {gitrev} # prefer tags over commits, commits over branches
67
+ {usemd5}md5:{md5}
68
+ # patches:
69
+ # List any patch files here
70
+ # - fix.patch
71
+
72
+ build:
73
+ {noarch_python_comment}noarch: generic
74
+ # Useful to leave this on by default, will allow relocating
75
+ # packages that have hard-coded paths in them
76
+ detect_binary_files_with_prefix: true
77
+ # If this is a new build for the same version, increment the build
78
+ # number. If you do not include this key, it defaults to 0.
79
+ # number: 1
80
+
81
+ requirements:
82
+ build:{build_depends}
83
+
84
+ run:{run_depends}
85
+
86
+ {test_comment}test:
87
+ {entry_comment}commands:
88
+ # You can put test commands to be run here. Use this to test that the
89
+ # entry points work.
90
+ {test_commands}
91
+
92
+ # You can also put a file called run_test.lua in the recipe that will be run
93
+ # at test time.
94
+
95
+ about:
96
+ {home_comment}home: {homeurl}
97
+ license: {license}
98
+ {summary_comment}summary: {summary}
99
+
100
+ # See
101
+ # https://docs.conda.io/projects/conda-build for
102
+ # more information about meta.yaml
103
+ """
104
+
105
+ LUAROCKS_BUILD_SH = """\
106
+ #!/bin/bash
107
+
108
+ set -o errexit -o pipefail
109
+
110
+ # Make sure luarocks can see all local dependencies
111
+ "${{PREFIX}}"/bin/luarocks-admin make_manifest --local-tree
112
+
113
+ # Install
114
+ # Rocks aren't located in a standard location, although
115
+ # they tend to be top-level or in a rocks/ directory.
116
+ # NOTE: we're just picking the first rock we find. If there's
117
+ # more than one, specify it manually.
118
+ ROCK=$(find . -name "*.rockspec" | sort -n -r | head -n 1)
119
+ "${{PREFIX}}"/bin/luarocks install "${{ROCK}}" --local-tree
120
+
121
+ # Add more build steps here, if they are necessary.
122
+
123
+ # See
124
+ # https://docs.conda.io/projects/conda-build
125
+ # for a list of environment variables that are set during the build process.
126
+ """
127
+
128
+ LUAROCKS_POSTLINK_SH = """\
129
+ # Let luarocks know that we've installed a new project
130
+ $PREFIX/bin/luarocks-admin make_manifest --local-tree
131
+ """
132
+
133
+ LUAROCKS_PREUNLINK_SH = """\
134
+ # Tell luarocks we've removed the project
135
+ $PREFIX/bin/luarocks remove {rockname}
136
+ """
137
+
138
+
139
+ def add_parser(repos):
140
+ luarocks = repos.add_parser(
141
+ "luarocks",
142
+ help="""
143
+ Create recipe skeleton for luarocks, hosted at luarocks.org
144
+ """,
145
+ )
146
+ luarocks.add_argument(
147
+ "packages",
148
+ nargs="+",
149
+ help="luarocks packages to create recipe skeletons for.",
150
+ )
151
+ luarocks.add_argument(
152
+ "--output-dir",
153
+ help="Directory to write recipes to (default: %(default)s).",
154
+ default=".",
155
+ )
156
+ luarocks.add_argument(
157
+ "--version",
158
+ help="Version to use. Applies to all packages.",
159
+ )
160
+ luarocks.add_argument(
161
+ "--recursive",
162
+ action="store_true",
163
+ help="Create recipes for dependencies if they do not already exist.",
164
+ )
165
+
166
+
167
+ def package_exists(package_name):
168
+ return True
169
+ # TODO: no current Lua packages work for me. Need to verify this method.
170
+ # subprocess.check_call(['luarocks', 'search', package_name])
171
+
172
+
173
+ def getval(spec, k):
174
+ if k not in spec:
175
+ raise Exception("Required key %s not in spec" % k)
176
+ else:
177
+ return spec[k]
178
+
179
+
180
+ def warn_against_branches(branch):
181
+ print("")
182
+ print("=========================================")
183
+ print("")
184
+ print("WARNING:")
185
+ print("Building a rock referenced to branch %s." % branch)
186
+ print("This is not a tag. This is dangerous, because rebuilding")
187
+ print("at a later date may produce a different package.")
188
+ print("Please replace with a tag, git commit, or tarball.")
189
+ print("")
190
+ print("=========================================")
191
+
192
+
193
+ def format_dep(dep):
194
+ name_without_ver = "".join([c for c in dep if c.isalpha()])
195
+ if name_without_ver not in ["lua"]:
196
+ # Enforce conda naming convention.
197
+ # lower case, no white-space, and prepended "lua-"
198
+ # (all languages other than Python prepend their language to package names)
199
+ if dep[:4] != "lua-":
200
+ dep = "lua-" + dep
201
+ dep = dep.replace(" ", "").lower()
202
+
203
+ # Ensure a space between the first special-character that specifies version logic
204
+ # Not "-", because that's used in e.g. lua-penlight
205
+ special_char_test = [c in "<>=~" for c in dep]
206
+ for i, v in enumerate(special_char_test):
207
+ if v:
208
+ split_dep = [c for c in dep]
209
+ split_dep.insert(i, " ")
210
+ dep = "".join(split_dep)
211
+ break
212
+ return dep
213
+
214
+
215
+ def ensure_base_deps(deps):
216
+ basenames = ["".join([c for c in dep if c.isalpha()]) for dep in deps]
217
+ extra_deps = []
218
+ if "lua" not in basenames:
219
+ extra_deps.append("lua")
220
+ if "luarocks" not in basenames:
221
+ extra_deps.append("luarocks")
222
+ if len(extra_deps):
223
+ deps = extra_deps + deps
224
+ return deps
225
+
226
+
227
+ def skeletonize(packages, output_dir=".", version=None, recursive=False):
228
+ # Check that we have Lua installed (any version)
229
+
230
+ # Check that we have luarocks installed
231
+
232
+ # Check that we have lua-cjson installed
233
+
234
+ # Get the platform
235
+ platform = "linux" if _platform == "linux2" else _platform
236
+
237
+ # Make temporary directory
238
+ cwd = os.getcwd()
239
+ temp_dir = tempfile.mkdtemp()
240
+ package_dicts = {}
241
+
242
+ # Step into it
243
+ os.chdir(temp_dir)
244
+
245
+ while packages:
246
+ package = packages.pop()
247
+
248
+ packagename = (
249
+ "lua-%s" % package.lower() if package[:4] != "lua-" else package.lower()
250
+ )
251
+ d = package_dicts.setdefault(
252
+ package,
253
+ {
254
+ "packagename": packagename,
255
+ "version": "0.0",
256
+ "filename": "",
257
+ "url": "",
258
+ "md5": "",
259
+ "usemd5": "# ",
260
+ "usefile": "# ",
261
+ "usegit": "# ",
262
+ "usegittag": "# ",
263
+ "usegitrev": "# ",
264
+ "gittag": "",
265
+ "gitrev": "",
266
+ "noarch_python_comment": "# ",
267
+ "build_depends": "",
268
+ "run_depends": "",
269
+ "test_comment": "",
270
+ "entry_comment": "",
271
+ "test_commands": "",
272
+ "home_comment": "# ",
273
+ "homeurl": "",
274
+ "license": "Unknown",
275
+ "summary_comment": "# ",
276
+ "summary": "",
277
+ },
278
+ )
279
+
280
+ # Download rockspec
281
+ o = subprocess.call(["luarocks", "download", package, "--rockspec"])
282
+ if o != 0:
283
+ raise Exception(f"Could not download rockspec for {package}")
284
+
285
+ # Find the downloaded rockspec
286
+ fs = glob(package + "*.rockspec")
287
+ if len(fs) != 1:
288
+ raise Exception("Failed to download rockspec")
289
+ d["rockspec_file"] = fs[0]
290
+
291
+ # Parse the rockspec into a dictionary
292
+ p = subprocess.Popen(
293
+ ["lua", "-e", rockspec_parser % d["rockspec_file"]], stdout=subprocess.PIPE
294
+ )
295
+ out, err = p.communicate()
296
+ if "ERROR" in out:
297
+ raise Exception(out.replace("ERROR: ", ""))
298
+ spec = json.loads(out)
299
+
300
+ # Gather the basic details
301
+ d["rockname"] = getval(spec, "package")
302
+ d["version"] = getval(spec, "version")
303
+ d["version"] = "".join([c for c in d["version"] if c.isalnum()])
304
+ source = getval(spec, "source")
305
+
306
+ # Figure out how to download the package, and from where
307
+ d["url"] = getval(source, "url")
308
+ ext = os.path.splitext(d["url"])[-1]
309
+ if ext in [".zip", ".tar", ".tar.bz2", ".tar.xz", ".tar.gz"]:
310
+ d["usefile"] = ""
311
+ d["filename"] = os.path.split(d["url"])[-1]
312
+ if "md5" in source:
313
+ md5 = getval(source, "md5")
314
+ if len(md5):
315
+ d["md5"] = md5
316
+ d["usemd5"] = ""
317
+ elif ext in [".git"] or d["url"][:4] == "git:":
318
+ d["usegit"] = ""
319
+ # Check if we're using a tag or a commit
320
+ if "tag" in source:
321
+ d["usegittag"] = ""
322
+ d["gittag"] = getval(source, "tag")
323
+ elif "branch" in source:
324
+ d["usegittag"] = ""
325
+ d["gittag"] = getval(source, "branch")
326
+ warn_against_branches(d["gittag"])
327
+ else:
328
+ d["usegittag"] = ""
329
+ d["gittag"] = "master"
330
+ warn_against_branches(d["gittag"])
331
+
332
+ # Gather the description
333
+ if "description" in spec:
334
+ desc = getval(spec, "description")
335
+ if "homepage" in desc:
336
+ d["homeurl"] = desc["homepage"]
337
+ d["home_comment"] = ""
338
+ if "summary" in desc:
339
+ d["summary"] = desc["summary"]
340
+ d["summary_comment"] = ""
341
+ if "license" in desc:
342
+ d["license"] = desc["license"]
343
+
344
+ # Gather the dependencies
345
+ if "dependencies" in spec:
346
+ deps = getval(spec, "dependencies")
347
+ if len(deps):
348
+ deps = ensure_base_deps([format_dep(dep) for dep in deps])
349
+ d["build_depends"] = INDENT.join([""] + deps)
350
+ d["run_depends"] = d["build_depends"]
351
+
352
+ # Build some entry-point tests.
353
+ if "build" in spec:
354
+ if platform == "darwin":
355
+ our_plat = "macosx"
356
+ elif platform == "linux":
357
+ our_plat = "unix"
358
+
359
+ modules = None
360
+ if "modules" in spec["build"]:
361
+ modules = spec["build"]["modules"]
362
+ elif "platforms" in spec["build"]:
363
+ if our_plat in spec["build"]["platforms"]:
364
+ if "modules" in spec["build"]["platforms"][our_plat]:
365
+ modules = spec["build"]["platforms"][our_plat]["modules"]
366
+ if modules:
367
+ d["test_commands"] = INDENT.join(
368
+ [""] + ["""lua -e "require '%s'\"""" % r for r in modules.keys()]
369
+ )
370
+
371
+ # If we didn't find any modules to import, import the base name
372
+ if d["test_commands"] == "":
373
+ d["test_commands"] = INDENT.join(
374
+ [""] + ["""lua -e "require '%s'" """ % d["rockname"]]
375
+ )
376
+
377
+ # Build the luarocks skeleton
378
+ os.chdir(cwd)
379
+ for package in package_dicts:
380
+ d = package_dicts[package]
381
+ name = d["packagename"]
382
+ os.makedirs(os.path.join(output_dir, name))
383
+ print(
384
+ f"Writing recipe for {package.lower()} to {os.path.join(output_dir, name)}"
385
+ )
386
+ with open(os.path.join(output_dir, name, "meta.yaml"), "w") as f:
387
+ f.write(LUAROCKS_META.format(**d))
388
+ with open(os.path.join(output_dir, name, "build.sh"), "w") as f:
389
+ f.write(LUAROCKS_BUILD_SH.format(**d))
390
+ with open(os.path.join(output_dir, name, "post-link.sh"), "w") as f:
391
+ f.write(LUAROCKS_POSTLINK_SH)
392
+ with open(os.path.join(output_dir, name, "pre-unlink.sh"), "w") as f:
393
+ f.write(LUAROCKS_PREUNLINK_SH.format(**d))
shared/package-files/3f/3f3f193da2c9794d59bf040f0d0a9d350ecac123caea0d008628ea3ec8acbbb1/linalg_qr_ops.h 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 linalg_qr {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor> (const at::Tensor &, c10::string_view);
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::linalg_qr")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_qr(Tensor A, str mode='reduced') -> (Tensor Q, Tensor R)")
24
+ static ::std::tuple<at::Tensor,at::Tensor> call(const at::Tensor & A, c10::string_view mode);
25
+ static ::std::tuple<at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, c10::string_view mode);
26
+ };
27
+
28
+ struct TORCH_API linalg_qr_out {
29
+ using schema = ::std::tuple<at::Tensor &,at::Tensor &> (const at::Tensor &, c10::string_view, 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::linalg_qr")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "linalg_qr.out(Tensor A, str mode='reduced', *, Tensor(a!) Q, Tensor(b!) R) -> (Tensor(a!) Q, Tensor(b!) R)")
35
+ static ::std::tuple<at::Tensor &,at::Tensor &> call(const at::Tensor & A, c10::string_view mode, at::Tensor & Q, at::Tensor & R);
36
+ static ::std::tuple<at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & A, c10::string_view mode, at::Tensor & Q, at::Tensor & R);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/3f/3f3feab50db45dcee100212f6e4da83500c4298c1b836f5ab79e1b85c017861e/_foreach_sinh_ops.h 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 _foreach_sinh {
18
+ using schema = ::std::vector<at::Tensor> (at::TensorList);
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::_foreach_sinh")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_sinh(Tensor[] self) -> Tensor[]")
24
+ static ::std::vector<at::Tensor> call(at::TensorList self);
25
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
26
+ };
27
+
28
+ struct TORCH_API _foreach_sinh_ {
29
+ using schema = void (at::TensorList);
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::_foreach_sinh_")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_sinh_(Tensor(a!)[] self) -> ()")
35
+ static void call(at::TensorList self);
36
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self);
37
+ };
38
+
39
+ struct TORCH_API _foreach_sinh_out {
40
+ using schema = void (at::TensorList, at::TensorList);
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::_foreach_sinh")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_foreach_sinh.out(Tensor[] self, *, Tensor(a!)[] out) -> ()")
46
+ static void call(at::TensorList self, at::TensorList out);
47
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, at::TensorList self, at::TensorList out);
48
+ };
49
+
50
+ }} // namespace at::_ops
shared/package-files/3f/3f42eca19e398012fb7242f896a42deed75bac70f8c6555885f7e684779e4ff5/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ joblib
shared/package-files/3f/3f4337f6250bb1b9aed7b73d2be62f57f79998d119726f0579a06559f76432b3/special_ndtri_native.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #include <ATen/ops/special_ndtri_meta.h>
16
+
17
+ namespace at {
18
+ namespace native {
19
+ struct TORCH_API structured_special_ndtri_out : public at::meta::structured_special_ndtri {
20
+ void impl(const at::Tensor & self, const at::Tensor & out);
21
+ };
22
+ } // namespace native
23
+ } // namespace at
shared/package-files/3f/3f4bf12367dc9ddca6d545354b7ed703343342793263b62a00a9b19b6e3f82e8/_win32_console.py ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Light wrapper around the Win32 Console API - this module should only be imported on Windows
2
+
3
+ The API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions
4
+ """
5
+ import ctypes
6
+ import sys
7
+ from typing import Any
8
+
9
+ windll: Any = None
10
+ if sys.platform == "win32":
11
+ windll = ctypes.LibraryLoader(ctypes.WinDLL)
12
+ else:
13
+ raise ImportError(f"{__name__} can only be imported on Windows")
14
+
15
+ import time
16
+ from ctypes import Structure, byref, wintypes
17
+ from typing import IO, NamedTuple, Type, cast
18
+
19
+ from pip._vendor.rich.color import ColorSystem
20
+ from pip._vendor.rich.style import Style
21
+
22
+ STDOUT = -11
23
+ ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
24
+
25
+ COORD = wintypes._COORD
26
+
27
+
28
+ class LegacyWindowsError(Exception):
29
+ pass
30
+
31
+
32
+ class WindowsCoordinates(NamedTuple):
33
+ """Coordinates in the Windows Console API are (y, x), not (x, y).
34
+ This class is intended to prevent that confusion.
35
+ Rows and columns are indexed from 0.
36
+ This class can be used in place of wintypes._COORD in arguments and argtypes.
37
+ """
38
+
39
+ row: int
40
+ col: int
41
+
42
+ @classmethod
43
+ def from_param(cls, value: "WindowsCoordinates") -> COORD:
44
+ """Converts a WindowsCoordinates into a wintypes _COORD structure.
45
+ This classmethod is internally called by ctypes to perform the conversion.
46
+
47
+ Args:
48
+ value (WindowsCoordinates): The input coordinates to convert.
49
+
50
+ Returns:
51
+ wintypes._COORD: The converted coordinates struct.
52
+ """
53
+ return COORD(value.col, value.row)
54
+
55
+
56
+ class CONSOLE_SCREEN_BUFFER_INFO(Structure):
57
+ _fields_ = [
58
+ ("dwSize", COORD),
59
+ ("dwCursorPosition", COORD),
60
+ ("wAttributes", wintypes.WORD),
61
+ ("srWindow", wintypes.SMALL_RECT),
62
+ ("dwMaximumWindowSize", COORD),
63
+ ]
64
+
65
+
66
+ class CONSOLE_CURSOR_INFO(ctypes.Structure):
67
+ _fields_ = [("dwSize", wintypes.DWORD), ("bVisible", wintypes.BOOL)]
68
+
69
+
70
+ _GetStdHandle = windll.kernel32.GetStdHandle
71
+ _GetStdHandle.argtypes = [
72
+ wintypes.DWORD,
73
+ ]
74
+ _GetStdHandle.restype = wintypes.HANDLE
75
+
76
+
77
+ def GetStdHandle(handle: int = STDOUT) -> wintypes.HANDLE:
78
+ """Retrieves a handle to the specified standard device (standard input, standard output, or standard error).
79
+
80
+ Args:
81
+ handle (int): Integer identifier for the handle. Defaults to -11 (stdout).
82
+
83
+ Returns:
84
+ wintypes.HANDLE: The handle
85
+ """
86
+ return cast(wintypes.HANDLE, _GetStdHandle(handle))
87
+
88
+
89
+ _GetConsoleMode = windll.kernel32.GetConsoleMode
90
+ _GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD]
91
+ _GetConsoleMode.restype = wintypes.BOOL
92
+
93
+
94
+ def GetConsoleMode(std_handle: wintypes.HANDLE) -> int:
95
+ """Retrieves the current input mode of a console's input buffer
96
+ or the current output mode of a console screen buffer.
97
+
98
+ Args:
99
+ std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.
100
+
101
+ Raises:
102
+ LegacyWindowsError: If any error occurs while calling the Windows console API.
103
+
104
+ Returns:
105
+ int: Value representing the current console mode as documented at
106
+ https://docs.microsoft.com/en-us/windows/console/getconsolemode#parameters
107
+ """
108
+
109
+ console_mode = wintypes.DWORD()
110
+ success = bool(_GetConsoleMode(std_handle, console_mode))
111
+ if not success:
112
+ raise LegacyWindowsError("Unable to get legacy Windows Console Mode")
113
+ return console_mode.value
114
+
115
+
116
+ _FillConsoleOutputCharacterW = windll.kernel32.FillConsoleOutputCharacterW
117
+ _FillConsoleOutputCharacterW.argtypes = [
118
+ wintypes.HANDLE,
119
+ ctypes.c_char,
120
+ wintypes.DWORD,
121
+ cast(Type[COORD], WindowsCoordinates),
122
+ ctypes.POINTER(wintypes.DWORD),
123
+ ]
124
+ _FillConsoleOutputCharacterW.restype = wintypes.BOOL
125
+
126
+
127
+ def FillConsoleOutputCharacter(
128
+ std_handle: wintypes.HANDLE,
129
+ char: str,
130
+ length: int,
131
+ start: WindowsCoordinates,
132
+ ) -> int:
133
+ """Writes a character to the console screen buffer a specified number of times, beginning at the specified coordinates.
134
+
135
+ Args:
136
+ std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.
137
+ char (str): The character to write. Must be a string of length 1.
138
+ length (int): The number of times to write the character.
139
+ start (WindowsCoordinates): The coordinates to start writing at.
140
+
141
+ Returns:
142
+ int: The number of characters written.
143
+ """
144
+ character = ctypes.c_char(char.encode())
145
+ num_characters = wintypes.DWORD(length)
146
+ num_written = wintypes.DWORD(0)
147
+ _FillConsoleOutputCharacterW(
148
+ std_handle,
149
+ character,
150
+ num_characters,
151
+ start,
152
+ byref(num_written),
153
+ )
154
+ return num_written.value
155
+
156
+
157
+ _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
158
+ _FillConsoleOutputAttribute.argtypes = [
159
+ wintypes.HANDLE,
160
+ wintypes.WORD,
161
+ wintypes.DWORD,
162
+ cast(Type[COORD], WindowsCoordinates),
163
+ ctypes.POINTER(wintypes.DWORD),
164
+ ]
165
+ _FillConsoleOutputAttribute.restype = wintypes.BOOL
166
+
167
+
168
+ def FillConsoleOutputAttribute(
169
+ std_handle: wintypes.HANDLE,
170
+ attributes: int,
171
+ length: int,
172
+ start: WindowsCoordinates,
173
+ ) -> int:
174
+ """Sets the character attributes for a specified number of character cells,
175
+ beginning at the specified coordinates in a screen buffer.
176
+
177
+ Args:
178
+ std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.
179
+ attributes (int): Integer value representing the foreground and background colours of the cells.
180
+ length (int): The number of cells to set the output attribute of.
181
+ start (WindowsCoordinates): The coordinates of the first cell whose attributes are to be set.
182
+
183
+ Returns:
184
+ int: The number of cells whose attributes were actually set.
185
+ """
186
+ num_cells = wintypes.DWORD(length)
187
+ style_attrs = wintypes.WORD(attributes)
188
+ num_written = wintypes.DWORD(0)
189
+ _FillConsoleOutputAttribute(
190
+ std_handle, style_attrs, num_cells, start, byref(num_written)
191
+ )
192
+ return num_written.value
193
+
194
+
195
+ _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
196
+ _SetConsoleTextAttribute.argtypes = [
197
+ wintypes.HANDLE,
198
+ wintypes.WORD,
199
+ ]
200
+ _SetConsoleTextAttribute.restype = wintypes.BOOL
201
+
202
+
203
+ def SetConsoleTextAttribute(
204
+ std_handle: wintypes.HANDLE, attributes: wintypes.WORD
205
+ ) -> bool:
206
+ """Set the colour attributes for all text written after this function is called.
207
+
208
+ Args:
209
+ std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.
210
+ attributes (int): Integer value representing the foreground and background colours.
211
+
212
+
213
+ Returns:
214
+ bool: True if the attribute was set successfully, otherwise False.
215
+ """
216
+ return bool(_SetConsoleTextAttribute(std_handle, attributes))
217
+
218
+
219
+ _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
220
+ _GetConsoleScreenBufferInfo.argtypes = [
221
+ wintypes.HANDLE,
222
+ ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO),
223
+ ]
224
+ _GetConsoleScreenBufferInfo.restype = wintypes.BOOL
225
+
226
+
227
+ def GetConsoleScreenBufferInfo(
228
+ std_handle: wintypes.HANDLE,
229
+ ) -> CONSOLE_SCREEN_BUFFER_INFO:
230
+ """Retrieves information about the specified console screen buffer.
231
+
232
+ Args:
233
+ std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.
234
+
235
+ Returns:
236
+ CONSOLE_SCREEN_BUFFER_INFO: A CONSOLE_SCREEN_BUFFER_INFO ctype struct contain information about
237
+ screen size, cursor position, colour attributes, and more."""
238
+ console_screen_buffer_info = CONSOLE_SCREEN_BUFFER_INFO()
239
+ _GetConsoleScreenBufferInfo(std_handle, byref(console_screen_buffer_info))
240
+ return console_screen_buffer_info
241
+
242
+
243
+ _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
244
+ _SetConsoleCursorPosition.argtypes = [
245
+ wintypes.HANDLE,
246
+ cast(Type[COORD], WindowsCoordinates),
247
+ ]
248
+ _SetConsoleCursorPosition.restype = wintypes.BOOL
249
+
250
+
251
+ def SetConsoleCursorPosition(
252
+ std_handle: wintypes.HANDLE, coords: WindowsCoordinates
253
+ ) -> bool:
254
+ """Set the position of the cursor in the console screen
255
+
256
+ Args:
257
+ std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.
258
+ coords (WindowsCoordinates): The coordinates to move the cursor to.
259
+
260
+ Returns:
261
+ bool: True if the function succeeds, otherwise False.
262
+ """
263
+ return bool(_SetConsoleCursorPosition(std_handle, coords))
264
+
265
+
266
+ _GetConsoleCursorInfo = windll.kernel32.GetConsoleCursorInfo
267
+ _GetConsoleCursorInfo.argtypes = [
268
+ wintypes.HANDLE,
269
+ ctypes.POINTER(CONSOLE_CURSOR_INFO),
270
+ ]
271
+ _GetConsoleCursorInfo.restype = wintypes.BOOL
272
+
273
+
274
+ def GetConsoleCursorInfo(
275
+ std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO
276
+ ) -> bool:
277
+ """Get the cursor info - used to get cursor visibility and width
278
+
279
+ Args:
280
+ std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.
281
+ cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct that receives information
282
+ about the console's cursor.
283
+
284
+ Returns:
285
+ bool: True if the function succeeds, otherwise False.
286
+ """
287
+ return bool(_GetConsoleCursorInfo(std_handle, byref(cursor_info)))
288
+
289
+
290
+ _SetConsoleCursorInfo = windll.kernel32.SetConsoleCursorInfo
291
+ _SetConsoleCursorInfo.argtypes = [
292
+ wintypes.HANDLE,
293
+ ctypes.POINTER(CONSOLE_CURSOR_INFO),
294
+ ]
295
+ _SetConsoleCursorInfo.restype = wintypes.BOOL
296
+
297
+
298
+ def SetConsoleCursorInfo(
299
+ std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO
300
+ ) -> bool:
301
+ """Set the cursor info - used for adjusting cursor visibility and width
302
+
303
+ Args:
304
+ std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.
305
+ cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct containing the new cursor info.
306
+
307
+ Returns:
308
+ bool: True if the function succeeds, otherwise False.
309
+ """
310
+ return bool(_SetConsoleCursorInfo(std_handle, byref(cursor_info)))
311
+
312
+
313
+ _SetConsoleTitle = windll.kernel32.SetConsoleTitleW
314
+ _SetConsoleTitle.argtypes = [wintypes.LPCWSTR]
315
+ _SetConsoleTitle.restype = wintypes.BOOL
316
+
317
+
318
+ def SetConsoleTitle(title: str) -> bool:
319
+ """Sets the title of the current console window
320
+
321
+ Args:
322
+ title (str): The new title of the console window.
323
+
324
+ Returns:
325
+ bool: True if the function succeeds, otherwise False.
326
+ """
327
+ return bool(_SetConsoleTitle(title))
328
+
329
+
330
+ class LegacyWindowsTerm:
331
+ """This class allows interaction with the legacy Windows Console API. It should only be used in the context
332
+ of environments where virtual terminal processing is not available. However, if it is used in a Windows environment,
333
+ the entire API should work.
334
+
335
+ Args:
336
+ file (IO[str]): The file which the Windows Console API HANDLE is retrieved from, defaults to sys.stdout.
337
+ """
338
+
339
+ BRIGHT_BIT = 8
340
+
341
+ # Indices are ANSI color numbers, values are the corresponding Windows Console API color numbers
342
+ ANSI_TO_WINDOWS = [
343
+ 0, # black The Windows colours are defined in wincon.h as follows:
344
+ 4, # red define FOREGROUND_BLUE 0x0001 -- 0000 0001
345
+ 2, # green define FOREGROUND_GREEN 0x0002 -- 0000 0010
346
+ 6, # yellow define FOREGROUND_RED 0x0004 -- 0000 0100
347
+ 1, # blue define FOREGROUND_INTENSITY 0x0008 -- 0000 1000
348
+ 5, # magenta define BACKGROUND_BLUE 0x0010 -- 0001 0000
349
+ 3, # cyan define BACKGROUND_GREEN 0x0020 -- 0010 0000
350
+ 7, # white define BACKGROUND_RED 0x0040 -- 0100 0000
351
+ 8, # bright black (grey) define BACKGROUND_INTENSITY 0x0080 -- 1000 0000
352
+ 12, # bright red
353
+ 10, # bright green
354
+ 14, # bright yellow
355
+ 9, # bright blue
356
+ 13, # bright magenta
357
+ 11, # bright cyan
358
+ 15, # bright white
359
+ ]
360
+
361
+ def __init__(self, file: "IO[str]") -> None:
362
+ handle = GetStdHandle(STDOUT)
363
+ self._handle = handle
364
+ default_text = GetConsoleScreenBufferInfo(handle).wAttributes
365
+ self._default_text = default_text
366
+
367
+ self._default_fore = default_text & 7
368
+ self._default_back = (default_text >> 4) & 7
369
+ self._default_attrs = self._default_fore | (self._default_back << 4)
370
+
371
+ self._file = file
372
+ self.write = file.write
373
+ self.flush = file.flush
374
+
375
+ @property
376
+ def cursor_position(self) -> WindowsCoordinates:
377
+ """Returns the current position of the cursor (0-based)
378
+
379
+ Returns:
380
+ WindowsCoordinates: The current cursor position.
381
+ """
382
+ coord: COORD = GetConsoleScreenBufferInfo(self._handle).dwCursorPosition
383
+ return WindowsCoordinates(row=cast(int, coord.Y), col=cast(int, coord.X))
384
+
385
+ @property
386
+ def screen_size(self) -> WindowsCoordinates:
387
+ """Returns the current size of the console screen buffer, in character columns and rows
388
+
389
+ Returns:
390
+ WindowsCoordinates: The width and height of the screen as WindowsCoordinates.
391
+ """
392
+ screen_size: COORD = GetConsoleScreenBufferInfo(self._handle).dwSize
393
+ return WindowsCoordinates(
394
+ row=cast(int, screen_size.Y), col=cast(int, screen_size.X)
395
+ )
396
+
397
+ def write_text(self, text: str) -> None:
398
+ """Write text directly to the terminal without any modification of styles
399
+
400
+ Args:
401
+ text (str): The text to write to the console
402
+ """
403
+ self.write(text)
404
+ self.flush()
405
+
406
+ def write_styled(self, text: str, style: Style) -> None:
407
+ """Write styled text to the terminal.
408
+
409
+ Args:
410
+ text (str): The text to write
411
+ style (Style): The style of the text
412
+ """
413
+ color = style.color
414
+ bgcolor = style.bgcolor
415
+ if style.reverse:
416
+ color, bgcolor = bgcolor, color
417
+
418
+ if color:
419
+ fore = color.downgrade(ColorSystem.WINDOWS).number
420
+ fore = fore if fore is not None else 7 # Default to ANSI 7: White
421
+ if style.bold:
422
+ fore = fore | self.BRIGHT_BIT
423
+ if style.dim:
424
+ fore = fore & ~self.BRIGHT_BIT
425
+ fore = self.ANSI_TO_WINDOWS[fore]
426
+ else:
427
+ fore = self._default_fore
428
+
429
+ if bgcolor:
430
+ back = bgcolor.downgrade(ColorSystem.WINDOWS).number
431
+ back = back if back is not None else 0 # Default to ANSI 0: Black
432
+ back = self.ANSI_TO_WINDOWS[back]
433
+ else:
434
+ back = self._default_back
435
+
436
+ assert fore is not None
437
+ assert back is not None
438
+
439
+ SetConsoleTextAttribute(
440
+ self._handle, attributes=ctypes.c_ushort(fore | (back << 4))
441
+ )
442
+ self.write_text(text)
443
+ SetConsoleTextAttribute(self._handle, attributes=self._default_text)
444
+
445
+ def move_cursor_to(self, new_position: WindowsCoordinates) -> None:
446
+ """Set the position of the cursor
447
+
448
+ Args:
449
+ new_position (WindowsCoordinates): The WindowsCoordinates representing the new position of the cursor.
450
+ """
451
+ if new_position.col < 0 or new_position.row < 0:
452
+ return
453
+ SetConsoleCursorPosition(self._handle, coords=new_position)
454
+
455
+ def erase_line(self) -> None:
456
+ """Erase all content on the line the cursor is currently located at"""
457
+ screen_size = self.screen_size
458
+ cursor_position = self.cursor_position
459
+ cells_to_erase = screen_size.col
460
+ start_coordinates = WindowsCoordinates(row=cursor_position.row, col=0)
461
+ FillConsoleOutputCharacter(
462
+ self._handle, " ", length=cells_to_erase, start=start_coordinates
463
+ )
464
+ FillConsoleOutputAttribute(
465
+ self._handle,
466
+ self._default_attrs,
467
+ length=cells_to_erase,
468
+ start=start_coordinates,
469
+ )
470
+
471
+ def erase_end_of_line(self) -> None:
472
+ """Erase all content from the cursor position to the end of that line"""
473
+ cursor_position = self.cursor_position
474
+ cells_to_erase = self.screen_size.col - cursor_position.col
475
+ FillConsoleOutputCharacter(
476
+ self._handle, " ", length=cells_to_erase, start=cursor_position
477
+ )
478
+ FillConsoleOutputAttribute(
479
+ self._handle,
480
+ self._default_attrs,
481
+ length=cells_to_erase,
482
+ start=cursor_position,
483
+ )
484
+
485
+ def erase_start_of_line(self) -> None:
486
+ """Erase all content from the cursor position to the start of that line"""
487
+ row, col = self.cursor_position
488
+ start = WindowsCoordinates(row, 0)
489
+ FillConsoleOutputCharacter(self._handle, " ", length=col, start=start)
490
+ FillConsoleOutputAttribute(
491
+ self._handle, self._default_attrs, length=col, start=start
492
+ )
493
+
494
+ def move_cursor_up(self) -> None:
495
+ """Move the cursor up a single cell"""
496
+ cursor_position = self.cursor_position
497
+ SetConsoleCursorPosition(
498
+ self._handle,
499
+ coords=WindowsCoordinates(
500
+ row=cursor_position.row - 1, col=cursor_position.col
501
+ ),
502
+ )
503
+
504
+ def move_cursor_down(self) -> None:
505
+ """Move the cursor down a single cell"""
506
+ cursor_position = self.cursor_position
507
+ SetConsoleCursorPosition(
508
+ self._handle,
509
+ coords=WindowsCoordinates(
510
+ row=cursor_position.row + 1,
511
+ col=cursor_position.col,
512
+ ),
513
+ )
514
+
515
+ def move_cursor_forward(self) -> None:
516
+ """Move the cursor forward a single cell. Wrap to the next line if required."""
517
+ row, col = self.cursor_position
518
+ if col == self.screen_size.col - 1:
519
+ row += 1
520
+ col = 0
521
+ else:
522
+ col += 1
523
+ SetConsoleCursorPosition(
524
+ self._handle, coords=WindowsCoordinates(row=row, col=col)
525
+ )
526
+
527
+ def move_cursor_to_column(self, column: int) -> None:
528
+ """Move cursor to the column specified by the zero-based column index, staying on the same row
529
+
530
+ Args:
531
+ column (int): The zero-based column index to move the cursor to.
532
+ """
533
+ row, _ = self.cursor_position
534
+ SetConsoleCursorPosition(self._handle, coords=WindowsCoordinates(row, column))
535
+
536
+ def move_cursor_backward(self) -> None:
537
+ """Move the cursor backward a single cell. Wrap to the previous line if required."""
538
+ row, col = self.cursor_position
539
+ if col == 0:
540
+ row -= 1
541
+ col = self.screen_size.col - 1
542
+ else:
543
+ col -= 1
544
+ SetConsoleCursorPosition(
545
+ self._handle, coords=WindowsCoordinates(row=row, col=col)
546
+ )
547
+
548
+ def hide_cursor(self) -> None:
549
+ """Hide the cursor"""
550
+ current_cursor_size = self._get_cursor_size()
551
+ invisible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=0)
552
+ SetConsoleCursorInfo(self._handle, cursor_info=invisible_cursor)
553
+
554
+ def show_cursor(self) -> None:
555
+ """Show the cursor"""
556
+ current_cursor_size = self._get_cursor_size()
557
+ visible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=1)
558
+ SetConsoleCursorInfo(self._handle, cursor_info=visible_cursor)
559
+
560
+ def set_title(self, title: str) -> None:
561
+ """Set the title of the terminal window
562
+
563
+ Args:
564
+ title (str): The new title of the console window
565
+ """
566
+ assert len(title) < 255, "Console title must be less than 255 characters"
567
+ SetConsoleTitle(title)
568
+
569
+ def _get_cursor_size(self) -> int:
570
+ """Get the percentage of the character cell that is filled by the cursor"""
571
+ cursor_info = CONSOLE_CURSOR_INFO()
572
+ GetConsoleCursorInfo(self._handle, cursor_info=cursor_info)
573
+ return int(cursor_info.dwSize)
574
+
575
+
576
+ if __name__ == "__main__":
577
+ handle = GetStdHandle()
578
+
579
+ from pip._vendor.rich.console import Console
580
+
581
+ console = Console()
582
+
583
+ term = LegacyWindowsTerm(sys.stdout)
584
+ term.set_title("Win32 Console Examples")
585
+
586
+ style = Style(color="black", bgcolor="red")
587
+
588
+ heading = Style.parse("black on green")
589
+
590
+ # Check colour output
591
+ console.rule("Checking colour output")
592
+ console.print("[on red]on red!")
593
+ console.print("[blue]blue!")
594
+ console.print("[yellow]yellow!")
595
+ console.print("[bold yellow]bold yellow!")
596
+ console.print("[bright_yellow]bright_yellow!")
597
+ console.print("[dim bright_yellow]dim bright_yellow!")
598
+ console.print("[italic cyan]italic cyan!")
599
+ console.print("[bold white on blue]bold white on blue!")
600
+ console.print("[reverse bold white on blue]reverse bold white on blue!")
601
+ console.print("[bold black on cyan]bold black on cyan!")
602
+ console.print("[black on green]black on green!")
603
+ console.print("[blue on green]blue on green!")
604
+ console.print("[white on black]white on black!")
605
+ console.print("[black on white]black on white!")
606
+ console.print("[#1BB152 on #DA812D]#1BB152 on #DA812D!")
607
+
608
+ # Check cursor movement
609
+ console.rule("Checking cursor movement")
610
+ console.print()
611
+ term.move_cursor_backward()
612
+ term.move_cursor_backward()
613
+ term.write_text("went back and wrapped to prev line")
614
+ time.sleep(1)
615
+ term.move_cursor_up()
616
+ term.write_text("we go up")
617
+ time.sleep(1)
618
+ term.move_cursor_down()
619
+ term.write_text("and down")
620
+ time.sleep(1)
621
+ term.move_cursor_up()
622
+ term.move_cursor_backward()
623
+ term.move_cursor_backward()
624
+ term.write_text("we went up and back 2")
625
+ time.sleep(1)
626
+ term.move_cursor_down()
627
+ term.move_cursor_backward()
628
+ term.move_cursor_backward()
629
+ term.write_text("we went down and back 2")
630
+ time.sleep(1)
631
+
632
+ # Check erasing of lines
633
+ term.hide_cursor()
634
+ console.print()
635
+ console.rule("Checking line erasing")
636
+ console.print("\n...Deleting to the start of the line...")
637
+ term.write_text("The red arrow shows the cursor location, and direction of erase")
638
+ time.sleep(1)
639
+ term.move_cursor_to_column(16)
640
+ term.write_styled("<", Style.parse("black on red"))
641
+ term.move_cursor_backward()
642
+ time.sleep(1)
643
+ term.erase_start_of_line()
644
+ time.sleep(1)
645
+
646
+ console.print("\n\n...And to the end of the line...")
647
+ term.write_text("The red arrow shows the cursor location, and direction of erase")
648
+ time.sleep(1)
649
+
650
+ term.move_cursor_to_column(16)
651
+ term.write_styled(">", Style.parse("black on red"))
652
+ time.sleep(1)
653
+ term.erase_end_of_line()
654
+ time.sleep(1)
655
+
656
+ console.print("\n\n...Now the whole line will be erased...")
657
+ term.write_styled("I'm going to disappear!", style=Style.parse("black on cyan"))
658
+ time.sleep(1)
659
+ term.erase_line()
660
+
661
+ term.show_cursor()
662
+ print("\n")
shared/package-files/3f/3f4fd44aa7e975b4761bab0889d600f0494cf3e58376eedfbadaca12099e9555/patch.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module implements the changes to conda's context class
2
+ # needed to deploy the additional anonmyous user data. It pulls
3
+ # the token management functions themselves from the api module.
4
+
5
+ import re
6
+ import sys
7
+
8
+ from conda.auxlib.decorators import memoizedproperty
9
+ from conda.base.context import Context, ParameterLoader, PrimitiveParameter, context
10
+
11
+ from .tokens import token_string
12
+ from .utils import _debug
13
+
14
+
15
+ def _new_user_agent(ctx):
16
+ result = ctx._old_user_agent
17
+ prefix = (
18
+ getattr(Context, "checked_prefix", None) or context.target_prefix or sys.prefix
19
+ )
20
+ try:
21
+ token = token_string(prefix, context.anaconda_anon_usage)
22
+ if token:
23
+ result += " " + token
24
+ except Exception: # pragma: nocover
25
+ pass
26
+ return result
27
+
28
+
29
+ def _new_check_prefix(prefix, json=False):
30
+ Context.checked_prefix = prefix
31
+ Context._old_check_prefix(prefix, json)
32
+
33
+
34
+ def _new_get_main_info_str(info_dict):
35
+ ua = info_dict["user_agent"]
36
+ if " aau/" in ua:
37
+ ua_redact = re.sub(r" ([a-z]/)([^ ]+)", r" \1.", ua)
38
+ info_dict["user_agent"] = ua_redact
39
+ return Context._old_get_main_info_str(info_dict)
40
+
41
+
42
+ def _patch_check_prefix():
43
+ if hasattr(Context, "_old_check_prefix"):
44
+ return
45
+ _debug("Applying anaconda_anon_usage cli.install patch")
46
+
47
+ from conda.cli import install as cli_install
48
+
49
+ Context._old_check_prefix = cli_install.check_prefix
50
+ cli_install.check_prefix = _new_check_prefix
51
+ context._aau_initialized = True
52
+
53
+
54
+ def _patch_conda_info():
55
+ if hasattr(Context, "_old_get_main_info_str"):
56
+ return
57
+ _debug("Applying anaconda_anon_usage conda info patch")
58
+
59
+ from conda.cli import main_info
60
+
61
+ Context._old_get_main_info_str = main_info.get_main_info_str
62
+ main_info.get_main_info_str = _new_get_main_info_str
63
+
64
+
65
+ def main(plugin=False):
66
+ if getattr(context, "_aau_initialized", None) is not None:
67
+ _debug("anaconda_anon_usage already active")
68
+ return False
69
+ _debug("Applying anaconda_anon_usage context patch")
70
+
71
+ # conda.base.context.Context.user_agent
72
+ # Adds the ident token to the user agent string
73
+ Context._old_user_agent = Context.user_agent
74
+ # Using a different name ensures that this is stored
75
+ # in the cache in a different place than the original
76
+ Context.user_agent = memoizedproperty(_new_user_agent)
77
+
78
+ # conda.base.context.Context
79
+ # Adds anaconda_anon_usage as a managed string config parameter
80
+ _param = ParameterLoader(PrimitiveParameter(True))
81
+ Context.anaconda_anon_usage = _param
82
+ Context.parameter_names += (_param._set_name("anaconda_anon_usage"),)
83
+
84
+ # conda.base.context.checked_prefix
85
+ # Saves the prefix used in a conda install command
86
+ Context.checked_prefix = None
87
+
88
+ # conda.base.context._aau_initialized
89
+ # This helps us determine if the patching is comlpete
90
+ context._aau_initialized = False
91
+
92
+ if plugin:
93
+ # The pre-command plugin avoids the circular import
94
+ # of conda.cli.install, so we can apply the patch now
95
+ _patch_conda_info()
96
+ _patch_check_prefix()
97
+ else:
98
+ # We need to delay further. Schedule the patch for the
99
+ # next time context.__init__ is called.
100
+ _debug("Deferring anaconda_anon_usage cli.install patch")
101
+ _old__init__ = context.__init__
102
+
103
+ def _new_init(*args, **kwargs):
104
+ _patch_conda_info()
105
+ _patch_check_prefix()
106
+ context.__init__ = _old__init__
107
+ _old__init__(*args, **kwargs)
108
+
109
+ context.__init__ = _new_init
110
+
111
+ return True
shared/package-files/3f/3f510f3d5da0e74593b7c51a5feea41684d9335c55aa8e92d87e8527a65dd5e7/filesave.pdf ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %PDF-1.4
2
+ %�� ��
3
+ 1 0 obj
4
+ << /Pages 2 0 R /Type /Catalog >>
5
+ endobj
6
+ 8 0 obj
7
+ << /ExtGState 4 0 R /Font 3 0 R /Pattern 5 0 R
8
+ /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] /Shading 6 0 R
9
+ /XObject 7 0 R >>
10
+ endobj
11
+ 10 0 obj
12
+ << /Annots [ ] /Contents 9 0 R
13
+ /Group << /CS /DeviceRGB /S /Transparency /Type /Group >>
14
+ /MediaBox [ 0 0 72 72 ] /Parent 2 0 R /Resources 8 0 R /Type /Page >>
15
+ endobj
16
+ 9 0 obj
17
+ << /Filter /FlateDecode /Length 11 0 R >>
18
+ stream
19
+ x�u�Kn1 D�:�N@���2A���
20
+
21
+ Z���-p���"=��\�-X�� ��az�ݫD��IT���b%��\�5Qr��Z���uz�(�T?PT���RJw��@��f�������4�J��l�W�A|Z���-A�f�H�E����m 6�Lft"�V�S�+�Ȯ���\,�i�v!���Rf�#�F�����2�o���v#���`:l���%�N�v�LEڵ��з]J=�����H�ыa,�5c `��f=��i0W��`5E?�u!7�x�2vk�t
22
+ endstream
23
+ endobj
24
+ 11 0 obj
25
+ 500
26
+ endobj
27
+ 3 0 obj
28
+ << >>
29
+ endobj
30
+ 4 0 obj
31
+ << /A1 << /CA 0 /Type /ExtGState /ca 0 >>
32
+ /A2 << /CA 1 /Type /ExtGState /ca 1 >> >>
33
+ endobj
34
+ 5 0 obj
35
+ << >>
36
+ endobj
37
+ 6 0 obj
38
+ << >>
39
+ endobj
40
+ 7 0 obj
41
+ << >>
42
+ endobj
43
+ 2 0 obj
44
+ << /Count 1 /Kids [ 10 0 R ] /Type /Pages >>
45
+ endobj
46
+ 12 0 obj
47
+ << /CreationDate (D:20160601123507-04'00')
48
+ /Creator (matplotlib 1.5.2rc2.post1933.dev0+gb775a26, http://matplotlib.org)
49
+ /Producer (matplotlib pdf backend) >>
50
+ endobj
51
+ xref
52
+ 0 13
53
+ 0000000000 65535 f
54
+ 0000000016 00000 n
55
+ 0000001161 00000 n
56
+ 0000000978 00000 n
57
+ 0000000999 00000 n
58
+ 0000001098 00000 n
59
+ 0000001119 00000 n
60
+ 0000001140 00000 n
61
+ 0000000065 00000 n
62
+ 0000000383 00000 n
63
+ 0000000208 00000 n
64
+ 0000000958 00000 n
65
+ 0000001221 00000 n
66
+ trailer
67
+ << /Info 12 0 R /Root 1 0 R /Size 13 >>
68
+ startxref
69
+ 1395
70
+ %%EOF
shared/package-files/3f/3f5264efd080601f392fe3b729124aa6caafc15260aaa27fbb8e0d8a0196b1a0/test_polysys.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for solvers of systems of polynomial equations. """
2
+ from sympy.core.numbers import (I, Integer, Rational)
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import symbols
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.polys.domains.rationalfield import QQ
7
+ from sympy.polys.polyerrors import UnsolvableFactorError
8
+ from sympy.polys.polyoptions import Options
9
+ from sympy.polys.polytools import Poly
10
+ from sympy.solvers.solvers import solve
11
+ from sympy.utilities.iterables import flatten
12
+ from sympy.abc import x, y, z
13
+ from sympy.polys import PolynomialError
14
+ from sympy.solvers.polysys import (solve_poly_system,
15
+ solve_triangulated,
16
+ solve_biquadratic, SolveFailed,
17
+ solve_generic)
18
+ from sympy.polys.polytools import parallel_poly_from_expr
19
+ from sympy.testing.pytest import raises
20
+
21
+
22
+ def test_solve_poly_system():
23
+ assert solve_poly_system([x - 1], x) == [(S.One,)]
24
+
25
+ assert solve_poly_system([y - x, y - x - 1], x, y) is None
26
+
27
+ assert solve_poly_system([y - x**2, y + x**2], x, y) == [(S.Zero, S.Zero)]
28
+
29
+ assert solve_poly_system([2*x - 3, y*Rational(3, 2) - 2*x, z - 5*y], x, y, z) == \
30
+ [(Rational(3, 2), Integer(2), Integer(10))]
31
+
32
+ assert solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) == \
33
+ [(0, 0), (2, -sqrt(2)), (2, sqrt(2))]
34
+
35
+ assert solve_poly_system([y - x**2, y + x**2 + 1], x, y) == \
36
+ [(-I*sqrt(S.Half), Rational(-1, 2)), (I*sqrt(S.Half), Rational(-1, 2))]
37
+
38
+ f_1 = x**2 + y + z - 1
39
+ f_2 = x + y**2 + z - 1
40
+ f_3 = x + y + z**2 - 1
41
+
42
+ a, b = sqrt(2) - 1, -sqrt(2) - 1
43
+
44
+ assert solve_poly_system([f_1, f_2, f_3], x, y, z) == \
45
+ [(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)]
46
+
47
+ solution = [(1, -1), (1, 1)]
48
+
49
+ assert solve_poly_system([Poly(x**2 - y**2), Poly(x - 1)]) == solution
50
+ assert solve_poly_system([x**2 - y**2, x - 1], x, y) == solution
51
+ assert solve_poly_system([x**2 - y**2, x - 1]) == solution
52
+
53
+ assert solve_poly_system(
54
+ [x + x*y - 3, y + x*y - 4], x, y) == [(-3, -2), (1, 2)]
55
+
56
+ raises(NotImplementedError, lambda: solve_poly_system([x**3 - y**3], x, y))
57
+ raises(NotImplementedError, lambda: solve_poly_system(
58
+ [z, -2*x*y**2 + x + y**2*z, y**2*(-z - 4) + 2]))
59
+ raises(PolynomialError, lambda: solve_poly_system([1/x], x))
60
+
61
+ raises(NotImplementedError, lambda: solve_poly_system(
62
+ [x-1,], (x, y)))
63
+ raises(NotImplementedError, lambda: solve_poly_system(
64
+ [y-1,], (x, y)))
65
+
66
+ # solve_poly_system should ideally construct solutions using
67
+ # CRootOf for the following four tests
68
+ assert solve_poly_system([x**5 - x + 1], [x], strict=False) == []
69
+ raises(UnsolvableFactorError, lambda: solve_poly_system(
70
+ [x**5 - x + 1], [x], strict=True))
71
+
72
+ assert solve_poly_system([(x - 1)*(x**5 - x + 1), y**2 - 1], [x, y],
73
+ strict=False) == [(1, -1), (1, 1)]
74
+ raises(UnsolvableFactorError,
75
+ lambda: solve_poly_system([(x - 1)*(x**5 - x + 1), y**2-1],
76
+ [x, y], strict=True))
77
+
78
+
79
+ def test_solve_generic():
80
+ NewOption = Options((x, y), {'domain': 'ZZ'})
81
+ assert solve_generic([x**2 - 2*y**2, y**2 - y + 1], NewOption) == \
82
+ [(-sqrt(-1 - sqrt(3)*I), Rational(1, 2) - sqrt(3)*I/2),
83
+ (sqrt(-1 - sqrt(3)*I), Rational(1, 2) - sqrt(3)*I/2),
84
+ (-sqrt(-1 + sqrt(3)*I), Rational(1, 2) + sqrt(3)*I/2),
85
+ (sqrt(-1 + sqrt(3)*I), Rational(1, 2) + sqrt(3)*I/2)]
86
+
87
+ # solve_generic should ideally construct solutions using
88
+ # CRootOf for the following two tests
89
+ assert solve_generic(
90
+ [2*x - y, (y - 1)*(y**5 - y + 1)], NewOption, strict=False) == \
91
+ [(Rational(1, 2), 1)]
92
+ raises(UnsolvableFactorError, lambda: solve_generic(
93
+ [2*x - y, (y - 1)*(y**5 - y + 1)], NewOption, strict=True))
94
+
95
+
96
+ def test_solve_biquadratic():
97
+ x0, y0, x1, y1, r = symbols('x0 y0 x1 y1 r')
98
+
99
+ f_1 = (x - 1)**2 + (y - 1)**2 - r**2
100
+ f_2 = (x - 2)**2 + (y - 2)**2 - r**2
101
+ s = sqrt(2*r**2 - 1)
102
+ a = (3 - s)/2
103
+ b = (3 + s)/2
104
+ assert solve_poly_system([f_1, f_2], x, y) == [(a, b), (b, a)]
105
+
106
+ f_1 = (x - 1)**2 + (y - 2)**2 - r**2
107
+ f_2 = (x - 1)**2 + (y - 1)**2 - r**2
108
+
109
+ assert solve_poly_system([f_1, f_2], x, y) == \
110
+ [(1 - sqrt((2*r - 1)*(2*r + 1))/2, Rational(3, 2)),
111
+ (1 + sqrt((2*r - 1)*(2*r + 1))/2, Rational(3, 2))]
112
+
113
+ query = lambda expr: expr.is_Pow and expr.exp is S.Half
114
+
115
+ f_1 = (x - 1 )**2 + (y - 2)**2 - r**2
116
+ f_2 = (x - x1)**2 + (y - 1)**2 - r**2
117
+
118
+ result = solve_poly_system([f_1, f_2], x, y)
119
+
120
+ assert len(result) == 2 and all(len(r) == 2 for r in result)
121
+ assert all(r.count(query) == 1 for r in flatten(result))
122
+
123
+ f_1 = (x - x0)**2 + (y - y0)**2 - r**2
124
+ f_2 = (x - x1)**2 + (y - y1)**2 - r**2
125
+
126
+ result = solve_poly_system([f_1, f_2], x, y)
127
+
128
+ assert len(result) == 2 and all(len(r) == 2 for r in result)
129
+ assert all(len(r.find(query)) == 1 for r in flatten(result))
130
+
131
+ s1 = (x*y - y, x**2 - x)
132
+ assert solve(s1) == [{x: 1}, {x: 0, y: 0}]
133
+ s2 = (x*y - x, y**2 - y)
134
+ assert solve(s2) == [{y: 1}, {x: 0, y: 0}]
135
+ gens = (x, y)
136
+ for seq in (s1, s2):
137
+ (f, g), opt = parallel_poly_from_expr(seq, *gens)
138
+ raises(SolveFailed, lambda: solve_biquadratic(f, g, opt))
139
+ seq = (x**2 + y**2 - 2, y**2 - 1)
140
+ (f, g), opt = parallel_poly_from_expr(seq, *gens)
141
+ assert solve_biquadratic(f, g, opt) == [
142
+ (-1, -1), (-1, 1), (1, -1), (1, 1)]
143
+ ans = [(0, -1), (0, 1)]
144
+ seq = (x**2 + y**2 - 1, y**2 - 1)
145
+ (f, g), opt = parallel_poly_from_expr(seq, *gens)
146
+ assert solve_biquadratic(f, g, opt) == ans
147
+ seq = (x**2 + y**2 - 1, x**2 - x + y**2 - 1)
148
+ (f, g), opt = parallel_poly_from_expr(seq, *gens)
149
+ assert solve_biquadratic(f, g, opt) == ans
150
+
151
+
152
+ def test_solve_triangulated():
153
+ f_1 = x**2 + y + z - 1
154
+ f_2 = x + y**2 + z - 1
155
+ f_3 = x + y + z**2 - 1
156
+
157
+ a, b = sqrt(2) - 1, -sqrt(2) - 1
158
+
159
+ assert solve_triangulated([f_1, f_2, f_3], x, y, z) == \
160
+ [(0, 0, 1), (0, 1, 0), (1, 0, 0)]
161
+
162
+ dom = QQ.algebraic_field(sqrt(2))
163
+
164
+ assert solve_triangulated([f_1, f_2, f_3], x, y, z, domain=dom) == \
165
+ [(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)]
166
+
167
+
168
+ def test_solve_issue_3686():
169
+ roots = solve_poly_system([((x - 5)**2/250000 + (y - Rational(5, 10))**2/250000) - 1, x], x, y)
170
+ assert roots == [(0, S.Half - 15*sqrt(1111)), (0, S.Half + 15*sqrt(1111))]
171
+
172
+ roots = solve_poly_system([((x - 5)**2/250000 + (y - 5.0/10)**2/250000) - 1, x], x, y)
173
+ # TODO: does this really have to be so complicated?!
174
+ assert len(roots) == 2
175
+ assert roots[0][0] == 0
176
+ assert roots[0][1].epsilon_eq(-499.474999374969, 1e12)
177
+ assert roots[1][0] == 0
178
+ assert roots[1][1].epsilon_eq(500.474999374969, 1e12)
shared/package-files/3f/3f5726aab02371a09d39b90d6757ba1e9fff669c41021431d22222a4e556f238/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from networkx.algorithms.coloring.greedy_coloring import *
2
+ from networkx.algorithms.coloring.equitable_coloring import equitable_color
3
+
4
+ __all__ = ["greedy_color", "equitable_color"]
shared/package-files/3f/3f589029f5e5ec8bade99e58f7b4261abfd4aa2019eaa47e7a844cb5869c19f0/abc.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module exports all latin and greek letters as Symbols, so you can
3
+ conveniently do
4
+
5
+ >>> from sympy.abc import x, y
6
+
7
+ instead of the slightly more clunky-looking
8
+
9
+ >>> from sympy import symbols
10
+ >>> x, y = symbols('x y')
11
+
12
+ Caveats
13
+ =======
14
+
15
+ 1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``,
16
+ ``E``, and ``Q`` are colliding with names defined in SymPy. If you import them
17
+ from both ``sympy.abc`` and ``sympy``, the second import will "win".
18
+ This is an issue only for * imports, which should only be used for short-lived
19
+ code such as interactive sessions and throwaway scripts that do not survive
20
+ until the next SymPy upgrade, where ``sympy`` may contain a different set of
21
+ names.
22
+
23
+ 2. This module does not define symbol names on demand, i.e.
24
+ ``from sympy.abc import foo`` will be reported as an error because
25
+ ``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``,
26
+ you still need to use ``Symbol('foo')`` or ``symbols('foo')``.
27
+ You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though
28
+ sticking with one and only one way to get the symbols does tend to make the code
29
+ more readable.
30
+
31
+ The module also defines some special names to help detect which names clash
32
+ with the default SymPy namespace.
33
+
34
+ ``_clash1`` defines all the single letter variables that clash with
35
+ SymPy objects; ``_clash2`` defines the multi-letter clashing symbols;
36
+ and ``_clash`` is the union of both. These can be passed for ``locals``
37
+ during sympification if one desires Symbols rather than the non-Symbol
38
+ objects for those names.
39
+
40
+ Examples
41
+ ========
42
+
43
+ >>> from sympy import S
44
+ >>> from sympy.abc import _clash1, _clash2, _clash
45
+ >>> S("Q & C", locals=_clash1)
46
+ C & Q
47
+ >>> S('pi(x)', locals=_clash2)
48
+ pi(x)
49
+ >>> S('pi(C, Q)', locals=_clash)
50
+ pi(C, Q)
51
+
52
+ """
53
+
54
+ from typing import Any, Dict as tDict
55
+
56
+ import string
57
+
58
+ from .core import Symbol, symbols
59
+ from .core.alphabets import greeks
60
+ from sympy.parsing.sympy_parser import null
61
+
62
+ ##### Symbol definitions #####
63
+
64
+ # Implementation note: The easiest way to avoid typos in the symbols()
65
+ # parameter is to copy it from the left-hand side of the assignment.
66
+
67
+ a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j')
68
+ k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t')
69
+ u, v, w, x, y, z = symbols('u, v, w, x, y, z')
70
+
71
+ A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J')
72
+ K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T')
73
+ U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z')
74
+
75
+ alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta')
76
+ epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta')
77
+ iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu')
78
+ nu, xi, omicron, pi = symbols('nu, xi, omicron, pi')
79
+ rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon')
80
+ phi, chi, psi, omega = symbols('phi, chi, psi, omega')
81
+
82
+
83
+ ##### Clashing-symbols diagnostics #####
84
+
85
+ # We want to know which names in SymPy collide with those in here.
86
+ # This is mostly for diagnosing SymPy's namespace during SymPy development.
87
+
88
+ _latin = list(string.ascii_letters)
89
+ # QOSINE should not be imported as they clash; gamma, pi and zeta clash, too
90
+ _greek = list(greeks) # make a copy, so we can mutate it
91
+ # Note: We import lamda since lambda is a reserved keyword in Python
92
+ _greek.remove("lambda")
93
+ _greek.append("lamda")
94
+
95
+ ns: tDict[str, Any] = {}
96
+ exec('from sympy import *', ns)
97
+ _clash1: tDict[str, Any] = {}
98
+ _clash2: tDict[str, Any] = {}
99
+ while ns:
100
+ _k, _ = ns.popitem()
101
+ if _k in _greek:
102
+ _clash2[_k] = null
103
+ _greek.remove(_k)
104
+ elif _k in _latin:
105
+ _clash1[_k] = null
106
+ _latin.remove(_k)
107
+ _clash = {}
108
+ _clash.update(_clash1)
109
+ _clash.update(_clash2)
110
+
111
+ del _latin, _greek, Symbol, _k, null
shared/package-files/3f/3f58ae9d9d901b4bc5a5bd5038dfb80e7d7df52fc8e6ba697dda099a78cd0224/Types.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/miopen/miopen-wrapper.h>
4
+ #include <ATen/Tensor.h>
5
+
6
+ namespace at { namespace native {
7
+
8
+ miopenDataType_t getMiopenDataType(const at::Tensor& tensor);
9
+
10
+ int64_t miopen_version();
11
+
12
+ }} // namespace at::miopen
shared/package-files/3f/3f5b5005469cead828149e0137c8962e3674655a1e8118cadfa572862cace2c3/vi200-rv ADDED
Binary file (713 Bytes). View file
 
shared/package-files/3f/3f5e7fde03397994186fff8addcef4c4a75e20633cd6ee5602456163c7a2e0dd/fitpack2.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.interpolate` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'BivariateSpline',
10
+ 'InterpolatedUnivariateSpline',
11
+ 'LSQBivariateSpline',
12
+ 'LSQSphereBivariateSpline',
13
+ 'LSQUnivariateSpline',
14
+ 'RectBivariateSpline',
15
+ 'RectSphereBivariateSpline',
16
+ 'SmoothBivariateSpline',
17
+ 'SmoothSphereBivariateSpline',
18
+ 'UnivariateSpline',
19
+ ]
20
+
21
+
22
+ def __dir__():
23
+ return __all__
24
+
25
+
26
+ def __getattr__(name):
27
+ return _sub_module_deprecation(sub_package="interpolate", module="fitpack2",
28
+ private_modules=["_fitpack2"], all=__all__,
29
+ attribute=name)
shared/package-files/3f/3f5f0b88547cf2a3a5296b3712ae9ba7f2b7b22e9598dbf2d36918b084f7b473/Parallel-inl.h ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/Exception.h>
4
+ #include <c10/util/ParallelGuard.h>
5
+ #include <c10/util/SmallVector.h>
6
+
7
+ namespace at {
8
+
9
+ template <class F>
10
+ inline void parallel_for(
11
+ const int64_t begin,
12
+ const int64_t end,
13
+ const int64_t grain_size,
14
+ const F& f) {
15
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(grain_size >= 0);
16
+ if (begin >= end) {
17
+ return;
18
+ }
19
+
20
+ #ifdef INTRA_OP_PARALLEL
21
+ at::internal::lazy_init_num_threads();
22
+ const auto numiter = end - begin;
23
+ const bool use_parallel =
24
+ (numiter > grain_size && numiter > 1 && !at::in_parallel_region() &&
25
+ at::get_num_threads() > 1);
26
+ if (!use_parallel) {
27
+ internal::ThreadIdGuard tid_guard(0);
28
+ c10::ParallelGuard guard(true);
29
+ f(begin, end);
30
+ return;
31
+ }
32
+
33
+ internal::invoke_parallel(
34
+ begin, end, grain_size, [&](int64_t begin, int64_t end) {
35
+ c10::ParallelGuard guard(true);
36
+ f(begin, end);
37
+ });
38
+ #else
39
+ internal::ThreadIdGuard tid_guard(0);
40
+ c10::ParallelGuard guard(true);
41
+ f(begin, end);
42
+ #endif
43
+ }
44
+
45
+ template <class scalar_t, class F, class SF>
46
+ inline scalar_t parallel_reduce(
47
+ const int64_t begin,
48
+ const int64_t end,
49
+ const int64_t grain_size,
50
+ const scalar_t ident,
51
+ const F& f,
52
+ const SF& sf) {
53
+ TORCH_CHECK(grain_size >= 0);
54
+ if (begin >= end) {
55
+ return ident;
56
+ }
57
+
58
+ #ifdef INTRA_OP_PARALLEL
59
+ at::internal::lazy_init_num_threads();
60
+ const auto max_threads = at::get_num_threads();
61
+ const bool use_parallel =
62
+ ((end - begin) > grain_size && !at::in_parallel_region() &&
63
+ max_threads > 1);
64
+ if (!use_parallel) {
65
+ internal::ThreadIdGuard tid_guard(0);
66
+ c10::ParallelGuard guard(true);
67
+ return f(begin, end, ident);
68
+ }
69
+
70
+ c10::SmallVector<scalar_t, 64> results(max_threads, ident);
71
+ internal::invoke_parallel(
72
+ begin,
73
+ end,
74
+ grain_size,
75
+ [&](const int64_t my_begin, const int64_t my_end) {
76
+ const auto tid = at::get_thread_num();
77
+ c10::ParallelGuard guard(true);
78
+ results[tid] = f(my_begin, my_end, ident);
79
+ });
80
+
81
+ scalar_t result = ident;
82
+ for (auto partial_result : results) {
83
+ result = sf(result, partial_result);
84
+ }
85
+ return result;
86
+ #else
87
+ internal::ThreadIdGuard tid_guard(0);
88
+ c10::ParallelGuard guard(true);
89
+ return f(begin, end, ident);
90
+ #endif
91
+ }
92
+
93
+ } // namespace at
shared/package-files/3f/3f5f56f73665f2d37410af8f6848b68081472f009baee4cc1149bbfc02c61fd4/test_astype.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ Index,
6
+ to_datetime,
7
+ to_timedelta,
8
+ )
9
+ import pandas._testing as tm
10
+
11
+
12
+ class TestAstype:
13
+ def test_astype_float64_to_uint64(self):
14
+ # GH#45309 used to incorrectly return Index with int64 dtype
15
+ idx = Index([0.0, 5.0, 10.0, 15.0, 20.0], dtype=np.float64)
16
+ result = idx.astype("u8")
17
+ expected = Index([0, 5, 10, 15, 20], dtype=np.uint64)
18
+ tm.assert_index_equal(result, expected, exact=True)
19
+
20
+ idx_with_negatives = idx - 10
21
+ with pytest.raises(ValueError, match="losslessly"):
22
+ idx_with_negatives.astype(np.uint64)
23
+
24
+ def test_astype_float64_to_object(self):
25
+ float_index = Index([0.0, 2.5, 5.0, 7.5, 10.0], dtype=np.float64)
26
+ result = float_index.astype(object)
27
+ assert result.equals(float_index)
28
+ assert float_index.equals(result)
29
+ assert isinstance(result, Index) and result.dtype == object
30
+
31
+ def test_astype_float64_mixed_to_object(self):
32
+ # mixed int-float
33
+ idx = Index([1.5, 2, 3, 4, 5], dtype=np.float64)
34
+ idx.name = "foo"
35
+ result = idx.astype(object)
36
+ assert result.equals(idx)
37
+ assert idx.equals(result)
38
+ assert isinstance(result, Index) and result.dtype == object
39
+
40
+ @pytest.mark.parametrize("dtype", ["int16", "int32", "int64"])
41
+ def test_astype_float64_to_int_dtype(self, dtype):
42
+ # GH#12881
43
+ # a float astype int
44
+ idx = Index([0, 1, 2], dtype=np.float64)
45
+ result = idx.astype(dtype)
46
+ expected = Index([0, 1, 2], dtype=dtype)
47
+ tm.assert_index_equal(result, expected, exact=True)
48
+
49
+ idx = Index([0, 1.1, 2], dtype=np.float64)
50
+ result = idx.astype(dtype)
51
+ expected = Index([0, 1, 2], dtype=dtype)
52
+ tm.assert_index_equal(result, expected, exact=True)
53
+
54
+ @pytest.mark.parametrize("dtype", ["float32", "float64"])
55
+ def test_astype_float64_to_float_dtype(self, dtype):
56
+ # GH#12881
57
+ # a float astype int
58
+ idx = Index([0, 1, 2], dtype=np.float64)
59
+ result = idx.astype(dtype)
60
+ assert isinstance(result, Index) and result.dtype == dtype
61
+
62
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
63
+ def test_astype_float_to_datetimelike(self, dtype):
64
+ # GH#49660 pre-2.0 Index.astype from floating to M8/m8/Period raised,
65
+ # inconsistent with Series.astype
66
+ idx = Index([0, 1.1, 2], dtype=np.float64)
67
+
68
+ result = idx.astype(dtype)
69
+ if dtype[0] == "M":
70
+ expected = to_datetime(idx.values)
71
+ else:
72
+ expected = to_timedelta(idx.values)
73
+ tm.assert_index_equal(result, expected)
74
+
75
+ # check that we match Series behavior
76
+ result = idx.to_series().set_axis(range(3)).astype(dtype)
77
+ expected = expected.to_series().set_axis(range(3))
78
+ tm.assert_series_equal(result, expected)
79
+
80
+ @pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"])
81
+ @pytest.mark.parametrize("non_finite", [np.inf, np.nan])
82
+ def test_cannot_cast_inf_to_int(self, non_finite, dtype):
83
+ # GH#13149
84
+ idx = Index([1, 2, non_finite], dtype=np.float64)
85
+
86
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
87
+ with pytest.raises(ValueError, match=msg):
88
+ idx.astype(dtype)
89
+
90
+ def test_astype_from_object(self):
91
+ index = Index([1.0, np.nan, 0.2], dtype="object")
92
+ result = index.astype(float)
93
+ expected = Index([1.0, np.nan, 0.2], dtype=np.float64)
94
+ assert result.dtype == expected.dtype
95
+ tm.assert_index_equal(result, expected)
shared/package-files/3f/3f5f901d3e1aef5874bdb4513c722da054932f24b31f4ded8d7bc1b841dd2457/daft_extension.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Useless IPython extension to test installing and loading extensions.
4
+ """
5
+ some_vars = {'arq': 185}
6
+
7
+ def load_ipython_extension(ip):
8
+ # set up simplified quantity input
9
+ ip.push(some_vars)
10
+
11
+ def unload_ipython_extension(ip):
12
+ ip.drop_by_id(some_vars)
shared/package-files/3f/3f6006921760dd92ea5da41d7fcca875b96b0697601106412ca3cbd666f19857/sankey.pyi ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib.axes import Axes
2
+
3
+ from collections.abc import Callable, Iterable
4
+ from typing import Any
5
+ from typing_extensions import Self # < Py 3.11
6
+
7
+ import numpy as np
8
+
9
+ __license__: str
10
+ __credits__: list[str]
11
+ __author__: str
12
+ __version__: str
13
+
14
+ RIGHT: int
15
+ UP: int
16
+ DOWN: int
17
+
18
+ # TODO typing units
19
+ class Sankey:
20
+ diagrams: list[Any]
21
+ ax: Axes
22
+ unit: Any
23
+ format: str | Callable[[float], str]
24
+ scale: float
25
+ gap: float
26
+ radius: float
27
+ shoulder: float
28
+ offset: float
29
+ margin: float
30
+ pitch: float
31
+ tolerance: float
32
+ extent: np.ndarray
33
+ def __init__(
34
+ self,
35
+ ax: Axes | None = ...,
36
+ scale: float = ...,
37
+ unit: Any = ...,
38
+ format: str | Callable[[float], str] = ...,
39
+ gap: float = ...,
40
+ radius: float = ...,
41
+ shoulder: float = ...,
42
+ offset: float = ...,
43
+ head_angle: float = ...,
44
+ margin: float = ...,
45
+ tolerance: float = ...,
46
+ **kwargs
47
+ ) -> None: ...
48
+ def add(
49
+ self,
50
+ patchlabel: str = ...,
51
+ flows: Iterable[float] | None = ...,
52
+ orientations: Iterable[int] | None = ...,
53
+ labels: str | Iterable[str | None] = ...,
54
+ trunklength: float = ...,
55
+ pathlengths: float | Iterable[float] = ...,
56
+ prior: int | None = ...,
57
+ connect: tuple[int, int] = ...,
58
+ rotation: float = ...,
59
+ **kwargs
60
+ ) -> Self: ...
61
+ def finish(self) -> list[Any]: ...
shared/package-files/3f/3f60186df29e6686acbbd200e4b9d05d832f2abe26727e21492ac3f5885f4d70/special_laguerre_polynomial_l_compositeexplicitautogradnonfunctional_dispatch.h 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 compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor special_laguerre_polynomial_l(const at::Tensor & x, const at::Tensor & n);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at