s42chen commited on
Commit
8cb77a3
·
verified ·
1 Parent(s): 9d20952

Remove 5000 files superseded by the deduplicated export

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/9b/9b2824a306502b0a6f1290bd19fd1fcd2869bb52c21a5c33a1bc9480da5752dd/blob +0 -413
  2. shared/package-files/9b/9b29fc93ae95aef6672fa47a556e880cf4df3baf15c636c9f14a7922e4a314be/blob +0 -88
  3. shared/package-files/9b/9b2c1a62c96e69385c72c6f7d5499d217c1773c48436f016e83412ea582aace6/blob +0 -57
  4. shared/package-files/9b/9b2e55e0f1d3df31cb2b442f6a712a427eb98c9e7f9cd572eae97fd301d14f5f/blob +0 -140
  5. shared/package-files/9b/9b2f91be34024fbcf645f6ef92460e5f944ca6a16268b79478ab904b2934d357/blob +0 -52
  6. shared/package-files/9b/9b2ff15cb3d217ce7ef0b06547f16743aef6d5363072c505bff85d03e769596e/blob +0 -360
  7. shared/package-files/9b/9b34108030dba74e01d372b226ba2cb0ba7c62aef6449ce3a7edc0adf8db307f/blob +0 -188
  8. shared/package-files/9b/9b3bb70cade8184ee8eca3239aa7e6762ad6be906e15e8ea42ed5629b8abdafa/blob +0 -200
  9. shared/package-files/9b/9b3e92596047cab99a939229b56d656a7862d617eacf9291d7fa6f6c95f80e36/blob +0 -570
  10. shared/package-files/9b/9b45a809e914c434a5fedb1bcfe7f9bd9ee4471fd5d828bcafa59cd50b502507/blob +0 -884
  11. shared/package-files/9b/9b484599c4f3bd9f2c65b6e759e10dc332b2b9fa44f735b0651f96088e247695/blob +0 -113
  12. shared/package-files/9b/9b4b2ab4ef7b3c4bfcfff6eca7136078b7c168c81adab9d952790797eea37249/blob +0 -63
  13. shared/package-files/9b/9b4d6e6e077c5be4e16cbf790138fb75158aea70027ab99005cd0cac43cf42bf/blob +0 -68
  14. shared/package-files/9b/9b4fa9e614c6536132eee050ac1ecb48f813bd2d02f05afe480f5dd81017e8c9/blob +0 -687
  15. shared/package-files/9b/9b542cdd392345b80afdab68e0f7056548da6fee5a1315a7bf918d1b54bd957b/blob +0 -11
  16. shared/package-files/9b/9b5b3703806bbd17835f93e58836a5639dd884f7ef875b3ec7879f6b57e521a1/blob +0 -95
  17. shared/package-files/9b/9b62149e65ae88c6dd4da6bc3fd68cac9355d5be78045d9faf3270495fdc5451/blob +0 -160
  18. shared/package-files/9b/9b633e2d6aa5d803d19bb099de8163f7b49408a1bfaea3fe3e7d519e15dda808/blob +0 -50
  19. shared/package-files/9b/9b65eeebf6d708da9966136f37d3d3eef925cdce7587f22da457eeee1f8ba83e/blob +0 -557
  20. shared/package-files/9b/9b66f7e1cf75ec85b9a3e43fe936081e5b0af6549494d8b2ac84d3507ff3c1ec/blob +0 -353
  21. shared/package-files/9b/9b6742f1d21425a930997735c01c838096af851948a118f4923bade4c777e9e7/blob +0 -24
  22. shared/package-files/9b/9b6cdb3f80bbf7a16f415b15566b175028b3f0fae3d8efa94f9e6b6c70363700/blob +0 -25
  23. shared/package-files/9b/9b6d58df002d41cfa38ba55e6fa93f33983a034672148e1e81c853767c21fa94/blob +0 -11
  24. shared/package-files/9b/9b6e400eb85440ec64ab66b4ac111546585740c9ca61fd156400d7153cbad9f4/blob +0 -335
  25. shared/package-files/9b/9b6fd8df3c9d5193733e9bbcf27f303cd5aa6b17da01330a128ff30205ccab26/blob +0 -166
  26. shared/package-files/9b/9b717166deba6db15d053b26793d1c34c4a756495065bafecb0657dd9461794f/blob +0 -57
  27. shared/package-files/9b/9b7207dba4c2ccb0e94bc72dbf324a2c0f31e35e2eaf98e55f7b1d4f8b01e26f/blob +0 -50
  28. shared/package-files/9b/9b72799855182eb383e06337a6fb5c8a9e01872fcdf9c1e1adcb01a3915657a7/blob +0 -27
  29. shared/package-files/9b/9b73f686d2ddb70d184f449d22d666b0a1ea63797ad578875be8245c4efa817e/blob +0 -3
  30. shared/package-files/9b/9b754b17f8c1e4f6d11f3ae7c0f25b6bfcfb78c73ce79016075e681189215e73/blob +0 -28
  31. shared/package-files/9b/9b75f170af5486c48214aefebeb394eb3b67f9e69e5ca2ee4bc74ff3c418eb3c/blob +0 -480
  32. shared/package-files/9b/9b79065dfee170914ab9ff6306eddbabe921f4c432484396c6011b04497447c4/blob +0 -1202
  33. shared/package-files/9b/9b7ac2e8ca2073a71cd5af5727c14f21885969214d758931699fa97c7846dd7e/blob +0 -0
  34. shared/package-files/9b/9b7c8bd1d4c05d73ca75e619a0bf9958598fd50abe57a63d5f11bb10c43ba2f1/blob +0 -329
  35. shared/package-files/9b/9b7d4f55a4e2fdb02c430068fdffabc732addce238da3f1df2690249c3353274/blob +0 -17
  36. shared/package-files/9b/9b7d69d168dc15419c91b2621e70a949a2101aabfe2eae6788862475ddf760ca/blob +0 -234
  37. shared/package-files/9b/9b7e40ee33b9e3130d800e30e44767d62fd21db5d6065a504d12cc47c1a06d91/blob +0 -109
  38. shared/package-files/9b/9b8280d86ff5b59acd6ff6f3f7773279ffddb6a6f7f90befc8516f754879e456/blob +0 -0
  39. shared/package-files/9b/9b8648ab7c6ea7dec4c0aab3db5e6fd033f3925eb80c627c7248893b35a43c78/blob +0 -17
  40. shared/package-files/9b/9b86cb0749eb28f07811ecd87954712f8bacda87a621d2d31e209acfbab4be1a/blob +0 -27
  41. shared/package-files/9b/9b8b84fe0598495357e29ad58df7c0c4bd126e2514fec2e861a167606009660b/blob +0 -39
  42. shared/package-files/9b/9b8c6edddc57710cdff7af9638a24f14d9b0d0611517b243e7294c45c79f760d/blob +0 -288
  43. shared/package-files/9b/9b8d9aaa3bcbfbf84b3f67da398e1ab16ea4ed4cbe2f859f853e6fcaac7ddb6a/blob +0 -0
  44. shared/package-files/9b/9b9249bfb2c4ed5ba4a7c879d2bf74b027db392003d9b3152154145313597834/blob +0 -2808
  45. shared/package-files/9b/9b99fa34cb2c454490337a62a9d91f5828c1a4f1ac22d94d94fffea34a2d612e/blob +0 -563
  46. shared/package-files/9b/9ba27558c729a3ded33a153652e663250379593d748ad9c473f4942553ddd247/blob +0 -106
  47. shared/package-files/9b/9ba2eb28230878d7ae89c7ee30c146dfe29efbba328d3b03d5045b29d4d15589/blob +0 -365
  48. shared/package-files/9b/9ba3dbd2b159c35b0bad95c6b8c54bf2ba8da83afa007f930f298988ea22d915/blob +0 -0
  49. shared/package-files/9b/9ba66c370c751a1b0492d42beb73715c74245f607b36d8b4d755d8b0f836c5fa/blob +0 -112
  50. shared/package-files/9b/9ba7b5b1a97124d16a01ca9921b766b8f2bf995761f7f4d5a4776df91868353d/blob +0 -13
shared/package-files/9b/9b2824a306502b0a6f1290bd19fd1fcd2869bb52c21a5c33a1bc9480da5752dd/blob DELETED
@@ -1,413 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import abc
4
- from functools import lru_cache
5
- from typing import TYPE_CHECKING, Any, ClassVar, Final, Protocol, TypeVar, cast, overload
6
-
7
- import polars as pl
8
-
9
- from narwhals._duration import Interval
10
- from narwhals._utils import (
11
- Implementation,
12
- Version,
13
- _DeferredIterable,
14
- _StoresCompliant,
15
- _StoresNative,
16
- deep_getattr,
17
- isinstance_or_issubclass,
18
- )
19
- from narwhals.exceptions import (
20
- ColumnNotFoundError,
21
- ComputeError,
22
- DuplicateError,
23
- InvalidOperationError,
24
- NarwhalsError,
25
- ShapeError,
26
- )
27
-
28
- if TYPE_CHECKING:
29
- from collections.abc import Callable, Iterable, Iterator, Mapping
30
-
31
- from typing_extensions import TypeIs
32
-
33
- from narwhals._compliant.typing import Accessor
34
- from narwhals._polars.dataframe import Method
35
- from narwhals._polars.expr import PolarsExpr
36
- from narwhals._polars.series import PolarsSeries
37
- from narwhals.dtypes import DType
38
- from narwhals.typing import IntoDType
39
-
40
- T = TypeVar("T")
41
- NativeT = TypeVar(
42
- "NativeT", bound="pl.DataFrame | pl.LazyFrame | pl.Series | pl.Expr"
43
- )
44
-
45
- NativeT_co = TypeVar("NativeT_co", "pl.Series", "pl.Expr", covariant=True)
46
- CompliantT_co = TypeVar("CompliantT_co", "PolarsSeries", "PolarsExpr", covariant=True)
47
- CompliantT = TypeVar("CompliantT", "PolarsSeries", "PolarsExpr")
48
-
49
- BACKEND_VERSION = Implementation.POLARS._backend_version()
50
- """Static backend version for `polars`."""
51
-
52
- SERIES_ACCEPTS_PD_INDEX: Final[bool] = BACKEND_VERSION >= (0, 20, 7)
53
- """`pl.Series(values: pd.Index)` fixed in https://github.com/pola-rs/polars/pull/14087"""
54
-
55
- RESPECT_JOIN_NULL_SEMI_ANTI: Final[bool] = BACKEND_VERSION >= (0, 20, 22)
56
- """Polars < 0.20.22 treats `null == null` as a match in semi/anti joins.
57
-
58
- Dropping rows with null keys on the right removes these spurious matches,
59
- which is always valid since narwhals treats nulls as non-matching.
60
-
61
- Fixed in https://github.com/pola-rs/polars/pull/15696
62
- """
63
-
64
- SERIES_RESPECTS_DTYPE: Final[bool] = BACKEND_VERSION >= (0, 20, 26)
65
- """`pl.Series(dtype=...)` fixed in https://github.com/pola-rs/polars/pull/15962
66
-
67
- Includes `SERIES_ACCEPTS_PD_INDEX`.
68
- """
69
-
70
- HAS_INT_128: Final[bool] = BACKEND_VERSION >= (1, 18, 0)
71
- """https://github.com/pola-rs/polars/pull/20232"""
72
-
73
- FROM_DICTS_ACCEPTS_MAPPINGS: Final[bool] = BACKEND_VERSION >= (1, 30, 0)
74
- """`pl.from_dicts(data: Iterable[Mapping[str, Any]])` since https://github.com/pola-rs/polars/pull/22638"""
75
-
76
- HAS_UINT_128: Final[bool] = BACKEND_VERSION >= (1, 34, 0)
77
- """https://github.com/pola-rs/polars/pull/24346"""
78
-
79
- HAS_FLOAT_16: Final[bool] = BACKEND_VERSION >= (1, 36, 0)
80
- """https://github.com/pola-rs/polars/pull/25185"""
81
-
82
- BINARY_ADD_UPCASTS_DECIMAL_TO_FLOAT: Final[bool] = BACKEND_VERSION >= (1, 34, 0)
83
- """Polars >= 1.34 upcasts `Decimal + float` to `Float64` (matching `int`/`Float32` promotion).
84
-
85
- https://github.com/pola-rs/polars/pull/24594
86
- """
87
-
88
-
89
- @overload
90
- def extract_native(obj: _StoresNative[NativeT]) -> NativeT: ...
91
- @overload
92
- def extract_native(obj: T) -> T: ...
93
- def extract_native(obj: _StoresNative[NativeT] | T) -> NativeT | T:
94
- return obj.native if _is_compliant_polars(obj) else cast("T", obj)
95
-
96
-
97
- def _is_compliant_polars(
98
- obj: _StoresNative[NativeT] | Any,
99
- ) -> TypeIs[_StoresNative[NativeT]]:
100
- from narwhals._polars.dataframe import PolarsDataFrame, PolarsLazyFrame
101
- from narwhals._polars.expr import PolarsExpr
102
- from narwhals._polars.series import PolarsSeries
103
-
104
- return isinstance(obj, (PolarsDataFrame, PolarsLazyFrame, PolarsSeries, PolarsExpr))
105
-
106
-
107
- def extract_args_kwargs(
108
- args: Iterable[Any], kwds: Mapping[str, Any], /
109
- ) -> tuple[Iterator[Any], dict[str, Any]]:
110
- it_args = (extract_native(arg) for arg in args)
111
- return it_args, {k: extract_native(v) for k, v in kwds.items()}
112
-
113
-
114
- @lru_cache(maxsize=128)
115
- def native_to_narwhals_dtype( # noqa: C901, PLR0912
116
- dtype: pl.DataType, version: Version
117
- ) -> DType:
118
- dtypes = version.dtypes
119
- if dtype == pl.Float64:
120
- return dtypes.Float64()
121
- if dtype == pl.Float32:
122
- return dtypes.Float32()
123
- if HAS_FLOAT_16 and dtype == pl.Float16:
124
- return dtypes.Float16()
125
- if HAS_INT_128 and dtype == pl.Int128:
126
- return dtypes.Int128()
127
- if dtype == pl.Int64:
128
- return dtypes.Int64()
129
- if dtype == pl.Int32:
130
- return dtypes.Int32()
131
- if dtype == pl.Int16:
132
- return dtypes.Int16()
133
- if dtype == pl.Int8:
134
- return dtypes.Int8()
135
- if HAS_UINT_128 and dtype == pl.UInt128:
136
- return dtypes.UInt128()
137
- if dtype == pl.UInt64:
138
- return dtypes.UInt64()
139
- if dtype == pl.UInt32:
140
- return dtypes.UInt32()
141
- if dtype == pl.UInt16:
142
- return dtypes.UInt16()
143
- if dtype == pl.UInt8:
144
- return dtypes.UInt8()
145
- if dtype == pl.String:
146
- return dtypes.String()
147
- if dtype == pl.Boolean:
148
- return dtypes.Boolean()
149
- if dtype == pl.Object:
150
- return dtypes.Object()
151
- if isinstance(dtype, pl.Categorical):
152
- return dtypes.Categorical()
153
- if isinstance(dtype, pl.Enum):
154
- if version is Version.V1:
155
- return dtypes.Enum() # type: ignore[call-arg]
156
- categories = _DeferredIterable(dtype.categories.to_list)
157
- return dtypes.Enum(categories)
158
- if dtype == pl.Date:
159
- return dtypes.Date()
160
- if isinstance(dtype, pl.Datetime):
161
- return dtypes.Datetime(dtype.time_unit, dtype.time_zone)
162
- if isinstance(dtype, pl.Duration):
163
- return dtypes.Duration(dtype.time_unit)
164
- if isinstance(dtype, pl.Struct):
165
- fields = [
166
- dtypes.Field(name, native_to_narwhals_dtype(tp, version))
167
- for name, tp in dtype
168
- ]
169
- return dtypes.Struct(fields)
170
- if isinstance(dtype, pl.List):
171
- return dtypes.List(native_to_narwhals_dtype(dtype.inner, version))
172
- if isinstance(dtype, pl.Array):
173
- outer_shape = dtype.width if BACKEND_VERSION < (0, 20, 30) else dtype.size # type: ignore[attr-defined]
174
- return dtypes.Array(native_to_narwhals_dtype(dtype.inner, version), outer_shape)
175
- if isinstance(dtype, pl.Decimal):
176
- return dtypes.Decimal(dtype.precision, dtype.scale)
177
- if dtype == pl.Time:
178
- return dtypes.Time()
179
- if dtype == pl.Binary:
180
- return dtypes.Binary()
181
- return dtypes.Unknown()
182
-
183
-
184
- dtypes = Version.MAIN.dtypes
185
-
186
-
187
- def _version_dependent_dtypes() -> dict[type[DType], pl.DataType]:
188
- if not HAS_INT_128: # pragma: no cover
189
- return {}
190
- nw_to_pl: dict[type[DType], pl.DataType] = {dtypes.Int128: pl.Int128()}
191
- nw_to_pl = nw_to_pl | {dtypes.UInt128: pl.UInt128()} if HAS_UINT_128 else nw_to_pl
192
- return nw_to_pl | {dtypes.Float16: pl.Float16()} if HAS_FLOAT_16 else nw_to_pl
193
-
194
-
195
- NW_TO_PL_DTYPES: Mapping[type[DType], pl.DataType] = {
196
- dtypes.Float64: pl.Float64(),
197
- dtypes.Float32: pl.Float32(),
198
- dtypes.Binary: pl.Binary(),
199
- dtypes.String: pl.String(),
200
- dtypes.Boolean: pl.Boolean(),
201
- dtypes.Categorical: pl.Categorical(),
202
- dtypes.Date: pl.Date(),
203
- dtypes.Time: pl.Time(),
204
- dtypes.Int8: pl.Int8(),
205
- dtypes.Int16: pl.Int16(),
206
- dtypes.Int32: pl.Int32(),
207
- dtypes.Int64: pl.Int64(),
208
- dtypes.UInt8: pl.UInt8(),
209
- dtypes.UInt16: pl.UInt16(),
210
- dtypes.UInt32: pl.UInt32(),
211
- dtypes.UInt64: pl.UInt64(),
212
- dtypes.Object: pl.Object(),
213
- dtypes.Unknown: pl.Unknown(),
214
- **_version_dependent_dtypes(),
215
- }
216
-
217
-
218
- def narwhals_to_native_dtype( # noqa: C901
219
- dtype: IntoDType, version: Version
220
- ) -> pl.DataType:
221
- dtypes = version.dtypes
222
- base_type = dtype.base_type()
223
- if pl_type := NW_TO_PL_DTYPES.get(base_type):
224
- return pl_type
225
- if isinstance_or_issubclass(dtype, dtypes.Enum):
226
- if version is Version.V1:
227
- msg = "Converting to Enum is not supported in narwhals.stable.v1"
228
- raise NotImplementedError(msg)
229
- if isinstance(dtype, dtypes.Enum):
230
- return pl.Enum(dtype.categories)
231
- msg = "Can not cast / initialize Enum without categories present"
232
- raise ValueError(msg)
233
- if isinstance_or_issubclass(dtype, dtypes.Datetime):
234
- return pl.Datetime(dtype.time_unit, dtype.time_zone) # type: ignore[arg-type]
235
- if isinstance_or_issubclass(dtype, dtypes.Duration):
236
- return pl.Duration(dtype.time_unit) # type: ignore[arg-type]
237
- if isinstance_or_issubclass(dtype, dtypes.List):
238
- return pl.List(narwhals_to_native_dtype(dtype.inner, version))
239
- if isinstance_or_issubclass(dtype, dtypes.Struct):
240
- fields = [
241
- pl.Field(field.name, narwhals_to_native_dtype(field.dtype, version))
242
- for field in dtype.fields
243
- ]
244
- return pl.Struct(fields)
245
- if isinstance_or_issubclass(dtype, dtypes.Array): # pragma: no cover
246
- size = dtype.size
247
- kwargs = {"width": size} if BACKEND_VERSION < (0, 20, 30) else {"shape": size}
248
- return pl.Array(narwhals_to_native_dtype(dtype.inner, version), **kwargs)
249
- if isinstance_or_issubclass(dtype, dtypes.Decimal):
250
- return pl.Decimal(dtype.precision, dtype.scale)
251
- return pl.Unknown() # pragma: no cover
252
-
253
-
254
- def _is_polars_exception(exception: Exception) -> bool:
255
- if BACKEND_VERSION >= (1,):
256
- # Old versions of Polars didn't have PolarsError.
257
- return isinstance(exception, pl.exceptions.PolarsError)
258
- # Last attempt, for old Polars versions.
259
- return "polars.exceptions" in str(type(exception)) # pragma: no cover
260
-
261
-
262
- def _is_cudf_exception(exception: Exception) -> bool:
263
- # These exceptions are raised when running polars on GPUs via cuDF
264
- return str(exception).startswith("CUDF failure")
265
-
266
-
267
- def catch_polars_exception(exception: Exception) -> NarwhalsError | Exception:
268
- if isinstance(exception, pl.exceptions.ColumnNotFoundError):
269
- return ColumnNotFoundError(str(exception))
270
- if isinstance(exception, pl.exceptions.ShapeError):
271
- return ShapeError(str(exception))
272
- if isinstance(exception, pl.exceptions.InvalidOperationError):
273
- return InvalidOperationError(str(exception))
274
- if isinstance(exception, pl.exceptions.DuplicateError):
275
- return DuplicateError(str(exception))
276
- if isinstance(exception, pl.exceptions.ComputeError):
277
- return ComputeError(str(exception))
278
- if _is_polars_exception(exception) or _is_cudf_exception(exception):
279
- return NarwhalsError(str(exception)) # pragma: no cover
280
- # Just return exception as-is.
281
- return exception
282
-
283
-
284
- class PolarsAnyNamespace(
285
- _StoresCompliant[CompliantT_co],
286
- _StoresNative[NativeT_co],
287
- Protocol[CompliantT_co, NativeT_co],
288
- ):
289
- _accessor: ClassVar[Accessor]
290
-
291
- def __getattr__(self, attr: str) -> Callable[..., CompliantT_co]:
292
- def func(*args: Any, **kwargs: Any) -> CompliantT_co:
293
- pos, kwds = extract_args_kwargs(args, kwargs)
294
- method = deep_getattr(self.native, self._accessor, attr)
295
- return self.compliant._with_native(method(*pos, **kwds))
296
-
297
- return func
298
-
299
-
300
- class PolarsDateTimeNamespace(PolarsAnyNamespace[CompliantT, NativeT_co]):
301
- _accessor: ClassVar[Accessor] = "dt"
302
-
303
- def truncate(self, every: str) -> CompliantT:
304
- # Ensure consistent error message is raised.
305
- Interval.parse(every)
306
- return self.__getattr__("truncate")(every)
307
-
308
- def offset_by(self, by: str) -> CompliantT:
309
- # Ensure consistent error message is raised.
310
- Interval.parse_no_constraints(by)
311
- return self.__getattr__("offset_by")(by)
312
-
313
- to_string: Method[CompliantT]
314
- replace_time_zone: Method[CompliantT]
315
- convert_time_zone: Method[CompliantT]
316
- timestamp: Method[CompliantT]
317
- date: Method[CompliantT]
318
- year: Method[CompliantT]
319
- month: Method[CompliantT]
320
- day: Method[CompliantT]
321
- hour: Method[CompliantT]
322
- minute: Method[CompliantT]
323
- second: Method[CompliantT]
324
- millisecond: Method[CompliantT]
325
- microsecond: Method[CompliantT]
326
- nanosecond: Method[CompliantT]
327
- ordinal_day: Method[CompliantT]
328
- weekday: Method[CompliantT]
329
- total_minutes: Method[CompliantT]
330
- total_seconds: Method[CompliantT]
331
- total_milliseconds: Method[CompliantT]
332
- total_microseconds: Method[CompliantT]
333
- total_nanoseconds: Method[CompliantT]
334
-
335
-
336
- class PolarsStringNamespace(PolarsAnyNamespace[CompliantT, NativeT_co]):
337
- _accessor: ClassVar[Accessor] = "str"
338
-
339
- # NOTE: Use `abstractmethod` if we have defs to implement, but also `Method` usage
340
- @abc.abstractmethod
341
- def to_titlecase(self) -> CompliantT: ...
342
-
343
- @abc.abstractmethod
344
- def zfill(self, width: int) -> CompliantT: ...
345
-
346
- @abc.abstractmethod
347
- def slice(self, offset: int, length: int | None) -> CompliantT: ...
348
-
349
- len_chars: Method[CompliantT]
350
- replace: Method[CompliantT]
351
- replace_all: Method[CompliantT]
352
- strip_chars: Method[CompliantT]
353
- strip_chars_start: Method[CompliantT]
354
- strip_chars_end: Method[CompliantT]
355
- starts_with: Method[CompliantT]
356
- ends_with: Method[CompliantT]
357
- contains: Method[CompliantT]
358
- split: Method[CompliantT]
359
- to_date: Method[CompliantT]
360
- to_datetime: Method[CompliantT]
361
- to_time: Method[CompliantT]
362
- to_lowercase: Method[CompliantT]
363
- to_uppercase: Method[CompliantT]
364
- pad_start: Method[CompliantT]
365
- pad_end: Method[CompliantT]
366
-
367
-
368
- def native_get_categories(native: pl.Series) -> pl.Series:
369
- # NOTE: Polars deprecated `cat.get_categories` in v1.44 and removed it
370
- # in v2.0, so we use the workaround they suggest.
371
- # See https://github.com/narwhals-dev/narwhals/issues/3895.
372
- #
373
- # For `Enum`, the declared categories are already unique, ordered, and
374
- # null-free, so we can return `dtype.categories` directly.
375
- dtype = native.dtype
376
- if isinstance(dtype, pl.Enum):
377
- return dtype.categories
378
- return native.unique(maintain_order=True).drop_nulls().cast(pl.String)
379
-
380
-
381
- class PolarsCatNamespace(PolarsAnyNamespace[CompliantT, NativeT_co]):
382
- _accessor: ClassVar[Accessor] = "cat"
383
-
384
- @abc.abstractmethod
385
- def get_categories(self) -> CompliantT: ...
386
-
387
-
388
- class PolarsListNamespace(PolarsAnyNamespace[CompliantT, NativeT_co]):
389
- _accessor: ClassVar[Accessor] = "list"
390
-
391
- @abc.abstractmethod
392
- def len(self) -> CompliantT: ...
393
-
394
- get: Method[CompliantT]
395
-
396
- unique: Method[CompliantT]
397
-
398
- max: Method[CompliantT]
399
-
400
- mean: Method[CompliantT]
401
-
402
- median: Method[CompliantT]
403
-
404
- min: Method[CompliantT]
405
-
406
- sort: Method[CompliantT]
407
-
408
- sum: Method[CompliantT]
409
-
410
-
411
- class PolarsStructNamespace(PolarsAnyNamespace[CompliantT, NativeT_co]):
412
- _accessor: ClassVar[Accessor] = "struct"
413
- field: Method[CompliantT]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b29fc93ae95aef6672fa47a556e880cf4df3baf15c636c9f14a7922e4a314be/blob DELETED
@@ -1,88 +0,0 @@
1
- // Licensed to the Apache Software Foundation (ASF) under one
2
- // or more contributor license agreements. See the NOTICE file
3
- // distributed with this work for additional information
4
- // regarding copyright ownership. The ASF licenses this file
5
- // to you under the Apache License, Version 2.0 (the
6
- // "License"); you may not use this file except in compliance
7
- // with the License. You may obtain a copy of the License at
8
- //
9
- // http://www.apache.org/licenses/LICENSE-2.0
10
- //
11
- // Unless required by applicable law or agreed to in writing,
12
- // software distributed under the License is distributed on an
13
- // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
- // KIND, either express or implied. See the License for the
15
- // specific language governing permissions and limitations
16
- // under the License.
17
-
18
- #pragma once
19
-
20
- #include <cstdint>
21
-
22
- #include "arrow/util/bit_util.h"
23
- #include "arrow/util/bitmap_reader.h"
24
-
25
- namespace arrow {
26
- namespace internal {
27
-
28
- // A function that visits each bit in a bitmap and calls a visitor function with a
29
- // boolean representation of that bit. This is intended to be analogous to
30
- // GenerateBits.
31
- template <class Visitor>
32
- void VisitBits(const uint8_t* bitmap, int64_t start_offset, int64_t length,
33
- Visitor&& visit) {
34
- BitmapReader reader(bitmap, start_offset, length);
35
- for (int64_t index = 0; index < length; ++index) {
36
- visit(reader.IsSet());
37
- reader.Next();
38
- }
39
- }
40
-
41
- // Like VisitBits(), but unrolls its main loop for better performance.
42
- template <class Visitor>
43
- void VisitBitsUnrolled(const uint8_t* bitmap, int64_t start_offset, int64_t length,
44
- Visitor&& visit) {
45
- if (length == 0) {
46
- return;
47
- }
48
-
49
- // Start by visiting any bits preceding the first full byte.
50
- int64_t num_bits_before_full_bytes =
51
- bit_util::RoundUpToMultipleOf8(start_offset) - start_offset;
52
- // Truncate num_bits_before_full_bytes if it is greater than length.
53
- if (num_bits_before_full_bytes > length) {
54
- num_bits_before_full_bytes = length;
55
- }
56
- // Use the non loop-unrolled VisitBits since we don't want to add branches
57
- VisitBits<Visitor>(bitmap, start_offset, num_bits_before_full_bytes, visit);
58
-
59
- // Shift the start pointer to the first full byte and compute the
60
- // number of full bytes to be read.
61
- const uint8_t* first_full_byte = bitmap + bit_util::CeilDiv(start_offset, 8);
62
- const int64_t num_full_bytes = (length - num_bits_before_full_bytes) / 8;
63
-
64
- // Iterate over each full byte of the input bitmap and call the visitor in
65
- // a loop-unrolled manner.
66
- for (int64_t byte_index = 0; byte_index < num_full_bytes; ++byte_index) {
67
- // Get the current bit-packed byte value from the bitmap.
68
- const uint8_t byte = *(first_full_byte + byte_index);
69
-
70
- // Execute the visitor function on each bit of the current byte.
71
- visit(bit_util::GetBitFromByte(byte, 0));
72
- visit(bit_util::GetBitFromByte(byte, 1));
73
- visit(bit_util::GetBitFromByte(byte, 2));
74
- visit(bit_util::GetBitFromByte(byte, 3));
75
- visit(bit_util::GetBitFromByte(byte, 4));
76
- visit(bit_util::GetBitFromByte(byte, 5));
77
- visit(bit_util::GetBitFromByte(byte, 6));
78
- visit(bit_util::GetBitFromByte(byte, 7));
79
- }
80
-
81
- // Write any leftover bits in the last byte.
82
- const int64_t num_bits_after_full_bytes = (length - num_bits_before_full_bytes) % 8;
83
- VisitBits<Visitor>(first_full_byte + num_full_bytes, 0, num_bits_after_full_bytes,
84
- visit);
85
- }
86
-
87
- } // namespace internal
88
- } // namespace arrow
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b2c1a62c96e69385c72c6f7d5499d217c1773c48436f016e83412ea582aace6/blob DELETED
@@ -1,57 +0,0 @@
1
- #pragma once
2
-
3
- #include <functional>
4
- #include <memory>
5
-
6
- #include <c10/core/Device.h>
7
- #include <c10/util/strong_type.h>
8
- #include <torch/csrc/Export.h>
9
-
10
- struct CUevent_st;
11
-
12
- namespace torch {
13
- namespace profiler {
14
- namespace impl {
15
-
16
- // ----------------------------------------------------------------------------
17
- // -- Annotation --------------------------------------------------------------
18
- // ----------------------------------------------------------------------------
19
- using ProfilerEventStub = std::shared_ptr<CUevent_st>;
20
- using ProfilerVoidEventStub = std::shared_ptr<void>;
21
-
22
- struct TORCH_API ProfilerStubs {
23
- virtual void record(
24
- c10::DeviceIndex* device,
25
- ProfilerVoidEventStub* event,
26
- int64_t* cpu_ns) const = 0;
27
- virtual float elapsed(
28
- const ProfilerVoidEventStub* event,
29
- const ProfilerVoidEventStub* event2) const = 0;
30
- virtual void mark(const char* name) const = 0;
31
- virtual void rangePush(const char* name) const = 0;
32
- virtual void rangePop() const = 0;
33
- virtual bool enabled() const {
34
- return false;
35
- }
36
- virtual void onEachDevice(std::function<void(int)> op) const = 0;
37
- virtual void synchronize() const = 0;
38
- virtual ~ProfilerStubs();
39
- };
40
-
41
- TORCH_API void registerCUDAMethods(ProfilerStubs* stubs);
42
- TORCH_API const ProfilerStubs* cudaStubs();
43
- TORCH_API void registerITTMethods(ProfilerStubs* stubs);
44
- TORCH_API const ProfilerStubs* ittStubs();
45
- TORCH_API void registerPrivateUse1Methods(ProfilerStubs* stubs);
46
- TORCH_API const ProfilerStubs* privateuse1Stubs();
47
-
48
- using vulkan_id_t = strong::type<
49
- int64_t,
50
- struct _VulkanID,
51
- strong::regular,
52
- strong::convertible_to<int64_t>,
53
- strong::hashable>;
54
-
55
- } // namespace impl
56
- } // namespace profiler
57
- } // namespace torch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b2e55e0f1d3df31cb2b442f6a712a427eb98c9e7f9cd572eae97fd301d14f5f/blob DELETED
@@ -1,140 +0,0 @@
1
- """ Functions related to graph covers."""
2
-
3
- from functools import partial
4
- from itertools import chain
5
-
6
- import networkx as nx
7
- from networkx.utils import arbitrary_element, not_implemented_for
8
-
9
- __all__ = ["min_edge_cover", "is_edge_cover"]
10
-
11
-
12
- @not_implemented_for("directed")
13
- @not_implemented_for("multigraph")
14
- def min_edge_cover(G, matching_algorithm=None):
15
- """Returns the min cardinality edge cover of the graph as a set of edges.
16
-
17
- A smallest edge cover can be found in polynomial time by finding
18
- a maximum matching and extending it greedily so that all nodes
19
- are covered. This function follows that process. A maximum matching
20
- algorithm can be specified for the first step of the algorithm.
21
- The resulting set may return a set with one 2-tuple for each edge,
22
- (the usual case) or with both 2-tuples `(u, v)` and `(v, u)` for
23
- each edge. The latter is only done when a bipartite matching algorithm
24
- is specified as `matching_algorithm`.
25
-
26
- Parameters
27
- ----------
28
- G : NetworkX graph
29
- An undirected graph.
30
-
31
- matching_algorithm : function
32
- A function that returns a maximum cardinality matching for `G`.
33
- The function must take one input, the graph `G`, and return
34
- either a set of edges (with only one direction for the pair of nodes)
35
- or a dictionary mapping each node to its mate. If not specified,
36
- :func:`~networkx.algorithms.matching.max_weight_matching` is used.
37
- Common bipartite matching functions include
38
- :func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
39
- or
40
- :func:`~networkx.algorithms.bipartite.matching.eppstein_matching`.
41
-
42
- Returns
43
- -------
44
- min_cover : set
45
-
46
- A set of the edges in a minimum edge cover in the form of tuples.
47
- It contains only one of the equivalent 2-tuples `(u, v)` and `(v, u)`
48
- for each edge. If a bipartite method is used to compute the matching,
49
- the returned set contains both the 2-tuples `(u, v)` and `(v, u)`
50
- for each edge of a minimum edge cover.
51
-
52
- Examples
53
- --------
54
- >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
55
- >>> sorted(nx.min_edge_cover(G))
56
- [(2, 1), (3, 0)]
57
-
58
- Notes
59
- -----
60
- An edge cover of a graph is a set of edges such that every node of
61
- the graph is incident to at least one edge of the set.
62
- The minimum edge cover is an edge covering of smallest cardinality.
63
-
64
- Due to its implementation, the worst-case running time of this algorithm
65
- is bounded by the worst-case running time of the function
66
- ``matching_algorithm``.
67
-
68
- Minimum edge cover for `G` can also be found using the `min_edge_covering`
69
- function in :mod:`networkx.algorithms.bipartite.covering` which is
70
- simply this function with a default matching algorithm of
71
- :func:`~networkx.algorithms.bipartite.matching.hopcraft_karp_matching`
72
- """
73
- if len(G) == 0:
74
- return set()
75
- if nx.number_of_isolates(G) > 0:
76
- # ``min_cover`` does not exist as there is an isolated node
77
- raise nx.NetworkXException(
78
- "Graph has a node with no edge incident on it, " "so no edge cover exists."
79
- )
80
- if matching_algorithm is None:
81
- matching_algorithm = partial(nx.max_weight_matching, maxcardinality=True)
82
- maximum_matching = matching_algorithm(G)
83
- # ``min_cover`` is superset of ``maximum_matching``
84
- try:
85
- # bipartite matching algs return dict so convert if needed
86
- min_cover = set(maximum_matching.items())
87
- bipartite_cover = True
88
- except AttributeError:
89
- min_cover = maximum_matching
90
- bipartite_cover = False
91
- # iterate for uncovered nodes
92
- uncovered_nodes = set(G) - {v for u, v in min_cover} - {u for u, v in min_cover}
93
- for v in uncovered_nodes:
94
- # Since `v` is uncovered, each edge incident to `v` will join it
95
- # with a covered node (otherwise, if there were an edge joining
96
- # uncovered nodes `u` and `v`, the maximum matching algorithm
97
- # would have found it), so we can choose an arbitrary edge
98
- # incident to `v`. (This applies only in a simple graph, not a
99
- # multigraph.)
100
- u = arbitrary_element(G[v])
101
- min_cover.add((u, v))
102
- if bipartite_cover:
103
- min_cover.add((v, u))
104
- return min_cover
105
-
106
-
107
- @not_implemented_for("directed")
108
- def is_edge_cover(G, cover):
109
- """Decides whether a set of edges is a valid edge cover of the graph.
110
-
111
- Given a set of edges, whether it is an edge covering can
112
- be decided if we just check whether all nodes of the graph
113
- has an edge from the set, incident on it.
114
-
115
- Parameters
116
- ----------
117
- G : NetworkX graph
118
- An undirected bipartite graph.
119
-
120
- cover : set
121
- Set of edges to be checked.
122
-
123
- Returns
124
- -------
125
- bool
126
- Whether the set of edges is a valid edge cover of the graph.
127
-
128
- Examples
129
- --------
130
- >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
131
- >>> cover = {(2, 1), (3, 0)}
132
- >>> nx.is_edge_cover(G, cover)
133
- True
134
-
135
- Notes
136
- -----
137
- An edge cover of a graph is a set of edges such that every node of
138
- the graph is incident to at least one edge of the set.
139
- """
140
- return set(G) <= set(chain.from_iterable(cover))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b2f91be34024fbcf645f6ef92460e5f944ca6a16268b79478ab904b2934d357/blob DELETED
@@ -1,52 +0,0 @@
1
- # created by tools/loadICU.tcl -- do not edit
2
- namespace eval ::tcl::clock {
3
- ::msgcat::mcset el DAYS_OF_WEEK_ABBREV [list \
4
- "\u039a\u03c5\u03c1"\
5
- "\u0394\u03b5\u03c5"\
6
- "\u03a4\u03c1\u03b9"\
7
- "\u03a4\u03b5\u03c4"\
8
- "\u03a0\u03b5\u03bc"\
9
- "\u03a0\u03b1\u03c1"\
10
- "\u03a3\u03b1\u03b2"]
11
- ::msgcat::mcset el DAYS_OF_WEEK_FULL [list \
12
- "\u039a\u03c5\u03c1\u03b9\u03b1\u03ba\u03ae"\
13
- "\u0394\u03b5\u03c5\u03c4\u03ad\u03c1\u03b1"\
14
- "\u03a4\u03c1\u03af\u03c4\u03b7"\
15
- "\u03a4\u03b5\u03c4\u03ac\u03c1\u03c4\u03b7"\
16
- "\u03a0\u03ad\u03bc\u03c0\u03c4\u03b7"\
17
- "\u03a0\u03b1\u03c1\u03b1\u03c3\u03ba\u03b5\u03c5\u03ae"\
18
- "\u03a3\u03ac\u03b2\u03b2\u03b1\u03c4\u03bf"]
19
- ::msgcat::mcset el MONTHS_ABBREV [list \
20
- "\u0399\u03b1\u03bd"\
21
- "\u03a6\u03b5\u03b2"\
22
- "\u039c\u03b1\u03c1"\
23
- "\u0391\u03c0\u03c1"\
24
- "\u039c\u03b1\u03ca"\
25
- "\u0399\u03bf\u03c5\u03bd"\
26
- "\u0399\u03bf\u03c5\u03bb"\
27
- "\u0391\u03c5\u03b3"\
28
- "\u03a3\u03b5\u03c0"\
29
- "\u039f\u03ba\u03c4"\
30
- "\u039d\u03bf\u03b5"\
31
- "\u0394\u03b5\u03ba"\
32
- ""]
33
- ::msgcat::mcset el MONTHS_FULL [list \
34
- "\u0399\u03b1\u03bd\u03bf\u03c5\u03ac\u03c1\u03b9\u03bf\u03c2"\
35
- "\u03a6\u03b5\u03b2\u03c1\u03bf\u03c5\u03ac\u03c1\u03b9\u03bf\u03c2"\
36
- "\u039c\u03ac\u03c1\u03c4\u03b9\u03bf\u03c2"\
37
- "\u0391\u03c0\u03c1\u03af\u03bb\u03b9\u03bf\u03c2"\
38
- "\u039c\u03ac\u03ca\u03bf\u03c2"\
39
- "\u0399\u03bf\u03cd\u03bd\u03b9\u03bf\u03c2"\
40
- "\u0399\u03bf\u03cd\u03bb\u03b9\u03bf\u03c2"\
41
- "\u0391\u03cd\u03b3\u03bf\u03c5\u03c3\u03c4\u03bf\u03c2"\
42
- "\u03a3\u03b5\u03c0\u03c4\u03ad\u03bc\u03b2\u03c1\u03b9\u03bf\u03c2"\
43
- "\u039f\u03ba\u03c4\u03ce\u03b2\u03c1\u03b9\u03bf\u03c2"\
44
- "\u039d\u03bf\u03ad\u03bc\u03b2\u03c1\u03b9\u03bf\u03c2"\
45
- "\u0394\u03b5\u03ba\u03ad\u03bc\u03b2\u03c1\u03b9\u03bf\u03c2"\
46
- ""]
47
- ::msgcat::mcset el AM "\u03c0\u03bc"
48
- ::msgcat::mcset el PM "\u03bc\u03bc"
49
- ::msgcat::mcset el DATE_FORMAT "%e/%m/%Y"
50
- ::msgcat::mcset el TIME_FORMAT_12 "%l:%M:%S %P"
51
- ::msgcat::mcset el DATE_TIME_FORMAT "%e/%m/%Y %l:%M:%S %P %z"
52
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b2ff15cb3d217ce7ef0b06547f16743aef6d5363072c505bff85d03e769596e/blob DELETED
@@ -1,360 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: pyOpenSSL
3
- Version: 24.0.0
4
- Summary: Python wrapper module around the OpenSSL library
5
- Home-page: https://pyopenssl.org/
6
- Author: The pyOpenSSL developers
7
- Author-email: cryptography-dev@python.org
8
- License: Apache License, Version 2.0
9
- Project-URL: Source, https://github.com/pyca/pyopenssl
10
- Classifier: Development Status :: 6 - Mature
11
- Classifier: Intended Audience :: Developers
12
- Classifier: License :: OSI Approved :: Apache Software License
13
- Classifier: Operating System :: MacOS :: MacOS X
14
- Classifier: Operating System :: Microsoft :: Windows
15
- Classifier: Operating System :: POSIX
16
- Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.7
18
- Classifier: Programming Language :: Python :: 3.8
19
- Classifier: Programming Language :: Python :: 3.9
20
- Classifier: Programming Language :: Python :: 3.10
21
- Classifier: Programming Language :: Python :: 3.11
22
- Classifier: Programming Language :: Python :: 3.12
23
- Classifier: Programming Language :: Python :: Implementation :: CPython
24
- Classifier: Programming Language :: Python :: Implementation :: PyPy
25
- Classifier: Topic :: Security :: Cryptography
26
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
- Classifier: Topic :: System :: Networking
28
- Requires-Python: >=3.7
29
- License-File: LICENSE
30
- Requires-Dist: cryptography <43,>=41.0.5
31
- Provides-Extra: docs
32
- Requires-Dist: sphinx !=5.2.0,!=5.2.0.post0,!=7.2.5 ; extra == 'docs'
33
- Requires-Dist: sphinx-rtd-theme ; extra == 'docs'
34
- Provides-Extra: test
35
- Requires-Dist: flaky ; extra == 'test'
36
- Requires-Dist: pretend ; extra == 'test'
37
- Requires-Dist: pytest >=3.0.1 ; extra == 'test'
38
-
39
- ========================================================
40
- pyOpenSSL -- A Python wrapper around the OpenSSL library
41
- ========================================================
42
-
43
- .. image:: https://readthedocs.org/projects/pyopenssl/badge/?version=stable
44
- :target: https://pyopenssl.org/en/stable/
45
- :alt: Stable Docs
46
-
47
- .. image:: https://github.com/pyca/pyopenssl/workflows/CI/badge.svg?branch=main
48
- :target: https://github.com/pyca/pyopenssl/actions?query=workflow%3ACI+branch%3Amain
49
-
50
- .. image:: https://codecov.io/github/pyca/pyopenssl/branch/main/graph/badge.svg
51
- :target: https://codecov.io/github/pyca/pyopenssl
52
- :alt: Test coverage
53
-
54
- **Note:** The Python Cryptographic Authority **strongly suggests** the use of `pyca/cryptography`_
55
- where possible. If you are using pyOpenSSL for anything other than making a TLS connection
56
- **you should move to cryptography and drop your pyOpenSSL dependency**.
57
-
58
- High-level wrapper around a subset of the OpenSSL library. Includes
59
-
60
- * ``SSL.Connection`` objects, wrapping the methods of Python's portable sockets
61
- * Callbacks written in Python
62
- * Extensive error-handling mechanism, mirroring OpenSSL's error codes
63
-
64
- ... and much more.
65
-
66
- You can find more information in the documentation_.
67
- Development takes place on GitHub_.
68
-
69
-
70
- Discussion
71
- ==========
72
-
73
- If you run into bugs, you can file them in our `issue tracker`_.
74
-
75
- We maintain a cryptography-dev_ mailing list for both user and development discussions.
76
-
77
- You can also join ``#pyca`` on ``irc.libera.chat`` to ask questions or get involved.
78
-
79
-
80
- .. _documentation: https://pyopenssl.org/
81
- .. _`issue tracker`: https://github.com/pyca/pyopenssl/issues
82
- .. _cryptography-dev: https://mail.python.org/mailman/listinfo/cryptography-dev
83
- .. _GitHub: https://github.com/pyca/pyopenssl
84
- .. _`pyca/cryptography`: https://github.com/pyca/cryptography
85
-
86
-
87
- Release Information
88
- ===================
89
-
90
- 24.0.0 (2024-01-22)
91
- -------------------
92
-
93
- Backward-incompatible changes:
94
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
95
-
96
- Deprecations:
97
- ^^^^^^^^^^^^^
98
-
99
- Changes:
100
- ^^^^^^^^
101
-
102
- - Added ``OpenSSL.SSL.Connection.get_selected_srtp_profile`` to determine which SRTP profile was negotiated.
103
- `#1279 <https://github.com/pyca/pyopenssl/pull/1279>`_.
104
-
105
- 23.3.0 (2023-10-25)
106
- -------------------
107
-
108
- Backward-incompatible changes:
109
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
110
-
111
- - Dropped support for Python 3.6.
112
- - The minimum ``cryptography`` version is now 41.0.5.
113
- - Removed ``OpenSSL.crypto.loads_pkcs7`` and ``OpenSSL.crypto.loads_pkcs12`` which had been deprecated for 3 years.
114
- - Added ``OpenSSL.SSL.OP_LEGACY_SERVER_CONNECT`` to allow legacy insecure renegotiation between OpenSSL and unpatched servers.
115
- `#1234 <https://github.com/pyca/pyopenssl/pull/1234>`_.
116
-
117
- Deprecations:
118
- ^^^^^^^^^^^^^
119
-
120
- - Deprecated ``OpenSSL.crypto.PKCS12`` (which was intended to have been deprecated at the same time as ``OpenSSL.crypto.load_pkcs12``).
121
- - Deprecated ``OpenSSL.crypto.NetscapeSPKI``.
122
- - Deprecated ``OpenSSL.crypto.CRL``
123
- - Deprecated ``OpenSSL.crypto.Revoked``
124
- - Deprecated ``OpenSSL.crypto.load_crl`` and ``OpenSSL.crypto.dump_crl``
125
- - Deprecated ``OpenSSL.crypto.sign`` and ``OpenSSL.crypto.verify``
126
- - Deprecated ``OpenSSL.crypto.X509Extension``
127
-
128
- Changes:
129
- ^^^^^^^^
130
-
131
- - Changed ``OpenSSL.crypto.X509Store.add_crl`` to also accept
132
- ``cryptography``'s ``x509.CertificateRevocationList`` arguments in addition
133
- to the now deprecated ``OpenSSL.crypto.CRL`` arguments.
134
- - Fixed ``test_set_default_verify_paths`` test so that it is skipped if no
135
- network connection is available.
136
-
137
- 23.2.0 (2023-05-30)
138
- -------------------
139
-
140
- Backward-incompatible changes:
141
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
142
-
143
- - Removed ``X509StoreFlags.NOTIFY_POLICY``.
144
- `#1213 <https://github.com/pyca/pyopenssl/pull/1213>`_.
145
-
146
- Deprecations:
147
- ^^^^^^^^^^^^^
148
-
149
- Changes:
150
- ^^^^^^^^
151
-
152
- - ``cryptography`` maximum version has been increased to 41.0.x.
153
- - Invalid versions are now rejected in ``OpenSSL.crypto.X509Req.set_version``.
154
- - Added ``X509VerificationCodes`` to ``OpenSSL.SSL``.
155
- `#1202 <https://github.com/pyca/pyopenssl/pull/1202>`_.
156
-
157
- 23.1.1 (2023-03-28)
158
- -------------------
159
-
160
- Backward-incompatible changes:
161
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
162
-
163
- Deprecations:
164
- ^^^^^^^^^^^^^
165
-
166
- Changes:
167
- ^^^^^^^^
168
-
169
- - Worked around an issue in OpenSSL 3.1.0 which caused `X509Extension.get_short_name` to raise an exception when no short name was known to OpenSSL.
170
- `#1204 <https://github.com/pyca/pyopenssl/pull/1204>`_.
171
-
172
- 23.1.0 (2023-03-24)
173
- -------------------
174
-
175
- Backward-incompatible changes:
176
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
177
-
178
- Deprecations:
179
- ^^^^^^^^^^^^^
180
-
181
- Changes:
182
- ^^^^^^^^
183
-
184
- - ``cryptography`` maximum version has been increased to 40.0.x.
185
- - Add ``OpenSSL.SSL.Connection.DTLSv1_get_timeout`` and ``OpenSSL.SSL.Connection.DTLSv1_handle_timeout``
186
- to support DTLS timeouts `#1180 <https://github.com/pyca/pyopenssl/pull/1180>`_.
187
-
188
- 23.0.0 (2023-01-01)
189
- -------------------
190
-
191
- Backward-incompatible changes:
192
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
193
-
194
- Deprecations:
195
- ^^^^^^^^^^^^^
196
-
197
- Changes:
198
- ^^^^^^^^
199
-
200
- - Add ``OpenSSL.SSL.X509StoreFlags.PARTIAL_CHAIN`` constant to allow for users
201
- to perform certificate verification on partial certificate chains.
202
- `#1166 <https://github.com/pyca/pyopenssl/pull/1166>`_
203
- - ``cryptography`` maximum version has been increased to 39.0.x.
204
-
205
- 22.1.0 (2022-09-25)
206
- -------------------
207
-
208
- Backward-incompatible changes:
209
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
210
-
211
- - Remove support for SSLv2 and SSLv3.
212
- - The minimum ``cryptography`` version is now 38.0.x (and we now pin releases
213
- against ``cryptography`` major versions to prevent future breakage)
214
- - The ``OpenSSL.crypto.X509StoreContextError`` exception has been refactored,
215
- changing its internal attributes.
216
- `#1133 <https://github.com/pyca/pyopenssl/pull/1133>`_
217
-
218
- Deprecations:
219
- ^^^^^^^^^^^^^
220
-
221
- - ``OpenSSL.SSL.SSLeay_version`` is deprecated in favor of
222
- ``OpenSSL.SSL.OpenSSL_version``. The constants ``OpenSSL.SSL.SSLEAY_*`` are
223
- deprecated in favor of ``OpenSSL.SSL.OPENSSL_*``.
224
-
225
- Changes:
226
- ^^^^^^^^
227
-
228
- - Add ``OpenSSL.SSL.Connection.set_verify`` and ``OpenSSL.SSL.Connection.get_verify_mode``
229
- to override the context object's verification flags.
230
- `#1073 <https://github.com/pyca/pyopenssl/pull/1073>`_
231
- - Add ``OpenSSL.SSL.Connection.use_certificate`` and ``OpenSSL.SSL.Connection.use_privatekey``
232
- to set a certificate per connection (and not just per context) `#1121 <https://github.com/pyca/pyopenssl/pull/1121>`_.
233
-
234
- 22.0.0 (2022-01-29)
235
- -------------------
236
-
237
- Backward-incompatible changes:
238
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
239
-
240
- - Drop support for Python 2.7.
241
- `#1047 <https://github.com/pyca/pyopenssl/pull/1047>`_
242
- - The minimum ``cryptography`` version is now 35.0.
243
-
244
- Deprecations:
245
- ^^^^^^^^^^^^^
246
-
247
- Changes:
248
- ^^^^^^^^
249
-
250
- - Expose wrappers for some `DTLS
251
- <https://en.wikipedia.org/wiki/Datagram_Transport_Layer_Security>`_
252
- primitives. `#1026 <https://github.com/pyca/pyopenssl/pull/1026>`_
253
-
254
- 21.0.0 (2021-09-28)
255
- -------------------
256
-
257
- Backward-incompatible changes:
258
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
259
-
260
- - The minimum ``cryptography`` version is now 3.3.
261
- - Drop support for Python 3.5
262
-
263
- Deprecations:
264
- ^^^^^^^^^^^^^
265
-
266
- Changes:
267
- ^^^^^^^^
268
-
269
- - Raise an error when an invalid ALPN value is set.
270
- `#993 <https://github.com/pyca/pyopenssl/pull/993>`_
271
- - Added ``OpenSSL.SSL.Context.set_min_proto_version`` and ``OpenSSL.SSL.Context.set_max_proto_version``
272
- to set the minimum and maximum supported TLS version `#985 <https://github.com/pyca/pyopenssl/pull/985>`_.
273
- - Updated ``to_cryptography`` and ``from_cryptography`` methods to support an upcoming release of ``cryptography`` without raising deprecation warnings.
274
- `#1030 <https://github.com/pyca/pyopenssl/pull/1030>`_
275
-
276
- 20.0.1 (2020-12-15)
277
- -------------------
278
-
279
- Backward-incompatible changes:
280
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
281
-
282
- Deprecations:
283
- ^^^^^^^^^^^^^
284
-
285
- Changes:
286
- ^^^^^^^^
287
-
288
- - Fixed compatibility with OpenSSL 1.1.0.
289
-
290
- 20.0.0 (2020-11-27)
291
- -------------------
292
-
293
-
294
- Backward-incompatible changes:
295
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
296
-
297
- - The minimum ``cryptography`` version is now 3.2.
298
- - Remove deprecated ``OpenSSL.tsafe`` module.
299
- - Removed deprecated ``OpenSSL.SSL.Context.set_npn_advertise_callback``, ``OpenSSL.SSL.Context.set_npn_select_callback``, and ``OpenSSL.SSL.Connection.get_next_proto_negotiated``.
300
- - Drop support for Python 3.4
301
- - Drop support for OpenSSL 1.0.1 and 1.0.2
302
-
303
- Deprecations:
304
- ^^^^^^^^^^^^^
305
-
306
- - Deprecated ``OpenSSL.crypto.loads_pkcs7`` and ``OpenSSL.crypto.loads_pkcs12``.
307
-
308
- Changes:
309
- ^^^^^^^^
310
-
311
- - Added a new optional ``chain`` parameter to ``OpenSSL.crypto.X509StoreContext()``
312
- where additional untrusted certificates can be specified to help chain building.
313
- `#948 <https://github.com/pyca/pyopenssl/pull/948>`_
314
- - Added ``OpenSSL.crypto.X509Store.load_locations`` to set trusted
315
- certificate file bundles and/or directories for verification.
316
- `#943 <https://github.com/pyca/pyopenssl/pull/943>`_
317
- - Added ``Context.set_keylog_callback`` to log key material.
318
- `#910 <https://github.com/pyca/pyopenssl/pull/910>`_
319
- - Added ``OpenSSL.SSL.Connection.get_verified_chain`` to retrieve the
320
- verified certificate chain of the peer.
321
- `#894 <https://github.com/pyca/pyopenssl/pull/894>`_.
322
- - Make verification callback optional in ``Context.set_verify``.
323
- If omitted, OpenSSL's default verification is used.
324
- `#933 <https://github.com/pyca/pyopenssl/pull/933>`_
325
- - Fixed a bug that could truncate or cause a zero-length key error due to a
326
- null byte in private key passphrase in ``OpenSSL.crypto.load_privatekey``
327
- and ``OpenSSL.crypto.dump_privatekey``.
328
- `#947 <https://github.com/pyca/pyopenssl/pull/947>`_
329
-
330
- 19.1.0 (2019-11-18)
331
- -------------------
332
-
333
-
334
- Backward-incompatible changes:
335
- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336
-
337
- - Removed deprecated ``ContextType``, ``ConnectionType``, ``PKeyType``, ``X509NameType``, ``X509ReqType``, ``X509Type``, ``X509StoreType``, ``CRLType``, ``PKCS7Type``, ``PKCS12Type``, and ``NetscapeSPKIType`` aliases.
338
- Use the classes without the ``Type`` suffix instead.
339
- `#814 <https://github.com/pyca/pyopenssl/pull/814>`_
340
- - The minimum ``cryptography`` version is now 2.8 due to issues on macOS with a transitive dependency.
341
- `#875 <https://github.com/pyca/pyopenssl/pull/875>`_
342
-
343
- Deprecations:
344
- ^^^^^^^^^^^^^
345
-
346
- - Deprecated ``OpenSSL.SSL.Context.set_npn_advertise_callback``, ``OpenSSL.SSL.Context.set_npn_select_callback``, and ``OpenSSL.SSL.Connection.get_next_proto_negotiated``.
347
- ALPN should be used instead.
348
- `#820 <https://github.com/pyca/pyopenssl/pull/820>`_
349
-
350
-
351
- Changes:
352
- ^^^^^^^^
353
-
354
- - Support ``bytearray`` in ``SSL.Connection.send()`` by using cffi's from_buffer.
355
- `#852 <https://github.com/pyca/pyopenssl/pull/852>`_
356
- - The ``OpenSSL.SSL.Context.set_alpn_select_callback`` can return a new ``NO_OVERLAPPING_PROTOCOLS`` sentinel value
357
- to allow a TLS handshake to complete without an application protocol.
358
-
359
- `Full changelog <https://pyopenssl.org/en/stable/changelog.html>`_.
360
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b34108030dba74e01d372b226ba2cb0ba7c62aef6449ce3a7edc0adf8db307f/blob DELETED
@@ -1,188 +0,0 @@
1
- try:
2
- from ctypes import c_float, c_int, c_double
3
- except ImportError:
4
- pass
5
-
6
- import pyglet.gl as pgl
7
- from sympy.core import S
8
-
9
-
10
- def get_model_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv):
11
- """
12
- Returns the current modelview matrix.
13
- """
14
- m = (array_type*16)()
15
- glGetMethod(pgl.GL_MODELVIEW_MATRIX, m)
16
- return m
17
-
18
-
19
- def get_projection_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv):
20
- """
21
- Returns the current modelview matrix.
22
- """
23
- m = (array_type*16)()
24
- glGetMethod(pgl.GL_PROJECTION_MATRIX, m)
25
- return m
26
-
27
-
28
- def get_viewport():
29
- """
30
- Returns the current viewport.
31
- """
32
- m = (c_int*4)()
33
- pgl.glGetIntegerv(pgl.GL_VIEWPORT, m)
34
- return m
35
-
36
-
37
- def get_direction_vectors():
38
- m = get_model_matrix()
39
- return ((m[0], m[4], m[8]),
40
- (m[1], m[5], m[9]),
41
- (m[2], m[6], m[10]))
42
-
43
-
44
- def get_view_direction_vectors():
45
- m = get_model_matrix()
46
- return ((m[0], m[1], m[2]),
47
- (m[4], m[5], m[6]),
48
- (m[8], m[9], m[10]))
49
-
50
-
51
- def get_basis_vectors():
52
- return ((1, 0, 0), (0, 1, 0), (0, 0, 1))
53
-
54
-
55
- def screen_to_model(x, y, z):
56
- m = get_model_matrix(c_double, pgl.glGetDoublev)
57
- p = get_projection_matrix(c_double, pgl.glGetDoublev)
58
- w = get_viewport()
59
- mx, my, mz = c_double(), c_double(), c_double()
60
- pgl.gluUnProject(x, y, z, m, p, w, mx, my, mz)
61
- return float(mx.value), float(my.value), float(mz.value)
62
-
63
-
64
- def model_to_screen(x, y, z):
65
- m = get_model_matrix(c_double, pgl.glGetDoublev)
66
- p = get_projection_matrix(c_double, pgl.glGetDoublev)
67
- w = get_viewport()
68
- mx, my, mz = c_double(), c_double(), c_double()
69
- pgl.gluProject(x, y, z, m, p, w, mx, my, mz)
70
- return float(mx.value), float(my.value), float(mz.value)
71
-
72
-
73
- def vec_subs(a, b):
74
- return tuple(a[i] - b[i] for i in range(len(a)))
75
-
76
-
77
- def billboard_matrix():
78
- """
79
- Removes rotational components of
80
- current matrix so that primitives
81
- are always drawn facing the viewer.
82
-
83
- |1|0|0|x|
84
- |0|1|0|x|
85
- |0|0|1|x| (x means left unchanged)
86
- |x|x|x|x|
87
- """
88
- m = get_model_matrix()
89
- # XXX: for i in range(11): m[i] = i ?
90
- m[0] = 1
91
- m[1] = 0
92
- m[2] = 0
93
- m[4] = 0
94
- m[5] = 1
95
- m[6] = 0
96
- m[8] = 0
97
- m[9] = 0
98
- m[10] = 1
99
- pgl.glLoadMatrixf(m)
100
-
101
-
102
- def create_bounds():
103
- return [[S.Infinity, S.NegativeInfinity, 0],
104
- [S.Infinity, S.NegativeInfinity, 0],
105
- [S.Infinity, S.NegativeInfinity, 0]]
106
-
107
-
108
- def update_bounds(b, v):
109
- if v is None:
110
- return
111
- for axis in range(3):
112
- b[axis][0] = min([b[axis][0], v[axis]])
113
- b[axis][1] = max([b[axis][1], v[axis]])
114
-
115
-
116
- def interpolate(a_min, a_max, a_ratio):
117
- return a_min + a_ratio * (a_max - a_min)
118
-
119
-
120
- def rinterpolate(a_min, a_max, a_value):
121
- a_range = a_max - a_min
122
- if a_max == a_min:
123
- a_range = 1.0
124
- return (a_value - a_min) / float(a_range)
125
-
126
-
127
- def interpolate_color(color1, color2, ratio):
128
- return tuple(interpolate(color1[i], color2[i], ratio) for i in range(3))
129
-
130
-
131
- def scale_value(v, v_min, v_len):
132
- return (v - v_min) / v_len
133
-
134
-
135
- def scale_value_list(flist):
136
- v_min, v_max = min(flist), max(flist)
137
- v_len = v_max - v_min
138
- return [scale_value(f, v_min, v_len) for f in flist]
139
-
140
-
141
- def strided_range(r_min, r_max, stride, max_steps=50):
142
- o_min, o_max = r_min, r_max
143
- if abs(r_min - r_max) < 0.001:
144
- return []
145
- try:
146
- range(int(r_min - r_max))
147
- except (TypeError, OverflowError):
148
- return []
149
- if r_min > r_max:
150
- raise ValueError("r_min cannot be greater than r_max")
151
- r_min_s = (r_min % stride)
152
- r_max_s = stride - (r_max % stride)
153
- if abs(r_max_s - stride) < 0.001:
154
- r_max_s = 0.0
155
- r_min -= r_min_s
156
- r_max += r_max_s
157
- r_steps = int((r_max - r_min)/stride)
158
- if max_steps and r_steps > max_steps:
159
- return strided_range(o_min, o_max, stride*2)
160
- return [r_min] + [r_min + e*stride for e in range(1, r_steps + 1)] + [r_max]
161
-
162
-
163
- def parse_option_string(s):
164
- if not isinstance(s, str):
165
- return None
166
- options = {}
167
- for token in s.split(';'):
168
- pieces = token.split('=')
169
- if len(pieces) == 1:
170
- option, value = pieces[0], ""
171
- elif len(pieces) == 2:
172
- option, value = pieces
173
- else:
174
- raise ValueError("Plot option string '%s' is malformed." % (s))
175
- options[option.strip()] = value.strip()
176
- return options
177
-
178
-
179
- def dot_product(v1, v2):
180
- return sum(v1[i]*v2[i] for i in range(3))
181
-
182
-
183
- def vec_sub(v1, v2):
184
- return tuple(v1[i] - v2[i] for i in range(3))
185
-
186
-
187
- def vec_mag(v):
188
- return sum(v[i]**2 for i in range(3))**(0.5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b3bb70cade8184ee8eca3239aa7e6762ad6be906e15e8ea42ed5629b8abdafa/blob DELETED
@@ -1,200 +0,0 @@
1
- /* Translated from Cython into C++ by SciPy developers in 2024.
2
- * Original header with Copyright information appears below.
3
- */
4
-
5
- /* Implementation of sin/cos/sinh/cosh integrals for complex arguments
6
- *
7
- * Sources
8
- * [1] Fredrik Johansson and others. mpmath: a Python library for
9
- * arbitrary-precision floating-point arithmetic (version 0.19),
10
- * December 2013. http://mpmath.org/.
11
- * [2] NIST, "Digital Library of Mathematical Functions",
12
- * https://dlmf.nist.gov/
13
- */
14
-
15
- #pragma once
16
-
17
- #include "config.h"
18
- #include "error.h"
19
-
20
- #include "expint.h"
21
- #include "cephes/const.h"
22
- #include "cephes/sici.h"
23
- #include "cephes/shichi.h"
24
-
25
- namespace xsf {
26
- namespace detail {
27
-
28
- XSF_HOST_DEVICE inline void sici_power_series(int sgn, std::complex<double> z,
29
- std::complex<double> *s, std::complex<double> *c) {
30
- /* DLMF 6.6.5 and 6.6.6. If sgn = -1 computes si/ci, and if sgn = 1
31
- * computes shi/chi.
32
- */
33
- std::complex<double> fac = z;
34
- *s = fac;
35
- *c = 0;
36
- std::complex<double> term1, term2;
37
- for (int n = 1; n < 100; n++) {
38
- fac *= static_cast<double>(sgn)*z/(2.0*n);
39
- term2 = fac/(2.0*n);
40
- *c += term2;
41
- fac *= z/(2.0*n + 1.0);
42
- term1 = fac/(2.0*n + 1.0);
43
- *s += term1;
44
- constexpr double tol = std::numeric_limits<double>::epsilon();
45
- if (std::abs(term1) < tol*std::abs(*s) && std::abs(term2) < tol*std::abs(*c)) {
46
- break;
47
- }
48
- }
49
- }
50
-
51
- }
52
-
53
-
54
- XSF_HOST_DEVICE inline int sici(std::complex<double> z,
55
- std::complex<double> *si, std::complex<double> *ci) {
56
- /* Compute sin/cos integrals at complex arguments. The algorithm
57
- * largely follows that of [1].
58
- */
59
-
60
- constexpr double EULER = xsf::cephes::detail::SCIPY_EULER;
61
-
62
- if (z == std::numeric_limits<double>::infinity()) {
63
- *si = M_PI_2;
64
- *ci = 0;
65
- return 0;
66
- }
67
- if (z == -std::numeric_limits<double>::infinity()) {
68
- *si = -M_PI_2;
69
- *ci = {0.0, M_PI};
70
- return 0;
71
- }
72
-
73
- if (std::abs(z) < 0.8) {
74
- // Use the series to avoid cancellation in si
75
- detail::sici_power_series(-1, z, si, ci);
76
-
77
- if (z == 0.0) {
78
- set_error("sici", SF_ERROR_DOMAIN, NULL);
79
- *ci = {-std::numeric_limits<double>::infinity(), std::numeric_limits<double>::quiet_NaN()};
80
- } else {
81
- *ci += EULER + std::log(z);
82
- }
83
- return 0;
84
- }
85
-
86
- // DLMF 6.5.5/6.5.6 plus DLMF 6.4.4/6.4.6/6.4.7
87
- std::complex<double> jz = std::complex<double>(0.0, 1.0) * z;
88
- std::complex<double> term1 = expi(jz);
89
- std::complex<double> term2 = expi(-jz);
90
- *si = std::complex<double>(0.0, -0.5)*(term1 - term2);
91
- *ci = 0.5*(term1 + term2);
92
- if (z.real() == 0) {
93
- if (z.imag() > 0) {
94
- *ci += std::complex<double>(0.0, M_PI_2);
95
- } else if (z.imag() < 0) {
96
- *ci -= std::complex<double>(0.0, M_PI_2);
97
- }
98
- } else if (z.real() > 0) {
99
- *si -= M_PI_2;
100
- } else {
101
- *si += M_PI_2;
102
- if (z.imag() >= 0) {
103
- *ci += std::complex<double>(0.0, M_PI);
104
- } else {
105
- *ci -= std::complex<double>(0.0, M_PI);
106
- }
107
- }
108
- return 0;
109
- }
110
-
111
- XSF_HOST_DEVICE inline int sici(std::complex<float> z,
112
- std::complex<float> *si_f, std::complex<float> *ci_f) {
113
- std::complex<double> si;
114
- std::complex<double> ci;
115
- int res = sici(z, &si, &ci);
116
- *si_f = si;
117
- *ci_f = ci;
118
- return res;
119
- }
120
-
121
- XSF_HOST_DEVICE inline int shichi(std::complex<double> z,
122
- std::complex<double> *shi, std::complex<double> *chi) {
123
- /* Compute sinh/cosh integrals at complex arguments. The algorithm
124
- * largely follows that of [1].
125
- */
126
- constexpr double EULER = xsf::cephes::detail::SCIPY_EULER;
127
- if (z == std::numeric_limits<double>::infinity()) {
128
- *shi = std::numeric_limits<double>::infinity();
129
- *chi = std::numeric_limits<double>::infinity();
130
- return 0;
131
- }
132
- if (z == -std::numeric_limits<double>::infinity()) {
133
- *shi = -std::numeric_limits<double>::infinity();
134
- *chi = std::numeric_limits<double>::infinity();
135
- return 0;
136
- }
137
- if (std::abs(z) < 0.8) {
138
- // Use the series to avoid cancellation in shi
139
- detail::sici_power_series(1, z, shi, chi);
140
- if (z == 0.0) {
141
- set_error("shichi", SF_ERROR_DOMAIN, NULL);
142
- *chi = {-std::numeric_limits<double>::infinity(), std::numeric_limits<double>::quiet_NaN()};
143
- } else {
144
- *chi += EULER + std::log(z);
145
- }
146
- return 0;
147
- }
148
-
149
- std::complex<double> term1 = expi(z);
150
- std::complex<double> term2 = expi(-z);
151
- *shi = 0.5*(term1 - term2);
152
- *chi = 0.5*(term1 + term2);
153
- if (z.imag() > 0) {
154
- *shi -= std::complex<double>(0.0, 0.5*M_PI);
155
- *chi += std::complex<double>(0.0, 0.5*M_PI);
156
- } else if (z.imag() < 0) {
157
- *shi += std::complex<double>(0.0, 0.5*M_PI);
158
- *chi -= std::complex<double>(0.0, 0.5*M_PI);
159
- } else if (z.real() < 0) {
160
- *chi += std::complex<double>(0.0, M_PI);
161
- }
162
- return 0;
163
- }
164
-
165
- XSF_HOST_DEVICE inline int shichi(std::complex<float> z,
166
- std::complex<float> *shi_f, std::complex<float> *chi_f) {
167
- std::complex<double> shi;
168
- std::complex<double> chi;
169
- int res = shichi(z, &shi, &chi);
170
- *shi_f = shi;
171
- *chi_f = chi;
172
- return res;
173
- }
174
-
175
- XSF_HOST_DEVICE inline int sici(double x, double *si, double *ci) {
176
- return cephes::sici(x, si, ci);
177
- }
178
-
179
- XSF_HOST_DEVICE inline int shichi(double x, double *shi, double *chi) {
180
- return cephes::shichi(x, shi, chi);
181
- }
182
-
183
- XSF_HOST_DEVICE inline int sici(float x, float *si_f, float *ci_f) {
184
- double si;
185
- double ci;
186
- int res = cephes::sici(x, &si, &ci);
187
- *si_f = si;
188
- *ci_f = ci;
189
- return res;
190
- }
191
-
192
- XSF_HOST_DEVICE inline int shichi(float x, float *shi_f, float *chi_f) {
193
- double shi;
194
- double chi;
195
- int res = cephes::shichi(x, &shi, &chi);
196
- *shi_f = shi;
197
- *chi_f = chi;
198
- return res;
199
- }
200
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b3e92596047cab99a939229b56d656a7862d617eacf9291d7fa6f6c95f80e36/blob DELETED
@@ -1,570 +0,0 @@
1
- from collections import defaultdict
2
-
3
- import numpy as np
4
-
5
- import statsmodels.base.model as base
6
- import statsmodels.base.wrapper as wrap
7
- from statsmodels.formula.formulatools import advance_eval_env
8
- from statsmodels.genmod import families
9
- from statsmodels.genmod.families import links, varfuncs
10
- from statsmodels.genmod.generalized_linear_model import GLM
11
- import statsmodels.regression.linear_model as lm
12
- from statsmodels.tools._decorators import cache_readonly
13
-
14
-
15
- class QIFCovariance:
16
- """
17
- A covariance model for quadratic inference function regression.
18
-
19
- The mat method returns a basis matrix B such that the inverse
20
- of the working covariance lies in the linear span of the
21
- basis matrices.
22
-
23
- Subclasses should set the number of basis matrices `num_terms`,
24
- so that `mat(d, j)` for j=0, ..., num_terms-1 gives the basis
25
- of dimension d.
26
- """
27
-
28
- def mat(self, dim, term):
29
- """
30
- Returns the term'th basis matrix, which is a dim x dim
31
- matrix.
32
-
33
- Parameters
34
- ----------
35
- dim : int
36
- The dimension of the basis matrix.
37
- term : int
38
- The index of the basis matrix to return, ranging from 0
39
- to `num_terms` - 1.
40
-
41
- Returns
42
- -------
43
- ndarray or None
44
- The dim x dim basis matrix for `term`, or None if `term`
45
- is greater than or equal to `num_terms`.
46
- """
47
- raise NotImplementedError
48
-
49
-
50
- class QIFIndependence(QIFCovariance):
51
- """
52
- Independent working covariance for QIF regression. This covariance
53
- model gives identical results to GEE with the independence working
54
- covariance. When using QIFIndependence as the working covariance,
55
- the QIF value will be zero, and cannot be used for chi^2 testing, or
56
- for model selection using AIC, BIC, etc.
57
- """
58
-
59
- def __init__(self):
60
- self.num_terms = 1
61
-
62
- def mat(self, dim, term):
63
- if term == 0:
64
- return np.eye(dim)
65
- else:
66
- return None
67
-
68
-
69
- class QIFExchangeable(QIFCovariance):
70
- """
71
- Exchangeable working covariance for QIF regression.
72
- """
73
-
74
- def __init__(self):
75
- self.num_terms = 2
76
-
77
- def mat(self, dim, term):
78
- if term == 0:
79
- return np.eye(dim)
80
- elif term == 1:
81
- return np.ones((dim, dim))
82
- else:
83
- return None
84
-
85
-
86
- class QIFAutoregressive(QIFCovariance):
87
- """
88
- Autoregressive working covariance for QIF regression.
89
- """
90
-
91
- def __init__(self):
92
- self.num_terms = 3
93
-
94
- def mat(self, dim, term):
95
-
96
- if dim < 3:
97
- msg = ("Groups must have size at least 3 for "
98
- "autoregressive covariance.")
99
- raise ValueError(msg)
100
-
101
- if term == 0:
102
- return np.eye(dim)
103
- elif term == 1:
104
- mat = np.zeros((dim, dim))
105
- mat.flat[1::(dim+1)] = 1
106
- mat += mat.T
107
- return mat
108
- elif term == 2:
109
- mat = np.zeros((dim, dim))
110
- mat[0, 0] = 1
111
- mat[dim-1, dim-1] = 1
112
- return mat
113
- else:
114
- return None
115
-
116
-
117
- class QIF(base.Model):
118
- """
119
- Fit a regression model using quadratic inference functions (QIF).
120
-
121
- QIF is an alternative to GEE that can be more efficient, and that
122
- offers different approaches for model selection and inference.
123
-
124
- Parameters
125
- ----------
126
- endog : array_like
127
- The dependent variables of the regression.
128
- exog : array_like
129
- The independent variables of the regression.
130
- groups : array_like
131
- Labels indicating which group each observation belongs to.
132
- Observations in different groups should be independent.
133
- family : genmod family, optional
134
- An instance of a GLM family. The default is Gaussian.
135
- cov_struct : QIFCovariance instance, optional
136
- An instance of a QIFCovariance. The default is
137
- QIFIndependence.
138
- missing : str, optional
139
- Available options are 'none', 'drop', and 'raise'. If 'none', no nan
140
- checking is done. If 'drop', any observations with nans are dropped.
141
- If 'raise', an error is raised.
142
-
143
- References
144
- ----------
145
- A. Qu, B. Lindsay, B. Li (2000). Improving Generalized Estimating
146
- Equations using Quadratic Inference Functions, Biometrika 87:4.
147
- www.jstor.org/stable/2673612
148
- """
149
-
150
- def __init__(self, endog, exog, groups, family=None,
151
- cov_struct=None, missing="none", **kwargs):
152
-
153
- # Handle the family argument
154
- if family is None:
155
- family = families.Gaussian()
156
- elif not issubclass(family.__class__, families.Family):
157
- raise ValueError("QIF: `family` must be a genmod "
158
- "family instance")
159
- self.family = family
160
-
161
- self._fit_history = defaultdict(list)
162
-
163
- # Handle the cov_struct argument
164
- if cov_struct is None:
165
- cov_struct = QIFIndependence()
166
- elif not isinstance(cov_struct, QIFCovariance):
167
- raise ValueError(
168
- "QIF: `cov_struct` must be a QIFCovariance instance")
169
- self.cov_struct = cov_struct
170
-
171
- groups = np.asarray(groups)
172
-
173
- super().__init__(endog, exog, groups=groups,
174
- missing=missing, **kwargs)
175
-
176
- self.group_names = list(set(groups))
177
- self.nobs = len(self.endog)
178
-
179
- groups_ix = defaultdict(list)
180
- for i, g in enumerate(groups):
181
- groups_ix[g].append(i)
182
- self.groups_ix = [groups_ix[na] for na in self.group_names]
183
-
184
- self._check_args(groups)
185
-
186
- def _check_args(self, groups):
187
-
188
- if len(groups) != len(self.endog):
189
- msg = "QIF: groups and endog should have the same length"
190
- raise ValueError(msg)
191
-
192
- if len(self.endog) != self.exog.shape[0]:
193
- msg = ("QIF: the length of endog should be equal to the "
194
- "number of rows of exog.")
195
- raise ValueError(msg)
196
-
197
- def objective(self, params):
198
- """
199
- Calculate the QIF objective function and its gradient.
200
-
201
- Parameters
202
- ----------
203
- params : array_like
204
- The model parameters at which the objective function and
205
- its gradient are evaluated.
206
-
207
- Returns
208
- -------
209
- qif : float
210
- The value of the QIF objective function.
211
- grad : ndarray
212
- The gradient vector of the QIF objective function.
213
- cmat : ndarray
214
- The estimated covariance matrix of the estimating
215
- equations.
216
- gn : ndarray
217
- The moment vector, i.e., the average of the estimating
218
- equations over the groups.
219
- gn_deriv : ndarray
220
- The gradients of each estimating equation with
221
- respect to the parameter.
222
- """
223
-
224
- endog = self.endog
225
- exog = self.exog
226
- lpr = np.dot(exog, params)
227
- mean = self.family.link.inverse(lpr)
228
- va = self.family.variance(mean)
229
-
230
- # Mean derivative
231
- idl = self.family.link.inverse_deriv(lpr)
232
- idl2 = self.family.link.inverse_deriv2(lpr)
233
- vd = self.family.variance.deriv(mean)
234
-
235
- m = self.cov_struct.num_terms
236
- p = exog.shape[1]
237
-
238
- d = p * m
239
- gn = np.zeros(d)
240
- gi = np.zeros(d)
241
- gi_deriv = np.zeros((d, p))
242
- gn_deriv = np.zeros((d, p))
243
- cn_deriv = [0] * p
244
- cmat = np.zeros((d, d))
245
-
246
- fastvar = self.family.variance is varfuncs.constant
247
- fastlink = isinstance(
248
- self.family.link,
249
- # TODO: Remove links.identity after deprecation final
250
- (links.Identity, links.identity)
251
- )
252
-
253
- for ix in self.groups_ix:
254
- sd = np.sqrt(va[ix])
255
- resid = endog[ix] - mean[ix]
256
- sresid = resid / sd
257
- deriv = exog[ix, :] * idl[ix, None]
258
-
259
- jj = 0
260
- for j in range(m):
261
- # The derivative of each term in (5) of Qu et al.
262
- # There are four terms involving beta in a product.
263
- # Iterated application of the product rule gives
264
- # the gradient as a sum of four terms.
265
- c = self.cov_struct.mat(len(ix), j)
266
- crs1 = np.dot(c, sresid) / sd
267
- gi[jj:jj+p] = np.dot(deriv.T, crs1)
268
- crs2 = np.dot(c, -deriv / sd[:, None]) / sd[:, None]
269
- gi_deriv[jj:jj+p, :] = np.dot(deriv.T, crs2)
270
- if not (fastlink and fastvar):
271
- for k in range(p):
272
- m1 = np.dot(exog[ix, :].T,
273
- idl2[ix] * exog[ix, k] * crs1)
274
- if not fastvar:
275
- vx = -0.5 * vd[ix] * deriv[:, k] / va[ix]**1.5
276
- m2 = np.dot(deriv.T, vx * np.dot(c, sresid))
277
- m3 = np.dot(deriv.T, np.dot(c, vx * resid) / sd)
278
- else:
279
- m2, m3 = 0, 0
280
- gi_deriv[jj:jj+p, k] += m1 + m2 + m3
281
- jj += p
282
-
283
- for j in range(p):
284
- u = np.outer(gi, gi_deriv[:, j])
285
- cn_deriv[j] += u + u.T
286
-
287
- gn += gi
288
- gn_deriv += gi_deriv
289
-
290
- cmat += np.outer(gi, gi)
291
-
292
- ngrp = len(self.groups_ix)
293
- gn /= ngrp
294
- gn_deriv /= ngrp
295
- cmat /= ngrp**2
296
-
297
- qif = np.dot(gn, np.linalg.solve(cmat, gn))
298
-
299
- gcg = np.zeros(p)
300
- for j in range(p):
301
- cn_deriv[j] /= len(self.groups_ix)**2
302
- u = np.linalg.solve(cmat, cn_deriv[j]).T
303
- u = np.linalg.solve(cmat, u)
304
- gcg[j] = np.dot(gn, np.dot(u, gn))
305
-
306
- grad = 2 * np.dot(gn_deriv.T, np.linalg.solve(cmat, gn)) - gcg
307
-
308
- return qif, grad, cmat, gn, gn_deriv
309
-
310
- def estimate_scale(self, params):
311
- """
312
- Estimate the dispersion/scale.
313
-
314
- The scale parameter for binomial and Poisson families is
315
- fixed at 1, otherwise it is estimated from the data.
316
-
317
- Parameters
318
- ----------
319
- params : array_like
320
- The regression coefficients at which the scale is
321
- estimated.
322
-
323
- Returns
324
- -------
325
- float
326
- The estimated scale parameter.
327
- """
328
-
329
- if isinstance(self.family, (families.Binomial, families.Poisson)):
330
- return 1.
331
-
332
- if hasattr(self, "ddof_scale"):
333
- ddof_scale = self.ddof_scale
334
- else:
335
- ddof_scale = self.exog[1]
336
-
337
- lpr = np.dot(self.exog, params)
338
- mean = self.family.link.inverse(lpr)
339
- resid = self.endog - mean
340
- scale = np.sum(resid**2) / (self.nobs - ddof_scale)
341
-
342
- return scale
343
-
344
- @classmethod
345
- def from_formula(cls, formula, groups, data, subset=None,
346
- *args, **kwargs):
347
- """
348
- Create a QIF model instance from a formula and dataframe.
349
-
350
- Parameters
351
- ----------
352
- formula : str or generic Formula object
353
- The formula specifying the model
354
- groups : array_like or str
355
- Array of grouping labels. If a string, this is the name
356
- of a variable in `data` that contains the grouping labels.
357
- data : array_like
358
- The data for the model.
359
- subset : array_like, optional
360
- An array_like object of booleans, integers, or index
361
- values that indicate the subset of the data to use when
362
- fitting the model.
363
-
364
- Returns
365
- -------
366
- model : QIF model instance
367
- """
368
-
369
- if isinstance(groups, str):
370
- groups = data[groups]
371
- advance_eval_env(kwargs)
372
- model = super().from_formula(
373
- formula, data, *args, subset=subset, groups=groups, **kwargs
374
- )
375
-
376
- return model
377
-
378
- def fit(self, maxiter=100, start_params=None, tol=1e-6, gtol=1e-4,
379
- ddof_scale=None):
380
- """
381
- Fit a GLM to correlated data using QIF.
382
-
383
- Parameters
384
- ----------
385
- maxiter : int, optional
386
- Maximum number of iterations.
387
- start_params : array_like, optional
388
- Starting values
389
- tol : float, optional
390
- Convergence threshold for difference of successive
391
- estimates.
392
- gtol : float, optional
393
- Convergence threshold for gradient.
394
- ddof_scale : int, optional
395
- Degrees of freedom for the scale parameter
396
-
397
- Returns
398
- -------
399
- QIFResults object
400
- """
401
-
402
- if ddof_scale is None:
403
- self.ddof_scale = self.exog.shape[1]
404
- else:
405
- self.ddof_scale = ddof_scale
406
-
407
- if start_params is None:
408
- model = GLM(self.endog, self.exog, family=self.family)
409
- result = model.fit()
410
- params = result.params
411
- else:
412
- params = start_params
413
-
414
- for _ in range(maxiter):
415
-
416
- qif, grad, cmat, _, gn_deriv = self.objective(params)
417
-
418
- gnorm = np.sqrt(np.sum(grad * grad))
419
- self._fit_history["qif"].append(qif)
420
- self._fit_history["gradnorm"].append(gnorm)
421
-
422
- if gnorm < gtol:
423
- break
424
-
425
- cjac = 2 * np.dot(gn_deriv.T, np.linalg.solve(cmat, gn_deriv))
426
- step = np.linalg.solve(cjac, grad)
427
-
428
- snorm = np.sqrt(np.sum(step * step))
429
- self._fit_history["stepnorm"].append(snorm)
430
- if snorm < tol:
431
- break
432
- params -= step
433
-
434
- vcov = np.dot(gn_deriv.T, np.linalg.solve(cmat, gn_deriv))
435
- vcov = np.linalg.inv(vcov)
436
- scale = self.estimate_scale(params)
437
-
438
- rslt = QIFResults(self, params, vcov / scale, scale)
439
- rslt.fit_history = self._fit_history
440
- self._fit_history = defaultdict(list)
441
-
442
- return QIFResultsWrapper(rslt)
443
-
444
-
445
- class QIFResults(base.LikelihoodModelResults):
446
- """
447
- Results class for QIF Regression
448
-
449
- Attributes
450
- ----------
451
- qif : float
452
- The value of the QIF objective function at the estimated
453
- parameters.
454
- """
455
- def __init__(self, model, params, cov_params, scale,
456
- use_t=False, **kwds):
457
-
458
- super().__init__(
459
- model, params, normalized_cov_params=cov_params,
460
- scale=scale)
461
-
462
- self.qif, _, _, _, _ = self.model.objective(params)
463
-
464
- @cache_readonly
465
- def aic(self):
466
- """
467
- An AIC-like statistic for models fit using QIF.
468
- """
469
- if isinstance(self.model.cov_struct, QIFIndependence):
470
- msg = "AIC not available with QIFIndependence covariance"
471
- raise ValueError(msg)
472
- df = self.model.exog.shape[1]
473
- return self.qif + 2*df
474
-
475
- @cache_readonly
476
- def bic(self):
477
- """
478
- A BIC-like statistic for models fit using QIF.
479
- """
480
- if isinstance(self.model.cov_struct, QIFIndependence):
481
- msg = "BIC not available with QIFIndependence covariance"
482
- raise ValueError(msg)
483
- df = self.model.exog.shape[1]
484
- return self.qif + np.log(self.model.nobs)*df
485
-
486
- @cache_readonly
487
- def fittedvalues(self):
488
- """
489
- Returns the fitted values from the model.
490
- """
491
- return self.model.family.link.inverse(
492
- np.dot(self.model.exog, self.params))
493
-
494
- def summary(self, yname=None, xname=None, title=None, alpha=.05):
495
- """
496
- Summarize the QIF regression results
497
-
498
- Parameters
499
- ----------
500
- yname : str, optional
501
- Default is `y`
502
- xname : list of str, optional
503
- Names for the exogenous variables, default is `var_#` where `#`
504
- is the 0-based index of the regressor. Must match the number of
505
- parameters in the model
506
- title : str, optional
507
- Title for the top table. If not None, then this replaces
508
- the default title
509
- alpha : float, optional
510
- significance level for the confidence intervals
511
-
512
- Returns
513
- -------
514
- smry : Summary instance
515
- this holds the summary tables and text, which can be
516
- printed or converted to various output formats.
517
-
518
- See Also
519
- --------
520
- statsmodels.iolib.summary.Summary : class to hold summary results
521
- """
522
-
523
- top_left = [("Dep. Variable:", None),
524
- ("Method:", ["QIF"]),
525
- ("Family:", [self.model.family.__class__.__name__]),
526
- ("Covariance structure:",
527
- [self.model.cov_struct.__class__.__name__]),
528
- ("Date:", None),
529
- ("Time:", None),
530
- ]
531
-
532
- NY = [len(y) for y in self.model.groups_ix]
533
-
534
- top_right = [("No. Observations:", [sum(NY)]),
535
- ("No. clusters:", [len(NY)]),
536
- ("Min. cluster size:", [min(NY)]),
537
- ("Max. cluster size:", [max(NY)]),
538
- ("Mean cluster size:", [f"{np.mean(NY):.1f}"]),
539
- ("Scale:", [f"{self.scale:.3f}"]),
540
- ]
541
-
542
- if title is None:
543
- title = self.model.__class__.__name__ + " " +\
544
- "Regression Results"
545
-
546
- # Override the exog variable names if xname is provided as an
547
- # argument.
548
- if xname is None:
549
- xname = self.model.exog_names
550
-
551
- if yname is None:
552
- yname = self.model.endog_names
553
-
554
- # Create summary table instance
555
- from statsmodels.iolib.summary import Summary
556
- smry = Summary()
557
- smry.add_table_2cols(self, gleft=top_left, gright=top_right,
558
- yname=yname, xname=xname,
559
- title=title)
560
- smry.add_table_params(self, yname=yname, xname=xname,
561
- alpha=alpha, use_t=False)
562
-
563
- return smry
564
-
565
-
566
- class QIFResultsWrapper(lm.RegressionResultsWrapper):
567
- pass
568
-
569
-
570
- wrap.populate_wrapper(QIFResultsWrapper, QIFResults)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b45a809e914c434a5fedb1bcfe7f9bd9ee4471fd5d828bcafa59cd50b502507/blob DELETED
@@ -1,884 +0,0 @@
1
- #pragma once
2
-
3
- #include <ATen/Context.h>
4
- #include <c10/core/DeviceType.h>
5
- #include <torch/csrc/autograd/autograd.h>
6
- #include <torch/csrc/autograd/edge.h>
7
- #include <torch/csrc/autograd/function.h>
8
- #include <torch/csrc/autograd/generated/variable_factories.h>
9
- #include <torch/csrc/autograd/variable.h>
10
- #include <torch/csrc/jit/api/compilation_unit.h>
11
- #include <torch/csrc/jit/api/module.h>
12
- #include <torch/csrc/jit/frontend/error_report.h>
13
- #include <torch/csrc/jit/ir/ir.h>
14
- #include <torch/csrc/jit/mobile/register_ops_common_utils.h>
15
- #include <torch/csrc/jit/runtime/custom_operator.h>
16
- #include <torch/csrc/jit/runtime/graph_executor.h>
17
- #include <torch/csrc/jit/runtime/jit_exception.h>
18
- #include <torch/csrc/jit/runtime/logging.h>
19
- #include <torch/csrc/jit/runtime/operator.h>
20
- #include <torch/csrc/jit/runtime/print_handler.h>
21
- #include <torch/csrc/jit/runtime/profiling_record.h>
22
- #include <torch/csrc/jit/runtime/vararg_functions.h>
23
- #include <torch/csrc/jit/serialization/pickle.h>
24
-
25
- #include <ATen/ExpandUtils.h>
26
- #include <ATen/Parallel.h>
27
- #include <ATen/WrapDimUtils.h>
28
- #include <ATen/core/Dict.h>
29
- #include <ATen/core/Generator.h>
30
- #include <ATen/core/ivalue.h>
31
- #include <c10/core/Device.h>
32
- #include <c10/core/thread_pool.h>
33
- #include <c10/util/SmallVector.h>
34
- #include <c10/util/irange.h>
35
- #include <c10/util/string_utils.h>
36
-
37
- namespace torch::jit {
38
- constexpr inline c10::AliasAnalysisKind aliasAnalysisFromSchema() {
39
- return c10::AliasAnalysisKind::FROM_SCHEMA;
40
- }
41
-
42
- constexpr inline c10::AliasAnalysisKind aliasAnalysisConservative() {
43
- return c10::AliasAnalysisKind::CONSERVATIVE;
44
- }
45
-
46
- constexpr inline c10::AliasAnalysisKind aliasAnalysisSpecialCase() {
47
- return c10::AliasAnalysisKind::INTERNAL_SPECIAL_CASE;
48
- }
49
-
50
- template <class T>
51
- c10::List<T> make_result_list(const TypePtr& elemType) {
52
- return c10::List<T>();
53
- }
54
-
55
- template <>
56
- c10::impl::GenericList make_result_list<IValue>(const TypePtr& elemType);
57
-
58
- // As described in https://docs.python.org/3/library/functions.html#round
59
- // When a number is exactly halfway between two integers, python builtin round
60
- // function will round to even number. We use round(x/2)*2 to handle the
61
- // special halfway case. For positive 'x', round(x/2)*2 =
62
- // round((x_e + x_r)/2)*2 = x_e + round(x_r/2)*2, where x_e is an even integer,
63
- // x_r is either 0.5 of 1.5, round(x_r/2)*2 results a 0 or 2, so the final
64
- // result will always be a even number. Due to symmetricity, it also applies to
65
- // negative cases.
66
- inline double round_to_even(double a) {
67
- return a - std::floor(a) == 0.5 ? (std::round(a * 0.5) * 2.0) : std::round(a);
68
- }
69
-
70
- // using the rules from python_arg_parser FunctionParameter::check
71
- // tensor cannot have grad set, tensor must be 0 dim,
72
- // and if the dest is an int the source must be integral type
73
- void checkImplicitTensorToNum(const at::Tensor& t, bool toInt);
74
-
75
- static C10_UNUSED int64_t floordiv(int64_t a, int64_t b) {
76
- if (b == 0) {
77
- throw std::runtime_error("division by 0");
78
- }
79
- if ((a > 0) == (b > 0)) {
80
- // simple case, both have same sign
81
- return a / b;
82
- } else {
83
- // in python division rounds down, it doesn't not truncate like in c++
84
- auto r = lldiv(a, b);
85
- return (r.rem) ? r.quot - 1 : r.quot;
86
- }
87
- }
88
- TORCH_API void checkDoubleInRange(double a);
89
- static C10_UNUSED int64_t floor(double a) {
90
- checkDoubleInRange(a);
91
- return std::floor(a);
92
- }
93
- static C10_UNUSED int64_t ceil(double a) {
94
- checkDoubleInRange(a);
95
- return std::ceil(a);
96
- }
97
-
98
- static C10_UNUSED int64_t gcd(int64_t a, int64_t b) {
99
- while (b != 0) {
100
- int64_t r = a % b;
101
- a = b;
102
- b = r;
103
- }
104
- // in python gcd returns non-negative values
105
- return std::abs(a);
106
- }
107
-
108
- int64_t partProduct(int n, int m);
109
-
110
- void loop(int n, int64_t& p, int64_t& r);
111
-
112
- int nminussumofbits(int v);
113
-
114
- int64_t factorial(int n);
115
- static const double degToRad = std::acos(-1.0) / 180.0;
116
- static const double radToDeg = 180.0 / std::acos(-1.0);
117
- double degrees(double x);
118
- double radians(double x);
119
-
120
- // Convert an python index (which may be negative) into an index usable for a
121
- // C++ container
122
-
123
- // Equivalent to list.at(idx)
124
- template <typename T>
125
- decltype(auto) getItem(const c10::List<T>& list, int64_t idx) {
126
- const int64_t list_size = list.size();
127
- const int64_t normalized_idx = normalizeIndex(idx, list_size);
128
- if (normalized_idx < 0 || normalized_idx >= list_size) {
129
- throw std::out_of_range("list index out of range");
130
- }
131
- return list.get(normalized_idx);
132
- }
133
-
134
- template <typename T>
135
- void setItem(const c10::List<T>& list, int64_t idx, T&& value) {
136
- const int64_t list_size = list.size();
137
- const int64_t normalized_idx = normalizeIndex(idx, list_size);
138
- if (normalized_idx < 0 || normalized_idx >= list_size) {
139
- throw std::out_of_range("list index out of range");
140
- }
141
- list.set(normalized_idx, std::forward<T>(value));
142
- }
143
-
144
- void listAppend(Stack& stack);
145
-
146
- void listReverse(Stack& stack);
147
-
148
- template <typename T>
149
- void minList(Stack& stack) {
150
- c10::List<T> a = pop(stack).to<c10::List<T>>();
151
- c10::List<T> b = pop(stack).to<c10::List<T>>();
152
-
153
- size_t min_size = std::min(a.size(), b.size());
154
- for (const auto i : c10::irange(min_size)) {
155
- if (a[i] == b[i]) {
156
- continue;
157
- }
158
-
159
- push(stack, a[i] < b[i] ? a : b);
160
- return;
161
- }
162
-
163
- push(stack, b.size() < a.size() ? b : a);
164
- }
165
-
166
- template <typename T>
167
- void maxList(Stack& stack) {
168
- c10::List<T> a = pop(stack).to<c10::List<T>>();
169
- c10::List<T> b = pop(stack).to<c10::List<T>>();
170
-
171
- size_t min_size = std::min(a.size(), b.size());
172
- for (const auto i : c10::irange(min_size)) {
173
- if (a[i] == b[i]) {
174
- continue;
175
- }
176
-
177
- push(stack, a[i] > b[i] ? a : b);
178
- return;
179
- }
180
-
181
- push(stack, b.size() > a.size() ? b : a);
182
- }
183
-
184
- void listPopImpl(Stack& stack, const char* empty_message);
185
-
186
- void listPop(Stack& stack);
187
-
188
- void listClear(Stack& stack);
189
-
190
- void listDelete(Stack& stack);
191
-
192
- void listInsert(Stack& stack);
193
-
194
- template <typename T>
195
- void listRemove(Stack& stack) {
196
- T elem = pop(stack).to<T>();
197
- c10::List<T> list = pop(stack).to<c10::List<T>>();
198
-
199
- auto pos = std::find(list.begin(), list.end(), elem);
200
-
201
- if (pos != list.end()) {
202
- list.erase(pos);
203
- } else {
204
- AT_ERROR("list.remove(x): x not in list");
205
- }
206
- }
207
-
208
- template <typename T>
209
- void listMin(Stack& stack) {
210
- c10::List<T> list = pop(stack).to<c10::List<T>>();
211
- size_t list_size = list.size();
212
- if (list_size == 0) {
213
- throw std::runtime_error("min() arg is an empty sequence");
214
- }
215
-
216
- T min_elem = list[0];
217
- for (const auto i : c10::irange(1, list_size)) {
218
- T elem = list[i];
219
- min_elem = elem < min_elem ? elem : min_elem;
220
- }
221
-
222
- stack.push_back(min_elem);
223
- }
224
-
225
- template <typename T>
226
- void listMax(Stack& stack) {
227
- c10::List<T> list = pop(stack).to<c10::List<T>>();
228
- size_t list_size = list.size();
229
- if (list_size == 0) {
230
- throw std::runtime_error("max() arg is an empty sequence");
231
- }
232
-
233
- T max_elem = list[0];
234
- for (const auto i : c10::irange(1, list_size)) {
235
- T elem = list[i];
236
- max_elem = elem > max_elem ? elem : max_elem;
237
- }
238
-
239
- stack.push_back(max_elem);
240
- }
241
-
242
- template <>
243
- void listRemove<at::Tensor>(Stack& stack);
244
-
245
- template <typename T>
246
- void listIndex(Stack& stack) {
247
- T elem = pop(stack).to<T>();
248
- c10::List<T> list = pop(stack).to<c10::List<T>>();
249
-
250
- auto pos = std::find(list.begin(), list.end(), elem);
251
-
252
- if (pos != list.end()) {
253
- push(stack, static_cast<int64_t>(std::distance(list.begin(), pos)));
254
- } else {
255
- AT_ERROR("'", elem, "' is not in list");
256
- }
257
- }
258
-
259
- template <>
260
- void listIndex<at::Tensor>(Stack& stack);
261
-
262
- template <typename T>
263
- void listCount(Stack& stack) {
264
- T elem = pop(stack).to<T>();
265
- c10::List<T> list = pop(stack).to<c10::List<T>>();
266
-
267
- const int64_t count = std::count(list.begin(), list.end(), elem);
268
- push(stack, count);
269
- }
270
-
271
- template <>
272
- void listCount<at::Tensor>(Stack& stack);
273
-
274
- void listExtend(Stack& stack);
275
-
276
- void listCopy(Stack& stack);
277
-
278
- void listSelect(Stack& stack);
279
-
280
- void listLen(Stack& stack);
281
-
282
- template <typename T>
283
- void listEq(Stack& stack) {
284
- c10::List<T> b = pop(stack).to<c10::List<T>>();
285
- c10::List<T> a = pop(stack).to<c10::List<T>>();
286
- push(stack, a == b);
287
- }
288
-
289
- template <typename T>
290
- void listNe(Stack& stack) {
291
- c10::List<T> b = pop(stack).to<c10::List<T>>();
292
- c10::List<T> a = pop(stack).to<c10::List<T>>();
293
- push(stack, a != b);
294
- }
295
-
296
- inline bool tensor_list_equal(
297
- const c10::List<at::Tensor>& a,
298
- const c10::List<at::Tensor>& b) {
299
- if (a.size() != b.size()) {
300
- return false;
301
- }
302
-
303
- for (const auto i : c10::irange(a.size())) {
304
- const at::Tensor& a_element = a[i];
305
- const at::Tensor& b_element = b[i];
306
- // This preserves Python's semantics, which uses eq() to compare two
307
- // elements, then passes the result to bool().
308
- // see: https://docs.python.org/3.4/reference/datamodel.html#object.__ge__
309
- const auto cmp_result = a_element.eq(b_element);
310
- if (!at::native::is_nonzero(cmp_result)) {
311
- return false;
312
- }
313
- }
314
-
315
- return true;
316
- }
317
-
318
- // Specialization for at::Tensor, since it doesn't define operator==
319
- template <>
320
- void listEq<at::Tensor>(Stack& stack);
321
-
322
- // Specialization for at::Tensor, since it doesn't define operator==
323
- template <>
324
- void listNe<at::Tensor>(Stack& stack);
325
-
326
- void listList(Stack& stack);
327
-
328
- template <typename T>
329
- void listContains(Stack& stack) {
330
- auto key = pop(stack).to<T>();
331
- auto list = pop(stack).to<c10::List<T>>();
332
- // NOLINTNEXTLINE(performance-implicit-conversion-in-loop)
333
- for (const T& item : list) {
334
- if (item == key) {
335
- push(stack, true);
336
- return;
337
- }
338
- }
339
- push(stack, false);
340
- }
341
-
342
- void listAdd(Stack& stack);
343
-
344
- void listInplaceAdd(Stack& stack);
345
-
346
- void listMulIntLeftInPlace(Stack& stack);
347
-
348
- void listMulIntLeft(Stack& stack);
349
-
350
- void listMulIntRight(Stack& stack);
351
-
352
- void listSlice(Stack& stack);
353
-
354
- template <typename T>
355
- void listSort(Stack& stack) {
356
- bool reverse = pop(stack).toBool();
357
- c10::List<T> list = pop(stack).to<c10::List<T>>();
358
- std::sort(list.begin(), list.end(), [reverse](const T& a, const T& b) {
359
- // FBCode errors without this check - "strict weak ordering"
360
- // TODO: remove when possible, since it just slows down
361
- // sorting and doesn't do anything useful
362
- if (a == b) {
363
- return false;
364
- }
365
- return (a < b) != reverse;
366
- });
367
- }
368
-
369
- // Specialization for at::Tensor
370
- template <>
371
- void listSort<at::Tensor>(Stack& stack);
372
-
373
- template <typename T>
374
- void listCopyAndSort(Stack& stack) {
375
- c10::List<T> list = pop(stack).to<c10::List<T>>();
376
- auto list_copied = list.copy();
377
- std::sort(list_copied.begin(), list_copied.end(), [](const T& a, const T& b) {
378
- // "strict weak ordering" issue - see other sort
379
- if (a == b) {
380
- return false;
381
- }
382
- return a < b;
383
- });
384
- push(stack, list_copied);
385
- }
386
-
387
- // Specialization for at::Tensor
388
- template <>
389
- void listCopyAndSort<at::Tensor>(Stack& stack);
390
-
391
- void listSetItem(Stack& stack);
392
-
393
- struct OperatorGeneratorArgs {
394
- const char* schema_str;
395
- bool isOperationCreator;
396
- union {
397
- void (*operation)(Stack&);
398
- OperationCreator operationCreator;
399
- };
400
- AliasAnalysisKind aliasAnalysis;
401
-
402
- explicit constexpr OperatorGeneratorArgs(
403
- torch::detail::SelectiveStr<true> schema_str,
404
- void (*op)(Stack&),
405
- AliasAnalysisKind aa)
406
- : schema_str(schema_str),
407
- isOperationCreator(false),
408
- operation(op),
409
- aliasAnalysis(aa) {}
410
-
411
- explicit constexpr OperatorGeneratorArgs(
412
- torch::detail::SelectiveStr<true> schema_str,
413
- OperationCreator opCreator,
414
- AliasAnalysisKind aa)
415
- : schema_str(schema_str),
416
- isOperationCreator(true),
417
- operationCreator(opCreator),
418
- aliasAnalysis(aa) {}
419
-
420
- template <typename... Args>
421
- explicit constexpr OperatorGeneratorArgs(
422
- torch::detail::SelectiveStr<false>,
423
- Args...)
424
- : schema_str(nullptr),
425
- isOperationCreator(false),
426
- operation(nullptr),
427
- aliasAnalysis(AliasAnalysisKind::INTERNAL_SPECIAL_CASE) {}
428
- };
429
-
430
- #define DEFINE_GENERIC_BINARY_OP( \
431
- aten_op, op, int_float_result, complex_result) \
432
- OperatorGeneratorArgs( \
433
- TORCH_SELECTIVE_SCHEMA(#aten_op \
434
- ".int_int(int a, int b) -> " #int_float_result), \
435
- [](Stack& stack) { \
436
- int64_t a, b; \
437
- pop(stack, a, b); \
438
- push(stack, op); \
439
- }, \
440
- aliasAnalysisFromSchema()), \
441
- OperatorGeneratorArgs( \
442
- TORCH_SELECTIVE_SCHEMA( \
443
- #aten_op \
444
- ".float_float(float a, float b) -> " #int_float_result), \
445
- [](Stack& stack) { \
446
- double a, b; \
447
- pop(stack, a, b); \
448
- push(stack, op); \
449
- }, \
450
- aliasAnalysisFromSchema()), \
451
- OperatorGeneratorArgs( \
452
- TORCH_SELECTIVE_SCHEMA( \
453
- #aten_op \
454
- ".complex_complex(complex a, complex b) -> " #complex_result), \
455
- [](Stack& stack) { \
456
- c10::complex<double> a, b; \
457
- pop(stack, a, b); \
458
- push(stack, op); \
459
- }, \
460
- aliasAnalysisFromSchema())
461
-
462
- // define implementations for primitive number ops
463
- #define DEFINE_GENERIC_OP(aten_op, int_op, float_op, int_result, float_result) \
464
- OperatorGeneratorArgs( \
465
- TORCH_SELECTIVE_SCHEMA(#aten_op ".int(int a, int b) -> " #int_result), \
466
- [](Stack& stack) { \
467
- int64_t a, b; \
468
- pop(stack, a, b); \
469
- push(stack, int_op); \
470
- }, \
471
- aliasAnalysisFromSchema()), \
472
- OperatorGeneratorArgs( \
473
- TORCH_SELECTIVE_SCHEMA( \
474
- #aten_op ".float(float a, float b) -> " #float_result), \
475
- [](Stack& stack) { \
476
- double a, b; \
477
- pop(stack, a, b); \
478
- push(stack, float_op); \
479
- }, \
480
- aliasAnalysisFromSchema())
481
-
482
- #define DEFINE_INT_FLOAT_OP(aten_op, op, result) \
483
- OperatorGeneratorArgs( \
484
- TORCH_SELECTIVE_SCHEMA(#aten_op \
485
- ".int_float(int a, float b) -> " #result), \
486
- [](Stack& stack) { \
487
- int64_t a; \
488
- double b; \
489
- pop(stack, a, b); \
490
- push(stack, op); \
491
- }, \
492
- aliasAnalysisFromSchema()), \
493
- OperatorGeneratorArgs( \
494
- TORCH_SELECTIVE_SCHEMA(#aten_op \
495
- ".float_int(float a, int b) -> " #result), \
496
- [](Stack& stack) { \
497
- double a; \
498
- int64_t b; \
499
- pop(stack, a, b); \
500
- push(stack, op); \
501
- }, \
502
- aliasAnalysisFromSchema())
503
-
504
- #define DEFINE_INT_OP(aten_op, op) \
505
- OperatorGeneratorArgs( \
506
- TORCH_SELECTIVE_SCHEMA(#aten_op ".int(int a, int b) -> int"), \
507
- [](Stack& stack) { \
508
- int64_t a, b; \
509
- pop(stack, a, b); \
510
- push(stack, op); /* NOLINT(hicpp-signed-bitwise) */ \
511
- }, \
512
- aliasAnalysisFromSchema())
513
-
514
- #define DEFINE_STR_CMP_OP(aten_op, op) \
515
- OperatorGeneratorArgs( \
516
- TORCH_SELECTIVE_SCHEMA(#aten_op ".str(str a, str b) -> bool"), \
517
- [](Stack& stack) { \
518
- auto b = pop(stack).toStringRef(); \
519
- auto a = pop(stack).toStringRef(); \
520
- push(stack, op); \
521
- }, \
522
- aliasAnalysisFromSchema())
523
-
524
- // define a primitive op over Scalar operands.
525
- // it's necessary to register this overload following
526
- // int/float variations to avoid trapping Scalar args
527
- // in unintended implicit conversions
528
- #define DEFINE_SCALAR_BINARY_OP_AVOID_COLLISION_GENERIC( \
529
- aten_op, int_op, float_op, result, string_val) \
530
- OperatorGeneratorArgs( \
531
- TORCH_SELECTIVE_SCHEMA(#aten_op string_val \
532
- "(Scalar a, Scalar b) -> " #result), \
533
- [](Stack& stack) { \
534
- IValue x, y; \
535
- pop(stack, x, y); \
536
- if (x.isDouble()) { \
537
- if (y.isDouble()) { \
538
- double a = x.toDouble(); \
539
- double b = y.toDouble(); \
540
- push(stack, float_op); \
541
- } else { \
542
- double a = x.toDouble(); \
543
- int64_t b = y.toInt(); \
544
- push(stack, float_op); \
545
- } \
546
- } else { \
547
- if (y.isDouble()) { \
548
- int64_t a = x.toInt(); \
549
- double b = y.toDouble(); \
550
- push(stack, float_op); \
551
- } else { \
552
- int64_t a = x.toInt(); \
553
- int64_t b = y.toInt(); \
554
- push(stack, int_op); \
555
- } \
556
- } \
557
- }, \
558
- aliasAnalysisFromSchema())
559
-
560
- #define DEFINE_SCALAR_BINARY_OP(aten_op, int_op, float_op, result) \
561
- DEFINE_SCALAR_BINARY_OP_AVOID_COLLISION_GENERIC( \
562
- aten_op, int_op, float_op, result, "")
563
-
564
- #define DEFINE_SCALAR_BINARY_OP_AVOID_COLLISION( \
565
- aten_op, int_op, float_op, result) \
566
- DEFINE_SCALAR_BINARY_OP_AVOID_COLLISION_GENERIC( \
567
- aten_op, int_op, float_op, result, ".Scalar_Scalar")
568
-
569
- #define DEFINE_BINARY_OP(aten_op, op) \
570
- DEFINE_GENERIC_OP(aten_op, op, op, int, float), \
571
- DEFINE_INT_FLOAT_OP(aten_op, op, float), \
572
- DEFINE_SCALAR_BINARY_OP(aten_op, op, op, Scalar)
573
-
574
- #define DEFINE_BINARY_FLOAT_OP(aten_op, op) \
575
- DEFINE_GENERIC_OP(aten_op, op, op, float, float), \
576
- DEFINE_INT_FLOAT_OP(aten_op, op, float), \
577
- DEFINE_SCALAR_BINARY_OP(aten_op, op, op, float)
578
-
579
- #define DEFINE_COMPARISON_OP(aten_op, op) \
580
- DEFINE_GENERIC_OP(aten_op, op, op, bool, bool), \
581
- DEFINE_INT_FLOAT_OP(aten_op, op, bool), \
582
- DEFINE_SCALAR_BINARY_OP(aten_op, op, op, bool), \
583
- DEFINE_STR_CMP_OP(aten_op, op)
584
-
585
- #define DEFINE_UNARY_INT_OP(aten_op, op, result) \
586
- OperatorGeneratorArgs( \
587
- TORCH_SELECTIVE_SCHEMA(#aten_op ".int(int a) -> " #result), \
588
- [](Stack& stack) { \
589
- int64_t a; \
590
- pop(stack, a); \
591
- push(stack, op); \
592
- }, \
593
- aliasAnalysisFromSchema())
594
-
595
- #define DEFINE_UNARY_FLOAT_OP(aten_op, op, result) \
596
- OperatorGeneratorArgs( \
597
- TORCH_SELECTIVE_SCHEMA(#aten_op ".float(float a) -> " #result), \
598
- [](Stack& stack) { \
599
- double a; \
600
- pop(stack, a); \
601
- push(stack, op); \
602
- }, \
603
- aliasAnalysisFromSchema())
604
-
605
- #define DEFINE_UNARY_OP(aten_op, op, int_result, float_result) \
606
- DEFINE_UNARY_INT_OP(aten_op, op, int_result), \
607
- DEFINE_UNARY_FLOAT_OP(aten_op, op, float_result), \
608
- OperatorGeneratorArgs( \
609
- TORCH_SELECTIVE_SCHEMA(#aten_op ".Scalar(Scalar a) -> Scalar"), \
610
- [](Stack& stack) { \
611
- IValue x; \
612
- pop(stack, x); \
613
- if (x.isDouble()) { \
614
- double a = x.toDouble(); \
615
- push(stack, static_cast<float_result>(op)); \
616
- } else { \
617
- int64_t a = x.toInt(); \
618
- push(stack, static_cast<int_result>(op)); \
619
- } \
620
- }, \
621
- aliasAnalysisFromSchema())
622
- #define DEFINE_BOOL_OP(aten_op, op) \
623
- OperatorGeneratorArgs( \
624
- TORCH_SELECTIVE_SCHEMA(#aten_op ".bool(bool a, bool b) -> bool"), \
625
- [](Stack& stack) { \
626
- bool a, b; \
627
- pop(stack, a, b); \
628
- push(stack, op); \
629
- }, \
630
- aliasAnalysisFromSchema())
631
- #define DEFINE_STRING_OP(op_name, string_op, result) \
632
- OperatorGeneratorArgs( \
633
- TORCH_SELECTIVE_SCHEMA(#op_name ".str(str a, str b) ->" #result), \
634
- [](Stack& stack) { \
635
- auto b = pop(stack).toStringRef(); \
636
- auto a = pop(stack).toStringRef(); \
637
- push(stack, string_op); \
638
- }, \
639
- aliasAnalysisFromSchema())
640
-
641
- //-----------------------------------------------------------------------------
642
- //-----------------------------------------------------------------------------
643
- //-----------------------------------------------------------------------------
644
- //-----------------------------------------------------------------------------
645
- #define DEFINE_UNARY_COMPLEX_OP(aten_op, op, result) \
646
- OperatorGeneratorArgs( \
647
- TORCH_SELECTIVE_SCHEMA(#aten_op ".complex(complex a) -> " #result), \
648
- [](Stack& stack) { \
649
- c10::complex<double> a; \
650
- pop(stack, a); \
651
- push(stack, op); \
652
- }, \
653
- aliasAnalysisFromSchema())
654
-
655
- // Some complex unary ops (like abs, angle) return real valued output, but most
656
- // other unary ops return complex valued output. So, this macro is used in the
657
- // former case where we can explicitly pass complex_result_cast argument, which
658
- // is set to c10::complex<float> in the macro `DEFINE_UNARY_OP_WITH_COMPLEX`
659
- // defined below.
660
- #define DEFINE_UNARY_OP_WITH_COMPLEX_CAST( \
661
- aten_op, \
662
- op, \
663
- int_result, \
664
- float_result, \
665
- complex_result, \
666
- complex_result_cast) \
667
- DEFINE_UNARY_INT_OP(aten_op, op, int_result), \
668
- DEFINE_UNARY_FLOAT_OP(aten_op, op, float_result), \
669
- DEFINE_UNARY_COMPLEX_OP(aten_op, op, complex_result), \
670
- OperatorGeneratorArgs( \
671
- TORCH_SELECTIVE_SCHEMA(#aten_op ".Scalar(Scalar a) -> Scalar"), \
672
- [](Stack& stack) { \
673
- IValue x; \
674
- pop(stack, x); \
675
- if (x.isDouble()) { \
676
- double a = x.toDouble(); \
677
- push(stack, static_cast<float_result>(op)); \
678
- } else if (x.isComplexDouble()) { \
679
- c10::complex<double> a = x.toComplexDouble(); \
680
- push(stack, static_cast<complex_result_cast>(op)); \
681
- } else { \
682
- int64_t a = x.toInt(); \
683
- push(stack, static_cast<int_result>(op)); \
684
- } \
685
- }, \
686
- aliasAnalysisFromSchema())
687
-
688
- #define DEFINE_UNARY_OP_WITH_COMPLEX(aten_op, op, int_result, float_result) \
689
- DEFINE_UNARY_OP_WITH_COMPLEX_CAST( \
690
- aten_op, op, int_result, float_result, complex, c10::complex<double>)
691
-
692
- #define DEFINE_GENERIC_OP_WITH_COMPLEX( \
693
- aten_op, \
694
- int_op, \
695
- float_op, \
696
- complex_op, \
697
- int_result, \
698
- float_result, \
699
- complex_result) \
700
- OperatorGeneratorArgs( \
701
- TORCH_SELECTIVE_SCHEMA(#aten_op ".int(int a, int b) -> " #int_result), \
702
- [](Stack& stack) { \
703
- int64_t a, b; \
704
- pop(stack, a, b); \
705
- push(stack, int_op); \
706
- }, \
707
- aliasAnalysisFromSchema()), \
708
- OperatorGeneratorArgs( \
709
- TORCH_SELECTIVE_SCHEMA( \
710
- #aten_op ".complex(complex a, complex b) -> " #complex_result), \
711
- [](Stack& stack) { \
712
- c10::complex<double> a, b; \
713
- pop(stack, a, b); \
714
- push(stack, complex_op); \
715
- }, \
716
- aliasAnalysisFromSchema()), \
717
- OperatorGeneratorArgs( \
718
- TORCH_SELECTIVE_SCHEMA( \
719
- #aten_op ".float(float a, float b) -> " #float_result), \
720
- [](Stack& stack) { \
721
- double a, b; \
722
- pop(stack, a, b); \
723
- push(stack, float_op); \
724
- }, \
725
- aliasAnalysisFromSchema())
726
-
727
- #define DEFINE_INT_COMPLEX_OP(aten_op, op, result) \
728
- OperatorGeneratorArgs( \
729
- TORCH_SELECTIVE_SCHEMA(#aten_op \
730
- ".int_complex(int a, complex b) -> " #result), \
731
- [](Stack& stack) { \
732
- int64_t a; \
733
- c10::complex<double> b; \
734
- pop(stack, a, b); \
735
- push(stack, op); \
736
- }, \
737
- aliasAnalysisFromSchema()), \
738
- OperatorGeneratorArgs( \
739
- TORCH_SELECTIVE_SCHEMA( \
740
- #aten_op ".complex_int(complex a, int b) -> " #result), \
741
- [](Stack& stack) { \
742
- c10::complex<double> a; \
743
- int64_t b; \
744
- pop(stack, a, b); \
745
- push(stack, op); \
746
- }, \
747
- aliasAnalysisFromSchema())
748
-
749
- #define DEFINE_FLOAT_COMPLEX_OP(aten_op, op, result) \
750
- OperatorGeneratorArgs( \
751
- TORCH_SELECTIVE_SCHEMA( \
752
- #aten_op ".float_complex(float a, complex b) -> " #result), \
753
- [](Stack& stack) { \
754
- double a; \
755
- c10::complex<double> b; \
756
- pop(stack, a, b); \
757
- push(stack, op); \
758
- }, \
759
- aliasAnalysisFromSchema()), \
760
- OperatorGeneratorArgs( \
761
- TORCH_SELECTIVE_SCHEMA( \
762
- #aten_op ".complex_float(complex a, float b) -> " #result), \
763
- [](Stack& stack) { \
764
- c10::complex<double> a; \
765
- double b; \
766
- pop(stack, a, b); \
767
- push(stack, op); \
768
- }, \
769
- aliasAnalysisFromSchema())
770
-
771
- #define DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX_AVOID_COLLISION_GENERIC( \
772
- aten_op, int_op, float_op, complex_op, result, string_val) \
773
- OperatorGeneratorArgs( \
774
- TORCH_SELECTIVE_SCHEMA(#aten_op string_val \
775
- "(Scalar a, Scalar b) -> " #result), \
776
- [](Stack& stack) { \
777
- IValue x, y; \
778
- pop(stack, x, y); \
779
- if (x.isComplexDouble()) { \
780
- c10::complex<double> a = x.toComplexDouble(); \
781
- if (y.isComplexDouble()) { \
782
- c10::complex<double> b = y.toComplexDouble(); \
783
- push(stack, complex_op); \
784
- } else if (y.isDouble()) { \
785
- double b = y.toDouble(); \
786
- push(stack, complex_op); \
787
- } else { \
788
- int64_t b = y.toInt(); \
789
- push(stack, complex_op); \
790
- } \
791
- } else if (x.isDouble()) { \
792
- double a = x.toDouble(); \
793
- if (y.isComplexDouble()) { \
794
- c10::complex<double> b = y.toComplexDouble(); \
795
- push(stack, complex_op); \
796
- } else if (y.isDouble()) { \
797
- double b = y.toDouble(); \
798
- push(stack, float_op); \
799
- } else { \
800
- int64_t b = y.toInt(); \
801
- push(stack, float_op); \
802
- } \
803
- } else { \
804
- int64_t a = x.toInt(); \
805
- if (y.isComplexDouble()) { \
806
- c10::complex<double> b = y.toComplexDouble(); \
807
- push(stack, complex_op); \
808
- } else if (y.isDouble()) { \
809
- double b = y.toDouble(); \
810
- push(stack, float_op); \
811
- } else { \
812
- int64_t b = y.toInt(); \
813
- push(stack, int_op); \
814
- } \
815
- } \
816
- }, \
817
- aliasAnalysisFromSchema())
818
-
819
- #define DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX_WITHOUT_INT_COMPLEX_PAIR( \
820
- aten_op, int_op, float_op, complex_op, result) \
821
- OperatorGeneratorArgs( \
822
- TORCH_SELECTIVE_SCHEMA(#aten_op "(Scalar a, Scalar b) -> " #result), \
823
- [](Stack& stack) { \
824
- IValue x, y; \
825
- pop(stack, x, y); \
826
- if (x.isComplexDouble()) { \
827
- c10::complex<double> a = x.toComplexDouble(); \
828
- if (y.isComplexDouble()) { \
829
- c10::complex<double> b = y.toComplexDouble(); \
830
- push(stack, complex_op); \
831
- } else if (y.isDouble()) { \
832
- double b = y.toDouble(); \
833
- push(stack, complex_op); \
834
- } \
835
- } else if (x.isDouble()) { \
836
- double a = x.toDouble(); \
837
- if (y.isComplexDouble()) { \
838
- c10::complex<double> b = y.toComplexDouble(); \
839
- push(stack, complex_op); \
840
- } else if (y.isDouble()) { \
841
- double b = y.toDouble(); \
842
- push(stack, float_op); \
843
- } else { \
844
- int64_t b = y.toInt(); \
845
- push(stack, float_op); \
846
- } \
847
- } else { \
848
- int64_t a = x.toInt(); \
849
- if (y.isDouble()) { \
850
- double b = y.toDouble(); \
851
- push(stack, float_op); \
852
- } else if (y.isInt()) { \
853
- int64_t b = y.toInt(); \
854
- push(stack, int_op); \
855
- } \
856
- } \
857
- }, \
858
- aliasAnalysisFromSchema())
859
-
860
- #define DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX( \
861
- aten_op, int_op, float_op, complex_op, result) \
862
- DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX_AVOID_COLLISION_GENERIC( \
863
- aten_op, int_op, float_op, complex_op, result, "")
864
-
865
- #define DEFINE_BINARY_OP_WITH_COMPLEX(aten_op, op) \
866
- DEFINE_GENERIC_OP_WITH_COMPLEX(aten_op, op, op, op, int, float, complex), \
867
- DEFINE_INT_COMPLEX_OP(aten_op, op, complex), \
868
- DEFINE_FLOAT_COMPLEX_OP(aten_op, op, complex), \
869
- DEFINE_INT_FLOAT_OP(aten_op, op, float), \
870
- DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX(aten_op, op, op, op, Scalar)
871
-
872
- #define DEFINE_COMPARISON_OP_WITH_COMPLEX(aten_op, op) \
873
- DEFINE_GENERIC_OP_WITH_COMPLEX(aten_op, op, op, op, bool, bool, bool), \
874
- DEFINE_INT_FLOAT_OP(aten_op, op, bool), \
875
- DEFINE_FLOAT_COMPLEX_OP(aten_op, op, bool), \
876
- DEFINE_SCALAR_BINARY_OP_WITH_COMPLEX_WITHOUT_INT_COMPLEX_PAIR( \
877
- aten_op, op, op, op, bool), \
878
- DEFINE_STR_CMP_OP(aten_op, op)
879
-
880
- TORCH_API at::Generator make_generator_for_device(
881
- c10::Device device,
882
- c10::optional<int64_t> seed = c10::nullopt);
883
-
884
- } // namespace torch::jit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b484599c4f3bd9f2c65b6e759e10dc332b2b9fa44f735b0651f96088e247695/blob DELETED
@@ -1,113 +0,0 @@
1
- """Tests for homomorphisms."""
2
-
3
- from sympy.core.singleton import S
4
- from sympy.polys.domains.rationalfield import QQ
5
- from sympy.abc import x, y
6
- from sympy.polys.agca import homomorphism
7
- from sympy.testing.pytest import raises
8
-
9
-
10
- def test_printing():
11
- R = QQ.old_poly_ring(x)
12
-
13
- assert str(homomorphism(R.free_module(1), R.free_module(1), [0])) == \
14
- 'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1'
15
- assert str(homomorphism(R.free_module(2), R.free_module(2), [0, 0])) == \
16
- 'Matrix([ \n[0, 0], : QQ[x]**2 -> QQ[x]**2\n[0, 0]]) '
17
- assert str(homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0])) == \
18
- 'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1/<[x]>'
19
- assert str(R.free_module(0).identity_hom()) == 'Matrix(0, 0, []) : QQ[x]**0 -> QQ[x]**0'
20
-
21
- def test_operations():
22
- F = QQ.old_poly_ring(x).free_module(2)
23
- G = QQ.old_poly_ring(x).free_module(3)
24
- f = F.identity_hom()
25
- g = homomorphism(F, F, [0, [1, x]])
26
- h = homomorphism(F, F, [[1, 0], 0])
27
- i = homomorphism(F, G, [[1, 0, 0], [0, 1, 0]])
28
-
29
- assert f == f
30
- assert f != g
31
- assert f != i
32
- assert (f != F.identity_hom()) is False
33
- assert 2*f == f*2 == homomorphism(F, F, [[2, 0], [0, 2]])
34
- assert f/2 == homomorphism(F, F, [[S.Half, 0], [0, S.Half]])
35
- assert f + g == homomorphism(F, F, [[1, 0], [1, x + 1]])
36
- assert f - g == homomorphism(F, F, [[1, 0], [-1, 1 - x]])
37
- assert f*g == g == g*f
38
- assert h*g == homomorphism(F, F, [0, [1, 0]])
39
- assert g*h == homomorphism(F, F, [0, 0])
40
- assert i*f == i
41
- assert f([1, 2]) == [1, 2]
42
- assert g([1, 2]) == [2, 2*x]
43
-
44
- assert i.restrict_domain(F.submodule([x, x]))([x, x]) == i([x, x])
45
- h1 = h.quotient_domain(F.submodule([0, 1]))
46
- assert h1([1, 0]) == h([1, 0])
47
- assert h1.restrict_domain(h1.domain.submodule([x, 0]))([x, 0]) == h([x, 0])
48
-
49
- raises(TypeError, lambda: f/g)
50
- raises(TypeError, lambda: f + 1)
51
- raises(TypeError, lambda: f + i)
52
- raises(TypeError, lambda: f - 1)
53
- raises(TypeError, lambda: f*i)
54
-
55
-
56
- def test_creation():
57
- F = QQ.old_poly_ring(x).free_module(3)
58
- G = QQ.old_poly_ring(x).free_module(2)
59
- SM = F.submodule([1, 1, 1])
60
- Q = F / SM
61
- SQ = Q.submodule([1, 0, 0])
62
-
63
- matrix = [[1, 0], [0, 1], [-1, -1]]
64
- h = homomorphism(F, G, matrix)
65
- h2 = homomorphism(Q, G, matrix)
66
- assert h.quotient_domain(SM) == h2
67
- raises(ValueError, lambda: h.quotient_domain(F.submodule([1, 0, 0])))
68
- assert h2.restrict_domain(SQ) == homomorphism(SQ, G, matrix)
69
- raises(ValueError, lambda: h.restrict_domain(G))
70
- raises(ValueError, lambda: h.restrict_codomain(G.submodule([1, 0])))
71
- raises(ValueError, lambda: h.quotient_codomain(F))
72
-
73
- im = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
74
- for M in [F, SM, Q, SQ]:
75
- assert M.identity_hom() == homomorphism(M, M, im)
76
- assert SM.inclusion_hom() == homomorphism(SM, F, im)
77
- assert SQ.inclusion_hom() == homomorphism(SQ, Q, im)
78
- assert Q.quotient_hom() == homomorphism(F, Q, im)
79
- assert SQ.quotient_hom() == homomorphism(SQ.base, SQ, im)
80
-
81
- class conv:
82
- def convert(x, y=None):
83
- return x
84
-
85
- class dummy:
86
- container = conv()
87
-
88
- def submodule(*args):
89
- return None
90
- raises(TypeError, lambda: homomorphism(dummy(), G, matrix))
91
- raises(TypeError, lambda: homomorphism(F, dummy(), matrix))
92
- raises(
93
- ValueError, lambda: homomorphism(QQ.old_poly_ring(x, y).free_module(3), G, matrix))
94
- raises(ValueError, lambda: homomorphism(F, G, [0, 0]))
95
-
96
-
97
- def test_properties():
98
- R = QQ.old_poly_ring(x, y)
99
- F = R.free_module(2)
100
- h = homomorphism(F, F, [[x, 0], [y, 0]])
101
- assert h.kernel() == F.submodule([-y, x])
102
- assert h.image() == F.submodule([x, 0], [y, 0])
103
- assert not h.is_injective()
104
- assert not h.is_surjective()
105
- assert h.restrict_codomain(h.image()).is_surjective()
106
- assert h.restrict_domain(F.submodule([1, 0])).is_injective()
107
- assert h.quotient_domain(
108
- h.kernel()).restrict_codomain(h.image()).is_isomorphism()
109
-
110
- R2 = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) / [x**2 + 1]
111
- F = R2.free_module(2)
112
- h = homomorphism(F, F, [[x, 0], [y, y + 1]])
113
- assert h.is_isomorphism()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b4b2ab4ef7b3c4bfcfff6eca7136078b7c168c81adab9d952790797eea37249/blob DELETED
@@ -1,63 +0,0 @@
1
- from typing import Any, Dict, Optional, TypeVar, Union
2
-
3
- from django.db.models.expressions import Combinable, CombinedExpression, Func, Value, _OutputField
4
- from django.db.models.lookups import Lookup
5
-
6
- from django.db.models import Field
7
-
8
- _Expression = Union[str, Combinable, "SearchQueryCombinable"]
9
-
10
- class SearchVectorExact(Lookup): ...
11
- class SearchVectorField(Field): ...
12
- class SearchQueryField(Field): ...
13
-
14
- class SearchVectorCombinable:
15
- ADD: str = ...
16
-
17
- class SearchVector(SearchVectorCombinable, Func):
18
- config: Optional[Any] = ...
19
- def __init__(self, *expressions: _Expression, **extra: Any): ...
20
-
21
- class CombinedSearchVector(SearchVectorCombinable, CombinedExpression):
22
- def __init__(
23
- self, lhs, connector, rhs, config: Optional[_Expression] = ..., output_field: Optional[_OutputField] = ...
24
- ): ...
25
-
26
- _T = TypeVar("_T", bound="SearchQueryCombinable")
27
-
28
- class SearchQueryCombinable:
29
- BITAND: str = ...
30
- BITOR: str = ...
31
- def __or__(self: _T, other: SearchQueryCombinable) -> _T: ...
32
- def __ror__(self: _T, other: SearchQueryCombinable) -> _T: ...
33
- def __and__(self: _T, other: SearchQueryCombinable) -> _T: ...
34
- def __rand__(self: _T, other: SearchQueryCombinable) -> _T: ...
35
-
36
- class SearchQuery(SearchQueryCombinable, Value): # type: ignore
37
- SEARCH_TYPES: Dict[str, str] = ...
38
- def __init__(
39
- self,
40
- value: str,
41
- output_field: Optional[_OutputField] = ...,
42
- *,
43
- config: Optional[_Expression] = ...,
44
- invert: bool = ...,
45
- search_type: str = ...
46
- ): ...
47
- def __invert__(self: _T) -> _T: ...
48
-
49
- class CombinedSearchQuery(SearchQueryCombinable, CombinedExpression): # type: ignore
50
- def __init__(
51
- self, lhs, connector, rhs, config: Optional[_Expression] = ..., output_field: Optional[_OutputField] = ...
52
- ) -> None: ...
53
-
54
- class SearchRank(Func):
55
- def __init__(
56
- self, vector: Union[SearchVector, _Expression], query: Union[SearchQuery, _Expression], **extra: Any
57
- ) -> None: ...
58
-
59
- class TrigramBase(Func):
60
- def __init__(self, expression: _Expression, string, **extra: Any) -> None: ...
61
-
62
- class TrigramSimilarity(TrigramBase): ...
63
- class TrigramDistance(TrigramBase): ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b4d6e6e077c5be4e16cbf790138fb75158aea70027ab99005cd0cac43cf42bf/blob DELETED
@@ -1,68 +0,0 @@
1
- # Authors: The scikit-learn developers
2
- # SPDX-License-Identifier: BSD-3-Clause
3
-
4
-
5
- def _check_feature_names(X, feature_names=None):
6
- """Check feature names.
7
-
8
- Parameters
9
- ----------
10
- X : array-like of shape (n_samples, n_features)
11
- Input data.
12
-
13
- feature_names : None or array-like of shape (n_names,), dtype=str
14
- Feature names to check or `None`.
15
-
16
- Returns
17
- -------
18
- feature_names : list of str
19
- Feature names validated. If `feature_names` is `None`, then a list of
20
- feature names is provided, i.e. the column names of a pandas dataframe
21
- or a generic list of feature names (e.g. `["x0", "x1", ...]`) for a
22
- NumPy array.
23
- """
24
- if feature_names is None:
25
- if hasattr(X, "columns") and hasattr(X.columns, "tolist"):
26
- # get the column names for a pandas dataframe
27
- feature_names = X.columns.tolist()
28
- else:
29
- # define a list of numbered indices for a numpy array
30
- feature_names = [f"x{i}" for i in range(X.shape[1])]
31
- elif hasattr(feature_names, "tolist"):
32
- # convert numpy array or pandas index to a list
33
- feature_names = feature_names.tolist()
34
- if len(set(feature_names)) != len(feature_names):
35
- raise ValueError("feature_names should not contain duplicates.")
36
-
37
- return feature_names
38
-
39
-
40
- def _get_feature_index(fx, feature_names=None):
41
- """Get feature index.
42
-
43
- Parameters
44
- ----------
45
- fx : int or str
46
- Feature index or name.
47
-
48
- feature_names : list of str, default=None
49
- All feature names from which to search the indices.
50
-
51
- Returns
52
- -------
53
- idx : int
54
- Feature index.
55
- """
56
- if isinstance(fx, str):
57
- if feature_names is None:
58
- raise ValueError(
59
- f"Cannot plot partial dependence for feature {fx!r} since "
60
- "the list of feature names was not provided, neither as "
61
- "column names of a pandas data-frame nor via the feature_names "
62
- "parameter."
63
- )
64
- try:
65
- return feature_names.index(fx)
66
- except ValueError as e:
67
- raise ValueError(f"Feature {fx!r} not in feature_names") from e
68
- return fx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b4fa9e614c6536132eee050ac1ecb48f813bd2d02f05afe480f5dd81017e8c9/blob DELETED
@@ -1,687 +0,0 @@
1
- import itertools
2
-
3
- from sympy.concrete.summations import Sum
4
- from sympy.core.add import Add
5
- from sympy.core.expr import Expr
6
- from sympy.core.function import expand as _expand
7
- from sympy.core.mul import Mul
8
- from sympy.core.relational import Eq
9
- from sympy.core.singleton import S
10
- from sympy.core.symbol import Symbol
11
- from sympy.integrals.integrals import Integral
12
- from sympy.logic.boolalg import Not
13
- from sympy.core.parameters import global_parameters
14
- from sympy.core.sorting import default_sort_key
15
- from sympy.core.sympify import _sympify
16
- from sympy.core.relational import Relational
17
- from sympy.logic.boolalg import Boolean
18
- from sympy.stats import variance, covariance
19
- from sympy.stats.rv import (RandomSymbol, pspace, dependent,
20
- given, sampling_E, RandomIndexedSymbol, is_random,
21
- PSpace, sampling_P, random_symbols)
22
-
23
- __all__ = ['Probability', 'Expectation', 'Variance', 'Covariance']
24
-
25
-
26
- @is_random.register(Expr)
27
- def _(x):
28
- atoms = x.free_symbols
29
- if len(atoms) == 1 and next(iter(atoms)) == x:
30
- return False
31
- return any(is_random(i) for i in atoms)
32
-
33
- @is_random.register(RandomSymbol) # type: ignore
34
- def _(x):
35
- return True
36
-
37
-
38
- class Probability(Expr):
39
- """
40
- Symbolic expression for the probability.
41
-
42
- Examples
43
- ========
44
-
45
- >>> from sympy.stats import Probability, Normal
46
- >>> from sympy import Integral
47
- >>> X = Normal("X", 0, 1)
48
- >>> prob = Probability(X > 1)
49
- >>> prob
50
- Probability(X > 1)
51
-
52
- Integral representation:
53
-
54
- >>> prob.rewrite(Integral)
55
- Integral(sqrt(2)*exp(-_z**2/2)/(2*sqrt(pi)), (_z, 1, oo))
56
-
57
- Evaluation of the integral:
58
-
59
- >>> prob.evaluate_integral()
60
- sqrt(2)*(-sqrt(2)*sqrt(pi)*erf(sqrt(2)/2) + sqrt(2)*sqrt(pi))/(4*sqrt(pi))
61
- """
62
- def __new__(cls, prob, condition=None, **kwargs):
63
- prob = _sympify(prob)
64
- if condition is None:
65
- obj = Expr.__new__(cls, prob)
66
- else:
67
- condition = _sympify(condition)
68
- obj = Expr.__new__(cls, prob, condition)
69
- obj._condition = condition
70
- return obj
71
-
72
- def doit(self, **hints):
73
- condition = self.args[0]
74
- given_condition = self._condition
75
- numsamples = hints.get('numsamples', False)
76
- for_rewrite = not hints.get('for_rewrite', False)
77
-
78
- if isinstance(condition, Not):
79
- return S.One - self.func(condition.args[0], given_condition,
80
- evaluate=for_rewrite).doit(**hints)
81
-
82
- if condition.has(RandomIndexedSymbol):
83
- return pspace(condition).probability(condition, given_condition,
84
- evaluate=for_rewrite)
85
-
86
- if isinstance(given_condition, RandomSymbol):
87
- condrv = random_symbols(condition)
88
- if len(condrv) == 1 and condrv[0] == given_condition:
89
- from sympy.stats.frv_types import BernoulliDistribution
90
- return BernoulliDistribution(self.func(condition).doit(**hints), 0, 1)
91
- if any(dependent(rv, given_condition) for rv in condrv):
92
- return Probability(condition, given_condition)
93
- else:
94
- return Probability(condition).doit()
95
-
96
- if given_condition is not None and \
97
- not isinstance(given_condition, (Relational, Boolean)):
98
- raise ValueError("%s is not a relational or combination of relationals"
99
- % (given_condition))
100
-
101
- if given_condition == False or condition is S.false:
102
- return S.Zero
103
- if not isinstance(condition, (Relational, Boolean)):
104
- raise ValueError("%s is not a relational or combination of relationals"
105
- % (condition))
106
- if condition is S.true:
107
- return S.One
108
-
109
- if numsamples:
110
- return sampling_P(condition, given_condition, numsamples=numsamples)
111
- if given_condition is not None: # If there is a condition
112
- # Recompute on new conditional expr
113
- return Probability(given(condition, given_condition)).doit()
114
-
115
- # Otherwise pass work off to the ProbabilitySpace
116
- if pspace(condition) == PSpace():
117
- return Probability(condition, given_condition)
118
-
119
- result = pspace(condition).probability(condition)
120
- if hasattr(result, 'doit') and for_rewrite:
121
- return result.doit()
122
- else:
123
- return result
124
-
125
- def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs):
126
- return self.func(arg, condition=condition).doit(for_rewrite=True)
127
-
128
- _eval_rewrite_as_Sum = _eval_rewrite_as_Integral
129
-
130
- def evaluate_integral(self):
131
- return self.rewrite(Integral).doit()
132
-
133
-
134
- class Expectation(Expr):
135
- """
136
- Symbolic expression for the expectation.
137
-
138
- Examples
139
- ========
140
-
141
- >>> from sympy.stats import Expectation, Normal, Probability, Poisson
142
- >>> from sympy import symbols, Integral, Sum
143
- >>> mu = symbols("mu")
144
- >>> sigma = symbols("sigma", positive=True)
145
- >>> X = Normal("X", mu, sigma)
146
- >>> Expectation(X)
147
- Expectation(X)
148
- >>> Expectation(X).evaluate_integral().simplify()
149
- mu
150
-
151
- To get the integral expression of the expectation:
152
-
153
- >>> Expectation(X).rewrite(Integral)
154
- Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo))
155
-
156
- The same integral expression, in more abstract terms:
157
-
158
- >>> Expectation(X).rewrite(Probability)
159
- Integral(x*Probability(Eq(X, x)), (x, -oo, oo))
160
-
161
- To get the Summation expression of the expectation for discrete random variables:
162
-
163
- >>> lamda = symbols('lamda', positive=True)
164
- >>> Z = Poisson('Z', lamda)
165
- >>> Expectation(Z).rewrite(Sum)
166
- Sum(Z*lamda**Z*exp(-lamda)/factorial(Z), (Z, 0, oo))
167
-
168
- This class is aware of some properties of the expectation:
169
-
170
- >>> from sympy.abc import a
171
- >>> Expectation(a*X)
172
- Expectation(a*X)
173
- >>> Y = Normal("Y", 1, 2)
174
- >>> Expectation(X + Y)
175
- Expectation(X + Y)
176
-
177
- To expand the ``Expectation`` into its expression, use ``expand()``:
178
-
179
- >>> Expectation(X + Y).expand()
180
- Expectation(X) + Expectation(Y)
181
- >>> Expectation(a*X + Y).expand()
182
- a*Expectation(X) + Expectation(Y)
183
- >>> Expectation(a*X + Y)
184
- Expectation(a*X + Y)
185
- >>> Expectation((X + Y)*(X - Y)).expand()
186
- Expectation(X**2) - Expectation(Y**2)
187
-
188
- To evaluate the ``Expectation``, use ``doit()``:
189
-
190
- >>> Expectation(X + Y).doit()
191
- mu + 1
192
- >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit()
193
- 3*mu + 1
194
-
195
- To prevent evaluating nested ``Expectation``, use ``doit(deep=False)``
196
-
197
- >>> Expectation(X + Expectation(Y)).doit(deep=False)
198
- mu + Expectation(Expectation(Y))
199
- >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit(deep=False)
200
- mu + Expectation(Expectation(Y + Expectation(2*X)))
201
-
202
- """
203
-
204
- def __new__(cls, expr, condition=None, **kwargs):
205
- expr = _sympify(expr)
206
- if expr.is_Matrix:
207
- from sympy.stats.symbolic_multivariate_probability import ExpectationMatrix
208
- return ExpectationMatrix(expr, condition)
209
- if condition is None:
210
- if not is_random(expr):
211
- return expr
212
- obj = Expr.__new__(cls, expr)
213
- else:
214
- condition = _sympify(condition)
215
- obj = Expr.__new__(cls, expr, condition)
216
- obj._condition = condition
217
- return obj
218
-
219
- def expand(self, **hints):
220
- expr = self.args[0]
221
- condition = self._condition
222
-
223
- if not is_random(expr):
224
- return expr
225
-
226
- if isinstance(expr, Add):
227
- return Add.fromiter(Expectation(a, condition=condition).expand()
228
- for a in expr.args)
229
-
230
- expand_expr = _expand(expr)
231
- if isinstance(expand_expr, Add):
232
- return Add.fromiter(Expectation(a, condition=condition).expand()
233
- for a in expand_expr.args)
234
-
235
- elif isinstance(expr, Mul):
236
- rv = []
237
- nonrv = []
238
- for a in expr.args:
239
- if is_random(a):
240
- rv.append(a)
241
- else:
242
- nonrv.append(a)
243
- return Mul.fromiter(nonrv)*Expectation(Mul.fromiter(rv), condition=condition)
244
-
245
- return self
246
-
247
- def doit(self, **hints):
248
- deep = hints.get('deep', True)
249
- condition = self._condition
250
- expr = self.args[0]
251
- numsamples = hints.get('numsamples', False)
252
- for_rewrite = not hints.get('for_rewrite', False)
253
-
254
- if deep:
255
- expr = expr.doit(**hints)
256
-
257
- if not is_random(expr) or isinstance(expr, Expectation): # expr isn't random?
258
- return expr
259
- if numsamples: # Computing by monte carlo sampling?
260
- evalf = hints.get('evalf', True)
261
- return sampling_E(expr, condition, numsamples=numsamples, evalf=evalf)
262
-
263
- if expr.has(RandomIndexedSymbol):
264
- return pspace(expr).compute_expectation(expr, condition)
265
-
266
- # Create new expr and recompute E
267
- if condition is not None: # If there is a condition
268
- return self.func(given(expr, condition)).doit(**hints)
269
-
270
- # A few known statements for efficiency
271
-
272
- if expr.is_Add: # We know that E is Linear
273
- return Add(*[self.func(arg, condition).doit(**hints)
274
- if not isinstance(arg, Expectation) else self.func(arg, condition)
275
- for arg in expr.args])
276
- if expr.is_Mul:
277
- if expr.atoms(Expectation):
278
- return expr
279
-
280
- if pspace(expr) == PSpace():
281
- return self.func(expr)
282
- # Otherwise case is simple, pass work off to the ProbabilitySpace
283
- result = pspace(expr).compute_expectation(expr, evaluate=for_rewrite)
284
- if hasattr(result, 'doit') and for_rewrite:
285
- return result.doit(**hints)
286
- else:
287
- return result
288
-
289
-
290
- def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs):
291
- rvs = arg.atoms(RandomSymbol)
292
- if len(rvs) > 1:
293
- raise NotImplementedError()
294
- if len(rvs) == 0:
295
- return arg
296
-
297
- rv = rvs.pop()
298
- if rv.pspace is None:
299
- raise ValueError("Probability space not known")
300
-
301
- symbol = rv.symbol
302
- if symbol.name[0].isupper():
303
- symbol = Symbol(symbol.name.lower())
304
- else :
305
- symbol = Symbol(symbol.name + "_1")
306
-
307
- if rv.pspace.is_Continuous:
308
- return Integral(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.domain.set.sup))
309
- else:
310
- if rv.pspace.is_Finite:
311
- raise NotImplementedError
312
- else:
313
- return Sum(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.set.sup))
314
-
315
- def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs):
316
- return self.func(arg, condition=condition).doit(deep=False, for_rewrite=True)
317
-
318
- _eval_rewrite_as_Sum = _eval_rewrite_as_Integral # For discrete this will be Sum
319
-
320
- def evaluate_integral(self):
321
- return self.rewrite(Integral).doit()
322
-
323
- evaluate_sum = evaluate_integral
324
-
325
- class Variance(Expr):
326
- """
327
- Symbolic expression for the variance.
328
-
329
- Examples
330
- ========
331
-
332
- >>> from sympy import symbols, Integral
333
- >>> from sympy.stats import Normal, Expectation, Variance, Probability
334
- >>> mu = symbols("mu", positive=True)
335
- >>> sigma = symbols("sigma", positive=True)
336
- >>> X = Normal("X", mu, sigma)
337
- >>> Variance(X)
338
- Variance(X)
339
- >>> Variance(X).evaluate_integral()
340
- sigma**2
341
-
342
- Integral representation of the underlying calculations:
343
-
344
- >>> Variance(X).rewrite(Integral)
345
- Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**2*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo))
346
-
347
- Integral representation, without expanding the PDF:
348
-
349
- >>> Variance(X).rewrite(Probability)
350
- -Integral(x*Probability(Eq(X, x)), (x, -oo, oo))**2 + Integral(x**2*Probability(Eq(X, x)), (x, -oo, oo))
351
-
352
- Rewrite the variance in terms of the expectation
353
-
354
- >>> Variance(X).rewrite(Expectation)
355
- -Expectation(X)**2 + Expectation(X**2)
356
-
357
- Some transformations based on the properties of the variance may happen:
358
-
359
- >>> from sympy.abc import a
360
- >>> Y = Normal("Y", 0, 1)
361
- >>> Variance(a*X)
362
- Variance(a*X)
363
-
364
- To expand the variance in its expression, use ``expand()``:
365
-
366
- >>> Variance(a*X).expand()
367
- a**2*Variance(X)
368
- >>> Variance(X + Y)
369
- Variance(X + Y)
370
- >>> Variance(X + Y).expand()
371
- 2*Covariance(X, Y) + Variance(X) + Variance(Y)
372
-
373
- """
374
- def __new__(cls, arg, condition=None, **kwargs):
375
- arg = _sympify(arg)
376
-
377
- if arg.is_Matrix:
378
- from sympy.stats.symbolic_multivariate_probability import VarianceMatrix
379
- return VarianceMatrix(arg, condition)
380
- if condition is None:
381
- obj = Expr.__new__(cls, arg)
382
- else:
383
- condition = _sympify(condition)
384
- obj = Expr.__new__(cls, arg, condition)
385
- obj._condition = condition
386
- return obj
387
-
388
- def expand(self, **hints):
389
- arg = self.args[0]
390
- condition = self._condition
391
-
392
- if not is_random(arg):
393
- return S.Zero
394
-
395
- if isinstance(arg, RandomSymbol):
396
- return self
397
- elif isinstance(arg, Add):
398
- rv = []
399
- for a in arg.args:
400
- if is_random(a):
401
- rv.append(a)
402
- variances = Add(*(Variance(xv, condition).expand() for xv in rv))
403
- map_to_covar = lambda x: 2*Covariance(*x, condition=condition).expand()
404
- covariances = Add(*map(map_to_covar, itertools.combinations(rv, 2)))
405
- return variances + covariances
406
- elif isinstance(arg, Mul):
407
- nonrv = []
408
- rv = []
409
- for a in arg.args:
410
- if is_random(a):
411
- rv.append(a)
412
- else:
413
- nonrv.append(a**2)
414
- if len(rv) == 0:
415
- return S.Zero
416
- return Mul.fromiter(nonrv)*Variance(Mul.fromiter(rv), condition)
417
-
418
- # this expression contains a RandomSymbol somehow:
419
- return self
420
-
421
- def _eval_rewrite_as_Expectation(self, arg, condition=None, **kwargs):
422
- e1 = Expectation(arg**2, condition)
423
- e2 = Expectation(arg, condition)**2
424
- return e1 - e2
425
-
426
- def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs):
427
- return self.rewrite(Expectation).rewrite(Probability)
428
-
429
- def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs):
430
- return variance(self.args[0], self._condition, evaluate=False)
431
-
432
- _eval_rewrite_as_Sum = _eval_rewrite_as_Integral
433
-
434
- def evaluate_integral(self):
435
- return self.rewrite(Integral).doit()
436
-
437
-
438
- class Covariance(Expr):
439
- """
440
- Symbolic expression for the covariance.
441
-
442
- Examples
443
- ========
444
-
445
- >>> from sympy.stats import Covariance
446
- >>> from sympy.stats import Normal
447
- >>> X = Normal("X", 3, 2)
448
- >>> Y = Normal("Y", 0, 1)
449
- >>> Z = Normal("Z", 0, 1)
450
- >>> W = Normal("W", 0, 1)
451
- >>> cexpr = Covariance(X, Y)
452
- >>> cexpr
453
- Covariance(X, Y)
454
-
455
- Evaluate the covariance, `X` and `Y` are independent,
456
- therefore zero is the result:
457
-
458
- >>> cexpr.evaluate_integral()
459
- 0
460
-
461
- Rewrite the covariance expression in terms of expectations:
462
-
463
- >>> from sympy.stats import Expectation
464
- >>> cexpr.rewrite(Expectation)
465
- Expectation(X*Y) - Expectation(X)*Expectation(Y)
466
-
467
- In order to expand the argument, use ``expand()``:
468
-
469
- >>> from sympy.abc import a, b, c, d
470
- >>> Covariance(a*X + b*Y, c*Z + d*W)
471
- Covariance(a*X + b*Y, c*Z + d*W)
472
- >>> Covariance(a*X + b*Y, c*Z + d*W).expand()
473
- a*c*Covariance(X, Z) + a*d*Covariance(W, X) + b*c*Covariance(Y, Z) + b*d*Covariance(W, Y)
474
-
475
- This class is aware of some properties of the covariance:
476
-
477
- >>> Covariance(X, X).expand()
478
- Variance(X)
479
- >>> Covariance(a*X, b*Y).expand()
480
- a*b*Covariance(X, Y)
481
- """
482
-
483
- def __new__(cls, arg1, arg2, condition=None, **kwargs):
484
- arg1 = _sympify(arg1)
485
- arg2 = _sympify(arg2)
486
-
487
- if arg1.is_Matrix or arg2.is_Matrix:
488
- from sympy.stats.symbolic_multivariate_probability import CrossCovarianceMatrix
489
- return CrossCovarianceMatrix(arg1, arg2, condition)
490
-
491
- if kwargs.pop('evaluate', global_parameters.evaluate):
492
- arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)
493
-
494
- if condition is None:
495
- obj = Expr.__new__(cls, arg1, arg2)
496
- else:
497
- condition = _sympify(condition)
498
- obj = Expr.__new__(cls, arg1, arg2, condition)
499
- obj._condition = condition
500
- return obj
501
-
502
- def expand(self, **hints):
503
- arg1 = self.args[0]
504
- arg2 = self.args[1]
505
- condition = self._condition
506
-
507
- if arg1 == arg2:
508
- return Variance(arg1, condition).expand()
509
-
510
- if not is_random(arg1):
511
- return S.Zero
512
- if not is_random(arg2):
513
- return S.Zero
514
-
515
- arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)
516
-
517
- if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol):
518
- return Covariance(arg1, arg2, condition)
519
-
520
- coeff_rv_list1 = self._expand_single_argument(arg1.expand())
521
- coeff_rv_list2 = self._expand_single_argument(arg2.expand())
522
-
523
- addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), condition=condition)
524
- for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2]
525
- return Add.fromiter(addends)
526
-
527
- @classmethod
528
- def _expand_single_argument(cls, expr):
529
- # return (coefficient, random_symbol) pairs:
530
- if isinstance(expr, RandomSymbol):
531
- return [(S.One, expr)]
532
- elif isinstance(expr, Add):
533
- outval = []
534
- for a in expr.args:
535
- if isinstance(a, Mul):
536
- outval.append(cls._get_mul_nonrv_rv_tuple(a))
537
- elif is_random(a):
538
- outval.append((S.One, a))
539
-
540
- return outval
541
- elif isinstance(expr, Mul):
542
- return [cls._get_mul_nonrv_rv_tuple(expr)]
543
- elif is_random(expr):
544
- return [(S.One, expr)]
545
-
546
- @classmethod
547
- def _get_mul_nonrv_rv_tuple(cls, m):
548
- rv = []
549
- nonrv = []
550
- for a in m.args:
551
- if is_random(a):
552
- rv.append(a)
553
- else:
554
- nonrv.append(a)
555
- return (Mul.fromiter(nonrv), Mul.fromiter(rv))
556
-
557
- def _eval_rewrite_as_Expectation(self, arg1, arg2, condition=None, **kwargs):
558
- e1 = Expectation(arg1*arg2, condition)
559
- e2 = Expectation(arg1, condition)*Expectation(arg2, condition)
560
- return e1 - e2
561
-
562
- def _eval_rewrite_as_Probability(self, arg1, arg2, condition=None, **kwargs):
563
- return self.rewrite(Expectation).rewrite(Probability)
564
-
565
- def _eval_rewrite_as_Integral(self, arg1, arg2, condition=None, **kwargs):
566
- return covariance(self.args[0], self.args[1], self._condition, evaluate=False)
567
-
568
- _eval_rewrite_as_Sum = _eval_rewrite_as_Integral
569
-
570
- def evaluate_integral(self):
571
- return self.rewrite(Integral).doit()
572
-
573
-
574
- class Moment(Expr):
575
- """
576
- Symbolic class for Moment
577
-
578
- Examples
579
- ========
580
-
581
- >>> from sympy import Symbol, Integral
582
- >>> from sympy.stats import Normal, Expectation, Probability, Moment
583
- >>> mu = Symbol('mu', real=True)
584
- >>> sigma = Symbol('sigma', positive=True)
585
- >>> X = Normal('X', mu, sigma)
586
- >>> M = Moment(X, 3, 1)
587
-
588
- To evaluate the result of Moment use `doit`:
589
-
590
- >>> M.doit()
591
- mu**3 - 3*mu**2 + 3*mu*sigma**2 + 3*mu - 3*sigma**2 - 1
592
-
593
- Rewrite the Moment expression in terms of Expectation:
594
-
595
- >>> M.rewrite(Expectation)
596
- Expectation((X - 1)**3)
597
-
598
- Rewrite the Moment expression in terms of Probability:
599
-
600
- >>> M.rewrite(Probability)
601
- Integral((x - 1)**3*Probability(Eq(X, x)), (x, -oo, oo))
602
-
603
- Rewrite the Moment expression in terms of Integral:
604
-
605
- >>> M.rewrite(Integral)
606
- Integral(sqrt(2)*(X - 1)**3*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo))
607
-
608
- """
609
- def __new__(cls, X, n, c=0, condition=None, **kwargs):
610
- X = _sympify(X)
611
- n = _sympify(n)
612
- c = _sympify(c)
613
- if condition is not None:
614
- condition = _sympify(condition)
615
- return super().__new__(cls, X, n, c, condition)
616
- else:
617
- return super().__new__(cls, X, n, c)
618
-
619
- def doit(self, **hints):
620
- return self.rewrite(Expectation).doit(**hints)
621
-
622
- def _eval_rewrite_as_Expectation(self, X, n, c=0, condition=None, **kwargs):
623
- return Expectation((X - c)**n, condition)
624
-
625
- def _eval_rewrite_as_Probability(self, X, n, c=0, condition=None, **kwargs):
626
- return self.rewrite(Expectation).rewrite(Probability)
627
-
628
- def _eval_rewrite_as_Integral(self, X, n, c=0, condition=None, **kwargs):
629
- return self.rewrite(Expectation).rewrite(Integral)
630
-
631
-
632
- class CentralMoment(Expr):
633
- """
634
- Symbolic class Central Moment
635
-
636
- Examples
637
- ========
638
-
639
- >>> from sympy import Symbol, Integral
640
- >>> from sympy.stats import Normal, Expectation, Probability, CentralMoment
641
- >>> mu = Symbol('mu', real=True)
642
- >>> sigma = Symbol('sigma', positive=True)
643
- >>> X = Normal('X', mu, sigma)
644
- >>> CM = CentralMoment(X, 4)
645
-
646
- To evaluate the result of CentralMoment use `doit`:
647
-
648
- >>> CM.doit().simplify()
649
- 3*sigma**4
650
-
651
- Rewrite the CentralMoment expression in terms of Expectation:
652
-
653
- >>> CM.rewrite(Expectation)
654
- Expectation((X - Expectation(X))**4)
655
-
656
- Rewrite the CentralMoment expression in terms of Probability:
657
-
658
- >>> CM.rewrite(Probability)
659
- Integral((x - Integral(x*Probability(True), (x, -oo, oo)))**4*Probability(Eq(X, x)), (x, -oo, oo))
660
-
661
- Rewrite the CentralMoment expression in terms of Integral:
662
-
663
- >>> CM.rewrite(Integral)
664
- Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**4*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo))
665
-
666
- """
667
- def __new__(cls, X, n, condition=None, **kwargs):
668
- X = _sympify(X)
669
- n = _sympify(n)
670
- if condition is not None:
671
- condition = _sympify(condition)
672
- return super().__new__(cls, X, n, condition)
673
- else:
674
- return super().__new__(cls, X, n)
675
-
676
- def doit(self, **hints):
677
- return self.rewrite(Expectation).doit(**hints)
678
-
679
- def _eval_rewrite_as_Expectation(self, X, n, condition=None, **kwargs):
680
- mu = Expectation(X, condition, **kwargs)
681
- return Moment(X, n, mu, condition, **kwargs).rewrite(Expectation)
682
-
683
- def _eval_rewrite_as_Probability(self, X, n, condition=None, **kwargs):
684
- return self.rewrite(Expectation).rewrite(Probability)
685
-
686
- def _eval_rewrite_as_Integral(self, X, n, condition=None, **kwargs):
687
- return self.rewrite(Expectation).rewrite(Integral)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b542cdd392345b80afdab68e0f7056548da6fee5a1315a7bf918d1b54bd957b/blob DELETED
@@ -1,11 +0,0 @@
1
- from .optimizer import Optimizer, ParamsT
2
-
3
- class Adadelta(Optimizer):
4
- def __init__(
5
- self,
6
- params: ParamsT,
7
- lr: float = ...,
8
- rho: float = ...,
9
- eps: float = ...,
10
- weight_decay: float = ...,
11
- ) -> None: ...
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b5b3703806bbd17835f93e58836a5639dd884f7ef875b3ec7879f6b57e521a1/blob DELETED
@@ -1,95 +0,0 @@
1
- """A variety of linear models."""
2
-
3
- # Authors: The scikit-learn developers
4
- # SPDX-License-Identifier: BSD-3-Clause
5
-
6
- # See http://scikit-learn.sourceforge.net/modules/sgd.html and
7
- # http://scikit-learn.sourceforge.net/modules/linear_model.html for
8
- # complete documentation.
9
-
10
- from ._base import LinearRegression
11
- from ._bayes import ARDRegression, BayesianRidge
12
- from ._coordinate_descent import (
13
- ElasticNet,
14
- ElasticNetCV,
15
- Lasso,
16
- LassoCV,
17
- MultiTaskElasticNet,
18
- MultiTaskElasticNetCV,
19
- MultiTaskLasso,
20
- MultiTaskLassoCV,
21
- enet_path,
22
- lasso_path,
23
- )
24
- from ._glm import GammaRegressor, PoissonRegressor, TweedieRegressor
25
- from ._huber import HuberRegressor
26
- from ._least_angle import (
27
- Lars,
28
- LarsCV,
29
- LassoLars,
30
- LassoLarsCV,
31
- LassoLarsIC,
32
- lars_path,
33
- lars_path_gram,
34
- )
35
- from ._logistic import LogisticRegression, LogisticRegressionCV
36
- from ._omp import (
37
- OrthogonalMatchingPursuit,
38
- OrthogonalMatchingPursuitCV,
39
- orthogonal_mp,
40
- orthogonal_mp_gram,
41
- )
42
- from ._passive_aggressive import PassiveAggressiveClassifier, PassiveAggressiveRegressor
43
- from ._perceptron import Perceptron
44
- from ._quantile import QuantileRegressor
45
- from ._ransac import RANSACRegressor
46
- from ._ridge import Ridge, RidgeClassifier, RidgeClassifierCV, RidgeCV, ridge_regression
47
- from ._stochastic_gradient import SGDClassifier, SGDOneClassSVM, SGDRegressor
48
- from ._theil_sen import TheilSenRegressor
49
-
50
- __all__ = [
51
- "ARDRegression",
52
- "BayesianRidge",
53
- "ElasticNet",
54
- "ElasticNetCV",
55
- "GammaRegressor",
56
- "HuberRegressor",
57
- "Lars",
58
- "LarsCV",
59
- "Lasso",
60
- "LassoCV",
61
- "LassoLars",
62
- "LassoLarsCV",
63
- "LassoLarsIC",
64
- "LinearRegression",
65
- "LogisticRegression",
66
- "LogisticRegressionCV",
67
- "MultiTaskElasticNet",
68
- "MultiTaskElasticNetCV",
69
- "MultiTaskLasso",
70
- "MultiTaskLassoCV",
71
- "OrthogonalMatchingPursuit",
72
- "OrthogonalMatchingPursuitCV",
73
- "PassiveAggressiveClassifier",
74
- "PassiveAggressiveRegressor",
75
- "Perceptron",
76
- "PoissonRegressor",
77
- "QuantileRegressor",
78
- "RANSACRegressor",
79
- "Ridge",
80
- "RidgeCV",
81
- "RidgeClassifier",
82
- "RidgeClassifierCV",
83
- "SGDClassifier",
84
- "SGDOneClassSVM",
85
- "SGDRegressor",
86
- "TheilSenRegressor",
87
- "TweedieRegressor",
88
- "enet_path",
89
- "lars_path",
90
- "lars_path_gram",
91
- "lasso_path",
92
- "orthogonal_mp",
93
- "orthogonal_mp_gram",
94
- "ridge_regression",
95
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b62149e65ae88c6dd4da6bc3fd68cac9355d5be78045d9faf3270495fdc5451/blob DELETED
@@ -1,160 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import TYPE_CHECKING, Any
4
-
5
- from narwhals._compliant.any_namespace import StringNamespace
6
- from narwhals._pandas_like.utils import (
7
- PandasLikeSeriesNamespace,
8
- align_and_extract_native,
9
- get_dtype_backend,
10
- is_dtype_pyarrow,
11
- )
12
- from narwhals._utils import str_slice_stop
13
-
14
- if TYPE_CHECKING:
15
- from narwhals._pandas_like.series import PandasLikeSeries
16
-
17
-
18
- class PandasLikeSeriesStringNamespace(
19
- PandasLikeSeriesNamespace, StringNamespace["PandasLikeSeries"]
20
- ):
21
- def _with_native_bool(self, result: Any) -> PandasLikeSeries:
22
- # See https://narwhals-dev.github.io/narwhals/concepts/boolean/.
23
- if (
24
- result.dtype == object
25
- and get_dtype_backend(self.native.dtype, self.implementation) is None
26
- ):
27
- not_na = result.notna()
28
- all_valid = not_na.all()
29
- if not all_valid and self.implementation._backend_version() < (3,):
30
- result.where(not_na, False, inplace=True)
31
- result = result.astype(bool, copy=False)
32
- elif not all_valid:
33
- result = result.where(not_na, False).astype(bool)
34
- else: # pragma: no cover
35
- pass
36
- return self.with_native(result)
37
-
38
- def len_chars(self) -> PandasLikeSeries:
39
- result = self.native.str.len()
40
- if result.dtype == object:
41
- # pandas returns `object` instead of a number for an all-null `object` column.
42
- result = self.implementation.to_native_namespace().to_numeric(result)
43
- return self.with_native(result)
44
-
45
- def replace(
46
- self, value: PandasLikeSeries, pattern: str, *, literal: bool, n: int
47
- ) -> PandasLikeSeries:
48
- if n == 0:
49
- return self.compliant
50
- _, value_native = align_and_extract_native(self.compliant, value)
51
- if not isinstance(value_native, str):
52
- msg = f"{self.compliant._implementation} backed `.str.replace` only supports str replacement values"
53
- raise TypeError(msg)
54
- series = self.native.str.replace(
55
- pat=pattern, repl=value_native, n=n, regex=not literal
56
- )
57
- return self.with_native(series)
58
-
59
- def replace_all(
60
- self, value: PandasLikeSeries, pattern: str, *, literal: bool
61
- ) -> PandasLikeSeries:
62
- return self.replace(value, pattern, literal=literal, n=-1)
63
-
64
- def strip_chars(self, characters: str | None) -> PandasLikeSeries:
65
- return self.with_native(self.native.str.strip(characters))
66
-
67
- def strip_chars_start(self, characters: str) -> PandasLikeSeries:
68
- return self.with_native(self.native.str.lstrip(characters))
69
-
70
- def strip_chars_end(self, characters: str) -> PandasLikeSeries:
71
- return self.with_native(self.native.str.rstrip(characters))
72
-
73
- def starts_with(self, prefix: PandasLikeSeries) -> PandasLikeSeries:
74
- _, prefix_native = align_and_extract_native(self.compliant, prefix)
75
- if not isinstance(prefix_native, str):
76
- msg = f"`.str.starts_with` only supports prefix values for {self.compliant._implementation} backend"
77
- raise TypeError(msg)
78
- return self._with_native_bool(self.native.str.startswith(prefix_native))
79
-
80
- def ends_with(self, suffix: PandasLikeSeries) -> PandasLikeSeries:
81
- _, suffix_native = align_and_extract_native(self.compliant, suffix)
82
- if not isinstance(suffix_native, str):
83
- msg = f"`.str.ends_with` only supports suffix values for {self.compliant._implementation} backend"
84
- raise TypeError(msg)
85
- return self._with_native_bool(self.native.str.endswith(suffix_native))
86
-
87
- def contains(self, pattern: PandasLikeSeries, *, literal: bool) -> PandasLikeSeries:
88
- _, pattern_native = align_and_extract_native(self.compliant, pattern)
89
- if not isinstance(pattern_native, str):
90
- msg = f"`.str.contains` only supports str pattern values for {self.compliant._implementation} backend"
91
- raise TypeError(msg)
92
- return self._with_native_bool(
93
- self.native.str.contains(pat=pattern_native, regex=not literal)
94
- )
95
-
96
- def slice(self, offset: int, length: int | None) -> PandasLikeSeries:
97
- stop = str_slice_stop(offset, length)
98
- return self.with_native(self.native.str.slice(start=offset, stop=stop))
99
-
100
- def split(self, by: str) -> PandasLikeSeries:
101
- implementation = self.implementation
102
- if not implementation.is_cudf() and not is_dtype_pyarrow(self.native.dtype):
103
- msg = (
104
- "This operation requires a pyarrow-backed series. "
105
- "Please refer to https://narwhals-dev.github.io/narwhals/api-reference/narwhals/#narwhals.maybe_convert_dtypes "
106
- "and ensure you are using dtype_backend='pyarrow'. "
107
- "Additionally, make sure you have pandas version 1.5+ and pyarrow installed. "
108
- )
109
- raise TypeError(msg)
110
- return self.with_native(self.native.str.split(pat=by))
111
-
112
- def to_datetime(self, format: str | None) -> PandasLikeSeries:
113
- # If we know inputs are timezone-aware, we can pass `utc=True` for better performance.
114
- if format and any(x in format for x in ("%z", "Z")):
115
- return self.with_native(self._to_datetime(format, utc=True))
116
- result = self.with_native(self._to_datetime(format, utc=False))
117
- if (tz := getattr(result.dtype, "time_zone", None)) and tz != "UTC":
118
- return result.dt.convert_time_zone("UTC")
119
- return result
120
-
121
- def _to_datetime(self, format: str | None, *, utc: bool) -> Any:
122
- result = self.implementation.to_native_namespace().to_datetime(
123
- self.native, format=format, utc=utc
124
- )
125
- return (
126
- result.convert_dtypes(dtype_backend="pyarrow")
127
- if is_dtype_pyarrow(self.native.dtype)
128
- else result
129
- )
130
-
131
- def to_date(self, format: str | None) -> PandasLikeSeries:
132
- return self.to_datetime(format=format).dt.date()
133
-
134
- def to_time(self, format: str | None) -> PandasLikeSeries:
135
- time_dtype = self.version.dtypes.Time()
136
- return self.with_native(self._to_datetime(format, utc=False)).cast(time_dtype)
137
-
138
- def to_uppercase(self) -> PandasLikeSeries:
139
- return self.with_native(self.native.str.upper())
140
-
141
- def to_lowercase(self) -> PandasLikeSeries:
142
- return self.with_native(self.native.str.lower())
143
-
144
- def to_titlecase(self) -> PandasLikeSeries:
145
- return self.with_native(self.native.str.title())
146
-
147
- def zfill(self, width: int) -> PandasLikeSeries:
148
- if width == 0:
149
- return self.compliant
150
- return self.with_native(self.native.str.zfill(width))
151
-
152
- def pad_start(self, length: int, fill_char: str) -> PandasLikeSeries:
153
- return self.with_native(
154
- self.native.str.pad(width=length, fillchar=fill_char, side="left")
155
- )
156
-
157
- def pad_end(self, length: int, fill_char: str) -> PandasLikeSeries:
158
- return self.with_native(
159
- self.native.str.pad(width=length, fillchar=fill_char, side="right")
160
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b633e2d6aa5d803d19bb099de8163f7b49408a1bfaea3fe3e7d519e15dda808/blob DELETED
@@ -1,50 +0,0 @@
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 ldexp_Tensor {
18
- using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
19
- using ptr_schema = schema*;
20
- // See Note [static constexpr char* members for windows NVCC]
21
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::ldexp")
22
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
23
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ldexp.Tensor(Tensor self, Tensor other) -> Tensor")
24
- static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
25
- static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
26
- };
27
-
28
- struct TORCH_API ldexp_ {
29
- using schema = at::Tensor & (at::Tensor &, const 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::ldexp_")
33
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ldexp_(Tensor(a!) self, Tensor other) -> Tensor(a!)")
35
- static at::Tensor & call(at::Tensor & self, const at::Tensor & other);
36
- static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other);
37
- };
38
-
39
- struct TORCH_API ldexp_out {
40
- using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
41
- using ptr_schema = schema*;
42
- // See Note [static constexpr char* members for windows NVCC]
43
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::ldexp")
44
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
45
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "ldexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)")
46
- static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
47
- static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
48
- };
49
-
50
- }} // namespace at::_ops
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b65eeebf6d708da9966136f37d3d3eef925cdce7587f22da457eeee1f8ba83e/blob DELETED
@@ -1,557 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import ctypes
4
- import re
5
- from typing import Any
6
-
7
- import numpy as np
8
-
9
- from pandas._config import using_string_dtype
10
-
11
- from pandas.compat._optional import import_optional_dependency
12
- from pandas.errors import SettingWithCopyError
13
-
14
- import pandas as pd
15
- from pandas.core.interchange.dataframe_protocol import (
16
- Buffer,
17
- Column,
18
- ColumnNullType,
19
- DataFrame as DataFrameXchg,
20
- DtypeKind,
21
- )
22
- from pandas.core.interchange.utils import (
23
- ArrowCTypes,
24
- Endianness,
25
- )
26
-
27
- _NP_DTYPES: dict[DtypeKind, dict[int, Any]] = {
28
- DtypeKind.INT: {8: np.int8, 16: np.int16, 32: np.int32, 64: np.int64},
29
- DtypeKind.UINT: {8: np.uint8, 16: np.uint16, 32: np.uint32, 64: np.uint64},
30
- DtypeKind.FLOAT: {32: np.float32, 64: np.float64},
31
- DtypeKind.BOOL: {1: bool, 8: bool},
32
- }
33
-
34
-
35
- def from_dataframe(df, allow_copy: bool = True) -> pd.DataFrame:
36
- """
37
- Build a ``pd.DataFrame`` from any DataFrame supporting the interchange protocol.
38
-
39
- .. note::
40
-
41
- For new development, we highly recommend using the Arrow C Data Interface
42
- alongside the Arrow PyCapsule Interface instead of the interchange protocol.
43
- From pandas 2.3 onwards, `from_dataframe` uses the PyCapsule Interface,
44
- only falling back to the interchange protocol if that fails.
45
-
46
- .. warning::
47
-
48
- Due to severe implementation issues, we recommend only considering using the
49
- interchange protocol in the following cases:
50
-
51
- - converting to pandas: for pandas >= 2.0.3
52
- - converting from pandas: for pandas >= 3.0.0
53
-
54
- Parameters
55
- ----------
56
- df : DataFrameXchg
57
- Object supporting the interchange protocol, i.e. `__dataframe__` method.
58
- allow_copy : bool, default: True
59
- Whether to allow copying the memory to perform the conversion
60
- (if false then zero-copy approach is requested).
61
-
62
- Returns
63
- -------
64
- pd.DataFrame
65
-
66
- Examples
67
- --------
68
- >>> df_not_necessarily_pandas = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
69
- >>> interchange_object = df_not_necessarily_pandas.__dataframe__()
70
- >>> interchange_object.column_names()
71
- Index(['A', 'B'], dtype='object')
72
- >>> df_pandas = (pd.api.interchange.from_dataframe
73
- ... (interchange_object.select_columns_by_name(['A'])))
74
- >>> df_pandas
75
- A
76
- 0 1
77
- 1 2
78
-
79
- These methods (``column_names``, ``select_columns_by_name``) should work
80
- for any dataframe library which implements the interchange protocol.
81
- """
82
- if isinstance(df, pd.DataFrame):
83
- return df
84
-
85
- if hasattr(df, "__arrow_c_stream__"):
86
- try:
87
- pa = import_optional_dependency("pyarrow", min_version="14.0.0")
88
- except ImportError:
89
- # fallback to _from_dataframe
90
- pass
91
- else:
92
- try:
93
- return pa.table(df).to_pandas(zero_copy_only=not allow_copy)
94
- except pa.ArrowInvalid as e:
95
- raise RuntimeError(e) from e
96
-
97
- if not hasattr(df, "__dataframe__"):
98
- raise ValueError("`df` does not support __dataframe__")
99
-
100
- return _from_dataframe(
101
- df.__dataframe__(allow_copy=allow_copy), allow_copy=allow_copy
102
- )
103
-
104
-
105
- def _from_dataframe(df: DataFrameXchg, allow_copy: bool = True):
106
- """
107
- Build a ``pd.DataFrame`` from the DataFrame interchange object.
108
-
109
- Parameters
110
- ----------
111
- df : DataFrameXchg
112
- Object supporting the interchange protocol, i.e. `__dataframe__` method.
113
- allow_copy : bool, default: True
114
- Whether to allow copying the memory to perform the conversion
115
- (if false then zero-copy approach is requested).
116
-
117
- Returns
118
- -------
119
- pd.DataFrame
120
- """
121
- pandas_dfs = []
122
- for chunk in df.get_chunks():
123
- pandas_df = protocol_df_chunk_to_pandas(chunk)
124
- pandas_dfs.append(pandas_df)
125
-
126
- if not allow_copy and len(pandas_dfs) > 1:
127
- raise RuntimeError(
128
- "To join chunks a copy is required which is forbidden by allow_copy=False"
129
- )
130
- if not pandas_dfs:
131
- pandas_df = protocol_df_chunk_to_pandas(df)
132
- elif len(pandas_dfs) == 1:
133
- pandas_df = pandas_dfs[0]
134
- else:
135
- pandas_df = pd.concat(pandas_dfs, axis=0, ignore_index=True, copy=False)
136
-
137
- index_obj = df.metadata.get("pandas.index", None)
138
- if index_obj is not None:
139
- pandas_df.index = index_obj
140
-
141
- return pandas_df
142
-
143
-
144
- def protocol_df_chunk_to_pandas(df: DataFrameXchg) -> pd.DataFrame:
145
- """
146
- Convert interchange protocol chunk to ``pd.DataFrame``.
147
-
148
- Parameters
149
- ----------
150
- df : DataFrameXchg
151
-
152
- Returns
153
- -------
154
- pd.DataFrame
155
- """
156
- columns: dict[str, Any] = {}
157
- buffers = [] # hold on to buffers, keeps memory alive
158
- for name in df.column_names():
159
- if not isinstance(name, str):
160
- raise ValueError(f"Column {name} is not a string")
161
- if name in columns:
162
- raise ValueError(f"Column {name} is not unique")
163
- col = df.get_column_by_name(name)
164
- dtype = col.dtype[0]
165
- if dtype in (
166
- DtypeKind.INT,
167
- DtypeKind.UINT,
168
- DtypeKind.FLOAT,
169
- DtypeKind.BOOL,
170
- ):
171
- columns[name], buf = primitive_column_to_ndarray(col)
172
- elif dtype == DtypeKind.CATEGORICAL:
173
- columns[name], buf = categorical_column_to_series(col)
174
- elif dtype == DtypeKind.STRING:
175
- columns[name], buf = string_column_to_ndarray(col)
176
- elif dtype == DtypeKind.DATETIME:
177
- columns[name], buf = datetime_column_to_ndarray(col)
178
- else:
179
- raise NotImplementedError(f"Data type {dtype} not handled yet")
180
-
181
- buffers.append(buf)
182
-
183
- pandas_df = pd.DataFrame(columns)
184
- pandas_df.attrs["_INTERCHANGE_PROTOCOL_BUFFERS"] = buffers
185
- return pandas_df
186
-
187
-
188
- def primitive_column_to_ndarray(col: Column) -> tuple[np.ndarray, Any]:
189
- """
190
- Convert a column holding one of the primitive dtypes to a NumPy array.
191
-
192
- A primitive type is one of: int, uint, float, bool.
193
-
194
- Parameters
195
- ----------
196
- col : Column
197
-
198
- Returns
199
- -------
200
- tuple
201
- Tuple of np.ndarray holding the data and the memory owner object
202
- that keeps the memory alive.
203
- """
204
- buffers = col.get_buffers()
205
-
206
- data_buff, data_dtype = buffers["data"]
207
- data = buffer_to_ndarray(
208
- data_buff, data_dtype, offset=col.offset, length=col.size()
209
- )
210
-
211
- data = set_nulls(data, col, buffers["validity"])
212
- return data, buffers
213
-
214
-
215
- def categorical_column_to_series(col: Column) -> tuple[pd.Series, Any]:
216
- """
217
- Convert a column holding categorical data to a pandas Series.
218
-
219
- Parameters
220
- ----------
221
- col : Column
222
-
223
- Returns
224
- -------
225
- tuple
226
- Tuple of pd.Series holding the data and the memory owner object
227
- that keeps the memory alive.
228
- """
229
- categorical = col.describe_categorical
230
-
231
- if not categorical["is_dictionary"]:
232
- raise NotImplementedError("Non-dictionary categoricals not supported yet")
233
-
234
- cat_column = categorical["categories"]
235
- if hasattr(cat_column, "_col"):
236
- # Item "Column" of "Optional[Column]" has no attribute "_col"
237
- # Item "None" of "Optional[Column]" has no attribute "_col"
238
- categories = np.array(cat_column._col) # type: ignore[union-attr]
239
- else:
240
- raise NotImplementedError(
241
- "Interchanging categorical columns isn't supported yet, and our "
242
- "fallback of using the `col._col` attribute (a ndarray) failed."
243
- )
244
- buffers = col.get_buffers()
245
-
246
- codes_buff, codes_dtype = buffers["data"]
247
- codes = buffer_to_ndarray(
248
- codes_buff, codes_dtype, offset=col.offset, length=col.size()
249
- )
250
-
251
- # Doing module in order to not get ``IndexError`` for
252
- # out-of-bounds sentinel values in `codes`
253
- if len(categories) > 0:
254
- values = categories[codes % len(categories)]
255
- else:
256
- values = codes
257
-
258
- cat = pd.Categorical(
259
- values, categories=categories, ordered=categorical["is_ordered"]
260
- )
261
- data = pd.Series(cat)
262
-
263
- data = set_nulls(data, col, buffers["validity"])
264
- return data, buffers
265
-
266
-
267
- def string_column_to_ndarray(col: Column) -> tuple[np.ndarray, Any]:
268
- """
269
- Convert a column holding string data to a NumPy array.
270
-
271
- Parameters
272
- ----------
273
- col : Column
274
-
275
- Returns
276
- -------
277
- tuple
278
- Tuple of np.ndarray holding the data and the memory owner object
279
- that keeps the memory alive.
280
- """
281
- null_kind, sentinel_val = col.describe_null
282
-
283
- if null_kind not in (
284
- ColumnNullType.NON_NULLABLE,
285
- ColumnNullType.USE_BITMASK,
286
- ColumnNullType.USE_BYTEMASK,
287
- ):
288
- raise NotImplementedError(
289
- f"{null_kind} null kind is not yet supported for string columns."
290
- )
291
-
292
- buffers = col.get_buffers()
293
-
294
- assert buffers["offsets"], "String buffers must contain offsets"
295
- # Retrieve the data buffer containing the UTF-8 code units
296
- data_buff, _ = buffers["data"]
297
- # We're going to reinterpret the buffer as uint8, so make sure we can do it safely
298
- assert col.dtype[2] in (
299
- ArrowCTypes.STRING,
300
- ArrowCTypes.LARGE_STRING,
301
- ) # format_str == utf-8
302
- # Convert the buffers to NumPy arrays. In order to go from STRING to
303
- # an equivalent ndarray, we claim that the buffer is uint8 (i.e., a byte array)
304
- data_dtype = (
305
- DtypeKind.UINT,
306
- 8,
307
- ArrowCTypes.UINT8,
308
- Endianness.NATIVE,
309
- )
310
- # Specify zero offset as we don't want to chunk the string data
311
- data = buffer_to_ndarray(data_buff, data_dtype, offset=0, length=data_buff.bufsize)
312
-
313
- # Retrieve the offsets buffer containing the index offsets demarcating
314
- # the beginning and the ending of each string
315
- offset_buff, offset_dtype = buffers["offsets"]
316
- # Offsets buffer contains start-stop positions of strings in the data buffer,
317
- # meaning that it has more elements than in the data buffer, do `col.size() + 1`
318
- # here to pass a proper offsets buffer size
319
- offsets = buffer_to_ndarray(
320
- offset_buff, offset_dtype, offset=col.offset, length=col.size() + 1
321
- )
322
-
323
- null_pos = None
324
- if null_kind in (ColumnNullType.USE_BITMASK, ColumnNullType.USE_BYTEMASK):
325
- validity = buffers["validity"]
326
- if validity is not None:
327
- valid_buff, valid_dtype = validity
328
- null_pos = buffer_to_ndarray(
329
- valid_buff, valid_dtype, offset=col.offset, length=col.size()
330
- )
331
- if sentinel_val == 0:
332
- null_pos = ~null_pos
333
-
334
- # Assemble the strings from the code units
335
- str_list: list[None | float | str] = [None] * col.size()
336
- for i in range(col.size()):
337
- # Check for missing values
338
- if null_pos is not None and null_pos[i]:
339
- str_list[i] = np.nan
340
- continue
341
-
342
- # Extract a range of code units
343
- units = data[offsets[i] : offsets[i + 1]]
344
-
345
- # Convert the list of code units to bytes
346
- str_bytes = bytes(units)
347
-
348
- # Create the string
349
- string = str_bytes.decode(encoding="utf-8")
350
-
351
- # Add to our list of strings
352
- str_list[i] = string
353
-
354
- if using_string_dtype():
355
- res = pd.Series(str_list, dtype="str")
356
- else:
357
- res = np.asarray(str_list, dtype="object") # type: ignore[assignment]
358
-
359
- return res, buffers # type: ignore[return-value]
360
-
361
-
362
- def parse_datetime_format_str(format_str, data) -> pd.Series | np.ndarray:
363
- """Parse datetime `format_str` to interpret the `data`."""
364
- # timestamp 'ts{unit}:tz'
365
- timestamp_meta = re.match(r"ts([smun]):(.*)", format_str)
366
- if timestamp_meta:
367
- unit, tz = timestamp_meta.group(1), timestamp_meta.group(2)
368
- if unit != "s":
369
- # the format string describes only a first letter of the unit, so
370
- # add one extra letter to convert the unit to numpy-style:
371
- # 'm' -> 'ms', 'u' -> 'us', 'n' -> 'ns'
372
- unit += "s"
373
- data = data.astype(f"datetime64[{unit}]")
374
- if tz != "":
375
- data = pd.Series(data).dt.tz_localize("UTC").dt.tz_convert(tz)
376
- return data
377
-
378
- # date 'td{Days/Ms}'
379
- date_meta = re.match(r"td([Dm])", format_str)
380
- if date_meta:
381
- unit = date_meta.group(1)
382
- if unit == "D":
383
- # NumPy doesn't support DAY unit, so converting days to seconds
384
- # (converting to uint64 to avoid overflow)
385
- data = (data.astype(np.uint64) * (24 * 60 * 60)).astype("datetime64[s]")
386
- elif unit == "m":
387
- data = data.astype("datetime64[ms]")
388
- else:
389
- raise NotImplementedError(f"Date unit is not supported: {unit}")
390
- return data
391
-
392
- raise NotImplementedError(f"DateTime kind is not supported: {format_str}")
393
-
394
-
395
- def datetime_column_to_ndarray(col: Column) -> tuple[np.ndarray | pd.Series, Any]:
396
- """
397
- Convert a column holding DateTime data to a NumPy array.
398
-
399
- Parameters
400
- ----------
401
- col : Column
402
-
403
- Returns
404
- -------
405
- tuple
406
- Tuple of np.ndarray holding the data and the memory owner object
407
- that keeps the memory alive.
408
- """
409
- buffers = col.get_buffers()
410
-
411
- _, col_bit_width, format_str, _ = col.dtype
412
- dbuf, _ = buffers["data"]
413
- # Consider dtype being `uint` to get number of units passed since the 01.01.1970
414
-
415
- data = buffer_to_ndarray(
416
- dbuf,
417
- (
418
- DtypeKind.INT,
419
- col_bit_width,
420
- getattr(ArrowCTypes, f"INT{col_bit_width}"),
421
- Endianness.NATIVE,
422
- ),
423
- offset=col.offset,
424
- length=col.size(),
425
- )
426
-
427
- data = parse_datetime_format_str(format_str, data) # type: ignore[assignment]
428
- data = set_nulls(data, col, buffers["validity"])
429
- return data, buffers
430
-
431
-
432
- def buffer_to_ndarray(
433
- buffer: Buffer,
434
- dtype: tuple[DtypeKind, int, str, str],
435
- *,
436
- length: int,
437
- offset: int = 0,
438
- ) -> np.ndarray:
439
- """
440
- Build a NumPy array from the passed buffer.
441
-
442
- Parameters
443
- ----------
444
- buffer : Buffer
445
- Buffer to build a NumPy array from.
446
- dtype : tuple
447
- Data type of the buffer conforming protocol dtypes format.
448
- offset : int, default: 0
449
- Number of elements to offset from the start of the buffer.
450
- length : int, optional
451
- If the buffer is a bit-mask, specifies a number of bits to read
452
- from the buffer. Has no effect otherwise.
453
-
454
- Returns
455
- -------
456
- np.ndarray
457
-
458
- Notes
459
- -----
460
- The returned array doesn't own the memory. The caller of this function is
461
- responsible for keeping the memory owner object alive as long as
462
- the returned NumPy array is being used.
463
- """
464
- kind, bit_width, _, _ = dtype
465
-
466
- column_dtype = _NP_DTYPES.get(kind, {}).get(bit_width, None)
467
- if column_dtype is None:
468
- raise NotImplementedError(f"Conversion for {dtype} is not yet supported.")
469
-
470
- # TODO: No DLPack yet, so need to construct a new ndarray from the data pointer
471
- # and size in the buffer plus the dtype on the column. Use DLPack as NumPy supports
472
- # it since https://github.com/numpy/numpy/pull/19083
473
- ctypes_type = np.ctypeslib.as_ctypes_type(column_dtype)
474
-
475
- if bit_width == 1:
476
- assert length is not None, "`length` must be specified for a bit-mask buffer."
477
- pa = import_optional_dependency("pyarrow")
478
- arr = pa.BooleanArray.from_buffers(
479
- pa.bool_(),
480
- length,
481
- [None, pa.foreign_buffer(buffer.ptr, length)],
482
- offset=offset,
483
- )
484
- return np.asarray(arr)
485
- else:
486
- data_pointer = ctypes.cast(
487
- buffer.ptr + (offset * bit_width // 8), ctypes.POINTER(ctypes_type)
488
- )
489
- if length > 0:
490
- return np.ctypeslib.as_array(data_pointer, shape=(length,))
491
- return np.array([], dtype=ctypes_type)
492
-
493
-
494
- def set_nulls(
495
- data: np.ndarray | pd.Series,
496
- col: Column,
497
- validity: tuple[Buffer, tuple[DtypeKind, int, str, str]] | None,
498
- allow_modify_inplace: bool = True,
499
- ):
500
- """
501
- Set null values for the data according to the column null kind.
502
-
503
- Parameters
504
- ----------
505
- data : np.ndarray or pd.Series
506
- Data to set nulls in.
507
- col : Column
508
- Column object that describes the `data`.
509
- validity : tuple(Buffer, dtype) or None
510
- The return value of ``col.buffers()``. We do not access the ``col.buffers()``
511
- here to not take the ownership of the memory of buffer objects.
512
- allow_modify_inplace : bool, default: True
513
- Whether to modify the `data` inplace when zero-copy is possible (True) or always
514
- modify a copy of the `data` (False).
515
-
516
- Returns
517
- -------
518
- np.ndarray or pd.Series
519
- Data with the nulls being set.
520
- """
521
- if validity is None:
522
- return data
523
- null_kind, sentinel_val = col.describe_null
524
- null_pos = None
525
-
526
- if null_kind == ColumnNullType.USE_SENTINEL:
527
- null_pos = pd.Series(data) == sentinel_val
528
- elif null_kind in (ColumnNullType.USE_BITMASK, ColumnNullType.USE_BYTEMASK):
529
- assert validity, "Expected to have a validity buffer for the mask"
530
- valid_buff, valid_dtype = validity
531
- null_pos = buffer_to_ndarray(
532
- valid_buff, valid_dtype, offset=col.offset, length=col.size()
533
- )
534
- if sentinel_val == 0:
535
- null_pos = ~null_pos
536
- elif null_kind in (ColumnNullType.NON_NULLABLE, ColumnNullType.USE_NAN):
537
- pass
538
- else:
539
- raise NotImplementedError(f"Null kind {null_kind} is not yet supported.")
540
-
541
- if null_pos is not None and np.any(null_pos):
542
- if not allow_modify_inplace:
543
- data = data.copy()
544
- try:
545
- data[null_pos] = None
546
- except TypeError:
547
- # TypeError happens if the `data` dtype appears to be non-nullable
548
- # in numpy notation (bool, int, uint). If this happens,
549
- # cast the `data` to nullable float dtype.
550
- data = data.astype(float)
551
- data[null_pos] = None
552
- except SettingWithCopyError:
553
- # `SettingWithCopyError` may happen for datetime-like with missing values.
554
- data = data.copy()
555
- data[null_pos] = None
556
-
557
- return data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b66f7e1cf75ec85b9a3e43fe936081e5b0af6549494d8b2ac84d3507ff3c1ec/blob DELETED
@@ -1,353 +0,0 @@
1
- """This is invoked in a subprocess to call the build backend hooks.
2
-
3
- It expects:
4
- - Command line args: hook_name, control_dir
5
- - Environment variables:
6
- PEP517_BUILD_BACKEND=entry.point:spec
7
- PEP517_BACKEND_PATH=paths (separated with os.pathsep)
8
- - control_dir/input.json:
9
- - {"kwargs": {...}}
10
-
11
- Results:
12
- - control_dir/output.json
13
- - {"return_val": ...}
14
- """
15
- import json
16
- import os
17
- import os.path
18
- import re
19
- import shutil
20
- import sys
21
- import traceback
22
- from glob import glob
23
- from importlib import import_module
24
- from os.path import join as pjoin
25
-
26
- # This file is run as a script, and `import wrappers` is not zip-safe, so we
27
- # include write_json() and read_json() from wrappers.py.
28
-
29
-
30
- def write_json(obj, path, **kwargs):
31
- with open(path, 'w', encoding='utf-8') as f:
32
- json.dump(obj, f, **kwargs)
33
-
34
-
35
- def read_json(path):
36
- with open(path, encoding='utf-8') as f:
37
- return json.load(f)
38
-
39
-
40
- class BackendUnavailable(Exception):
41
- """Raised if we cannot import the backend"""
42
- def __init__(self, traceback):
43
- self.traceback = traceback
44
-
45
-
46
- class BackendInvalid(Exception):
47
- """Raised if the backend is invalid"""
48
- def __init__(self, message):
49
- self.message = message
50
-
51
-
52
- class HookMissing(Exception):
53
- """Raised if a hook is missing and we are not executing the fallback"""
54
- def __init__(self, hook_name=None):
55
- super().__init__(hook_name)
56
- self.hook_name = hook_name
57
-
58
-
59
- def contained_in(filename, directory):
60
- """Test if a file is located within the given directory."""
61
- filename = os.path.normcase(os.path.abspath(filename))
62
- directory = os.path.normcase(os.path.abspath(directory))
63
- return os.path.commonprefix([filename, directory]) == directory
64
-
65
-
66
- def _build_backend():
67
- """Find and load the build backend"""
68
- # Add in-tree backend directories to the front of sys.path.
69
- backend_path = os.environ.get('PEP517_BACKEND_PATH')
70
- if backend_path:
71
- extra_pathitems = backend_path.split(os.pathsep)
72
- sys.path[:0] = extra_pathitems
73
-
74
- ep = os.environ['PEP517_BUILD_BACKEND']
75
- mod_path, _, obj_path = ep.partition(':')
76
- try:
77
- obj = import_module(mod_path)
78
- except ImportError:
79
- raise BackendUnavailable(traceback.format_exc())
80
-
81
- if backend_path:
82
- if not any(
83
- contained_in(obj.__file__, path)
84
- for path in extra_pathitems
85
- ):
86
- raise BackendInvalid("Backend was not loaded from backend-path")
87
-
88
- if obj_path:
89
- for path_part in obj_path.split('.'):
90
- obj = getattr(obj, path_part)
91
- return obj
92
-
93
-
94
- def _supported_features():
95
- """Return the list of options features supported by the backend.
96
-
97
- Returns a list of strings.
98
- The only possible value is 'build_editable'.
99
- """
100
- backend = _build_backend()
101
- features = []
102
- if hasattr(backend, "build_editable"):
103
- features.append("build_editable")
104
- return features
105
-
106
-
107
- def get_requires_for_build_wheel(config_settings):
108
- """Invoke the optional get_requires_for_build_wheel hook
109
-
110
- Returns [] if the hook is not defined.
111
- """
112
- backend = _build_backend()
113
- try:
114
- hook = backend.get_requires_for_build_wheel
115
- except AttributeError:
116
- return []
117
- else:
118
- return hook(config_settings)
119
-
120
-
121
- def get_requires_for_build_editable(config_settings):
122
- """Invoke the optional get_requires_for_build_editable hook
123
-
124
- Returns [] if the hook is not defined.
125
- """
126
- backend = _build_backend()
127
- try:
128
- hook = backend.get_requires_for_build_editable
129
- except AttributeError:
130
- return []
131
- else:
132
- return hook(config_settings)
133
-
134
-
135
- def prepare_metadata_for_build_wheel(
136
- metadata_directory, config_settings, _allow_fallback):
137
- """Invoke optional prepare_metadata_for_build_wheel
138
-
139
- Implements a fallback by building a wheel if the hook isn't defined,
140
- unless _allow_fallback is False in which case HookMissing is raised.
141
- """
142
- backend = _build_backend()
143
- try:
144
- hook = backend.prepare_metadata_for_build_wheel
145
- except AttributeError:
146
- if not _allow_fallback:
147
- raise HookMissing()
148
- else:
149
- return hook(metadata_directory, config_settings)
150
- # fallback to build_wheel outside the try block to avoid exception chaining
151
- # which can be confusing to users and is not relevant
152
- whl_basename = backend.build_wheel(metadata_directory, config_settings)
153
- return _get_wheel_metadata_from_wheel(whl_basename, metadata_directory,
154
- config_settings)
155
-
156
-
157
- def prepare_metadata_for_build_editable(
158
- metadata_directory, config_settings, _allow_fallback):
159
- """Invoke optional prepare_metadata_for_build_editable
160
-
161
- Implements a fallback by building an editable wheel if the hook isn't
162
- defined, unless _allow_fallback is False in which case HookMissing is
163
- raised.
164
- """
165
- backend = _build_backend()
166
- try:
167
- hook = backend.prepare_metadata_for_build_editable
168
- except AttributeError:
169
- if not _allow_fallback:
170
- raise HookMissing()
171
- try:
172
- build_hook = backend.build_editable
173
- except AttributeError:
174
- raise HookMissing(hook_name='build_editable')
175
- else:
176
- whl_basename = build_hook(metadata_directory, config_settings)
177
- return _get_wheel_metadata_from_wheel(whl_basename,
178
- metadata_directory,
179
- config_settings)
180
- else:
181
- return hook(metadata_directory, config_settings)
182
-
183
-
184
- WHEEL_BUILT_MARKER = 'PEP517_ALREADY_BUILT_WHEEL'
185
-
186
-
187
- def _dist_info_files(whl_zip):
188
- """Identify the .dist-info folder inside a wheel ZipFile."""
189
- res = []
190
- for path in whl_zip.namelist():
191
- m = re.match(r'[^/\\]+-[^/\\]+\.dist-info/', path)
192
- if m:
193
- res.append(path)
194
- if res:
195
- return res
196
- raise Exception("No .dist-info folder found in wheel")
197
-
198
-
199
- def _get_wheel_metadata_from_wheel(
200
- whl_basename, metadata_directory, config_settings):
201
- """Extract the metadata from a wheel.
202
-
203
- Fallback for when the build backend does not
204
- define the 'get_wheel_metadata' hook.
205
- """
206
- from zipfile import ZipFile
207
- with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):
208
- pass # Touch marker file
209
-
210
- whl_file = os.path.join(metadata_directory, whl_basename)
211
- with ZipFile(whl_file) as zipf:
212
- dist_info = _dist_info_files(zipf)
213
- zipf.extractall(path=metadata_directory, members=dist_info)
214
- return dist_info[0].split('/')[0]
215
-
216
-
217
- def _find_already_built_wheel(metadata_directory):
218
- """Check for a wheel already built during the get_wheel_metadata hook.
219
- """
220
- if not metadata_directory:
221
- return None
222
- metadata_parent = os.path.dirname(metadata_directory)
223
- if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):
224
- return None
225
-
226
- whl_files = glob(os.path.join(metadata_parent, '*.whl'))
227
- if not whl_files:
228
- print('Found wheel built marker, but no .whl files')
229
- return None
230
- if len(whl_files) > 1:
231
- print('Found multiple .whl files; unspecified behaviour. '
232
- 'Will call build_wheel.')
233
- return None
234
-
235
- # Exactly one .whl file
236
- return whl_files[0]
237
-
238
-
239
- def build_wheel(wheel_directory, config_settings, metadata_directory=None):
240
- """Invoke the mandatory build_wheel hook.
241
-
242
- If a wheel was already built in the
243
- prepare_metadata_for_build_wheel fallback, this
244
- will copy it rather than rebuilding the wheel.
245
- """
246
- prebuilt_whl = _find_already_built_wheel(metadata_directory)
247
- if prebuilt_whl:
248
- shutil.copy2(prebuilt_whl, wheel_directory)
249
- return os.path.basename(prebuilt_whl)
250
-
251
- return _build_backend().build_wheel(wheel_directory, config_settings,
252
- metadata_directory)
253
-
254
-
255
- def build_editable(wheel_directory, config_settings, metadata_directory=None):
256
- """Invoke the optional build_editable hook.
257
-
258
- If a wheel was already built in the
259
- prepare_metadata_for_build_editable fallback, this
260
- will copy it rather than rebuilding the wheel.
261
- """
262
- backend = _build_backend()
263
- try:
264
- hook = backend.build_editable
265
- except AttributeError:
266
- raise HookMissing()
267
- else:
268
- prebuilt_whl = _find_already_built_wheel(metadata_directory)
269
- if prebuilt_whl:
270
- shutil.copy2(prebuilt_whl, wheel_directory)
271
- return os.path.basename(prebuilt_whl)
272
-
273
- return hook(wheel_directory, config_settings, metadata_directory)
274
-
275
-
276
- def get_requires_for_build_sdist(config_settings):
277
- """Invoke the optional get_requires_for_build_wheel hook
278
-
279
- Returns [] if the hook is not defined.
280
- """
281
- backend = _build_backend()
282
- try:
283
- hook = backend.get_requires_for_build_sdist
284
- except AttributeError:
285
- return []
286
- else:
287
- return hook(config_settings)
288
-
289
-
290
- class _DummyException(Exception):
291
- """Nothing should ever raise this exception"""
292
-
293
-
294
- class GotUnsupportedOperation(Exception):
295
- """For internal use when backend raises UnsupportedOperation"""
296
- def __init__(self, traceback):
297
- self.traceback = traceback
298
-
299
-
300
- def build_sdist(sdist_directory, config_settings):
301
- """Invoke the mandatory build_sdist hook."""
302
- backend = _build_backend()
303
- try:
304
- return backend.build_sdist(sdist_directory, config_settings)
305
- except getattr(backend, 'UnsupportedOperation', _DummyException):
306
- raise GotUnsupportedOperation(traceback.format_exc())
307
-
308
-
309
- HOOK_NAMES = {
310
- 'get_requires_for_build_wheel',
311
- 'prepare_metadata_for_build_wheel',
312
- 'build_wheel',
313
- 'get_requires_for_build_editable',
314
- 'prepare_metadata_for_build_editable',
315
- 'build_editable',
316
- 'get_requires_for_build_sdist',
317
- 'build_sdist',
318
- '_supported_features',
319
- }
320
-
321
-
322
- def main():
323
- if len(sys.argv) < 3:
324
- sys.exit("Needs args: hook_name, control_dir")
325
- hook_name = sys.argv[1]
326
- control_dir = sys.argv[2]
327
- if hook_name not in HOOK_NAMES:
328
- sys.exit("Unknown hook: %s" % hook_name)
329
- hook = globals()[hook_name]
330
-
331
- hook_input = read_json(pjoin(control_dir, 'input.json'))
332
-
333
- json_out = {'unsupported': False, 'return_val': None}
334
- try:
335
- json_out['return_val'] = hook(**hook_input['kwargs'])
336
- except BackendUnavailable as e:
337
- json_out['no_backend'] = True
338
- json_out['traceback'] = e.traceback
339
- except BackendInvalid as e:
340
- json_out['backend_invalid'] = True
341
- json_out['backend_error'] = e.message
342
- except GotUnsupportedOperation as e:
343
- json_out['unsupported'] = True
344
- json_out['traceback'] = e.traceback
345
- except HookMissing as e:
346
- json_out['hook_missing'] = True
347
- json_out['missing_hook_name'] = e.hook_name or hook_name
348
-
349
- write_json(json_out, pjoin(control_dir, 'output.json'), indent=2)
350
-
351
-
352
- if __name__ == '__main__':
353
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b6742f1d21425a930997735c01c838096af851948a118f4923bade4c777e9e7/blob DELETED
@@ -1,24 +0,0 @@
1
- #pragma once
2
- // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
-
4
- // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
-
6
- // The only #includes we need are for custom classes that have defaults in the C++ API
7
- #include <c10/core/MemoryFormat.h>
8
- #include <c10/core/Scalar.h>
9
- #include <ATen/core/Reduction.h>
10
-
11
- // Forward declarations of any types needed in the operator signatures.
12
- // We can't directly include these classes because it will cause circular include dependencies.
13
- // This file is included by TensorBody.h, which defines the Tensor class.
14
- #include <ATen/core/ATen_fwd.h>
15
-
16
- namespace at {
17
-
18
- namespace compositeimplicitautograd {
19
-
20
- TORCH_API at::Tensor _upsample_bilinear2d_aa(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, c10::optional<at::ArrayRef<double>> scale_factors);
21
- TORCH_API at::Tensor _upsample_bilinear2d_aa_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, c10::optional<at::ArrayRef<double>> scale_factors);
22
-
23
- } // namespace compositeimplicitautograd
24
- } // namespace at
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b6cdb3f80bbf7a16f415b15566b175028b3f0fae3d8efa94f9e6b6c70363700/blob DELETED
@@ -1,25 +0,0 @@
1
- #pragma once
2
-
3
- #include <Python.h>
4
-
5
- // @generated from ../tools/autograd/templates/python_functions.h
6
-
7
- // Python bindings for automatically generated autograd functions
8
-
9
- namespace torch { namespace autograd { namespace generated {
10
-
11
- void initialize_autogenerated_functions_0(PyObject* module);
12
- void initialize_autogenerated_functions_1(PyObject* module);
13
- void initialize_autogenerated_functions_2(PyObject* module);
14
- void initialize_autogenerated_functions_3(PyObject* module);
15
- void initialize_autogenerated_functions_4(PyObject* module);
16
-
17
- inline void initialize_autogenerated_functions(PyObject* module) {
18
- initialize_autogenerated_functions_0(module);
19
- initialize_autogenerated_functions_1(module);
20
- initialize_autogenerated_functions_2(module);
21
- initialize_autogenerated_functions_3(module);
22
- initialize_autogenerated_functions_4(module);
23
- }
24
-
25
- }}} // namespace torch::autograd::generated
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b6d58df002d41cfa38ba55e6fa93f33983a034672148e1e81c853767c21fa94/blob DELETED
@@ -1,11 +0,0 @@
1
- """For when pip wants to check the date or time.
2
- """
3
-
4
- import datetime
5
-
6
-
7
- def today_is_later_than(year: int, month: int, day: int) -> bool:
8
- today = datetime.date.today()
9
- given = datetime.date(year, month, day)
10
-
11
- return today > given
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b6e400eb85440ec64ab66b4ac111546585740c9ca61fd156400d7153cbad9f4/blob DELETED
@@ -1,335 +0,0 @@
1
- # history.tcl --
2
- #
3
- # Implementation of the history command.
4
- #
5
- # Copyright (c) 1997 Sun Microsystems, Inc.
6
- #
7
- # See the file "license.terms" for information on usage and redistribution of
8
- # this file, and for a DISCLAIMER OF ALL WARRANTIES.
9
- #
10
-
11
- # The tcl::history array holds the history list and some additional
12
- # bookkeeping variables.
13
- #
14
- # nextid the index used for the next history list item.
15
- # keep the max size of the history list
16
- # oldest the index of the oldest item in the history.
17
-
18
- namespace eval ::tcl {
19
- variable history
20
- if {![info exists history]} {
21
- array set history {
22
- nextid 0
23
- keep 20
24
- oldest -20
25
- }
26
- }
27
-
28
- namespace ensemble create -command ::tcl::history -map {
29
- add ::tcl::HistAdd
30
- change ::tcl::HistChange
31
- clear ::tcl::HistClear
32
- event ::tcl::HistEvent
33
- info ::tcl::HistInfo
34
- keep ::tcl::HistKeep
35
- nextid ::tcl::HistNextID
36
- redo ::tcl::HistRedo
37
- }
38
- }
39
-
40
- # history --
41
- #
42
- # This is the main history command. See the man page for its interface.
43
- # This does some argument checking and calls the helper ensemble in the
44
- # tcl namespace.
45
-
46
- proc ::history {args} {
47
- # If no command given, we're doing 'history info'. Can't be done with an
48
- # ensemble unknown handler, as those don't fire when no subcommand is
49
- # given at all.
50
-
51
- if {![llength $args]} {
52
- set args info
53
- }
54
-
55
- # Tricky stuff needed to make stack and errors come out right!
56
- tailcall apply {arglist {tailcall history {*}$arglist} ::tcl} $args
57
- }
58
-
59
- # (unnamed) --
60
- #
61
- # Callback when [::history] is destroyed. Destroys the implementation.
62
- #
63
- # Parameters:
64
- # oldName what the command was called.
65
- # newName what the command is now called (an empty string).
66
- # op the operation (= delete).
67
- #
68
- # Results:
69
- # none
70
- #
71
- # Side Effects:
72
- # The implementation of the [::history] command ceases to exist.
73
-
74
- trace add command ::history delete [list apply {{oldName newName op} {
75
- variable history
76
- unset -nocomplain history
77
- foreach c [info procs ::tcl::Hist*] {
78
- rename $c {}
79
- }
80
- rename ::tcl::history {}
81
- } ::tcl}]
82
-
83
- # tcl::HistAdd --
84
- #
85
- # Add an item to the history, and optionally eval it at the global scope
86
- #
87
- # Parameters:
88
- # event the command to add
89
- # exec (optional) a substring of "exec" causes the command to
90
- # be evaled.
91
- # Results:
92
- # If executing, then the results of the command are returned
93
- #
94
- # Side Effects:
95
- # Adds to the history list
96
-
97
- proc ::tcl::HistAdd {event {exec {}}} {
98
- variable history
99
-
100
- if {
101
- [prefix longest {exec {}} $exec] eq ""
102
- && [llength [info level 0]] == 3
103
- } then {
104
- return -code error "bad argument \"$exec\": should be \"exec\""
105
- }
106
-
107
- # Do not add empty commands to the history
108
- if {[string trim $event] eq ""} {
109
- return ""
110
- }
111
-
112
- # Maintain the history
113
- set history([incr history(nextid)]) $event
114
- unset -nocomplain history([incr history(oldest)])
115
-
116
- # Only execute if 'exec' (or non-empty prefix of it) given
117
- if {$exec eq ""} {
118
- return ""
119
- }
120
- tailcall eval $event
121
- }
122
-
123
- # tcl::HistKeep --
124
- #
125
- # Set or query the limit on the length of the history list
126
- #
127
- # Parameters:
128
- # limit (optional) the length of the history list
129
- #
130
- # Results:
131
- # If no limit is specified, the current limit is returned
132
- #
133
- # Side Effects:
134
- # Updates history(keep) if a limit is specified
135
-
136
- proc ::tcl::HistKeep {{count {}}} {
137
- variable history
138
- if {[llength [info level 0]] == 1} {
139
- return $history(keep)
140
- }
141
- if {![string is integer -strict $count] || ($count < 0)} {
142
- return -code error "illegal keep count \"$count\""
143
- }
144
- set oldold $history(oldest)
145
- set history(oldest) [expr {$history(nextid) - $count}]
146
- for {} {$oldold <= $history(oldest)} {incr oldold} {
147
- unset -nocomplain history($oldold)
148
- }
149
- set history(keep) $count
150
- }
151
-
152
- # tcl::HistClear --
153
- #
154
- # Erase the history list
155
- #
156
- # Parameters:
157
- # none
158
- #
159
- # Results:
160
- # none
161
- #
162
- # Side Effects:
163
- # Resets the history array, except for the keep limit
164
-
165
- proc ::tcl::HistClear {} {
166
- variable history
167
- set keep $history(keep)
168
- unset history
169
- array set history [list \
170
- nextid 0 \
171
- keep $keep \
172
- oldest -$keep \
173
- ]
174
- }
175
-
176
- # tcl::HistInfo --
177
- #
178
- # Return a pretty-printed version of the history list
179
- #
180
- # Parameters:
181
- # num (optional) the length of the history list to return
182
- #
183
- # Results:
184
- # A formatted history list
185
-
186
- proc ::tcl::HistInfo {{count {}}} {
187
- variable history
188
- if {[llength [info level 0]] == 1} {
189
- set count [expr {$history(keep) + 1}]
190
- } elseif {![string is integer -strict $count]} {
191
- return -code error "bad integer \"$count\""
192
- }
193
- set result {}
194
- set newline ""
195
- for {set i [expr {$history(nextid) - $count + 1}]} \
196
- {$i <= $history(nextid)} {incr i} {
197
- if {![info exists history($i)]} {
198
- continue
199
- }
200
- set cmd [string map [list \n \n\t] [string trimright $history($i) \ \n]]
201
- append result $newline[format "%6d %s" $i $cmd]
202
- set newline \n
203
- }
204
- return $result
205
- }
206
-
207
- # tcl::HistRedo --
208
- #
209
- # Fetch the previous or specified event, execute it, and then replace
210
- # the current history item with that event.
211
- #
212
- # Parameters:
213
- # event (optional) index of history item to redo. Defaults to -1,
214
- # which means the previous event.
215
- #
216
- # Results:
217
- # Those of the command being redone.
218
- #
219
- # Side Effects:
220
- # Replaces the current history list item with the one being redone.
221
-
222
- proc ::tcl::HistRedo {{event -1}} {
223
- variable history
224
-
225
- set i [HistIndex $event]
226
- if {$i == $history(nextid)} {
227
- return -code error "cannot redo the current event"
228
- }
229
- set cmd $history($i)
230
- HistChange $cmd 0
231
- tailcall eval $cmd
232
- }
233
-
234
- # tcl::HistIndex --
235
- #
236
- # Map from an event specifier to an index in the history list.
237
- #
238
- # Parameters:
239
- # event index of history item to redo.
240
- # If this is a positive number, it is used directly.
241
- # If it is a negative number, then it counts back to a previous
242
- # event, where -1 is the most recent event.
243
- # A string can be matched, either by being the prefix of a
244
- # command or by matching a command with string match.
245
- #
246
- # Results:
247
- # The index into history, or an error if the index didn't match.
248
-
249
- proc ::tcl::HistIndex {event} {
250
- variable history
251
- if {![string is integer -strict $event]} {
252
- for {set i [expr {$history(nextid)-1}]} {[info exists history($i)]} \
253
- {incr i -1} {
254
- if {[string match $event* $history($i)]} {
255
- return $i
256
- }
257
- if {[string match $event $history($i)]} {
258
- return $i
259
- }
260
- }
261
- return -code error "no event matches \"$event\""
262
- } elseif {$event <= 0} {
263
- set i [expr {$history(nextid) + $event}]
264
- } else {
265
- set i $event
266
- }
267
- if {$i <= $history(oldest)} {
268
- return -code error "event \"$event\" is too far in the past"
269
- }
270
- if {$i > $history(nextid)} {
271
- return -code error "event \"$event\" hasn't occured yet"
272
- }
273
- return $i
274
- }
275
-
276
- # tcl::HistEvent --
277
- #
278
- # Map from an event specifier to the value in the history list.
279
- #
280
- # Parameters:
281
- # event index of history item to redo. See index for a description of
282
- # possible event patterns.
283
- #
284
- # Results:
285
- # The value from the history list.
286
-
287
- proc ::tcl::HistEvent {{event -1}} {
288
- variable history
289
- set i [HistIndex $event]
290
- if {![info exists history($i)]} {
291
- return ""
292
- }
293
- return [string trimright $history($i) \ \n]
294
- }
295
-
296
- # tcl::HistChange --
297
- #
298
- # Replace a value in the history list.
299
- #
300
- # Parameters:
301
- # newValue The new value to put into the history list.
302
- # event (optional) index of history item to redo. See index for a
303
- # description of possible event patterns. This defaults to 0,
304
- # which specifies the current event.
305
- #
306
- # Side Effects:
307
- # Changes the history list.
308
-
309
- proc ::tcl::HistChange {newValue {event 0}} {
310
- variable history
311
- set i [HistIndex $event]
312
- set history($i) $newValue
313
- }
314
-
315
- # tcl::HistNextID --
316
- #
317
- # Returns the number of the next history event.
318
- #
319
- # Parameters:
320
- # None.
321
- #
322
- # Side Effects:
323
- # None.
324
-
325
- proc ::tcl::HistNextID {} {
326
- variable history
327
- return [expr {$history(nextid) + 1}]
328
- }
329
-
330
- return
331
-
332
- # Local Variables:
333
- # mode: tcl
334
- # fill-column: 78
335
- # End:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b6fd8df3c9d5193733e9bbcf27f303cd5aa6b17da01330a128ff30205ccab26/blob DELETED
@@ -1,166 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import dataclasses
4
- import inspect
5
- from types import FunctionType
6
- from typing import Any
7
- from typing import final
8
- from typing import Generic
9
- from typing import TypeVar
10
- import warnings
11
-
12
-
13
- class PytestWarning(UserWarning):
14
- """Base class for all warnings emitted by pytest."""
15
-
16
- __module__ = "pytest"
17
-
18
-
19
- @final
20
- class PytestAssertRewriteWarning(PytestWarning):
21
- """Warning emitted by the pytest assert rewrite module."""
22
-
23
- __module__ = "pytest"
24
-
25
-
26
- @final
27
- class PytestCacheWarning(PytestWarning):
28
- """Warning emitted by the cache plugin in various situations."""
29
-
30
- __module__ = "pytest"
31
-
32
-
33
- @final
34
- class PytestConfigWarning(PytestWarning):
35
- """Warning emitted for configuration issues."""
36
-
37
- __module__ = "pytest"
38
-
39
-
40
- @final
41
- class PytestCollectionWarning(PytestWarning):
42
- """Warning emitted when pytest is not able to collect a file or symbol in a module."""
43
-
44
- __module__ = "pytest"
45
-
46
-
47
- class PytestDeprecationWarning(PytestWarning, DeprecationWarning):
48
- """Warning class for features that will be removed in a future version."""
49
-
50
- __module__ = "pytest"
51
-
52
-
53
- class PytestRemovedIn9Warning(PytestDeprecationWarning):
54
- """Warning class for features that will be removed in pytest 9."""
55
-
56
- __module__ = "pytest"
57
-
58
-
59
- class PytestReturnNotNoneWarning(PytestWarning):
60
- """Warning emitted when a test function is returning value other than None."""
61
-
62
- __module__ = "pytest"
63
-
64
-
65
- @final
66
- class PytestExperimentalApiWarning(PytestWarning, FutureWarning):
67
- """Warning category used to denote experiments in pytest.
68
-
69
- Use sparingly as the API might change or even be removed completely in a
70
- future version.
71
- """
72
-
73
- __module__ = "pytest"
74
-
75
- @classmethod
76
- def simple(cls, apiname: str) -> PytestExperimentalApiWarning:
77
- return cls(f"{apiname} is an experimental api that may change over time")
78
-
79
-
80
- @final
81
- class PytestUnhandledCoroutineWarning(PytestReturnNotNoneWarning):
82
- """Warning emitted for an unhandled coroutine.
83
-
84
- A coroutine was encountered when collecting test functions, but was not
85
- handled by any async-aware plugin.
86
- Coroutine test functions are not natively supported.
87
- """
88
-
89
- __module__ = "pytest"
90
-
91
-
92
- @final
93
- class PytestUnknownMarkWarning(PytestWarning):
94
- """Warning emitted on use of unknown markers.
95
-
96
- See :ref:`mark` for details.
97
- """
98
-
99
- __module__ = "pytest"
100
-
101
-
102
- @final
103
- class PytestUnraisableExceptionWarning(PytestWarning):
104
- """An unraisable exception was reported.
105
-
106
- Unraisable exceptions are exceptions raised in :meth:`__del__ <object.__del__>`
107
- implementations and similar situations when the exception cannot be raised
108
- as normal.
109
- """
110
-
111
- __module__ = "pytest"
112
-
113
-
114
- @final
115
- class PytestUnhandledThreadExceptionWarning(PytestWarning):
116
- """An unhandled exception occurred in a :class:`~threading.Thread`.
117
-
118
- Such exceptions don't propagate normally.
119
- """
120
-
121
- __module__ = "pytest"
122
-
123
-
124
- _W = TypeVar("_W", bound=PytestWarning)
125
-
126
-
127
- @final
128
- @dataclasses.dataclass
129
- class UnformattedWarning(Generic[_W]):
130
- """A warning meant to be formatted during runtime.
131
-
132
- This is used to hold warnings that need to format their message at runtime,
133
- as opposed to a direct message.
134
- """
135
-
136
- category: type[_W]
137
- template: str
138
-
139
- def format(self, **kwargs: Any) -> _W:
140
- """Return an instance of the warning category, formatted with given kwargs."""
141
- return self.category(self.template.format(**kwargs))
142
-
143
-
144
- def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None:
145
- """
146
- Issue the warning :param:`message` for the definition of the given :param:`method`
147
-
148
- this helps to log warnings for functions defined prior to finding an issue with them
149
- (like hook wrappers being marked in a legacy mechanism)
150
- """
151
- lineno = method.__code__.co_firstlineno
152
- filename = inspect.getfile(method)
153
- module = method.__module__
154
- mod_globals = method.__globals__
155
- try:
156
- warnings.warn_explicit(
157
- message,
158
- type(message),
159
- filename=filename,
160
- module=module,
161
- registry=mod_globals.setdefault("__warningregistry__", {}),
162
- lineno=lineno,
163
- )
164
- except Warning as w:
165
- # If warnings are errors (e.g. -Werror), location information gets lost, so we add it to the message.
166
- raise type(w)(f"{w}\n at {filename}:{lineno}") from None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b717166deba6db15d053b26793d1c34c4a756495065bafecb0657dd9461794f/blob DELETED
@@ -1,57 +0,0 @@
1
- from .module import Module
2
- from .. import functional as F
3
-
4
- from torch import Tensor
5
-
6
- __all__ = ['ChannelShuffle']
7
-
8
- class ChannelShuffle(Module):
9
- r"""Divides and rearranges the channels in a tensor.
10
-
11
- This operation divides the channels in a tensor of shape :math:`(*, C , H, W)`
12
- into g groups and rearranges them as :math:`(*, \frac{C}{g}, g, H, W)`,
13
- while keeping the original tensor shape.
14
-
15
- Args:
16
- groups (int): number of groups to divide channels in.
17
-
18
- Examples::
19
-
20
- >>> # xdoctest: +IGNORE_WANT("FIXME: incorrect want")
21
- >>> channel_shuffle = nn.ChannelShuffle(2)
22
- >>> input = torch.randn(1, 4, 2, 2)
23
- >>> print(input)
24
- [[[[1, 2],
25
- [3, 4]],
26
- [[5, 6],
27
- [7, 8]],
28
- [[9, 10],
29
- [11, 12]],
30
- [[13, 14],
31
- [15, 16]],
32
- ]]
33
- >>> output = channel_shuffle(input)
34
- >>> print(output)
35
- [[[[1, 2],
36
- [3, 4]],
37
- [[9, 10],
38
- [11, 12]],
39
- [[5, 6],
40
- [7, 8]],
41
- [[13, 14],
42
- [15, 16]],
43
- ]]
44
- """
45
-
46
- __constants__ = ['groups']
47
- groups: int
48
-
49
- def __init__(self, groups: int) -> None:
50
- super().__init__()
51
- self.groups = groups
52
-
53
- def forward(self, input: Tensor) -> Tensor:
54
- return F.channel_shuffle(input, self.groups)
55
-
56
- def extra_repr(self) -> str:
57
- return f'groups={self.groups}'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b7207dba4c2ccb0e94bc72dbf324a2c0f31e35e2eaf98e55f7b1d4f8b01e26f/blob DELETED
@@ -1,50 +0,0 @@
1
- from collections.abc import Generator
2
- from contextlib import contextmanager
3
- import pathlib
4
- import tempfile
5
-
6
- import pytest
7
-
8
- from pandas.io.pytables import HDFStore
9
-
10
- tables = pytest.importorskip("tables")
11
- # set these parameters so we don't have file sharing
12
- tables.parameters.MAX_NUMEXPR_THREADS = 1
13
- tables.parameters.MAX_BLOSC_THREADS = 1
14
- tables.parameters.MAX_THREADS = 1
15
-
16
-
17
- def safe_close(store):
18
- try:
19
- if store is not None:
20
- store.close()
21
- except OSError:
22
- pass
23
-
24
-
25
- # contextmanager to ensure the file cleanup
26
- @contextmanager
27
- def ensure_clean_store(
28
- path, mode="a", complevel=None, complib=None, fletcher32=False
29
- ) -> Generator[HDFStore, None, None]:
30
- with tempfile.TemporaryDirectory() as tmpdirname:
31
- tmp_path = pathlib.Path(tmpdirname, path)
32
- with HDFStore(
33
- tmp_path,
34
- mode=mode,
35
- complevel=complevel,
36
- complib=complib,
37
- fletcher32=fletcher32,
38
- ) as store:
39
- yield store
40
-
41
-
42
- def _maybe_remove(store, key):
43
- """
44
- For tests using tables, try removing the table to be sure there is
45
- no content from previous tests using the same table name.
46
- """
47
- try:
48
- store.remove(key)
49
- except (ValueError, KeyError):
50
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b72799855182eb383e06337a6fb5c8a9e01872fcdf9c1e1adcb01a3915657a7/blob DELETED
@@ -1,27 +0,0 @@
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_upsample_trilinear3d : public at::impl::MetaBase {
21
-
22
-
23
- void meta(const at::Tensor & self, at::ArrayRef<int64_t> output_size, bool align_corners, c10::optional<double> scales_d, c10::optional<double> scales_h, c10::optional<double> scales_w);
24
- };
25
-
26
- } // namespace native
27
- } // namespace at
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b73f686d2ddb70d184f449d22d666b0a1ea63797ad578875be8245c4efa817e/blob DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:9b73f686d2ddb70d184f449d22d666b0a1ea63797ad578875be8245c4efa817e
3
- size 831312
 
 
 
 
shared/package-files/9b/9b754b17f8c1e4f6d11f3ae7c0f25b6bfcfb78c73ce79016075e681189215e73/blob DELETED
@@ -1,28 +0,0 @@
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 avg_pool1d {
18
- using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool, bool);
19
- using ptr_schema = schema*;
20
- // See Note [static constexpr char* members for windows NVCC]
21
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::avg_pool1d")
22
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
- STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "avg_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, bool ceil_mode=False, bool count_include_pad=True) -> Tensor")
24
- static at::Tensor call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad);
25
- static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad);
26
- };
27
-
28
- }} // namespace at::_ops
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b75f170af5486c48214aefebeb394eb3b67f9e69e5ca2ee4bc74ff3c418eb3c/blob DELETED
@@ -1,480 +0,0 @@
1
- from functools import lru_cache
2
- from typing import Optional, List
3
-
4
- from charset_normalizer.constant import UNICODE_SECONDARY_RANGE_KEYWORD
5
- from charset_normalizer.utils import is_punctuation, is_symbol, unicode_range, is_accentuated, is_latin, \
6
- remove_accent, is_separator, is_cjk, is_case_variable, is_hangul, is_katakana, is_hiragana, is_ascii, is_thai
7
-
8
-
9
- class MessDetectorPlugin:
10
- """
11
- Base abstract class used for mess detection plugins.
12
- All detectors MUST extend and implement given methods.
13
- """
14
-
15
- def eligible(self, character: str) -> bool:
16
- """
17
- Determine if given character should be fed in.
18
- """
19
- raise NotImplementedError # pragma: nocover
20
-
21
- def feed(self, character: str) -> None:
22
- """
23
- The main routine to be executed upon character.
24
- Insert the logic in witch the text would be considered chaotic.
25
- """
26
- raise NotImplementedError # pragma: nocover
27
-
28
- def reset(self) -> None:
29
- """
30
- Permit to reset the plugin to the initial state.
31
- """
32
- raise NotImplementedError # pragma: nocover
33
-
34
- @property
35
- def ratio(self) -> float:
36
- """
37
- Compute the chaos ratio based on what your feed() has seen.
38
- Must NOT be lower than 0.; No restriction gt 0.
39
- """
40
- raise NotImplementedError # pragma: nocover
41
-
42
-
43
- class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin):
44
-
45
- def __init__(self):
46
- self._punctuation_count = 0 # type: int
47
- self._symbol_count = 0 # type: int
48
- self._character_count = 0 # type: int
49
-
50
- self._last_printable_char = None # type: Optional[str]
51
- self._frenzy_symbol_in_word = False # type: bool
52
-
53
- def eligible(self, character: str) -> bool:
54
- return character.isprintable()
55
-
56
- def feed(self, character: str) -> None:
57
- self._character_count += 1
58
-
59
- if character != self._last_printable_char and character not in ["<", ">", "=", ":", "/", "&", ";", "{", "}", "[", "]", ",", "|", '"']:
60
- if is_punctuation(character):
61
- self._punctuation_count += 1
62
- elif character.isdigit() is False and is_symbol(character):
63
- self._symbol_count += 2
64
-
65
- self._last_printable_char = character
66
-
67
- def reset(self) -> None:
68
- self._punctuation_count = 0
69
- self._character_count = 0
70
- self._symbol_count = 0
71
-
72
- @property
73
- def ratio(self) -> float:
74
- if self._character_count == 0:
75
- return 0.
76
-
77
- ratio_of_punctuation = (self._punctuation_count + self._symbol_count) / self._character_count # type: float
78
-
79
- return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.
80
-
81
-
82
- class TooManyAccentuatedPlugin(MessDetectorPlugin):
83
-
84
- def __init__(self):
85
- self._character_count = 0 # type: int
86
- self._accentuated_count = 0 # type: int
87
-
88
- def eligible(self, character: str) -> bool:
89
- return character.isalpha()
90
-
91
- def feed(self, character: str) -> None:
92
- self._character_count += 1
93
-
94
- if is_accentuated(character):
95
- self._accentuated_count += 1
96
-
97
- def reset(self) -> None:
98
- self._character_count = 0
99
- self._accentuated_count = 0
100
-
101
- @property
102
- def ratio(self) -> float:
103
- if self._character_count == 0:
104
- return 0.
105
- ratio_of_accentuation = self._accentuated_count / self._character_count # type: float
106
- return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.
107
-
108
-
109
- class UnprintablePlugin(MessDetectorPlugin):
110
-
111
- def __init__(self):
112
- self._unprintable_count = 0 # type: int
113
- self._character_count = 0 # type: int
114
-
115
- def eligible(self, character: str) -> bool:
116
- return True
117
-
118
- def feed(self, character: str) -> None:
119
- if character not in {'\n', '\t', '\r', '\v'} and character.isprintable() is False:
120
- self._unprintable_count += 1
121
- self._character_count += 1
122
-
123
- def reset(self) -> None:
124
- self._unprintable_count = 0
125
-
126
- @property
127
- def ratio(self) -> float:
128
- if self._character_count == 0:
129
- return 0.
130
-
131
- return (self._unprintable_count * 8) / self._character_count
132
-
133
-
134
- class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
135
-
136
- def __init__(self):
137
- self._successive_count = 0 # type: int
138
- self._character_count = 0 # type: int
139
-
140
- self._last_latin_character = None # type: Optional[str]
141
-
142
- def eligible(self, character: str) -> bool:
143
- return character.isalpha() and is_latin(character)
144
-
145
- def feed(self, character: str) -> None:
146
- self._character_count += 1
147
- if self._last_latin_character is not None:
148
- if is_accentuated(character) and is_accentuated(self._last_latin_character):
149
- if character.isupper() and self._last_latin_character.isupper():
150
- self._successive_count += 1
151
- # Worse if its the same char duplicated with different accent.
152
- if remove_accent(character) == remove_accent(self._last_latin_character):
153
- self._successive_count += 1
154
- self._last_latin_character = character
155
-
156
- def reset(self) -> None:
157
- self._successive_count = 0
158
- self._character_count = 0
159
- self._last_latin_character = None
160
-
161
- @property
162
- def ratio(self) -> float:
163
- if self._character_count == 0:
164
- return 0.
165
-
166
- return (self._successive_count * 2) / self._character_count
167
-
168
-
169
- class SuspiciousRange(MessDetectorPlugin):
170
-
171
- def __init__(self):
172
- self._suspicious_successive_range_count = 0 # type: int
173
- self._character_count = 0 # type: int
174
- self._last_printable_seen = None # type: Optional[str]
175
-
176
- def eligible(self, character: str) -> bool:
177
- return character.isprintable()
178
-
179
- def feed(self, character: str) -> None:
180
- self._character_count += 1
181
-
182
- if character.isspace() or is_punctuation(character):
183
- self._last_printable_seen = None
184
- return
185
-
186
- if self._last_printable_seen is None:
187
- self._last_printable_seen = character
188
- return
189
-
190
- unicode_range_a = unicode_range(self._last_printable_seen) # type: Optional[str]
191
- unicode_range_b = unicode_range(character) # type: Optional[str]
192
-
193
- if is_suspiciously_successive_range(unicode_range_a, unicode_range_b):
194
- self._suspicious_successive_range_count += 1
195
-
196
- self._last_printable_seen = character
197
-
198
- def reset(self) -> None:
199
- self._character_count = 0
200
- self._suspicious_successive_range_count = 0
201
- self._last_printable_seen = None
202
-
203
- @property
204
- def ratio(self) -> float:
205
- if self._character_count == 0:
206
- return 0.
207
-
208
- ratio_of_suspicious_range_usage = (self._suspicious_successive_range_count * 2) / self._character_count # type: float
209
-
210
- if ratio_of_suspicious_range_usage < 0.1:
211
- return 0.
212
-
213
- return ratio_of_suspicious_range_usage
214
-
215
-
216
- class SuperWeirdWordPlugin(MessDetectorPlugin):
217
-
218
- def __init__(self):
219
- self._word_count = 0 # type: int
220
- self._bad_word_count = 0 # type: int
221
- self._is_current_word_bad = False # type: bool
222
- self._foreign_long_watch = False # type: bool
223
-
224
- self._character_count = 0 # type: int
225
- self._bad_character_count = 0 # type: int
226
-
227
- self._buffer = "" # type: str
228
- self._buffer_accent_count = 0 # type: int
229
-
230
- def eligible(self, character: str) -> bool:
231
- return True
232
-
233
- def feed(self, character: str) -> None:
234
- if character.isalpha():
235
- self._buffer = "".join([self._buffer, character])
236
- if is_accentuated(character):
237
- self._buffer_accent_count += 1
238
- if self._foreign_long_watch is False and is_latin(character) is False and is_cjk(character) is False and is_hangul(character) is False and is_katakana(character) is False and is_hiragana(character) is False and is_thai(character) is False:
239
- self._foreign_long_watch = True
240
- return
241
- if not self._buffer:
242
- return
243
- if (character.isspace() or is_punctuation(character) or is_separator(character)) and self._buffer:
244
- self._word_count += 1
245
- buffer_length = len(self._buffer) # type: int
246
-
247
- self._character_count += buffer_length
248
-
249
- if buffer_length >= 4 and self._buffer_accent_count / buffer_length >= 0.3:
250
- self._is_current_word_bad = True
251
- if buffer_length >= 24 and self._foreign_long_watch:
252
- self._is_current_word_bad = True
253
-
254
- if self._is_current_word_bad:
255
- self._bad_word_count += 1
256
- self._bad_character_count += len(self._buffer)
257
- self._is_current_word_bad = False
258
-
259
- self._foreign_long_watch = False
260
- self._buffer = ""
261
- self._buffer_accent_count = 0
262
- elif character not in {"<", ">", "-", "="} and character.isdigit() is False and is_symbol(character):
263
- self._is_current_word_bad = True
264
- self._buffer += character
265
-
266
- def reset(self) -> None:
267
- self._buffer = ""
268
- self._is_current_word_bad = False
269
- self._foreign_long_watch = False
270
- self._bad_word_count = 0
271
- self._word_count = 0
272
- self._character_count = 0
273
- self._bad_character_count = 0
274
-
275
- @property
276
- def ratio(self) -> float:
277
- if self._word_count <= 10:
278
- return 0.
279
-
280
- return self._bad_character_count / self._character_count
281
-
282
-
283
- class CjkInvalidStopPlugin(MessDetectorPlugin):
284
- """
285
- GB(Chinese) based encoding often render the stop incorrectly when the content does not fit and can be easily detected.
286
- Searching for the overuse of '丅' and '丄'.
287
- """
288
-
289
- def __init__(self):
290
- self._wrong_stop_count = 0 # type: int
291
- self._cjk_character_count = 0 # type: int
292
-
293
- def eligible(self, character: str) -> bool:
294
- return True
295
-
296
- def feed(self, character: str) -> None:
297
- if character in ["丅", "丄"]:
298
- self._wrong_stop_count += 1
299
- return
300
- if is_cjk(character):
301
- self._cjk_character_count += 1
302
-
303
- def reset(self) -> None:
304
- self._wrong_stop_count = 0
305
- self._cjk_character_count = 0
306
-
307
- @property
308
- def ratio(self) -> float:
309
- if self._cjk_character_count < 16:
310
- return 0.
311
- return self._wrong_stop_count / self._cjk_character_count
312
-
313
-
314
- class ArchaicUpperLowerPlugin(MessDetectorPlugin):
315
-
316
- def __init__(self):
317
- self._buf = False # type: bool
318
-
319
- self._character_count_since_last_sep = 0 # type: int
320
-
321
- self._successive_upper_lower_count = 0 # type: int
322
- self._successive_upper_lower_count_final = 0 # type: int
323
-
324
- self._character_count = 0 # type: int
325
-
326
- self._last_alpha_seen = None # type: Optional[str]
327
- self._current_ascii_only = True # type: bool
328
-
329
- def eligible(self, character: str) -> bool:
330
- return True
331
-
332
- def feed(self, character: str) -> None:
333
- is_concerned = character.isalpha() and is_case_variable(character)
334
- chunk_sep = is_concerned is False
335
-
336
- if chunk_sep and self._character_count_since_last_sep > 0:
337
- if self._character_count_since_last_sep <= 64 and character.isdigit() is False and self._current_ascii_only is False:
338
- self._successive_upper_lower_count_final += self._successive_upper_lower_count
339
-
340
- self._successive_upper_lower_count = 0
341
- self._character_count_since_last_sep = 0
342
- self._last_alpha_seen = None
343
- self._buf = False
344
- self._character_count += 1
345
- self._current_ascii_only = True
346
-
347
- return
348
-
349
- if self._current_ascii_only is True and is_ascii(character) is False:
350
- self._current_ascii_only = False
351
-
352
- if self._last_alpha_seen is not None:
353
- if (character.isupper() and self._last_alpha_seen.islower()) or (character.islower() and self._last_alpha_seen.isupper()):
354
- if self._buf is True:
355
- self._successive_upper_lower_count += 2
356
- self._buf = False
357
- else:
358
- self._buf = True
359
- else:
360
- self._buf = False
361
-
362
- self._character_count += 1
363
- self._character_count_since_last_sep += 1
364
- self._last_alpha_seen = character
365
-
366
- def reset(self) -> None:
367
- self._character_count = 0
368
- self._character_count_since_last_sep = 0
369
- self._successive_upper_lower_count = 0
370
- self._successive_upper_lower_count_final = 0
371
- self._last_alpha_seen = None
372
- self._buf = False
373
- self._current_ascii_only = True
374
-
375
- @property
376
- def ratio(self) -> float:
377
- if self._character_count == 0:
378
- return 0.
379
-
380
- return self._successive_upper_lower_count_final / self._character_count
381
-
382
-
383
- def is_suspiciously_successive_range(unicode_range_a: Optional[str], unicode_range_b: Optional[str]) -> bool:
384
- """
385
- Determine if two Unicode range seen next to each other can be considered as suspicious.
386
- """
387
- if unicode_range_a is None or unicode_range_b is None:
388
- return True
389
-
390
- if unicode_range_a == unicode_range_b:
391
- return False
392
-
393
- if "Latin" in unicode_range_a and "Latin" in unicode_range_b:
394
- return False
395
-
396
- if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b:
397
- return False
398
-
399
- keywords_range_a, keywords_range_b = unicode_range_a.split(" "), unicode_range_b.split(" ")
400
-
401
- for el in keywords_range_a:
402
- if el in UNICODE_SECONDARY_RANGE_KEYWORD:
403
- continue
404
- if el in keywords_range_b:
405
- return False
406
-
407
- # Japanese Exception
408
- if unicode_range_a in ['Katakana', 'Hiragana'] and unicode_range_b in ['Katakana', 'Hiragana']:
409
- return False
410
-
411
- if unicode_range_a in ['Katakana', 'Hiragana'] or unicode_range_b in ['Katakana', 'Hiragana']:
412
- if "CJK" in unicode_range_a or "CJK" in unicode_range_b:
413
- return False
414
-
415
- if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b:
416
- if "CJK" in unicode_range_a or "CJK" in unicode_range_b:
417
- return False
418
- if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin":
419
- return False
420
-
421
- # Chinese/Japanese use dedicated range for punctuation and/or separators.
422
- if ('CJK' in unicode_range_a or 'CJK' in unicode_range_b) or (unicode_range_a in ['Katakana', 'Hiragana'] and unicode_range_b in ['Katakana', 'Hiragana']):
423
- if 'Punctuation' in unicode_range_a or 'Punctuation' in unicode_range_b:
424
- return False
425
- if 'Forms' in unicode_range_a or 'Forms' in unicode_range_b:
426
- return False
427
-
428
- return True
429
-
430
-
431
- @lru_cache(maxsize=2048)
432
- def mess_ratio(decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False) -> float:
433
- """
434
- Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier.
435
- """
436
- detectors = [] # type: List[MessDetectorPlugin]
437
-
438
- for md_class in MessDetectorPlugin.__subclasses__():
439
- detectors.append(
440
- md_class()
441
- )
442
-
443
- length = len(decoded_sequence) # type: int
444
-
445
- mean_mess_ratio = 0. # type: float
446
-
447
- if length < 512:
448
- intermediary_mean_mess_ratio_calc = 32 # type: int
449
- elif length <= 1024:
450
- intermediary_mean_mess_ratio_calc = 64
451
- else:
452
- intermediary_mean_mess_ratio_calc = 128
453
-
454
- for character, index in zip(decoded_sequence, range(0, length)):
455
- for detector in detectors:
456
- if detector.eligible(character):
457
- detector.feed(character)
458
-
459
- if (index > 0 and index % intermediary_mean_mess_ratio_calc == 0) or index == length-1:
460
- mean_mess_ratio = sum(
461
- [
462
- dt.ratio for dt in detectors
463
- ]
464
- )
465
-
466
- if mean_mess_ratio >= maximum_threshold:
467
- break
468
-
469
- if debug:
470
- for dt in detectors: # pragma: nocover
471
- print(
472
- dt.__class__,
473
- dt.ratio
474
- )
475
-
476
- return round(
477
- mean_mess_ratio,
478
- 3
479
- )
480
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b79065dfee170914ab9ff6306eddbabe921f4c432484396c6011b04497447c4/blob DELETED
@@ -1,1202 +0,0 @@
1
- import collections
2
- import dataclasses
3
- import enum
4
- import itertools as it
5
- import logging
6
- from typing import (
7
- Any,
8
- cast,
9
- DefaultDict,
10
- Dict,
11
- Iterator,
12
- List,
13
- Optional,
14
- Set,
15
- Tuple,
16
- Union,
17
- )
18
-
19
- from typing_extensions import Literal
20
-
21
- import torch
22
- from torch._C import FunctionSchema
23
- from torch._C._autograd import _ProfilerResult
24
- from torch._C._profiler import (
25
- _EventType,
26
- _ExtraFields_Allocation,
27
- _ExtraFields_TorchOp,
28
- _ProfilerEvent,
29
- _TensorMetadata,
30
- RecordScope,
31
- )
32
- from torch._utils import _element_size
33
- from torch.profiler import _utils
34
-
35
- KeyAndID = Tuple["Key", int]
36
- TensorAndID = Tuple["TensorKey", int]
37
-
38
- log = logging.getLogger(__name__)
39
-
40
-
41
- class Category(enum.Enum):
42
- INPUT = enum.auto()
43
- TEMPORARY = enum.auto()
44
- ACTIVATION = enum.auto()
45
- GRADIENT = enum.auto()
46
- AUTOGRAD_DETAIL = enum.auto()
47
- PARAMETER = enum.auto()
48
- OPTIMIZER_STATE = enum.auto()
49
-
50
-
51
- _CATEGORY_TO_COLORS = {
52
- Category.PARAMETER: "darkgreen",
53
- Category.OPTIMIZER_STATE: "goldenrod",
54
- Category.INPUT: "black",
55
- Category.TEMPORARY: "mediumpurple",
56
- Category.ACTIVATION: "red",
57
- Category.GRADIENT: "mediumblue",
58
- Category.AUTOGRAD_DETAIL: "royalblue",
59
- None: "grey",
60
- }
61
-
62
- _CATEGORY_TO_INDEX = {c: i for i, c in enumerate(_CATEGORY_TO_COLORS)}
63
-
64
-
65
- class Action(enum.Enum):
66
- PREEXISTING = enum.auto()
67
- CREATE = enum.auto()
68
- INCREMENT_VERSION = enum.auto()
69
- DESTROY = enum.auto()
70
-
71
-
72
- _ACTION_TO_INDEX = {i: i.value for i in Action}
73
-
74
-
75
- @dataclasses.dataclass(eq=True, unsafe_hash=False, frozen=True)
76
- class Key:
77
- device: torch.device
78
-
79
-
80
- @dataclasses.dataclass
81
- class _Storage:
82
- """Bundle storage pointer and id.
83
-
84
- All profiling logic should use `allocation_id`, however it is useful to
85
- print storage pointers for debugging and unit tests sometimes look up
86
- values using the storage data pointer of a live Tensor."""
87
-
88
- ptr: int
89
- allocation_id: int
90
-
91
- def __repr__(self) -> str:
92
- return f"{hex(self.ptr):>18} ({self.allocation_id})"
93
-
94
- def __eq__(self, other: object) -> bool:
95
- return isinstance(other, _Storage) and self.allocation_id == other.allocation_id
96
-
97
- def __hash__(self) -> int:
98
- return hash(self.allocation_id)
99
-
100
-
101
- @dataclasses.dataclass(eq=True, unsafe_hash=True, frozen=True)
102
- class TensorKey(Key):
103
- """Hashable identifier for a storage which has been asigned an ID.
104
-
105
- A detailed description of Tensor IDs and why they are needed is given in
106
- `torch/csrc/profiler/collection.h` when `TensorID` is declared. To
107
- summarize, multiple Storage buffers can map to the same logical Tensor.
108
- This dataclass is used to refer to a concrete in-memory StorageImpl of
109
- a Tensor.
110
- """
111
-
112
- id: int
113
- storage: _Storage
114
-
115
- def __repr__(self) -> str:
116
- return f"id={self.id}: {repr(self.storage):<24} ({self.device})"
117
-
118
- def __lt__(self, other: "TensorKey") -> bool:
119
- return self._as_sortable < other._as_sortable
120
-
121
- @staticmethod
122
- def _make(
123
- tensor_id: Optional[int],
124
- storage_ptr: Optional[int],
125
- allocation_id: Optional[int],
126
- device: torch.device,
127
- ) -> Optional["TensorKey"]:
128
- if (
129
- tensor_id is not None
130
- and storage_ptr is not None
131
- and allocation_id is not None
132
- ):
133
- return TensorKey(device, tensor_id, _Storage(storage_ptr, allocation_id))
134
- return None
135
-
136
- @classmethod
137
- def from_allocation(cls, alloc: _ExtraFields_Allocation) -> Optional["TensorKey"]:
138
- return cls._make(alloc.id, alloc.ptr, alloc.allocation_id, alloc.device)
139
-
140
- @classmethod
141
- def from_tensor(cls, t: Optional[_TensorMetadata]) -> Optional["TensorKey"]:
142
- if t is not None:
143
- return cls._make(t.id, t.storage_data_ptr, t.allocation_id, t.device)
144
- return None
145
-
146
- @property
147
- def _as_sortable(self) -> Tuple[int, int, str, int]:
148
- return self.id, self.storage.allocation_id, self.device.type, self.device.index
149
-
150
-
151
- def _extract_parameters_and_gradients(
152
- node: _ProfilerEvent,
153
- ) -> Iterator[Tuple[Optional[TensorKey], Optional[TensorKey]]]:
154
- children = node.children
155
-
156
- # AccumulateGrad is used in the Autograd engine to handle gradient updates.
157
- # There are two possible cases:
158
- # 1) This is a newly created gradient Tensor. In that case there is nothing
159
- # to accumulate, so autograd simply detaches the Tensor.
160
- #
161
- # 2) There is a preexisting gradient Tensor and we need to add the newly
162
- # computed update. This is done with an in-place add (aten::add_) op.
163
- # (The underscore suffix denotes "in-place".)
164
- if (
165
- node.typed[0] == _EventType.TorchOp
166
- and node.typed[1].scope == RecordScope.BACKWARD_FUNCTION
167
- # TODO(robieta): Move away from load bearing names
168
- and node.name == "torch::autograd::AccumulateGrad"
169
- and children
170
- and children[0].typed[0] == _EventType.TorchOp
171
- and children[0].name in ("aten::detach", "aten::add_")
172
- and children[0].typed[1].inputs
173
- and isinstance(children[0].typed[1].inputs[0], _TensorMetadata)
174
- ):
175
- yield None, TensorKey.from_tensor(children[0].typed[1].inputs[0])
176
-
177
- # We directly instrument `torch.nn.Module` and `torch.optim.Optimizer`
178
- # NOTE: The values captured by the python tracer are cached; they can be
179
- # used to build up labels but do not imply that a Tensor was live at
180
- # a particular time.
181
- elif node.typed[0] == _EventType.PyCall:
182
- typed_fields = node.typed[1]
183
- assert typed_fields.module is None or typed_fields.optimizer is None
184
- if typed_fields.module is not None:
185
- for _, p, p_grad in typed_fields.module.parameters:
186
- yield TensorKey.from_tensor(p), TensorKey.from_tensor(p_grad)
187
-
188
- if typed_fields.optimizer is not None:
189
- for p, p_grad, _ in typed_fields.optimizer.parameters:
190
- yield TensorKey.from_tensor(p), TensorKey.from_tensor(p_grad)
191
-
192
-
193
- def extract_parameters(node: _ProfilerEvent) -> Iterator[TensorKey]:
194
- for p, p_grad in _extract_parameters_and_gradients(node):
195
- if p is not None:
196
- yield p
197
-
198
-
199
- def extract_gradients(
200
- node: _ProfilerEvent,
201
- ) -> Iterator[Tuple[Optional[TensorKey], TensorKey]]:
202
- for p, p_grad in _extract_parameters_and_gradients(node):
203
- if p_grad is not None:
204
- yield p, p_grad
205
-
206
-
207
- def get_scopes(event: Optional[_ProfilerEvent]) -> Tuple[RecordScope, ...]:
208
- scopes = []
209
- while event:
210
- if event.typed[0] == _EventType.TorchOp:
211
- scopes.append(event.typed[1].scope)
212
- event = event.parent
213
- return tuple(scopes)
214
-
215
-
216
- class SchemaMatcher:
217
- """Lookup operator schema based on profiled name.
218
-
219
- When profiling we record the operator's name but not the schema. However
220
- some analysis requires that information. Fortunately we can look up
221
- registered schema from the recorded name. We do not, however, record the
222
- overload and so we must compare the profiled arguments with all overloads
223
- to determine viable matches.
224
-
225
- Note: Once https://github.com/pytorch/pytorch/issues/78871 is completed
226
- this code will be obsolete.
227
- """
228
-
229
- @classmethod
230
- def inputs_are_mutable(cls, t: _ExtraFields_TorchOp) -> Tuple[Optional[bool], ...]:
231
- """Determine which inputs may have mutated based on function schema.
232
-
233
- Note that we don't need to resolve down to a single schema to perform
234
- this analysis. An input is mutable if it is mutable in any overload. In
235
- practice, however, it is overwhelmingly common to match a single
236
- overload. If we cannot find any valid schema then we must be
237
- conservative and assume all inputs are mutable.
238
- """
239
- mutable: Optional[List[bool]] = None
240
- for schema in cls.match_schemas(t):
241
- mutable = mutable or [False for _ in schema.arguments]
242
- for i, arg in enumerate(schema.arguments):
243
- mutable[i] |= getattr(arg.alias_info, "is_write", False)
244
-
245
- return tuple(mutable or (None for _ in t.inputs))
246
-
247
- @classmethod
248
- def match_schemas(cls, t: _ExtraFields_TorchOp) -> Tuple[FunctionSchema, ...]:
249
- signature = tuple(
250
- # Tensor
251
- TensorKey.from_tensor(i) if isinstance(i, _TensorMetadata)
252
- #
253
- # TensorList
254
- else [TensorKey.from_tensor(j) for j in i] if isinstance(i, list)
255
- #
256
- # Scalar and uncaptured inputs.
257
- else i
258
- for i in t.inputs
259
- )
260
-
261
- def matches(schema) -> bool:
262
- return len(schema.arguments) == len(signature) and all(
263
- cls._types_match(observed, schema_arg.type)
264
- for observed, schema_arg in zip(signature, schema.arguments)
265
- )
266
-
267
- return tuple(s for s in cls.lookup_schemas(t.name) or () if matches(s))
268
-
269
- @classmethod
270
- def _types_match(cls, observed, schema_type) -> bool:
271
- if isinstance(schema_type, torch._C.OptionalType):
272
- schema_type = schema_type.getElementType()
273
- return observed is None or cls._types_match(observed, schema_type)
274
-
275
- if isinstance(schema_type, torch._C.AnyType):
276
- return True
277
-
278
- if schema_type.isSubtypeOf(torch._C.ListType.ofTensors()):
279
- return isinstance(observed, list) and all(
280
- isinstance(i, TensorKey) for i in observed
281
- )
282
-
283
- type_map: Tuple[Tuple[Any, Union[type, Tuple[type, ...]]], ...] = (
284
- (torch._C.TensorType, TensorKey),
285
- (torch._C.NoneType, type(None)),
286
- (torch._C.BoolType, bool),
287
- (torch._C.IntType, int),
288
- (torch._C.FloatType, float),
289
- (torch._C.ComplexType, complex),
290
- (torch._C.NumberType, (bool, int, float, complex)),
291
- )
292
-
293
- for jit_type, py_types in type_map:
294
- if isinstance(schema_type, jit_type):
295
- return isinstance(observed, py_types)
296
-
297
- # Profiler only records a subset of possible argument types. If we
298
- # reach this point then the schema must call for a type that profiler
299
- # does not record. Thus, the schema can only be a match if `observed`
300
- # is also None.
301
- return observed is None
302
-
303
- @staticmethod
304
- def lookup_schemas(name: str) -> Optional[Tuple[FunctionSchema, ...]]:
305
- # TODO(robieta):
306
- # _jit_get_schemas_for_operator is quite expensive. (~100us / call)
307
- # Consider adding `functools.lru_cache` if that becomes an issue.
308
-
309
- try:
310
- # Schema lookup will throw if `name` is malformed. (For example,
311
- # schemas must be namespaced and schema lookup will fail if name
312
- # does not include "::".) We simply catch the exception and return
313
- # `None` to denote that `name` cannot be an operator name.
314
- #
315
- # Note that record_function annotations also go through this path,
316
- # so it is expected that some names will not correspond to PyTorch
317
- # operators.
318
- if "::" not in name:
319
- return None
320
- return tuple(torch._C._jit_get_schemas_for_operator(name))
321
- except RuntimeError:
322
- return None
323
-
324
-
325
- class OpTree:
326
- def __init__(self, result: _ProfilerResult) -> None:
327
- self._root_nodes = result.experimental_event_tree()
328
- self._sorted_nodes = tuple(sorted(self.dfs(), key=lambda x: x.start_time_ns))
329
-
330
- def dfs(self, *args, **kwargs) -> Iterator[_ProfilerEvent]:
331
- yield from _utils.traverse_dfs(self._root_nodes, *args, **kwargs)
332
-
333
- @property
334
- def sorted_nodes(self) -> Tuple[_ProfilerEvent, ...]:
335
- return self._sorted_nodes
336
-
337
-
338
- class SizeMap:
339
- def __init__(self, op_tree: OpTree) -> None:
340
- self._values: Dict[TensorKey, int] = {}
341
-
342
- for node in op_tree.sorted_nodes:
343
- if node.typed[0] == _EventType.TorchOp:
344
- for t in self._flat_tensor_inputs(node.typed[1]):
345
- self._update_values(t)
346
-
347
- elif node.typed[0] == _EventType.PyCall:
348
- typed_fields = node.typed[1]
349
- assert typed_fields.module is None or typed_fields.optimizer is None
350
- if typed_fields.module is not None:
351
- for _, p, p_grad in typed_fields.module.parameters:
352
- self._update_values(p)
353
- self._update_values(p_grad)
354
-
355
- if typed_fields.optimizer is not None:
356
- for p, p_grad, state in typed_fields.optimizer.parameters:
357
- self._update_values(p)
358
- self._update_values(p_grad)
359
- for _, t in state:
360
- self._update_values(t)
361
-
362
- allocations: Dict[TensorKey, int] = {}
363
- for node in op_tree.sorted_nodes:
364
- if node.typed[0] == _EventType.Allocation:
365
- alloc_fields = node.typed[1]
366
- key = TensorKey.from_allocation(alloc_fields)
367
- if key:
368
- new_size = abs(alloc_fields.alloc_size)
369
- prior_size = allocations.setdefault(key, new_size)
370
-
371
- # It is possible to resize Storage in PyTorch, however we
372
- # key on data pointer so most resizes will be treated as a
373
- # change in storage. The one corner case that cannot be
374
- # handled is `realloc` which successfully resizes the
375
- # storage. At time of writing this is not done anywhere in
376
- # the core PyTorch codebase.
377
- if prior_size != new_size:
378
- delta = f"{prior_size} vs. {new_size}"
379
- log.warning("Mismatch between allocation and free: %s", delta)
380
-
381
- self._values.update(allocations)
382
-
383
- def _update_values(self, t: Optional[_TensorMetadata]) -> None:
384
- key = TensorKey.from_tensor(t)
385
- if key is not None and t is not None and t.layout == torch.strided:
386
- # Scalars are represented as zero dim Tensors
387
- n = max(i[0] * i[1] for i in zip(t.sizes or [1], t.strides or [1]))
388
-
389
- num_bytes = n * _element_size(t.dtype)
390
- assert num_bytes >= 0, f"{num_bytes}"
391
- self._values[key] = max(self._values.get(key, 0), num_bytes)
392
-
393
- @staticmethod
394
- def _flat_tensor_inputs(op: _ExtraFields_TorchOp) -> Iterator[_TensorMetadata]:
395
- for i in op.inputs:
396
- if isinstance(i, _TensorMetadata):
397
- yield i
398
- elif isinstance(i, list):
399
- yield from i
400
-
401
- def __getitem__(self, key: TensorKey):
402
- return self._values[key]
403
-
404
-
405
- @dataclasses.dataclass()
406
- class DataFlowEdge:
407
- input_version: Optional[int] = None
408
- mutated: Optional[bool] = False
409
-
410
- @property
411
- def is_allocation(self) -> bool:
412
- return self.input_version is None
413
-
414
- @property
415
- def is_deletion(self) -> bool:
416
- return self.mutated is None
417
-
418
-
419
- class DataFlowNode:
420
- def __init__(self, event: _ProfilerEvent, graph: "DataFlowGraph") -> None:
421
- self._event = event
422
- self._graph = graph
423
- self._edges: Dict[TensorKey, DataFlowEdge] = self._determine_edges()
424
-
425
- for key, edge in self._edges.items():
426
- if edge.mutated and not edge.is_allocation:
427
- self._graph.bump(key)
428
-
429
- # Make sure the version bumping behavior matches what we expect.
430
- versions = {k: (v, self._graph.lookup(k)) for k, v in self.outputs.items()}
431
- assert all(i == j for i, j in versions.values()), f"{versions}, {self._edges}"
432
-
433
- def _determine_edges(self) -> Dict[TensorKey, DataFlowEdge]:
434
- subtree = tuple(_utils.traverse_dfs([self._event]))
435
-
436
- # Start by populating edges from op inputs and outputs.
437
- mutable_by_key: Dict[Optional[TensorKey], Set[Optional[bool]]] = {}
438
- for op in (i.typed[1] for i in subtree if i.typed[0] == _EventType.TorchOp):
439
- for op_input, mutable in zip(
440
- op.inputs, SchemaMatcher.inputs_are_mutable(op)
441
- ):
442
- # Tensor
443
- if isinstance(op_input, _TensorMetadata):
444
- key = TensorKey.from_tensor(op_input)
445
- mutable_by_key.setdefault(key, set()).add(mutable)
446
-
447
- # TensorList
448
- elif isinstance(op_input, list):
449
- for op_input_i in op_input:
450
- key = TensorKey.from_tensor(op_input_i)
451
- mutable_by_key.setdefault(key, set()).add(mutable)
452
-
453
- edges: DefaultDict[Optional[TensorKey], DataFlowEdge]
454
- edges = collections.defaultdict(DataFlowEdge)
455
- for key, mutable_set in mutable_by_key.items():
456
- if key is not None:
457
- edges[key].input_version = self._graph.lookup(key) if key else -1
458
-
459
- # We consider an op to be mutated if we encounter a schema where it
460
- # is a mutable argument OR if it is ambiguous. (We never explicitly
461
- # see it in any schema.)
462
- mutated = (True in mutable_set) or (tuple(mutable_set) == (None,))
463
- edges[key].mutated = mutated
464
-
465
- # Then handle deletions. Note that deleting a Tensor implicitly adds
466
- # it as an input edge.
467
- for i in subtree:
468
- if i.typed[0] == _EventType.Allocation and i.typed[1].alloc_size < 0:
469
- key = TensorKey.from_allocation(i.typed[1])
470
- edge = edges[key]
471
- assert key is None or edge.mutated is not None, f"Double delete: {key}"
472
- edge.mutated = None
473
- edge.input_version = self._graph.lookup(key) if key else -1
474
-
475
- # And finally handle allocations. This step must be last, because the
476
- # previous two steps optimistically add input edges.
477
- for i in subtree:
478
- if i.typed[0] == _EventType.Allocation and i.typed[1].alloc_size > 0:
479
- edges[TensorKey.from_allocation(i.typed[1])].input_version = None
480
-
481
- # We don't need to sort the inputs, but it makes debugging and unit tests nicer.
482
- return dict(sorted((k, v) for k, v in edges.items() if k is not None))
483
-
484
- @property
485
- def inputs(self) -> Dict[TensorKey, Tuple[bool, int]]:
486
- return {
487
- # MyPy can't see through `is_allocation` to know that
488
- # `v.input_version` is not None.
489
- k: (bool(v.mutated), cast(int, v.input_version))
490
- for k, v in self._edges.items()
491
- if not v.is_allocation
492
- }
493
-
494
- @property
495
- def outputs(self) -> Dict[TensorKey, int]:
496
- return {
497
- k: 0 if v.input_version is None else v.input_version + 1
498
- for k, v in self._edges.items()
499
- if (v.is_allocation and not v.is_deletion) or v.mutated
500
- }
501
-
502
- @property
503
- def intermediates(self) -> Tuple[TensorKey, ...]:
504
- return tuple(
505
- k for k, v in self._edges.items() if v.is_allocation and v.is_deletion
506
- )
507
-
508
- @property
509
- def start_time(self) -> int:
510
- return self._event.start_time_ns
511
-
512
-
513
- class DataFlowGraph:
514
- def __init__(self, op_tree: OpTree) -> None:
515
- self._op_tree = op_tree
516
- self._leaf_events = self._extract_leaf_events(op_tree)
517
- self._active_version: Dict[TensorKey, Optional[int]] = {}
518
- self._flow_nodes = [DataFlowNode(e, self) for e in self.leaf_events]
519
- self._flow_nodes.sort(key=lambda x: x.start_time)
520
- self.validate()
521
-
522
- @property
523
- def flow_nodes(self) -> Tuple[DataFlowNode, ...]:
524
- return tuple(self._flow_nodes)
525
-
526
- def validate(self):
527
- # Check that each (Tensor, version) pair has a unique creation node
528
- outputs: Set[Tuple[TensorKey, int]] = set()
529
- for node in self.flow_nodes:
530
- node_outputs = set(node.outputs.items())
531
- duplicates = outputs & node_outputs
532
- assert not duplicates, f"{node._event.name} {node._edges} {duplicates}"
533
- outputs |= node_outputs
534
-
535
- # And check that `self._nodes` forms a valid topologically sorted DAG.
536
- tensor_versions: Dict[TensorKey, int] = {}
537
- for node in self.flow_nodes:
538
- for key, (_, version) in node.inputs.items():
539
- expected = tensor_versions.get(key, 0)
540
- assert expected == version, (expected, version)
541
-
542
- for key, version in node.outputs.items():
543
- prior_version = tensor_versions.get(key, version)
544
- assert version >= prior_version, (version, prior_version)
545
- tensor_versions[key] = version
546
-
547
- @property
548
- def leaf_events(self) -> Tuple[_ProfilerEvent, ...]:
549
- return self._leaf_events
550
-
551
- @staticmethod
552
- def _extract_leaf_events(op_tree: OpTree) -> Tuple[_ProfilerEvent, ...]:
553
- """Partially traverse the op tree and extract top level ops.
554
-
555
- Consider the following code:
556
- ```
557
- with record_function("My annotation"):
558
- x.zero_()
559
- y.zero_()
560
- ```
561
-
562
- The op tree (assuming no Autograd) will look like:
563
- <Python context>
564
- TorchOp: "My annotation"
565
- TorchOp: zero_
566
- TorchOp: fill_
567
- TorchOp: zero_
568
- TorchOp: fill_
569
-
570
- The recursive structure of operator calls makes data flow unwieldy.
571
- In order to simplify analysis we would like to select the highest level
572
- ops to represent in the graph. In this case those are the `zero_` ops;
573
- the fact that `fill_` is called is an implementation detail. We also
574
- do not want to group everything under "My annotation" as this could
575
- create overly coarse bundles and lose critical semantics.
576
-
577
- To address this issue we walk over the graph and select the topmost
578
- torch ops ** which match at least one operator schema **. These form
579
- the leaves of the first pass through the op tree. (As well as any
580
- allocations or frees which do are not part of a kernel.) These events
581
- form the logical nodes in our data flow graph.
582
- """
583
-
584
- leaf_events: List[_ProfilerEvent] = []
585
-
586
- def leaf_op(e: _ProfilerEvent) -> bool:
587
- return e.typed[0] == _EventType.TorchOp and (
588
- e.typed[1].scope == RecordScope.BACKWARD_FUNCTION
589
- or bool(SchemaMatcher.match_schemas(e.typed[1]))
590
- )
591
-
592
- def children_fn(e: _ProfilerEvent):
593
- if leaf_op(e) or e.tag == _EventType.Allocation:
594
- leaf_events.append(e)
595
- return []
596
-
597
- return e.children
598
-
599
- for _ in op_tree.dfs(children_fn=children_fn):
600
- pass
601
-
602
- return tuple(sorted(leaf_events, key=lambda x: x.start_time_ns))
603
-
604
- def lookup(self, key: TensorKey) -> int:
605
- version = self._active_version.setdefault(key, 0)
606
- assert version is not None
607
- return version
608
-
609
- def bump(self, key: TensorKey) -> None:
610
- prior_version = self._active_version.get(key, None)
611
- assert prior_version is not None
612
- self._active_version[key] = prior_version + 1
613
-
614
- def delete(self, key: TensorKey) -> None:
615
- assert self._active_version.setdefault(key, 0) is not None
616
- self._active_version[key] = None
617
-
618
-
619
- @dataclasses.dataclass
620
- class CategoryElement:
621
- by_id: Optional[Category] = None
622
- by_key: Dict[TensorKey, Category] = dataclasses.field(default_factory=dict)
623
- by_version: Dict[TensorAndID, Category] = dataclasses.field(default_factory=dict)
624
-
625
- # Used by unit tests to check internals. (And consequently by
626
- # MemoryProfile.lookup) This should not be used in any other capacity.
627
- _by_id_keyset: Set[TensorKey] = dataclasses.field(default_factory=set)
628
-
629
-
630
- @dataclasses.dataclass
631
- class CategoryDict:
632
- _values: DefaultDict[int, CategoryElement] = dataclasses.field(
633
- default_factory=lambda: collections.defaultdict(CategoryElement)
634
- )
635
-
636
- def set_by_id(self, key: TensorKey, category: Category) -> None:
637
- self._values[key.id].by_id = category
638
- self._values[key.id]._by_id_keyset.add(key)
639
-
640
- def set_by_key(self, key: TensorKey, category: Category) -> None:
641
- self._values[key.id].by_key[key] = category
642
-
643
- def set_by_version(self, key: TensorKey, version: int, category: Category) -> None:
644
- self._values[key.id].by_version[(key, version)] = category
645
-
646
- def setdefault_by_version(
647
- self, key: TensorKey, version: int, category: Category
648
- ) -> None:
649
- self._values[key.id].by_version.setdefault((key, version), category)
650
-
651
- def get(self, key: Key, version: int) -> Optional[Category]:
652
- if isinstance(key, Key) and not isinstance(key, TensorKey):
653
- return None
654
- element = self._values[key.id]
655
- return (
656
- element.by_id
657
- or element.by_key.get(key, None)
658
- or element.by_version.get((key, version), None)
659
- )
660
-
661
-
662
- class MemoryProfile:
663
- def __init__(self, result: _ProfilerResult) -> None:
664
- self._op_tree = OpTree(result)
665
- self._data_flow_graph = DataFlowGraph(self._op_tree)
666
- self._size_map = SizeMap(self._op_tree)
667
- self._categories = CategoryDict()
668
-
669
- self._set_gradients_and_temporaries()
670
- self._set_parameters_using_python_tracer()
671
- self._set_inputs()
672
- self._set_parameters_using_data_flow()
673
- self._set_activations()
674
- self._set_optimizer_state()
675
- self._set_autograd_detail()
676
-
677
- @property
678
- def timeline(self) -> Tuple[Tuple[int, Action, KeyAndID, int], ...]:
679
- output: List[Tuple[int, Action, KeyAndID, int]] = []
680
- allocation_times: Dict[Tuple[TensorKey, bool], int] = {}
681
- live_unknown: Dict[Tuple[int, torch.device], Literal[True]] = {}
682
- for event in self._op_tree.dfs():
683
- if event.typed[0] == _EventType.Allocation:
684
- alloc_fields = event.typed[1]
685
- alloc_size = alloc_fields.alloc_size
686
- is_allocation = alloc_size > 0
687
- t = event.start_time_ns
688
-
689
- tkey = TensorKey.from_allocation(alloc_fields)
690
- if tkey is not None:
691
- allocation_times[(tkey, is_allocation)] = t
692
-
693
- else:
694
- key = Key(alloc_fields.device)
695
- ptr_and_device = (alloc_fields.ptr, key.device)
696
- if is_allocation:
697
- if ptr_and_device in live_unknown:
698
- output.append(
699
- (t, Action.INCREMENT_VERSION, (key, 0), alloc_size)
700
- )
701
- else:
702
- live_unknown[ptr_and_device] = True
703
- output.append((t, Action.CREATE, (key, 0), alloc_size))
704
- else:
705
- output.append((t, Action.DESTROY, (key, 0), -alloc_size))
706
- if not live_unknown.pop(ptr_and_device, False):
707
- output.append(
708
- (-1, Action.PREEXISTING, (key, 0), -alloc_size)
709
- )
710
-
711
- snapshot = self._category_snapshot()
712
- last_version = dict(sorted(snapshot.keys()))
713
-
714
- events: List[Tuple[int, Action, TensorAndID]] = [
715
- (-1, Action.PREEXISTING, (key, version))
716
- for key, version in snapshot.keys()
717
- if (key, True) not in allocation_times and version == 0
718
- ]
719
-
720
- for node in self._data_flow_graph.flow_nodes:
721
- for key, edge in node._edges.items():
722
- if edge.is_allocation:
723
- t = allocation_times[(key, True)]
724
- events.append((t, Action.CREATE, (key, 0)))
725
-
726
- elif edge.mutated:
727
- t = node._event.start_time_ns
728
- version = edge.input_version
729
- assert version is not None
730
- events.append((t, Action.INCREMENT_VERSION, (key, version)))
731
-
732
- if edge.is_deletion:
733
- t = allocation_times[(key, False)]
734
- events.append((t, Action.DESTROY, (key, last_version[key])))
735
-
736
- output.extend(
737
- (time, action, (key, version), self._size_map[key])
738
- for time, action, (key, version) in events
739
- )
740
-
741
- output.sort(key=lambda x: (x[0], x[1].value))
742
- return tuple(output)
743
-
744
- def _is_gradient(self, *args, **kwargs) -> bool:
745
- return self._categories.get(*args, **kwargs) == Category.GRADIENT
746
-
747
- def _category_snapshot(self) -> Dict[TensorAndID, Optional[Category]]:
748
- all_tensor_versions: Set[TensorAndID] = set()
749
-
750
- for node in self._data_flow_graph.flow_nodes:
751
- all_tensor_versions.update(((k, v) for k, (_, v) in node.inputs.items()))
752
- all_tensor_versions.update((key, 0) for key in node.intermediates)
753
- all_tensor_versions.update(node.outputs.items())
754
-
755
- for i in self._categories._values.values():
756
- all_tensor_versions.update((key, 0) for key in i._by_id_keyset)
757
-
758
- return {
759
- (key, version): self._categories.get(key, version)
760
- for key, version in sorted(all_tensor_versions)
761
- }
762
-
763
- def _any_version_depends_on_gradient(self) -> Set[int]:
764
- """Extract IDs of Tensors which depend or will depend on a gradient.
765
-
766
- Note that this weakened definition of "depends" requires us to loop
767
- over the data flow graph multiple times because it allows dependency
768
- information to flow backward through edges and removes the guarantee
769
- that nodes are topologically sorted. (Or indeed, even that a valid
770
- topological order exists.) Put another way, we have converted an
771
- acyclic data flow graph into a cyclic graph and we are attempting to
772
- partition cycles involving a gradient from the rest of the graph.
773
- """
774
- depends_on_gradient: Set[int] = set()
775
- while True:
776
- start_size = len(depends_on_gradient)
777
- for node in self._data_flow_graph.flow_nodes:
778
- ids = tuple(
779
- key.id
780
- for key, (_, version) in node.inputs.items()
781
- if self._categories.get(key, version)
782
- in (Category.GRADIENT, Category.PARAMETER)
783
- or key.id in depends_on_gradient
784
- )
785
-
786
- if ids:
787
- depends_on_gradient.update(ids)
788
- depends_on_gradient.update(key.id for key in node.outputs)
789
-
790
- # We are guaranteed to exit because there is a finite set of
791
- # TensorAndID pairs. In practice we do not expect to loop more than
792
- # three times: once to identify the core parameter update loop,
793
- # once to fold the first step into that loop, and a third time
794
- # where no new elements are added.
795
- if len(depends_on_gradient) == start_size:
796
- return depends_on_gradient
797
-
798
- def _set_gradients_and_temporaries(self) -> None:
799
- """Mark Tensors which are unambiguous and simple to reason about."""
800
-
801
- # Gradients are straightforward to detect. We directly check the
802
- # `.grad` property in the Python tracer, and we can detect any new
803
- # gradient Tensors from `AccumulateGrad` ops.
804
- for event in self._op_tree.dfs():
805
- for _, p_grad in extract_gradients(event):
806
- self._categories.set_by_id(p_grad, Category.GRADIENT)
807
-
808
- # Similarly, temporary Tensors are easy to identify and are useful to
809
- # flag since they can make memory use "spikier" than one would
810
- # otherwise expect.
811
- for node in self._data_flow_graph.flow_nodes:
812
- for i in node.intermediates:
813
- self._categories.set_by_key(i, Category.TEMPORARY)
814
-
815
- def _set_parameters_using_python_tracer(self) -> None:
816
- for event in self._op_tree.dfs():
817
- for p in extract_parameters(event):
818
- if p is not None:
819
- self._categories.set_by_id(p, Category.PARAMETER)
820
-
821
- def _set_inputs(self) -> None:
822
- """Mark inputs based on which Tensors are updated using gradients.
823
-
824
- The process for differentiating between inputs and activations is more
825
- involved. Most Tensors in a training loop depend on at least one
826
- gradient: parameters depend on them through updates, and activations
827
- and optimizer state depend on them transitively through parameters.
828
- Critically, we do not need to know which Tensors are parameters to
829
- apply this method; we can simply walk the data flow graph to build the
830
- set of all values which depend on a gradient and then obtain the set
831
- of inputs from the conjugate set.
832
-
833
- There is, however, one hiccup. The first time we see a parameter is
834
- generally on the forward pass of the first step. We know from
835
- inspection of the data flow graph that v1 of that Tensor depends on
836
- a gradient (provided we profile an optimizer step), but not v0. To
837
- address this problem we weaken the definition of "depends on a
838
- gradient" to "any version of this Tensor depends on a gradient",
839
- which in turn strengthens the criteria for the input set enough to
840
- filter the activations in the forward pass of the first step."""
841
-
842
- # All of this analysis is predicated on using at least one training
843
- # step (or parameters from the python tracer) to partition the graph.
844
- # Absent that we cannot determine which Tensors are inputs and which
845
- # ones are part of the model.
846
- depends_on_gradient = self._any_version_depends_on_gradient()
847
-
848
- # We only want to annotate Tensors which actually contribute to the
849
- # model calculation.
850
- produces_gradient: Set[TensorAndID] = set()
851
- for node in reversed(self._data_flow_graph.flow_nodes):
852
- tensors = {(key, version) for key, (_, version) in node.inputs.items()}
853
- tensors |= node.outputs.items()
854
- if any(
855
- self._categories.get(*i) in (Category.GRADIENT, Category.PARAMETER)
856
- or i in produces_gradient
857
- for i in tensors
858
- ):
859
- produces_gradient |= tensors
860
-
861
- # Don't include Tensors created in the backward pass, as these are
862
- # generally Autograd implementation details rather than proper inputs.
863
- input_candidates = produces_gradient.copy()
864
- for node in self._data_flow_graph.flow_nodes:
865
- if RecordScope.BACKWARD_FUNCTION in get_scopes(node._event):
866
- input_candidates -= set(node.outputs.items())
867
-
868
- for key, version in input_candidates:
869
- if key.id not in depends_on_gradient:
870
- self._categories.setdefault_by_version(key, version, Category.INPUT)
871
-
872
- def _set_parameters_using_data_flow(self) -> None:
873
- """Deduce which Tensors are parameters.
874
-
875
- Consider the following code for the step of SGD with momentum
876
- (nesterov=False), where `d_p` is the gradient of `param` and `buf` is
877
- the momentum buffer.
878
- ```
879
- buf.mul_(momentum).add_(d_p, alpha=1 - dampening)
880
- d_p = buf
881
- param.add_(d_p, alpha=-lr)
882
- ```
883
- Both `param` and `buf` take a gradient and perform an in-place update.
884
-
885
- The python tracer will inspect calls to `nn.Module.forward` and
886
- `optim.Optimizer.step` to extract parameter and optimizer state
887
- respectively (including parameters), so this is generally a non-issue.
888
-
889
- However as a fallback we can also exploit several properties of
890
- parameters to distinguish them from other model state.
891
-
892
- First, they are directly used in the forward pass. (At this point we
893
- haven't established which parts of the graph correspond to the forward
894
- pass but we can deduce enough to suffice.) Some mutable state such as
895
- batch norm moving averages also contribute to the forward pass, but
896
- optimizer state does not.
897
-
898
- Second, a parameter is by definition used to compute at least one
899
- gradient and depends on at least one gradient.
900
- """
901
- snapshot = self._category_snapshot()
902
-
903
- # Determine which Tensors might be parameters based on forward pass
904
- # data flow. Note this these are only candidates; we filter nodes that
905
- # we know are part of the backward pass but that doesn't guarantee that
906
- # they are part of the forward pass.
907
- candidate_parameters: Set[TensorAndID] = set()
908
- candidate_fwd_tensors: Set[TensorAndID] = {
909
- i for i, category in snapshot.items() if category == Category.INPUT
910
- }
911
-
912
- for node in self._data_flow_graph.flow_nodes:
913
- inputs = {(key, value) for key, (_, value) in node.inputs.items()}
914
- if (
915
- # Don't check nodes in the backward pass.
916
- RecordScope.BACKWARD_FUNCTION not in get_scopes(node._event)
917
- and not any(self._is_gradient(*i) for i in inputs)
918
- and not any(self._is_gradient(*i) for i in node.outputs.items())
919
- #
920
- # and only check nodes which depend on an input.
921
- and candidate_fwd_tensors.intersection(inputs)
922
- ):
923
- candidate_fwd_tensors |= node.outputs.items()
924
- candidate_parameters |= inputs.difference(candidate_fwd_tensors)
925
-
926
- # Require that each parameter eventually contributes to the value of a gradient
927
- used_for_gradient: Set[TensorAndID] = set()
928
- for node in reversed(self._data_flow_graph.flow_nodes):
929
- if any(
930
- self._is_gradient(*i) or i in used_for_gradient
931
- for i in node.outputs.items()
932
- ):
933
- for key, (_, version) in node.inputs.items():
934
- used_for_gradient.add((key, version))
935
- candidate_parameters.intersection_update(used_for_gradient)
936
-
937
- # and depends on a gradient.
938
- parameter_keys = {key.id for key, _ in candidate_parameters}
939
- parameter_keys &= self._any_version_depends_on_gradient()
940
-
941
- for key, _ in snapshot.keys():
942
- if key.id in parameter_keys:
943
- self._categories.set_by_id(key, Category.PARAMETER)
944
-
945
- def _set_activations(self) -> None:
946
- """Flood the graph to identify activations."""
947
-
948
- required = {Category.INPUT, Category.ACTIVATION}
949
- also_allowed = {Category.PARAMETER, Category.TEMPORARY}
950
- for node in self._data_flow_graph.flow_nodes:
951
- inputs = {(key, value) for key, (_, value) in node.inputs.items()}
952
- input_categories = {self._categories.get(*i) for i in inputs}
953
-
954
- if (
955
- (input_categories & required)
956
- and not (input_categories - (required | also_allowed))
957
- #
958
- # Stop filling when we reach the backward pass.
959
- and RecordScope.BACKWARD_FUNCTION not in get_scopes(node._event)
960
- ):
961
- for i in node.outputs.items():
962
- self._categories.setdefault_by_version(*i, Category.ACTIVATION)
963
-
964
- def _set_optimizer_state(self) -> None:
965
- for event in self._op_tree.dfs():
966
- if event.typed[0] == _EventType.PyCall and event.typed[1].optimizer:
967
- parameters = event.typed[1].optimizer.parameters
968
- for _, t in it.chain(*[state for _, _, state in parameters]):
969
- key = TensorKey.from_tensor(t)
970
- if key is not None:
971
- self._categories.set_by_id(key, Category.OPTIMIZER_STATE)
972
-
973
- def _set_autograd_detail(self):
974
- prior = {None, Category.AUTOGRAD_DETAIL}
975
- for node in self._data_flow_graph.flow_nodes:
976
- if RecordScope.BACKWARD_FUNCTION in get_scopes(node._event):
977
- for key, version in node.outputs.items():
978
- if version == 0 or self._categories.get(key, version - 1) in prior:
979
- self._categories.setdefault_by_version(
980
- key, version, Category.AUTOGRAD_DETAIL
981
- )
982
-
983
-
984
- class MemoryProfileTimeline:
985
- def __init__(self, memory_profile):
986
- """The minimum representation of the memory profile timeline
987
- includes the memory timeline and categories. The timeline
988
- consists of [timestamp, action, (TensorKey, version), numbytes]
989
- elements, to denote any actions (pre-existing, create, destroy,
990
- or increment_version) that occurred to a specific Tensor for a
991
- chunk of memory. The categories help map each (TensorKey,
992
- version) pair into a category."""
993
- self.timeline = memory_profile.timeline
994
- self.categories = memory_profile._categories
995
-
996
- def _coalesce_timeline(self, device_str):
997
- """Convert the memory timeline and categories into a memory plot
998
- consisting of timestamps and their respective sizes by category
999
- for a given device.
1000
-
1001
- Input: device
1002
- Output: [timestamps, sizes by category]
1003
- """
1004
- device = torch.device(device_str)
1005
- times: List[int] = []
1006
- sizes: List[List[int]] = []
1007
-
1008
- def update(key, version, delta):
1009
- category = (
1010
- self.categories.get(key, version)
1011
- if isinstance(key, TensorKey)
1012
- else None
1013
- )
1014
- index = _CATEGORY_TO_INDEX[category] + 1
1015
- sizes[-1][index] += int(delta)
1016
-
1017
- t_min = -1
1018
- for t, action, (key, version), numbytes in self.timeline:
1019
- if key.device != device:
1020
- continue
1021
-
1022
- # Convert timestamps from ns to us, to match trace events.
1023
- if t != -1:
1024
- t = int(t / 1000)
1025
-
1026
- # Save the smallest timestamp to populate pre-existing allocs.
1027
- if t_min == -1 or (t < t_min and t > 0):
1028
- t_min = t
1029
-
1030
- # Handle timestep
1031
- if len(times) == 0:
1032
- times.append(t)
1033
- sizes.append([0] + [0 for _ in _CATEGORY_TO_INDEX])
1034
-
1035
- elif t != times[-1]:
1036
- times.append(t)
1037
- sizes.append(sizes[-1].copy())
1038
-
1039
- # Handle memory and categories
1040
- if action in (Action.PREEXISTING, Action.CREATE):
1041
- update(key, version, numbytes)
1042
-
1043
- elif action == Action.INCREMENT_VERSION:
1044
- update(key, version, -numbytes)
1045
- update(key, version + 1, numbytes)
1046
-
1047
- elif action == Action.DESTROY:
1048
- update(key, version, -numbytes)
1049
-
1050
- else:
1051
- raise ValueError(f"Unknown action: {action}")
1052
-
1053
- times = [t_min if t < 0 else t for t in times]
1054
- return times, sizes
1055
-
1056
- def export_memory_timeline(self, path, device_str) -> None:
1057
- """Saves the memory timeline as [times, sizes by category]
1058
- as a JSON formatted file to the given path for the given
1059
- device."""
1060
- times, sizes = self._coalesce_timeline(device_str)
1061
- # TODO: Write a faster serialize (orjson not available in CI)
1062
- import json
1063
-
1064
- with open(path, "w") as f:
1065
- json.dump([times, sizes], f)
1066
-
1067
- def export_memory_timeline_raw(self, path, device_str) -> None:
1068
- """Saves the memory timeline as raw memory event tuples in the
1069
- form of (timestamp, action, numbytes, category)
1070
- as a JSON formatted file to the given path for the given
1071
- device."""
1072
- device = torch.device(device_str)
1073
- raw_events: List[Tuple[int, int, int, int]] = []
1074
-
1075
- def get_category_index(key, version):
1076
- category = (
1077
- self.categories.get(key, version)
1078
- if isinstance(key, TensorKey)
1079
- else None
1080
- )
1081
- return _CATEGORY_TO_INDEX[category]
1082
-
1083
- for t, action, (key, version), numbytes in self.timeline:
1084
- if key.device != device:
1085
- continue
1086
-
1087
- if action in (Action.PREEXISTING, Action.CREATE):
1088
- raw_events.append(
1089
- (
1090
- t,
1091
- _ACTION_TO_INDEX[action],
1092
- numbytes,
1093
- get_category_index(key, version),
1094
- )
1095
- )
1096
-
1097
- elif action == Action.INCREMENT_VERSION:
1098
- raw_events.append(
1099
- (
1100
- t,
1101
- _ACTION_TO_INDEX[action],
1102
- -numbytes,
1103
- get_category_index(key, version),
1104
- )
1105
- )
1106
- raw_events.append(
1107
- (
1108
- t,
1109
- _ACTION_TO_INDEX[action],
1110
- numbytes,
1111
- get_category_index(key, version + 1),
1112
- )
1113
- )
1114
-
1115
- elif action == Action.DESTROY:
1116
- raw_events.append(
1117
- (
1118
- t,
1119
- _ACTION_TO_INDEX[action],
1120
- -numbytes,
1121
- get_category_index(key, version),
1122
- )
1123
- )
1124
-
1125
- else:
1126
- raise ValueError(f"Unknown action: {action}")
1127
-
1128
- import json
1129
-
1130
- with open(path, "w") as f:
1131
- json.dump(raw_events, f)
1132
-
1133
- def export_memory_timeline_html(
1134
- self, path, device_str, figsize=(20, 12), title=None
1135
- ) -> None:
1136
- """Exports the memory timeline as an HTML file which contains
1137
- the memory timeline plot embedded as a PNG file."""
1138
- # Check if user has matplotlib installed, return gracefully if not.
1139
- import importlib.util
1140
-
1141
- matplotlib_spec = importlib.util.find_spec("matplotlib")
1142
- if matplotlib_spec is None:
1143
- print(
1144
- "export_memory_timeline_html failed because matplotlib was not found."
1145
- )
1146
- return
1147
-
1148
- from base64 import b64encode
1149
- from os import remove
1150
- from tempfile import NamedTemporaryFile
1151
-
1152
- import matplotlib.pyplot as plt
1153
- import numpy as np
1154
-
1155
- mt = self._coalesce_timeline(device_str)
1156
- times, sizes = np.array(mt[0]), np.array(mt[1])
1157
- # For this timeline, start at 0 to match Chrome traces.
1158
- t_min = min(times)
1159
- times -= t_min
1160
- stacked = np.cumsum(sizes, axis=1) / 1024**3
1161
- device = torch.device(device_str)
1162
- max_memory_allocated = torch.cuda.max_memory_allocated(device)
1163
- max_memory_reserved = torch.cuda.max_memory_reserved(device)
1164
-
1165
- # Plot memory timeline as stacked data
1166
- fig = plt.figure(figsize=figsize, dpi=80)
1167
- axes = fig.gca()
1168
- for category, color in _CATEGORY_TO_COLORS.items():
1169
- i = _CATEGORY_TO_INDEX[category]
1170
- axes.fill_between(
1171
- times / 1e3, stacked[:, i], stacked[:, i + 1], color=color, alpha=0.7
1172
- )
1173
- fig.legend(["Unknown" if i is None else i.name for i in _CATEGORY_TO_COLORS])
1174
- # Usually training steps are in magnitude of ms.
1175
- axes.set_xlabel("Time (ms)")
1176
- axes.set_ylabel("Memory (GB)")
1177
- title = "\n\n".join(
1178
- ([title] if title else [])
1179
- + [
1180
- f"Max memory allocated: {max_memory_allocated/(1024**3):.2f} GiB \n"
1181
- f"Max memory reserved: {max_memory_reserved/(1024**3):.2f} GiB"
1182
- ]
1183
- )
1184
- axes.set_title(title)
1185
-
1186
- # Embed the memory timeline image into the HTML file
1187
- tmpfile = NamedTemporaryFile("wb", suffix=".png", delete=False)
1188
- tmpfile.close()
1189
- fig.savefig(tmpfile.name, format="png")
1190
-
1191
- with open(tmpfile.name, "rb") as tmp:
1192
- encoded = b64encode(tmp.read()).decode("utf-8")
1193
- html = f"""<html>
1194
- <head><meta charset="utf-8" /><title>GPU Memory Timeline HTML</title></head>
1195
- <body>
1196
- <img src='data:image/png;base64,{encoded}'>
1197
- </body>
1198
- </html>"""
1199
-
1200
- with open(path, "w") as f:
1201
- f.write(html)
1202
- remove(tmpfile.name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b7ac2e8ca2073a71cd5af5727c14f21885969214d758931699fa97c7846dd7e/blob DELETED
Binary file (178 Bytes)
 
shared/package-files/9b/9b7c8bd1d4c05d73ca75e619a0bf9958598fd50abe57a63d5f11bb10c43ba2f1/blob DELETED
@@ -1,329 +0,0 @@
1
- from torch.fx.passes.utils.fuser_utils import fuse_by_partitions
2
- import collections
3
- import itertools
4
- import logging
5
-
6
- from copy import copy
7
- from typing import Dict, Iterable, List, Optional, Sequence, Set
8
-
9
- from torch.fx.graph_module import GraphModule
10
- from torch.fx.node import Node, _get_qualified_name
11
- from torch.fx.passes.operator_support import OperatorSupportBase
12
-
13
-
14
- logger = logging.getLogger(__name__)
15
- logger.setLevel(logging.WARNING)
16
-
17
- class Partition:
18
- def __init__(self, id: Optional[int] = None, nodes: Optional[Iterable[Node]] = None):
19
- self.id = id
20
- self.nodes: Set[Node] = set(nodes) if nodes is not None else set()
21
-
22
- def __repr__(self) -> str:
23
- return str(self.nodes)
24
-
25
- def add_node(self, node: Node):
26
- self.nodes.add(node)
27
-
28
- def remove_node(self, node: Node):
29
- self.nodes.remove(node)
30
-
31
- def size(self):
32
- return len(self.nodes)
33
-
34
- class _DependencyViewer:
35
- def __init__(self, graph_module: GraphModule):
36
- self.upstreams = collections.defaultdict(set)
37
- self.downstreams = collections.defaultdict(set)
38
-
39
- for node in graph_module.graph.nodes:
40
- for input_node in node.all_input_nodes:
41
- # add input_node and input_node's upstream dependency
42
- self.upstreams[node].add(input_node)
43
- self.upstreams[node].update(self.upstreams[input_node])
44
-
45
- for node in reversed(graph_module.graph.nodes):
46
- for output_node in node.users:
47
- # add output_node and output_node's downstream dependency
48
- self.downstreams[node].add(output_node)
49
- self.downstreams[node].update(self.downstreams[output_node])
50
-
51
- def downstreams_of(self, node: Node) -> Set[Node]:
52
- return self.downstreams[node]
53
-
54
- def upstreams_of(self, node: Node) -> Set[Node]:
55
- return self.upstreams[node]
56
-
57
- class CapabilityBasedPartitioner:
58
-
59
- def __init__(self,
60
- graph_module: GraphModule,
61
- operator_support: OperatorSupportBase,
62
- allows_single_node_partition: bool = False,
63
- non_compute_ops: Optional[Sequence[str]] = None,
64
- allowed_single_node_partition_ops: Optional[Sequence[str]] = None,
65
- ) -> None:
66
- self.graph_module = graph_module
67
- self.operator_support = operator_support
68
- self.allows_single_node_partition = allows_single_node_partition
69
- self.non_compute_ops = non_compute_ops if non_compute_ops is not None else []
70
- self.allowed_single_node_partition_ops = (
71
- allowed_single_node_partition_ops
72
- if allowed_single_node_partition_ops is not None
73
- else []
74
- )
75
- self.dependency_viewer = _DependencyViewer(graph_module)
76
-
77
- def __is_node_supported(self, node: Node) -> bool:
78
- return (
79
- self.operator_support.is_node_supported(dict(self.graph_module.named_modules()), node)
80
- )
81
-
82
- def propose_partitions(self) -> List[Partition]:
83
- # partition_map is a mapping from partition id to a set of partition id's.
84
- # The value set contains all the partition ids that can be reached by doing a
85
- # DFS starting from the partition id in the key.
86
- partition_map : Dict[int, Set] = collections.defaultdict(set)
87
-
88
- # assumptions: nodes in candidate list is sorted in topological order
89
- assignment: Dict[Node, int] = {} # mapping from node to partition_id
90
- partitions_by_id: Dict[int, Partition] = {} # mapping from partition_id to partition
91
- new_partition_id = itertools.count()
92
-
93
- # try to merge partition other_id into partition self_id
94
- # merge only happens if the end graph doesn't contain cyclic dependency
95
- # returns `True` when merge happens, `False` otherwise.
96
- def maybe_merge_partition(self_id: int, other_id: int):
97
- # merged_nodes is the union of nodes in two partition to-be-merged
98
- merged_nodes = copy(partitions_by_id[self_id].nodes)
99
- merged_nodes.update(partitions_by_id[other_id].nodes)
100
-
101
- def dfs_iter_find_cycle(all_user_nodes: List[Node]):
102
- for user_node in all_user_nodes:
103
- visited_partition_ids = set()
104
-
105
- for path_node in self.dependency_viewer.downstreams_of(user_node):
106
- # If any of the nodes in the dfs path of this node are in the merged_nodes
107
- # list then there is a cycle in the graph.
108
- if path_node in merged_nodes:
109
- return True
110
-
111
- # If any of the nodes in the dfs path of this node are in the assignment
112
- # map then we have to make sure that the partitions that these nodes belong
113
- # to do not form a cycle with the current partitions being merged. This means
114
- # iterating through all the nodes in all the parititons that are traversed in
115
- # the dfs path and checking if they are in the merged_nodes list.
116
- if path_node in assignment:
117
- partition_id = assignment[path_node]
118
- # If the partition id has already been visited then we know that it doesn't
119
- # form a cycle with the current partitions being merged.
120
- if partition_id in visited_partition_ids:
121
- continue
122
- p_map = partition_map[partition_id]
123
- if self_id in p_map or other_id in p_map:
124
- return True
125
-
126
- visited_partition_ids.add(partition_id)
127
-
128
- return False
129
-
130
- # check if merge would create cyclic dependency.
131
- all_user_nodes = []
132
- for node in merged_nodes:
133
- for user_node in node.users:
134
- if user_node not in merged_nodes:
135
- all_user_nodes.append(user_node)
136
-
137
- if dfs_iter_find_cycle(all_user_nodes):
138
- # return false indicating cyclic dependency found and
139
- # merge is aborted
140
- return False
141
-
142
- # no cyclic dependency found, move forward with the merge
143
- # updating partition nodes
144
- partitions_by_id[self_id].nodes = merged_nodes
145
- # updating assignment map
146
- for node in partitions_by_id[other_id].nodes:
147
- assignment[node] = self_id
148
- # delete other partition
149
- del partitions_by_id[other_id]
150
-
151
- partition_map[self_id] = partition_map[self_id].union(partition_map[other_id])
152
- del partition_map[other_id]
153
-
154
- return True
155
-
156
- def merge_single_node(node: Node, id: Optional[int]):
157
- def _update_partition_map(node: Node, id: int):
158
- # Iterate through all the downstream nodes of this node and update the partition map
159
- # to indicate that there is a path from the partition id of this node to the target
160
- # partition id.
161
- downstream_nodes = self.dependency_viewer.downstreams_of(node)
162
- for curr_node in downstream_nodes:
163
- target_id = assignment.get(curr_node, None)
164
- if target_id is not None:
165
- partition_map[id].add(target_id)
166
-
167
- # Iterate through all the upstream nodes of this node and update the partition map
168
- # to indicate that there is a path from the partition id of the upstream node to the
169
- # current node's partition id.
170
- upstream_nodes = self.dependency_viewer.upstreams_of(node)
171
- for curr_node in upstream_nodes:
172
- source_id = assignment.get(curr_node, None)
173
- if source_id is not None:
174
- partition_map[source_id].add(id)
175
-
176
- if node in assignment:
177
- partitions_by_id[assignment[node]].remove_node(node)
178
-
179
- if id is None:
180
- assignment.pop(node)
181
- elif id not in partitions_by_id:
182
- assignment[node] = id
183
- partitions_by_id[id] = Partition(id=id, nodes=[node])
184
- _update_partition_map(node, id)
185
- else:
186
- assignment[node] = id
187
- partitions_by_id[id].add_node(node)
188
- _update_partition_map(node, id)
189
-
190
- logger.debug("Proposing partitions...")
191
-
192
- for node in reversed(self.graph_module.graph.nodes):
193
- # use Dict as an ordered set to ensure deterministic partitioning result, don't care value
194
- merge_candidates: Dict[int, None] = {}
195
-
196
- # Note a limited horizontal fusion is enabled:
197
- # when `node` is not supported, the code below attempts to fuse consumer of `node`.
198
- #
199
- # I don't see a need to add a knob to disable horizontal fusion yet, we can short-cut
200
- # the fusion by adding an `else` block here to skip horizontal fusion.
201
- if self.__is_node_supported(node) and node not in assignment:
202
- partition_id = next(new_partition_id)
203
- merge_single_node(node, partition_id)
204
- merge_candidates[partition_id] = None
205
-
206
- # merge all possible partitions
207
- for node in assignment:
208
- merge_candidates[assignment[node]] = None
209
-
210
- merge_candidates_list = list(merge_candidates.keys())
211
- if len(merge_candidates_list) > 1:
212
- self_id = merge_candidates_list[0]
213
- for other_id in merge_candidates_list[1:]:
214
- # note: merge partition `other_id` into partition `self_id` if
215
- # it doesn't create cyclic dependency in the graph, otherwise,
216
- # this is a no-op
217
- maybe_merge_partition(self_id, other_id)
218
-
219
- # post processing to re-assign "getitem" nodes into upstream partition
220
- logger.debug("Reassigning getitem nodes to its producer node's partition...")
221
- nodes_reassignment: Dict[Node, int] = {}
222
- for node in self.graph_module.graph.nodes:
223
- is_tuple_output = True
224
- for user in node.users:
225
- if user.op != "call_function" or \
226
- _get_qualified_name(user.target) != "_operator.getitem": # type: ignore[arg-type]
227
- is_tuple_output = False
228
- break
229
-
230
- # node has tuple outputs, re-assign all following getitem node into node's partition
231
- if is_tuple_output:
232
- id = assignment.get(node, None) # type: ignore[arg-type]
233
- for user in node.users:
234
- if assignment.get(user, None) != id: # type: ignore[arg-type]
235
- nodes_reassignment[user] = id # type: ignore[assignment]
236
- for node, id in nodes_reassignment.items():
237
- merge_single_node(node, id)
238
-
239
- # filter out single node partitions
240
- if not self.allows_single_node_partition:
241
- logger.debug("Filtering out single node partitions...")
242
- default_non_compute_ops = {"torch.ops.aten.view", "_operator.getitem"}
243
- non_compute_ops = default_non_compute_ops.union(set(self.non_compute_ops))
244
- partitions_to_remove: List[int] = []
245
- for id, partition in partitions_by_id.items():
246
- compute_node_count = 0
247
- for node in partition.nodes:
248
- if node.op == "call_function":
249
- assert callable(node.target)
250
- if _get_qualified_name(node.target) not in non_compute_ops:
251
- compute_node_count += 1
252
- if _get_qualified_name(node.target) in self.allowed_single_node_partition_ops:
253
- compute_node_count += 1
254
- if compute_node_count <= 1:
255
- partitions_to_remove.append(id)
256
- for id in partitions_to_remove:
257
- del partitions_by_id[id]
258
-
259
- logger.debug("Partitions proposed:")
260
- for id, partition in partitions_by_id.items():
261
- logger.debug("partition #%s: %s", id, [node.name for node in partition.nodes])
262
-
263
- return list(partitions_by_id.values())
264
-
265
- def fuse_partitions(self, partitions: List[Partition]) -> GraphModule:
266
- logger.debug("Fusing partitions...")
267
- # fuse_by_partitions expects partitions in List[List[Node]]: [ [node0, node1], [node2, node3] ]
268
- return fuse_by_partitions(self.graph_module, [list(partition.nodes) for partition in partitions])
269
-
270
- # remove non-compute-ops that sits at the boundary of a partition.
271
- def remove_bookend_non_compute_ops(self, partitions: List[Partition]):
272
- non_compute_ops = set(self.non_compute_ops)
273
-
274
- def is_non_compute_node(node: Node):
275
- return node.op == "call_function" and \
276
- _get_qualified_name(node.target) in non_compute_ops # type: ignore[arg-type]
277
-
278
- # cache transparent nodes
279
- transparent_input_nodes: Dict[Node, bool] = {}
280
- transparent_output_nodes: Dict[Node, bool] = {}
281
-
282
- def is_transparent_input_node(node: Node, partition: Set[Node], removed_nodes: Set[Node]):
283
- if node.op == "placeholder" or (node not in partition) or (node in removed_nodes):
284
- return True
285
- if node in transparent_input_nodes:
286
- return transparent_input_nodes[node]
287
- if is_non_compute_node(node):
288
- for input_n in node.all_input_nodes:
289
- if not is_transparent_input_node(input_n, partition, removed_nodes):
290
- transparent_input_nodes[node] = False
291
- return False
292
- transparent_input_nodes[node] = True
293
- return True
294
- transparent_input_nodes[node] = False
295
- return False
296
-
297
- def is_transparent_output_node(node: Node, partition: Set[Node], removed_nodes: Set[Node]):
298
- if node.op == "placeholder" or (node not in partition) or (node in removed_nodes):
299
- return True
300
- if node in transparent_output_nodes:
301
- return transparent_output_nodes[node]
302
- if is_non_compute_node(node):
303
- for output_n in node.users:
304
- if not is_transparent_output_node(output_n, partition, removed_nodes):
305
- transparent_output_nodes[node] = False
306
- return False
307
- transparent_output_nodes[node] = True
308
- return True
309
- transparent_output_nodes[node] = False
310
- return False
311
-
312
- for partition in partitions:
313
- # Note it's ok to use `set` here, since we are only query if a node
314
- # has been removed. We are NEVER going to iterate on nodes inside
315
- # the set.
316
- remove_node: Set[Node] = set()
317
- for node in partition.nodes:
318
- if is_non_compute_node(node) and \
319
- (is_transparent_input_node(node, partition.nodes, remove_node) or
320
- is_transparent_output_node(node, partition.nodes, remove_node)):
321
- remove_node.add(node)
322
-
323
- if len(remove_node) != 0:
324
- partition.nodes = partition.nodes - remove_node
325
-
326
- def partition_and_fuse(self) -> GraphModule:
327
- partitions = self.propose_partitions()
328
- fused_gm = self.fuse_partitions(partitions)
329
- return fused_gm
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b7d4f55a4e2fdb02c430068fdffabc732addce238da3f1df2690249c3353274/blob DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2019-09/schema",
3
- "$id": "https://json-schema.org/draft/2019-09/meta/content",
4
- "$vocabulary": {
5
- "https://json-schema.org/draft/2019-09/vocab/content": true
6
- },
7
- "$recursiveAnchor": true,
8
-
9
- "title": "Content vocabulary meta-schema",
10
-
11
- "type": ["object", "boolean"],
12
- "properties": {
13
- "contentMediaType": { "type": "string" },
14
- "contentEncoding": { "type": "string" },
15
- "contentSchema": { "$recursiveRef": "#" }
16
- }
17
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b7d69d168dc15419c91b2621e70a949a2101aabfe2eae6788862475ddf760ca/blob DELETED
@@ -1,234 +0,0 @@
1
- """
2
- Array methods which are called by both the C-code for the method
3
- and the Python code for the NumPy-namespace function
4
-
5
- """
6
- import warnings
7
- from contextlib import nullcontext
8
-
9
- from numpy.core import multiarray as mu
10
- from numpy.core import umath as um
11
- from numpy.core.multiarray import asanyarray
12
- from numpy.core import numerictypes as nt
13
- from numpy.core import _exceptions
14
- from numpy.core._ufunc_config import _no_nep50_warning
15
- from numpy._globals import _NoValue
16
- from numpy.compat import pickle, os_fspath
17
-
18
- # save those O(100) nanoseconds!
19
- umr_maximum = um.maximum.reduce
20
- umr_minimum = um.minimum.reduce
21
- umr_sum = um.add.reduce
22
- umr_prod = um.multiply.reduce
23
- umr_any = um.logical_or.reduce
24
- umr_all = um.logical_and.reduce
25
-
26
- # Complex types to -> (2,)float view for fast-path computation in _var()
27
- _complex_to_float = {
28
- nt.dtype(nt.csingle) : nt.dtype(nt.single),
29
- nt.dtype(nt.cdouble) : nt.dtype(nt.double),
30
- }
31
- # Special case for windows: ensure double takes precedence
32
- if nt.dtype(nt.longdouble) != nt.dtype(nt.double):
33
- _complex_to_float.update({
34
- nt.dtype(nt.clongdouble) : nt.dtype(nt.longdouble),
35
- })
36
-
37
- # avoid keyword arguments to speed up parsing, saves about 15%-20% for very
38
- # small reductions
39
- def _amax(a, axis=None, out=None, keepdims=False,
40
- initial=_NoValue, where=True):
41
- return umr_maximum(a, axis, None, out, keepdims, initial, where)
42
-
43
- def _amin(a, axis=None, out=None, keepdims=False,
44
- initial=_NoValue, where=True):
45
- return umr_minimum(a, axis, None, out, keepdims, initial, where)
46
-
47
- def _sum(a, axis=None, dtype=None, out=None, keepdims=False,
48
- initial=_NoValue, where=True):
49
- return umr_sum(a, axis, dtype, out, keepdims, initial, where)
50
-
51
- def _prod(a, axis=None, dtype=None, out=None, keepdims=False,
52
- initial=_NoValue, where=True):
53
- return umr_prod(a, axis, dtype, out, keepdims, initial, where)
54
-
55
- def _any(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
56
- # Parsing keyword arguments is currently fairly slow, so avoid it for now
57
- if where is True:
58
- return umr_any(a, axis, dtype, out, keepdims)
59
- return umr_any(a, axis, dtype, out, keepdims, where=where)
60
-
61
- def _all(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
62
- # Parsing keyword arguments is currently fairly slow, so avoid it for now
63
- if where is True:
64
- return umr_all(a, axis, dtype, out, keepdims)
65
- return umr_all(a, axis, dtype, out, keepdims, where=where)
66
-
67
- def _count_reduce_items(arr, axis, keepdims=False, where=True):
68
- # fast-path for the default case
69
- if where is True:
70
- # no boolean mask given, calculate items according to axis
71
- if axis is None:
72
- axis = tuple(range(arr.ndim))
73
- elif not isinstance(axis, tuple):
74
- axis = (axis,)
75
- items = 1
76
- for ax in axis:
77
- items *= arr.shape[mu.normalize_axis_index(ax, arr.ndim)]
78
- items = nt.intp(items)
79
- else:
80
- # TODO: Optimize case when `where` is broadcast along a non-reduction
81
- # axis and full sum is more excessive than needed.
82
-
83
- # guarded to protect circular imports
84
- from numpy.lib.stride_tricks import broadcast_to
85
- # count True values in (potentially broadcasted) boolean mask
86
- items = umr_sum(broadcast_to(where, arr.shape), axis, nt.intp, None,
87
- keepdims)
88
- return items
89
-
90
- def _clip(a, min=None, max=None, out=None, **kwargs):
91
- if min is None and max is None:
92
- raise ValueError("One of max or min must be given")
93
-
94
- if min is None:
95
- return um.minimum(a, max, out=out, **kwargs)
96
- elif max is None:
97
- return um.maximum(a, min, out=out, **kwargs)
98
- else:
99
- return um.clip(a, min, max, out=out, **kwargs)
100
-
101
- def _mean(a, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
102
- arr = asanyarray(a)
103
-
104
- is_float16_result = False
105
-
106
- rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
107
- if rcount == 0 if where is True else umr_any(rcount == 0, axis=None):
108
- warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)
109
-
110
- # Cast bool, unsigned int, and int to float64 by default
111
- if dtype is None:
112
- if issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
113
- dtype = mu.dtype('f8')
114
- elif issubclass(arr.dtype.type, nt.float16):
115
- dtype = mu.dtype('f4')
116
- is_float16_result = True
117
-
118
- ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
119
- if isinstance(ret, mu.ndarray):
120
- with _no_nep50_warning():
121
- ret = um.true_divide(
122
- ret, rcount, out=ret, casting='unsafe', subok=False)
123
- if is_float16_result and out is None:
124
- ret = arr.dtype.type(ret)
125
- elif hasattr(ret, 'dtype'):
126
- if is_float16_result:
127
- ret = arr.dtype.type(ret / rcount)
128
- else:
129
- ret = ret.dtype.type(ret / rcount)
130
- else:
131
- ret = ret / rcount
132
-
133
- return ret
134
-
135
- def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
136
- where=True):
137
- arr = asanyarray(a)
138
-
139
- rcount = _count_reduce_items(arr, axis, keepdims=keepdims, where=where)
140
- # Make this warning show up on top.
141
- if ddof >= rcount if where is True else umr_any(ddof >= rcount, axis=None):
142
- warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
143
- stacklevel=2)
144
-
145
- # Cast bool, unsigned int, and int to float64 by default
146
- if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
147
- dtype = mu.dtype('f8')
148
-
149
- # Compute the mean.
150
- # Note that if dtype is not of inexact type then arraymean will
151
- # not be either.
152
- arrmean = umr_sum(arr, axis, dtype, keepdims=True, where=where)
153
- # The shape of rcount has to match arrmean to not change the shape of out
154
- # in broadcasting. Otherwise, it cannot be stored back to arrmean.
155
- if rcount.ndim == 0:
156
- # fast-path for default case when where is True
157
- div = rcount
158
- else:
159
- # matching rcount to arrmean when where is specified as array
160
- div = rcount.reshape(arrmean.shape)
161
- if isinstance(arrmean, mu.ndarray):
162
- with _no_nep50_warning():
163
- arrmean = um.true_divide(arrmean, div, out=arrmean,
164
- casting='unsafe', subok=False)
165
- elif hasattr(arrmean, "dtype"):
166
- arrmean = arrmean.dtype.type(arrmean / rcount)
167
- else:
168
- arrmean = arrmean / rcount
169
-
170
- # Compute sum of squared deviations from mean
171
- # Note that x may not be inexact and that we need it to be an array,
172
- # not a scalar.
173
- x = asanyarray(arr - arrmean)
174
-
175
- if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
176
- x = um.multiply(x, x, out=x)
177
- # Fast-paths for built-in complex types
178
- elif x.dtype in _complex_to_float:
179
- xv = x.view(dtype=(_complex_to_float[x.dtype], (2,)))
180
- um.multiply(xv, xv, out=xv)
181
- x = um.add(xv[..., 0], xv[..., 1], out=x.real).real
182
- # Most general case; includes handling object arrays containing imaginary
183
- # numbers and complex types with non-native byteorder
184
- else:
185
- x = um.multiply(x, um.conjugate(x), out=x).real
186
-
187
- ret = umr_sum(x, axis, dtype, out, keepdims=keepdims, where=where)
188
-
189
- # Compute degrees of freedom and make sure it is not negative.
190
- rcount = um.maximum(rcount - ddof, 0)
191
-
192
- # divide by degrees of freedom
193
- if isinstance(ret, mu.ndarray):
194
- with _no_nep50_warning():
195
- ret = um.true_divide(
196
- ret, rcount, out=ret, casting='unsafe', subok=False)
197
- elif hasattr(ret, 'dtype'):
198
- ret = ret.dtype.type(ret / rcount)
199
- else:
200
- ret = ret / rcount
201
-
202
- return ret
203
-
204
- def _std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *,
205
- where=True):
206
- ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
207
- keepdims=keepdims, where=where)
208
-
209
- if isinstance(ret, mu.ndarray):
210
- ret = um.sqrt(ret, out=ret)
211
- elif hasattr(ret, 'dtype'):
212
- ret = ret.dtype.type(um.sqrt(ret))
213
- else:
214
- ret = um.sqrt(ret)
215
-
216
- return ret
217
-
218
- def _ptp(a, axis=None, out=None, keepdims=False):
219
- return um.subtract(
220
- umr_maximum(a, axis, None, out, keepdims),
221
- umr_minimum(a, axis, None, None, keepdims),
222
- out
223
- )
224
-
225
- def _dump(self, file, protocol=2):
226
- if hasattr(file, 'write'):
227
- ctx = nullcontext(file)
228
- else:
229
- ctx = open(os_fspath(file), "wb")
230
- with ctx as f:
231
- pickle.dump(self, f, protocol=protocol)
232
-
233
- def _dumps(self, protocol=2):
234
- return pickle.dumps(self, protocol=protocol)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b7e40ee33b9e3130d800e30e44767d62fd21db5d6065a504d12cc47c1a06d91/blob DELETED
@@ -1,109 +0,0 @@
1
- """Numerical Methods for Holonomic Functions"""
2
-
3
- from sympy.core.sympify import sympify
4
- from sympy.holonomic.holonomic import DMFsubs
5
-
6
- from mpmath import mp
7
-
8
-
9
- def _evalf(func, points, derivatives=False, method='RK4'):
10
- """
11
- Numerical methods for numerical integration along a given set of
12
- points in the complex plane.
13
- """
14
-
15
- ann = func.annihilator
16
- a = ann.order
17
- R = ann.parent.base
18
- K = R.get_field()
19
-
20
- if method == 'Euler':
21
- meth = _euler
22
- else:
23
- meth = _rk4
24
-
25
- dmf = []
26
- for j in ann.listofpoly:
27
- dmf.append(K.new(j.rep))
28
-
29
- red = [-dmf[i] / dmf[a] for i in range(a)]
30
-
31
- y0 = func.y0
32
- if len(y0) < a:
33
- raise TypeError("Not Enough Initial Conditions")
34
- x0 = func.x0
35
- sol = [meth(red, x0, points[0], y0, a)]
36
-
37
- for i, j in enumerate(points[1:]):
38
- sol.append(meth(red, points[i], j, sol[-1], a))
39
-
40
- if not derivatives:
41
- return [sympify(i[0]) for i in sol]
42
- else:
43
- return sympify(sol)
44
-
45
-
46
- def _euler(red, x0, x1, y0, a):
47
- """
48
- Euler's method for numerical integration.
49
- From x0 to x1 with initial values given at x0 as vector y0.
50
- """
51
-
52
- A = sympify(x0)._to_mpmath(mp.prec)
53
- B = sympify(x1)._to_mpmath(mp.prec)
54
- y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
55
- h = B - A
56
- f_0 = y_0[1:]
57
- f_0_n = 0
58
-
59
- for i in range(a):
60
- f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
61
- f_0.append(f_0_n)
62
-
63
- sol = []
64
- for i in range(a):
65
- sol.append(y_0[i] + h * f_0[i])
66
-
67
- return sol
68
-
69
-
70
- def _rk4(red, x0, x1, y0, a):
71
- """
72
- Runge-Kutta 4th order numerical method.
73
- """
74
-
75
- A = sympify(x0)._to_mpmath(mp.prec)
76
- B = sympify(x1)._to_mpmath(mp.prec)
77
- y_0 = [sympify(i)._to_mpmath(mp.prec) for i in y0]
78
- h = B - A
79
-
80
- f_0_n = 0
81
- f_1_n = 0
82
- f_2_n = 0
83
- f_3_n = 0
84
-
85
- f_0 = y_0[1:]
86
- for i in range(a):
87
- f_0_n += sympify(DMFsubs(red[i], A, mpm=True))._to_mpmath(mp.prec) * y_0[i]
88
- f_0.append(f_0_n)
89
-
90
- f_1 = [y_0[i] + f_0[i]*h/2 for i in range(1, a)]
91
- for i in range(a):
92
- f_1_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_0[i]*h/2)
93
- f_1.append(f_1_n)
94
-
95
- f_2 = [y_0[i] + f_1[i]*h/2 for i in range(1, a)]
96
- for i in range(a):
97
- f_2_n += sympify(DMFsubs(red[i], A + h/2, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_1[i]*h/2)
98
- f_2.append(f_2_n)
99
-
100
- f_3 = [y_0[i] + f_2[i]*h for i in range(1, a)]
101
- for i in range(a):
102
- f_3_n += sympify(DMFsubs(red[i], A + h, mpm=True))._to_mpmath(mp.prec) * (y_0[i] + f_2[i]*h)
103
- f_3.append(f_3_n)
104
-
105
- sol = []
106
- for i in range(a):
107
- sol.append(y_0[i] + h * (f_0[i]+2*f_1[i]+2*f_2[i]+f_3[i])/6)
108
-
109
- return sol
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b8280d86ff5b59acd6ff6f3f7773279ffddb6a6f7f90befc8516f754879e456/blob DELETED
The diff for this file is too large to render. See raw diff
 
shared/package-files/9b/9b8648ab7c6ea7dec4c0aab3db5e6fd033f3925eb80c627c7248893b35a43c78/blob DELETED
@@ -1,17 +0,0 @@
1
- from typing import Dict, Tuple
2
-
3
- from django.db.backends.base.base import BaseDatabaseWrapper
4
-
5
- def psycopg2_version() -> Tuple[int, ...]: ...
6
-
7
- PSYCOPG2_VERSION: Tuple[int, ...] = ...
8
-
9
- class DatabaseWrapper(BaseDatabaseWrapper):
10
- operators: Dict[str, str] = ...
11
- pattern_esc: str = ...
12
- pattern_ops: Dict[str, str] = ...
13
-
14
- # PostgreSQL backend-specific attributes.
15
- _named_cursor_idx: int = ...
16
- @property
17
- def pg_version(self) -> str: ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b86cb0749eb28f07811ecd87954712f8bacda87a621d2d31e209acfbab4be1a/blob DELETED
@@ -1,27 +0,0 @@
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_fractional_max_pool2d_backward : public at::impl::MetaBase {
21
-
22
-
23
- void meta(const at::Tensor & grad_output, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef output_size, const at::Tensor & indices);
24
- };
25
-
26
- } // namespace native
27
- } // namespace at
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b8b84fe0598495357e29ad58df7c0c4bd126e2514fec2e861a167606009660b/blob DELETED
@@ -1,39 +0,0 @@
1
- #pragma once
2
-
3
- // @generated by torchgen/gen.py from Function.h
4
-
5
- #include <ATen/Context.h>
6
- #include <ATen/DeviceGuard.h>
7
- #include <ATen/TensorUtils.h>
8
- #include <ATen/TracerMode.h>
9
- #include <ATen/core/Generator.h>
10
- #include <ATen/core/Reduction.h>
11
- #include <ATen/core/Tensor.h>
12
- #include <c10/core/Scalar.h>
13
- #include <c10/core/Storage.h>
14
- #include <c10/core/TensorOptions.h>
15
- #include <c10/util/Deprecated.h>
16
- #include <c10/util/Optional.h>
17
-
18
-
19
-
20
- #include <ATen/ops/_cdist_forward_ops.h>
21
-
22
- namespace at {
23
-
24
-
25
- // aten::_cdist_forward(Tensor x1, Tensor x2, float p, int? compute_mode) -> Tensor
26
- inline at::Tensor _cdist_forward(const at::Tensor & x1, const at::Tensor & x2, double p, c10::optional<int64_t> compute_mode) {
27
- return at::_ops::_cdist_forward::call(x1, x2, p, compute_mode);
28
- }
29
-
30
- // aten::_cdist_forward.out(Tensor x1, Tensor x2, float p, int? compute_mode, *, Tensor(a!) out) -> Tensor(a!)
31
- inline at::Tensor & _cdist_forward_out(at::Tensor & out, const at::Tensor & x1, const at::Tensor & x2, double p, c10::optional<int64_t> compute_mode) {
32
- return at::_ops::_cdist_forward_out::call(x1, x2, p, compute_mode, out);
33
- }
34
- // aten::_cdist_forward.out(Tensor x1, Tensor x2, float p, int? compute_mode, *, Tensor(a!) out) -> Tensor(a!)
35
- inline at::Tensor & _cdist_forward_outf(const at::Tensor & x1, const at::Tensor & x2, double p, c10::optional<int64_t> compute_mode, at::Tensor & out) {
36
- return at::_ops::_cdist_forward_out::call(x1, x2, p, compute_mode, out);
37
- }
38
-
39
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b8c6edddc57710cdff7af9638a24f14d9b0d0611517b243e7294c45c79f760d/blob DELETED
@@ -1,288 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from typing import TYPE_CHECKING, Any
4
-
5
- from narwhals._compliant.any_namespace import DateTimeNamespace
6
- from narwhals._constants import (
7
- MS_PER_SECOND,
8
- NS_PER_SECOND,
9
- SECONDS_PER_DAY,
10
- US_PER_SECOND,
11
- )
12
- from narwhals._duration import Interval
13
- from narwhals._pandas_like.utils import (
14
- ALIAS_DICT,
15
- UNITS_DICT,
16
- PandasLikeSeriesNamespace,
17
- calculate_timestamp_date,
18
- calculate_timestamp_datetime,
19
- get_dtype_backend,
20
- int_dtype_mapper,
21
- is_dtype_pyarrow,
22
- )
23
-
24
- if TYPE_CHECKING:
25
- from datetime import timedelta
26
-
27
- import pandas as pd
28
-
29
- from narwhals._pandas_like.series import PandasLikeSeries
30
- from narwhals.typing import TimeUnit
31
-
32
-
33
- class PandasLikeSeriesDateTimeNamespace(
34
- PandasLikeSeriesNamespace, DateTimeNamespace["PandasLikeSeries"]
35
- ):
36
- def date(self) -> PandasLikeSeries:
37
- result = self.with_native(self.native.dt.date)
38
- if str(result.dtype).lower() == "object":
39
- msg = (
40
- "Accessing `date` on the default pandas backend "
41
- "will return a Series of type `object`."
42
- "\nThis differs from polars API and will prevent `.dt` chaining. "
43
- "Please switch to the `pyarrow` backend:"
44
- '\ndf.convert_dtypes(dtype_backend="pyarrow")'
45
- )
46
- raise NotImplementedError(msg)
47
- return result
48
-
49
- def year(self) -> PandasLikeSeries:
50
- return self.with_native(self.native.dt.year)
51
-
52
- def month(self) -> PandasLikeSeries:
53
- return self.with_native(self.native.dt.month)
54
-
55
- def day(self) -> PandasLikeSeries:
56
- return self.with_native(self.native.dt.day)
57
-
58
- def hour(self) -> PandasLikeSeries:
59
- return self.with_native(self.native.dt.hour)
60
-
61
- def minute(self) -> PandasLikeSeries:
62
- return self.with_native(self.native.dt.minute)
63
-
64
- def second(self) -> PandasLikeSeries:
65
- return self.with_native(self.native.dt.second)
66
-
67
- def millisecond(self) -> PandasLikeSeries:
68
- return self.microsecond() // 1000
69
-
70
- def microsecond(self) -> PandasLikeSeries:
71
- if self.backend_version < (3, 0, 0) and self._is_pyarrow():
72
- # crazy workaround for https://github.com/pandas-dev/pandas/issues/59154
73
- import pyarrow.compute as pc # ignore-banned-import()
74
-
75
- from narwhals._arrow.utils import lit
76
-
77
- arr_ns = self.native.array
78
- arr = arr_ns.__arrow_array__()
79
- result_arr = pc.add(
80
- pc.multiply(pc.millisecond(arr), lit(1_000)), pc.microsecond(arr)
81
- )
82
- result = type(self.native)(type(arr_ns)(result_arr), name=self.native.name)
83
- return self.with_native(result)
84
-
85
- return self.with_native(self.native.dt.microsecond)
86
-
87
- def nanosecond(self) -> PandasLikeSeries:
88
- return self.microsecond() * 1_000 + self.native.dt.nanosecond
89
-
90
- def ordinal_day(self) -> PandasLikeSeries:
91
- return self.with_native(self.native.dt.day_of_year)
92
-
93
- def weekday(self) -> PandasLikeSeries:
94
- # Pandas is 0-6 while Polars is 1-7
95
- impl = self.compliant._implementation
96
- native = self.native
97
- result = (
98
- native.dt.day_of_week
99
- if impl.is_pandas() and impl._backend_version() >= (1, 5)
100
- else native.dt.weekday
101
- )
102
- return self.with_native(result) + 1
103
-
104
- def _is_pyarrow(self) -> bool:
105
- return is_dtype_pyarrow(self.native.dtype)
106
-
107
- def _get_total_seconds(self) -> Any:
108
- if hasattr(self.native.dt, "total_seconds"):
109
- return self.native.dt.total_seconds()
110
- return ( # pragma: no cover
111
- self.native.dt.days * SECONDS_PER_DAY
112
- + self.native.dt.seconds
113
- + (self.native.dt.microseconds / US_PER_SECOND)
114
- + (self.native.dt.nanoseconds / NS_PER_SECOND)
115
- )
116
-
117
- def total_minutes(self) -> PandasLikeSeries:
118
- s = self._get_total_seconds()
119
- # this calculates the sign of each series element
120
- s_sign = 2 * (s > 0).astype(int_dtype_mapper(s.dtype)) - 1
121
- s_abs = s.abs() // 60
122
- if ~s.isna().any():
123
- s_abs = s_abs.astype(int_dtype_mapper(s.dtype))
124
- return self.with_native(s_abs * s_sign)
125
-
126
- def total_seconds(self) -> PandasLikeSeries:
127
- s = self._get_total_seconds()
128
- # this calculates the sign of each series element
129
- s_sign = 2 * (s > 0).astype(int_dtype_mapper(s.dtype)) - 1
130
- s_abs = s.abs() // 1
131
- if ~s.isna().any():
132
- s_abs = s_abs.astype(int_dtype_mapper(s.dtype))
133
- return self.with_native(s_abs * s_sign)
134
-
135
- def total_milliseconds(self) -> PandasLikeSeries:
136
- s = self._get_total_seconds() * MS_PER_SECOND
137
- # this calculates the sign of each series element
138
- s_sign = 2 * (s > 0).astype(int_dtype_mapper(s.dtype)) - 1
139
- s_abs = s.abs() // 1
140
- if ~s.isna().any():
141
- s_abs = s_abs.astype(int_dtype_mapper(s.dtype))
142
- return self.with_native(s_abs * s_sign)
143
-
144
- def total_microseconds(self) -> PandasLikeSeries:
145
- s = self._get_total_seconds() * US_PER_SECOND
146
- # this calculates the sign of each series element
147
- s_sign = 2 * (s > 0).astype(int_dtype_mapper(s.dtype)) - 1
148
- s_abs = s.abs() // 1
149
- if ~s.isna().any():
150
- s_abs = s_abs.astype(int_dtype_mapper(s.dtype))
151
- return self.with_native(s_abs * s_sign)
152
-
153
- def total_nanoseconds(self) -> PandasLikeSeries:
154
- s = self._get_total_seconds() * NS_PER_SECOND
155
- # this calculates the sign of each series element
156
- s_sign = 2 * (s > 0).astype(int_dtype_mapper(s.dtype)) - 1
157
- s_abs = s.abs() // 1
158
- if ~s.isna().any():
159
- s_abs = s_abs.astype(int_dtype_mapper(s.dtype))
160
- return self.with_native(s_abs * s_sign)
161
-
162
- def to_string(self, format: str) -> PandasLikeSeries:
163
- # Polars' parser treats `'%.f'` as pandas does `'.%f'`
164
- # PyArrow interprets `'%S'` as "seconds, plus fractional seconds"
165
- # and doesn't support `%f`
166
- if not self._is_pyarrow():
167
- format = format.replace("%S%.f", "%S.%f")
168
- else:
169
- format = format.replace("%S.%f", "%S").replace("%S%.f", "%S")
170
- return self.with_native(self.native.dt.strftime(format))
171
-
172
- def replace_time_zone(self, time_zone: str | None) -> PandasLikeSeries:
173
- de_zone = self.native.dt.tz_localize(None)
174
- result = de_zone.dt.tz_localize(time_zone) if time_zone is not None else de_zone
175
- return self.with_native(result)
176
-
177
- def convert_time_zone(self, time_zone: str) -> PandasLikeSeries:
178
- if self.compliant.dtype.time_zone is None: # type: ignore[attr-defined]
179
- result = self.native.dt.tz_localize("UTC").dt.tz_convert(time_zone)
180
- else:
181
- result = self.native.dt.tz_convert(time_zone)
182
- return self.with_native(result)
183
-
184
- def timestamp(self, time_unit: TimeUnit) -> PandasLikeSeries:
185
- s = self.native
186
- dtype = self.compliant.dtype
187
- mask_na = s.isna()
188
- dtypes = self.version.dtypes
189
- if dtype == dtypes.Date:
190
- # Date is only supported in pandas dtypes if pyarrow-backed
191
- s_cast = s.astype("Int32[pyarrow]")
192
- result = calculate_timestamp_date(s_cast, time_unit)
193
- elif isinstance(dtype, dtypes.Datetime):
194
- fn = (
195
- s.view
196
- if (self.implementation.is_pandas() and self.backend_version < (2,))
197
- else s.astype
198
- )
199
- s_cast = fn("Int64[pyarrow]") if self._is_pyarrow() else fn("int64")
200
- result = calculate_timestamp_datetime(s_cast, dtype.time_unit, time_unit)
201
- else:
202
- msg = "Input should be either of Date or Datetime type"
203
- raise TypeError(msg)
204
- result[mask_na] = None
205
- return self.with_native(result)
206
-
207
- def truncate(self, every: str) -> PandasLikeSeries:
208
- interval = Interval.parse(every)
209
- multiple, unit = interval.multiple, interval.unit
210
- native = self.native
211
- if self.implementation.is_cudf():
212
- if multiple != 1:
213
- msg = f"Only multiple `1` is supported for cuDF, got: {multiple}."
214
- raise NotImplementedError(msg)
215
- return self.with_native(self.native.dt.floor(ALIAS_DICT.get(unit, unit)))
216
- dtype_backend = get_dtype_backend(native.dtype, self.compliant._implementation)
217
- if unit in {"mo", "q", "y"}:
218
- if self.implementation.is_cudf():
219
- msg = f"Truncating to {unit} is not supported yet for cuDF."
220
- raise NotImplementedError(msg)
221
- if dtype_backend == "pyarrow":
222
- import pyarrow.compute as pc # ignore-banned-import
223
-
224
- ca = native.array._pa_array
225
- result_arr = pc.floor_temporal(ca, multiple, UNITS_DICT[unit])
226
- else:
227
- if unit == "q":
228
- multiple *= 3
229
- np_unit = "M"
230
- elif unit == "mo":
231
- np_unit = "M"
232
- else:
233
- np_unit = "Y"
234
- arr = native.values # noqa: PD011
235
- arr_dtype = arr.dtype
236
- result_arr = arr.astype(f"datetime64[{multiple}{np_unit}]").astype(
237
- arr_dtype
238
- )
239
- result_native = type(native)(
240
- result_arr, dtype=native.dtype, index=native.index, name=native.name
241
- )
242
- return self.with_native(result_native)
243
- return self.with_native(
244
- self.native.dt.floor(f"{multiple}{ALIAS_DICT.get(unit, unit)}")
245
- )
246
-
247
- def offset_by(self, by: str) -> PandasLikeSeries:
248
- native = self.native
249
- pdx = self.compliant.__native_namespace__()
250
- if self._is_pyarrow():
251
- import pyarrow as pa # ignore-banned-import
252
-
253
- compliant = self.compliant
254
- ca = pa.chunked_array([compliant.to_arrow()])
255
- result = (
256
- compliant._version.namespace.from_backend("pyarrow")
257
- .compliant.from_native(ca)
258
- .dt.offset_by(by)
259
- .native
260
- )
261
- result_pd = native.__class__(
262
- result, dtype=native.dtype, index=native.index, name=native.name
263
- )
264
- else:
265
- interval = Interval.parse_no_constraints(by)
266
- multiple, unit = interval.multiple, interval.unit
267
- if unit == "q":
268
- multiple *= 3
269
- unit = "mo"
270
- offset: pd.DateOffset | timedelta
271
- if unit == "y":
272
- offset = pdx.DateOffset(years=multiple)
273
- elif unit == "mo":
274
- offset = pdx.DateOffset(months=multiple)
275
- elif unit == "ns":
276
- offset = pdx.Timedelta(multiple, unit=UNITS_DICT[unit])
277
- else:
278
- offset = interval.to_timedelta()
279
- dtype = self.compliant.dtype
280
- datetime_dtype = self.version.dtypes.Datetime
281
- if unit == "d" and isinstance(dtype, datetime_dtype) and dtype.time_zone:
282
- native_without_timezone = native.dt.tz_localize(None)
283
- result_pd = native_without_timezone + offset
284
- result_pd = result_pd.dt.tz_localize(dtype.time_zone)
285
- else:
286
- result_pd = native + offset
287
-
288
- return self.with_native(result_pd)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b8d9aaa3bcbfbf84b3f67da398e1ab16ea4ed4cbe2f859f853e6fcaac7ddb6a/blob DELETED
The diff for this file is too large to render. See raw diff
 
shared/package-files/9b/9b9249bfb2c4ed5ba4a7c879d2bf74b027db392003d9b3152154145313597834/blob DELETED
@@ -1,2808 +0,0 @@
1
- #ifndef TZ_H
2
- #define TZ_H
3
-
4
- // The MIT License (MIT)
5
- //
6
- // Copyright (c) 2015, 2016, 2017 Howard Hinnant
7
- // Copyright (c) 2017 Jiangang Zhuang
8
- // Copyright (c) 2017 Aaron Bishop
9
- // Copyright (c) 2017 Tomasz Kamiński
10
- //
11
- // Permission is hereby granted, free of charge, to any person obtaining a copy
12
- // of this software and associated documentation files (the "Software"), to deal
13
- // in the Software without restriction, including without limitation the rights
14
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
- // copies of the Software, and to permit persons to whom the Software is
16
- // furnished to do so, subject to the following conditions:
17
- //
18
- // The above copyright notice and this permission notice shall be included in all
19
- // copies or substantial portions of the Software.
20
- //
21
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
- // SOFTWARE.
28
- //
29
- // Our apologies. When the previous paragraph was written, lowercase had not yet
30
- // been invented (that would involve another several millennia of evolution).
31
- // We did not mean to shout.
32
-
33
- // Get more recent database at http://www.iana.org/time-zones
34
-
35
- // The notion of "current timezone" is something the operating system is expected to "just
36
- // know". How it knows this is system specific. It's often a value set by the user at OS
37
- // installation time and recorded by the OS somewhere. On Linux and Mac systems the current
38
- // timezone name is obtained by looking at the name or contents of a particular file on
39
- // disk. On Windows the current timezone name comes from the registry. In either method,
40
- // there is no guarantee that the "native" current timezone name obtained will match any
41
- // of the "Standard" names in this library's "database". On Linux, the names usually do
42
- // seem to match so mapping functions to map from native to "Standard" are typically not
43
- // required. On Windows, the names are never "Standard" so mapping is always required.
44
- // Technically any OS may use the mapping process but currently only Windows does use it.
45
-
46
- #ifndef USE_OS_TZDB
47
- # define USE_OS_TZDB 0
48
- #endif
49
-
50
- #ifndef HAS_REMOTE_API
51
- # if USE_OS_TZDB == 0
52
- # if defined _WIN32 || defined __ANDROID__
53
- # define HAS_REMOTE_API 0
54
- # else
55
- # define HAS_REMOTE_API 1
56
- # endif
57
- # else // HAS_REMOTE_API makes no sense when using the OS timezone database
58
- # define HAS_REMOTE_API 0
59
- # endif
60
- #endif
61
-
62
- #ifdef __clang__
63
- # pragma clang diagnostic push
64
- # pragma clang diagnostic ignored "-Wconstant-logical-operand"
65
- #endif
66
-
67
- static_assert(!(USE_OS_TZDB && HAS_REMOTE_API),
68
- "USE_OS_TZDB and HAS_REMOTE_API can not be used together");
69
-
70
- #ifdef __clang__
71
- # pragma clang diagnostic pop
72
- #endif
73
-
74
- #ifndef AUTO_DOWNLOAD
75
- # define AUTO_DOWNLOAD HAS_REMOTE_API
76
- #endif
77
-
78
- static_assert(HAS_REMOTE_API == 0 ? AUTO_DOWNLOAD == 0 : true,
79
- "AUTO_DOWNLOAD can not be turned on without HAS_REMOTE_API");
80
-
81
- #ifndef USE_SHELL_API
82
- # define USE_SHELL_API 1
83
- #endif
84
-
85
- #if USE_OS_TZDB
86
- # ifdef _WIN32
87
- # error "USE_OS_TZDB can not be used on Windows"
88
- # endif
89
- #endif
90
-
91
- #ifndef HAS_DEDUCTION_GUIDES
92
- # if __cplusplus >= 201703
93
- # define HAS_DEDUCTION_GUIDES 1
94
- # else
95
- # define HAS_DEDUCTION_GUIDES 0
96
- # endif
97
- #endif // HAS_DEDUCTION_GUIDES
98
-
99
- #include "date.h"
100
-
101
- #if defined(_MSC_VER) && (_MSC_VER < 1900)
102
- #include "tz_private.h"
103
- #endif
104
-
105
- #include <algorithm>
106
- #include <atomic>
107
- #include <cassert>
108
- #include <chrono>
109
- #include <istream>
110
- #include <locale>
111
- #include <memory>
112
- #include <mutex>
113
- #include <ostream>
114
- #include <sstream>
115
- #include <stdexcept>
116
- #include <string>
117
- #include <type_traits>
118
- #include <utility>
119
- #include <vector>
120
-
121
- #ifdef _WIN32
122
- # ifdef DATE_BUILD_DLL
123
- # define DATE_API __declspec(dllexport)
124
- # elif defined(DATE_USE_DLL)
125
- # define DATE_API __declspec(dllimport)
126
- # else
127
- # define DATE_API
128
- # endif
129
- #else
130
- # ifdef DATE_BUILD_DLL
131
- # define DATE_API __attribute__ ((visibility ("default")))
132
- # else
133
- # define DATE_API
134
- # endif
135
- #endif
136
-
137
- namespace arrow_vendored::date
138
- {
139
-
140
- enum class choose {earliest, latest};
141
-
142
- #if defined(BUILD_TZ_LIB)
143
- # if defined(ANDROID) || defined(__ANDROID__)
144
- struct tzdb;
145
- static std::unique_ptr<tzdb> init_tzdb();
146
- # endif // defined(ANDROID) || defined(__ANDROID__)
147
- #endif // defined(BUILD_TZ_LIB)
148
-
149
- namespace detail
150
- {
151
- struct undocumented;
152
-
153
- template<typename T>
154
- struct nodeduct
155
- {
156
- using type = T;
157
- };
158
-
159
- template<typename T>
160
- using nodeduct_t = typename nodeduct<T>::type;
161
- }
162
-
163
- struct sys_info
164
- {
165
- sys_seconds begin;
166
- sys_seconds end;
167
- std::chrono::seconds offset;
168
- std::chrono::minutes save;
169
- std::string abbrev;
170
- };
171
-
172
- template<class CharT, class Traits>
173
- std::basic_ostream<CharT, Traits>&
174
- operator<<(std::basic_ostream<CharT, Traits>& os, const sys_info& r)
175
- {
176
- os << r.begin << '\n';
177
- os << r.end << '\n';
178
- os << make_time(r.offset) << "\n";
179
- os << make_time(r.save) << "\n";
180
- os << r.abbrev << '\n';
181
- return os;
182
- }
183
-
184
- struct local_info
185
- {
186
- enum {unique, nonexistent, ambiguous} result;
187
- sys_info first;
188
- sys_info second;
189
- };
190
-
191
- template<class CharT, class Traits>
192
- std::basic_ostream<CharT, Traits>&
193
- operator<<(std::basic_ostream<CharT, Traits>& os, const local_info& r)
194
- {
195
- if (r.result == local_info::nonexistent)
196
- os << "nonexistent between\n";
197
- else if (r.result == local_info::ambiguous)
198
- os << "ambiguous between\n";
199
- os << r.first;
200
- if (r.result != local_info::unique)
201
- {
202
- os << "and\n";
203
- os << r.second;
204
- }
205
- return os;
206
- }
207
-
208
- class nonexistent_local_time
209
- : public std::runtime_error
210
- {
211
- public:
212
- template <class Duration>
213
- nonexistent_local_time(local_time<Duration> tp, const local_info& i);
214
-
215
- private:
216
- template <class Duration>
217
- static
218
- std::string
219
- make_msg(local_time<Duration> tp, const local_info& i);
220
- };
221
-
222
- template <class Duration>
223
- inline
224
- nonexistent_local_time::nonexistent_local_time(local_time<Duration> tp,
225
- const local_info& i)
226
- : std::runtime_error(make_msg(tp, i))
227
- {
228
- }
229
-
230
- template <class Duration>
231
- std::string
232
- nonexistent_local_time::make_msg(local_time<Duration> tp, const local_info& i)
233
- {
234
- assert(i.result == local_info::nonexistent);
235
- std::ostringstream os;
236
- os << tp << " is in a gap between\n"
237
- << local_seconds{i.first.end.time_since_epoch()} + i.first.offset << ' '
238
- << i.first.abbrev << " and\n"
239
- << local_seconds{i.second.begin.time_since_epoch()} + i.second.offset << ' '
240
- << i.second.abbrev
241
- << " which are both equivalent to\n";
242
- date::operator<<(os, i.first.end) << " UTC";
243
- return os.str();
244
- }
245
-
246
- class ambiguous_local_time
247
- : public std::runtime_error
248
- {
249
- public:
250
- template <class Duration>
251
- ambiguous_local_time(local_time<Duration> tp, const local_info& i);
252
-
253
- private:
254
- template <class Duration>
255
- static
256
- std::string
257
- make_msg(local_time<Duration> tp, const local_info& i);
258
- };
259
-
260
- template <class Duration>
261
- inline
262
- ambiguous_local_time::ambiguous_local_time(local_time<Duration> tp, const local_info& i)
263
- : std::runtime_error(make_msg(tp, i))
264
- {
265
- }
266
-
267
- template <class Duration>
268
- std::string
269
- ambiguous_local_time::make_msg(local_time<Duration> tp, const local_info& i)
270
- {
271
- assert(i.result == local_info::ambiguous);
272
- std::ostringstream os;
273
- os << tp << " is ambiguous. It could be\n"
274
- << tp << ' ' << i.first.abbrev << " == "
275
- << tp - i.first.offset << " UTC or\n"
276
- << tp << ' ' << i.second.abbrev << " == "
277
- << tp - i.second.offset << " UTC";
278
- return os.str();
279
- }
280
-
281
- class time_zone;
282
-
283
- #if HAS_STRING_VIEW
284
- DATE_API const time_zone* locate_zone(std::string_view tz_name);
285
- #else
286
- DATE_API const time_zone* locate_zone(const std::string& tz_name);
287
- #endif
288
-
289
- DATE_API const time_zone* current_zone();
290
-
291
- template <class T>
292
- struct zoned_traits
293
- {
294
- };
295
-
296
- template <>
297
- struct zoned_traits<const time_zone*>
298
- {
299
- static
300
- const time_zone*
301
- default_zone()
302
- {
303
- return date::locate_zone("Etc/UTC");
304
- }
305
-
306
- #if HAS_STRING_VIEW
307
-
308
- static
309
- const time_zone*
310
- locate_zone(std::string_view name)
311
- {
312
- return date::locate_zone(name);
313
- }
314
-
315
- #else // !HAS_STRING_VIEW
316
-
317
- static
318
- const time_zone*
319
- locate_zone(const std::string& name)
320
- {
321
- return date::locate_zone(name);
322
- }
323
-
324
- static
325
- const time_zone*
326
- locate_zone(const char* name)
327
- {
328
- return date::locate_zone(name);
329
- }
330
-
331
- #endif // !HAS_STRING_VIEW
332
- };
333
-
334
- template <class Duration, class TimeZonePtr>
335
- class zoned_time;
336
-
337
- template <class Duration1, class Duration2, class TimeZonePtr>
338
- bool
339
- operator==(const zoned_time<Duration1, TimeZonePtr>& x,
340
- const zoned_time<Duration2, TimeZonePtr>& y);
341
-
342
- template <class Duration, class TimeZonePtr = const time_zone*>
343
- class zoned_time
344
- {
345
- public:
346
- using duration = typename std::common_type<Duration, std::chrono::seconds>::type;
347
-
348
- private:
349
- TimeZonePtr zone_;
350
- sys_time<duration> tp_;
351
-
352
- public:
353
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
354
- template <class T = TimeZonePtr,
355
- class = decltype(zoned_traits<T>::default_zone())>
356
- #endif
357
- zoned_time();
358
-
359
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
360
- template <class T = TimeZonePtr,
361
- class = decltype(zoned_traits<T>::default_zone())>
362
- #endif
363
- zoned_time(const sys_time<Duration>& st);
364
- explicit zoned_time(TimeZonePtr z);
365
-
366
- #if HAS_STRING_VIEW
367
- template <class T = TimeZonePtr,
368
- class = typename std::enable_if
369
- <
370
- std::is_constructible
371
- <
372
- zoned_time,
373
- decltype(zoned_traits<T>::locate_zone(std::string_view()))
374
- >::value
375
- >::type>
376
- explicit zoned_time(std::string_view name);
377
- #else
378
- # if !defined(_MSC_VER) || (_MSC_VER > 1916)
379
- template <class T = TimeZonePtr,
380
- class = typename std::enable_if
381
- <
382
- std::is_constructible
383
- <
384
- zoned_time,
385
- decltype(zoned_traits<T>::locate_zone(std::string()))
386
- >::value
387
- >::type>
388
- # endif
389
- explicit zoned_time(const std::string& name);
390
- #endif
391
-
392
- template <class Duration2,
393
- class = typename std::enable_if
394
- <
395
- std::is_convertible<sys_time<Duration2>,
396
- sys_time<Duration>>::value
397
- >::type>
398
- zoned_time(const zoned_time<Duration2, TimeZonePtr>& zt) NOEXCEPT;
399
-
400
- zoned_time(TimeZonePtr z, const sys_time<Duration>& st);
401
-
402
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
403
- template <class T = TimeZonePtr,
404
- class = typename std::enable_if
405
- <
406
- std::is_convertible
407
- <
408
- decltype(std::declval<T&>()->to_sys(local_time<Duration>{})),
409
- sys_time<duration>
410
- >::value
411
- >::type>
412
- #endif
413
- zoned_time(TimeZonePtr z, const local_time<Duration>& tp);
414
-
415
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
416
- template <class T = TimeZonePtr,
417
- class = typename std::enable_if
418
- <
419
- std::is_convertible
420
- <
421
- decltype(std::declval<T&>()->to_sys(local_time<Duration>{},
422
- choose::earliest)),
423
- sys_time<duration>
424
- >::value
425
- >::type>
426
- #endif
427
- zoned_time(TimeZonePtr z, const local_time<Duration>& tp, choose c);
428
-
429
- template <class Duration2, class TimeZonePtr2,
430
- class = typename std::enable_if
431
- <
432
- std::is_convertible<sys_time<Duration2>,
433
- sys_time<Duration>>::value
434
- >::type>
435
- zoned_time(TimeZonePtr z, const zoned_time<Duration2, TimeZonePtr2>& zt);
436
-
437
- template <class Duration2, class TimeZonePtr2,
438
- class = typename std::enable_if
439
- <
440
- std::is_convertible<sys_time<Duration2>,
441
- sys_time<Duration>>::value
442
- >::type>
443
- zoned_time(TimeZonePtr z, const zoned_time<Duration2, TimeZonePtr2>& zt, choose);
444
-
445
- #if HAS_STRING_VIEW
446
-
447
- template <class T = TimeZonePtr,
448
- class = typename std::enable_if
449
- <
450
- std::is_constructible
451
- <
452
- zoned_time,
453
- decltype(zoned_traits<T>::locate_zone(std::string_view())),
454
- sys_time<Duration>
455
- >::value
456
- >::type>
457
- zoned_time(std::string_view name, detail::nodeduct_t<const sys_time<Duration>&> st);
458
-
459
- template <class T = TimeZonePtr,
460
- class = typename std::enable_if
461
- <
462
- std::is_constructible
463
- <
464
- zoned_time,
465
- decltype(zoned_traits<T>::locate_zone(std::string_view())),
466
- local_time<Duration>
467
- >::value
468
- >::type>
469
- zoned_time(std::string_view name, detail::nodeduct_t<const local_time<Duration>&> tp);
470
-
471
- template <class T = TimeZonePtr,
472
- class = typename std::enable_if
473
- <
474
- std::is_constructible
475
- <
476
- zoned_time,
477
- decltype(zoned_traits<T>::locate_zone(std::string_view())),
478
- local_time<Duration>,
479
- choose
480
- >::value
481
- >::type>
482
- zoned_time(std::string_view name, detail::nodeduct_t<const local_time<Duration>&> tp, choose c);
483
-
484
- template <class Duration2, class TimeZonePtr2, class T = TimeZonePtr,
485
- class = typename std::enable_if
486
- <
487
- std::is_convertible<sys_time<Duration2>,
488
- sys_time<Duration>>::value &&
489
- std::is_constructible
490
- <
491
- zoned_time,
492
- decltype(zoned_traits<T>::locate_zone(std::string_view())),
493
- zoned_time
494
- >::value
495
- >::type>
496
- zoned_time(std::string_view name, const zoned_time<Duration2, TimeZonePtr2>& zt);
497
-
498
- template <class Duration2, class TimeZonePtr2, class T = TimeZonePtr,
499
- class = typename std::enable_if
500
- <
501
- std::is_convertible<sys_time<Duration2>,
502
- sys_time<Duration>>::value &&
503
- std::is_constructible
504
- <
505
- zoned_time,
506
- decltype(zoned_traits<T>::locate_zone(std::string_view())),
507
- zoned_time,
508
- choose
509
- >::value
510
- >::type>
511
- zoned_time(std::string_view name, const zoned_time<Duration2, TimeZonePtr2>& zt, choose);
512
-
513
- #else // !HAS_STRING_VIEW
514
-
515
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
516
- template <class T = TimeZonePtr,
517
- class = typename std::enable_if
518
- <
519
- std::is_constructible
520
- <
521
- zoned_time,
522
- decltype(zoned_traits<T>::locate_zone(std::string())),
523
- sys_time<Duration>
524
- >::value
525
- >::type>
526
- #endif
527
- zoned_time(const std::string& name, const sys_time<Duration>& st);
528
-
529
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
530
- template <class T = TimeZonePtr,
531
- class = typename std::enable_if
532
- <
533
- std::is_constructible
534
- <
535
- zoned_time,
536
- decltype(zoned_traits<T>::locate_zone(std::string())),
537
- sys_time<Duration>
538
- >::value
539
- >::type>
540
- #endif
541
- zoned_time(const char* name, const sys_time<Duration>& st);
542
-
543
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
544
- template <class T = TimeZonePtr,
545
- class = typename std::enable_if
546
- <
547
- std::is_constructible
548
- <
549
- zoned_time,
550
- decltype(zoned_traits<T>::locate_zone(std::string())),
551
- local_time<Duration>
552
- >::value
553
- >::type>
554
- #endif
555
- zoned_time(const std::string& name, const local_time<Duration>& tp);
556
-
557
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
558
- template <class T = TimeZonePtr,
559
- class = typename std::enable_if
560
- <
561
- std::is_constructible
562
- <
563
- zoned_time,
564
- decltype(zoned_traits<T>::locate_zone(std::string())),
565
- local_time<Duration>
566
- >::value
567
- >::type>
568
- #endif
569
- zoned_time(const char* name, const local_time<Duration>& tp);
570
-
571
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
572
- template <class T = TimeZonePtr,
573
- class = typename std::enable_if
574
- <
575
- std::is_constructible
576
- <
577
- zoned_time,
578
- decltype(zoned_traits<T>::locate_zone(std::string())),
579
- local_time<Duration>,
580
- choose
581
- >::value
582
- >::type>
583
- #endif
584
- zoned_time(const std::string& name, const local_time<Duration>& tp, choose c);
585
-
586
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
587
- template <class T = TimeZonePtr,
588
- class = typename std::enable_if
589
- <
590
- std::is_constructible
591
- <
592
- zoned_time,
593
- decltype(zoned_traits<T>::locate_zone(std::string())),
594
- local_time<Duration>,
595
- choose
596
- >::value
597
- >::type>
598
- #endif
599
- zoned_time(const char* name, const local_time<Duration>& tp, choose c);
600
-
601
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
602
- template <class Duration2, class TimeZonePtr2, class T = TimeZonePtr,
603
- class = typename std::enable_if
604
- <
605
- std::is_convertible<sys_time<Duration2>,
606
- sys_time<Duration>>::value &&
607
- std::is_constructible
608
- <
609
- zoned_time,
610
- decltype(zoned_traits<T>::locate_zone(std::string())),
611
- zoned_time
612
- >::value
613
- >::type>
614
- #else
615
- template <class Duration2, class TimeZonePtr2>
616
- #endif
617
- zoned_time(const std::string& name, const zoned_time<Duration2, TimeZonePtr2>& zt);
618
-
619
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
620
- template <class Duration2, class TimeZonePtr2, class T = TimeZonePtr,
621
- class = typename std::enable_if
622
- <
623
- std::is_convertible<sys_time<Duration2>,
624
- sys_time<Duration>>::value &&
625
- std::is_constructible
626
- <
627
- zoned_time,
628
- decltype(zoned_traits<T>::locate_zone(std::string())),
629
- zoned_time
630
- >::value
631
- >::type>
632
- #else
633
- template <class Duration2, class TimeZonePtr2>
634
- #endif
635
- zoned_time(const char* name, const zoned_time<Duration2, TimeZonePtr2>& zt);
636
-
637
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
638
- template <class Duration2, class TimeZonePtr2, class T = TimeZonePtr,
639
- class = typename std::enable_if
640
- <
641
- std::is_convertible<sys_time<Duration2>,
642
- sys_time<Duration>>::value &&
643
- std::is_constructible
644
- <
645
- zoned_time,
646
- decltype(zoned_traits<T>::locate_zone(std::string())),
647
- zoned_time,
648
- choose
649
- >::value
650
- >::type>
651
- #else
652
- template <class Duration2, class TimeZonePtr2>
653
- #endif
654
- zoned_time(const std::string& name, const zoned_time<Duration2, TimeZonePtr2>& zt,
655
- choose);
656
-
657
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
658
- template <class Duration2, class TimeZonePtr2, class T = TimeZonePtr,
659
- class = typename std::enable_if
660
- <
661
- std::is_convertible<sys_time<Duration2>,
662
- sys_time<Duration>>::value &&
663
- std::is_constructible
664
- <
665
- zoned_time,
666
- decltype(zoned_traits<T>::locate_zone(std::string())),
667
- zoned_time,
668
- choose
669
- >::value
670
- >::type>
671
- #else
672
- template <class Duration2, class TimeZonePtr2>
673
- #endif
674
- zoned_time(const char* name, const zoned_time<Duration2, TimeZonePtr2>& zt,
675
- choose);
676
-
677
- #endif // !HAS_STRING_VIEW
678
-
679
- zoned_time& operator=(const sys_time<Duration>& st);
680
- zoned_time& operator=(const local_time<Duration>& ut);
681
-
682
- explicit operator sys_time<duration>() const;
683
- explicit operator local_time<duration>() const;
684
-
685
- TimeZonePtr get_time_zone() const;
686
- local_time<duration> get_local_time() const;
687
- sys_time<duration> get_sys_time() const;
688
- sys_info get_info() const;
689
-
690
- template <class Duration1, class Duration2, class TimeZonePtr1>
691
- friend
692
- bool
693
- operator==(const zoned_time<Duration1, TimeZonePtr1>& x,
694
- const zoned_time<Duration2, TimeZonePtr1>& y);
695
-
696
- template <class CharT, class Traits, class Duration1, class TimeZonePtr1>
697
- friend
698
- std::basic_ostream<CharT, Traits>&
699
- operator<<(std::basic_ostream<CharT, Traits>& os,
700
- const zoned_time<Duration1, TimeZonePtr1>& t);
701
-
702
- private:
703
- template <class D, class T> friend class zoned_time;
704
-
705
- template <class TimeZonePtr2>
706
- static
707
- TimeZonePtr2&&
708
- check(TimeZonePtr2&& p);
709
- };
710
-
711
- using zoned_seconds = zoned_time<std::chrono::seconds>;
712
-
713
- #if HAS_DEDUCTION_GUIDES
714
-
715
- namespace detail
716
- {
717
- template<typename TimeZonePtrOrName>
718
- using time_zone_representation =
719
- std::conditional_t
720
- <
721
- std::is_convertible<TimeZonePtrOrName, std::string_view>::value,
722
- time_zone const*,
723
- std::remove_cv_t<std::remove_reference_t<TimeZonePtrOrName>>
724
- >;
725
- }
726
-
727
- zoned_time()
728
- -> zoned_time<std::chrono::seconds>;
729
-
730
- template <class Duration>
731
- zoned_time(sys_time<Duration>)
732
- -> zoned_time<std::common_type_t<Duration, std::chrono::seconds>>;
733
-
734
- template <class TimeZonePtrOrName>
735
- zoned_time(TimeZonePtrOrName&&)
736
- -> zoned_time<std::chrono::seconds, detail::time_zone_representation<TimeZonePtrOrName>>;
737
-
738
- template <class TimeZonePtrOrName, class Duration>
739
- zoned_time(TimeZonePtrOrName&&, sys_time<Duration>)
740
- -> zoned_time<std::common_type_t<Duration, std::chrono::seconds>, detail::time_zone_representation<TimeZonePtrOrName>>;
741
-
742
- template <class TimeZonePtrOrName, class Duration>
743
- zoned_time(TimeZonePtrOrName&&, local_time<Duration>, choose = choose::earliest)
744
- -> zoned_time<std::common_type_t<Duration, std::chrono::seconds>, detail::time_zone_representation<TimeZonePtrOrName>>;
745
-
746
- template <class Duration, class TimeZonePtrOrName, class TimeZonePtr2>
747
- zoned_time(TimeZonePtrOrName&&, zoned_time<Duration, TimeZonePtr2>, choose = choose::earliest)
748
- -> zoned_time<std::common_type_t<Duration, std::chrono::seconds>, detail::time_zone_representation<TimeZonePtrOrName>>;
749
-
750
- #endif // HAS_DEDUCTION_GUIDES
751
-
752
- template <class Duration1, class Duration2, class TimeZonePtr>
753
- inline
754
- bool
755
- operator==(const zoned_time<Duration1, TimeZonePtr>& x,
756
- const zoned_time<Duration2, TimeZonePtr>& y)
757
- {
758
- return x.zone_ == y.zone_ && x.tp_ == y.tp_;
759
- }
760
-
761
- template <class Duration1, class Duration2, class TimeZonePtr>
762
- inline
763
- bool
764
- operator!=(const zoned_time<Duration1, TimeZonePtr>& x,
765
- const zoned_time<Duration2, TimeZonePtr>& y)
766
- {
767
- return !(x == y);
768
- }
769
-
770
- #if !defined(_MSC_VER) || (_MSC_VER >= 1900)
771
-
772
- namespace detail
773
- {
774
- # if USE_OS_TZDB
775
- struct transition;
776
- struct expanded_ttinfo;
777
- # else // !USE_OS_TZDB
778
- struct zonelet;
779
- class Rule;
780
- # endif // !USE_OS_TZDB
781
- }
782
-
783
- #endif // !defined(_MSC_VER) || (_MSC_VER >= 1900)
784
-
785
- class time_zone
786
- {
787
- private:
788
- std::string name_;
789
- #if USE_OS_TZDB
790
- std::vector<detail::transition> transitions_;
791
- std::vector<detail::expanded_ttinfo> ttinfos_;
792
- #else // !USE_OS_TZDB
793
- std::vector<detail::zonelet> zonelets_;
794
- #endif // !USE_OS_TZDB
795
- std::unique_ptr<std::once_flag> adjusted_;
796
-
797
- public:
798
- #if !defined(_MSC_VER) || (_MSC_VER >= 1900)
799
- time_zone(time_zone&&) = default;
800
- time_zone& operator=(time_zone&&) = default;
801
- #else // defined(_MSC_VER) && (_MSC_VER < 1900)
802
- time_zone(time_zone&& src);
803
- time_zone& operator=(time_zone&& src);
804
- #endif // defined(_MSC_VER) && (_MSC_VER < 1900)
805
-
806
- DATE_API explicit time_zone(const std::string& s, detail::undocumented);
807
-
808
- const std::string& name() const NOEXCEPT;
809
-
810
- template <class Duration> sys_info get_info(sys_time<Duration> st) const;
811
- template <class Duration> local_info get_info(local_time<Duration> tp) const;
812
-
813
- template <class Duration>
814
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
815
- to_sys(local_time<Duration> tp) const;
816
-
817
- template <class Duration>
818
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
819
- to_sys(local_time<Duration> tp, choose z) const;
820
-
821
- template <class Duration>
822
- local_time<typename std::common_type<Duration, std::chrono::seconds>::type>
823
- to_local(sys_time<Duration> tp) const;
824
-
825
- friend bool operator==(const time_zone& x, const time_zone& y) NOEXCEPT;
826
- friend bool operator< (const time_zone& x, const time_zone& y) NOEXCEPT;
827
- friend DATE_API std::ostream& operator<<(std::ostream& os, const time_zone& z);
828
-
829
- #if !USE_OS_TZDB
830
- DATE_API void add(const std::string& s);
831
- #else
832
- # if defined(BUILD_TZ_LIB)
833
- # if defined(ANDROID) || defined(__ANDROID__)
834
- friend std::unique_ptr<tzdb> init_tzdb();
835
- # endif // defined(ANDROID) || defined(__ANDROID__)
836
- # endif // defined(BUILD_TZ_LIB)
837
- #endif // !USE_OS_TZDB
838
-
839
- private:
840
- DATE_API sys_info get_info_impl(sys_seconds tp) const;
841
- DATE_API local_info get_info_impl(local_seconds tp) const;
842
-
843
- template <class Duration>
844
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
845
- to_sys_impl(local_time<Duration> tp, choose z, std::false_type) const;
846
- template <class Duration>
847
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
848
- to_sys_impl(local_time<Duration> tp, choose, std::true_type) const;
849
-
850
- #if USE_OS_TZDB
851
- DATE_API void init() const;
852
- DATE_API void init_impl();
853
- DATE_API sys_info
854
- load_sys_info(std::vector<detail::transition>::const_iterator i) const;
855
-
856
- template <class TimeType>
857
- DATE_API void
858
- load_data(std::istream& inf, std::int32_t tzh_leapcnt, std::int32_t tzh_timecnt,
859
- std::int32_t tzh_typecnt, std::int32_t tzh_charcnt);
860
- # if defined(ANDROID) || defined(__ANDROID__)
861
- void parse_from_android_tzdata(std::ifstream& inf, const std::size_t off);
862
- # endif // defined(ANDROID) || defined(__ANDROID__)
863
- #else // !USE_OS_TZDB
864
- DATE_API sys_info get_info_impl(sys_seconds tp, int tz_int) const;
865
- DATE_API void adjust_infos(const std::vector<detail::Rule>& rules);
866
- DATE_API void parse_info(std::istream& in);
867
- #endif // !USE_OS_TZDB
868
- };
869
-
870
- #if defined(_MSC_VER) && (_MSC_VER < 1900)
871
-
872
- inline
873
- time_zone::time_zone(time_zone&& src)
874
- : name_(std::move(src.name_))
875
- , zonelets_(std::move(src.zonelets_))
876
- , adjusted_(std::move(src.adjusted_))
877
- {}
878
-
879
- inline
880
- time_zone&
881
- time_zone::operator=(time_zone&& src)
882
- {
883
- name_ = std::move(src.name_);
884
- zonelets_ = std::move(src.zonelets_);
885
- adjusted_ = std::move(src.adjusted_);
886
- return *this;
887
- }
888
-
889
- #endif // defined(_MSC_VER) && (_MSC_VER < 1900)
890
-
891
- inline
892
- const std::string&
893
- time_zone::name() const NOEXCEPT
894
- {
895
- return name_;
896
- }
897
-
898
- template <class Duration>
899
- inline
900
- sys_info
901
- time_zone::get_info(sys_time<Duration> st) const
902
- {
903
- return get_info_impl(date::floor<std::chrono::seconds>(st));
904
- }
905
-
906
- template <class Duration>
907
- inline
908
- local_info
909
- time_zone::get_info(local_time<Duration> tp) const
910
- {
911
- return get_info_impl(date::floor<std::chrono::seconds>(tp));
912
- }
913
-
914
- template <class Duration>
915
- inline
916
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
917
- time_zone::to_sys(local_time<Duration> tp) const
918
- {
919
- return to_sys_impl(tp, choose{}, std::true_type{});
920
- }
921
-
922
- template <class Duration>
923
- inline
924
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
925
- time_zone::to_sys(local_time<Duration> tp, choose z) const
926
- {
927
- return to_sys_impl(tp, z, std::false_type{});
928
- }
929
-
930
- template <class Duration>
931
- inline
932
- local_time<typename std::common_type<Duration, std::chrono::seconds>::type>
933
- time_zone::to_local(sys_time<Duration> tp) const
934
- {
935
- using LT = local_time<typename std::common_type<Duration, std::chrono::seconds>::type>;
936
- auto i = get_info(tp);
937
- return LT{(tp + i.offset).time_since_epoch()};
938
- }
939
-
940
- inline bool operator==(const time_zone& x, const time_zone& y) NOEXCEPT {return x.name_ == y.name_;}
941
- inline bool operator< (const time_zone& x, const time_zone& y) NOEXCEPT {return x.name_ < y.name_;}
942
-
943
- inline bool operator!=(const time_zone& x, const time_zone& y) NOEXCEPT {return !(x == y);}
944
- inline bool operator> (const time_zone& x, const time_zone& y) NOEXCEPT {return y < x;}
945
- inline bool operator<=(const time_zone& x, const time_zone& y) NOEXCEPT {return !(y < x);}
946
- inline bool operator>=(const time_zone& x, const time_zone& y) NOEXCEPT {return !(x < y);}
947
-
948
- template <class Duration>
949
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
950
- time_zone::to_sys_impl(local_time<Duration> tp, choose z, std::false_type) const
951
- {
952
- auto i = get_info(tp);
953
- if (i.result == local_info::nonexistent)
954
- {
955
- return i.first.end;
956
- }
957
- else if (i.result == local_info::ambiguous)
958
- {
959
- if (z == choose::latest)
960
- return sys_time<Duration>{tp.time_since_epoch()} - i.second.offset;
961
- }
962
- return sys_time<Duration>{tp.time_since_epoch()} - i.first.offset;
963
- }
964
-
965
- template <class Duration>
966
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
967
- time_zone::to_sys_impl(local_time<Duration> tp, choose, std::true_type) const
968
- {
969
- auto i = get_info(tp);
970
- if (i.result == local_info::nonexistent)
971
- throw nonexistent_local_time(tp, i);
972
- else if (i.result == local_info::ambiguous)
973
- throw ambiguous_local_time(tp, i);
974
- return sys_time<Duration>{tp.time_since_epoch()} - i.first.offset;
975
- }
976
-
977
- #if !USE_OS_TZDB
978
-
979
- class time_zone_link
980
- {
981
- private:
982
- std::string name_;
983
- std::string target_;
984
- public:
985
- DATE_API explicit time_zone_link(const std::string& s);
986
-
987
- const std::string& name() const {return name_;}
988
- const std::string& target() const {return target_;}
989
-
990
- friend bool operator==(const time_zone_link& x, const time_zone_link& y) {return x.name_ == y.name_;}
991
- friend bool operator< (const time_zone_link& x, const time_zone_link& y) {return x.name_ < y.name_;}
992
-
993
- friend DATE_API std::ostream& operator<<(std::ostream& os, const time_zone_link& x);
994
- };
995
-
996
- using link = time_zone_link;
997
-
998
- inline bool operator!=(const time_zone_link& x, const time_zone_link& y) {return !(x == y);}
999
- inline bool operator> (const time_zone_link& x, const time_zone_link& y) {return y < x;}
1000
- inline bool operator<=(const time_zone_link& x, const time_zone_link& y) {return !(y < x);}
1001
- inline bool operator>=(const time_zone_link& x, const time_zone_link& y) {return !(x < y);}
1002
-
1003
- #endif // !USE_OS_TZDB
1004
-
1005
- class leap_second
1006
- {
1007
- private:
1008
- sys_seconds date_;
1009
-
1010
- public:
1011
- #if USE_OS_TZDB
1012
- DATE_API explicit leap_second(const sys_seconds& s, detail::undocumented);
1013
- #else
1014
- DATE_API explicit leap_second(const std::string& s, detail::undocumented);
1015
- #endif
1016
-
1017
- sys_seconds date() const {return date_;}
1018
-
1019
- friend bool operator==(const leap_second& x, const leap_second& y) {return x.date_ == y.date_;}
1020
- friend bool operator< (const leap_second& x, const leap_second& y) {return x.date_ < y.date_;}
1021
-
1022
- template <class Duration>
1023
- friend
1024
- bool
1025
- operator==(const leap_second& x, const sys_time<Duration>& y)
1026
- {
1027
- return x.date_ == y;
1028
- }
1029
-
1030
- template <class Duration>
1031
- friend
1032
- bool
1033
- operator< (const leap_second& x, const sys_time<Duration>& y)
1034
- {
1035
- return x.date_ < y;
1036
- }
1037
-
1038
- template <class Duration>
1039
- friend
1040
- bool
1041
- operator< (const sys_time<Duration>& x, const leap_second& y)
1042
- {
1043
- return x < y.date_;
1044
- }
1045
-
1046
- friend DATE_API std::ostream& operator<<(std::ostream& os, const leap_second& x);
1047
- };
1048
-
1049
- inline bool operator!=(const leap_second& x, const leap_second& y) {return !(x == y);}
1050
- inline bool operator> (const leap_second& x, const leap_second& y) {return y < x;}
1051
- inline bool operator<=(const leap_second& x, const leap_second& y) {return !(y < x);}
1052
- inline bool operator>=(const leap_second& x, const leap_second& y) {return !(x < y);}
1053
-
1054
- template <class Duration>
1055
- inline
1056
- bool
1057
- operator==(const sys_time<Duration>& x, const leap_second& y)
1058
- {
1059
- return y == x;
1060
- }
1061
-
1062
- template <class Duration>
1063
- inline
1064
- bool
1065
- operator!=(const leap_second& x, const sys_time<Duration>& y)
1066
- {
1067
- return !(x == y);
1068
- }
1069
-
1070
- template <class Duration>
1071
- inline
1072
- bool
1073
- operator!=(const sys_time<Duration>& x, const leap_second& y)
1074
- {
1075
- return !(x == y);
1076
- }
1077
-
1078
- template <class Duration>
1079
- inline
1080
- bool
1081
- operator> (const leap_second& x, const sys_time<Duration>& y)
1082
- {
1083
- return y < x;
1084
- }
1085
-
1086
- template <class Duration>
1087
- inline
1088
- bool
1089
- operator> (const sys_time<Duration>& x, const leap_second& y)
1090
- {
1091
- return y < x;
1092
- }
1093
-
1094
- template <class Duration>
1095
- inline
1096
- bool
1097
- operator<=(const leap_second& x, const sys_time<Duration>& y)
1098
- {
1099
- return !(y < x);
1100
- }
1101
-
1102
- template <class Duration>
1103
- inline
1104
- bool
1105
- operator<=(const sys_time<Duration>& x, const leap_second& y)
1106
- {
1107
- return !(y < x);
1108
- }
1109
-
1110
- template <class Duration>
1111
- inline
1112
- bool
1113
- operator>=(const leap_second& x, const sys_time<Duration>& y)
1114
- {
1115
- return !(x < y);
1116
- }
1117
-
1118
- template <class Duration>
1119
- inline
1120
- bool
1121
- operator>=(const sys_time<Duration>& x, const leap_second& y)
1122
- {
1123
- return !(x < y);
1124
- }
1125
-
1126
- using leap = leap_second;
1127
-
1128
- #ifdef _WIN32
1129
-
1130
- namespace detail
1131
- {
1132
-
1133
- // The time zone mapping is modelled after this data file:
1134
- // http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml
1135
- // and the field names match the element names from the mapZone element
1136
- // of windowsZones.xml.
1137
- // The website displays this file here:
1138
- // http://www.unicode.org/cldr/charts/latest/supplemental/zone_tzid.html
1139
- // The html view is sorted before being displayed but is otherwise the same
1140
- // There is a mapping between the os centric view (in this case windows)
1141
- // the html displays uses and the generic view the xml file.
1142
- // That mapping is this:
1143
- // display column "windows" -> xml field "other".
1144
- // display column "region" -> xml field "territory".
1145
- // display column "tzid" -> xml field "type".
1146
- // This structure uses the generic terminology because it could be
1147
- // used to to support other os/native name conversions, not just windows,
1148
- // and using the same generic names helps retain the connection to the
1149
- // origin of the data that we are using.
1150
- struct timezone_mapping
1151
- {
1152
- timezone_mapping(const char* other, const char* territory, const char* type)
1153
- : other(other), territory(territory), type(type)
1154
- {
1155
- }
1156
- timezone_mapping() = default;
1157
- std::string other;
1158
- std::string territory;
1159
- std::string type;
1160
- };
1161
-
1162
- } // detail
1163
-
1164
- #endif // _WIN32
1165
-
1166
- struct tzdb
1167
- {
1168
- std::string version = "unknown";
1169
- std::vector<time_zone> zones;
1170
- #if !USE_OS_TZDB
1171
- std::vector<time_zone_link> links;
1172
- #endif
1173
- std::vector<leap_second> leap_seconds;
1174
- #if !USE_OS_TZDB
1175
- std::vector<detail::Rule> rules;
1176
- #endif
1177
- #ifdef _WIN32
1178
- std::vector<detail::timezone_mapping> mappings;
1179
- #endif
1180
- tzdb* next = nullptr;
1181
-
1182
- tzdb() = default;
1183
- #if !defined(_MSC_VER) || (_MSC_VER >= 1900)
1184
- tzdb(tzdb&&) = default;
1185
- tzdb& operator=(tzdb&&) = default;
1186
- #else // defined(_MSC_VER) && (_MSC_VER < 1900)
1187
- tzdb(tzdb&& src)
1188
- : version(std::move(src.version))
1189
- , zones(std::move(src.zones))
1190
- , links(std::move(src.links))
1191
- , leap_seconds(std::move(src.leap_seconds))
1192
- , rules(std::move(src.rules))
1193
- , mappings(std::move(src.mappings))
1194
- {}
1195
-
1196
- tzdb& operator=(tzdb&& src)
1197
- {
1198
- version = std::move(src.version);
1199
- zones = std::move(src.zones);
1200
- links = std::move(src.links);
1201
- leap_seconds = std::move(src.leap_seconds);
1202
- rules = std::move(src.rules);
1203
- mappings = std::move(src.mappings);
1204
- return *this;
1205
- }
1206
- #endif // defined(_MSC_VER) && (_MSC_VER < 1900)
1207
-
1208
- #if HAS_STRING_VIEW
1209
- DATE_API const time_zone* locate_zone(std::string_view tz_name) const;
1210
- #else
1211
- DATE_API const time_zone* locate_zone(const std::string& tz_name) const;
1212
- #endif
1213
- DATE_API const time_zone* current_zone() const;
1214
- };
1215
-
1216
- using TZ_DB = tzdb;
1217
-
1218
- DATE_API std::ostream&
1219
- operator<<(std::ostream& os, const tzdb& db);
1220
-
1221
- DATE_API const tzdb& get_tzdb();
1222
-
1223
- class tzdb_list
1224
- {
1225
- std::atomic<tzdb*> head_{nullptr};
1226
-
1227
- public:
1228
- DATE_API ~tzdb_list();
1229
- tzdb_list() = default;
1230
- DATE_API tzdb_list(tzdb_list&& x) NOEXCEPT;
1231
-
1232
- const tzdb& front() const NOEXCEPT {return *head_;}
1233
- tzdb& front() NOEXCEPT {return *head_;}
1234
-
1235
- class const_iterator;
1236
-
1237
- const_iterator begin() const NOEXCEPT;
1238
- const_iterator end() const NOEXCEPT;
1239
-
1240
- const_iterator cbegin() const NOEXCEPT;
1241
- const_iterator cend() const NOEXCEPT;
1242
-
1243
- DATE_API const_iterator erase_after(const_iterator p) NOEXCEPT;
1244
-
1245
- struct undocumented_helper;
1246
- private:
1247
- void push_front(tzdb* tzdb) NOEXCEPT;
1248
- };
1249
-
1250
- class tzdb_list::const_iterator
1251
- {
1252
- tzdb* p_ = nullptr;
1253
-
1254
- explicit const_iterator(tzdb* p) NOEXCEPT : p_{p} {}
1255
- public:
1256
- const_iterator() = default;
1257
-
1258
- using iterator_category = std::forward_iterator_tag;
1259
- using value_type = tzdb;
1260
- using reference = const value_type&;
1261
- using pointer = const value_type*;
1262
- using difference_type = std::ptrdiff_t;
1263
-
1264
- reference operator*() const NOEXCEPT {return *p_;}
1265
- pointer operator->() const NOEXCEPT {return p_;}
1266
-
1267
- const_iterator& operator++() NOEXCEPT {p_ = p_->next; return *this;}
1268
- const_iterator operator++(int) NOEXCEPT {auto t = *this; ++(*this); return t;}
1269
-
1270
- friend
1271
- bool
1272
- operator==(const const_iterator& x, const const_iterator& y) NOEXCEPT
1273
- {return x.p_ == y.p_;}
1274
-
1275
- friend
1276
- bool
1277
- operator!=(const const_iterator& x, const const_iterator& y) NOEXCEPT
1278
- {return !(x == y);}
1279
-
1280
- friend class tzdb_list;
1281
- };
1282
-
1283
- inline
1284
- tzdb_list::const_iterator
1285
- tzdb_list::begin() const NOEXCEPT
1286
- {
1287
- return const_iterator{head_};
1288
- }
1289
-
1290
- inline
1291
- tzdb_list::const_iterator
1292
- tzdb_list::end() const NOEXCEPT
1293
- {
1294
- return const_iterator{nullptr};
1295
- }
1296
-
1297
- inline
1298
- tzdb_list::const_iterator
1299
- tzdb_list::cbegin() const NOEXCEPT
1300
- {
1301
- return begin();
1302
- }
1303
-
1304
- inline
1305
- tzdb_list::const_iterator
1306
- tzdb_list::cend() const NOEXCEPT
1307
- {
1308
- return end();
1309
- }
1310
-
1311
- DATE_API tzdb_list& get_tzdb_list();
1312
-
1313
- #if !USE_OS_TZDB
1314
-
1315
- DATE_API const tzdb& reload_tzdb();
1316
- DATE_API void set_install(const std::string& install);
1317
-
1318
- #endif // !USE_OS_TZDB
1319
-
1320
- #if HAS_REMOTE_API
1321
-
1322
- DATE_API std::string remote_version();
1323
- // if provided error_buffer size should be at least CURL_ERROR_SIZE
1324
- DATE_API bool remote_download(const std::string& version, char* error_buffer = nullptr);
1325
- DATE_API bool remote_install(const std::string& version);
1326
-
1327
- #endif
1328
-
1329
- // zoned_time
1330
-
1331
- namespace detail
1332
- {
1333
-
1334
- template <class T>
1335
- inline
1336
- T*
1337
- to_raw_pointer(T* p) NOEXCEPT
1338
- {
1339
- return p;
1340
- }
1341
-
1342
- template <class Pointer>
1343
- inline
1344
- auto
1345
- to_raw_pointer(Pointer p) NOEXCEPT
1346
- -> decltype(detail::to_raw_pointer(p.operator->()))
1347
- {
1348
- return detail::to_raw_pointer(p.operator->());
1349
- }
1350
-
1351
- } // namespace detail
1352
-
1353
- template <class Duration, class TimeZonePtr>
1354
- template <class TimeZonePtr2>
1355
- inline
1356
- TimeZonePtr2&&
1357
- zoned_time<Duration, TimeZonePtr>::check(TimeZonePtr2&& p)
1358
- {
1359
- if (detail::to_raw_pointer(p) == nullptr)
1360
- throw std::runtime_error(
1361
- "zoned_time constructed with a time zone pointer == nullptr");
1362
- return std::forward<TimeZonePtr2>(p);
1363
- }
1364
-
1365
- template <class Duration, class TimeZonePtr>
1366
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1367
- template <class T, class>
1368
- #endif
1369
- inline
1370
- zoned_time<Duration, TimeZonePtr>::zoned_time()
1371
- : zone_(check(zoned_traits<TimeZonePtr>::default_zone()))
1372
- {}
1373
-
1374
- template <class Duration, class TimeZonePtr>
1375
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1376
- template <class T, class>
1377
- #endif
1378
- inline
1379
- zoned_time<Duration, TimeZonePtr>::zoned_time(const sys_time<Duration>& st)
1380
- : zone_(check(zoned_traits<TimeZonePtr>::default_zone()))
1381
- , tp_(st)
1382
- {}
1383
-
1384
- template <class Duration, class TimeZonePtr>
1385
- inline
1386
- zoned_time<Duration, TimeZonePtr>::zoned_time(TimeZonePtr z)
1387
- : zone_(check(std::move(z)))
1388
- {}
1389
-
1390
- #if HAS_STRING_VIEW
1391
-
1392
- template <class Duration, class TimeZonePtr>
1393
- template <class T, class>
1394
- inline
1395
- zoned_time<Duration, TimeZonePtr>::zoned_time(std::string_view name)
1396
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name))
1397
- {}
1398
-
1399
- #else // !HAS_STRING_VIEW
1400
-
1401
- template <class Duration, class TimeZonePtr>
1402
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1403
- template <class T, class>
1404
- #endif
1405
- inline
1406
- zoned_time<Duration, TimeZonePtr>::zoned_time(const std::string& name)
1407
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name))
1408
- {}
1409
-
1410
- #endif // !HAS_STRING_VIEW
1411
-
1412
- template <class Duration, class TimeZonePtr>
1413
- template <class Duration2, class>
1414
- inline
1415
- zoned_time<Duration, TimeZonePtr>::zoned_time(const zoned_time<Duration2, TimeZonePtr>& zt) NOEXCEPT
1416
- : zone_(zt.zone_)
1417
- , tp_(zt.tp_)
1418
- {}
1419
-
1420
- template <class Duration, class TimeZonePtr>
1421
- inline
1422
- zoned_time<Duration, TimeZonePtr>::zoned_time(TimeZonePtr z, const sys_time<Duration>& st)
1423
- : zone_(check(std::move(z)))
1424
- , tp_(st)
1425
- {}
1426
-
1427
- template <class Duration, class TimeZonePtr>
1428
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1429
- template <class T, class>
1430
- #endif
1431
- inline
1432
- zoned_time<Duration, TimeZonePtr>::zoned_time(TimeZonePtr z, const local_time<Duration>& t)
1433
- : zone_(check(std::move(z)))
1434
- , tp_(zone_->to_sys(t))
1435
- {}
1436
-
1437
- template <class Duration, class TimeZonePtr>
1438
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1439
- template <class T, class>
1440
- #endif
1441
- inline
1442
- zoned_time<Duration, TimeZonePtr>::zoned_time(TimeZonePtr z, const local_time<Duration>& t,
1443
- choose c)
1444
- : zone_(check(std::move(z)))
1445
- , tp_(zone_->to_sys(t, c))
1446
- {}
1447
-
1448
- template <class Duration, class TimeZonePtr>
1449
- template <class Duration2, class TimeZonePtr2, class>
1450
- inline
1451
- zoned_time<Duration, TimeZonePtr>::zoned_time(TimeZonePtr z,
1452
- const zoned_time<Duration2, TimeZonePtr2>& zt)
1453
- : zone_(check(std::move(z)))
1454
- , tp_(zt.tp_)
1455
- {}
1456
-
1457
- template <class Duration, class TimeZonePtr>
1458
- template <class Duration2, class TimeZonePtr2, class>
1459
- inline
1460
- zoned_time<Duration, TimeZonePtr>::zoned_time(TimeZonePtr z,
1461
- const zoned_time<Duration2, TimeZonePtr2>& zt, choose)
1462
- : zoned_time(std::move(z), zt)
1463
- {}
1464
-
1465
- #if HAS_STRING_VIEW
1466
-
1467
- template <class Duration, class TimeZonePtr>
1468
- template <class T, class>
1469
- inline
1470
- zoned_time<Duration, TimeZonePtr>::zoned_time(std::string_view name,
1471
- detail::nodeduct_t<const sys_time<Duration>&> st)
1472
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), st)
1473
- {}
1474
-
1475
- template <class Duration, class TimeZonePtr>
1476
- template <class T, class>
1477
- inline
1478
- zoned_time<Duration, TimeZonePtr>::zoned_time(std::string_view name,
1479
- detail::nodeduct_t<const local_time<Duration>&> t)
1480
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), t)
1481
- {}
1482
-
1483
- template <class Duration, class TimeZonePtr>
1484
- template <class T, class>
1485
- inline
1486
- zoned_time<Duration, TimeZonePtr>::zoned_time(std::string_view name,
1487
- detail::nodeduct_t<const local_time<Duration>&> t, choose c)
1488
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), t, c)
1489
- {}
1490
-
1491
- template <class Duration, class TimeZonePtr>
1492
- template <class Duration2, class TimeZonePtr2, class, class>
1493
- inline
1494
- zoned_time<Duration, TimeZonePtr>::zoned_time(std::string_view name,
1495
- const zoned_time<Duration2, TimeZonePtr2>& zt)
1496
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), zt)
1497
- {}
1498
-
1499
- template <class Duration, class TimeZonePtr>
1500
- template <class Duration2, class TimeZonePtr2, class, class>
1501
- inline
1502
- zoned_time<Duration, TimeZonePtr>::zoned_time(std::string_view name,
1503
- const zoned_time<Duration2, TimeZonePtr2>& zt,
1504
- choose c)
1505
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), zt, c)
1506
- {}
1507
-
1508
- #else // !HAS_STRING_VIEW
1509
-
1510
- template <class Duration, class TimeZonePtr>
1511
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1512
- template <class T, class>
1513
- #endif
1514
- inline
1515
- zoned_time<Duration, TimeZonePtr>::zoned_time(const std::string& name,
1516
- const sys_time<Duration>& st)
1517
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), st)
1518
- {}
1519
-
1520
- template <class Duration, class TimeZonePtr>
1521
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1522
- template <class T, class>
1523
- #endif
1524
- inline
1525
- zoned_time<Duration, TimeZonePtr>::zoned_time(const char* name,
1526
- const sys_time<Duration>& st)
1527
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), st)
1528
- {}
1529
-
1530
- template <class Duration, class TimeZonePtr>
1531
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1532
- template <class T, class>
1533
- #endif
1534
- inline
1535
- zoned_time<Duration, TimeZonePtr>::zoned_time(const std::string& name,
1536
- const local_time<Duration>& t)
1537
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), t)
1538
- {}
1539
-
1540
- template <class Duration, class TimeZonePtr>
1541
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1542
- template <class T, class>
1543
- #endif
1544
- inline
1545
- zoned_time<Duration, TimeZonePtr>::zoned_time(const char* name,
1546
- const local_time<Duration>& t)
1547
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), t)
1548
- {}
1549
-
1550
- template <class Duration, class TimeZonePtr>
1551
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1552
- template <class T, class>
1553
- #endif
1554
- inline
1555
- zoned_time<Duration, TimeZonePtr>::zoned_time(const std::string& name,
1556
- const local_time<Duration>& t, choose c)
1557
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), t, c)
1558
- {}
1559
-
1560
- template <class Duration, class TimeZonePtr>
1561
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1562
- template <class T, class>
1563
- #endif
1564
- inline
1565
- zoned_time<Duration, TimeZonePtr>::zoned_time(const char* name,
1566
- const local_time<Duration>& t, choose c)
1567
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), t, c)
1568
- {}
1569
-
1570
- template <class Duration, class TimeZonePtr>
1571
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1572
- template <class Duration2, class TimeZonePtr2, class, class>
1573
- #else
1574
- template <class Duration2, class TimeZonePtr2>
1575
- #endif
1576
- inline
1577
- zoned_time<Duration, TimeZonePtr>::zoned_time(const std::string& name,
1578
- const zoned_time<Duration2, TimeZonePtr2>& zt)
1579
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), zt)
1580
- {}
1581
-
1582
- template <class Duration, class TimeZonePtr>
1583
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1584
- template <class Duration2, class TimeZonePtr2, class, class>
1585
- #else
1586
- template <class Duration2, class TimeZonePtr2>
1587
- #endif
1588
- inline
1589
- zoned_time<Duration, TimeZonePtr>::zoned_time(const char* name,
1590
- const zoned_time<Duration2, TimeZonePtr2>& zt)
1591
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), zt)
1592
- {}
1593
-
1594
- template <class Duration, class TimeZonePtr>
1595
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1596
- template <class Duration2, class TimeZonePtr2, class, class>
1597
- #else
1598
- template <class Duration2, class TimeZonePtr2>
1599
- #endif
1600
- inline
1601
- zoned_time<Duration, TimeZonePtr>::zoned_time(const std::string& name,
1602
- const zoned_time<Duration2, TimeZonePtr2>& zt,
1603
- choose c)
1604
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), zt, c)
1605
- {}
1606
-
1607
- template <class Duration, class TimeZonePtr>
1608
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1609
- template <class Duration2, class TimeZonePtr2, class, class>
1610
- #else
1611
- template <class Duration2, class TimeZonePtr2>
1612
- #endif
1613
- inline
1614
- zoned_time<Duration, TimeZonePtr>::zoned_time(const char* name,
1615
- const zoned_time<Duration2, TimeZonePtr2>& zt,
1616
- choose c)
1617
- : zoned_time(zoned_traits<TimeZonePtr>::locate_zone(name), zt, c)
1618
- {}
1619
-
1620
- #endif // HAS_STRING_VIEW
1621
-
1622
- template <class Duration, class TimeZonePtr>
1623
- inline
1624
- zoned_time<Duration, TimeZonePtr>&
1625
- zoned_time<Duration, TimeZonePtr>::operator=(const sys_time<Duration>& st)
1626
- {
1627
- tp_ = st;
1628
- return *this;
1629
- }
1630
-
1631
- template <class Duration, class TimeZonePtr>
1632
- inline
1633
- zoned_time<Duration, TimeZonePtr>&
1634
- zoned_time<Duration, TimeZonePtr>::operator=(const local_time<Duration>& ut)
1635
- {
1636
- tp_ = zone_->to_sys(ut);
1637
- return *this;
1638
- }
1639
-
1640
- template <class Duration, class TimeZonePtr>
1641
- inline
1642
- zoned_time<Duration, TimeZonePtr>::operator local_time<typename zoned_time<Duration, TimeZonePtr>::duration>() const
1643
- {
1644
- return get_local_time();
1645
- }
1646
-
1647
- template <class Duration, class TimeZonePtr>
1648
- inline
1649
- zoned_time<Duration, TimeZonePtr>::operator sys_time<typename zoned_time<Duration, TimeZonePtr>::duration>() const
1650
- {
1651
- return get_sys_time();
1652
- }
1653
-
1654
- template <class Duration, class TimeZonePtr>
1655
- inline
1656
- TimeZonePtr
1657
- zoned_time<Duration, TimeZonePtr>::get_time_zone() const
1658
- {
1659
- return zone_;
1660
- }
1661
-
1662
- template <class Duration, class TimeZonePtr>
1663
- inline
1664
- local_time<typename zoned_time<Duration, TimeZonePtr>::duration>
1665
- zoned_time<Duration, TimeZonePtr>::get_local_time() const
1666
- {
1667
- return zone_->to_local(tp_);
1668
- }
1669
-
1670
- template <class Duration, class TimeZonePtr>
1671
- inline
1672
- sys_time<typename zoned_time<Duration, TimeZonePtr>::duration>
1673
- zoned_time<Duration, TimeZonePtr>::get_sys_time() const
1674
- {
1675
- return tp_;
1676
- }
1677
-
1678
- template <class Duration, class TimeZonePtr>
1679
- inline
1680
- sys_info
1681
- zoned_time<Duration, TimeZonePtr>::get_info() const
1682
- {
1683
- return zone_->get_info(tp_);
1684
- }
1685
-
1686
- // make_zoned_time
1687
-
1688
- inline
1689
- zoned_time<std::chrono::seconds>
1690
- make_zoned()
1691
- {
1692
- return zoned_time<std::chrono::seconds>();
1693
- }
1694
-
1695
- template <class Duration>
1696
- inline
1697
- zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type>
1698
- make_zoned(const sys_time<Duration>& tp)
1699
- {
1700
- return zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type>(tp);
1701
- }
1702
-
1703
- template <class TimeZonePtr
1704
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1705
- #if !defined(__INTEL_COMPILER) || (__INTEL_COMPILER > 1600)
1706
- , class = typename std::enable_if
1707
- <
1708
- std::is_class
1709
- <
1710
- typename std::decay
1711
- <
1712
- decltype(*detail::to_raw_pointer(std::declval<TimeZonePtr&>()))
1713
- >::type
1714
- >{}
1715
- >::type
1716
- #endif
1717
- #endif
1718
- >
1719
- inline
1720
- zoned_time<std::chrono::seconds, TimeZonePtr>
1721
- make_zoned(TimeZonePtr z)
1722
- {
1723
- return zoned_time<std::chrono::seconds, TimeZonePtr>(std::move(z));
1724
- }
1725
-
1726
- inline
1727
- zoned_seconds
1728
- make_zoned(const std::string& name)
1729
- {
1730
- return zoned_seconds(name);
1731
- }
1732
-
1733
- template <class Duration, class TimeZonePtr
1734
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1735
- #if !defined(__INTEL_COMPILER) || (__INTEL_COMPILER > 1600)
1736
- , class = typename std::enable_if
1737
- <
1738
- std::is_class<typename std::decay<decltype(*std::declval<TimeZonePtr&>())>::type>{}
1739
- >::type
1740
- #endif
1741
- #endif
1742
- >
1743
- inline
1744
- zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type, TimeZonePtr>
1745
- make_zoned(TimeZonePtr zone, const local_time<Duration>& tp)
1746
- {
1747
- return zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type,
1748
- TimeZonePtr>(std::move(zone), tp);
1749
- }
1750
-
1751
- template <class Duration, class TimeZonePtr
1752
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1753
- #if !defined(__INTEL_COMPILER) || (__INTEL_COMPILER > 1600)
1754
- , class = typename std::enable_if
1755
- <
1756
- std::is_class<typename std::decay<decltype(*std::declval<TimeZonePtr&>())>::type>{}
1757
- >::type
1758
- #endif
1759
- #endif
1760
- >
1761
- inline
1762
- zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type, TimeZonePtr>
1763
- make_zoned(TimeZonePtr zone, const local_time<Duration>& tp, choose c)
1764
- {
1765
- return zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type,
1766
- TimeZonePtr>(std::move(zone), tp, c);
1767
- }
1768
-
1769
- template <class Duration>
1770
- inline
1771
- zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type>
1772
- make_zoned(const std::string& name, const local_time<Duration>& tp)
1773
- {
1774
- return zoned_time<typename std::common_type<Duration,
1775
- std::chrono::seconds>::type>(name, tp);
1776
- }
1777
-
1778
- template <class Duration>
1779
- inline
1780
- zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type>
1781
- make_zoned(const std::string& name, const local_time<Duration>& tp, choose c)
1782
- {
1783
- return zoned_time<typename std::common_type<Duration,
1784
- std::chrono::seconds>::type>(name, tp, c);
1785
- }
1786
-
1787
- template <class Duration, class TimeZonePtr>
1788
- inline
1789
- zoned_time<Duration, TimeZonePtr>
1790
- make_zoned(TimeZonePtr zone, const zoned_time<Duration, TimeZonePtr>& zt)
1791
- {
1792
- return zoned_time<Duration, TimeZonePtr>(std::move(zone), zt);
1793
- }
1794
-
1795
- template <class Duration, class TimeZonePtr>
1796
- inline
1797
- zoned_time<Duration, TimeZonePtr>
1798
- make_zoned(const std::string& name, const zoned_time<Duration, TimeZonePtr>& zt)
1799
- {
1800
- return zoned_time<Duration, TimeZonePtr>(name, zt);
1801
- }
1802
-
1803
- template <class Duration, class TimeZonePtr>
1804
- inline
1805
- zoned_time<Duration, TimeZonePtr>
1806
- make_zoned(TimeZonePtr zone, const zoned_time<Duration, TimeZonePtr>& zt, choose c)
1807
- {
1808
- return zoned_time<Duration, TimeZonePtr>(std::move(zone), zt, c);
1809
- }
1810
-
1811
- template <class Duration, class TimeZonePtr>
1812
- inline
1813
- zoned_time<Duration, TimeZonePtr>
1814
- make_zoned(const std::string& name, const zoned_time<Duration, TimeZonePtr>& zt, choose c)
1815
- {
1816
- return zoned_time<Duration, TimeZonePtr>(name, zt, c);
1817
- }
1818
-
1819
- template <class Duration, class TimeZonePtr
1820
- #if !defined(_MSC_VER) || (_MSC_VER > 1916)
1821
- #if !defined(__INTEL_COMPILER) || (__INTEL_COMPILER > 1600)
1822
- , class = typename std::enable_if
1823
- <
1824
- std::is_class<typename std::decay<decltype(*std::declval<TimeZonePtr&>())>::type>{}
1825
- >::type
1826
- #endif
1827
- #endif
1828
- >
1829
- inline
1830
- zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type, TimeZonePtr>
1831
- make_zoned(TimeZonePtr zone, const sys_time<Duration>& st)
1832
- {
1833
- return zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type,
1834
- TimeZonePtr>(std::move(zone), st);
1835
- }
1836
-
1837
- template <class Duration>
1838
- inline
1839
- zoned_time<typename std::common_type<Duration, std::chrono::seconds>::type>
1840
- make_zoned(const std::string& name, const sys_time<Duration>& st)
1841
- {
1842
- return zoned_time<typename std::common_type<Duration,
1843
- std::chrono::seconds>::type>(name, st);
1844
- }
1845
-
1846
- template <class CharT, class Traits, class Duration, class TimeZonePtr>
1847
- std::basic_ostream<CharT, Traits>&
1848
- to_stream(std::basic_ostream<CharT, Traits>& os, const CharT* fmt,
1849
- const zoned_time<Duration, TimeZonePtr>& tp)
1850
- {
1851
- using duration = typename zoned_time<Duration, TimeZonePtr>::duration;
1852
- using LT = local_time<duration>;
1853
- auto const st = tp.get_sys_time();
1854
- auto const info = tp.get_time_zone()->get_info(st);
1855
- return to_stream(os, fmt, LT{(st+info.offset).time_since_epoch()},
1856
- &info.abbrev, &info.offset);
1857
- }
1858
-
1859
- template <class CharT, class Traits, class Duration, class TimeZonePtr>
1860
- inline
1861
- std::basic_ostream<CharT, Traits>&
1862
- operator<<(std::basic_ostream<CharT, Traits>& os, const zoned_time<Duration, TimeZonePtr>& t)
1863
- {
1864
- const CharT fmt[] = {'%', 'F', ' ', '%', 'T', ' ', '%', 'Z', CharT{}};
1865
- return to_stream(os, fmt, t);
1866
- }
1867
-
1868
- class utc_clock
1869
- {
1870
- public:
1871
- using duration = std::chrono::system_clock::duration;
1872
- using rep = duration::rep;
1873
- using period = duration::period;
1874
- using time_point = std::chrono::time_point<utc_clock>;
1875
- static CONSTDATA bool is_steady = false;
1876
-
1877
- static time_point now();
1878
-
1879
- template<typename Duration>
1880
- static
1881
- std::chrono::time_point<std::chrono::system_clock, typename std::common_type<Duration, std::chrono::seconds>::type>
1882
- to_sys(const std::chrono::time_point<utc_clock, Duration>&);
1883
-
1884
- template<typename Duration>
1885
- static
1886
- std::chrono::time_point<utc_clock, typename std::common_type<Duration, std::chrono::seconds>::type>
1887
- from_sys(const std::chrono::time_point<std::chrono::system_clock, Duration>&);
1888
-
1889
- template<typename Duration>
1890
- static
1891
- std::chrono::time_point<local_t, typename std::common_type<Duration, std::chrono::seconds>::type>
1892
- to_local(const std::chrono::time_point<utc_clock, Duration>&);
1893
-
1894
- template<typename Duration>
1895
- static
1896
- std::chrono::time_point<utc_clock, typename std::common_type<Duration, std::chrono::seconds>::type>
1897
- from_local(const std::chrono::time_point<local_t, Duration>&);
1898
- };
1899
-
1900
- template <class Duration>
1901
- using utc_time = std::chrono::time_point<utc_clock, Duration>;
1902
-
1903
- using utc_seconds = utc_time<std::chrono::seconds>;
1904
-
1905
- template <class Duration>
1906
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
1907
- utc_clock::from_sys(const sys_time<Duration>& st)
1908
- {
1909
- using std::chrono::seconds;
1910
- using CD = typename std::common_type<Duration, seconds>::type;
1911
- auto const& leaps = get_tzdb().leap_seconds;
1912
- auto const lt = std::upper_bound(leaps.begin(), leaps.end(), st);
1913
- return utc_time<CD>{st.time_since_epoch() + seconds{lt-leaps.begin()}};
1914
- }
1915
-
1916
- // Return pair<is_leap_second, seconds{number_of_leap_seconds_since_1970}>
1917
- // first is true if ut is during a leap second insertion, otherwise false.
1918
- // If ut is during a leap second insertion, that leap second is included in the count
1919
- template <class Duration>
1920
- std::pair<bool, std::chrono::seconds>
1921
- is_leap_second(date::utc_time<Duration> const& ut)
1922
- {
1923
- using std::chrono::seconds;
1924
- using duration = typename std::common_type<Duration, seconds>::type;
1925
- auto const& leaps = get_tzdb().leap_seconds;
1926
- auto tp = sys_time<duration>{ut.time_since_epoch()};
1927
- auto const lt = std::upper_bound(leaps.begin(), leaps.end(), tp);
1928
- auto ds = seconds{lt-leaps.begin()};
1929
- tp -= ds;
1930
- auto ls = false;
1931
- if (lt > leaps.begin())
1932
- {
1933
- if (tp < lt[-1])
1934
- {
1935
- if (tp >= lt[-1].date() - seconds{1})
1936
- ls = true;
1937
- else
1938
- --ds;
1939
- }
1940
- }
1941
- return {ls, ds};
1942
- }
1943
-
1944
- struct leap_second_info
1945
- {
1946
- bool is_leap_second;
1947
- std::chrono::seconds elapsed;
1948
- };
1949
-
1950
- template <class Duration>
1951
- leap_second_info
1952
- get_leap_second_info(date::utc_time<Duration> const& ut)
1953
- {
1954
- auto p = is_leap_second(ut);
1955
- return {p.first, p.second};
1956
- }
1957
-
1958
- template <class Duration>
1959
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
1960
- utc_clock::to_sys(const utc_time<Duration>& ut)
1961
- {
1962
- using std::chrono::seconds;
1963
- using CD = typename std::common_type<Duration, seconds>::type;
1964
- auto ls = is_leap_second(ut);
1965
- auto tp = sys_time<CD>{ut.time_since_epoch() - ls.second};
1966
- if (ls.first)
1967
- tp = floor<seconds>(tp) + seconds{1} - CD{1};
1968
- return tp;
1969
- }
1970
-
1971
- inline
1972
- utc_clock::time_point
1973
- utc_clock::now()
1974
- {
1975
- return from_sys(std::chrono::system_clock::now());
1976
- }
1977
-
1978
- template <class Duration>
1979
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
1980
- utc_clock::from_local(const local_time<Duration>& st)
1981
- {
1982
- return from_sys(sys_time<Duration>{st.time_since_epoch()});
1983
- }
1984
-
1985
- template <class Duration>
1986
- local_time<typename std::common_type<Duration, std::chrono::seconds>::type>
1987
- utc_clock::to_local(const utc_time<Duration>& ut)
1988
- {
1989
- using CD = typename std::common_type<Duration, std::chrono::seconds>::type;
1990
- return local_time<CD>{to_sys(ut).time_since_epoch()};
1991
- }
1992
-
1993
- template <class CharT, class Traits, class Duration>
1994
- std::basic_ostream<CharT, Traits>&
1995
- to_stream(std::basic_ostream<CharT, Traits>& os, const CharT* fmt,
1996
- const utc_time<Duration>& t)
1997
- {
1998
- using std::chrono::seconds;
1999
- using CT = typename std::common_type<Duration, seconds>::type;
2000
- const std::string abbrev("UTC");
2001
- CONSTDATA seconds offset{0};
2002
- auto ls = is_leap_second(t);
2003
- auto tp = sys_time<CT>{t.time_since_epoch() - ls.second};
2004
- auto const sd = floor<days>(tp);
2005
- year_month_day ymd = sd;
2006
- auto time = make_time(tp - sys_seconds{sd});
2007
- time.seconds(detail::undocumented{}) += seconds{ls.first};
2008
- fields<CT> fds{ymd, time};
2009
- return to_stream(os, fmt, fds, &abbrev, &offset);
2010
- }
2011
-
2012
- template <class CharT, class Traits, class Duration>
2013
- std::basic_ostream<CharT, Traits>&
2014
- operator<<(std::basic_ostream<CharT, Traits>& os, const utc_time<Duration>& t)
2015
- {
2016
- const CharT fmt[] = {'%', 'F', ' ', '%', 'T', CharT{}};
2017
- return to_stream(os, fmt, t);
2018
- }
2019
-
2020
- template <class Duration, class CharT, class Traits, class Alloc = std::allocator<CharT>>
2021
- std::basic_istream<CharT, Traits>&
2022
- from_stream(std::basic_istream<CharT, Traits>& is, const CharT* fmt,
2023
- utc_time<Duration>& tp, std::basic_string<CharT, Traits, Alloc>* abbrev = nullptr,
2024
- std::chrono::minutes* offset = nullptr)
2025
- {
2026
- using std::chrono::seconds;
2027
- using std::chrono::minutes;
2028
- using CT = typename std::common_type<Duration, seconds>::type;
2029
- minutes offset_local{};
2030
- auto offptr = offset ? offset : &offset_local;
2031
- fields<CT> fds{};
2032
- fds.has_tod = true;
2033
- from_stream(is, fmt, fds, abbrev, offptr);
2034
- if (!fds.ymd.ok())
2035
- is.setstate(std::ios::failbit);
2036
- if (!is.fail())
2037
- {
2038
- bool is_60_sec = fds.tod.seconds() == seconds{60};
2039
- if (is_60_sec)
2040
- fds.tod.seconds(detail::undocumented{}) -= seconds{1};
2041
- auto tmp = utc_clock::from_sys(sys_days(fds.ymd) - *offptr + fds.tod.to_duration());
2042
- if (is_60_sec)
2043
- tmp += seconds{1};
2044
- if (is_60_sec != is_leap_second(tmp).first || !fds.tod.in_conventional_range())
2045
- {
2046
- is.setstate(std::ios::failbit);
2047
- return is;
2048
- }
2049
- tp = std::chrono::time_point_cast<Duration>(tmp);
2050
- }
2051
- return is;
2052
- }
2053
-
2054
- // tai_clock
2055
-
2056
- class tai_clock
2057
- {
2058
- public:
2059
- using duration = std::chrono::system_clock::duration;
2060
- using rep = duration::rep;
2061
- using period = duration::period;
2062
- using time_point = std::chrono::time_point<tai_clock>;
2063
- static const bool is_steady = false;
2064
-
2065
- static time_point now();
2066
-
2067
- template<typename Duration>
2068
- static
2069
- std::chrono::time_point<utc_clock, typename std::common_type<Duration, std::chrono::seconds>::type>
2070
- to_utc(const std::chrono::time_point<tai_clock, Duration>&) NOEXCEPT;
2071
-
2072
- template<typename Duration>
2073
- static
2074
- std::chrono::time_point<tai_clock, typename std::common_type<Duration, std::chrono::seconds>::type>
2075
- from_utc(const std::chrono::time_point<utc_clock, Duration>&) NOEXCEPT;
2076
-
2077
- template<typename Duration>
2078
- static
2079
- std::chrono::time_point<local_t, typename std::common_type<Duration, date::days>::type>
2080
- to_local(const std::chrono::time_point<tai_clock, Duration>&) NOEXCEPT;
2081
-
2082
- template<typename Duration>
2083
- static
2084
- std::chrono::time_point<tai_clock, typename std::common_type<Duration, date::days>::type>
2085
- from_local(const std::chrono::time_point<local_t, Duration>&) NOEXCEPT;
2086
- };
2087
-
2088
- template <class Duration>
2089
- using tai_time = std::chrono::time_point<tai_clock, Duration>;
2090
-
2091
- using tai_seconds = tai_time<std::chrono::seconds>;
2092
-
2093
- template <class Duration>
2094
- inline
2095
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2096
- tai_clock::to_utc(const tai_time<Duration>& t) NOEXCEPT
2097
- {
2098
- using std::chrono::seconds;
2099
- using CD = typename std::common_type<Duration, seconds>::type;
2100
- return utc_time<CD>{t.time_since_epoch()} -
2101
- (sys_days(year{1970}/January/1) - sys_days(year{1958}/January/1) + seconds{10});
2102
- }
2103
-
2104
- template <class Duration>
2105
- inline
2106
- tai_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2107
- tai_clock::from_utc(const utc_time<Duration>& t) NOEXCEPT
2108
- {
2109
- using std::chrono::seconds;
2110
- using CD = typename std::common_type<Duration, seconds>::type;
2111
- return tai_time<CD>{t.time_since_epoch()} +
2112
- (sys_days(year{1970}/January/1) - sys_days(year{1958}/January/1) + seconds{10});
2113
- }
2114
-
2115
- inline
2116
- tai_clock::time_point
2117
- tai_clock::now()
2118
- {
2119
- return from_utc(utc_clock::now());
2120
- }
2121
-
2122
- template <class Duration>
2123
- inline
2124
- local_time<typename std::common_type<Duration, date::days>::type>
2125
- tai_clock::to_local(const tai_time<Duration>& t) NOEXCEPT
2126
- {
2127
- using CD = typename std::common_type<Duration, date::days>::type;
2128
- return local_time<CD>{t.time_since_epoch()} -
2129
- (local_days(year{1970}/January/1) - local_days(year{1958}/January/1));
2130
- }
2131
-
2132
- template <class Duration>
2133
- inline
2134
- tai_time<typename std::common_type<Duration, date::days>::type>
2135
- tai_clock::from_local(const local_time<Duration>& t) NOEXCEPT
2136
- {
2137
- using CD = typename std::common_type<Duration, date::days>::type;
2138
- return tai_time<CD>{t.time_since_epoch()} +
2139
- (local_days(year{1970}/January/1) - local_days(year{1958}/January/1));
2140
- }
2141
-
2142
- template <class CharT, class Traits, class Duration>
2143
- std::basic_ostream<CharT, Traits>&
2144
- to_stream(std::basic_ostream<CharT, Traits>& os, const CharT* fmt,
2145
- const tai_time<Duration>& t)
2146
- {
2147
- const std::string abbrev("TAI");
2148
- CONSTDATA std::chrono::seconds offset{0};
2149
- return to_stream(os, fmt, tai_clock::to_local(t), &abbrev, &offset);
2150
- }
2151
-
2152
- template <class CharT, class Traits, class Duration>
2153
- std::basic_ostream<CharT, Traits>&
2154
- operator<<(std::basic_ostream<CharT, Traits>& os, const tai_time<Duration>& t)
2155
- {
2156
- const CharT fmt[] = {'%', 'F', ' ', '%', 'T', CharT{}};
2157
- return to_stream(os, fmt, t);
2158
- }
2159
-
2160
- template <class Duration, class CharT, class Traits, class Alloc = std::allocator<CharT>>
2161
- std::basic_istream<CharT, Traits>&
2162
- from_stream(std::basic_istream<CharT, Traits>& is, const CharT* fmt,
2163
- tai_time<Duration>& tp,
2164
- std::basic_string<CharT, Traits, Alloc>* abbrev = nullptr,
2165
- std::chrono::minutes* offset = nullptr)
2166
- {
2167
- local_time<Duration> lp;
2168
- from_stream(is, fmt, lp, abbrev, offset);
2169
- if (!is.fail())
2170
- tp = tai_clock::from_local(lp);
2171
- return is;
2172
- }
2173
-
2174
- // gps_clock
2175
-
2176
- class gps_clock
2177
- {
2178
- public:
2179
- using duration = std::chrono::system_clock::duration;
2180
- using rep = duration::rep;
2181
- using period = duration::period;
2182
- using time_point = std::chrono::time_point<gps_clock>;
2183
- static const bool is_steady = false;
2184
-
2185
- static time_point now();
2186
-
2187
- template<typename Duration>
2188
- static
2189
- std::chrono::time_point<utc_clock, typename std::common_type<Duration, std::chrono::seconds>::type>
2190
- to_utc(const std::chrono::time_point<gps_clock, Duration>&) NOEXCEPT;
2191
-
2192
- template<typename Duration>
2193
- static
2194
- std::chrono::time_point<gps_clock, typename std::common_type<Duration, std::chrono::seconds>::type>
2195
- from_utc(const std::chrono::time_point<utc_clock, Duration>&) NOEXCEPT;
2196
-
2197
- template<typename Duration>
2198
- static
2199
- std::chrono::time_point<local_t, typename std::common_type<Duration, date::days>::type>
2200
- to_local(const std::chrono::time_point<gps_clock, Duration>&) NOEXCEPT;
2201
-
2202
- template<typename Duration>
2203
- static
2204
- std::chrono::time_point<gps_clock, typename std::common_type<Duration, date::days>::type>
2205
- from_local(const std::chrono::time_point<local_t, Duration>&) NOEXCEPT;
2206
- };
2207
-
2208
- template <class Duration>
2209
- using gps_time = std::chrono::time_point<gps_clock, Duration>;
2210
-
2211
- using gps_seconds = gps_time<std::chrono::seconds>;
2212
-
2213
- template <class Duration>
2214
- inline
2215
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2216
- gps_clock::to_utc(const gps_time<Duration>& t) NOEXCEPT
2217
- {
2218
- using std::chrono::seconds;
2219
- using CD = typename std::common_type<Duration, seconds>::type;
2220
- return utc_time<CD>{t.time_since_epoch()} +
2221
- (sys_days(year{1980}/January/Sunday[1]) - sys_days(year{1970}/January/1) +
2222
- seconds{9});
2223
- }
2224
-
2225
- template <class Duration>
2226
- inline
2227
- gps_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2228
- gps_clock::from_utc(const utc_time<Duration>& t) NOEXCEPT
2229
- {
2230
- using std::chrono::seconds;
2231
- using CD = typename std::common_type<Duration, seconds>::type;
2232
- return gps_time<CD>{t.time_since_epoch()} -
2233
- (sys_days(year{1980}/January/Sunday[1]) - sys_days(year{1970}/January/1) +
2234
- seconds{9});
2235
- }
2236
-
2237
- inline
2238
- gps_clock::time_point
2239
- gps_clock::now()
2240
- {
2241
- return from_utc(utc_clock::now());
2242
- }
2243
-
2244
- template <class Duration>
2245
- inline
2246
- local_time<typename std::common_type<Duration, date::days>::type>
2247
- gps_clock::to_local(const gps_time<Duration>& t) NOEXCEPT
2248
- {
2249
- using CD = typename std::common_type<Duration, date::days>::type;
2250
- return local_time<CD>{t.time_since_epoch()} +
2251
- (local_days(year{1980}/January/Sunday[1]) - local_days(year{1970}/January/1));
2252
- }
2253
-
2254
- template <class Duration>
2255
- inline
2256
- gps_time<typename std::common_type<Duration, date::days>::type>
2257
- gps_clock::from_local(const local_time<Duration>& t) NOEXCEPT
2258
- {
2259
- using CD = typename std::common_type<Duration, date::days>::type;
2260
- return gps_time<CD>{t.time_since_epoch()} -
2261
- (local_days(year{1980}/January/Sunday[1]) - local_days(year{1970}/January/1));
2262
- }
2263
-
2264
-
2265
- template <class CharT, class Traits, class Duration>
2266
- std::basic_ostream<CharT, Traits>&
2267
- to_stream(std::basic_ostream<CharT, Traits>& os, const CharT* fmt,
2268
- const gps_time<Duration>& t)
2269
- {
2270
- const std::string abbrev("GPS");
2271
- CONSTDATA std::chrono::seconds offset{0};
2272
- return to_stream(os, fmt, gps_clock::to_local(t), &abbrev, &offset);
2273
- }
2274
-
2275
- template <class CharT, class Traits, class Duration>
2276
- std::basic_ostream<CharT, Traits>&
2277
- operator<<(std::basic_ostream<CharT, Traits>& os, const gps_time<Duration>& t)
2278
- {
2279
- const CharT fmt[] = {'%', 'F', ' ', '%', 'T', CharT{}};
2280
- return to_stream(os, fmt, t);
2281
- }
2282
-
2283
- template <class Duration, class CharT, class Traits, class Alloc = std::allocator<CharT>>
2284
- std::basic_istream<CharT, Traits>&
2285
- from_stream(std::basic_istream<CharT, Traits>& is, const CharT* fmt,
2286
- gps_time<Duration>& tp,
2287
- std::basic_string<CharT, Traits, Alloc>* abbrev = nullptr,
2288
- std::chrono::minutes* offset = nullptr)
2289
- {
2290
- local_time<Duration> lp;
2291
- from_stream(is, fmt, lp, abbrev, offset);
2292
- if (!is.fail())
2293
- tp = gps_clock::from_local(lp);
2294
- return is;
2295
- }
2296
-
2297
- // clock_time_conversion
2298
-
2299
- template <class DstClock, class SrcClock>
2300
- struct clock_time_conversion
2301
- {};
2302
-
2303
- template <>
2304
- struct clock_time_conversion<std::chrono::system_clock, std::chrono::system_clock>
2305
- {
2306
- template <class Duration>
2307
- CONSTCD14
2308
- sys_time<Duration>
2309
- operator()(const sys_time<Duration>& st) const
2310
- {
2311
- return st;
2312
- }
2313
- };
2314
-
2315
- template <>
2316
- struct clock_time_conversion<utc_clock, utc_clock>
2317
- {
2318
- template <class Duration>
2319
- CONSTCD14
2320
- utc_time<Duration>
2321
- operator()(const utc_time<Duration>& ut) const
2322
- {
2323
- return ut;
2324
- }
2325
- };
2326
-
2327
- template<>
2328
- struct clock_time_conversion<local_t, local_t>
2329
- {
2330
- template <class Duration>
2331
- CONSTCD14
2332
- local_time<Duration>
2333
- operator()(const local_time<Duration>& lt) const
2334
- {
2335
- return lt;
2336
- }
2337
- };
2338
-
2339
- template <>
2340
- struct clock_time_conversion<utc_clock, std::chrono::system_clock>
2341
- {
2342
- template <class Duration>
2343
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2344
- operator()(const sys_time<Duration>& st) const
2345
- {
2346
- return utc_clock::from_sys(st);
2347
- }
2348
- };
2349
-
2350
- template <>
2351
- struct clock_time_conversion<std::chrono::system_clock, utc_clock>
2352
- {
2353
- template <class Duration>
2354
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2355
- operator()(const utc_time<Duration>& ut) const
2356
- {
2357
- return utc_clock::to_sys(ut);
2358
- }
2359
- };
2360
-
2361
- template<>
2362
- struct clock_time_conversion<local_t, std::chrono::system_clock>
2363
- {
2364
- template <class Duration>
2365
- CONSTCD14
2366
- local_time<Duration>
2367
- operator()(const sys_time<Duration>& st) const
2368
- {
2369
- return local_time<Duration>{st.time_since_epoch()};
2370
- }
2371
- };
2372
-
2373
- template<>
2374
- struct clock_time_conversion<std::chrono::system_clock, local_t>
2375
- {
2376
- template <class Duration>
2377
- CONSTCD14
2378
- sys_time<Duration>
2379
- operator()(const local_time<Duration>& lt) const
2380
- {
2381
- return sys_time<Duration>{lt.time_since_epoch()};
2382
- }
2383
- };
2384
-
2385
- template<>
2386
- struct clock_time_conversion<utc_clock, local_t>
2387
- {
2388
- template <class Duration>
2389
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2390
- operator()(const local_time<Duration>& lt) const
2391
- {
2392
- return utc_clock::from_local(lt);
2393
- }
2394
- };
2395
-
2396
- template<>
2397
- struct clock_time_conversion<local_t, utc_clock>
2398
- {
2399
- template <class Duration>
2400
- local_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2401
- operator()(const utc_time<Duration>& ut) const
2402
- {
2403
- return utc_clock::to_local(ut);
2404
- }
2405
- };
2406
-
2407
- template<typename Clock>
2408
- struct clock_time_conversion<Clock, Clock>
2409
- {
2410
- template <class Duration>
2411
- CONSTCD14
2412
- std::chrono::time_point<Clock, Duration>
2413
- operator()(const std::chrono::time_point<Clock, Duration>& tp) const
2414
- {
2415
- return tp;
2416
- }
2417
- };
2418
-
2419
- namespace ctc_detail
2420
- {
2421
-
2422
- template <class Clock, class Duration>
2423
- using time_point = std::chrono::time_point<Clock, Duration>;
2424
-
2425
- using std::declval;
2426
- using std::chrono::system_clock;
2427
-
2428
- //Check if TimePoint is time for given clock,
2429
- //if not emits hard error
2430
- template <class Clock, class TimePoint>
2431
- struct return_clock_time
2432
- {
2433
- using clock_time_point = time_point<Clock, typename TimePoint::duration>;
2434
- using type = TimePoint;
2435
-
2436
- static_assert(std::is_same<TimePoint, clock_time_point>::value,
2437
- "time point with appropariate clock shall be returned");
2438
- };
2439
-
2440
- // Check if Clock has to_sys method accepting TimePoint with given duration const& and
2441
- // returning sys_time. If so has nested type member equal to return type to_sys.
2442
- template <class Clock, class Duration, class = void>
2443
- struct return_to_sys
2444
- {};
2445
-
2446
- template <class Clock, class Duration>
2447
- struct return_to_sys
2448
- <
2449
- Clock, Duration,
2450
- decltype(Clock::to_sys(declval<time_point<Clock, Duration> const&>()), void())
2451
- >
2452
- : return_clock_time
2453
- <
2454
- system_clock,
2455
- decltype(Clock::to_sys(declval<time_point<Clock, Duration> const&>()))
2456
- >
2457
- {};
2458
-
2459
- // Similiar to above
2460
- template <class Clock, class Duration, class = void>
2461
- struct return_from_sys
2462
- {};
2463
-
2464
- template <class Clock, class Duration>
2465
- struct return_from_sys
2466
- <
2467
- Clock, Duration,
2468
- decltype(Clock::from_sys(declval<time_point<system_clock, Duration> const&>()),
2469
- void())
2470
- >
2471
- : return_clock_time
2472
- <
2473
- Clock,
2474
- decltype(Clock::from_sys(declval<time_point<system_clock, Duration> const&>()))
2475
- >
2476
- {};
2477
-
2478
- // Similiar to above
2479
- template <class Clock, class Duration, class = void>
2480
- struct return_to_utc
2481
- {};
2482
-
2483
- template <class Clock, class Duration>
2484
- struct return_to_utc
2485
- <
2486
- Clock, Duration,
2487
- decltype(Clock::to_utc(declval<time_point<Clock, Duration> const&>()), void())
2488
- >
2489
- : return_clock_time
2490
- <
2491
- utc_clock,
2492
- decltype(Clock::to_utc(declval<time_point<Clock, Duration> const&>()))>
2493
- {};
2494
-
2495
- // Similiar to above
2496
- template <class Clock, class Duration, class = void>
2497
- struct return_from_utc
2498
- {};
2499
-
2500
- template <class Clock, class Duration>
2501
- struct return_from_utc
2502
- <
2503
- Clock, Duration,
2504
- decltype(Clock::from_utc(declval<time_point<utc_clock, Duration> const&>()),
2505
- void())
2506
- >
2507
- : return_clock_time
2508
- <
2509
- Clock,
2510
- decltype(Clock::from_utc(declval<time_point<utc_clock, Duration> const&>()))
2511
- >
2512
- {};
2513
-
2514
- // Similiar to above
2515
- template<typename Clock, typename Duration, typename = void>
2516
- struct return_to_local
2517
- {};
2518
-
2519
- template<typename Clock, typename Duration>
2520
- struct return_to_local
2521
- <
2522
- Clock, Duration,
2523
- decltype(Clock::to_local(declval<time_point<Clock, Duration> const&>()),
2524
- void())
2525
- >
2526
- : return_clock_time
2527
- <
2528
- local_t,
2529
- decltype(Clock::to_local(declval<time_point<Clock, Duration> const&>()))
2530
- >
2531
- {};
2532
-
2533
- // Similiar to above
2534
- template<typename Clock, typename Duration, typename = void>
2535
- struct return_from_local
2536
- {};
2537
-
2538
- template<typename Clock, typename Duration>
2539
- struct return_from_local
2540
- <
2541
- Clock, Duration,
2542
- decltype(Clock::from_local(declval<time_point<local_t, Duration> const&>()),
2543
- void())
2544
- >
2545
- : return_clock_time
2546
- <
2547
- Clock,
2548
- decltype(Clock::from_local(declval<time_point<local_t, Duration> const&>()))
2549
- >
2550
- {};
2551
-
2552
- } // namespace ctc_detail
2553
-
2554
- template <class SrcClock>
2555
- struct clock_time_conversion<std::chrono::system_clock, SrcClock>
2556
- {
2557
- template <class Duration>
2558
- CONSTCD14
2559
- typename ctc_detail::return_to_sys<SrcClock, Duration>::type
2560
- operator()(const std::chrono::time_point<SrcClock, Duration>& tp) const
2561
- {
2562
- return SrcClock::to_sys(tp);
2563
- }
2564
- };
2565
-
2566
- template <class DstClock>
2567
- struct clock_time_conversion<DstClock, std::chrono::system_clock>
2568
- {
2569
- template <class Duration>
2570
- CONSTCD14
2571
- typename ctc_detail::return_from_sys<DstClock, Duration>::type
2572
- operator()(const sys_time<Duration>& st) const
2573
- {
2574
- return DstClock::from_sys(st);
2575
- }
2576
- };
2577
-
2578
- template <class SrcClock>
2579
- struct clock_time_conversion<utc_clock, SrcClock>
2580
- {
2581
- template <class Duration>
2582
- CONSTCD14
2583
- typename ctc_detail::return_to_utc<SrcClock, Duration>::type
2584
- operator()(const std::chrono::time_point<SrcClock, Duration>& tp) const
2585
- {
2586
- return SrcClock::to_utc(tp);
2587
- }
2588
- };
2589
-
2590
- template <class DstClock>
2591
- struct clock_time_conversion<DstClock, utc_clock>
2592
- {
2593
- template <class Duration>
2594
- CONSTCD14
2595
- typename ctc_detail::return_from_utc<DstClock, Duration>::type
2596
- operator()(const utc_time<Duration>& ut) const
2597
- {
2598
- return DstClock::from_utc(ut);
2599
- }
2600
- };
2601
-
2602
- template<typename SrcClock>
2603
- struct clock_time_conversion<local_t, SrcClock>
2604
- {
2605
- template <class Duration>
2606
- CONSTCD14
2607
- typename ctc_detail::return_to_local<SrcClock, Duration>::type
2608
- operator()(const std::chrono::time_point<SrcClock, Duration>& tp) const
2609
- {
2610
- return SrcClock::to_local(tp);
2611
- }
2612
- };
2613
-
2614
- template<typename DstClock>
2615
- struct clock_time_conversion<DstClock, local_t>
2616
- {
2617
- template <class Duration>
2618
- CONSTCD14
2619
- typename ctc_detail::return_from_local<DstClock, Duration>::type
2620
- operator()(const local_time<Duration>& lt) const
2621
- {
2622
- return DstClock::from_local(lt);
2623
- }
2624
- };
2625
-
2626
- namespace clock_cast_detail
2627
- {
2628
-
2629
- template <class Clock, class Duration>
2630
- using time_point = std::chrono::time_point<Clock, Duration>;
2631
- using std::chrono::system_clock;
2632
-
2633
- template <class DstClock, class SrcClock, class Duration>
2634
- CONSTCD14
2635
- auto
2636
- conv_clock(const time_point<SrcClock, Duration>& t)
2637
- -> decltype(std::declval<clock_time_conversion<DstClock, SrcClock>>()(t))
2638
- {
2639
- return clock_time_conversion<DstClock, SrcClock>{}(t);
2640
- }
2641
-
2642
- //direct trait conversion, 1st candidate
2643
- template <class DstClock, class SrcClock, class Duration>
2644
- CONSTCD14
2645
- auto
2646
- cc_impl(const time_point<SrcClock, Duration>& t, const time_point<SrcClock, Duration>*)
2647
- -> decltype(conv_clock<DstClock>(t))
2648
- {
2649
- return conv_clock<DstClock>(t);
2650
- }
2651
-
2652
- //conversion through sys, 2nd candidate
2653
- template <class DstClock, class SrcClock, class Duration>
2654
- CONSTCD14
2655
- auto
2656
- cc_impl(const time_point<SrcClock, Duration>& t, const void*)
2657
- -> decltype(conv_clock<DstClock>(conv_clock<system_clock>(t)))
2658
- {
2659
- return conv_clock<DstClock>(conv_clock<system_clock>(t));
2660
- }
2661
-
2662
- //conversion through utc, 2nd candidate
2663
- template <class DstClock, class SrcClock, class Duration>
2664
- CONSTCD14
2665
- auto
2666
- cc_impl(const time_point<SrcClock, Duration>& t, const void*)
2667
- -> decltype(0, // MSVC_WORKAROUND
2668
- conv_clock<DstClock>(conv_clock<utc_clock>(t)))
2669
- {
2670
- return conv_clock<DstClock>(conv_clock<utc_clock>(t));
2671
- }
2672
-
2673
- //conversion through sys and utc, 3rd candidate
2674
- template <class DstClock, class SrcClock, class Duration>
2675
- CONSTCD14
2676
- auto
2677
- cc_impl(const time_point<SrcClock, Duration>& t, ...)
2678
- -> decltype(conv_clock<DstClock>(conv_clock<utc_clock>(conv_clock<system_clock>(t))))
2679
- {
2680
- return conv_clock<DstClock>(conv_clock<utc_clock>(conv_clock<system_clock>(t)));
2681
- }
2682
-
2683
- //conversion through utc and sys, 3rd candidate
2684
- template <class DstClock, class SrcClock, class Duration>
2685
- CONSTCD14
2686
- auto
2687
- cc_impl(const time_point<SrcClock, Duration>& t, ...)
2688
- -> decltype(0, // MSVC_WORKAROUND
2689
- conv_clock<DstClock>(conv_clock<system_clock>(conv_clock<utc_clock>(t))))
2690
- {
2691
- return conv_clock<DstClock>(conv_clock<system_clock>(conv_clock<utc_clock>(t)));
2692
- }
2693
-
2694
- } // namespace clock_cast_detail
2695
-
2696
- template <class DstClock, class SrcClock, class Duration>
2697
- CONSTCD14
2698
- auto
2699
- clock_cast(const std::chrono::time_point<SrcClock, Duration>& tp)
2700
- -> decltype(clock_cast_detail::cc_impl<DstClock>(tp, &tp))
2701
- {
2702
- return clock_cast_detail::cc_impl<DstClock>(tp, &tp);
2703
- }
2704
-
2705
- // Deprecated API
2706
-
2707
- template <class Duration>
2708
- inline
2709
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2710
- to_sys_time(const utc_time<Duration>& t)
2711
- {
2712
- return utc_clock::to_sys(t);
2713
- }
2714
-
2715
- template <class Duration>
2716
- inline
2717
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2718
- to_sys_time(const tai_time<Duration>& t)
2719
- {
2720
- return utc_clock::to_sys(tai_clock::to_utc(t));
2721
- }
2722
-
2723
- template <class Duration>
2724
- inline
2725
- sys_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2726
- to_sys_time(const gps_time<Duration>& t)
2727
- {
2728
- return utc_clock::to_sys(gps_clock::to_utc(t));
2729
- }
2730
-
2731
-
2732
- template <class Duration>
2733
- inline
2734
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2735
- to_utc_time(const sys_time<Duration>& t)
2736
- {
2737
- return utc_clock::from_sys(t);
2738
- }
2739
-
2740
- template <class Duration>
2741
- inline
2742
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2743
- to_utc_time(const tai_time<Duration>& t)
2744
- {
2745
- return tai_clock::to_utc(t);
2746
- }
2747
-
2748
- template <class Duration>
2749
- inline
2750
- utc_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2751
- to_utc_time(const gps_time<Duration>& t)
2752
- {
2753
- return gps_clock::to_utc(t);
2754
- }
2755
-
2756
-
2757
- template <class Duration>
2758
- inline
2759
- tai_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2760
- to_tai_time(const sys_time<Duration>& t)
2761
- {
2762
- return tai_clock::from_utc(utc_clock::from_sys(t));
2763
- }
2764
-
2765
- template <class Duration>
2766
- inline
2767
- tai_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2768
- to_tai_time(const utc_time<Duration>& t)
2769
- {
2770
- return tai_clock::from_utc(t);
2771
- }
2772
-
2773
- template <class Duration>
2774
- inline
2775
- tai_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2776
- to_tai_time(const gps_time<Duration>& t)
2777
- {
2778
- return tai_clock::from_utc(gps_clock::to_utc(t));
2779
- }
2780
-
2781
-
2782
- template <class Duration>
2783
- inline
2784
- gps_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2785
- to_gps_time(const sys_time<Duration>& t)
2786
- {
2787
- return gps_clock::from_utc(utc_clock::from_sys(t));
2788
- }
2789
-
2790
- template <class Duration>
2791
- inline
2792
- gps_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2793
- to_gps_time(const utc_time<Duration>& t)
2794
- {
2795
- return gps_clock::from_utc(t);
2796
- }
2797
-
2798
- template <class Duration>
2799
- inline
2800
- gps_time<typename std::common_type<Duration, std::chrono::seconds>::type>
2801
- to_gps_time(const tai_time<Duration>& t)
2802
- {
2803
- return gps_clock::from_utc(tai_clock::to_utc(t));
2804
- }
2805
-
2806
- } // namespace arrow_vendored::date
2807
-
2808
- #endif // TZ_H
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9b99fa34cb2c454490337a62a9d91f5828c1a4f1ac22d94d94fffea34a2d612e/blob DELETED
@@ -1,563 +0,0 @@
1
- """create and manipulate C data types in Python"""
2
-
3
- import os as _os, sys as _sys
4
- import types as _types
5
-
6
- __version__ = "1.1.0"
7
-
8
- from _ctypes import Union, Structure, Array
9
- from _ctypes import _Pointer
10
- from _ctypes import CFuncPtr as _CFuncPtr
11
- from _ctypes import __version__ as _ctypes_version
12
- from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
13
- from _ctypes import ArgumentError
14
-
15
- from struct import calcsize as _calcsize
16
-
17
- if __version__ != _ctypes_version:
18
- raise Exception("Version number mismatch", __version__, _ctypes_version)
19
-
20
- if _os.name == "nt":
21
- from _ctypes import FormatError
22
-
23
- DEFAULT_MODE = RTLD_LOCAL
24
- if _os.name == "posix" and _sys.platform == "darwin":
25
- # On OS X 10.3, we use RTLD_GLOBAL as default mode
26
- # because RTLD_LOCAL does not work at least on some
27
- # libraries. OS X 10.3 is Darwin 7, so we check for
28
- # that.
29
-
30
- if int(_os.uname().release.split('.')[0]) < 8:
31
- DEFAULT_MODE = RTLD_GLOBAL
32
-
33
- from _ctypes import FUNCFLAG_CDECL as _FUNCFLAG_CDECL, \
34
- FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI, \
35
- FUNCFLAG_USE_ERRNO as _FUNCFLAG_USE_ERRNO, \
36
- FUNCFLAG_USE_LASTERROR as _FUNCFLAG_USE_LASTERROR
37
-
38
- # WINOLEAPI -> HRESULT
39
- # WINOLEAPI_(type)
40
- #
41
- # STDMETHODCALLTYPE
42
- #
43
- # STDMETHOD(name)
44
- # STDMETHOD_(type, name)
45
- #
46
- # STDAPICALLTYPE
47
-
48
- def create_string_buffer(init, size=None):
49
- """create_string_buffer(aBytes) -> character array
50
- create_string_buffer(anInteger) -> character array
51
- create_string_buffer(aBytes, anInteger) -> character array
52
- """
53
- if isinstance(init, bytes):
54
- if size is None:
55
- size = len(init)+1
56
- _sys.audit("ctypes.create_string_buffer", init, size)
57
- buftype = c_char * size
58
- buf = buftype()
59
- buf.value = init
60
- return buf
61
- elif isinstance(init, int):
62
- _sys.audit("ctypes.create_string_buffer", None, init)
63
- buftype = c_char * init
64
- buf = buftype()
65
- return buf
66
- raise TypeError(init)
67
-
68
- def c_buffer(init, size=None):
69
- ## "deprecated, use create_string_buffer instead"
70
- ## import warnings
71
- ## warnings.warn("c_buffer is deprecated, use create_string_buffer instead",
72
- ## DeprecationWarning, stacklevel=2)
73
- return create_string_buffer(init, size)
74
-
75
- _c_functype_cache = {}
76
- def CFUNCTYPE(restype, *argtypes, **kw):
77
- """CFUNCTYPE(restype, *argtypes,
78
- use_errno=False, use_last_error=False) -> function prototype.
79
-
80
- restype: the result type
81
- argtypes: a sequence specifying the argument types
82
-
83
- The function prototype can be called in different ways to create a
84
- callable object:
85
-
86
- prototype(integer address) -> foreign function
87
- prototype(callable) -> create and return a C callable function from callable
88
- prototype(integer index, method name[, paramflags]) -> foreign function calling a COM method
89
- prototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinal
90
- prototype((function name, dll object)[, paramflags]) -> foreign function exported by name
91
- """
92
- flags = _FUNCFLAG_CDECL
93
- if kw.pop("use_errno", False):
94
- flags |= _FUNCFLAG_USE_ERRNO
95
- if kw.pop("use_last_error", False):
96
- flags |= _FUNCFLAG_USE_LASTERROR
97
- if kw:
98
- raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
99
- try:
100
- return _c_functype_cache[(restype, argtypes, flags)]
101
- except KeyError:
102
- class CFunctionType(_CFuncPtr):
103
- _argtypes_ = argtypes
104
- _restype_ = restype
105
- _flags_ = flags
106
- _c_functype_cache[(restype, argtypes, flags)] = CFunctionType
107
- return CFunctionType
108
-
109
- if _os.name == "nt":
110
- from _ctypes import LoadLibrary as _dlopen
111
- from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
112
-
113
- _win_functype_cache = {}
114
- def WINFUNCTYPE(restype, *argtypes, **kw):
115
- # docstring set later (very similar to CFUNCTYPE.__doc__)
116
- flags = _FUNCFLAG_STDCALL
117
- if kw.pop("use_errno", False):
118
- flags |= _FUNCFLAG_USE_ERRNO
119
- if kw.pop("use_last_error", False):
120
- flags |= _FUNCFLAG_USE_LASTERROR
121
- if kw:
122
- raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
123
- try:
124
- return _win_functype_cache[(restype, argtypes, flags)]
125
- except KeyError:
126
- class WinFunctionType(_CFuncPtr):
127
- _argtypes_ = argtypes
128
- _restype_ = restype
129
- _flags_ = flags
130
- _win_functype_cache[(restype, argtypes, flags)] = WinFunctionType
131
- return WinFunctionType
132
- if WINFUNCTYPE.__doc__:
133
- WINFUNCTYPE.__doc__ = CFUNCTYPE.__doc__.replace("CFUNCTYPE", "WINFUNCTYPE")
134
-
135
- elif _os.name == "posix":
136
- from _ctypes import dlopen as _dlopen
137
-
138
- from _ctypes import sizeof, byref, addressof, alignment, resize
139
- from _ctypes import get_errno, set_errno
140
- from _ctypes import _SimpleCData
141
-
142
- def _check_size(typ, typecode=None):
143
- # Check if sizeof(ctypes_type) against struct.calcsize. This
144
- # should protect somewhat against a misconfigured libffi.
145
- from struct import calcsize
146
- if typecode is None:
147
- # Most _type_ codes are the same as used in struct
148
- typecode = typ._type_
149
- actual, required = sizeof(typ), calcsize(typecode)
150
- if actual != required:
151
- raise SystemError("sizeof(%s) wrong: %d instead of %d" % \
152
- (typ, actual, required))
153
-
154
- class py_object(_SimpleCData):
155
- _type_ = "O"
156
- def __repr__(self):
157
- try:
158
- return super().__repr__()
159
- except ValueError:
160
- return "%s(<NULL>)" % type(self).__name__
161
- _check_size(py_object, "P")
162
-
163
- class c_short(_SimpleCData):
164
- _type_ = "h"
165
- _check_size(c_short)
166
-
167
- class c_ushort(_SimpleCData):
168
- _type_ = "H"
169
- _check_size(c_ushort)
170
-
171
- class c_long(_SimpleCData):
172
- _type_ = "l"
173
- _check_size(c_long)
174
-
175
- class c_ulong(_SimpleCData):
176
- _type_ = "L"
177
- _check_size(c_ulong)
178
-
179
- if _calcsize("i") == _calcsize("l"):
180
- # if int and long have the same size, make c_int an alias for c_long
181
- c_int = c_long
182
- c_uint = c_ulong
183
- else:
184
- class c_int(_SimpleCData):
185
- _type_ = "i"
186
- _check_size(c_int)
187
-
188
- class c_uint(_SimpleCData):
189
- _type_ = "I"
190
- _check_size(c_uint)
191
-
192
- class c_float(_SimpleCData):
193
- _type_ = "f"
194
- _check_size(c_float)
195
-
196
- class c_double(_SimpleCData):
197
- _type_ = "d"
198
- _check_size(c_double)
199
-
200
- class c_longdouble(_SimpleCData):
201
- _type_ = "g"
202
- if sizeof(c_longdouble) == sizeof(c_double):
203
- c_longdouble = c_double
204
-
205
- if _calcsize("l") == _calcsize("q"):
206
- # if long and long long have the same size, make c_longlong an alias for c_long
207
- c_longlong = c_long
208
- c_ulonglong = c_ulong
209
- else:
210
- class c_longlong(_SimpleCData):
211
- _type_ = "q"
212
- _check_size(c_longlong)
213
-
214
- class c_ulonglong(_SimpleCData):
215
- _type_ = "Q"
216
- ## def from_param(cls, val):
217
- ## return ('d', float(val), val)
218
- ## from_param = classmethod(from_param)
219
- _check_size(c_ulonglong)
220
-
221
- class c_ubyte(_SimpleCData):
222
- _type_ = "B"
223
- c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte
224
- # backward compatibility:
225
- ##c_uchar = c_ubyte
226
- _check_size(c_ubyte)
227
-
228
- class c_byte(_SimpleCData):
229
- _type_ = "b"
230
- c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte
231
- _check_size(c_byte)
232
-
233
- class c_char(_SimpleCData):
234
- _type_ = "c"
235
- c_char.__ctype_le__ = c_char.__ctype_be__ = c_char
236
- _check_size(c_char)
237
-
238
- class c_char_p(_SimpleCData):
239
- _type_ = "z"
240
- def __repr__(self):
241
- return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
242
- _check_size(c_char_p, "P")
243
-
244
- class c_void_p(_SimpleCData):
245
- _type_ = "P"
246
- c_voidp = c_void_p # backwards compatibility (to a bug)
247
- _check_size(c_void_p)
248
-
249
- class c_bool(_SimpleCData):
250
- _type_ = "?"
251
-
252
- from _ctypes import POINTER, pointer, _pointer_type_cache
253
-
254
- class c_wchar_p(_SimpleCData):
255
- _type_ = "Z"
256
- def __repr__(self):
257
- return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
258
-
259
- class c_wchar(_SimpleCData):
260
- _type_ = "u"
261
-
262
- def _reset_cache():
263
- _pointer_type_cache.clear()
264
- _c_functype_cache.clear()
265
- if _os.name == "nt":
266
- _win_functype_cache.clear()
267
- # _SimpleCData.c_wchar_p_from_param
268
- POINTER(c_wchar).from_param = c_wchar_p.from_param
269
- # _SimpleCData.c_char_p_from_param
270
- POINTER(c_char).from_param = c_char_p.from_param
271
- _pointer_type_cache[None] = c_void_p
272
-
273
- def create_unicode_buffer(init, size=None):
274
- """create_unicode_buffer(aString) -> character array
275
- create_unicode_buffer(anInteger) -> character array
276
- create_unicode_buffer(aString, anInteger) -> character array
277
- """
278
- if isinstance(init, str):
279
- if size is None:
280
- if sizeof(c_wchar) == 2:
281
- # UTF-16 requires a surrogate pair (2 wchar_t) for non-BMP
282
- # characters (outside [U+0000; U+FFFF] range). +1 for trailing
283
- # NUL character.
284
- size = sum(2 if ord(c) > 0xFFFF else 1 for c in init) + 1
285
- else:
286
- # 32-bit wchar_t (1 wchar_t per Unicode character). +1 for
287
- # trailing NUL character.
288
- size = len(init) + 1
289
- _sys.audit("ctypes.create_unicode_buffer", init, size)
290
- buftype = c_wchar * size
291
- buf = buftype()
292
- buf.value = init
293
- return buf
294
- elif isinstance(init, int):
295
- _sys.audit("ctypes.create_unicode_buffer", None, init)
296
- buftype = c_wchar * init
297
- buf = buftype()
298
- return buf
299
- raise TypeError(init)
300
-
301
-
302
- # XXX Deprecated
303
- def SetPointerType(pointer, cls):
304
- if _pointer_type_cache.get(cls, None) is not None:
305
- raise RuntimeError("This type already exists in the cache")
306
- if id(pointer) not in _pointer_type_cache:
307
- raise RuntimeError("What's this???")
308
- pointer.set_type(cls)
309
- _pointer_type_cache[cls] = pointer
310
- del _pointer_type_cache[id(pointer)]
311
-
312
- # XXX Deprecated
313
- def ARRAY(typ, len):
314
- return typ * len
315
-
316
- ################################################################
317
-
318
-
319
- class CDLL(object):
320
- """An instance of this class represents a loaded dll/shared
321
- library, exporting functions using the standard C calling
322
- convention (named 'cdecl' on Windows).
323
-
324
- The exported functions can be accessed as attributes, or by
325
- indexing with the function name. Examples:
326
-
327
- <obj>.qsort -> callable object
328
- <obj>['qsort'] -> callable object
329
-
330
- Calling the functions releases the Python GIL during the call and
331
- reacquires it afterwards.
332
- """
333
- _func_flags_ = _FUNCFLAG_CDECL
334
- _func_restype_ = c_int
335
- # default values for repr
336
- _name = '<uninitialized>'
337
- _handle = 0
338
- _FuncPtr = None
339
-
340
- def __init__(self, name, mode=DEFAULT_MODE, handle=None,
341
- use_errno=False,
342
- use_last_error=False,
343
- winmode=None):
344
- self._name = name
345
- flags = self._func_flags_
346
- if use_errno:
347
- flags |= _FUNCFLAG_USE_ERRNO
348
- if use_last_error:
349
- flags |= _FUNCFLAG_USE_LASTERROR
350
- if _sys.platform.startswith("aix"):
351
- """When the name contains ".a(" and ends with ")",
352
- e.g., "libFOO.a(libFOO.so)" - this is taken to be an
353
- archive(member) syntax for dlopen(), and the mode is adjusted.
354
- Otherwise, name is presented to dlopen() as a file argument.
355
- """
356
- if name and name.endswith(")") and ".a(" in name:
357
- mode |= ( _os.RTLD_MEMBER | _os.RTLD_NOW )
358
- if _os.name == "nt":
359
- if winmode is not None:
360
- mode = winmode
361
- else:
362
- import nt
363
- mode = nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
364
- if '/' in name or '\\' in name:
365
- self._name = nt._getfullpathname(self._name)
366
- mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
367
-
368
- class _FuncPtr(_CFuncPtr):
369
- _flags_ = flags
370
- _restype_ = self._func_restype_
371
- self._FuncPtr = _FuncPtr
372
-
373
- if handle is None:
374
- self._handle = _dlopen(self._name, mode)
375
- else:
376
- self._handle = handle
377
-
378
- def __repr__(self):
379
- return "<%s '%s', handle %x at %#x>" % \
380
- (self.__class__.__name__, self._name,
381
- (self._handle & (_sys.maxsize*2 + 1)),
382
- id(self) & (_sys.maxsize*2 + 1))
383
-
384
- def __getattr__(self, name):
385
- if name.startswith('__') and name.endswith('__'):
386
- raise AttributeError(name)
387
- func = self.__getitem__(name)
388
- setattr(self, name, func)
389
- return func
390
-
391
- def __getitem__(self, name_or_ordinal):
392
- func = self._FuncPtr((name_or_ordinal, self))
393
- if not isinstance(name_or_ordinal, int):
394
- func.__name__ = name_or_ordinal
395
- return func
396
-
397
- class PyDLL(CDLL):
398
- """This class represents the Python library itself. It allows
399
- accessing Python API functions. The GIL is not released, and
400
- Python exceptions are handled correctly.
401
- """
402
- _func_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
403
-
404
- if _os.name == "nt":
405
-
406
- class WinDLL(CDLL):
407
- """This class represents a dll exporting functions using the
408
- Windows stdcall calling convention.
409
- """
410
- _func_flags_ = _FUNCFLAG_STDCALL
411
-
412
- # XXX Hm, what about HRESULT as normal parameter?
413
- # Mustn't it derive from c_long then?
414
- from _ctypes import _check_HRESULT, _SimpleCData
415
- class HRESULT(_SimpleCData):
416
- _type_ = "l"
417
- # _check_retval_ is called with the function's result when it
418
- # is used as restype. It checks for the FAILED bit, and
419
- # raises an OSError if it is set.
420
- #
421
- # The _check_retval_ method is implemented in C, so that the
422
- # method definition itself is not included in the traceback
423
- # when it raises an error - that is what we want (and Python
424
- # doesn't have a way to raise an exception in the caller's
425
- # frame).
426
- _check_retval_ = _check_HRESULT
427
-
428
- class OleDLL(CDLL):
429
- """This class represents a dll exporting functions using the
430
- Windows stdcall calling convention, and returning HRESULT.
431
- HRESULT error values are automatically raised as OSError
432
- exceptions.
433
- """
434
- _func_flags_ = _FUNCFLAG_STDCALL
435
- _func_restype_ = HRESULT
436
-
437
- class LibraryLoader(object):
438
- def __init__(self, dlltype):
439
- self._dlltype = dlltype
440
-
441
- def __getattr__(self, name):
442
- if name[0] == '_':
443
- raise AttributeError(name)
444
- dll = self._dlltype(name)
445
- setattr(self, name, dll)
446
- return dll
447
-
448
- def __getitem__(self, name):
449
- return getattr(self, name)
450
-
451
- def LoadLibrary(self, name):
452
- return self._dlltype(name)
453
-
454
- __class_getitem__ = classmethod(_types.GenericAlias)
455
-
456
- cdll = LibraryLoader(CDLL)
457
- pydll = LibraryLoader(PyDLL)
458
-
459
- if _os.name == "nt":
460
- pythonapi = PyDLL("python dll", None, _sys.dllhandle)
461
- elif _sys.platform == "cygwin":
462
- pythonapi = PyDLL("libpython%d.%d.dll" % _sys.version_info[:2])
463
- else:
464
- pythonapi = PyDLL(None)
465
-
466
-
467
- if _os.name == "nt":
468
- windll = LibraryLoader(WinDLL)
469
- oledll = LibraryLoader(OleDLL)
470
-
471
- GetLastError = windll.kernel32.GetLastError
472
- from _ctypes import get_last_error, set_last_error
473
-
474
- def WinError(code=None, descr=None):
475
- if code is None:
476
- code = GetLastError()
477
- if descr is None:
478
- descr = FormatError(code).strip()
479
- return OSError(None, descr, None, code)
480
-
481
- if sizeof(c_uint) == sizeof(c_void_p):
482
- c_size_t = c_uint
483
- c_ssize_t = c_int
484
- elif sizeof(c_ulong) == sizeof(c_void_p):
485
- c_size_t = c_ulong
486
- c_ssize_t = c_long
487
- elif sizeof(c_ulonglong) == sizeof(c_void_p):
488
- c_size_t = c_ulonglong
489
- c_ssize_t = c_longlong
490
-
491
- # functions
492
-
493
- from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, _cast_addr
494
-
495
- ## void *memmove(void *, const void *, size_t);
496
- memmove = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_size_t)(_memmove_addr)
497
-
498
- ## void *memset(void *, int, size_t)
499
- memset = CFUNCTYPE(c_void_p, c_void_p, c_int, c_size_t)(_memset_addr)
500
-
501
- def PYFUNCTYPE(restype, *argtypes):
502
- class CFunctionType(_CFuncPtr):
503
- _argtypes_ = argtypes
504
- _restype_ = restype
505
- _flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
506
- return CFunctionType
507
-
508
- _cast = PYFUNCTYPE(py_object, c_void_p, py_object, py_object)(_cast_addr)
509
- def cast(obj, typ):
510
- return _cast(obj, obj, typ)
511
-
512
- _string_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr)
513
- def string_at(ptr, size=-1):
514
- """string_at(addr[, size]) -> string
515
-
516
- Return the string at addr."""
517
- return _string_at(ptr, size)
518
-
519
- try:
520
- from _ctypes import _wstring_at_addr
521
- except ImportError:
522
- pass
523
- else:
524
- _wstring_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_wstring_at_addr)
525
- def wstring_at(ptr, size=-1):
526
- """wstring_at(addr[, size]) -> string
527
-
528
- Return the string at addr."""
529
- return _wstring_at(ptr, size)
530
-
531
-
532
- if _os.name == "nt": # COM stuff
533
- def DllGetClassObject(rclsid, riid, ppv):
534
- try:
535
- ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
536
- except ImportError:
537
- return -2147221231 # CLASS_E_CLASSNOTAVAILABLE
538
- else:
539
- return ccom.DllGetClassObject(rclsid, riid, ppv)
540
-
541
- def DllCanUnloadNow():
542
- try:
543
- ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
544
- except ImportError:
545
- return 0 # S_OK
546
- return ccom.DllCanUnloadNow()
547
-
548
- from ctypes._endian import BigEndianStructure, LittleEndianStructure
549
-
550
- # Fill in specifically-sized types
551
- c_int8 = c_byte
552
- c_uint8 = c_ubyte
553
- for kind in [c_short, c_int, c_long, c_longlong]:
554
- if sizeof(kind) == 2: c_int16 = kind
555
- elif sizeof(kind) == 4: c_int32 = kind
556
- elif sizeof(kind) == 8: c_int64 = kind
557
- for kind in [c_ushort, c_uint, c_ulong, c_ulonglong]:
558
- if sizeof(kind) == 2: c_uint16 = kind
559
- elif sizeof(kind) == 4: c_uint32 = kind
560
- elif sizeof(kind) == 8: c_uint64 = kind
561
- del(kind)
562
-
563
- _reset_cache()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9ba27558c729a3ded33a153652e663250379593d748ad9c473f4942553ddd247/blob DELETED
@@ -1,106 +0,0 @@
1
- import numpy as np
2
-
3
- from pandas.compat import WARNING_CHECK_DISABLED
4
-
5
- from pandas import (
6
- DataFrame,
7
- option_context,
8
- )
9
- import pandas._testing as tm
10
- from pandas.tests.copy_view.util import get_array
11
-
12
-
13
- def test_clip_inplace_reference(using_copy_on_write, warn_copy_on_write):
14
- df = DataFrame({"a": [1.5, 2, 3]})
15
- df_copy = df.copy()
16
- arr_a = get_array(df, "a")
17
- view = df[:]
18
- if warn_copy_on_write:
19
- with tm.assert_cow_warning():
20
- df.clip(lower=2, inplace=True)
21
- else:
22
- df.clip(lower=2, inplace=True)
23
-
24
- if using_copy_on_write:
25
- assert not np.shares_memory(get_array(df, "a"), arr_a)
26
- assert df._mgr._has_no_reference(0)
27
- assert view._mgr._has_no_reference(0)
28
- tm.assert_frame_equal(df_copy, view)
29
- else:
30
- assert np.shares_memory(get_array(df, "a"), arr_a)
31
-
32
-
33
- def test_clip_inplace_reference_no_op(using_copy_on_write):
34
- df = DataFrame({"a": [1.5, 2, 3]})
35
- df_copy = df.copy()
36
- arr_a = get_array(df, "a")
37
- view = df[:]
38
- df.clip(lower=0, inplace=True)
39
-
40
- assert np.shares_memory(get_array(df, "a"), arr_a)
41
-
42
- if using_copy_on_write:
43
- assert not df._mgr._has_no_reference(0)
44
- assert not view._mgr._has_no_reference(0)
45
- tm.assert_frame_equal(df_copy, view)
46
-
47
-
48
- def test_clip_inplace(using_copy_on_write):
49
- df = DataFrame({"a": [1.5, 2, 3]})
50
- arr_a = get_array(df, "a")
51
- df.clip(lower=2, inplace=True)
52
-
53
- assert np.shares_memory(get_array(df, "a"), arr_a)
54
-
55
- if using_copy_on_write:
56
- assert df._mgr._has_no_reference(0)
57
-
58
-
59
- def test_clip(using_copy_on_write):
60
- df = DataFrame({"a": [1.5, 2, 3]})
61
- df_orig = df.copy()
62
- df2 = df.clip(lower=2)
63
-
64
- assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
65
-
66
- if using_copy_on_write:
67
- assert df._mgr._has_no_reference(0)
68
- tm.assert_frame_equal(df_orig, df)
69
-
70
-
71
- def test_clip_no_op(using_copy_on_write):
72
- df = DataFrame({"a": [1.5, 2, 3]})
73
- df2 = df.clip(lower=0)
74
-
75
- if using_copy_on_write:
76
- assert not df._mgr._has_no_reference(0)
77
- assert np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
78
- else:
79
- assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a"))
80
-
81
-
82
- def test_clip_chained_inplace(using_copy_on_write):
83
- df = DataFrame({"a": [1, 4, 2], "b": 1})
84
- df_orig = df.copy()
85
- if using_copy_on_write:
86
- with tm.raises_chained_assignment_error():
87
- df["a"].clip(1, 2, inplace=True)
88
- tm.assert_frame_equal(df, df_orig)
89
-
90
- with tm.raises_chained_assignment_error():
91
- df[["a"]].clip(1, 2, inplace=True)
92
- tm.assert_frame_equal(df, df_orig)
93
- else:
94
- with tm.assert_produces_warning(
95
- FutureWarning if not WARNING_CHECK_DISABLED else None,
96
- match="inplace method",
97
- ):
98
- df["a"].clip(1, 2, inplace=True)
99
-
100
- with tm.assert_produces_warning(None):
101
- with option_context("mode.chained_assignment", None):
102
- df[["a"]].clip(1, 2, inplace=True)
103
-
104
- with tm.assert_produces_warning(None):
105
- with option_context("mode.chained_assignment", None):
106
- df[df["a"] > 1].clip(1, 2, inplace=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9ba2eb28230878d7ae89c7ee30c146dfe29efbba328d3b03d5045b29d4d15589/blob DELETED
@@ -1,365 +0,0 @@
1
- from sympy.core.numbers import (E, Rational, pi)
2
- from sympy.functions.elementary.exponential import exp
3
- from sympy.functions.elementary.miscellaneous import sqrt
4
- from sympy.core import S, symbols, I
5
- from sympy.discrete.convolutions import (
6
- convolution, convolution_fft, convolution_ntt, convolution_fwht,
7
- convolution_subset, covering_product, intersecting_product)
8
- from sympy.testing.pytest import raises
9
- from sympy.abc import x, y
10
-
11
- def test_convolution():
12
- # fft
13
- a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
14
- b = [9, 5, 5, 4, 3, 2]
15
- c = [3, 5, 3, 7, 8]
16
- d = [1422, 6572, 3213, 5552]
17
-
18
- assert convolution(a, b) == convolution_fft(a, b)
19
- assert convolution(a, b, dps=9) == convolution_fft(a, b, dps=9)
20
- assert convolution(a, d, dps=7) == convolution_fft(d, a, dps=7)
21
- assert convolution(a, d[1:], dps=3) == convolution_fft(d[1:], a, dps=3)
22
-
23
- # prime moduli of the form (m*2**k + 1), sequence length
24
- # should be a divisor of 2**k
25
- p = 7*17*2**23 + 1
26
- q = 19*2**10 + 1
27
-
28
- # ntt
29
- assert convolution(d, b, prime=q) == convolution_ntt(b, d, prime=q)
30
- assert convolution(c, b, prime=p) == convolution_ntt(b, c, prime=p)
31
- assert convolution(d, c, prime=p) == convolution_ntt(c, d, prime=p)
32
- raises(TypeError, lambda: convolution(b, d, dps=5, prime=q))
33
- raises(TypeError, lambda: convolution(b, d, dps=6, prime=q))
34
-
35
- # fwht
36
- assert convolution(a, b, dyadic=True) == convolution_fwht(a, b)
37
- assert convolution(a, b, dyadic=False) == convolution(a, b)
38
- raises(TypeError, lambda: convolution(b, d, dps=2, dyadic=True))
39
- raises(TypeError, lambda: convolution(b, d, prime=p, dyadic=True))
40
- raises(TypeError, lambda: convolution(a, b, dps=2, dyadic=True))
41
- raises(TypeError, lambda: convolution(b, c, prime=p, dyadic=True))
42
-
43
- # subset
44
- assert convolution(a, b, subset=True) == convolution_subset(a, b) == \
45
- convolution(a, b, subset=True, dyadic=False) == \
46
- convolution(a, b, subset=True)
47
- assert convolution(a, b, subset=False) == convolution(a, b)
48
- raises(TypeError, lambda: convolution(a, b, subset=True, dyadic=True))
49
- raises(TypeError, lambda: convolution(c, d, subset=True, dps=6))
50
- raises(TypeError, lambda: convolution(a, c, subset=True, prime=q))
51
-
52
-
53
- def test_cyclic_convolution():
54
- # fft
55
- a = [1, Rational(5, 3), sqrt(3), Rational(7, 5)]
56
- b = [9, 5, 5, 4, 3, 2]
57
-
58
- assert convolution([1, 2, 3], [4, 5, 6], cycle=0) == \
59
- convolution([1, 2, 3], [4, 5, 6], cycle=5) == \
60
- convolution([1, 2, 3], [4, 5, 6])
61
-
62
- assert convolution([1, 2, 3], [4, 5, 6], cycle=3) == [31, 31, 28]
63
-
64
- a = [Rational(1, 3), Rational(7, 3), Rational(5, 9), Rational(2, 7), Rational(5, 8)]
65
- b = [Rational(3, 5), Rational(4, 7), Rational(7, 8), Rational(8, 9)]
66
-
67
- assert convolution(a, b, cycle=0) == \
68
- convolution(a, b, cycle=len(a) + len(b) - 1)
69
-
70
- assert convolution(a, b, cycle=4) == [Rational(87277, 26460), Rational(30521, 11340),
71
- Rational(11125, 4032), Rational(3653, 1080)]
72
-
73
- assert convolution(a, b, cycle=6) == [Rational(20177, 20160), Rational(676, 315), Rational(47, 24),
74
- Rational(3053, 1080), Rational(16397, 5292), Rational(2497, 2268)]
75
-
76
- assert convolution(a, b, cycle=9) == \
77
- convolution(a, b, cycle=0) + [S.Zero]
78
-
79
- # ntt
80
- a = [2313, 5323532, S(3232), 42142, 42242421]
81
- b = [S(33456), 56757, 45754, 432423]
82
-
83
- assert convolution(a, b, prime=19*2**10 + 1, cycle=0) == \
84
- convolution(a, b, prime=19*2**10 + 1, cycle=8) == \
85
- convolution(a, b, prime=19*2**10 + 1)
86
-
87
- assert convolution(a, b, prime=19*2**10 + 1, cycle=5) == [96, 17146, 2664,
88
- 15534, 3517]
89
-
90
- assert convolution(a, b, prime=19*2**10 + 1, cycle=7) == [4643, 3458, 1260,
91
- 15534, 3517, 16314, 13688]
92
-
93
- assert convolution(a, b, prime=19*2**10 + 1, cycle=9) == \
94
- convolution(a, b, prime=19*2**10 + 1) + [0]
95
-
96
- # fwht
97
- u, v, w, x, y = symbols('u v w x y')
98
- p, q, r, s, t = symbols('p q r s t')
99
- c = [u, v, w, x, y]
100
- d = [p, q, r, s, t]
101
-
102
- assert convolution(a, b, dyadic=True, cycle=3) == \
103
- [2499522285783, 19861417974796, 4702176579021]
104
-
105
- assert convolution(a, b, dyadic=True, cycle=5) == [2718149225143,
106
- 2114320852171, 20571217906407, 246166418903, 1413262436976]
107
-
108
- assert convolution(c, d, dyadic=True, cycle=4) == \
109
- [p*u + p*y + q*v + r*w + s*x + t*u + t*y,
110
- p*v + q*u + q*y + r*x + s*w + t*v,
111
- p*w + q*x + r*u + r*y + s*v + t*w,
112
- p*x + q*w + r*v + s*u + s*y + t*x]
113
-
114
- assert convolution(c, d, dyadic=True, cycle=6) == \
115
- [p*u + q*v + r*w + r*y + s*x + t*w + t*y,
116
- p*v + q*u + r*x + s*w + s*y + t*x,
117
- p*w + q*x + r*u + s*v,
118
- p*x + q*w + r*v + s*u,
119
- p*y + t*u,
120
- q*y + t*v]
121
-
122
- # subset
123
- assert convolution(a, b, subset=True, cycle=7) == [18266671799811,
124
- 178235365533, 213958794, 246166418903, 1413262436976,
125
- 2397553088697, 1932759730434]
126
-
127
- assert convolution(a[1:], b, subset=True, cycle=4) == \
128
- [178104086592, 302255835516, 244982785880, 3717819845434]
129
-
130
- assert convolution(a, b[:-1], subset=True, cycle=6) == [1932837114162,
131
- 178235365533, 213958794, 245166224504, 1413262436976, 2397553088697]
132
-
133
- assert convolution(c, d, subset=True, cycle=3) == \
134
- [p*u + p*x + q*w + r*v + r*y + s*u + t*w,
135
- p*v + p*y + q*u + s*y + t*u + t*x,
136
- p*w + q*y + r*u + t*v]
137
-
138
- assert convolution(c, d, subset=True, cycle=5) == \
139
- [p*u + q*y + t*v,
140
- p*v + q*u + r*y + t*w,
141
- p*w + r*u + s*y + t*x,
142
- p*x + q*w + r*v + s*u,
143
- p*y + t*u]
144
-
145
- raises(ValueError, lambda: convolution([1, 2, 3], [4, 5, 6], cycle=-1))
146
-
147
-
148
- def test_convolution_fft():
149
- assert all(convolution_fft([], x, dps=y) == [] for x in ([], [1]) for y in (None, 3))
150
- assert convolution_fft([1, 2, 3], [4, 5, 6]) == [4, 13, 28, 27, 18]
151
- assert convolution_fft([1], [5, 6, 7]) == [5, 6, 7]
152
- assert convolution_fft([1, 3], [5, 6, 7]) == [5, 21, 25, 21]
153
-
154
- assert convolution_fft([1 + 2*I], [2 + 3*I]) == [-4 + 7*I]
155
- assert convolution_fft([1 + 2*I, 3 + 4*I, 5 + 3*I/5], [Rational(2, 5) + 4*I/7]) == \
156
- [Rational(-26, 35) + I*48/35, Rational(-38, 35) + I*116/35, Rational(58, 35) + I*542/175]
157
-
158
- assert convolution_fft([Rational(3, 4), Rational(5, 6)], [Rational(7, 8), Rational(1, 3), Rational(2, 5)]) == \
159
- [Rational(21, 32), Rational(47, 48), Rational(26, 45), Rational(1, 3)]
160
-
161
- assert convolution_fft([Rational(1, 9), Rational(2, 3), Rational(3, 5)], [Rational(2, 5), Rational(3, 7), Rational(4, 9)]) == \
162
- [Rational(2, 45), Rational(11, 35), Rational(8152, 14175), Rational(523, 945), Rational(4, 15)]
163
-
164
- assert convolution_fft([pi, E, sqrt(2)], [sqrt(3), 1/pi, 1/E]) == \
165
- [sqrt(3)*pi, 1 + sqrt(3)*E, E/pi + pi*exp(-1) + sqrt(6),
166
- sqrt(2)/pi + 1, sqrt(2)*exp(-1)]
167
-
168
- assert convolution_fft([2321, 33123], [5321, 6321, 71323]) == \
169
- [12350041, 190918524, 374911166, 2362431729]
170
-
171
- assert convolution_fft([312313, 31278232], [32139631, 319631]) == \
172
- [10037624576503, 1005370659728895, 9997492572392]
173
-
174
- raises(TypeError, lambda: convolution_fft(x, y))
175
- raises(ValueError, lambda: convolution_fft([x, y], [y, x]))
176
-
177
-
178
- def test_convolution_ntt():
179
- # prime moduli of the form (m*2**k + 1), sequence length
180
- # should be a divisor of 2**k
181
- p = 7*17*2**23 + 1
182
- q = 19*2**10 + 1
183
- r = 2*500000003 + 1 # only for sequences of length 1 or 2
184
- # s = 2*3*5*7 # composite modulus
185
-
186
- assert all(convolution_ntt([], x, prime=y) == [] for x in ([], [1]) for y in (p, q, r))
187
- assert convolution_ntt([2], [3], r) == [6]
188
- assert convolution_ntt([2, 3], [4], r) == [8, 12]
189
-
190
- assert convolution_ntt([32121, 42144, 4214, 4241], [32132, 3232, 87242], p) == [33867619,
191
- 459741727, 79180879, 831885249, 381344700, 369993322]
192
- assert convolution_ntt([121913, 3171831, 31888131, 12], [17882, 21292, 29921, 312], q) == \
193
- [8158, 3065, 3682, 7090, 1239, 2232, 3744]
194
-
195
- assert convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], p) == \
196
- convolution_ntt([12, 19, 21, 98, 67], [2, 6, 7, 8, 9], q)
197
- assert convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], p) == \
198
- convolution_ntt([12, 19, 21, 98, 67], [21, 76, 17, 78, 69], q)
199
-
200
- raises(ValueError, lambda: convolution_ntt([2, 3], [4, 5], r))
201
- raises(ValueError, lambda: convolution_ntt([x, y], [y, x], q))
202
- raises(TypeError, lambda: convolution_ntt(x, y, p))
203
-
204
-
205
- def test_convolution_fwht():
206
- assert convolution_fwht([], []) == []
207
- assert convolution_fwht([], [1]) == []
208
- assert convolution_fwht([1, 2, 3], [4, 5, 6]) == [32, 13, 18, 27]
209
-
210
- assert convolution_fwht([Rational(5, 7), Rational(6, 8), Rational(7, 3)], [2, 4, Rational(6, 7)]) == \
211
- [Rational(45, 7), Rational(61, 14), Rational(776, 147), Rational(419, 42)]
212
-
213
- a = [1, Rational(5, 3), sqrt(3), Rational(7, 5), 4 + 5*I]
214
- b = [94, 51, 53, 45, 31, 27, 13]
215
- c = [3 + 4*I, 5 + 7*I, 3, Rational(7, 6), 8]
216
-
217
- assert convolution_fwht(a, b) == [53*sqrt(3) + 366 + 155*I,
218
- 45*sqrt(3) + Rational(5848, 15) + 135*I,
219
- 94*sqrt(3) + Rational(1257, 5) + 65*I,
220
- 51*sqrt(3) + Rational(3974, 15),
221
- 13*sqrt(3) + 452 + 470*I,
222
- Rational(4513, 15) + 255*I,
223
- 31*sqrt(3) + Rational(1314, 5) + 265*I,
224
- 27*sqrt(3) + Rational(3676, 15) + 225*I]
225
-
226
- assert convolution_fwht(b, c) == [Rational(1993, 2) + 733*I, Rational(6215, 6) + 862*I,
227
- Rational(1659, 2) + 527*I, Rational(1988, 3) + 551*I, 1019 + 313*I, Rational(3955, 6) + 325*I,
228
- Rational(1175, 2) + 52*I, Rational(3253, 6) + 91*I]
229
-
230
- assert convolution_fwht(a[3:], c) == [Rational(-54, 5) + I*293/5, -1 + I*204/5,
231
- Rational(133, 15) + I*35/6, Rational(409, 30) + 15*I, Rational(56, 5), 32 + 40*I, 0, 0]
232
-
233
- u, v, w, x, y, z = symbols('u v w x y z')
234
-
235
- assert convolution_fwht([u, v], [x, y]) == [u*x + v*y, u*y + v*x]
236
-
237
- assert convolution_fwht([u, v, w], [x, y]) == \
238
- [u*x + v*y, u*y + v*x, w*x, w*y]
239
-
240
- assert convolution_fwht([u, v, w], [x, y, z]) == \
241
- [u*x + v*y + w*z, u*y + v*x, u*z + w*x, v*z + w*y]
242
-
243
- raises(TypeError, lambda: convolution_fwht(x, y))
244
- raises(TypeError, lambda: convolution_fwht(x*y, u + v))
245
-
246
-
247
- def test_convolution_subset():
248
- assert convolution_subset([], []) == []
249
- assert convolution_subset([], [Rational(1, 3)]) == []
250
- assert convolution_subset([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
251
-
252
- a = [1, Rational(5, 3), sqrt(3), 4 + 5*I]
253
- b = [64, 71, 55, 47, 33, 29, 15]
254
- c = [3 + I*2/3, 5 + 7*I, 7, Rational(7, 5), 9]
255
-
256
- assert convolution_subset(a, b) == [64, Rational(533, 3), 55 + 64*sqrt(3),
257
- 71*sqrt(3) + Rational(1184, 3) + 320*I, 33, 84,
258
- 15 + 33*sqrt(3), 29*sqrt(3) + 157 + 165*I]
259
-
260
- assert convolution_subset(b, c) == [192 + I*128/3, 533 + I*1486/3,
261
- 613 + I*110/3, Rational(5013, 5) + I*1249/3,
262
- 675 + 22*I, 891 + I*751/3,
263
- 771 + 10*I, Rational(3736, 5) + 105*I]
264
-
265
- assert convolution_subset(a, c) == convolution_subset(c, a)
266
- assert convolution_subset(a[:2], b) == \
267
- [64, Rational(533, 3), 55, Rational(416, 3), 33, 84, 15, 25]
268
-
269
- assert convolution_subset(a[:2], c) == \
270
- [3 + I*2/3, 10 + I*73/9, 7, Rational(196, 15), 9, 15, 0, 0]
271
-
272
- u, v, w, x, y, z = symbols('u v w x y z')
273
-
274
- assert convolution_subset([u, v, w], [x, y]) == [u*x, u*y + v*x, w*x, w*y]
275
- assert convolution_subset([u, v, w, x], [y, z]) == \
276
- [u*y, u*z + v*y, w*y, w*z + x*y]
277
-
278
- assert convolution_subset([u, v], [x, y, z]) == \
279
- convolution_subset([x, y, z], [u, v])
280
-
281
- raises(TypeError, lambda: convolution_subset(x, z))
282
- raises(TypeError, lambda: convolution_subset(Rational(7, 3), u))
283
-
284
-
285
- def test_covering_product():
286
- assert covering_product([], []) == []
287
- assert covering_product([], [Rational(1, 3)]) == []
288
- assert covering_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
289
-
290
- a = [1, Rational(5, 8), sqrt(7), 4 + 9*I]
291
- b = [66, 81, 95, 49, 37, 89, 17]
292
- c = [3 + I*2/3, 51 + 72*I, 7, Rational(7, 15), 91]
293
-
294
- assert covering_product(a, b) == [66, Rational(1383, 8), 95 + 161*sqrt(7),
295
- 130*sqrt(7) + 1303 + 2619*I, 37,
296
- Rational(671, 4), 17 + 54*sqrt(7),
297
- 89*sqrt(7) + Rational(4661, 8) + 1287*I]
298
-
299
- assert covering_product(b, c) == [198 + 44*I, 7740 + 10638*I,
300
- 1412 + I*190/3, Rational(42684, 5) + I*31202/3,
301
- 9484 + I*74/3, 22163 + I*27394/3,
302
- 10621 + I*34/3, Rational(90236, 15) + 1224*I]
303
-
304
- assert covering_product(a, c) == covering_product(c, a)
305
- assert covering_product(b, c[:-1]) == [198 + 44*I, 7740 + 10638*I,
306
- 1412 + I*190/3, Rational(42684, 5) + I*31202/3,
307
- 111 + I*74/3, 6693 + I*27394/3,
308
- 429 + I*34/3, Rational(23351, 15) + 1224*I]
309
-
310
- assert covering_product(a, c[:-1]) == [3 + I*2/3,
311
- Rational(339, 4) + I*1409/12, 7 + 10*sqrt(7) + 2*sqrt(7)*I/3,
312
- -403 + 772*sqrt(7)/15 + 72*sqrt(7)*I + I*12658/15]
313
-
314
- u, v, w, x, y, z = symbols('u v w x y z')
315
-
316
- assert covering_product([u, v, w], [x, y]) == \
317
- [u*x, u*y + v*x + v*y, w*x, w*y]
318
-
319
- assert covering_product([u, v, w, x], [y, z]) == \
320
- [u*y, u*z + v*y + v*z, w*y, w*z + x*y + x*z]
321
-
322
- assert covering_product([u, v], [x, y, z]) == \
323
- covering_product([x, y, z], [u, v])
324
-
325
- raises(TypeError, lambda: covering_product(x, z))
326
- raises(TypeError, lambda: covering_product(Rational(7, 3), u))
327
-
328
-
329
- def test_intersecting_product():
330
- assert intersecting_product([], []) == []
331
- assert intersecting_product([], [Rational(1, 3)]) == []
332
- assert intersecting_product([6 + I*3/7], [Rational(2, 3)]) == [4 + I*2/7]
333
-
334
- a = [1, sqrt(5), Rational(3, 8) + 5*I, 4 + 7*I]
335
- b = [67, 51, 65, 48, 36, 79, 27]
336
- c = [3 + I*2/5, 5 + 9*I, 7, Rational(7, 19), 13]
337
-
338
- assert intersecting_product(a, b) == [195*sqrt(5) + Rational(6979, 8) + 1886*I,
339
- 178*sqrt(5) + 520 + 910*I, Rational(841, 2) + 1344*I,
340
- 192 + 336*I, 0, 0, 0, 0]
341
-
342
- assert intersecting_product(b, c) == [Rational(128553, 19) + I*9521/5,
343
- Rational(17820, 19) + 1602*I, Rational(19264, 19), Rational(336, 19), 1846, 0, 0, 0]
344
-
345
- assert intersecting_product(a, c) == intersecting_product(c, a)
346
- assert intersecting_product(b[1:], c[:-1]) == [Rational(64788, 19) + I*8622/5,
347
- Rational(12804, 19) + 1152*I, Rational(11508, 19), Rational(252, 19), 0, 0, 0, 0]
348
-
349
- assert intersecting_product(a, c[:-2]) == \
350
- [Rational(-99, 5) + 10*sqrt(5) + 2*sqrt(5)*I/5 + I*3021/40,
351
- -43 + 5*sqrt(5) + 9*sqrt(5)*I + 71*I, Rational(245, 8) + 84*I, 0]
352
-
353
- u, v, w, x, y, z = symbols('u v w x y z')
354
-
355
- assert intersecting_product([u, v, w], [x, y]) == \
356
- [u*x + u*y + v*x + w*x + w*y, v*y, 0, 0]
357
-
358
- assert intersecting_product([u, v, w, x], [y, z]) == \
359
- [u*y + u*z + v*y + w*y + w*z + x*y, v*z + x*z, 0, 0]
360
-
361
- assert intersecting_product([u, v], [x, y, z]) == \
362
- intersecting_product([x, y, z], [u, v])
363
-
364
- raises(TypeError, lambda: intersecting_product(x, z))
365
- raises(TypeError, lambda: intersecting_product(u, Rational(8, 3)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9ba3dbd2b159c35b0bad95c6b8c54bf2ba8da83afa007f930f298988ea22d915/blob DELETED
The diff for this file is too large to render. See raw diff
 
shared/package-files/9b/9ba66c370c751a1b0492d42beb73715c74245f607b36d8b4d755d8b0f836c5fa/blob DELETED
@@ -1,112 +0,0 @@
1
- // Licensed to the Apache Software Foundation (ASF) under one
2
- // or more contributor license agreements. See the NOTICE file
3
- // distributed with this work for additional information
4
- // regarding copyright ownership. The ASF licenses this file
5
- // to you under the Apache License, Version 2.0 (the
6
- // "License"); you may not use this file except in compliance
7
- // with the License. You may obtain a copy of the License at
8
- //
9
- // http://www.apache.org/licenses/LICENSE-2.0
10
- //
11
- // Unless required by applicable law or agreed to in writing,
12
- // software distributed under the License is distributed on an
13
- // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
- // KIND, either express or implied. See the License for the
15
- // specific language governing permissions and limitations
16
- // under the License.
17
-
18
- #pragma once
19
-
20
- #include <cstdint>
21
- #include <memory>
22
-
23
- #include "arrow/buffer.h"
24
- #include "arrow/memory_pool.h"
25
- #include "arrow/result.h"
26
- #include "arrow/util/bit_util.h"
27
- #include "arrow/util/visibility.h"
28
-
29
- namespace arrow {
30
- namespace internal {
31
-
32
- // A std::generate() like function to write sequential bits into a bitmap area.
33
- // Bits preceding the bitmap area are preserved, bits following the bitmap
34
- // area may be clobbered.
35
-
36
- template <class Generator>
37
- void GenerateBits(uint8_t* bitmap, int64_t start_offset, int64_t length, Generator&& g) {
38
- if (length == 0) {
39
- return;
40
- }
41
- uint8_t* cur = bitmap + start_offset / 8;
42
- uint8_t bit_mask = bit_util::kBitmask[start_offset % 8];
43
- uint8_t current_byte = *cur & bit_util::kPrecedingBitmask[start_offset % 8];
44
-
45
- for (int64_t index = 0; index < length; ++index) {
46
- const bool bit = g();
47
- current_byte = bit ? (current_byte | bit_mask) : current_byte;
48
- bit_mask = static_cast<uint8_t>(bit_mask << 1);
49
- if (bit_mask == 0) {
50
- bit_mask = 1;
51
- *cur++ = current_byte;
52
- current_byte = 0;
53
- }
54
- }
55
- if (bit_mask != 1) {
56
- *cur++ = current_byte;
57
- }
58
- }
59
-
60
- // Like GenerateBits(), but unrolls its main loop for higher performance.
61
-
62
- template <class Generator>
63
- void GenerateBitsUnrolled(uint8_t* bitmap, int64_t start_offset, int64_t length,
64
- Generator&& g) {
65
- static_assert(std::is_same<decltype(std::declval<Generator>()()), bool>::value,
66
- "Functor passed to GenerateBitsUnrolled must return bool");
67
-
68
- if (length == 0) {
69
- return;
70
- }
71
- uint8_t current_byte;
72
- uint8_t* cur = bitmap + start_offset / 8;
73
- const uint64_t start_bit_offset = start_offset % 8;
74
- uint8_t bit_mask = bit_util::kBitmask[start_bit_offset];
75
- int64_t remaining = length;
76
-
77
- if (bit_mask != 0x01) {
78
- current_byte = *cur & bit_util::kPrecedingBitmask[start_bit_offset];
79
- while (bit_mask != 0 && remaining > 0) {
80
- current_byte |= g() * bit_mask;
81
- bit_mask = static_cast<uint8_t>(bit_mask << 1);
82
- --remaining;
83
- }
84
- *cur++ = current_byte;
85
- }
86
-
87
- int64_t remaining_bytes = remaining / 8;
88
- uint8_t out_results[8];
89
- while (remaining_bytes-- > 0) {
90
- for (int i = 0; i < 8; ++i) {
91
- out_results[i] = g();
92
- }
93
- *cur++ = static_cast<uint8_t>(out_results[0] | out_results[1] << 1 |
94
- out_results[2] << 2 | out_results[3] << 3 |
95
- out_results[4] << 4 | out_results[5] << 5 |
96
- out_results[6] << 6 | out_results[7] << 7);
97
- }
98
-
99
- int64_t remaining_bits = remaining % 8;
100
- if (remaining_bits) {
101
- current_byte = 0;
102
- bit_mask = 0x01;
103
- while (remaining_bits-- > 0) {
104
- current_byte |= g() * bit_mask;
105
- bit_mask = static_cast<uint8_t>(bit_mask << 1);
106
- }
107
- *cur++ = current_byte;
108
- }
109
- }
110
-
111
- } // namespace internal
112
- } // namespace arrow
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
shared/package-files/9b/9ba7b5b1a97124d16a01ca9921b766b8f2bf995761f7f4d5a4776df91868353d/blob DELETED
@@ -1,13 +0,0 @@
1
- *** Mon, 25 Jul 2016 11:30:46 ***
2
- TEST FOR GRANGER-CAUSALITY:
3
- H0: "Dp" do not Granger-cause "R"
4
-
5
- Test statistic l = 0.7474
6
- pval-F( l; 4, 176) = 0.5610
7
-
8
- TEST FOR INSTANTANEOUS CAUSALITY:
9
- H0: No instantaneous causality between "Dp" and "R"
10
-
11
- Test statistic: c = 0.4071
12
- pval-Chi( c; 1) = 0.5235
13
-