s42chen commited on
Commit
c40417a
·
verified ·
1 Parent(s): c8e3c42

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

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +43 -0
  2. shared/package-files/56/561d36b5dc82ca96bc35be10cdd5619c30225c43b6590adcc1cbce7430c5179c/blob +0 -0
  3. shared/package-files/56/561ec7f24a961f85fc6b7557d976765737bdb2bc096af90d1c0671749533fdb9/blob +14 -0
  4. shared/package-files/56/56200dff83bb581b078ee68656999e720a8916f51ea86e52ea7123753ac149fd/blob +3 -0
  5. shared/package-files/56/562173cf3e5a16d3dc69ef89fd17b99d9aefbd1789fc63443d84f01b855ef8cc/blob +47 -0
  6. shared/package-files/56/5621b7f0f809b08853df1680aee82fc344cf3fa556a0fd95263ec51085b2a648/blob +65 -0
  7. shared/package-files/56/56243a12c4fe44781e453d01d2388a4dfbcfe0107b49a7010b64656cd569a966/blob +1205 -0
  8. shared/package-files/56/5625ccbe57902084adaae1cdd350a94d43d8c6ede3802e7b19a08e92e5d1b285/blob +841 -0
  9. shared/package-files/56/5625dde86e5d3428f96dd588a61155f28936505d3c537a4a448d967e716af150/blob +212 -0
  10. shared/package-files/56/5627831bc850c2f3bb9ecaafe77e4a9afaa5c219ac19f0acdebde802a9078900/blob +39 -0
  11. shared/package-files/56/562825f936033f38d1b61561663a9b6f3352aeed36351d6259f65f9a1ed621f2/blob +39 -0
  12. shared/package-files/56/562d4b893ac95f9058d000cbc68264c02ec7dbb1f7d2d4cf33cf71674e00e465/blob +2 -0
  13. shared/package-files/56/562d4d8bd25e6725fb9145fb60482f6a3d52ea4cba472532f2a2ff08e375520c/blob +20 -0
  14. shared/package-files/56/562d986ed52133d57160f6373c1bf17eed31658afa7c1cac9798103c9128f3c9/blob +285 -0
  15. shared/package-files/56/56325687bbec94c348a1074f14d525019234131b8b155e8476bcb061a223a905/blob +841 -0
  16. shared/package-files/56/5637254ab13a7f25d7584d074a6c0fa33cde89d8b7a9f397d94291ce47025fd0/blob +30 -0
  17. shared/package-files/56/563906875503fa2d734c3035757a35b9e712b3a3f11dd190e6f94293f982098b/blob +35 -0
  18. shared/package-files/56/56396fd018eb070fa3025504ec0605f95dfe1aa31824ef3068d3a92c144ab373/blob +104 -0
  19. shared/package-files/56/5639df194837f65be5083c4ea0649e626f142f5db0642e724399fcf96f76783d/blob +301 -0
  20. shared/package-files/56/563a1e1c187330875efa2ccd66fae72633c03e07e5497df26d155b2eb6f2a38b/blob +28 -0
  21. shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/blob +0 -0
  22. shared/package-files/56/563b9821194c63e2bbf616ab92d863cdc8052fbae59242cea00c0d7c4088959c/blob +857 -0
  23. shared/package-files/56/563bae0d769e16d7de0c6d77333e35c68f398272b7223c3890bbdfadbc2d0d76/blob +3 -0
  24. shared/package-files/56/563cf6e58e87fe2874884136006d246b13bd53c3f07174aba1fcea9cde170702/blob +551 -0
  25. shared/package-files/56/563dcf55580ef635d85c2c376da6f3269d00624d3d914e0cde871258b0929f8b/blob +1297 -0
  26. shared/package-files/56/563e1558fcad6e16795bbefe59ab34fffabc06bf514d4d6f467045ac7f0cdf3c/blob +227 -0
  27. shared/package-files/56/563e435ddf0f296b765370c217a43555179ae3317e4104ce4494b5b4c3b59e4b/blob +28 -0
  28. shared/package-files/56/563fa8988b3ade8702d35f49f4e1940ba66e3adae9fe83cd64743e2e400353a9/blob +189 -0
  29. shared/package-files/56/5641a9e909f66d0b990a6d4fb2093bc4490352081f4974b9844e06dbfdfb5822/blob +20 -0
  30. shared/package-files/56/5642d1b0a514557a37ceb8405e7f6233ea4ac926c62157f35a8a290e199c78c0/blob +0 -0
  31. shared/package-files/56/5643ad9376af2ed3a5d23bdae0172e6ec19fbb325d68d62661e90050f4cf118f/blob +25 -0
  32. shared/package-files/56/5645a590a79bb3c1ff657da38e6fb44a23430625c5374a0fb6699fdde3e116b5/blob +0 -0
  33. shared/package-files/56/5646119d7e7043b4628400fa918aa2748fe16fd36028948013419a62e94da476/blob +359 -0
  34. shared/package-files/56/56496724da7238138ed04b02aa5dfd17e03f3830063abcc620bc2f92b5436833/blob +161 -0
  35. shared/package-files/56/564c14cab191be17a8429c304e53fe65b464a83d6175f5d304e3232bab785e97/blob +1505 -0
  36. shared/package-files/56/564d6cca251b3adad0ba10b91ca657e113d82ad7406f2a53b17f9f668c7c1ad7/blob +114 -0
  37. shared/package-files/56/564f153bbe095146991ef7a3be45890519e693ece9987c2392c3026680435837/blob +130 -0
  38. shared/package-files/56/5652bcc2d84bb33915968e96a2b1f17c53beb242a11ed79abd839a80779d0821/blob +51 -0
  39. shared/package-files/56/565454d155b79ca728b997f7ca4b7c23e8ad2bd520ed89561831c99d8b95b438/blob +27 -0
  40. shared/package-files/56/56549f6a15910c6ee83b2922aefd8b06bbe24d0c739afb966802d06cf10023b5/blob +0 -0
  41. shared/package-files/56/5659af72d45a42d8ee62f42ea1edaddae7e26fbe13b9affbaac895aecde3fa9d/blob +9 -0
  42. shared/package-files/56/565b18e09c1951c905e6ec43ad596b2510559ef4e6bae6a3774877ec13246cea/blob +447 -0
  43. shared/package-files/56/565ef8fb81829dc98a4be79bd3ac584d2e4a66d9a63a5ff80e55dc78583f95b6/blob +17 -0
  44. shared/package-files/56/566141a62fbfb4d6bccb3366bbf7ee7dec263d39c253ac9c34219c377e1405c7/blob +14 -0
  45. shared/package-files/56/566520ef07b56189e8e87e331e08c2a0f63ba533b7cf314792714c0bca18c047/blob +67 -0
  46. shared/package-files/56/56664ff52e693ee705c72a80395f74f049965d066f8028162e6949253525d0b1/blob +0 -0
  47. shared/package-files/56/5666818020fce78b306322e8b8330725fe0b2fa8943606a310e41fd295231e38/blob +0 -0
  48. shared/package-files/56/5666bb7eda54f19534e85cecf9cca49fce014790c8cd7bb2eaf3b1646851eba8/blob +661 -0
  49. shared/package-files/56/56678668d6a1892cc1253e114d7301f010ea40bbce65c8d67bfc518a620f3f62/blob +23 -0
  50. shared/package-files/56/5667c31dcece0b6d20cad709faa0d16a2a57ee42563742cfa16ea8c0cca4dc48/blob +1331 -0
.gitattributes CHANGED
@@ -445,3 +445,46 @@ shared/package-files/55/5502ad58d22988cf4bf19181ba7bd9639b7b163bebd08a65bad62edd
445
  shared/package-files/55/55100c41d53c4378900457f83afe3a2a87605598f06b5fe55395011ccabe8376/blob filter=lfs diff=lfs merge=lfs -text
446
  shared/package-files/55/55aa0e595790ba47863e3b8b60fcac1728af9360017c06ca09049ade495e41e0/blob filter=lfs diff=lfs merge=lfs -text
447
  shared/package-files/55/55ae261f3d27c23f34f9d4c1328562bf5f4119a0f62d9aad40b37db02800ea92/blob filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445
  shared/package-files/55/55100c41d53c4378900457f83afe3a2a87605598f06b5fe55395011ccabe8376/blob filter=lfs diff=lfs merge=lfs -text
446
  shared/package-files/55/55aa0e595790ba47863e3b8b60fcac1728af9360017c06ca09049ade495e41e0/blob filter=lfs diff=lfs merge=lfs -text
447
  shared/package-files/55/55ae261f3d27c23f34f9d4c1328562bf5f4119a0f62d9aad40b37db02800ea92/blob filter=lfs diff=lfs merge=lfs -text
448
+ shared/package-files/56/56200dff83bb581b078ee68656999e720a8916f51ea86e52ea7123753ac149fd/blob filter=lfs diff=lfs merge=lfs -text
449
+ shared/package-files/56/563bae0d769e16d7de0c6d77333e35c68f398272b7223c3890bbdfadbc2d0d76/blob filter=lfs diff=lfs merge=lfs -text
450
+ shared/package-files/56/569318a3168345477b972293d086b9318dbcdb6c79a4df1dbd1f7c57ed7a296e/blob filter=lfs diff=lfs merge=lfs -text
451
+ shared/package-files/56/56d6740b800583fa54adba6594ef8562832f86d156435527c4a1ca8584653bbe/blob filter=lfs diff=lfs merge=lfs -text
452
+ shared/package-files/57/573228ba3e53a6349b543fd02f858ce9d8cc2ce2fd7d278f3abe181c245768da/blob filter=lfs diff=lfs merge=lfs -text
453
+ shared/package-files/57/5756e9ba55f144cc0501b4921eb246c51cded107896b5b8eb62f533ae8783c84/blob filter=lfs diff=lfs merge=lfs -text
454
+ shared/package-files/57/57890ca757167d3ba732d0e70064b6926101c4e2c67c1bd9c902983d4e7e3f58/blob filter=lfs diff=lfs merge=lfs -text
455
+ shared/package-files/57/579016d0b705ddc977b1de41f89e134278ae465f9a920372af9a2776cda6ec83/blob filter=lfs diff=lfs merge=lfs -text
456
+ shared/package-files/57/579e20340ab76800c92d28a1f49c34074abf51a8baf71e38a3faefc89bc666ed/blob filter=lfs diff=lfs merge=lfs -text
457
+ shared/package-files/58/58091005c74f9a5e50f535052b35850c04f63a676448efb82c386f3bcf1f849c/blob filter=lfs diff=lfs merge=lfs -text
458
+ shared/package-files/58/580af86d75988e8c3fa2caab4352304ca80a276da4145886c6547a7dd929a910/blob filter=lfs diff=lfs merge=lfs -text
459
+ shared/package-files/58/58239d2916fb44f8c120a3d2ba7520ac51c7f2851c4e50b428e908661ab9be4c/blob filter=lfs diff=lfs merge=lfs -text
460
+ shared/package-files/58/583afcae904440fa8bdcbdc6400bb8a74113970a05b6517bdde3de343600b61e/blob filter=lfs diff=lfs merge=lfs -text
461
+ shared/package-files/58/585c091ae1f93828db647470326a379f2bbf69e9f2dc717e0bf5057c0c26f071/blob filter=lfs diff=lfs merge=lfs -text
462
+ shared/package-files/58/58839a0f8175fa5bc5b44c2b37effcc9b15679d3ec502d3287ff7d4d29640371/blob filter=lfs diff=lfs merge=lfs -text
463
+ shared/package-files/58/5887db851f7f8700e8ccb8252b530ed09632f393ef492c6e0077cc539054fed9/blob filter=lfs diff=lfs merge=lfs -text
464
+ shared/package-files/58/58883b24debc2464addc4b82387a5f28c8be816abe44b6b754567a6cca9a2482/blob filter=lfs diff=lfs merge=lfs -text
465
+ shared/package-files/58/58ce118d80dfe7d5603a2468ebe311d338125f8e5b766c040f15d723a5f99231/blob filter=lfs diff=lfs merge=lfs -text
466
+ shared/package-files/58/58cf984966970134b0e3e965a8ce7ff8eb7aa9a0817d05ef82e53d4ca74422e3/blob filter=lfs diff=lfs merge=lfs -text
467
+ shared/package-files/58/58d73aa22d8b83f9c9edacfd13ab8d744fb99e073d480da0e5f6085b6ab1fbb7/blob filter=lfs diff=lfs merge=lfs -text
468
+ shared/package-files/58/58e88d0b2dfad21e7382338eb9b556097c726be8c3ebf2d63ceb3decc2c44937/blob filter=lfs diff=lfs merge=lfs -text
469
+ shared/package-files/58/58e92051889458222282d3a430a2ba3c8a8c816166e5d55601bddb383f15dd93/blob filter=lfs diff=lfs merge=lfs -text
470
+ shared/package-files/59/591a29ec303b429688277aa34f00fc22c2c7a24a3bdd0b572af323f42c9fe22a/blob filter=lfs diff=lfs merge=lfs -text
471
+ shared/package-files/59/59255c69bc79fe83b3ef8c3359535d2a4cf723af8848cdf14b4e34afab33828c/blob filter=lfs diff=lfs merge=lfs -text
472
+ shared/package-files/59/59a674a4ea546a62d9e0fbeb7152b60c2c13c8bdd08935a4c8c6bc8b0df681c7/blob filter=lfs diff=lfs merge=lfs -text
473
+ shared/package-files/59/59f270823574f9d238d1e55f3f2ea91efbe690b34b4e8a5210ccbfb36d7d0069/blob filter=lfs diff=lfs merge=lfs -text
474
+ shared/package-files/59/59f839467f2752b7df6fb6d4094396edd32a5929b764f7ffa1e6666431e6cac6/blob filter=lfs diff=lfs merge=lfs -text
475
+ shared/package-files/5a/5a5e8f90a608f84f0592bad0213117ba9b3d056d6dc3feb325965a830f25a3e0/blob filter=lfs diff=lfs merge=lfs -text
476
+ shared/package-files/5a/5a657ad0673dd465f7647e920d9d8d29c519acd034d76f0c00d7617c2012bf1a/blob filter=lfs diff=lfs merge=lfs -text
477
+ shared/package-files/5a/5a788dc1ea57cdca643356628888f191cba7d3b21784bdb8a488132fdc261f78/blob filter=lfs diff=lfs merge=lfs -text
478
+ shared/package-files/5a/5a9bf614151d2ed9c5d0151e52295b0d2266dde627e0e6e58685a622389c8d05/blob filter=lfs diff=lfs merge=lfs -text
479
+ shared/package-files/5b/5b4228e644528d0195d8d2785973637be5c41408166e1e2e9417902b346720f7/blob filter=lfs diff=lfs merge=lfs -text
480
+ shared/package-files/5b/5b451c23149edea31ddcf56270e23494babf7c9137c460d7f50533cd938a83c3/blob filter=lfs diff=lfs merge=lfs -text
481
+ shared/package-files/5b/5b52d319e64c87be4647d770e58fe3509b84f7585dedc99c7411c54d3913d0e4/blob filter=lfs diff=lfs merge=lfs -text
482
+ shared/package-files/5b/5b72231a3ef9e1995615d4b2cf5925df58ba6f8f10d0b8a8eaa692270fb8c8c4/blob filter=lfs diff=lfs merge=lfs -text
483
+ shared/package-files/5b/5bc7d7e94302cd9b94f34d8df5d55a1b35d7eae3ce66372c73726652ff210e89/blob filter=lfs diff=lfs merge=lfs -text
484
+ shared/package-files/5b/5bcae5f2f1671d582e4891073209ec0bfe7e9c9f1f5b81543964080c1e74cd95/blob filter=lfs diff=lfs merge=lfs -text
485
+ shared/package-files/5c/5c2fae37c86e68c3a38605a95f512d7d12d5f3db986310be47f57304aa72a5ee/blob filter=lfs diff=lfs merge=lfs -text
486
+ shared/package-files/5c/5c3c5a4ee1fd1034102b390dc38a2c394d39816de74d7f0430e57263581b30a5/blob filter=lfs diff=lfs merge=lfs -text
487
+ shared/package-files/5c/5ca716cd5632c9b717bb167d187387483b5485fead55f45b25cc44325d5d18ea/blob filter=lfs diff=lfs merge=lfs -text
488
+ shared/package-files/5d/5d213d7fa401bd485e5d1f62c818db510af4d90c544dad78fd421e292c09500a/blob filter=lfs diff=lfs merge=lfs -text
489
+ shared/package-files/5d/5d4e01395b75733e2233105efa95ca8039c3eae40cf10423e89c9487bef60ed0/blob filter=lfs diff=lfs merge=lfs -text
490
+ shared/package-files/5d/5d7b238a111ba401377e9c0e157730483fa2081ea5badca34b5fd12c67aa1d05/blob filter=lfs diff=lfs merge=lfs -text
shared/package-files/56/561d36b5dc82ca96bc35be10cdd5619c30225c43b6590adcc1cbce7430c5179c/blob ADDED
Binary file (718 Bytes). View file
 
shared/package-files/56/561ec7f24a961f85fc6b7557d976765737bdb2bc096af90d1c0671749533fdb9/blob ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Render to qt from agg
3
+ """
4
+ from .. import backends
5
+
6
+ backends._QT_FORCE_QT5_BINDING = True
7
+ from .backend_qtagg import ( # noqa: F401, E402 # pylint: disable=W0611
8
+ _BackendQTAgg, FigureCanvasQTAgg, FigureManagerQT, NavigationToolbar2QT,
9
+ FigureCanvasAgg, FigureCanvasQT)
10
+
11
+
12
+ @_BackendQTAgg.export
13
+ class _BackendQT5Agg(_BackendQTAgg):
14
+ pass
shared/package-files/56/56200dff83bb581b078ee68656999e720a8916f51ea86e52ea7123753ac149fd/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56200dff83bb581b078ee68656999e720a8916f51ea86e52ea7123753ac149fd
3
+ size 342392
shared/package-files/56/562173cf3e5a16d3dc69ef89fd17b99d9aefbd1789fc63443d84f01b855ef8cc/blob ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/_reshape_copy_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_reshape_copy(Tensor self, SymInt[] size) -> Tensor
26
+ inline at::Tensor _reshape_copy(const at::Tensor & self, at::IntArrayRef size) {
27
+ return at::_ops::_reshape_copy::call(self, c10::fromIntArrayRefSlow(size));
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ at::Tensor _reshape_copy(const at::Tensor & self, at::IntArrayRef size) {
32
+ return at::_ops::_reshape_copy::call(self, c10::fromIntArrayRefSlow(size));
33
+ }
34
+ }
35
+
36
+ // aten::_reshape_copy(Tensor self, SymInt[] size) -> Tensor
37
+ inline at::Tensor _reshape_copy_symint(const at::Tensor & self, c10::SymIntArrayRef size) {
38
+ return at::_ops::_reshape_copy::call(self, size);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ at::Tensor _reshape_copy(const at::Tensor & self, c10::SymIntArrayRef size) {
43
+ return at::_ops::_reshape_copy::call(self, size);
44
+ }
45
+ }
46
+
47
+ }
shared/package-files/56/5621b7f0f809b08853df1680aee82fc344cf3fa556a0fd95263ec51085b2a648/blob ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from contextlib import suppress
6
+ from errno import ENOSYS
7
+ from typing import cast
8
+
9
+ from ._api import BaseFileLock
10
+ from ._util import ensure_directory_exists
11
+
12
+ #: a flag to indicate if the fcntl API is available
13
+ has_fcntl = False
14
+ if sys.platform == "win32": # pragma: win32 cover
15
+
16
+ class UnixFileLock(BaseFileLock):
17
+ """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
18
+
19
+ def _acquire(self) -> None:
20
+ raise NotImplementedError
21
+
22
+ def _release(self) -> None:
23
+ raise NotImplementedError
24
+
25
+ else: # pragma: win32 no cover
26
+ try:
27
+ import fcntl
28
+ except ImportError:
29
+ pass
30
+ else:
31
+ has_fcntl = True
32
+
33
+ class UnixFileLock(BaseFileLock):
34
+ """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
35
+
36
+ def _acquire(self) -> None:
37
+ ensure_directory_exists(self.lock_file)
38
+ open_flags = os.O_RDWR | os.O_CREAT | os.O_TRUNC
39
+ fd = os.open(self.lock_file, open_flags, self._context.mode)
40
+ with suppress(PermissionError): # This locked is not owned by this UID
41
+ os.fchmod(fd, self._context.mode)
42
+ try:
43
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
44
+ except OSError as exception:
45
+ os.close(fd)
46
+ if exception.errno == ENOSYS: # NotImplemented error
47
+ msg = "FileSystem does not appear to support flock; user SoftFileLock instead"
48
+ raise NotImplementedError(msg) from exception
49
+ else:
50
+ self._context.lock_file_fd = fd
51
+
52
+ def _release(self) -> None:
53
+ # Do not remove the lockfile:
54
+ # https://github.com/tox-dev/py-filelock/issues/31
55
+ # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
56
+ fd = cast(int, self._context.lock_file_fd)
57
+ self._context.lock_file_fd = None
58
+ fcntl.flock(fd, fcntl.LOCK_UN)
59
+ os.close(fd)
60
+
61
+
62
+ __all__ = [
63
+ "has_fcntl",
64
+ "UnixFileLock",
65
+ ]
shared/package-files/56/56243a12c4fe44781e453d01d2388a4dfbcfe0107b49a7010b64656cd569a966/blob ADDED
@@ -0,0 +1,1205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Multivariate Conditional and Unconditional Kernel Regression
3
+ with Mixed Data Types
4
+
5
+ References
6
+ ----------
7
+ [1] Racine, J., Li, Q. Nonparametric econometrics: theory and practice.
8
+ Princeton University Press. (2007)
9
+ [2] Racine, Jeff. "Nonparametric Econometrics: A Primer," Foundation
10
+ and Trends in Econometrics: Vol 3: No 1, pp1-88. (2008)
11
+ http://dx.doi.org/10.1561/0800000009
12
+ [3] Racine, J., Li, Q. "Nonparametric Estimation of Distributions
13
+ with Categorical and Continuous Data." Working Paper. (2000)
14
+ [4] Racine, J. Li, Q. "Kernel Estimation of Multivariate Conditional
15
+ Distributions Annals of Economics and Finance 5, 211-235 (2004)
16
+ [5] Liu, R., Yang, L. "Kernel estimation of multivariate
17
+ cumulative distribution function."
18
+ Journal of Nonparametric Statistics (2008)
19
+ [6] Li, R., Ju, G. "Nonparametric Estimation of Multivariate CDF
20
+ with Categorical and Continuous Data." Working Paper
21
+ [7] Li, Q., Racine, J. "Cross-validated local linear nonparametric
22
+ regression" Statistica Sinica 14(2004), pp. 485-512
23
+ [8] Racine, J.: "Consistent Significance Testing for Nonparametric
24
+ Regression" Journal of Business & Economics Statistics
25
+ [9] Racine, J., Hart, J., Li, Q., "Testing the Significance of
26
+ Categorical Predictor Variables in Nonparametric Regression
27
+ Models", 2006, Econometric Reviews 25, 523-544
28
+
29
+ """
30
+
31
+ from statsmodels.compat.pandas import deprecate_kwarg
32
+
33
+ # TODO: make default behavior efficient=True above a certain n_obs
34
+ import copy
35
+ import warnings
36
+
37
+ import numpy as np
38
+ from scipy import optimize
39
+ from scipy.stats.mstats import mquantiles
40
+
41
+ from ._kernel_base import (
42
+ EstimatorSettings,
43
+ GenericKDE,
44
+ LeaveOneOut,
45
+ _adjust_shape,
46
+ _compute_min_std_IQR,
47
+ _get_type_pos,
48
+ gpke,
49
+ initialize_generator,
50
+ kernel_func,
51
+ )
52
+
53
+ __all__ = ["KernelCensoredReg", "KernelReg"]
54
+
55
+
56
+ class KernelReg(GenericKDE):
57
+ """
58
+ Nonparametric kernel regression class
59
+
60
+ Calculates the conditional mean ``E[y|X]`` where ``y = g(X) + e``.
61
+ Note that the "local constant" type of regression provided here is also
62
+ known as Nadaraya-Watson kernel regression; "local linear" is an extension
63
+ of that which suffers less from bias issues at the edge of the support. Note
64
+ that specifying a custom kernel works only with "local linear" kernel
65
+ regression. For example, a custom ``tricube`` kernel yields LOESS regression.
66
+
67
+ Parameters
68
+ ----------
69
+ endog : array_like
70
+ This is the dependent variable.
71
+ exog : array_like
72
+ The training data for the independent variable(s)
73
+ Each element in the list is a separate variable
74
+ var_type : str
75
+ The type of the variables, one character per variable:
76
+
77
+ - c: continuous
78
+ - u: unordered (discrete)
79
+ - o: ordered (discrete)
80
+
81
+ reg_type : {'lc', 'll'}, optional
82
+ Type of regression estimator. 'lc' means local constant and
83
+ 'll' local Linear estimator. Default is 'll'
84
+ bw : str or array_like, optional
85
+ Either a user-specified bandwidth or the method for bandwidth
86
+ selection. If a string, valid values are 'cv_ls' (least-squares
87
+ cross-validation) and 'aic' (AIC Hurvich bandwidth estimation).
88
+ Default is 'cv_ls'. User specified bandwidth must have as many
89
+ entries as the number of variables.
90
+ ckertype : str, optional
91
+ The kernel used for the continuous variables.
92
+ okertype : str, optional
93
+ The kernel used for the ordered discrete variables.
94
+ ukertype : str, optional
95
+ The kernel used for the unordered discrete variables.
96
+ defaults : EstimatorSettings instance, optional
97
+ The default values for the efficient bandwidth estimation.
98
+ rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional
99
+ If `rng` is None, the legacy global (singleton) ``RandomState``
100
+ provided by ``numpy.random`` is used; this behavior is
101
+ deprecated and will change to creating a new ``Generator``
102
+ using fresh entropy from the operating system in a future
103
+ release. If `rng` is an int or array of ints, a new
104
+ ``Generator`` is created, seeded with `rng`. If `rng` is
105
+ already a ``Generator`` or ``RandomState`` instance, that
106
+ instance is used.
107
+
108
+ .. deprecated:: 0.15.0
109
+
110
+ In release 0.17.0 or after January 2028, whichever comes sooner,
111
+ using None will initialize a new numpy.random.default_rng using
112
+ system entropy.
113
+
114
+ Attributes
115
+ ----------
116
+ bw : ndarray
117
+ The bandwidth parameters.
118
+ """
119
+
120
+ @deprecate_kwarg("seed", "rng")
121
+ def __init__(
122
+ self,
123
+ endog,
124
+ exog,
125
+ var_type,
126
+ reg_type="ll",
127
+ bw="cv_ls",
128
+ ckertype="gaussian",
129
+ okertype="wangryzin",
130
+ ukertype="aitchisonaitken",
131
+ defaults=None,
132
+ *,
133
+ rng=None,
134
+ ):
135
+ self.var_type = var_type
136
+ self.data_type = var_type
137
+ self.reg_type = reg_type
138
+ self.ckertype = ckertype
139
+ self.okertype = okertype
140
+ self.ukertype = ukertype
141
+ if not (
142
+ self.ckertype in kernel_func
143
+ and self.ukertype in kernel_func
144
+ and self.okertype in kernel_func
145
+ ):
146
+ raise ValueError(
147
+ "user specified kernel must be a supported "
148
+ "kernel from statsmodels.nonparametric.kernels."
149
+ )
150
+
151
+ self.k_vars = len(self.var_type)
152
+ self.endog = _adjust_shape(endog, 1)
153
+ self.exog = _adjust_shape(exog, self.k_vars)
154
+ self.data = np.column_stack((self.endog, self.exog))
155
+ self.nobs = np.shape(self.exog)[0]
156
+ self.est = dict(lc=self._est_loc_constant, ll=self._est_loc_linear)
157
+ defaults = EstimatorSettings() if defaults is None else defaults
158
+ self._set_defaults(defaults)
159
+ self.seed = rng
160
+ self.rng = rng
161
+ self._generator = initialize_generator(rng)
162
+ if not isinstance(bw, str):
163
+ bw = np.asarray(bw)
164
+ if len(bw) != self.k_vars:
165
+ raise ValueError(
166
+ "bw must have the same dimension as the number of variables."
167
+ )
168
+ if not self.efficient:
169
+ self.bw = self._compute_reg_bw(bw)
170
+ else:
171
+ self.bw = self._compute_efficient(bw)
172
+
173
+ def _compute_reg_bw(self, bw):
174
+ if not isinstance(bw, str):
175
+ self._bw_method = "user-specified"
176
+ return np.asarray(bw)
177
+ else:
178
+ # The user specified a bandwidth selection method e.g., 'cv_ls'
179
+ self._bw_method = bw
180
+ # Workaround to avoid instance methods in __dict__
181
+ if bw == "cv_ls":
182
+ res = self.cv_loo
183
+ else: # bw == 'aic'
184
+ res = self.aic_hurvich
185
+ X = np.std(self.exog, axis=0)
186
+ h0 = 1.06 * X * self.nobs ** (-1.0 / (4 + np.size(self.exog, axis=1)))
187
+
188
+ func = self.est[self.reg_type]
189
+ bw_estimated = optimize.fmin(
190
+ res, x0=h0, args=(func,), maxiter=1e3, maxfun=1e3, disp=0
191
+ )
192
+ return bw_estimated
193
+
194
+ def _est_loc_linear(self, bw, endog, exog, data_predict):
195
+ """
196
+ Local linear estimator of g(x) in the regression ``y = g(x) + e``
197
+
198
+ Parameters
199
+ ----------
200
+ bw : array_like
201
+ Vector of bandwidth value(s).
202
+ endog : 1D array_like
203
+ The dependent variable.
204
+ exog : 1D or 2D array_like
205
+ The independent variable(s).
206
+ data_predict : 1D array_like of length K, where K is the number of variables.
207
+ The point at which the conditional mean is estimated.
208
+
209
+ Returns
210
+ -------
211
+ mean : ndarray
212
+ The value of the conditional mean at `data_predict`.
213
+ mfx : ndarray
214
+ The marginal effects.
215
+
216
+ Notes
217
+ -----
218
+ See p. 81 in [1] and p.38 in [2] for the formulas.
219
+ Unlike other methods, this one requires that `data_predict` be 1D.
220
+ """
221
+ nobs, k_vars = exog.shape
222
+ ker = gpke(
223
+ bw,
224
+ data=exog,
225
+ data_predict=data_predict,
226
+ var_type=self.var_type,
227
+ ckertype=self.ckertype,
228
+ ukertype=self.ukertype,
229
+ okertype=self.okertype,
230
+ tosum=False,
231
+ ) / float(nobs)
232
+ # Create the matrix on p.492 in [7], after the multiplication w/ K_h,ij
233
+ # See also p. 38 in [2]
234
+ # ix_cont = np.arange(self.k_vars) # Use all vars instead of continuous only
235
+ # Note: because ix_cont was defined here such that it selected all
236
+ # columns, I removed the indexing with it from exog/data_predict.
237
+
238
+ # Convert ker to a 2-D array to make matrix operations below work
239
+ ker = ker[:, np.newaxis]
240
+
241
+ M12 = exog - data_predict
242
+ M22 = np.dot(M12.T, M12 * ker)
243
+ M12 = (M12 * ker).sum(axis=0)
244
+ M = np.empty((k_vars + 1, k_vars + 1))
245
+ M[0, 0] = ker.sum()
246
+ M[0, 1:] = M12
247
+ M[1:, 0] = M12
248
+ M[1:, 1:] = M22
249
+
250
+ ker_endog = ker * endog
251
+ V = np.empty((k_vars + 1, 1))
252
+ V[0, 0] = ker_endog.sum()
253
+ V[1:, 0] = ((exog - data_predict) * ker_endog).sum(axis=0)
254
+
255
+ mean_mfx = np.dot(np.linalg.pinv(M), V)
256
+ mean = mean_mfx[0]
257
+ mfx = mean_mfx[1:, :]
258
+ return mean, mfx
259
+
260
+ def _est_loc_constant(self, bw, endog, exog, data_predict):
261
+ """
262
+ Local constant estimator of g(x) in the regression
263
+ y = g(x) + e
264
+
265
+ Parameters
266
+ ----------
267
+ bw : array_like
268
+ Array of bandwidth value(s).
269
+ endog : 1D array_like
270
+ The dependent variable.
271
+ exog : 1D or 2D array_like
272
+ The independent variable(s).
273
+ data_predict : 1D or 2D array_like
274
+ The point(s) at which the conditional mean is estimated.
275
+
276
+ Returns
277
+ -------
278
+ G : ndarray
279
+ The value of the conditional mean at `data_predict`.
280
+ B_x : ndarray
281
+ The marginal effects.
282
+ """
283
+ ker_x = gpke(
284
+ bw,
285
+ data=exog,
286
+ data_predict=data_predict,
287
+ var_type=self.var_type,
288
+ ckertype=self.ckertype,
289
+ ukertype=self.ukertype,
290
+ okertype=self.okertype,
291
+ tosum=False,
292
+ )
293
+ ker_x = np.reshape(ker_x, np.shape(endog))
294
+ G_numer = (ker_x * endog).sum(axis=0)
295
+ G_denom = ker_x.sum(axis=0)
296
+ G = G_numer / G_denom
297
+ nobs = exog.shape[0]
298
+ f_x = G_denom / float(nobs)
299
+ ker_xc = gpke(
300
+ bw,
301
+ data=exog,
302
+ data_predict=data_predict,
303
+ var_type=self.var_type,
304
+ ckertype="d_gaussian",
305
+ # okertype='wangryzin_reg',
306
+ tosum=False,
307
+ )
308
+
309
+ ker_xc = ker_xc[:, np.newaxis]
310
+ d_mx = -(endog * ker_xc).sum(axis=0) / float(nobs) # * np.prod(bw[:, ix_cont]))
311
+ d_fx = -ker_xc.sum(axis=0) / float(nobs) # * np.prod(bw[:, ix_cont]))
312
+ B_x = d_mx / f_x - G * d_fx / f_x
313
+ B_x = (G_numer * d_fx - G_denom * d_mx) / (G_denom**2)
314
+ # B_x = (f_x * d_mx - m_x * d_fx) / (f_x ** 2)
315
+ return G, B_x
316
+
317
+ def aic_hurvich(self, bw, func=None):
318
+ """
319
+ Computes the AIC Hurvich criteria for the estimation of the bandwidth
320
+
321
+ Parameters
322
+ ----------
323
+ bw : array_like
324
+ Vector of bandwidth value(s) at which to evaluate the criterion.
325
+ func : callable, optional
326
+ Unused here, needed in signature because it's used in `cv_loo`.
327
+
328
+ Returns
329
+ -------
330
+ aic : ndarray
331
+ The value of the AIC Hurvich criterion.
332
+
333
+ References
334
+ ----------
335
+ See ch.2 in [1] and p.35 in [2].
336
+ """
337
+ H = np.empty((self.nobs, self.nobs))
338
+ for j in range(self.nobs):
339
+ H[:, j] = gpke(
340
+ bw,
341
+ data=self.exog,
342
+ data_predict=self.exog[j, :],
343
+ ckertype=self.ckertype,
344
+ ukertype=self.ukertype,
345
+ okertype=self.okertype,
346
+ var_type=self.var_type,
347
+ tosum=False,
348
+ )
349
+
350
+ denom = H.sum(axis=1)
351
+ H = H / denom
352
+ gx = KernelReg(
353
+ endog=self.endog,
354
+ exog=self.exog,
355
+ var_type=self.var_type,
356
+ reg_type=self.reg_type,
357
+ bw=bw,
358
+ defaults=EstimatorSettings(efficient=False),
359
+ ).fit()[0]
360
+ gx = np.reshape(gx, (self.nobs, 1))
361
+ sigma = ((self.endog - gx) ** 2).sum(axis=0) / float(self.nobs)
362
+
363
+ frac = (1 + np.trace(H) / float(self.nobs)) / (
364
+ 1 - (np.trace(H) + 2) / float(self.nobs)
365
+ )
366
+ # siga = np.dot(self.endog.T, (I - H).T)
367
+ # sigb = np.dot((I - H), self.endog)
368
+ # sigma = np.dot(siga, sigb) / float(self.nobs)
369
+ aic = np.log(sigma) + frac
370
+ return aic
371
+
372
+ def cv_loo(self, bw, func):
373
+ r"""
374
+ The cross-validation function with leave-one-out estimator
375
+
376
+ Parameters
377
+ ----------
378
+ bw : array_like
379
+ Vector of bandwidth values.
380
+ func : callable
381
+ Returns the estimator of g(x). Can be either ``_est_loc_constant``
382
+ (local constant) or ``_est_loc_linear`` (local_linear).
383
+
384
+ Returns
385
+ -------
386
+ L : float
387
+ The value of the CV function.
388
+
389
+ Notes
390
+ -----
391
+ Calculates the cross-validation least-squares function. This function
392
+ is minimized by compute_bw to calculate the optimal value of `bw`.
393
+
394
+ For details see p.35 in [2]
395
+
396
+ .. math:: CV(h)=n^{-1}\sum_{i=1}^{n}(Y_{i}-g_{-i}(X_{i}))^{2}
397
+
398
+ where :math:`g_{-i}(X_{i})` is the leave-one-out estimator of g(X)
399
+ and :math:`h` is the vector of bandwidths
400
+ """
401
+ LOO_X = LeaveOneOut(self.exog)
402
+ LOO_Y = LeaveOneOut(self.endog).__iter__()
403
+ L = 0
404
+ for ii, X_not_i in enumerate(LOO_X):
405
+ Y = next(LOO_Y)
406
+ G = func(bw, endog=Y, exog=-X_not_i, data_predict=-self.exog[ii, :])[0]
407
+ L += (self.endog[ii] - G) ** 2
408
+
409
+ # Note: There might be a way to vectorize this. See p.72 in [1]
410
+ return L / self.nobs
411
+
412
+ def r_squared(self):
413
+ r"""
414
+ Returns the R-Squared for the nonparametric regression
415
+
416
+ Returns
417
+ -------
418
+ r2 : float
419
+ The R-Squared statistic computed from the fitted mean.
420
+
421
+ Notes
422
+ -----
423
+ For more details see p.45 in [2]
424
+ The R-Squared is calculated by:
425
+
426
+ .. math:: R^{2}=\frac{\left[\sum_{i=1}^{n}
427
+ (Y_{i}-\bar{y})(\hat{Y_{i}}-\bar{y}\right]^{2}}{\sum_{i=1}^{n}
428
+ (Y_{i}-\bar{y})^{2}\sum_{i=1}^{n}(\hat{Y_{i}}-\bar{y})^{2}},
429
+
430
+ where :math:`\hat{Y_{i}}` is the mean calculated in `fit` at the exog
431
+ points.
432
+ """
433
+ Y = np.squeeze(self.endog)
434
+ Yhat = self.fit()[0]
435
+ Y_bar = np.mean(Yhat)
436
+ R2_numer = (((Y - Y_bar) * (Yhat - Y_bar)).sum()) ** 2
437
+ R2_denom = ((Y - Y_bar) ** 2).sum(axis=0) * ((Yhat - Y_bar) ** 2).sum(axis=0)
438
+ return R2_numer / R2_denom
439
+
440
+ def fit(self, data_predict=None):
441
+ """
442
+ Returns the mean and marginal effects at the `data_predict` points
443
+
444
+ Parameters
445
+ ----------
446
+ data_predict : array_like, optional
447
+ Points at which to return the mean and marginal effects. If not
448
+ given, ``data_predict == exog``.
449
+
450
+ Returns
451
+ -------
452
+ mean : ndarray
453
+ The regression result for the mean (i.e., the actual curve).
454
+ mfx : ndarray
455
+ The marginal effects, i.e., the partial derivatives of the mean.
456
+ """
457
+ func = self.est[self.reg_type]
458
+ if data_predict is None:
459
+ data_predict = self.exog
460
+ else:
461
+ data_predict = _adjust_shape(data_predict, self.k_vars)
462
+
463
+ N_data_predict = np.shape(data_predict)[0]
464
+ mean = np.empty((N_data_predict,))
465
+ mfx = np.empty((N_data_predict, self.k_vars))
466
+ for i in range(N_data_predict):
467
+ mean_mfx = func(
468
+ self.bw, self.endog, self.exog, data_predict=data_predict[i, :]
469
+ )
470
+ mean[i] = np.squeeze(mean_mfx[0])
471
+ mfx_c = np.squeeze(mean_mfx[1])
472
+ mfx[i, :] = mfx_c
473
+
474
+ return mean, mfx
475
+
476
+ def sig_test(self, var_pos, nboot=50, nested_res=25, pivot=False):
477
+ """
478
+ Significance test for the variables in the regression
479
+
480
+ Parameters
481
+ ----------
482
+ var_pos : array_like of int
483
+ The position of the variable in exog to be tested.
484
+ nboot : int, optional
485
+ Number of bootstrap samples used to determine the distribution
486
+ of the test statistic in a finite sample. Default is 50.
487
+ nested_res : int, optional
488
+ Number of nested resamples used to calculate lambda when
489
+ `pivot` is True. Default is 25.
490
+ pivot : bool, optional
491
+ Pivot the test statistic by dividing by its standard error.
492
+ Significantly increases computational time, but pivot
493
+ statistics have more desirable properties. Default is False.
494
+
495
+ Returns
496
+ -------
497
+ sig : str
498
+ The level of significance:
499
+
500
+ - `*` : at 90% confidence level
501
+ - `**` : at 95% confidence level
502
+ - `***` : at 99% confidence level
503
+ - "Not Significant" : if not significant
504
+ """
505
+ var_pos = np.asarray(var_pos)
506
+ ix_cont, ix_ord, ix_unord = _get_type_pos(self.var_type)
507
+ if np.any(ix_cont[var_pos]):
508
+ if np.any(ix_ord[var_pos]) or np.any(ix_unord[var_pos]):
509
+ raise ValueError("Discrete variable in hypothesis. Must be continuous")
510
+
511
+ Sig = TestRegCoefC(self, var_pos, nboot, nested_res, pivot, rng=self.rng)
512
+ else:
513
+ Sig = TestRegCoefD(self, var_pos, nboot, rng=self.rng)
514
+
515
+ return Sig.sig
516
+
517
+ def __repr__(self):
518
+ """Provide something sane to print"""
519
+ rpr = "KernelReg instance\n"
520
+ rpr += "Number of variables: k_vars = " + str(self.k_vars) + "\n"
521
+ rpr += "Number of samples: N = " + str(self.nobs) + "\n"
522
+ rpr += "Variable types: " + self.var_type + "\n"
523
+ rpr += "BW selection method: " + self._bw_method + "\n"
524
+ rpr += "Estimator type: " + self.reg_type + "\n"
525
+ return rpr
526
+
527
+ def _get_class_vars_type(self):
528
+ """Helper method to be able to pass needed vars to _compute_subset"""
529
+ class_type = "KernelReg"
530
+ class_vars = (self.var_type, self.k_vars, self.reg_type)
531
+ return class_type, class_vars
532
+
533
+ def _compute_dispersion(self, data):
534
+ """
535
+ Computes the measure of dispersion
536
+
537
+ The minimum of the standard deviation and interquartile range / 1.349
538
+
539
+ Parameters
540
+ ----------
541
+ data : ndarray
542
+ The data array, with the dependent variable in the first column
543
+ and the independent variables in the remaining columns.
544
+
545
+ Returns
546
+ -------
547
+ ndarray
548
+ The minimum of the standard deviation and IQR / 1.349 for each
549
+ independent variable.
550
+
551
+ References
552
+ ----------
553
+ See the user guide for the np package in R.
554
+ In the notes on bwscaling option in npreg, npudens, npcdens there is
555
+ a discussion on the measure of dispersion
556
+ """
557
+ data = data[:, 1:]
558
+ return _compute_min_std_IQR(data)
559
+
560
+
561
+ class KernelCensoredReg(KernelReg):
562
+ """
563
+ Nonparametric censored regression
564
+
565
+ Calculates the conditional mean ``E[y|X]`` where ``y = g(X) + e``,
566
+ where y is left-censored. Left censored variable Y is defined as
567
+ ``Y = min {Y', L}`` where ``L`` is the value at which ``Y`` is censored
568
+ and ``Y'`` is the true value of the variable.
569
+
570
+ Parameters
571
+ ----------
572
+ endog : array_like
573
+ This is the dependent variable.
574
+ exog : array_like
575
+ The training data for the independent variable(s)
576
+ Each element in the list is a separate variable
577
+ var_type : str
578
+ The type of the variables, one character per variable:
579
+
580
+ - c: Continuous
581
+ - u: Unordered (Discrete)
582
+ - o: Ordered (Discrete)
583
+
584
+ reg_type : str
585
+ Type of regression estimator
586
+
587
+ - lc: Local Constant Estimator
588
+ - ll: Local Linear Estimator
589
+
590
+ bw : str or array_like, optional
591
+ Either a user-specified bandwidth or
592
+ the method for bandwidth selection.
593
+
594
+ - cv_ls: cross-validation least squares
595
+ - aic: AIC Hurvich Estimator
596
+
597
+ ckertype : str, optional
598
+ The kernel used for the continuous variables.
599
+ okertype : str, optional
600
+ The kernel used for the ordered discrete variables.
601
+ ukertype : str, optional
602
+ The kernel used for the unordered discrete variables.
603
+ censor_val : float, optional
604
+ Value at which the dependent variable is censored. Default is 0.
605
+ defaults : EstimatorSettings instance, optional
606
+ The default values for the efficient bandwidth estimation
607
+ rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional
608
+ If `rng` is None, the legacy global (singleton) ``RandomState``
609
+ provided by ``numpy.random`` is used; this behavior is
610
+ deprecated and will change to creating a new ``Generator``
611
+ using fresh entropy from the operating system in a future
612
+ release. If `rng` is an int or array of ints, a new
613
+ ``Generator`` is created, seeded with `rng`. If `rng` is
614
+ already a ``Generator`` or ``RandomState`` instance, that
615
+ instance is used.
616
+
617
+ .. deprecated:: 0.15.0
618
+
619
+ In release 0.17.0 or after January 2028, whichever comes sooner,
620
+ using None will initialize a new numpy.random.default_rng using
621
+ system entropy.
622
+
623
+ Attributes
624
+ ----------
625
+ bw : ndarray
626
+ The bandwidth parameters
627
+ """
628
+
629
+ @deprecate_kwarg("seed", "rng")
630
+ def __init__(
631
+ self,
632
+ endog,
633
+ exog,
634
+ var_type,
635
+ reg_type,
636
+ bw="cv_ls",
637
+ ckertype="gaussian",
638
+ ukertype="aitchison_aitken_reg",
639
+ okertype="wangryzin_reg",
640
+ censor_val=0,
641
+ defaults=None,
642
+ *,
643
+ rng=None,
644
+ ):
645
+ self.var_type = var_type
646
+ self.data_type = var_type
647
+ self.reg_type = reg_type
648
+ self.ckertype = ckertype
649
+ self.okertype = okertype
650
+ self.ukertype = ukertype
651
+ if not (
652
+ self.ckertype in kernel_func
653
+ and self.ukertype in kernel_func
654
+ and self.okertype in kernel_func
655
+ ):
656
+ raise ValueError(
657
+ "user specified kernel must be a supported "
658
+ "kernel from statsmodels.nonparametric.kernels."
659
+ )
660
+
661
+ self.k_vars = len(self.var_type)
662
+ self.endog = _adjust_shape(endog, 1)
663
+ self.exog = _adjust_shape(exog, self.k_vars)
664
+ self.data = np.column_stack((self.endog, self.exog))
665
+ self.nobs = np.shape(self.exog)[0]
666
+ self.est = dict(lc=self._est_loc_constant, ll=self._est_loc_linear)
667
+ self._generator = initialize_generator(rng)
668
+ defaults = EstimatorSettings() if defaults is None else defaults
669
+ self._set_defaults(defaults)
670
+ self.censor_val = censor_val
671
+ if self.censor_val is not None:
672
+ self.censored(censor_val)
673
+ else:
674
+ self.W_in = np.ones((self.nobs, 1))
675
+
676
+ if not self.efficient:
677
+ self.bw = self._compute_reg_bw(bw)
678
+ else:
679
+ self.bw = self._compute_efficient(bw)
680
+
681
+ def censored(self, censor_val):
682
+ # see pp. 341-344 in [1]
683
+ self.d = (self.endog != censor_val) * 1.0
684
+ ix = np.argsort(np.squeeze(self.endog))
685
+ self.sortix = ix
686
+ self.sortix_rev = np.zeros(ix.shape, int)
687
+ self.sortix_rev[ix] = np.arange(len(ix))
688
+ self.endog = np.squeeze(self.endog[ix])
689
+ self.endog = _adjust_shape(self.endog, 1)
690
+ self.exog = np.squeeze(self.exog[ix])
691
+ self.d = np.squeeze(self.d[ix])
692
+ self.W_in = np.empty((self.nobs, 1))
693
+ for i in range(1, self.nobs + 1):
694
+ P = 1
695
+ for j in range(1, i):
696
+ P *= ((self.nobs - j) / (float(self.nobs) - j + 1)) ** self.d[j - 1]
697
+ self.W_in[i - 1, 0] = P * self.d[i - 1] / (float(self.nobs) - i + 1)
698
+
699
+ def __repr__(self):
700
+ """Provide something sane to print"""
701
+ rpr = "KernelCensoredReg instance\n"
702
+ rpr += "Number of variables: k_vars = " + str(self.k_vars) + "\n"
703
+ rpr += "Number of samples: nobs = " + str(self.nobs) + "\n"
704
+ rpr += "Variable types: " + self.var_type + "\n"
705
+ rpr += "BW selection method: " + self._bw_method + "\n"
706
+ rpr += "Estimator type: " + self.reg_type + "\n"
707
+ return rpr
708
+
709
+ def _est_loc_linear(self, bw, endog, exog, data_predict, W):
710
+ """
711
+ Local linear estimator of g(x) in the regression ``y = g(x) + e``
712
+
713
+ Parameters
714
+ ----------
715
+ bw : array_like
716
+ Vector of bandwidth value(s)
717
+ endog : 1D array_like
718
+ The dependent variable
719
+ exog : 1D or 2D array_like
720
+ The independent variable(s)
721
+ data_predict : 1D array_like of length K, where K is
722
+ the number of variables. The point at which
723
+ the conditional mean is estimated
724
+ W : array_like
725
+ The weights used to account for the censoring, as computed by
726
+ `censored`.
727
+
728
+ Returns
729
+ -------
730
+ mean : ndarray
731
+ The value of the conditional mean at data_predict
732
+ mfx : ndarray
733
+ The marginal effects.
734
+
735
+ Notes
736
+ -----
737
+ See p. 81 in [1] and p.38 in [2] for the formulas
738
+ Unlike other methods, this one requires that data_predict be 1D
739
+ """
740
+ nobs, k_vars = exog.shape
741
+ ker = gpke(
742
+ bw,
743
+ data=exog,
744
+ data_predict=data_predict,
745
+ var_type=self.var_type,
746
+ ckertype=self.ckertype,
747
+ ukertype=self.ukertype,
748
+ okertype=self.okertype,
749
+ tosum=False,
750
+ )
751
+ # Create the matrix on p.492 in [7], after the multiplication w/ K_h,ij
752
+ # See also p. 38 in [2]
753
+
754
+ # Convert ker to a 2-D array to make matrix operations below work
755
+ ker = W * ker[:, np.newaxis]
756
+
757
+ M12 = exog - data_predict
758
+ M22 = np.dot(M12.T, M12 * ker)
759
+ M12 = (M12 * ker).sum(axis=0)
760
+ M = np.empty((k_vars + 1, k_vars + 1))
761
+ M[0, 0] = ker.sum()
762
+ M[0, 1:] = M12
763
+ M[1:, 0] = M12
764
+ M[1:, 1:] = M22
765
+
766
+ ker_endog = ker * endog
767
+ V = np.empty((k_vars + 1, 1))
768
+ V[0, 0] = ker_endog.sum()
769
+ V[1:, 0] = ((exog - data_predict) * ker_endog).sum(axis=0)
770
+
771
+ mean_mfx = np.dot(np.linalg.pinv(M), V)
772
+ mean = mean_mfx[0]
773
+ mfx = mean_mfx[1:, :]
774
+ return mean, mfx
775
+
776
+ def cv_loo(self, bw, func):
777
+ r"""
778
+ The cross-validation function with leave-one-out
779
+ estimator
780
+
781
+ Parameters
782
+ ----------
783
+ bw : array_like
784
+ Vector of bandwidth values
785
+ func : callable
786
+ Returns the estimator of g(x).
787
+ Can be either ``_est_loc_constant`` (local constant) or
788
+ ``_est_loc_linear`` (local_linear).
789
+
790
+ Returns
791
+ -------
792
+ L : float
793
+ The value of the CV function
794
+
795
+ Notes
796
+ -----
797
+ Calculates the cross-validation least-squares
798
+ function. This function is minimized by compute_bw
799
+ to calculate the optimal value of bw
800
+
801
+ For details see p.35 in [2]
802
+
803
+ .. math:: CV(h)=n^{-1}\sum_{i=1}^{n}(Y_{i}-g_{-i}(X_{i}))^{2}
804
+
805
+ where :math:`g_{-i}(X_{i})` is the leave-one-out estimator of g(X)
806
+ and :math:`h` is the vector of bandwidths
807
+ """
808
+ LOO_X = LeaveOneOut(self.exog)
809
+ LOO_Y = LeaveOneOut(self.endog).__iter__()
810
+ LOO_W = LeaveOneOut(self.W_in).__iter__()
811
+ L = 0
812
+ for ii, X_not_i in enumerate(LOO_X):
813
+ Y = next(LOO_Y)
814
+ w = next(LOO_W)
815
+ G = func(bw, endog=Y, exog=-X_not_i, data_predict=-self.exog[ii, :], W=w)[0]
816
+ L += (self.endog[ii] - G) ** 2
817
+
818
+ # Note: There might be a way to vectorize this. See p.72 in [1]
819
+ return L / self.nobs
820
+
821
+ def fit(self, data_predict=None):
822
+ """
823
+ Returns the mean and marginal effects at the `data_predict` points
824
+
825
+ Parameters
826
+ ----------
827
+ data_predict : array_like, optional
828
+ Points at which to return the mean and marginal effects. If not
829
+ given, ``data_predict == exog``.
830
+
831
+ Returns
832
+ -------
833
+ mean : ndarray
834
+ The regression result for the mean (i.e., the actual curve).
835
+ mfx : ndarray
836
+ The marginal effects, i.e., the partial derivatives of the mean.
837
+ """
838
+ func = self.est[self.reg_type]
839
+ if data_predict is None:
840
+ data_predict = self.exog
841
+ else:
842
+ data_predict = _adjust_shape(data_predict, self.k_vars)
843
+
844
+ N_data_predict = np.shape(data_predict)[0]
845
+ mean = np.empty((N_data_predict,))
846
+ mfx = np.empty((N_data_predict, self.k_vars))
847
+ for i in range(N_data_predict):
848
+ mean_mfx = func(
849
+ self.bw,
850
+ self.endog,
851
+ self.exog,
852
+ data_predict=data_predict[i, :],
853
+ W=self.W_in,
854
+ )
855
+ mean[i] = np.squeeze(mean_mfx[0])
856
+ mfx_c = np.squeeze(mean_mfx[1])
857
+ mfx[i, :] = mfx_c
858
+
859
+ return mean, mfx
860
+
861
+
862
+ class TestRegCoefC:
863
+ """
864
+ Significance test for continuous variables in a nonparametric regression
865
+
866
+ The null hypothesis is ``dE(Y|X)/dX_not_i = 0``, the alternative hypothesis
867
+ is ``dE(Y|X)/dX_not_i != 0``.
868
+
869
+ Parameters
870
+ ----------
871
+ model : KernelReg instance
872
+ This is the nonparametric regression model whose elements
873
+ are tested for significance.
874
+ test_vars : sequence of int
875
+ index of position of the continuous variables to be tested
876
+ for significance. e.g., (1,3,5) jointly tests variables at
877
+ position 1,3 and 5 for significance.
878
+ nboot : int, optional
879
+ Number of bootstrap samples used to determine the distribution
880
+ of the test statistic in a finite sample. Default is 400
881
+ nested_res : int, optional
882
+ Number of nested resamples used to calculate lambda. Default is 400.
883
+ Must enable the pivot option
884
+ pivot : bool, optional
885
+ Pivot the test statistic by dividing by its standard error
886
+ Significantly increases computational time. But pivot statistics
887
+ have more desirable properties
888
+ (See references). Default is False.
889
+ rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional
890
+ If `rng` is None, the legacy global (singleton) ``RandomState``
891
+ provided by ``numpy.random`` is used; this behavior is
892
+ deprecated and will change to creating a new ``Generator``
893
+ using fresh entropy from the operating system in a future
894
+ release. If `rng` is an int or array of ints, a new
895
+ ``Generator`` is created, seeded with `rng`. If `rng` is
896
+ already a ``Generator`` or ``RandomState`` instance, that
897
+ instance is used.
898
+
899
+ .. deprecated:: 0.15.0
900
+
901
+ In release 0.17.0 or after January 2028, whichever comes sooner,
902
+ using None will initialize a new numpy.random.default_rng using
903
+ system entropy.
904
+
905
+ Attributes
906
+ ----------
907
+ sig : str
908
+ The significance level of the variable(s) tested
909
+ "Not Significant": Not significant at the 90% confidence level
910
+ Fails to reject the null
911
+ "*": Significant at the 90% confidence level
912
+ "**": Significant at the 95% confidence level
913
+ "***": Significant at the 99% confidence level
914
+
915
+ Notes
916
+ -----
917
+ This class allows testing of joint hypothesis as long as all variables
918
+ are continuous.
919
+
920
+ References
921
+ ----------
922
+ Racine, J.: "Consistent Significance Testing for Nonparametric Regression"
923
+ Journal of Business & Economics Statistics.
924
+
925
+ Chapter 12 in [1].
926
+ """
927
+
928
+ # Significance of continuous vars in nonparametric regression
929
+ # Racine: Consistent Significance Testing for Nonparametric Regression
930
+ # Journal of Business & Economics Statistics
931
+ @deprecate_kwarg("seed", "rng")
932
+ def __init__(
933
+ self, model, test_vars, nboot=400, nested_res=400, pivot=False, rng=None
934
+ ):
935
+ self.nboot = nboot
936
+ self.nres = nested_res
937
+ self.test_vars = test_vars
938
+ self.model = model
939
+ self.bw = model.bw
940
+ self.var_type = model.var_type
941
+ self.k_vars = len(self.var_type)
942
+ self.endog = model.endog
943
+ self.exog = model.exog
944
+ self.gx = model.est[model.reg_type]
945
+ self.test_vars = test_vars
946
+ self.pivot = pivot
947
+ self._generator = initialize_generator(rng)
948
+ self.run()
949
+
950
+ def run(self):
951
+ self.test_stat = self._compute_test_stat(self.endog, self.exog)
952
+ self.sig = self._compute_sig()
953
+
954
+ def _compute_test_stat(self, Y, X):
955
+ """
956
+ Computes the test statistic
957
+
958
+ See p.371 in [8].
959
+ """
960
+ lam = self._compute_lambda(Y, X)
961
+ t = lam
962
+ if self.pivot:
963
+ se_lam = self._compute_se_lambda(Y, X)
964
+ t = lam / float(se_lam)
965
+
966
+ return t
967
+
968
+ def _compute_lambda(self, Y, X):
969
+ """Computes only lambda -- the main part of the test statistic"""
970
+ n = np.shape(X)[0]
971
+ Y = _adjust_shape(Y, 1)
972
+ X = _adjust_shape(X, self.k_vars)
973
+ with warnings.catch_warnings():
974
+ warnings.filterwarnings(
975
+ "ignore",
976
+ category=FutureWarning,
977
+ )
978
+ b = KernelReg(
979
+ Y,
980
+ X,
981
+ self.var_type,
982
+ self.model.reg_type,
983
+ self.bw,
984
+ defaults=EstimatorSettings(efficient=False),
985
+ ).fit()[1]
986
+
987
+ b = b[:, self.test_vars]
988
+ b = np.reshape(b, (n, len(self.test_vars)))
989
+ # fct = np.std(b) # Pivot the statistic by dividing by SE
990
+ fct = 1.0 # Do not Pivot -- Bootstrapping works better if Pivot
991
+ lam = ((b / fct) ** 2).sum() / float(n)
992
+ return lam
993
+
994
+ def _compute_se_lambda(self, Y, X):
995
+ """
996
+ Calculates the SE of lambda by nested resampling
997
+ Used to pivot the statistic.
998
+ Bootstrapping works better with estimating pivotal statistics
999
+ but slows down computation significantly.
1000
+ """
1001
+ n = np.shape(Y)[0]
1002
+ lam = np.empty(shape=(self.nres,))
1003
+ for i in range(self.nres):
1004
+ ind = self._integers(0, n, size=(n, 1))
1005
+ Y1 = Y[ind, 0]
1006
+ X1 = X[ind, :]
1007
+ lam[i] = self._compute_lambda(Y1, X1)
1008
+
1009
+ se_lambda = np.std(lam)
1010
+ return se_lambda
1011
+
1012
+ def _compute_sig(self):
1013
+ """
1014
+ Computes the significance value for the variable(s) tested
1015
+
1016
+ The empirical distribution of the test statistic is obtained through
1017
+ bootstrapping the sample. The null hypothesis is rejected if the test
1018
+ statistic is larger than the 90, 95, 99 percentiles.
1019
+ """
1020
+ t_dist = np.empty(shape=(self.nboot,))
1021
+ Y = self.endog
1022
+ X = copy.deepcopy(self.exog)
1023
+ n = np.shape(Y)[0]
1024
+
1025
+ X[:, self.test_vars] = np.mean(X[:, self.test_vars], axis=0)
1026
+ # Calculate the restricted mean. See p. 372 in [8]
1027
+ with warnings.catch_warnings():
1028
+ warnings.filterwarnings(
1029
+ "ignore",
1030
+ category=FutureWarning,
1031
+ )
1032
+ M = KernelReg(
1033
+ Y,
1034
+ X,
1035
+ self.var_type,
1036
+ self.model.reg_type,
1037
+ self.bw,
1038
+ defaults=EstimatorSettings(efficient=False),
1039
+ ).fit()[0]
1040
+ M = np.reshape(M, (n, 1))
1041
+ e = Y - M
1042
+ e = e - np.mean(e) # recenter residuals
1043
+ for i in range(self.nboot):
1044
+ ind = self._integers(0, n, size=(n, 1))
1045
+ e_boot = e[ind, 0]
1046
+ Y_boot = M + e_boot
1047
+ t_dist[i] = self._compute_test_stat(Y_boot, self.exog)
1048
+
1049
+ self.t_dist = t_dist
1050
+ sig = "Not Significant"
1051
+ if self.test_stat > mquantiles(t_dist, 0.9):
1052
+ sig = "*"
1053
+ if self.test_stat > mquantiles(t_dist, 0.95):
1054
+ sig = "**"
1055
+ if self.test_stat > mquantiles(t_dist, 0.99):
1056
+ sig = "***"
1057
+
1058
+ return sig
1059
+
1060
+ def _integers(self, low: int, upper: int, size: tuple[int, int]):
1061
+ if self._generator is None:
1062
+ return np.random.randint(low, upper, size=size)
1063
+ elif isinstance(self._generator, np.random.RandomState):
1064
+ return self._generator.randint(low, upper, size=size)
1065
+ else:
1066
+ return self._generator.integers(low, upper, size=size)
1067
+
1068
+ def _uniform(self, low: float, upper: float, size: tuple[int, int]):
1069
+ if self._generator is None:
1070
+ return np.random.uniform(low, upper, size=size)
1071
+ return self._generator.uniform(low, upper, size=size)
1072
+
1073
+
1074
+ class TestRegCoefD(TestRegCoefC):
1075
+ """
1076
+ Significance test for the categorical variables in a nonparametric
1077
+ regression
1078
+
1079
+ Parameters
1080
+ ----------
1081
+ model : Instance of KernelReg class
1082
+ This is the nonparametric regression model whose elements
1083
+ are tested for significance.
1084
+ test_vars : sequence of int
1085
+ index of position of the discrete variable to be tested
1086
+ for significance. e.g., (3) tests variable at
1087
+ position 3 for significance.
1088
+ nboot : int, optional
1089
+ Number of bootstrap samples used to determine the distribution
1090
+ of the test statistic in a finite sample. Default is 400
1091
+ rng : int, array_like of int, numpy.random.Generator, or numpy.random.RandomState, optional
1092
+ If `rng` is None, the legacy global (singleton) ``RandomState``
1093
+ provided by ``numpy.random`` is used; this behavior is
1094
+ deprecated and will change to creating a new ``Generator``
1095
+ using fresh entropy from the operating system in a future
1096
+ release. If `rng` is an int or array of ints, a new
1097
+ ``Generator`` is created, seeded with `rng`. If `rng` is
1098
+ already a ``Generator`` or ``RandomState`` instance, that
1099
+ instance is used.
1100
+
1101
+ .. deprecated:: 0.15.0
1102
+
1103
+ In release 0.17.0 or after January 2028, whichever comes sooner,
1104
+ using None will initialize a new numpy.random.default_rng using
1105
+ system entropy.
1106
+
1107
+ Attributes
1108
+ ----------
1109
+ sig : str
1110
+ The significance level of the variable(s) tested
1111
+ "Not Significant": Not significant at the 90% confidence level
1112
+ Fails to reject the null
1113
+ "*": Significant at the 90% confidence level
1114
+ "**": Significant at the 95% confidence level
1115
+ "***": Significant at the 99% confidence level
1116
+
1117
+ Notes
1118
+ -----
1119
+ This class currently does not allow joint hypothesis.
1120
+ Only one variable can be tested at a time
1121
+
1122
+ References
1123
+ ----------
1124
+ See [9] and chapter 12 in [1].
1125
+ """
1126
+
1127
+ def _compute_test_stat(self, Y, X):
1128
+ """Computes the test statistic"""
1129
+
1130
+ dom_x = np.sort(np.unique(self.exog[:, self.test_vars]))
1131
+
1132
+ n = np.shape(X)[0]
1133
+ model = KernelReg(
1134
+ Y,
1135
+ X,
1136
+ self.var_type,
1137
+ self.model.reg_type,
1138
+ self.bw,
1139
+ defaults=EstimatorSettings(efficient=False),
1140
+ rng=self._generator,
1141
+ )
1142
+ X1 = copy.deepcopy(X)
1143
+ X1[:, self.test_vars] = 0
1144
+
1145
+ m0 = model.fit(data_predict=X1)[0]
1146
+ m0 = np.reshape(m0, (n, 1))
1147
+ zvec = np.zeros((n, 1))
1148
+ for i in dom_x[1:]:
1149
+ X1[:, self.test_vars] = i
1150
+ m1 = model.fit(data_predict=X1)[0]
1151
+ m1 = np.reshape(m1, (n, 1))
1152
+ zvec += (m1 - m0) ** 2
1153
+
1154
+ avg = zvec.sum(axis=0) / float(n)
1155
+ return avg
1156
+
1157
+ def _compute_sig(self):
1158
+ """Calculates the significance level of the variable tested"""
1159
+
1160
+ m = self._est_cond_mean()
1161
+ Y = self.endog
1162
+ X = self.exog
1163
+ n = np.shape(X)[0]
1164
+ u = Y - m
1165
+ u = u - np.mean(u) # center
1166
+ fct1 = (1 - 5**0.5) / 2.0
1167
+ fct2 = (1 + 5**0.5) / 2.0
1168
+ u1 = fct1 * u
1169
+ u2 = fct2 * u
1170
+ r = fct2 / (5**0.5)
1171
+ I_dist = np.empty((self.nboot, 1))
1172
+ for j in range(self.nboot):
1173
+ u_boot = copy.deepcopy(u2)
1174
+
1175
+ prob = self._uniform(0, 1, size=(n, 1))
1176
+ ind = prob < r
1177
+ u_boot[ind] = u1[ind]
1178
+ Y_boot = m + u_boot
1179
+ I_dist[j] = self._compute_test_stat(Y_boot, X)
1180
+
1181
+ sig = "Not Significant"
1182
+ if self.test_stat > mquantiles(I_dist, 0.9):
1183
+ sig = "*"
1184
+ if self.test_stat > mquantiles(I_dist, 0.95):
1185
+ sig = "**"
1186
+ if self.test_stat > mquantiles(I_dist, 0.99):
1187
+ sig = "***"
1188
+
1189
+ return sig
1190
+
1191
+ def _est_cond_mean(self):
1192
+ """
1193
+ Calculates the expected conditional mean
1194
+ m(X, Z=l) for all possible l
1195
+ """
1196
+ self.dom_x = np.sort(np.unique(self.exog[:, self.test_vars]))
1197
+ X = copy.deepcopy(self.exog)
1198
+ m = 0
1199
+ for i in self.dom_x:
1200
+ X[:, self.test_vars] = i
1201
+ m += self.model.fit(data_predict=X)[0]
1202
+
1203
+ m = m / float(len(self.dom_x))
1204
+ m = np.reshape(m, (np.shape(self.exog)[0], 1))
1205
+ return m
shared/package-files/56/5625ccbe57902084adaae1cdd350a94d43d8c6ede3802e7b19a08e92e5d1b285/blob ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401
2
+ from .singularities import singularities
3
+ from sympy.core import Pow, S
4
+ from sympy.core.function import diff, expand_mul
5
+ from sympy.core.kind import NumberKind
6
+ from sympy.core.mod import Mod
7
+ from sympy.core.numbers import equal_valued
8
+ from sympy.core.relational import Relational
9
+ from sympy.core.symbol import Symbol, Dummy
10
+ from sympy.core.sympify import _sympify
11
+ from sympy.functions.elementary.complexes import Abs, im, re
12
+ from sympy.functions.elementary.exponential import exp, log
13
+ from sympy.functions.elementary.piecewise import Piecewise
14
+ from sympy.functions.elementary.trigonometric import (
15
+ TrigonometricFunction, sin, cos, csc, sec)
16
+ from sympy.polys.polytools import degree, lcm_list
17
+ from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union,
18
+ Complement)
19
+ from sympy.sets.fancysets import ImageSet
20
+ from sympy.utilities import filldedent
21
+ from sympy.utilities.iterables import iterable
22
+
23
+
24
+ def continuous_domain(f, symbol, domain):
25
+ """
26
+ Returns the intervals in the given domain for which the function
27
+ is continuous.
28
+ This method is limited by the ability to determine the various
29
+ singularities and discontinuities of the given function.
30
+
31
+ Parameters
32
+ ==========
33
+
34
+ f : :py:class:`~.Expr`
35
+ The concerned function.
36
+ symbol : :py:class:`~.Symbol`
37
+ The variable for which the intervals are to be determined.
38
+ domain : :py:class:`~.Interval`
39
+ The domain over which the continuity of the symbol has to be checked.
40
+
41
+ Examples
42
+ ========
43
+
44
+ >>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt
45
+ >>> from sympy.calculus.util import continuous_domain
46
+ >>> x = Symbol('x')
47
+ >>> continuous_domain(1/x, x, S.Reals)
48
+ Union(Interval.open(-oo, 0), Interval.open(0, oo))
49
+ >>> continuous_domain(tan(x), x, Interval(0, pi))
50
+ Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi))
51
+ >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5))
52
+ Interval(2, 5)
53
+ >>> continuous_domain(log(2*x - 1), x, S.Reals)
54
+ Interval.open(1/2, oo)
55
+
56
+ Returns
57
+ =======
58
+
59
+ :py:class:`~.Interval`
60
+ Union of all intervals where the function is continuous.
61
+
62
+ Raises
63
+ ======
64
+
65
+ NotImplementedError
66
+ If the method to determine continuity of such a function
67
+ has not yet been developed.
68
+
69
+ """
70
+ from sympy.solvers.inequalities import solve_univariate_inequality
71
+
72
+ if domain.is_subset(S.Reals):
73
+ constrained_interval = domain
74
+ for atom in f.atoms(Pow):
75
+ den = atom.exp.as_numer_denom()[1]
76
+ if den.is_even and den.is_nonzero:
77
+ constraint = solve_univariate_inequality(atom.base >= 0,
78
+ symbol).as_set()
79
+ constrained_interval = Intersection(constraint,
80
+ constrained_interval)
81
+
82
+ for atom in f.atoms(log):
83
+ constraint = solve_univariate_inequality(atom.args[0] > 0,
84
+ symbol).as_set()
85
+ constrained_interval = Intersection(constraint,
86
+ constrained_interval)
87
+
88
+
89
+ return constrained_interval - singularities(f, symbol, domain)
90
+
91
+
92
+ def function_range(f, symbol, domain):
93
+ """
94
+ Finds the range of a function in a given domain.
95
+ This method is limited by the ability to determine the singularities and
96
+ determine limits.
97
+
98
+ Parameters
99
+ ==========
100
+
101
+ f : :py:class:`~.Expr`
102
+ The concerned function.
103
+ symbol : :py:class:`~.Symbol`
104
+ The variable for which the range of function is to be determined.
105
+ domain : :py:class:`~.Interval`
106
+ The domain under which the range of the function has to be found.
107
+
108
+ Examples
109
+ ========
110
+
111
+ >>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan
112
+ >>> from sympy.calculus.util import function_range
113
+ >>> x = Symbol('x')
114
+ >>> function_range(sin(x), x, Interval(0, 2*pi))
115
+ Interval(-1, 1)
116
+ >>> function_range(tan(x), x, Interval(-pi/2, pi/2))
117
+ Interval(-oo, oo)
118
+ >>> function_range(1/x, x, S.Reals)
119
+ Union(Interval.open(-oo, 0), Interval.open(0, oo))
120
+ >>> function_range(exp(x), x, S.Reals)
121
+ Interval.open(0, oo)
122
+ >>> function_range(log(x), x, S.Reals)
123
+ Interval(-oo, oo)
124
+ >>> function_range(sqrt(x), x, Interval(-5, 9))
125
+ Interval(0, 3)
126
+
127
+ Returns
128
+ =======
129
+
130
+ :py:class:`~.Interval`
131
+ Union of all ranges for all intervals under domain where function is
132
+ continuous.
133
+
134
+ Raises
135
+ ======
136
+
137
+ NotImplementedError
138
+ If any of the intervals, in the given domain, for which function
139
+ is continuous are not finite or real,
140
+ OR if the critical points of the function on the domain cannot be found.
141
+ """
142
+
143
+ if domain is S.EmptySet:
144
+ return S.EmptySet
145
+
146
+ period = periodicity(f, symbol)
147
+ if period == S.Zero:
148
+ # the expression is constant wrt symbol
149
+ return FiniteSet(f.expand())
150
+
151
+ from sympy.series.limits import limit
152
+ from sympy.solvers.solveset import solveset
153
+
154
+ if period is not None:
155
+ if isinstance(domain, Interval):
156
+ if (domain.inf - domain.sup).is_infinite:
157
+ domain = Interval(0, period)
158
+ elif isinstance(domain, Union):
159
+ for sub_dom in domain.args:
160
+ if isinstance(sub_dom, Interval) and \
161
+ ((sub_dom.inf - sub_dom.sup).is_infinite):
162
+ domain = Interval(0, period)
163
+
164
+ intervals = continuous_domain(f, symbol, domain)
165
+ range_int = S.EmptySet
166
+ if isinstance(intervals,(Interval, FiniteSet)):
167
+ interval_iter = (intervals,)
168
+
169
+ elif isinstance(intervals, Union):
170
+ interval_iter = intervals.args
171
+
172
+ else:
173
+ raise NotImplementedError(filldedent('''
174
+ Unable to find range for the given domain.
175
+ '''))
176
+
177
+ for interval in interval_iter:
178
+ if isinstance(interval, FiniteSet):
179
+ for singleton in interval:
180
+ if singleton in domain:
181
+ range_int += FiniteSet(f.subs(symbol, singleton))
182
+ elif isinstance(interval, Interval):
183
+ vals = S.EmptySet
184
+ critical_points = S.EmptySet
185
+ critical_values = S.EmptySet
186
+ bounds = ((interval.left_open, interval.inf, '+'),
187
+ (interval.right_open, interval.sup, '-'))
188
+
189
+ for is_open, limit_point, direction in bounds:
190
+ if is_open:
191
+ critical_values += FiniteSet(limit(f, symbol, limit_point, direction))
192
+ vals += critical_values
193
+
194
+ else:
195
+ vals += FiniteSet(f.subs(symbol, limit_point))
196
+
197
+ solution = solveset(f.diff(symbol), symbol, interval)
198
+
199
+ if not iterable(solution):
200
+ raise NotImplementedError(
201
+ 'Unable to find critical points for {}'.format(f))
202
+ if isinstance(solution, ImageSet):
203
+ raise NotImplementedError(
204
+ 'Infinite number of critical points for {}'.format(f))
205
+
206
+ critical_points += solution
207
+
208
+ for critical_point in critical_points:
209
+ vals += FiniteSet(f.subs(symbol, critical_point))
210
+
211
+ left_open, right_open = False, False
212
+
213
+ if critical_values is not S.EmptySet:
214
+ if critical_values.inf == vals.inf:
215
+ left_open = True
216
+
217
+ if critical_values.sup == vals.sup:
218
+ right_open = True
219
+
220
+ range_int += Interval(vals.inf, vals.sup, left_open, right_open)
221
+ else:
222
+ raise NotImplementedError(filldedent('''
223
+ Unable to find range for the given domain.
224
+ '''))
225
+
226
+ return range_int
227
+
228
+
229
+ def not_empty_in(finset_intersection, *syms):
230
+ """
231
+ Finds the domain of the functions in ``finset_intersection`` in which the
232
+ ``finite_set`` is not-empty.
233
+
234
+ Parameters
235
+ ==========
236
+
237
+ finset_intersection : Intersection of FiniteSet
238
+ The unevaluated intersection of FiniteSet containing
239
+ real-valued functions with Union of Sets
240
+ syms : Tuple of symbols
241
+ Symbol for which domain is to be found
242
+
243
+ Raises
244
+ ======
245
+
246
+ NotImplementedError
247
+ The algorithms to find the non-emptiness of the given FiniteSet are
248
+ not yet implemented.
249
+ ValueError
250
+ The input is not valid.
251
+ RuntimeError
252
+ It is a bug, please report it to the github issue tracker
253
+ (https://github.com/sympy/sympy/issues).
254
+
255
+ Examples
256
+ ========
257
+
258
+ >>> from sympy import FiniteSet, Interval, not_empty_in, oo
259
+ >>> from sympy.abc import x
260
+ >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x)
261
+ Interval(0, 2)
262
+ >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x)
263
+ Union(Interval(1, 2), Interval(-sqrt(2), -1))
264
+ >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x)
265
+ Union(Interval.Lopen(-2, -1), Interval(2, oo))
266
+ """
267
+
268
+ # TODO: handle piecewise defined functions
269
+ # TODO: handle transcendental functions
270
+ # TODO: handle multivariate functions
271
+ if len(syms) == 0:
272
+ raise ValueError("One or more symbols must be given in syms.")
273
+
274
+ if finset_intersection is S.EmptySet:
275
+ return S.EmptySet
276
+
277
+ if isinstance(finset_intersection, Union):
278
+ elm_in_sets = finset_intersection.args[0]
279
+ return Union(not_empty_in(finset_intersection.args[1], *syms),
280
+ elm_in_sets)
281
+
282
+ if isinstance(finset_intersection, FiniteSet):
283
+ finite_set = finset_intersection
284
+ _sets = S.Reals
285
+ else:
286
+ finite_set = finset_intersection.args[1]
287
+ _sets = finset_intersection.args[0]
288
+
289
+ if not isinstance(finite_set, FiniteSet):
290
+ raise ValueError('A FiniteSet must be given, not %s: %s' %
291
+ (type(finite_set), finite_set))
292
+
293
+ if len(syms) == 1:
294
+ symb = syms[0]
295
+ else:
296
+ raise NotImplementedError('more than one variables %s not handled' %
297
+ (syms,))
298
+
299
+ def elm_domain(expr, intrvl):
300
+ """ Finds the domain of an expression in any given interval """
301
+ from sympy.solvers.solveset import solveset
302
+
303
+ _start = intrvl.start
304
+ _end = intrvl.end
305
+ _singularities = solveset(expr.as_numer_denom()[1], symb,
306
+ domain=S.Reals)
307
+
308
+ if intrvl.right_open:
309
+ if _end is S.Infinity:
310
+ _domain1 = S.Reals
311
+ else:
312
+ _domain1 = solveset(expr < _end, symb, domain=S.Reals)
313
+ else:
314
+ _domain1 = solveset(expr <= _end, symb, domain=S.Reals)
315
+
316
+ if intrvl.left_open:
317
+ if _start is S.NegativeInfinity:
318
+ _domain2 = S.Reals
319
+ else:
320
+ _domain2 = solveset(expr > _start, symb, domain=S.Reals)
321
+ else:
322
+ _domain2 = solveset(expr >= _start, symb, domain=S.Reals)
323
+
324
+ # domain in the interval
325
+ expr_with_sing = Intersection(_domain1, _domain2)
326
+ expr_domain = Complement(expr_with_sing, _singularities)
327
+ return expr_domain
328
+
329
+ if isinstance(_sets, Interval):
330
+ return Union(*[elm_domain(element, _sets) for element in finite_set])
331
+
332
+ if isinstance(_sets, Union):
333
+ _domain = S.EmptySet
334
+ for intrvl in _sets.args:
335
+ _domain_element = Union(*[elm_domain(element, intrvl)
336
+ for element in finite_set])
337
+ _domain = Union(_domain, _domain_element)
338
+ return _domain
339
+
340
+
341
+ def periodicity(f, symbol, check=False):
342
+ """
343
+ Tests the given function for periodicity in the given symbol.
344
+
345
+ Parameters
346
+ ==========
347
+
348
+ f : :py:class:`~.Expr`
349
+ The concerned function.
350
+ symbol : :py:class:`~.Symbol`
351
+ The variable for which the period is to be determined.
352
+ check : bool, optional
353
+ The flag to verify whether the value being returned is a period or not.
354
+
355
+ Returns
356
+ =======
357
+
358
+ period
359
+ The period of the function is returned.
360
+ ``None`` is returned when the function is aperiodic or has a complex period.
361
+ The value of $0$ is returned as the period of a constant function.
362
+
363
+ Raises
364
+ ======
365
+
366
+ NotImplementedError
367
+ The value of the period computed cannot be verified.
368
+
369
+
370
+ Notes
371
+ =====
372
+
373
+ Currently, we do not support functions with a complex period.
374
+ The period of functions having complex periodic values such
375
+ as ``exp``, ``sinh`` is evaluated to ``None``.
376
+
377
+ The value returned might not be the "fundamental" period of the given
378
+ function i.e. it may not be the smallest periodic value of the function.
379
+
380
+ The verification of the period through the ``check`` flag is not reliable
381
+ due to internal simplification of the given expression. Hence, it is set
382
+ to ``False`` by default.
383
+
384
+ Examples
385
+ ========
386
+ >>> from sympy import periodicity, Symbol, sin, cos, tan, exp
387
+ >>> x = Symbol('x')
388
+ >>> f = sin(x) + sin(2*x) + sin(3*x)
389
+ >>> periodicity(f, x)
390
+ 2*pi
391
+ >>> periodicity(sin(x)*cos(x), x)
392
+ pi
393
+ >>> periodicity(exp(tan(2*x) - 1), x)
394
+ pi/2
395
+ >>> periodicity(sin(4*x)**cos(2*x), x)
396
+ pi
397
+ >>> periodicity(exp(x), x)
398
+ """
399
+ if symbol.kind is not NumberKind:
400
+ raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind)
401
+ temp = Dummy('x', real=True)
402
+ f = f.subs(symbol, temp)
403
+ symbol = temp
404
+
405
+ def _check(orig_f, period):
406
+ '''Return the checked period or raise an error.'''
407
+ new_f = orig_f.subs(symbol, symbol + period)
408
+ if new_f.equals(orig_f):
409
+ return period
410
+ else:
411
+ raise NotImplementedError(filldedent('''
412
+ The period of the given function cannot be verified.
413
+ When `%s` was replaced with `%s + %s` in `%s`, the result
414
+ was `%s` which was not recognized as being the same as
415
+ the original function.
416
+ So either the period was wrong or the two forms were
417
+ not recognized as being equal.
418
+ Set check=False to obtain the value.''' %
419
+ (symbol, symbol, period, orig_f, new_f)))
420
+
421
+ orig_f = f
422
+ period = None
423
+
424
+ if isinstance(f, Relational):
425
+ f = f.lhs - f.rhs
426
+
427
+ f = f.simplify()
428
+
429
+ if symbol not in f.free_symbols:
430
+ return S.Zero
431
+
432
+ if isinstance(f, TrigonometricFunction):
433
+ try:
434
+ period = f.period(symbol)
435
+ except NotImplementedError:
436
+ pass
437
+
438
+ if isinstance(f, Abs):
439
+ arg = f.args[0]
440
+ if isinstance(arg, (sec, csc, cos)):
441
+ # all but tan and cot might have a
442
+ # a period that is half as large
443
+ # so recast as sin
444
+ arg = sin(arg.args[0])
445
+ period = periodicity(arg, symbol)
446
+ if period is not None and isinstance(arg, sin):
447
+ # the argument of Abs was a trigonometric other than
448
+ # cot or tan; test to see if the half-period
449
+ # is valid. Abs(arg) has behaviour equivalent to
450
+ # orig_f, so use that for test:
451
+ orig_f = Abs(arg)
452
+ try:
453
+ return _check(orig_f, period/2)
454
+ except NotImplementedError as err:
455
+ if check:
456
+ raise NotImplementedError(err)
457
+ # else let new orig_f and period be
458
+ # checked below
459
+
460
+ if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1):
461
+ f = Pow(S.Exp1, expand_mul(f.exp))
462
+ if im(f) != 0:
463
+ period_real = periodicity(re(f), symbol)
464
+ period_imag = periodicity(im(f), symbol)
465
+ if period_real is not None and period_imag is not None:
466
+ period = lcim([period_real, period_imag])
467
+
468
+ if f.is_Pow and f.base != S.Exp1:
469
+ base, expo = f.args
470
+ base_has_sym = base.has(symbol)
471
+ expo_has_sym = expo.has(symbol)
472
+
473
+ if base_has_sym and not expo_has_sym:
474
+ period = periodicity(base, symbol)
475
+
476
+ elif expo_has_sym and not base_has_sym:
477
+ period = periodicity(expo, symbol)
478
+
479
+ else:
480
+ period = _periodicity(f.args, symbol)
481
+
482
+ elif f.is_Mul:
483
+ coeff, g = f.as_independent(symbol, as_Add=False)
484
+ if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1):
485
+ period = periodicity(g, symbol)
486
+ else:
487
+ period = _periodicity(g.args, symbol)
488
+
489
+ elif f.is_Add:
490
+ k, g = f.as_independent(symbol)
491
+ if k is not S.Zero:
492
+ return periodicity(g, symbol)
493
+
494
+ period = _periodicity(g.args, symbol)
495
+
496
+ elif isinstance(f, Mod):
497
+ a, n = f.args
498
+
499
+ if a == symbol:
500
+ period = n
501
+ elif isinstance(a, TrigonometricFunction):
502
+ period = periodicity(a, symbol)
503
+ #check if 'f' is linear in 'symbol'
504
+ elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and
505
+ symbol not in n.free_symbols):
506
+ period = Abs(n / a.diff(symbol))
507
+
508
+ elif isinstance(f, Piecewise):
509
+ pass # not handling Piecewise yet as the return type is not favorable
510
+
511
+ elif period is None:
512
+ from sympy.solvers.decompogen import compogen, decompogen
513
+ g_s = decompogen(f, symbol)
514
+ num_of_gs = len(g_s)
515
+ if num_of_gs > 1:
516
+ for index, g in enumerate(reversed(g_s)):
517
+ start_index = num_of_gs - 1 - index
518
+ g = compogen(g_s[start_index:], symbol)
519
+ if g not in (orig_f, f): # Fix for issue 12620
520
+ period = periodicity(g, symbol)
521
+ if period is not None:
522
+ break
523
+
524
+ if period is not None:
525
+ if check:
526
+ return _check(orig_f, period)
527
+ return period
528
+
529
+ return None
530
+
531
+
532
+ def _periodicity(args, symbol):
533
+ """
534
+ Helper for `periodicity` to find the period of a list of simpler
535
+ functions.
536
+ It uses the `lcim` method to find the least common period of
537
+ all the functions.
538
+
539
+ Parameters
540
+ ==========
541
+
542
+ args : Tuple of :py:class:`~.Symbol`
543
+ All the symbols present in a function.
544
+
545
+ symbol : :py:class:`~.Symbol`
546
+ The symbol over which the function is to be evaluated.
547
+
548
+ Returns
549
+ =======
550
+
551
+ period
552
+ The least common period of the function for all the symbols
553
+ of the function.
554
+ ``None`` if for at least one of the symbols the function is aperiodic.
555
+
556
+ """
557
+ periods = []
558
+ for f in args:
559
+ period = periodicity(f, symbol)
560
+ if period is None:
561
+ return None
562
+
563
+ if period is not S.Zero:
564
+ periods.append(period)
565
+
566
+ if len(periods) > 1:
567
+ return lcim(periods)
568
+
569
+ if periods:
570
+ return periods[0]
571
+
572
+
573
+ def lcim(numbers):
574
+ """Returns the least common integral multiple of a list of numbers.
575
+
576
+ The numbers can be rational or irrational or a mixture of both.
577
+ `None` is returned for incommensurable numbers.
578
+
579
+ Parameters
580
+ ==========
581
+
582
+ numbers : list
583
+ Numbers (rational and/or irrational) for which lcim is to be found.
584
+
585
+ Returns
586
+ =======
587
+
588
+ number
589
+ lcim if it exists, otherwise ``None`` for incommensurable numbers.
590
+
591
+ Examples
592
+ ========
593
+
594
+ >>> from sympy.calculus.util import lcim
595
+ >>> from sympy import S, pi
596
+ >>> lcim([S(1)/2, S(3)/4, S(5)/6])
597
+ 15/2
598
+ >>> lcim([2*pi, 3*pi, pi, pi/2])
599
+ 6*pi
600
+ >>> lcim([S(1), 2*pi])
601
+ """
602
+ result = None
603
+ if all(num.is_irrational for num in numbers):
604
+ factorized_nums = [num.factor() for num in numbers]
605
+ factors_num = [num.as_coeff_Mul() for num in factorized_nums]
606
+ term = factors_num[0][1]
607
+ if all(factor == term for coeff, factor in factors_num):
608
+ common_term = term
609
+ coeffs = [coeff for coeff, factor in factors_num]
610
+ result = lcm_list(coeffs) * common_term
611
+
612
+ elif all(num.is_rational for num in numbers):
613
+ result = lcm_list(numbers)
614
+
615
+ else:
616
+ pass
617
+
618
+ return result
619
+
620
+ def is_convex(f, *syms, domain=S.Reals):
621
+ r"""Determines the convexity of the function passed in the argument.
622
+
623
+ Parameters
624
+ ==========
625
+
626
+ f : :py:class:`~.Expr`
627
+ The concerned function.
628
+ syms : Tuple of :py:class:`~.Symbol`
629
+ The variables with respect to which the convexity is to be determined.
630
+ domain : :py:class:`~.Interval`, optional
631
+ The domain over which the convexity of the function has to be checked.
632
+ If unspecified, S.Reals will be the default domain.
633
+
634
+ Returns
635
+ =======
636
+
637
+ bool
638
+ The method returns ``True`` if the function is convex otherwise it
639
+ returns ``False``.
640
+
641
+ Raises
642
+ ======
643
+
644
+ NotImplementedError
645
+ The check for the convexity of multivariate functions is not implemented yet.
646
+
647
+ Notes
648
+ =====
649
+
650
+ To determine concavity of a function pass `-f` as the concerned function.
651
+ To determine logarithmic convexity of a function pass `\log(f)` as
652
+ concerned function.
653
+ To determine logarithmic concavity of a function pass `-\log(f)` as
654
+ concerned function.
655
+
656
+ Currently, convexity check of multivariate functions is not handled.
657
+
658
+ Examples
659
+ ========
660
+
661
+ >>> from sympy import is_convex, symbols, exp, oo, Interval
662
+ >>> x = symbols('x')
663
+ >>> is_convex(exp(x), x)
664
+ True
665
+ >>> is_convex(x**3, x, domain = Interval(-1, oo))
666
+ False
667
+ >>> is_convex(1/x**2, x, domain=Interval.open(0, oo))
668
+ True
669
+
670
+ References
671
+ ==========
672
+
673
+ .. [1] https://en.wikipedia.org/wiki/Convex_function
674
+ .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf
675
+ .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function
676
+ .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function
677
+ .. [5] https://en.wikipedia.org/wiki/Concave_function
678
+
679
+ """
680
+
681
+ if len(syms) > 1:
682
+ raise NotImplementedError(
683
+ "The check for the convexity of multivariate functions is not implemented yet.")
684
+
685
+ from sympy.solvers.inequalities import solve_univariate_inequality
686
+
687
+ f = _sympify(f)
688
+ var = syms[0]
689
+ if any(s in domain for s in singularities(f, var)):
690
+ return False
691
+
692
+ condition = f.diff(var, 2) < 0
693
+ if solve_univariate_inequality(condition, var, False, domain):
694
+ return False
695
+ return True
696
+
697
+
698
+ def stationary_points(f, symbol, domain=S.Reals):
699
+ """
700
+ Returns the stationary points of a function (where derivative of the
701
+ function is 0) in the given domain.
702
+
703
+ Parameters
704
+ ==========
705
+
706
+ f : :py:class:`~.Expr`
707
+ The concerned function.
708
+ symbol : :py:class:`~.Symbol`
709
+ The variable for which the stationary points are to be determined.
710
+ domain : :py:class:`~.Interval`
711
+ The domain over which the stationary points have to be checked.
712
+ If unspecified, ``S.Reals`` will be the default domain.
713
+
714
+ Returns
715
+ =======
716
+
717
+ Set
718
+ A set of stationary points for the function. If there are no
719
+ stationary point, an :py:class:`~.EmptySet` is returned.
720
+
721
+ Examples
722
+ ========
723
+
724
+ >>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points
725
+ >>> x = Symbol('x')
726
+
727
+ >>> stationary_points(1/x, x, S.Reals)
728
+ EmptySet
729
+
730
+ >>> pprint(stationary_points(sin(x), x), use_unicode=False)
731
+ pi 3*pi
732
+ {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers}
733
+ 2 2
734
+
735
+ >>> stationary_points(sin(x),x, Interval(0, 4*pi))
736
+ {pi/2, 3*pi/2, 5*pi/2, 7*pi/2}
737
+
738
+ """
739
+ from sympy.solvers.solveset import solveset
740
+
741
+ if domain is S.EmptySet:
742
+ return S.EmptySet
743
+
744
+ domain = continuous_domain(f, symbol, domain)
745
+ set = solveset(diff(f, symbol), symbol, domain)
746
+
747
+ return set
748
+
749
+
750
+ def maximum(f, symbol, domain=S.Reals):
751
+ """
752
+ Returns the maximum value of a function in the given domain.
753
+
754
+ Parameters
755
+ ==========
756
+
757
+ f : :py:class:`~.Expr`
758
+ The concerned function.
759
+ symbol : :py:class:`~.Symbol`
760
+ The variable for maximum value needs to be determined.
761
+ domain : :py:class:`~.Interval`
762
+ The domain over which the maximum have to be checked.
763
+ If unspecified, then the global maximum is returned.
764
+
765
+ Returns
766
+ =======
767
+
768
+ number
769
+ Maximum value of the function in given domain.
770
+
771
+ Examples
772
+ ========
773
+
774
+ >>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum
775
+ >>> x = Symbol('x')
776
+
777
+ >>> f = -x**2 + 2*x + 5
778
+ >>> maximum(f, x, S.Reals)
779
+ 6
780
+
781
+ >>> maximum(sin(x), x, Interval(-pi, pi/4))
782
+ sqrt(2)/2
783
+
784
+ >>> maximum(sin(x)*cos(x), x)
785
+ 1/2
786
+
787
+ """
788
+ if isinstance(symbol, Symbol):
789
+ if domain is S.EmptySet:
790
+ raise ValueError("Maximum value not defined for empty domain.")
791
+
792
+ return function_range(f, symbol, domain).sup
793
+ else:
794
+ raise ValueError("%s is not a valid symbol." % symbol)
795
+
796
+
797
+ def minimum(f, symbol, domain=S.Reals):
798
+ """
799
+ Returns the minimum value of a function in the given domain.
800
+
801
+ Parameters
802
+ ==========
803
+
804
+ f : :py:class:`~.Expr`
805
+ The concerned function.
806
+ symbol : :py:class:`~.Symbol`
807
+ The variable for minimum value needs to be determined.
808
+ domain : :py:class:`~.Interval`
809
+ The domain over which the minimum have to be checked.
810
+ If unspecified, then the global minimum is returned.
811
+
812
+ Returns
813
+ =======
814
+
815
+ number
816
+ Minimum value of the function in the given domain.
817
+
818
+ Examples
819
+ ========
820
+
821
+ >>> from sympy import Interval, Symbol, S, sin, cos, minimum
822
+ >>> x = Symbol('x')
823
+
824
+ >>> f = x**2 + 2*x + 5
825
+ >>> minimum(f, x, S.Reals)
826
+ 4
827
+
828
+ >>> minimum(sin(x), x, Interval(2, 3))
829
+ sin(3)
830
+
831
+ >>> minimum(sin(x)*cos(x), x)
832
+ -1/2
833
+
834
+ """
835
+ if isinstance(symbol, Symbol):
836
+ if domain is S.EmptySet:
837
+ raise ValueError("Minimum value not defined for empty domain.")
838
+
839
+ return function_range(f, symbol, domain).inf
840
+ else:
841
+ raise ValueError("%s is not a valid symbol." % symbol)
shared/package-files/56/5625dde86e5d3428f96dd588a61155f28936505d3c537a4a448d967e716af150/blob ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/impl/DeviceGuardImplInterface.h>
4
+ #include <c10/core/impl/GPUTrace.h>
5
+ #include <c10/macros/Macros.h>
6
+ #include <c10/util/Exception.h>
7
+
8
+ #include <c10/cuda/CUDACachingAllocator.h>
9
+ #include <c10/cuda/CUDAException.h>
10
+ #include <c10/cuda/CUDAFunctions.h>
11
+ #include <c10/cuda/CUDAStream.h>
12
+
13
+ #include <c10/core/Device.h>
14
+ #include <c10/core/DeviceType.h>
15
+ #include <c10/core/Stream.h>
16
+ #include <c10/core/impl/PyInterpreter.h>
17
+ #include <c10/util/Optional.h>
18
+ #include <cuda_runtime_api.h>
19
+ #include <cstdint>
20
+
21
+ namespace c10::cuda::impl {
22
+
23
+ struct CUDAGuardImpl final : public c10::impl::DeviceGuardImplInterface {
24
+ static constexpr DeviceType static_type = DeviceType::CUDA;
25
+
26
+ CUDAGuardImpl() = default;
27
+ explicit CUDAGuardImpl(DeviceType t) {
28
+ TORCH_INTERNAL_ASSERT(t == DeviceType::CUDA);
29
+ }
30
+ DeviceType type() const override {
31
+ return DeviceType::CUDA;
32
+ }
33
+ Device exchangeDevice(Device d) const override {
34
+ TORCH_INTERNAL_ASSERT(d.is_cuda());
35
+ auto old_device_index = c10::cuda::ExchangeDevice(d.index());
36
+ return Device(DeviceType::CUDA, old_device_index);
37
+ }
38
+ Device getDevice() const override {
39
+ DeviceIndex device = 0;
40
+ C10_CUDA_CHECK(c10::cuda::GetDevice(&device));
41
+ return Device(DeviceType::CUDA, device);
42
+ }
43
+ c10::optional<Device> uncheckedGetDevice() const noexcept {
44
+ DeviceIndex device{-1};
45
+ const auto err = C10_CUDA_ERROR_HANDLED(c10::cuda::GetDevice(&device));
46
+ C10_CUDA_CHECK_WARN(err);
47
+ if (err != cudaSuccess) {
48
+ return c10::nullopt;
49
+ }
50
+ return Device(DeviceType::CUDA, device);
51
+ }
52
+ void setDevice(Device d) const override {
53
+ TORCH_INTERNAL_ASSERT(d.is_cuda());
54
+ C10_CUDA_CHECK(c10::cuda::SetDevice(d.index()));
55
+ }
56
+ void uncheckedSetDevice(Device d) const noexcept override {
57
+ C10_CUDA_CHECK_WARN(c10::cuda::MaybeSetDevice(d.index()));
58
+ }
59
+ Stream getStream(Device d) const noexcept override {
60
+ return getCurrentCUDAStream(d.index()).unwrap();
61
+ }
62
+ Stream getDefaultStream(Device d) const override {
63
+ return getDefaultCUDAStream(d.index());
64
+ }
65
+ Stream getStreamFromGlobalPool(Device d, bool isHighPriority = false)
66
+ const override {
67
+ return getStreamFromPool(isHighPriority, d.index());
68
+ }
69
+ // NB: These do NOT set the current device
70
+ Stream exchangeStream(Stream s) const noexcept override {
71
+ CUDAStream cs(s);
72
+ auto old_stream = getCurrentCUDAStream(s.device().index());
73
+ setCurrentCUDAStream(cs);
74
+ return old_stream.unwrap();
75
+ }
76
+ DeviceIndex deviceCount() const noexcept override {
77
+ return device_count();
78
+ }
79
+
80
+ // Event-related functions
81
+ void createEvent(cudaEvent_t* cuda_event, const EventFlag flag) const {
82
+ // Maps PyTorch's Event::Flag to CUDA flag
83
+ auto cuda_flag = cudaEventDefault;
84
+ switch (flag) {
85
+ case EventFlag::PYTORCH_DEFAULT:
86
+ case EventFlag::CUDA_EVENT_DISABLE_TIMING:
87
+ cuda_flag = cudaEventDisableTiming;
88
+ break;
89
+ case EventFlag::BACKEND_DEFAULT:
90
+ case EventFlag::CUDA_EVENT_DEFAULT:
91
+ cuda_flag = cudaEventDefault;
92
+ break;
93
+ default:
94
+ TORCH_CHECK(false, "CUDA event received unknown flag");
95
+ }
96
+
97
+ C10_CUDA_CHECK(cudaEventCreateWithFlags(cuda_event, cuda_flag));
98
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
99
+ if (C10_UNLIKELY(interp)) {
100
+ (*interp)->trace_gpu_event_creation(
101
+ reinterpret_cast<uintptr_t>(cuda_event));
102
+ }
103
+ }
104
+
105
+ void destroyEvent(void* event, const DeviceIndex device_index)
106
+ const noexcept override {
107
+ if (!event)
108
+ return;
109
+ auto cuda_event = static_cast<cudaEvent_t>(event);
110
+ DeviceIndex orig_device{-1};
111
+ C10_CUDA_CHECK_WARN(c10::cuda::GetDevice(&orig_device));
112
+ C10_CUDA_CHECK_WARN(c10::cuda::SetDevice(device_index));
113
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
114
+ if (C10_UNLIKELY(interp)) {
115
+ (*interp)->trace_gpu_event_deletion(
116
+ reinterpret_cast<uintptr_t>(cuda_event));
117
+ }
118
+ C10_CUDA_CHECK_WARN(cudaEventDestroy(cuda_event));
119
+ C10_CUDA_CHECK_WARN(c10::cuda::SetDevice(orig_device));
120
+ }
121
+
122
+ void record(
123
+ void** event,
124
+ const Stream& stream,
125
+ const DeviceIndex device_index,
126
+ const EventFlag flag) const override {
127
+ TORCH_CHECK(
128
+ device_index == -1 || device_index == stream.device_index(),
129
+ "Event device index ",
130
+ device_index,
131
+ " does not match recording stream's device index ",
132
+ stream.device_index(),
133
+ ".");
134
+
135
+ cudaEvent_t cuda_event = static_cast<cudaEvent_t>(*event);
136
+ CUDAStream cuda_stream{stream};
137
+
138
+ // Moves to stream's device to record
139
+ const auto orig_device = getDevice();
140
+ setDevice(stream.device());
141
+
142
+ // Creates the event (lazily)
143
+ if (!cuda_event)
144
+ createEvent(&cuda_event, flag);
145
+ C10_CUDA_CHECK(cudaEventRecord(cuda_event, cuda_stream));
146
+ // Makes the void* point to the (possibly just allocated) CUDA event
147
+ *event = cuda_event;
148
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
149
+ if (C10_UNLIKELY(interp)) {
150
+ (*interp)->trace_gpu_event_record(
151
+ reinterpret_cast<uintptr_t>(cuda_event),
152
+ reinterpret_cast<uintptr_t>(cuda_stream.stream()));
153
+ }
154
+
155
+ // Resets device
156
+ setDevice(orig_device);
157
+ }
158
+
159
+ void block(void* event, const Stream& stream) const override {
160
+ if (!event)
161
+ return;
162
+ cudaEvent_t cuda_event = static_cast<cudaEvent_t>(event);
163
+ CUDAStream cuda_stream{stream};
164
+ const auto orig_device = getDevice();
165
+ setDevice(stream.device());
166
+ C10_CUDA_CHECK(cudaStreamWaitEvent(
167
+ cuda_stream,
168
+ cuda_event,
169
+ /*flags (must be zero)=*/0));
170
+ const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
171
+ if (C10_UNLIKELY(interp)) {
172
+ (*interp)->trace_gpu_event_wait(
173
+ reinterpret_cast<uintptr_t>(cuda_event),
174
+ reinterpret_cast<uintptr_t>(cuda_stream.stream()));
175
+ }
176
+ setDevice(orig_device);
177
+ }
178
+
179
+ // May be called from any device
180
+ bool queryEvent(void* event) const override {
181
+ if (!event)
182
+ return true;
183
+ cudaEvent_t cuda_event = static_cast<cudaEvent_t>(event);
184
+ const cudaError_t err = C10_CUDA_ERROR_HANDLED(cudaEventQuery(cuda_event));
185
+ if (err != cudaErrorNotReady) {
186
+ C10_CUDA_CHECK(err);
187
+ } else {
188
+ // ignore and clear the error if not ready
189
+ (void)cudaGetLastError();
190
+ }
191
+ return (err == cudaSuccess);
192
+ }
193
+
194
+ // Stream-related functions
195
+ bool queryStream(const Stream& stream) const override {
196
+ CUDAStream cuda_stream{stream};
197
+ return cuda_stream.query();
198
+ }
199
+
200
+ void synchronizeStream(const Stream& stream) const override {
201
+ CUDAStream cuda_stream{stream};
202
+ cuda_stream.synchronize();
203
+ }
204
+
205
+ void recordDataPtrOnStream(const c10::DataPtr& data_ptr, const Stream& stream)
206
+ const override {
207
+ CUDAStream cuda_stream{stream};
208
+ CUDACachingAllocator::recordStream(data_ptr, cuda_stream);
209
+ }
210
+ };
211
+
212
+ } // namespace c10::cuda::impl
shared/package-files/56/5627831bc850c2f3bb9ecaafe77e4a9afaa5c219ac19f0acdebde802a9078900/blob ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API special_modified_bessel_k0 {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_modified_bessel_k0")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_modified_bessel_k0(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ struct TORCH_API special_modified_bessel_k0_out {
29
+ using schema = at::Tensor & (const at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_modified_bessel_k0")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_modified_bessel_k0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/56/562825f936033f38d1b61561663a9b6f3352aeed36351d6259f65f9a1ed621f2/blob ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/softplus_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!)
26
+ inline at::Tensor & softplus_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold) {
27
+ return at::_ops::softplus_backward_grad_input::call(grad_output, self, beta, threshold, grad_input);
28
+ }
29
+ // aten::softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!)
30
+ inline at::Tensor & softplus_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold, at::Tensor & grad_input) {
31
+ return at::_ops::softplus_backward_grad_input::call(grad_output, self, beta, threshold, grad_input);
32
+ }
33
+
34
+ // aten::softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor
35
+ inline at::Tensor softplus_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & beta, const at::Scalar & threshold) {
36
+ return at::_ops::softplus_backward::call(grad_output, self, beta, threshold);
37
+ }
38
+
39
+ }
shared/package-files/56/562d4b893ac95f9058d000cbc68264c02ec7dbb1f7d2d4cf33cf71674e00e465/blob ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #include <c10/util/Backtrace.h>
2
+ #include <c10/util/Type.h>
shared/package-files/56/562d4d8bd25e6725fb9145fb60482f6a3d52ea4cba472532f2a2ff08e375520c/blob ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+ from __future__ import absolute_import
3
+ from six.moves import cStringIO
4
+ from .unparser import Unparser
5
+ from .printer import Printer
6
+
7
+
8
+ __version__ = '1.6.3'
9
+
10
+
11
+ def unparse(tree):
12
+ v = cStringIO()
13
+ Unparser(tree, file=v)
14
+ return v.getvalue()
15
+
16
+
17
+ def dump(tree):
18
+ v = cStringIO()
19
+ Printer(file=v).visit(tree)
20
+ return v.getvalue()
shared/package-files/56/562d986ed52133d57160f6373c1bf17eed31658afa7c1cac9798103c9128f3c9/blob ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ import numpy as np
6
+
7
+ from contourpy._contourpy import (
8
+ ContourGenerator,
9
+ FillType,
10
+ LineType,
11
+ Mpl2005ContourGenerator,
12
+ Mpl2014ContourGenerator,
13
+ SerialContourGenerator,
14
+ ThreadedContourGenerator,
15
+ ZInterp,
16
+ max_threads,
17
+ )
18
+ from contourpy._version import __version__
19
+ from contourpy.chunk import calc_chunk_sizes
20
+ from contourpy.convert import (
21
+ convert_filled,
22
+ convert_lines,
23
+ convert_multi_filled,
24
+ convert_multi_lines,
25
+ )
26
+ from contourpy.dechunk import (
27
+ dechunk_filled,
28
+ dechunk_lines,
29
+ dechunk_multi_filled,
30
+ dechunk_multi_lines,
31
+ )
32
+ from contourpy.enum_util import as_fill_type, as_line_type, as_z_interp
33
+
34
+ if TYPE_CHECKING:
35
+ from typing import Any
36
+
37
+ from numpy.typing import ArrayLike
38
+
39
+ from ._contourpy import CoordinateArray, MaskArray
40
+
41
+ __all__ = [
42
+ "__version__",
43
+ "contour_generator",
44
+ "convert_filled",
45
+ "convert_lines",
46
+ "convert_multi_filled",
47
+ "convert_multi_lines",
48
+ "dechunk_filled",
49
+ "dechunk_lines",
50
+ "dechunk_multi_filled",
51
+ "dechunk_multi_lines",
52
+ "max_threads",
53
+ "FillType",
54
+ "LineType",
55
+ "ContourGenerator",
56
+ "Mpl2005ContourGenerator",
57
+ "Mpl2014ContourGenerator",
58
+ "SerialContourGenerator",
59
+ "ThreadedContourGenerator",
60
+ "ZInterp",
61
+ ]
62
+
63
+
64
+ # Simple mapping of algorithm name to class name.
65
+ _class_lookup: dict[str, type[ContourGenerator]] = {
66
+ "mpl2005": Mpl2005ContourGenerator,
67
+ "mpl2014": Mpl2014ContourGenerator,
68
+ "serial": SerialContourGenerator,
69
+ "threaded": ThreadedContourGenerator,
70
+ }
71
+
72
+
73
+ def _remove_z_mask(
74
+ z: ArrayLike | np.ma.MaskedArray[Any, Any] | None,
75
+ ) -> tuple[CoordinateArray, MaskArray | None]:
76
+ # Preserve mask if present.
77
+ z_array = np.ma.asarray(z, dtype=np.float64) # type: ignore[no-untyped-call]
78
+ z_masked = np.ma.masked_invalid(z_array, copy=False) # type: ignore[no-untyped-call]
79
+
80
+ if np.ma.is_masked(z_masked): # type: ignore[no-untyped-call]
81
+ mask = np.ma.getmask(z_masked) # type: ignore[no-untyped-call]
82
+ else:
83
+ mask = None
84
+
85
+ return np.ma.getdata(z_masked), mask # type: ignore[no-untyped-call]
86
+
87
+
88
+ def contour_generator(
89
+ x: ArrayLike | None = None,
90
+ y: ArrayLike | None = None,
91
+ z: ArrayLike | np.ma.MaskedArray[Any, Any] | None = None,
92
+ *,
93
+ name: str = "serial",
94
+ corner_mask: bool | None = None,
95
+ line_type: LineType | str | None = None,
96
+ fill_type: FillType | str | None = None,
97
+ chunk_size: int | tuple[int, int] | None = None,
98
+ chunk_count: int | tuple[int, int] | None = None,
99
+ total_chunk_count: int | None = None,
100
+ quad_as_tri: bool = False,
101
+ z_interp: ZInterp | str | None = ZInterp.Linear,
102
+ thread_count: int = 0,
103
+ ) -> ContourGenerator:
104
+ """Create and return a :class:`~.ContourGenerator` object.
105
+
106
+ The class and properties of the returned :class:`~.ContourGenerator` are determined by the
107
+ function arguments, with sensible defaults.
108
+
109
+ Args:
110
+ x (array-like of shape (ny, nx) or (nx,), optional): The x-coordinates of the ``z`` values.
111
+ May be 2D with the same shape as ``z.shape``, or 1D with length ``nx = z.shape[1]``.
112
+ If not specified are assumed to be ``np.arange(nx)``. Must be ordered monotonically.
113
+ y (array-like of shape (ny, nx) or (ny,), optional): The y-coordinates of the ``z`` values.
114
+ May be 2D with the same shape as ``z.shape``, or 1D with length ``ny = z.shape[0]``.
115
+ If not specified are assumed to be ``np.arange(ny)``. Must be ordered monotonically.
116
+ z (array-like of shape (ny, nx), may be a masked array): The 2D gridded values to calculate
117
+ the contours of. May be a masked array, and any invalid values (``np.inf`` or
118
+ ``np.nan``) will also be masked out.
119
+ name (str): Algorithm name, one of ``"serial"``, ``"threaded"``, ``"mpl2005"`` or
120
+ ``"mpl2014"``, default ``"serial"``.
121
+ corner_mask (bool, optional): Enable/disable corner masking, which only has an effect if
122
+ ``z`` is a masked array. If ``False``, any quad touching a masked point is masked out.
123
+ If ``True``, only the triangular corners of quads nearest these points are always masked
124
+ out, other triangular corners comprising three unmasked points are contoured as usual.
125
+ If not specified, uses the default provided by the algorithm ``name``.
126
+ line_type (LineType or str, optional): The format of contour line data returned from calls
127
+ to :meth:`~.ContourGenerator.lines`, specified either as a :class:`~.LineType` or its
128
+ string equivalent such as ``"SeparateCode"``.
129
+ If not specified, uses the default provided by the algorithm ``name``.
130
+ The relationship between the :class:`~.LineType` enum and the data format returned from
131
+ :meth:`~.ContourGenerator.lines` is explained at :ref:`line_type`.
132
+ fill_type (FillType or str, optional): The format of filled contour data returned from calls
133
+ to :meth:`~.ContourGenerator.filled`, specified either as a :class:`~.FillType` or its
134
+ string equivalent such as ``"OuterOffset"``.
135
+ If not specified, uses the default provided by the algorithm ``name``.
136
+ The relationship between the :class:`~.FillType` enum and the data format returned from
137
+ :meth:`~.ContourGenerator.filled` is explained at :ref:`fill_type`.
138
+ chunk_size (int or tuple(int, int), optional): Chunk size in (y, x) directions, or the same
139
+ size in both directions if only one value is specified.
140
+ chunk_count (int or tuple(int, int), optional): Chunk count in (y, x) directions, or the
141
+ same count in both directions if only one value is specified.
142
+ total_chunk_count (int, optional): Total number of chunks.
143
+ quad_as_tri (bool): Enable/disable treating quads as 4 triangles, default ``False``.
144
+ If ``False``, a contour line within a quad is a straight line between points on two of
145
+ its edges. If ``True``, each full quad is divided into 4 triangles using a virtual point
146
+ at the centre (mean x, y of the corner points) and a contour line is piecewise linear
147
+ within those triangles. Corner-masked triangles are not affected by this setting, only
148
+ full unmasked quads.
149
+ z_interp (ZInterp or str, optional): How to interpolate ``z`` values when determining where
150
+ contour lines intersect the edges of quads and the ``z`` values of the central points of
151
+ quads, specified either as a :class:`~contourpy.ZInterp` or its string equivalent such
152
+ as ``"Log"``. Default is ``ZInterp.Linear``.
153
+ thread_count (int): Number of threads to use for contour calculation, default 0. Threads can
154
+ only be used with an algorithm ``name`` that supports threads (currently only
155
+ ``name="threaded"``) and there must be at least the same number of chunks as threads.
156
+ If ``thread_count=0`` and ``name="threaded"`` then it uses the maximum number of threads
157
+ as determined by the C++11 call ``std::thread::hardware_concurrency()``. If ``name`` is
158
+ something other than ``"threaded"`` then the ``thread_count`` will be set to ``1``.
159
+
160
+ Return:
161
+ :class:`~.ContourGenerator`.
162
+
163
+ Note:
164
+ A maximum of one of ``chunk_size``, ``chunk_count`` and ``total_chunk_count`` may be
165
+ specified.
166
+
167
+ Warning:
168
+ The ``name="mpl2005"`` algorithm does not implement chunking for contour lines.
169
+ """
170
+ x = np.asarray(x, dtype=np.float64)
171
+ y = np.asarray(y, dtype=np.float64)
172
+ z, mask = _remove_z_mask(z)
173
+
174
+ # Check arguments: z.
175
+ if z.ndim != 2:
176
+ raise TypeError(f"Input z must be 2D, not {z.ndim}D")
177
+
178
+ if z.shape[0] < 2 or z.shape[1] < 2:
179
+ raise TypeError(f"Input z must be at least a (2, 2) shaped array, but has shape {z.shape}")
180
+
181
+ ny, nx = z.shape
182
+
183
+ # Check arguments: x and y.
184
+ if x.ndim != y.ndim:
185
+ raise TypeError(f"Number of dimensions of x ({x.ndim}) and y ({y.ndim}) do not match")
186
+
187
+ if x.ndim == 0:
188
+ x = np.arange(nx, dtype=np.float64)
189
+ y = np.arange(ny, dtype=np.float64)
190
+ x, y = np.meshgrid(x, y)
191
+ elif x.ndim == 1:
192
+ if len(x) != nx:
193
+ raise TypeError(f"Length of x ({len(x)}) must match number of columns in z ({nx})")
194
+ if len(y) != ny:
195
+ raise TypeError(f"Length of y ({len(y)}) must match number of rows in z ({ny})")
196
+ x, y = np.meshgrid(x, y)
197
+ elif x.ndim == 2:
198
+ if x.shape != z.shape:
199
+ raise TypeError(f"Shapes of x {x.shape} and z {z.shape} do not match")
200
+ if y.shape != z.shape:
201
+ raise TypeError(f"Shapes of y {y.shape} and z {z.shape} do not match")
202
+ else:
203
+ raise TypeError(f"Inputs x and y must be None, 1D or 2D, not {x.ndim}D")
204
+
205
+ # Check mask shape just in case.
206
+ if mask is not None and mask.shape != z.shape:
207
+ raise ValueError("If mask is set it must be a 2D array with the same shape as z")
208
+
209
+ # Check arguments: name.
210
+ if name not in _class_lookup:
211
+ raise ValueError(f"Unrecognised contour generator name: {name}")
212
+
213
+ # Check arguments: chunk_size, chunk_count and total_chunk_count.
214
+ y_chunk_size, x_chunk_size = calc_chunk_sizes(
215
+ chunk_size, chunk_count, total_chunk_count, ny, nx)
216
+
217
+ cls = _class_lookup[name]
218
+
219
+ # Check arguments: corner_mask.
220
+ if corner_mask is None:
221
+ # Set it to default, which is True if the algorithm supports it.
222
+ corner_mask = cls.supports_corner_mask()
223
+ elif corner_mask and not cls.supports_corner_mask():
224
+ raise ValueError(f"{name} contour generator does not support corner_mask=True")
225
+
226
+ # Check arguments: line_type.
227
+ if line_type is None:
228
+ line_type = cls.default_line_type
229
+ else:
230
+ line_type = as_line_type(line_type)
231
+
232
+ if not cls.supports_line_type(line_type):
233
+ raise ValueError(f"{name} contour generator does not support line_type {line_type}")
234
+
235
+ # Check arguments: fill_type.
236
+ if fill_type is None:
237
+ fill_type = cls.default_fill_type
238
+ else:
239
+ fill_type = as_fill_type(fill_type)
240
+
241
+ if not cls.supports_fill_type(fill_type):
242
+ raise ValueError(f"{name} contour generator does not support fill_type {fill_type}")
243
+
244
+ # Check arguments: quad_as_tri.
245
+ if quad_as_tri and not cls.supports_quad_as_tri():
246
+ raise ValueError(f"{name} contour generator does not support quad_as_tri=True")
247
+
248
+ # Check arguments: z_interp.
249
+ if z_interp is None:
250
+ z_interp = ZInterp.Linear
251
+ else:
252
+ z_interp = as_z_interp(z_interp)
253
+
254
+ if z_interp != ZInterp.Linear and not cls.supports_z_interp():
255
+ raise ValueError(f"{name} contour generator does not support z_interp {z_interp}")
256
+
257
+ # Check arguments: thread_count.
258
+ if thread_count not in (0, 1) and not cls.supports_threads():
259
+ raise ValueError(f"{name} contour generator does not support thread_count {thread_count}")
260
+
261
+ # Prepare args and kwargs for contour generator constructor.
262
+ args = [x, y, z, mask]
263
+ kwargs: dict[str, int | bool | LineType | FillType | ZInterp] = {
264
+ "x_chunk_size": x_chunk_size,
265
+ "y_chunk_size": y_chunk_size,
266
+ }
267
+
268
+ if name not in ("mpl2005", "mpl2014"):
269
+ kwargs["line_type"] = line_type
270
+ kwargs["fill_type"] = fill_type
271
+
272
+ if cls.supports_corner_mask():
273
+ kwargs["corner_mask"] = corner_mask
274
+
275
+ if cls.supports_quad_as_tri():
276
+ kwargs["quad_as_tri"] = quad_as_tri
277
+
278
+ if cls.supports_z_interp():
279
+ kwargs["z_interp"] = z_interp
280
+
281
+ if cls.supports_threads():
282
+ kwargs["thread_count"] = thread_count
283
+
284
+ # Create contour generator.
285
+ return cls(*args, **kwargs)
shared/package-files/56/56325687bbec94c348a1074f14d525019234131b8b155e8476bcb061a223a905/blob ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pygments.lexers.dotnet
3
+ ~~~~~~~~~~~~~~~~~~~~~~
4
+
5
+ Lexers for .net languages.
6
+
7
+ :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
8
+ :license: BSD, see LICENSE for details.
9
+ """
10
+ import re
11
+
12
+ from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, include, \
13
+ using, this, default, words
14
+ from pygments.token import Punctuation, Text, Comment, Operator, Keyword, \
15
+ Name, String, Number, Literal, Other, Whitespace
16
+ from pygments.util import get_choice_opt
17
+ from pygments import unistring as uni
18
+
19
+ from pygments.lexers.html import XmlLexer
20
+
21
+ __all__ = ['CSharpLexer', 'NemerleLexer', 'BooLexer', 'VbNetLexer',
22
+ 'CSharpAspxLexer', 'VbNetAspxLexer', 'FSharpLexer', 'XppLexer']
23
+
24
+
25
+ class CSharpLexer(RegexLexer):
26
+ """
27
+ For C# source code.
28
+
29
+ Additional options accepted:
30
+
31
+ `unicodelevel`
32
+ Determines which Unicode characters this lexer allows for identifiers.
33
+ The possible values are:
34
+
35
+ * ``none`` -- only the ASCII letters and numbers are allowed. This
36
+ is the fastest selection.
37
+ * ``basic`` -- all Unicode characters from the specification except
38
+ category ``Lo`` are allowed.
39
+ * ``full`` -- all Unicode characters as specified in the C# specs
40
+ are allowed. Note that this means a considerable slowdown since the
41
+ ``Lo`` category has more than 40,000 characters in it!
42
+
43
+ The default value is ``basic``.
44
+
45
+ .. versionadded:: 0.8
46
+ """
47
+
48
+ name = 'C#'
49
+ url = 'https://docs.microsoft.com/en-us/dotnet/csharp/'
50
+ aliases = ['csharp', 'c#', 'cs']
51
+ filenames = ['*.cs']
52
+ mimetypes = ['text/x-csharp'] # inferred
53
+
54
+ flags = re.MULTILINE | re.DOTALL
55
+
56
+ # for the range of allowed unicode characters in identifiers, see
57
+ # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
58
+
59
+ levels = {
60
+ 'none': r'@?[_a-zA-Z]\w*',
61
+ 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' +
62
+ '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc',
63
+ 'Cf', 'Mn', 'Mc') + ']*'),
64
+ 'full': ('@?(?:_|[^' +
65
+ uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' +
66
+ '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl',
67
+ 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'),
68
+ }
69
+
70
+ tokens = {}
71
+ token_variants = True
72
+
73
+ for levelname, cs_ident in levels.items():
74
+ tokens[levelname] = {
75
+ 'root': [
76
+ # method names
77
+ (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type
78
+ r'(' + cs_ident + ')' # method name
79
+ r'(\s*)(\()', # signature start
80
+ bygroups(Whitespace, using(this), Name.Function, Whitespace,
81
+ Punctuation)),
82
+ (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)),
83
+ (r'[^\S\n]+', Whitespace),
84
+ (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation
85
+ (r'//.*?\n', Comment.Single),
86
+ (r'/[*].*?[*]/', Comment.Multiline),
87
+ (r'\n', Whitespace),
88
+ (words((
89
+ '>>>=', '>>=', '<<=', '<=', '>=', '+=', '-=', '*=', '/=',
90
+ '%=', '&=', '|=', '^=', '??=', '=>', '??', '?.', '!=', '==',
91
+ '&&', '||', '>>>', '>>', '<<', '++', '--', '+', '-', '*',
92
+ '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=',
93
+ )), Operator),
94
+ (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator),
95
+ (r'[()\[\];:,.]', Punctuation),
96
+ (r'[{}]', Punctuation),
97
+ (r'@"(""|[^"])*"', String),
98
+ (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String),
99
+ (r"'\\.'|'[^\\]'", String.Char),
100
+ (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?"
101
+ r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number),
102
+ (r'(#)([ \t]*)(if|endif|else|elif|define|undef|'
103
+ r'line|error|warning|region|endregion|pragma)\b(.*?)(\n)',
104
+ bygroups(Comment.Preproc, Whitespace, Comment.Preproc,
105
+ Comment.Preproc, Whitespace)),
106
+ (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace,
107
+ Keyword)),
108
+ (r'(abstract|as|async|await|base|break|by|case|catch|'
109
+ r'checked|const|continue|default|delegate|'
110
+ r'do|else|enum|event|explicit|extern|false|finally|'
111
+ r'fixed|for|foreach|goto|if|implicit|in|interface|'
112
+ r'internal|is|let|lock|new|null|on|operator|'
113
+ r'out|override|params|private|protected|public|readonly|'
114
+ r'ref|return|sealed|sizeof|stackalloc|static|'
115
+ r'switch|this|throw|true|try|typeof|'
116
+ r'unchecked|unsafe|virtual|void|while|'
117
+ r'get|set|new|partial|yield|add|remove|value|alias|ascending|'
118
+ r'descending|from|group|into|orderby|select|thenby|where|'
119
+ r'join|equals)\b', Keyword),
120
+ (r'(global)(::)', bygroups(Keyword, Punctuation)),
121
+ (r'(bool|byte|char|decimal|double|dynamic|float|int|long|object|'
122
+ r'sbyte|short|string|uint|ulong|ushort|var)\b\??', Keyword.Type),
123
+ (r'(class|struct)(\s+)', bygroups(Keyword, Whitespace), 'class'),
124
+ (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace), 'namespace'),
125
+ (cs_ident, Name),
126
+ ],
127
+ 'class': [
128
+ (cs_ident, Name.Class, '#pop'),
129
+ default('#pop'),
130
+ ],
131
+ 'namespace': [
132
+ (r'(?=\()', Text, '#pop'), # using (resource)
133
+ ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop'),
134
+ ]
135
+ }
136
+
137
+ def __init__(self, **options):
138
+ level = get_choice_opt(options, 'unicodelevel', list(self.tokens), 'basic')
139
+ if level not in self._all_tokens:
140
+ # compile the regexes now
141
+ self._tokens = self.__class__.process_tokendef(level)
142
+ else:
143
+ self._tokens = self._all_tokens[level]
144
+
145
+ RegexLexer.__init__(self, **options)
146
+
147
+
148
+ class NemerleLexer(RegexLexer):
149
+ """
150
+ For Nemerle source code.
151
+
152
+ Additional options accepted:
153
+
154
+ `unicodelevel`
155
+ Determines which Unicode characters this lexer allows for identifiers.
156
+ The possible values are:
157
+
158
+ * ``none`` -- only the ASCII letters and numbers are allowed. This
159
+ is the fastest selection.
160
+ * ``basic`` -- all Unicode characters from the specification except
161
+ category ``Lo`` are allowed.
162
+ * ``full`` -- all Unicode characters as specified in the C# specs
163
+ are allowed. Note that this means a considerable slowdown since the
164
+ ``Lo`` category has more than 40,000 characters in it!
165
+
166
+ The default value is ``basic``.
167
+
168
+ .. versionadded:: 1.5
169
+ """
170
+
171
+ name = 'Nemerle'
172
+ url = 'http://nemerle.org'
173
+ aliases = ['nemerle']
174
+ filenames = ['*.n']
175
+ mimetypes = ['text/x-nemerle'] # inferred
176
+
177
+ flags = re.MULTILINE | re.DOTALL
178
+
179
+ # for the range of allowed unicode characters in identifiers, see
180
+ # http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
181
+
182
+ levels = {
183
+ 'none': r'@?[_a-zA-Z]\w*',
184
+ 'basic': ('@?[_' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl') + ']' +
185
+ '[' + uni.combine('Lu', 'Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc',
186
+ 'Cf', 'Mn', 'Mc') + ']*'),
187
+ 'full': ('@?(?:_|[^' +
188
+ uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' +
189
+ '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl',
190
+ 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'),
191
+ }
192
+
193
+ tokens = {}
194
+ token_variants = True
195
+
196
+ for levelname, cs_ident in levels.items():
197
+ tokens[levelname] = {
198
+ 'root': [
199
+ # method names
200
+ (r'^([ \t]*)((?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type
201
+ r'(' + cs_ident + ')' # method name
202
+ r'(\s*)(\()', # signature start
203
+ bygroups(Whitespace, using(this), Name.Function, Whitespace, \
204
+ Punctuation)),
205
+ (r'^(\s*)(\[.*?\])', bygroups(Whitespace, Name.Attribute)),
206
+ (r'[^\S\n]+', Whitespace),
207
+ (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation
208
+ (r'//.*?\n', Comment.Single),
209
+ (r'/[*].*?[*]/', Comment.Multiline),
210
+ (r'\n', Whitespace),
211
+ (r'(\$)(\s*)(")', bygroups(String, Whitespace, String),
212
+ 'splice-string'),
213
+ (r'(\$)(\s*)(<#)', bygroups(String, Whitespace, String),
214
+ 'splice-string2'),
215
+ (r'<#', String, 'recursive-string'),
216
+
217
+ (r'(<\[)(\s*)(' + cs_ident + ':)?',
218
+ bygroups(Keyword, Whitespace, Keyword)),
219
+ (r'\]\>', Keyword),
220
+
221
+ # quasiquotation only
222
+ (r'\$' + cs_ident, Name),
223
+ (r'(\$)(\()', bygroups(Name, Punctuation),
224
+ 'splice-string-content'),
225
+
226
+ (r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation),
227
+ (r'[{}]', Punctuation),
228
+ (r'@"(""|[^"])*"', String),
229
+ (r'"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String),
230
+ (r"'\\.'|'[^\\]'", String.Char),
231
+ (r"0[xX][0-9a-fA-F]+[Ll]?", Number),
232
+ (r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFLdD]?", Number),
233
+ (r'(#)([ \t]*)(if|endif|else|elif|define|undef|'
234
+ r'line|error|warning|region|endregion|pragma)\b',
235
+ bygroups(Comment.Preproc, Whitespace, Comment.Preproc), 'preproc'),
236
+ (r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Whitespace, Keyword)),
237
+ (r'(abstract|and|as|base|catch|def|delegate|'
238
+ r'enum|event|extern|false|finally|'
239
+ r'fun|implements|interface|internal|'
240
+ r'is|macro|match|matches|module|mutable|new|'
241
+ r'null|out|override|params|partial|private|'
242
+ r'protected|public|ref|sealed|static|'
243
+ r'syntax|this|throw|true|try|type|typeof|'
244
+ r'virtual|volatile|when|where|with|'
245
+ r'assert|assert2|async|break|checked|continue|do|else|'
246
+ r'ensures|for|foreach|if|late|lock|new|nolate|'
247
+ r'otherwise|regexp|repeat|requires|return|surroundwith|'
248
+ r'unchecked|unless|using|while|yield)\b', Keyword),
249
+ (r'(global)(::)', bygroups(Keyword, Punctuation)),
250
+ (r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|'
251
+ r'short|string|uint|ulong|ushort|void|array|list)\b\??',
252
+ Keyword.Type),
253
+ (r'(:>?)(\s*)(' + cs_ident + r'\??)',
254
+ bygroups(Punctuation, Whitespace, Keyword.Type)),
255
+ (r'(class|struct|variant|module)(\s+)',
256
+ bygroups(Keyword, Whitespace), 'class'),
257
+ (r'(namespace|using)(\s+)', bygroups(Keyword, Whitespace),
258
+ 'namespace'),
259
+ (cs_ident, Name),
260
+ ],
261
+ 'class': [
262
+ (cs_ident, Name.Class, '#pop')
263
+ ],
264
+ 'preproc': [
265
+ (r'\w+', Comment.Preproc),
266
+ (r'[ \t]+', Whitespace),
267
+ (r'\n', Whitespace, '#pop')
268
+ ],
269
+ 'namespace': [
270
+ (r'(?=\()', Text, '#pop'), # using (resource)
271
+ ('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop')
272
+ ],
273
+ 'splice-string': [
274
+ (r'[^"$]', String),
275
+ (r'\$' + cs_ident, Name),
276
+ (r'(\$)(\()', bygroups(Name, Punctuation),
277
+ 'splice-string-content'),
278
+ (r'\\"', String),
279
+ (r'"', String, '#pop')
280
+ ],
281
+ 'splice-string2': [
282
+ (r'[^#<>$]', String),
283
+ (r'\$' + cs_ident, Name),
284
+ (r'(\$)(\()', bygroups(Name, Punctuation),
285
+ 'splice-string-content'),
286
+ (r'<#', String, '#push'),
287
+ (r'#>', String, '#pop')
288
+ ],
289
+ 'recursive-string': [
290
+ (r'[^#<>]', String),
291
+ (r'<#', String, '#push'),
292
+ (r'#>', String, '#pop')
293
+ ],
294
+ 'splice-string-content': [
295
+ (r'if|match', Keyword),
296
+ (r'[~!%^&*+=|\[\]:;,.<>/?-\\"$ ]', Punctuation),
297
+ (cs_ident, Name),
298
+ (r'\d+', Number),
299
+ (r'\(', Punctuation, '#push'),
300
+ (r'\)', Punctuation, '#pop')
301
+ ]
302
+ }
303
+
304
+ def __init__(self, **options):
305
+ level = get_choice_opt(options, 'unicodelevel', list(self.tokens),
306
+ 'basic')
307
+ if level not in self._all_tokens:
308
+ # compile the regexes now
309
+ self._tokens = self.__class__.process_tokendef(level)
310
+ else:
311
+ self._tokens = self._all_tokens[level]
312
+
313
+ RegexLexer.__init__(self, **options)
314
+
315
+ def analyse_text(text):
316
+ """Nemerle is quite similar to Python, but @if is relatively uncommon
317
+ elsewhere."""
318
+ result = 0
319
+
320
+ if '@if' in text:
321
+ result += 0.1
322
+
323
+ return result
324
+
325
+
326
+ class BooLexer(RegexLexer):
327
+ """
328
+ For Boo source code.
329
+ """
330
+
331
+ name = 'Boo'
332
+ url = 'https://github.com/boo-lang/boo'
333
+ aliases = ['boo']
334
+ filenames = ['*.boo']
335
+ mimetypes = ['text/x-boo']
336
+
337
+ tokens = {
338
+ 'root': [
339
+ (r'\s+', Whitespace),
340
+ (r'(#|//).*$', Comment.Single),
341
+ (r'/[*]', Comment.Multiline, 'comment'),
342
+ (r'[]{}:(),.;[]', Punctuation),
343
+ (r'(\\)(\n)', bygroups(Text, Whitespace)),
344
+ (r'\\', Text),
345
+ (r'(in|is|and|or|not)\b', Operator.Word),
346
+ (r'/(\\\\|\\[^\\]|[^/\\\s])/', String.Regex),
347
+ (r'@/(\\\\|\\[^\\]|[^/\\])*/', String.Regex),
348
+ (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator),
349
+ (r'(as|abstract|callable|constructor|destructor|do|import|'
350
+ r'enum|event|final|get|interface|internal|of|override|'
351
+ r'partial|private|protected|public|return|set|static|'
352
+ r'struct|transient|virtual|yield|super|and|break|cast|'
353
+ r'continue|elif|else|ensure|except|for|given|goto|if|in|'
354
+ r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|'
355
+ r'while|from|as)\b', Keyword),
356
+ (r'def(?=\s+\(.*?\))', Keyword),
357
+ (r'(def)(\s+)', bygroups(Keyword, Whitespace), 'funcname'),
358
+ (r'(class)(\s+)', bygroups(Keyword, Whitespace), 'classname'),
359
+ (r'(namespace)(\s+)', bygroups(Keyword, Whitespace), 'namespace'),
360
+ (r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|'
361
+ r'assert|checked|enumerate|filter|getter|len|lock|map|'
362
+ r'matrix|max|min|normalArrayIndexing|print|property|range|'
363
+ r'rawArrayIndexing|required|typeof|unchecked|using|'
364
+ r'yieldAll|zip)\b', Name.Builtin),
365
+ (r'"""(\\\\|\\"|.*?)"""', String.Double),
366
+ (r'"(\\\\|\\[^\\]|[^"\\])*"', String.Double),
367
+ (r"'(\\\\|\\[^\\]|[^'\\])*'", String.Single),
368
+ (r'[a-zA-Z_]\w*', Name),
369
+ (r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float),
370
+ (r'[0-9][0-9.]*(ms?|d|h|s)', Number),
371
+ (r'0\d+', Number.Oct),
372
+ (r'0x[a-fA-F0-9]+', Number.Hex),
373
+ (r'\d+L', Number.Integer.Long),
374
+ (r'\d+', Number.Integer),
375
+ ],
376
+ 'comment': [
377
+ ('/[*]', Comment.Multiline, '#push'),
378
+ ('[*]/', Comment.Multiline, '#pop'),
379
+ ('[^/*]', Comment.Multiline),
380
+ ('[*/]', Comment.Multiline)
381
+ ],
382
+ 'funcname': [
383
+ (r'[a-zA-Z_]\w*', Name.Function, '#pop')
384
+ ],
385
+ 'classname': [
386
+ (r'[a-zA-Z_]\w*', Name.Class, '#pop')
387
+ ],
388
+ 'namespace': [
389
+ (r'[a-zA-Z_][\w.]*', Name.Namespace, '#pop')
390
+ ]
391
+ }
392
+
393
+
394
+ class VbNetLexer(RegexLexer):
395
+ """
396
+ For Visual Basic.NET source code.
397
+ Also LibreOffice Basic, OpenOffice Basic, and StarOffice Basic.
398
+ """
399
+
400
+ name = 'VB.net'
401
+ url = 'https://docs.microsoft.com/en-us/dotnet/visual-basic/'
402
+ aliases = ['vb.net', 'vbnet', 'lobas', 'oobas', 'sobas']
403
+ filenames = ['*.vb', '*.bas']
404
+ mimetypes = ['text/x-vbnet', 'text/x-vba'] # (?)
405
+
406
+ uni_name = '[_' + uni.combine('Ll', 'Lt', 'Lm', 'Nl') + ']' + \
407
+ '[' + uni.combine('Ll', 'Lt', 'Lm', 'Nl', 'Nd', 'Pc',
408
+ 'Cf', 'Mn', 'Mc') + ']*'
409
+
410
+ flags = re.MULTILINE | re.IGNORECASE
411
+ tokens = {
412
+ 'root': [
413
+ (r'^\s*<.*?>', Name.Attribute),
414
+ (r'\s+', Whitespace),
415
+ (r'\n', Whitespace),
416
+ (r'(rem\b.*?)(\n)', bygroups(Comment, Whitespace)),
417
+ (r"('.*?)(\n)", bygroups(Comment, Whitespace)),
418
+ (r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#Else|#End\s+If|#Const|'
419
+ r'#ExternalSource.*?\n|#End\s+ExternalSource|'
420
+ r'#Region.*?\n|#End\s+Region|#ExternalChecksum',
421
+ Comment.Preproc),
422
+ (r'[(){}!#,.:]', Punctuation),
423
+ (r'(Option)(\s+)(Strict|Explicit|Compare)(\s+)'
424
+ r'(On|Off|Binary|Text)',
425
+ bygroups(Keyword.Declaration, Whitespace, Keyword.Declaration,
426
+ Whitespace, Keyword.Declaration)),
427
+ (words((
428
+ 'AddHandler', 'Alias', 'ByRef', 'ByVal', 'Call', 'Case',
429
+ 'Catch', 'CBool', 'CByte', 'CChar', 'CDate', 'CDec', 'CDbl',
430
+ 'CInt', 'CLng', 'CObj', 'Continue', 'CSByte', 'CShort', 'CSng',
431
+ 'CStr', 'CType', 'CUInt', 'CULng', 'CUShort', 'Declare',
432
+ 'Default', 'Delegate', 'DirectCast', 'Do', 'Each', 'Else',
433
+ 'ElseIf', 'EndIf', 'Erase', 'Error', 'Event', 'Exit', 'False',
434
+ 'Finally', 'For', 'Friend', 'Get', 'Global', 'GoSub', 'GoTo',
435
+ 'Handles', 'If', 'Implements', 'Inherits', 'Interface', 'Let',
436
+ 'Lib', 'Loop', 'Me', 'MustInherit', 'MustOverride', 'MyBase',
437
+ 'MyClass', 'Narrowing', 'New', 'Next', 'Not', 'Nothing',
438
+ 'NotInheritable', 'NotOverridable', 'Of', 'On', 'Operator',
439
+ 'Option', 'Optional', 'Overloads', 'Overridable', 'Overrides',
440
+ 'ParamArray', 'Partial', 'Private', 'Protected', 'Public',
441
+ 'RaiseEvent', 'ReadOnly', 'ReDim', 'RemoveHandler', 'Resume',
442
+ 'Return', 'Select', 'Set', 'Shadows', 'Shared', 'Single',
443
+ 'Static', 'Step', 'Stop', 'SyncLock', 'Then', 'Throw', 'To',
444
+ 'True', 'Try', 'TryCast', 'Wend', 'Using', 'When', 'While',
445
+ 'Widening', 'With', 'WithEvents', 'WriteOnly'),
446
+ prefix=r'(?<!\.)', suffix=r'\b'), Keyword),
447
+ (r'(?<!\.)End\b', Keyword, 'end'),
448
+ (r'(?<!\.)(Dim|Const)\b', Keyword, 'dim'),
449
+ (r'(?<!\.)(Function|Sub|Property)(\s+)',
450
+ bygroups(Keyword, Whitespace), 'funcname'),
451
+ (r'(?<!\.)(Class|Structure|Enum)(\s+)',
452
+ bygroups(Keyword, Whitespace), 'classname'),
453
+ (r'(?<!\.)(Module|Namespace|Imports)(\s+)',
454
+ bygroups(Keyword, Whitespace), 'namespace'),
455
+ (r'(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|'
456
+ r'Object|SByte|Short|Single|String|Variant|UInteger|ULong|'
457
+ r'UShort)\b', Keyword.Type),
458
+ (r'(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|'
459
+ r'Or|OrElse|TypeOf|Xor)\b', Operator.Word),
460
+ (r'&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|'
461
+ r'<=|>=|<>|[-&*/\\^+=<>\[\]]',
462
+ Operator),
463
+ ('"', String, 'string'),
464
+ (r'(_)(\n)', bygroups(Text, Whitespace)), # Line continuation (must be before Name)
465
+ (uni_name + '[%&@!#$]?', Name),
466
+ ('#.*?#', Literal.Date),
467
+ (r'(\d+\.\d*|\d*\.\d+)(F[+-]?[0-9]+)?', Number.Float),
468
+ (r'\d+([SILDFR]|US|UI|UL)?', Number.Integer),
469
+ (r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer),
470
+ (r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer),
471
+ ],
472
+ 'string': [
473
+ (r'""', String),
474
+ (r'"C?', String, '#pop'),
475
+ (r'[^"]+', String),
476
+ ],
477
+ 'dim': [
478
+ (uni_name, Name.Variable, '#pop'),
479
+ default('#pop'), # any other syntax
480
+ ],
481
+ 'funcname': [
482
+ (uni_name, Name.Function, '#pop'),
483
+ ],
484
+ 'classname': [
485
+ (uni_name, Name.Class, '#pop'),
486
+ ],
487
+ 'namespace': [
488
+ (uni_name, Name.Namespace),
489
+ (r'\.', Name.Namespace),
490
+ default('#pop'),
491
+ ],
492
+ 'end': [
493
+ (r'\s+', Whitespace),
494
+ (r'(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b',
495
+ Keyword, '#pop'),
496
+ default('#pop'),
497
+ ]
498
+ }
499
+
500
+ def analyse_text(text):
501
+ if re.search(r'^\s*(#If|Module|Namespace)', text, re.MULTILINE):
502
+ return 0.5
503
+
504
+
505
+ class GenericAspxLexer(RegexLexer):
506
+ """
507
+ Lexer for ASP.NET pages.
508
+ """
509
+
510
+ name = 'aspx-gen'
511
+ filenames = []
512
+ mimetypes = []
513
+
514
+ flags = re.DOTALL
515
+
516
+ tokens = {
517
+ 'root': [
518
+ (r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)),
519
+ (r'(<script.*?>)(.*?)(</script>)', bygroups(using(XmlLexer),
520
+ Other,
521
+ using(XmlLexer))),
522
+ (r'(.+?)(?=<)', using(XmlLexer)),
523
+ (r'.+', using(XmlLexer)),
524
+ ],
525
+ }
526
+
527
+
528
+ # TODO support multiple languages within the same source file
529
+ class CSharpAspxLexer(DelegatingLexer):
530
+ """
531
+ Lexer for highlighting C# within ASP.NET pages.
532
+ """
533
+
534
+ name = 'aspx-cs'
535
+ aliases = ['aspx-cs']
536
+ filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
537
+ mimetypes = []
538
+
539
+ def __init__(self, **options):
540
+ super().__init__(CSharpLexer, GenericAspxLexer, **options)
541
+
542
+ def analyse_text(text):
543
+ if re.search(r'Page\s*Language="C#"', text, re.I) is not None:
544
+ return 0.2
545
+ elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None:
546
+ return 0.15
547
+
548
+
549
+ class VbNetAspxLexer(DelegatingLexer):
550
+ """
551
+ Lexer for highlighting Visual Basic.net within ASP.NET pages.
552
+ """
553
+
554
+ name = 'aspx-vb'
555
+ aliases = ['aspx-vb']
556
+ filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
557
+ mimetypes = []
558
+
559
+ def __init__(self, **options):
560
+ super().__init__(VbNetLexer, GenericAspxLexer, **options)
561
+
562
+ def analyse_text(text):
563
+ if re.search(r'Page\s*Language="Vb"', text, re.I) is not None:
564
+ return 0.2
565
+ elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None:
566
+ return 0.15
567
+
568
+
569
+ # Very close to functional.OcamlLexer
570
+ class FSharpLexer(RegexLexer):
571
+ """
572
+ For the F# language (version 3.0).
573
+
574
+ .. versionadded:: 1.5
575
+ """
576
+
577
+ name = 'F#'
578
+ url = 'https://fsharp.org/'
579
+ aliases = ['fsharp', 'f#']
580
+ filenames = ['*.fs', '*.fsi', '*.fsx']
581
+ mimetypes = ['text/x-fsharp']
582
+
583
+ keywords = [
584
+ 'abstract', 'as', 'assert', 'base', 'begin', 'class', 'default',
585
+ 'delegate', 'do!', 'do', 'done', 'downcast', 'downto', 'elif', 'else',
586
+ 'end', 'exception', 'extern', 'false', 'finally', 'for', 'function',
587
+ 'fun', 'global', 'if', 'inherit', 'inline', 'interface', 'internal',
588
+ 'in', 'lazy', 'let!', 'let', 'match', 'member', 'module', 'mutable',
589
+ 'namespace', 'new', 'null', 'of', 'open', 'override', 'private', 'public',
590
+ 'rec', 'return!', 'return', 'select', 'static', 'struct', 'then', 'to',
591
+ 'true', 'try', 'type', 'upcast', 'use!', 'use', 'val', 'void', 'when',
592
+ 'while', 'with', 'yield!', 'yield',
593
+ ]
594
+ # Reserved words; cannot hurt to color them as keywords too.
595
+ keywords += [
596
+ 'atomic', 'break', 'checked', 'component', 'const', 'constraint',
597
+ 'constructor', 'continue', 'eager', 'event', 'external', 'fixed',
598
+ 'functor', 'include', 'method', 'mixin', 'object', 'parallel',
599
+ 'process', 'protected', 'pure', 'sealed', 'tailcall', 'trait',
600
+ 'virtual', 'volatile',
601
+ ]
602
+ keyopts = [
603
+ '!=', '#', '&&', '&', r'\(', r'\)', r'\*', r'\+', ',', r'-\.',
604
+ '->', '-', r'\.\.', r'\.', '::', ':=', ':>', ':', ';;', ';', '<-',
605
+ r'<\]', '<', r'>\]', '>', r'\?\?', r'\?', r'\[<', r'\[\|', r'\[', r'\]',
606
+ '_', '`', r'\{', r'\|\]', r'\|', r'\}', '~', '<@@', '<@', '=', '@>', '@@>',
607
+ ]
608
+
609
+ operators = r'[!$%&*+\./:<=>?@^|~-]'
610
+ word_operators = ['and', 'or', 'not']
611
+ prefix_syms = r'[!?~]'
612
+ infix_syms = r'[=<>@^|&+\*/$%-]'
613
+ primitives = [
614
+ 'sbyte', 'byte', 'char', 'nativeint', 'unativeint', 'float32', 'single',
615
+ 'float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32',
616
+ 'uint32', 'int64', 'uint64', 'decimal', 'unit', 'bool', 'string',
617
+ 'list', 'exn', 'obj', 'enum',
618
+ ]
619
+
620
+ # See http://msdn.microsoft.com/en-us/library/dd233181.aspx and/or
621
+ # http://fsharp.org/about/files/spec.pdf for reference. Good luck.
622
+
623
+ tokens = {
624
+ 'escape-sequence': [
625
+ (r'\\[\\"\'ntbrafv]', String.Escape),
626
+ (r'\\[0-9]{3}', String.Escape),
627
+ (r'\\u[0-9a-fA-F]{4}', String.Escape),
628
+ (r'\\U[0-9a-fA-F]{8}', String.Escape),
629
+ ],
630
+ 'root': [
631
+ (r'\s+', Whitespace),
632
+ (r'\(\)|\[\]', Name.Builtin.Pseudo),
633
+ (r'\b(?<!\.)([A-Z][\w\']*)(?=\s*\.)',
634
+ Name.Namespace, 'dotted'),
635
+ (r'\b([A-Z][\w\']*)', Name),
636
+ (r'(///.*?)(\n)', bygroups(String.Doc, Whitespace)),
637
+ (r'(//.*?)(\n)', bygroups(Comment.Single, Whitespace)),
638
+ (r'\(\*(?!\))', Comment, 'comment'),
639
+
640
+ (r'@"', String, 'lstring'),
641
+ (r'"""', String, 'tqs'),
642
+ (r'"', String, 'string'),
643
+
644
+ (r'\b(open|module)(\s+)([\w.]+)',
645
+ bygroups(Keyword, Whitespace, Name.Namespace)),
646
+ (r'\b(let!?)(\s+)(\w+)',
647
+ bygroups(Keyword, Whitespace, Name.Variable)),
648
+ (r'\b(type)(\s+)(\w+)',
649
+ bygroups(Keyword, Whitespace, Name.Class)),
650
+ (r'\b(member|override)(\s+)(\w+)(\.)(\w+)',
651
+ bygroups(Keyword, Whitespace, Name, Punctuation, Name.Function)),
652
+ (r'\b(%s)\b' % '|'.join(keywords), Keyword),
653
+ (r'``([^`\n\r\t]|`[^`\n\r\t])+``', Name),
654
+ (r'(%s)' % '|'.join(keyopts), Operator),
655
+ (r'(%s|%s)?%s' % (infix_syms, prefix_syms, operators), Operator),
656
+ (r'\b(%s)\b' % '|'.join(word_operators), Operator.Word),
657
+ (r'\b(%s)\b' % '|'.join(primitives), Keyword.Type),
658
+ (r'(#)([ \t]*)(if|endif|else|line|nowarn|light|\d+)\b(.*?)(\n)',
659
+ bygroups(Comment.Preproc, Whitespace, Comment.Preproc,
660
+ Comment.Preproc, Whitespace)),
661
+
662
+ (r"[^\W\d][\w']*", Name),
663
+
664
+ (r'\d[\d_]*[uU]?[yslLnQRZINGmM]?', Number.Integer),
665
+ (r'0[xX][\da-fA-F][\da-fA-F_]*[uU]?[yslLn]?[fF]?', Number.Hex),
666
+ (r'0[oO][0-7][0-7_]*[uU]?[yslLn]?', Number.Oct),
667
+ (r'0[bB][01][01_]*[uU]?[yslLn]?', Number.Bin),
668
+ (r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)[fFmM]?',
669
+ Number.Float),
670
+
671
+ (r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'B?",
672
+ String.Char),
673
+ (r"'.'", String.Char),
674
+ (r"'", Keyword), # a stray quote is another syntax element
675
+
676
+ (r'@?"', String.Double, 'string'),
677
+
678
+ (r'[~?][a-z][\w\']*:', Name.Variable),
679
+ ],
680
+ 'dotted': [
681
+ (r'\s+', Whitespace),
682
+ (r'\.', Punctuation),
683
+ (r'[A-Z][\w\']*(?=\s*\.)', Name.Namespace),
684
+ (r'[A-Z][\w\']*', Name, '#pop'),
685
+ (r'[a-z_][\w\']*', Name, '#pop'),
686
+ # e.g. dictionary index access
687
+ default('#pop'),
688
+ ],
689
+ 'comment': [
690
+ (r'[^(*)@"]+', Comment),
691
+ (r'\(\*', Comment, '#push'),
692
+ (r'\*\)', Comment, '#pop'),
693
+ # comments cannot be closed within strings in comments
694
+ (r'@"', String, 'lstring'),
695
+ (r'"""', String, 'tqs'),
696
+ (r'"', String, 'string'),
697
+ (r'[(*)@]', Comment),
698
+ ],
699
+ 'string': [
700
+ (r'[^\\"]+', String),
701
+ include('escape-sequence'),
702
+ (r'\\\n', String),
703
+ (r'\n', String), # newlines are allowed in any string
704
+ (r'"B?', String, '#pop'),
705
+ ],
706
+ 'lstring': [
707
+ (r'[^"]+', String),
708
+ (r'\n', String),
709
+ (r'""', String),
710
+ (r'"B?', String, '#pop'),
711
+ ],
712
+ 'tqs': [
713
+ (r'[^"]+', String),
714
+ (r'\n', String),
715
+ (r'"""B?', String, '#pop'),
716
+ (r'"', String),
717
+ ],
718
+ }
719
+
720
+ def analyse_text(text):
721
+ """F# doesn't have that many unique features -- |> and <| are weak
722
+ indicators."""
723
+ result = 0
724
+ if '|>' in text:
725
+ result += 0.05
726
+ if '<|' in text:
727
+ result += 0.05
728
+
729
+ return result
730
+
731
+
732
+ class XppLexer(RegexLexer):
733
+
734
+ """
735
+ For X++ source code. This is based loosely on the CSharpLexer
736
+
737
+ .. versionadded:: 2.15
738
+ """
739
+
740
+ name = 'X++'
741
+ url = 'https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/dev-ref/xpp-language-reference'
742
+ aliases = ['xpp', 'x++']
743
+ filenames = ['*.xpp']
744
+
745
+ flags = re.MULTILINE
746
+
747
+ XPP_CHARS = ('@?(?:_|[^' +
748
+ uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])' +
749
+ '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl',
750
+ 'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*');
751
+ # Temporary, see
752
+ # https://github.com/thatch/regexlint/pull/49
753
+ XPP_CHARS = XPP_CHARS.replace('\x00', '\x01')
754
+
755
+ OPERATORS = (
756
+ '<=', '>=', '+=', '-=', '*=', '/=', '!=', '==',
757
+ '&&', '||', '>>', '<<', '++', '--', '+', '-', '*',
758
+ '/', '%', '&', '|', '^', '<', '>', '?', '!', '~', '=',
759
+ )
760
+ KEYWORDS = ('abstract','anytype','as','async','asc','at','avg','break','breakpoint','by','byref','case','catch',
761
+ 'changecompany','client','container','continue','count','crosscompany','default','delegate',
762
+ 'delete_from','desc','display','div','do','edit','else','element','eventhandler','exists','false','final',
763
+ 'firstfast','firstonly','firstonly10','firstonly100','firstonly1000','flush','for','forceliterals',
764
+ 'forcenestedloop','forceplaceholders','forceselectorder','forupdate','from','group','if','insert_recordset',
765
+ 'interface','is','join','like','maxof','minof','mod','new','next','nofetch','notexists','null','optimisticlock','order',
766
+ 'outer','pause','pessimisticlock','print','private','protected','public','repeatableread','retry','return',
767
+ 'reverse','select','server','setting','static','sum','super','switch','tablelock','this','throw','true','try','ttsabort','ttsbegin',
768
+ 'ttscommit','update_recordset','validtimestate','void','where','while','window')
769
+ RUNTIME_FUNCTIONS = ('_duration','abs','acos','any2Date','any2Enum','any2Guid','any2Int','any2Int64','any2Real','any2Str','anytodate',
770
+ 'anytoenum','anytoguid','anytoint','anytoint64','anytoreal','anytostr','asin','atan','beep','cTerm','char2Num','classIdGet',
771
+ 'corrFlagGet','corrFlagSet','cos','cosh','curExt','curUserId','date2Num','date2Str','datetime2Str','dayName','dayOfMth',
772
+ 'dayOfWk','dayOfYr','ddb','decRound','dg','dimOf','endMth','enum2str','exp','exp10','fV','fieldId2Name','fieldId2PName',
773
+ 'fieldName2Id','frac','funcName','getCurrentPartition','getCurrentPartitionRecId','getPrefix','guid2Str','idg','indexId2Name',
774
+ 'indexName2Id','int2Str','int642Str','intvMax','intvName','intvNo','intvNorm','log10','logN','match','max','min','mkDate','mthName',
775
+ 'mthOfYr','newGuid','nextMth','nextQtr','nextYr','num2Char','num2Date','num2Str','pmt','power','prevMth','prevQtr','prevYr',
776
+ 'prmIsDefault','pt','pv','rate','refPrintAll','round','runAs','sessionId','setPrefix','sin','sinh','sleep','sln','str2Date',
777
+ 'str2Datetime','str2Enum','str2Guid','str2Int','str2Int64','str2Num','str2Time','strAlpha','strCmp','strColSeq','strDel',
778
+ 'strFind','strFmt','strIns','strKeep','strLTrim','strLen','strLine','strLwr','strNFind','strPoke','strPrompt','strRTrim',
779
+ 'strRem','strRep','strScan','strUpr','subStr','syd','systemDateGet','systemDateSet','tableId2Name',
780
+ 'tableId2PName','tableName2Id','tan','tanh','term','time2Str','timeNow','today','trunc','typeOf','uint2Str','wkOfYr','year')
781
+ COMPILE_FUNCTIONS = ('attributeStr','classNum','classStr','configurationKeyNum','configurationKeyStr','dataEntityDataSourceStr','delegateStr',
782
+ 'dimensionHierarchyLevelStr','dimensionHierarchyStr','dimensionReferenceStr','dutyStr','enumCnt','enumLiteralStr','enumNum','enumStr',
783
+ 'extendedTypeNum','extendedTypeStr','fieldNum','fieldPName','fieldStr','formControlStr','formDataFieldStr','formDataSourceStr',
784
+ 'formMethodStr','formStr','identifierStr','indexNum','indexStr','licenseCodeNum','licenseCodeStr','literalStr','maxDate','maxInt',
785
+ 'measureStr','measurementStr','menuItemActionStr','menuItemDisplayStr','menuItemOutputStr','menuStr','methodStr','minInt','privilegeStr',
786
+ 'queryDatasourceStr','queryMethodStr','queryStr','reportStr','resourceStr','roleStr','ssrsReportStr','staticDelegateStr','staticMethodStr',
787
+ 'tableCollectionStr','tableFieldGroupStr','tableMethodStr','tableNum','tablePName','tableStaticMethodStr','tableStr','tileStr','varStr',
788
+ 'webActionItemStr','webDisplayContentItemStr','webFormStr','webMenuStr','webOutputContentItemStr','webReportStr','webSiteTempStr',
789
+ 'webStaticFileStr','webUrlItemStr','webWebPartStr','webletItemStr','webpageDefStr','websiteDefStr','workflowApprovalStr',
790
+ 'workflowCategoryStr','workflowTaskStr','workflowTypeStr')
791
+
792
+ tokens = {}
793
+
794
+ tokens = {
795
+ 'root': [
796
+ # method names
797
+ (r'(\s*)\b(else|if)\b([^\n])', bygroups(Whitespace, Keyword, using(this))), # ensure that if is not treated like a function
798
+ (r'^([ \t]*)((?:' + XPP_CHARS + r'(?:\[\])?\s+)+?)' # return type
799
+ r'(' + XPP_CHARS + ')' # method name
800
+ r'(\s*)(\()', # signature start
801
+ bygroups(Whitespace, using(this), Name.Function, Whitespace,
802
+ Punctuation)),
803
+ (r'^(\s*)(\[)([^\n]*?)(\])', bygroups(Whitespace, Name.Attribute, Name.Variable.Class, Name.Attribute)),
804
+ (r'[^\S\n]+', Whitespace),
805
+ (r'(\\)(\n)', bygroups(Text, Whitespace)), # line continuation
806
+ (r'//[^\n]*?\n', Comment.Single),
807
+ (r'/[*][^\n]*?[*]/', Comment.Multiline),
808
+ (r'\n', Whitespace),
809
+ (words(OPERATORS), Operator),
810
+ (r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator),
811
+ (r'[()\[\];:,.#@]', Punctuation),
812
+ (r'[{}]', Punctuation),
813
+ (r'@"(""|[^"])*"', String),
814
+ (r'\$?"(\\\\|\\[^\\]|[^"\\\n])*["\n]', String),
815
+ (r"'\\.'|'[^\\]'", String.Char),
816
+ (r"[0-9]+(\.[0-9]*)?([eE][+-][0-9]+)?"
817
+ r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number),
818
+ (words(KEYWORDS, suffix=r'\b'), Keyword),
819
+ (r'(boolean|int|int64|str|real|guid|date)\b\??', Keyword.Type),
820
+ (r'(class|struct|extends|implements)(\s+)', bygroups(Keyword, Whitespace), 'class'),
821
+ (r'('+XPP_CHARS+')(::)', bygroups(Name.Variable.Class, Punctuation)),
822
+ (r'(\s*)(\w+)(\s+\w+(,|=)?[^\n]*;)', bygroups(Whitespace, Name.Variable.Class, using(this))), # declaration
823
+ # x++ specific function to get field should highlight the classname
824
+ (r'(fieldNum\()('+XPP_CHARS+r')(\s*,\s*)('+XPP_CHARS+r')(\s*\))',
825
+ bygroups(using(this), Name.Variable.Class, using(this), Name.Property, using(this))),
826
+ # x++ specific function to get table should highlight the classname
827
+ (r'(tableNum\()('+XPP_CHARS+r')(\s*\))',
828
+ bygroups(using(this), Name.Variable.Class, using(this))),
829
+ (words(RUNTIME_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic),
830
+ (words(COMPILE_FUNCTIONS, suffix=r'(?=\()'), Name.Function.Magic),
831
+ (XPP_CHARS, Name),
832
+ ],
833
+ 'class': [
834
+ (XPP_CHARS, Name.Class, '#pop'),
835
+ default('#pop'),
836
+ ],
837
+ 'namespace': [
838
+ (r'(?=\()', Text, '#pop'), # using (resource)
839
+ ('(' + XPP_CHARS + r'|\.)+', Name.Namespace, '#pop'),
840
+ ]
841
+ }
shared/package-files/56/5637254ab13a7f25d7584d074a6c0fa33cde89d8b7a9f397d94291ce47025fd0/blob ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/_cast_Half_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_cast_Half(Tensor self, bool non_blocking=False) -> Tensor
26
+ inline at::Tensor _cast_Half(const at::Tensor & self, bool non_blocking=false) {
27
+ return at::_ops::_cast_Half::call(self, non_blocking);
28
+ }
29
+
30
+ }
shared/package-files/56/563906875503fa2d734c3035757a35b9e712b3a3f11dd190e6f94293f982098b/blob ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+
4
+ def main(args=None):
5
+ if args is None:
6
+ args = sys.argv[1:]
7
+
8
+ # TODO Handle library-wide options. Eg.:
9
+ # --unicodedata
10
+ # --verbose / other logging stuff
11
+
12
+ # TODO Allow a way to run arbitrary modules? Useful for setting
13
+ # library-wide options and calling another library. Eg.:
14
+ #
15
+ # $ fonttools --unicodedata=... fontmake ...
16
+ #
17
+ # This allows for a git-like command where thirdparty commands
18
+ # can be added. Should we just try importing the fonttools
19
+ # module first and try without if it fails?
20
+
21
+ if len(sys.argv) < 2:
22
+ sys.argv.append("help")
23
+ if sys.argv[1] == "-h" or sys.argv[1] == "--help":
24
+ sys.argv[1] = "help"
25
+ mod = "fontTools." + sys.argv[1]
26
+ sys.argv[1] = sys.argv[0] + " " + sys.argv[1]
27
+ del sys.argv[0]
28
+
29
+ import runpy
30
+
31
+ runpy.run_module(mod, run_name="__main__")
32
+
33
+
34
+ if __name__ == "__main__":
35
+ sys.exit(main())
shared/package-files/56/56396fd018eb070fa3025504ec0605f95dfe1aa31824ef3068d3a92c144ab373/blob ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Optional, Tuple, Union
3
+
4
+ from . import events, protocols, transports
5
+
6
+ _ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]]
7
+
8
+ if sys.version_info < (3, 8):
9
+ class IncompleteReadError(EOFError):
10
+ expected: Optional[int]
11
+ partial: bytes
12
+ def __init__(self, partial: bytes, expected: Optional[int]) -> None: ...
13
+ class LimitOverrunError(Exception):
14
+ consumed: int
15
+ def __init__(self, message: str, consumed: int) -> None: ...
16
+
17
+ async def open_connection(
18
+ host: Optional[str] = ...,
19
+ port: Optional[Union[int, str]] = ...,
20
+ *,
21
+ loop: Optional[events.AbstractEventLoop] = ...,
22
+ limit: int = ...,
23
+ ssl_handshake_timeout: Optional[float] = ...,
24
+ **kwds: Any,
25
+ ) -> Tuple[StreamReader, StreamWriter]: ...
26
+ async def start_server(
27
+ client_connected_cb: _ClientConnectedCallback,
28
+ host: Optional[str] = ...,
29
+ port: Optional[Union[int, str]] = ...,
30
+ *,
31
+ loop: Optional[events.AbstractEventLoop] = ...,
32
+ limit: int = ...,
33
+ ssl_handshake_timeout: Optional[float] = ...,
34
+ **kwds: Any,
35
+ ) -> events.AbstractServer: ...
36
+
37
+ if sys.platform != "win32":
38
+ if sys.version_info >= (3, 7):
39
+ from os import PathLike
40
+
41
+ _PathType = Union[str, PathLike[str]]
42
+ else:
43
+ _PathType = str
44
+ async def open_unix_connection(
45
+ path: Optional[_PathType] = ..., *, loop: Optional[events.AbstractEventLoop] = ..., limit: int = ..., **kwds: Any
46
+ ) -> Tuple[StreamReader, StreamWriter]: ...
47
+ async def start_unix_server(
48
+ client_connected_cb: _ClientConnectedCallback,
49
+ path: Optional[_PathType] = ...,
50
+ *,
51
+ loop: Optional[events.AbstractEventLoop] = ...,
52
+ limit: int = ...,
53
+ **kwds: Any,
54
+ ) -> events.AbstractServer: ...
55
+
56
+ class FlowControlMixin(protocols.Protocol): ...
57
+
58
+ class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
59
+ def __init__(
60
+ self,
61
+ stream_reader: StreamReader,
62
+ client_connected_cb: Optional[_ClientConnectedCallback] = ...,
63
+ loop: Optional[events.AbstractEventLoop] = ...,
64
+ ) -> None: ...
65
+ def connection_made(self, transport: transports.BaseTransport) -> None: ...
66
+ def connection_lost(self, exc: Optional[Exception]) -> None: ...
67
+ def data_received(self, data: bytes) -> None: ...
68
+ def eof_received(self) -> bool: ...
69
+
70
+ class StreamWriter:
71
+ def __init__(
72
+ self,
73
+ transport: transports.BaseTransport,
74
+ protocol: protocols.BaseProtocol,
75
+ reader: Optional[StreamReader],
76
+ loop: events.AbstractEventLoop,
77
+ ) -> None: ...
78
+ @property
79
+ def transport(self) -> transports.BaseTransport: ...
80
+ def write(self, data: bytes) -> None: ...
81
+ def writelines(self, data: Iterable[bytes]) -> None: ...
82
+ def write_eof(self) -> None: ...
83
+ def can_write_eof(self) -> bool: ...
84
+ def close(self) -> None: ...
85
+ if sys.version_info >= (3, 7):
86
+ def is_closing(self) -> bool: ...
87
+ async def wait_closed(self) -> None: ...
88
+ def get_extra_info(self, name: str, default: Any = ...) -> Any: ...
89
+ async def drain(self) -> None: ...
90
+
91
+ class StreamReader:
92
+ def __init__(self, limit: int = ..., loop: Optional[events.AbstractEventLoop] = ...) -> None: ...
93
+ def exception(self) -> Exception: ...
94
+ def set_exception(self, exc: Exception) -> None: ...
95
+ def set_transport(self, transport: transports.BaseTransport) -> None: ...
96
+ def feed_eof(self) -> None: ...
97
+ def at_eof(self) -> bool: ...
98
+ def feed_data(self, data: bytes) -> None: ...
99
+ async def readline(self) -> bytes: ...
100
+ async def readuntil(self, separator: bytes = ...) -> bytes: ...
101
+ async def read(self, n: int = ...) -> bytes: ...
102
+ async def readexactly(self, n: int) -> bytes: ...
103
+ def __aiter__(self) -> AsyncIterator[bytes]: ...
104
+ async def __anext__(self) -> bytes: ...
shared/package-files/56/5639df194837f65be5083c4ea0649e626f142f5db0642e724399fcf96f76783d/blob ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import types
5
+ import warnings
6
+
7
+ __all__ = ["registry", "get_filesystem_class", "default"]
8
+
9
+ # internal, mutable
10
+ _registry: dict[str, type] = {}
11
+
12
+ # external, immutable
13
+ registry = types.MappingProxyType(_registry)
14
+ default = "file"
15
+
16
+
17
+ def register_implementation(name, cls, clobber=False, errtxt=None):
18
+ """Add implementation class to the registry
19
+
20
+ Parameters
21
+ ----------
22
+ name: str
23
+ Protocol name to associate with the class
24
+ cls: class or str
25
+ if a class: fsspec-compliant implementation class (normally inherits from
26
+ ``fsspec.AbstractFileSystem``, gets added straight to the registry. If a
27
+ str, the full path to an implementation class like package.module.class,
28
+ which gets added to known_implementations,
29
+ so the import is deferred until the filesystem is actually used.
30
+ clobber: bool (optional)
31
+ Whether to overwrite a protocol with the same name; if False, will raise
32
+ instead.
33
+ errtxt: str (optional)
34
+ If given, then a failure to import the given class will result in this
35
+ text being given.
36
+ """
37
+ if isinstance(cls, str):
38
+ if name in known_implementations and clobber is False:
39
+ if cls != known_implementations[name]["class"]:
40
+ raise ValueError(
41
+ f"Name ({name}) already in the known_implementations and clobber "
42
+ f"is False"
43
+ )
44
+ else:
45
+ known_implementations[name] = {
46
+ "class": cls,
47
+ "err": errtxt or f"{cls} import failed for protocol {name}",
48
+ }
49
+
50
+ else:
51
+ if name in registry and clobber is False:
52
+ if _registry[name] is not cls:
53
+ raise ValueError(
54
+ f"Name ({name}) already in the registry and clobber is False"
55
+ )
56
+ else:
57
+ _registry[name] = cls
58
+
59
+
60
+ # protocols mapped to the class which implements them. This dict can be
61
+ # updated with register_implementation
62
+ known_implementations = {
63
+ "abfs": {
64
+ "class": "adlfs.AzureBlobFileSystem",
65
+ "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
66
+ },
67
+ "adl": {
68
+ "class": "adlfs.AzureDatalakeFileSystem",
69
+ "err": "Install adlfs to access Azure Datalake Gen1",
70
+ },
71
+ "arrow_hdfs": {
72
+ "class": "fsspec.implementations.arrow.HadoopFileSystem",
73
+ "err": "pyarrow and local java libraries required for HDFS",
74
+ },
75
+ "asynclocal": {
76
+ "class": "morefs.asyn_local.AsyncLocalFileSystem",
77
+ "err": "Install 'morefs[asynclocalfs]' to use AsyncLocalFileSystem",
78
+ },
79
+ "az": {
80
+ "class": "adlfs.AzureBlobFileSystem",
81
+ "err": "Install adlfs to access Azure Datalake Gen2 and Azure Blob Storage",
82
+ },
83
+ "blockcache": {"class": "fsspec.implementations.cached.CachingFileSystem"},
84
+ "box": {
85
+ "class": "boxfs.BoxFileSystem",
86
+ "err": "Please install boxfs to access BoxFileSystem",
87
+ },
88
+ "cached": {"class": "fsspec.implementations.cached.CachingFileSystem"},
89
+ "dask": {
90
+ "class": "fsspec.implementations.dask.DaskWorkerFileSystem",
91
+ "err": "Install dask distributed to access worker file system",
92
+ },
93
+ "data": {"class": "fsspec.implementations.data.DataFileSystem"},
94
+ "dbfs": {
95
+ "class": "fsspec.implementations.dbfs.DatabricksFileSystem",
96
+ "err": "Install the requests package to use the DatabricksFileSystem",
97
+ },
98
+ "dir": {"class": "fsspec.implementations.dirfs.DirFileSystem"},
99
+ "dropbox": {
100
+ "class": "dropboxdrivefs.DropboxDriveFileSystem",
101
+ "err": (
102
+ 'DropboxFileSystem requires "dropboxdrivefs","requests" and "'
103
+ '"dropbox" to be installed'
104
+ ),
105
+ },
106
+ "dvc": {
107
+ "class": "dvc.api.DVCFileSystem",
108
+ "err": "Install dvc to access DVCFileSystem",
109
+ },
110
+ "file": {"class": "fsspec.implementations.local.LocalFileSystem"},
111
+ "filecache": {"class": "fsspec.implementations.cached.WholeFileCacheFileSystem"},
112
+ "ftp": {"class": "fsspec.implementations.ftp.FTPFileSystem"},
113
+ "gcs": {
114
+ "class": "gcsfs.GCSFileSystem",
115
+ "err": "Please install gcsfs to access Google Storage",
116
+ },
117
+ "gdrive": {
118
+ "class": "gdrivefs.GoogleDriveFileSystem",
119
+ "err": "Please install gdrivefs for access to Google Drive",
120
+ },
121
+ "generic": {"class": "fsspec.generic.GenericFileSystem"},
122
+ "git": {
123
+ "class": "fsspec.implementations.git.GitFileSystem",
124
+ "err": "Install pygit2 to browse local git repos",
125
+ },
126
+ "github": {
127
+ "class": "fsspec.implementations.github.GithubFileSystem",
128
+ "err": "Install the requests package to use the github FS",
129
+ },
130
+ "gs": {
131
+ "class": "gcsfs.GCSFileSystem",
132
+ "err": "Please install gcsfs to access Google Storage",
133
+ },
134
+ "hdfs": {
135
+ "class": "fsspec.implementations.arrow.HadoopFileSystem",
136
+ "err": "pyarrow and local java libraries required for HDFS",
137
+ },
138
+ "hf": {
139
+ "class": "huggingface_hub.HfFileSystem",
140
+ "err": "Install huggingface_hub to access HfFileSystem",
141
+ },
142
+ "http": {
143
+ "class": "fsspec.implementations.http.HTTPFileSystem",
144
+ "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
145
+ },
146
+ "https": {
147
+ "class": "fsspec.implementations.http.HTTPFileSystem",
148
+ "err": 'HTTPFileSystem requires "requests" and "aiohttp" to be installed',
149
+ },
150
+ "jlab": {
151
+ "class": "fsspec.implementations.jupyter.JupyterFileSystem",
152
+ "err": "Jupyter FS requires requests to be installed",
153
+ },
154
+ "jupyter": {
155
+ "class": "fsspec.implementations.jupyter.JupyterFileSystem",
156
+ "err": "Jupyter FS requires requests to be installed",
157
+ },
158
+ "lakefs": {
159
+ "class": "lakefs_spec.LakeFSFileSystem",
160
+ "err": "Please install lakefs-spec to access LakeFSFileSystem",
161
+ },
162
+ "libarchive": {
163
+ "class": "fsspec.implementations.libarchive.LibArchiveFileSystem",
164
+ "err": "LibArchive requires to be installed",
165
+ },
166
+ "local": {"class": "fsspec.implementations.local.LocalFileSystem"},
167
+ "memory": {"class": "fsspec.implementations.memory.MemoryFileSystem"},
168
+ "oci": {
169
+ "class": "ocifs.OCIFileSystem",
170
+ "err": "Install ocifs to access OCI Object Storage",
171
+ },
172
+ "ocilake": {
173
+ "class": "ocifs.OCIFileSystem",
174
+ "err": "Install ocifs to access OCI Data Lake",
175
+ },
176
+ "oss": {
177
+ "class": "ossfs.OSSFileSystem",
178
+ "err": "Install ossfs to access Alibaba Object Storage System",
179
+ },
180
+ "reference": {"class": "fsspec.implementations.reference.ReferenceFileSystem"},
181
+ "root": {
182
+ "class": "fsspec_xrootd.XRootDFileSystem",
183
+ "err": (
184
+ "Install fsspec-xrootd to access xrootd storage system. "
185
+ "Note: 'root' is the protocol name for xrootd storage systems, "
186
+ "not referring to root directories"
187
+ ),
188
+ },
189
+ "s3": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
190
+ "s3a": {"class": "s3fs.S3FileSystem", "err": "Install s3fs to access S3"},
191
+ "sftp": {
192
+ "class": "fsspec.implementations.sftp.SFTPFileSystem",
193
+ "err": 'SFTPFileSystem requires "paramiko" to be installed',
194
+ },
195
+ "simplecache": {"class": "fsspec.implementations.cached.SimpleCacheFileSystem"},
196
+ "smb": {
197
+ "class": "fsspec.implementations.smb.SMBFileSystem",
198
+ "err": 'SMB requires "smbprotocol" or "smbprotocol[kerberos]" installed',
199
+ },
200
+ "ssh": {
201
+ "class": "fsspec.implementations.sftp.SFTPFileSystem",
202
+ "err": 'SFTPFileSystem requires "paramiko" to be installed',
203
+ },
204
+ "tar": {"class": "fsspec.implementations.tar.TarFileSystem"},
205
+ "wandb": {"class": "wandbfs.WandbFS", "err": "Install wandbfs to access wandb"},
206
+ "webdav": {
207
+ "class": "webdav4.fsspec.WebdavFileSystem",
208
+ "err": "Install webdav4 to access WebDAV",
209
+ },
210
+ "webhdfs": {
211
+ "class": "fsspec.implementations.webhdfs.WebHDFS",
212
+ "err": 'webHDFS access requires "requests" to be installed',
213
+ },
214
+ "zip": {"class": "fsspec.implementations.zip.ZipFileSystem"},
215
+ }
216
+
217
+
218
+ def get_filesystem_class(protocol):
219
+ """Fetch named protocol implementation from the registry
220
+
221
+ The dict ``known_implementations`` maps protocol names to the locations
222
+ of classes implementing the corresponding file-system. When used for the
223
+ first time, appropriate imports will happen and the class will be placed in
224
+ the registry. All subsequent calls will fetch directly from the registry.
225
+
226
+ Some protocol implementations require additional dependencies, and so the
227
+ import may fail. In this case, the string in the "err" field of the
228
+ ``known_implementations`` will be given as the error message.
229
+ """
230
+ if not protocol:
231
+ protocol = default
232
+
233
+ if protocol not in registry:
234
+ if protocol not in known_implementations:
235
+ raise ValueError(f"Protocol not known: {protocol}")
236
+ bit = known_implementations[protocol]
237
+ try:
238
+ register_implementation(protocol, _import_class(bit["class"]))
239
+ except ImportError as e:
240
+ raise ImportError(bit["err"]) from e
241
+ cls = registry[protocol]
242
+ if getattr(cls, "protocol", None) in ("abstract", None):
243
+ cls.protocol = protocol
244
+
245
+ return cls
246
+
247
+
248
+ s3_msg = """Your installed version of s3fs is very old and known to cause
249
+ severe performance issues, see also https://github.com/dask/dask/issues/10276
250
+
251
+ To fix, you should specify a lower version bound on s3fs, or
252
+ update the current installation.
253
+ """
254
+
255
+
256
+ def _import_class(cls, minv=None):
257
+ """Take a string FQP and return the imported class or identifier
258
+
259
+ cls is of the form "package.module.klass" or "package.module:subobject.klass"
260
+ """
261
+ if ":" in cls:
262
+ mod, name = cls.rsplit(":", 1)
263
+ s3 = mod == "s3fs"
264
+ mod = importlib.import_module(mod)
265
+ if s3 and mod.__version__.split(".") < ["0", "5"]:
266
+ warnings.warn(s3_msg)
267
+ for part in name.split("."):
268
+ mod = getattr(mod, part)
269
+ return mod
270
+ else:
271
+ mod, name = cls.rsplit(".", 1)
272
+ s3 = mod == "s3fs"
273
+ mod = importlib.import_module(mod)
274
+ if s3 and mod.__version__.split(".") < ["0", "5"]:
275
+ warnings.warn(s3_msg)
276
+ return getattr(mod, name)
277
+
278
+
279
+ def filesystem(protocol, **storage_options):
280
+ """Instantiate filesystems for given protocol and arguments
281
+
282
+ ``storage_options`` are specific to the protocol being chosen, and are
283
+ passed directly to the class.
284
+ """
285
+ if protocol == "arrow_hdfs":
286
+ warnings.warn(
287
+ "The 'arrow_hdfs' protocol has been deprecated and will be "
288
+ "removed in the future. Specify it as 'hdfs'.",
289
+ DeprecationWarning,
290
+ )
291
+
292
+ cls = get_filesystem_class(protocol)
293
+ return cls(**storage_options)
294
+
295
+
296
+ def available_protocols():
297
+ """Return a list of the implemented protocols.
298
+
299
+ Note that any given protocol may require extra packages to be importable.
300
+ """
301
+ return list(known_implementations)
shared/package-files/56/563a1e1c187330875efa2ccd66fae72633c03e07e5497df26d155b2eb6f2a38b/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API nonzero_numpy {
18
+ using schema = ::std::vector<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::nonzero_numpy")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nonzero_numpy(Tensor self) -> Tensor[]")
24
+ static ::std::vector<at::Tensor> call(const at::Tensor & self);
25
+ static ::std::vector<at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ }} // namespace at::_ops
shared/package-files/56/563b9052bebaf2986ae5b707e34afde013e7641287cc97ff31005f33a0dbf7a5/blob ADDED
Binary file (418 Bytes). View file
 
shared/package-files/56/563b9821194c63e2bbf616ab92d863cdc8052fbae59242cea00c0d7c4088959c/blob ADDED
@@ -0,0 +1,857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Principal Component Analysis."""
2
+
3
+ # Authors: The scikit-learn developers
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+
6
+ from math import lgamma, log, sqrt
7
+ from numbers import Integral, Real
8
+
9
+ import numpy as np
10
+ from scipy import linalg
11
+ from scipy.sparse import issparse
12
+ from scipy.sparse.linalg import svds
13
+
14
+ from ..base import _fit_context
15
+ from ..utils import check_random_state
16
+ from ..utils._arpack import _init_arpack_v0
17
+ from ..utils._array_api import _convert_to_numpy, get_namespace
18
+ from ..utils._param_validation import Interval, RealNotInt, StrOptions
19
+ from ..utils.extmath import _randomized_svd, fast_logdet, stable_cumsum, svd_flip
20
+ from ..utils.sparsefuncs import _implicit_column_offset, mean_variance_axis
21
+ from ..utils.validation import check_is_fitted, validate_data
22
+ from ._base import _BasePCA
23
+
24
+
25
+ def _assess_dimension(spectrum, rank, n_samples):
26
+ """Compute the log-likelihood of a rank ``rank`` dataset.
27
+
28
+ The dataset is assumed to be embedded in gaussian noise of shape(n,
29
+ dimf) having spectrum ``spectrum``. This implements the method of
30
+ T. P. Minka.
31
+
32
+ Parameters
33
+ ----------
34
+ spectrum : ndarray of shape (n_features,)
35
+ Data spectrum.
36
+ rank : int
37
+ Tested rank value. It should be strictly lower than n_features,
38
+ otherwise the method isn't specified (division by zero in equation
39
+ (31) from the paper).
40
+ n_samples : int
41
+ Number of samples.
42
+
43
+ Returns
44
+ -------
45
+ ll : float
46
+ The log-likelihood.
47
+
48
+ References
49
+ ----------
50
+ This implements the method of `Thomas P. Minka:
51
+ Automatic Choice of Dimensionality for PCA. NIPS 2000: 598-604
52
+ <https://proceedings.neurips.cc/paper/2000/file/7503cfacd12053d309b6bed5c89de212-Paper.pdf>`_
53
+ """
54
+ xp, _ = get_namespace(spectrum)
55
+
56
+ n_features = spectrum.shape[0]
57
+ if not 1 <= rank < n_features:
58
+ raise ValueError("the tested rank should be in [1, n_features - 1]")
59
+
60
+ eps = 1e-15
61
+
62
+ if spectrum[rank - 1] < eps:
63
+ # When the tested rank is associated with a small eigenvalue, there's
64
+ # no point in computing the log-likelihood: it's going to be very
65
+ # small and won't be the max anyway. Also, it can lead to numerical
66
+ # issues below when computing pa, in particular in log((spectrum[i] -
67
+ # spectrum[j]) because this will take the log of something very small.
68
+ return -xp.inf
69
+
70
+ pu = -rank * log(2.0)
71
+ for i in range(1, rank + 1):
72
+ pu += (
73
+ lgamma((n_features - i + 1) / 2.0) - log(xp.pi) * (n_features - i + 1) / 2.0
74
+ )
75
+
76
+ pl = xp.sum(xp.log(spectrum[:rank]))
77
+ pl = -pl * n_samples / 2.0
78
+
79
+ v = max(eps, xp.sum(spectrum[rank:]) / (n_features - rank))
80
+ pv = -log(v) * n_samples * (n_features - rank) / 2.0
81
+
82
+ m = n_features * rank - rank * (rank + 1.0) / 2.0
83
+ pp = log(2.0 * xp.pi) * (m + rank) / 2.0
84
+
85
+ pa = 0.0
86
+ spectrum_ = xp.asarray(spectrum, copy=True)
87
+ spectrum_[rank:n_features] = v
88
+ for i in range(rank):
89
+ for j in range(i + 1, spectrum.shape[0]):
90
+ pa += log(
91
+ (spectrum[i] - spectrum[j]) * (1.0 / spectrum_[j] - 1.0 / spectrum_[i])
92
+ ) + log(n_samples)
93
+
94
+ ll = pu + pl + pv + pp - pa / 2.0 - rank * log(n_samples) / 2.0
95
+
96
+ return ll
97
+
98
+
99
+ def _infer_dimension(spectrum, n_samples):
100
+ """Infers the dimension of a dataset with a given spectrum.
101
+
102
+ The returned value will be in [1, n_features - 1].
103
+ """
104
+ xp, _ = get_namespace(spectrum)
105
+
106
+ ll = xp.empty_like(spectrum)
107
+ ll[0] = -xp.inf # we don't want to return n_components = 0
108
+ for rank in range(1, spectrum.shape[0]):
109
+ ll[rank] = _assess_dimension(spectrum, rank, n_samples)
110
+ return xp.argmax(ll)
111
+
112
+
113
+ class PCA(_BasePCA):
114
+ """Principal component analysis (PCA).
115
+
116
+ Linear dimensionality reduction using Singular Value Decomposition of the
117
+ data to project it to a lower dimensional space. The input data is centered
118
+ but not scaled for each feature before applying the SVD.
119
+
120
+ It uses the LAPACK implementation of the full SVD or a randomized truncated
121
+ SVD by the method of Halko et al. 2009, depending on the shape of the input
122
+ data and the number of components to extract.
123
+
124
+ With sparse inputs, the ARPACK implementation of the truncated SVD can be
125
+ used (i.e. through :func:`scipy.sparse.linalg.svds`). Alternatively, one
126
+ may consider :class:`TruncatedSVD` where the data are not centered.
127
+
128
+ Notice that this class only supports sparse inputs for some solvers such as
129
+ "arpack" and "covariance_eigh". See :class:`TruncatedSVD` for an
130
+ alternative with sparse data.
131
+
132
+ For a usage example, see
133
+ :ref:`sphx_glr_auto_examples_decomposition_plot_pca_iris.py`
134
+
135
+ Read more in the :ref:`User Guide <PCA>`.
136
+
137
+ Parameters
138
+ ----------
139
+ n_components : int, float or 'mle', default=None
140
+ Number of components to keep.
141
+ if n_components is not set all components are kept::
142
+
143
+ n_components == min(n_samples, n_features)
144
+
145
+ If ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's
146
+ MLE is used to guess the dimension. Use of ``n_components == 'mle'``
147
+ will interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.
148
+
149
+ If ``0 < n_components < 1`` and ``svd_solver == 'full'``, select the
150
+ number of components such that the amount of variance that needs to be
151
+ explained is greater than the percentage specified by n_components.
152
+
153
+ If ``svd_solver == 'arpack'``, the number of components must be
154
+ strictly less than the minimum of n_features and n_samples.
155
+
156
+ Hence, the None case results in::
157
+
158
+ n_components == min(n_samples, n_features) - 1
159
+
160
+ copy : bool, default=True
161
+ If False, data passed to fit are overwritten and running
162
+ fit(X).transform(X) will not yield the expected results,
163
+ use fit_transform(X) instead.
164
+
165
+ whiten : bool, default=False
166
+ When True (False by default) the `components_` vectors are multiplied
167
+ by the square root of n_samples and then divided by the singular values
168
+ to ensure uncorrelated outputs with unit component-wise variances.
169
+
170
+ Whitening will remove some information from the transformed signal
171
+ (the relative variance scales of the components) but can sometime
172
+ improve the predictive accuracy of the downstream estimators by
173
+ making their data respect some hard-wired assumptions.
174
+
175
+ svd_solver : {'auto', 'full', 'covariance_eigh', 'arpack', 'randomized'},\
176
+ default='auto'
177
+ "auto" :
178
+ The solver is selected by a default 'auto' policy is based on `X.shape` and
179
+ `n_components`: if the input data has fewer than 1000 features and
180
+ more than 10 times as many samples, then the "covariance_eigh"
181
+ solver is used. Otherwise, if the input data is larger than 500x500
182
+ and the number of components to extract is lower than 80% of the
183
+ smallest dimension of the data, then the more efficient
184
+ "randomized" method is selected. Otherwise the exact "full" SVD is
185
+ computed and optionally truncated afterwards.
186
+ "full" :
187
+ Run exact full SVD calling the standard LAPACK solver via
188
+ `scipy.linalg.svd` and select the components by postprocessing
189
+ "covariance_eigh" :
190
+ Precompute the covariance matrix (on centered data), run a
191
+ classical eigenvalue decomposition on the covariance matrix
192
+ typically using LAPACK and select the components by postprocessing.
193
+ This solver is very efficient for n_samples >> n_features and small
194
+ n_features. It is, however, not tractable otherwise for large
195
+ n_features (large memory footprint required to materialize the
196
+ covariance matrix). Also note that compared to the "full" solver,
197
+ this solver effectively doubles the condition number and is
198
+ therefore less numerical stable (e.g. on input data with a large
199
+ range of singular values).
200
+ "arpack" :
201
+ Run SVD truncated to `n_components` calling ARPACK solver via
202
+ `scipy.sparse.linalg.svds`. It requires strictly
203
+ `0 < n_components < min(X.shape)`
204
+ "randomized" :
205
+ Run randomized SVD by the method of Halko et al.
206
+
207
+ .. versionadded:: 0.18.0
208
+
209
+ .. versionchanged:: 1.5
210
+ Added the 'covariance_eigh' solver.
211
+
212
+ tol : float, default=0.0
213
+ Tolerance for singular values computed by svd_solver == 'arpack'.
214
+ Must be of range [0.0, infinity).
215
+
216
+ .. versionadded:: 0.18.0
217
+
218
+ iterated_power : int or 'auto', default='auto'
219
+ Number of iterations for the power method computed by
220
+ svd_solver == 'randomized'.
221
+ Must be of range [0, infinity).
222
+
223
+ .. versionadded:: 0.18.0
224
+
225
+ n_oversamples : int, default=10
226
+ This parameter is only relevant when `svd_solver="randomized"`.
227
+ It corresponds to the additional number of random vectors to sample the
228
+ range of `X` so as to ensure proper conditioning. See
229
+ :func:`~sklearn.utils.extmath.randomized_svd` for more details.
230
+
231
+ .. versionadded:: 1.1
232
+
233
+ power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'
234
+ Power iteration normalizer for randomized SVD solver.
235
+ Not used by ARPACK. See :func:`~sklearn.utils.extmath.randomized_svd`
236
+ for more details.
237
+
238
+ .. versionadded:: 1.1
239
+
240
+ random_state : int, RandomState instance or None, default=None
241
+ Used when the 'arpack' or 'randomized' solvers are used. Pass an int
242
+ for reproducible results across multiple function calls.
243
+ See :term:`Glossary <random_state>`.
244
+
245
+ .. versionadded:: 0.18.0
246
+
247
+ Attributes
248
+ ----------
249
+ components_ : ndarray of shape (n_components, n_features)
250
+ Principal axes in feature space, representing the directions of
251
+ maximum variance in the data. Equivalently, the right singular
252
+ vectors of the centered input data, parallel to its eigenvectors.
253
+ The components are sorted by decreasing ``explained_variance_``.
254
+
255
+ explained_variance_ : ndarray of shape (n_components,)
256
+ The amount of variance explained by each of the selected components.
257
+ The variance estimation uses `n_samples - 1` degrees of freedom.
258
+
259
+ Equal to n_components largest eigenvalues
260
+ of the covariance matrix of X.
261
+
262
+ .. versionadded:: 0.18
263
+
264
+ explained_variance_ratio_ : ndarray of shape (n_components,)
265
+ Percentage of variance explained by each of the selected components.
266
+
267
+ If ``n_components`` is not set then all components are stored and the
268
+ sum of the ratios is equal to 1.0.
269
+
270
+ singular_values_ : ndarray of shape (n_components,)
271
+ The singular values corresponding to each of the selected components.
272
+ The singular values are equal to the 2-norms of the ``n_components``
273
+ variables in the lower-dimensional space.
274
+
275
+ .. versionadded:: 0.19
276
+
277
+ mean_ : ndarray of shape (n_features,)
278
+ Per-feature empirical mean, estimated from the training set.
279
+
280
+ Equal to `X.mean(axis=0)`.
281
+
282
+ n_components_ : int
283
+ The estimated number of components. When n_components is set
284
+ to 'mle' or a number between 0 and 1 (with svd_solver == 'full') this
285
+ number is estimated from input data. Otherwise it equals the parameter
286
+ n_components, or the lesser value of n_features and n_samples
287
+ if n_components is None.
288
+
289
+ n_samples_ : int
290
+ Number of samples in the training data.
291
+
292
+ noise_variance_ : float
293
+ The estimated noise covariance following the Probabilistic PCA model
294
+ from Tipping and Bishop 1999. See "Pattern Recognition and
295
+ Machine Learning" by C. Bishop, 12.2.1 p. 574 or
296
+ http://www.miketipping.com/papers/met-mppca.pdf. It is required to
297
+ compute the estimated data covariance and score samples.
298
+
299
+ Equal to the average of (min(n_features, n_samples) - n_components)
300
+ smallest eigenvalues of the covariance matrix of X.
301
+
302
+ n_features_in_ : int
303
+ Number of features seen during :term:`fit`.
304
+
305
+ .. versionadded:: 0.24
306
+
307
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
308
+ Names of features seen during :term:`fit`. Defined only when `X`
309
+ has feature names that are all strings.
310
+
311
+ .. versionadded:: 1.0
312
+
313
+ See Also
314
+ --------
315
+ KernelPCA : Kernel Principal Component Analysis.
316
+ SparsePCA : Sparse Principal Component Analysis.
317
+ TruncatedSVD : Dimensionality reduction using truncated SVD.
318
+ IncrementalPCA : Incremental Principal Component Analysis.
319
+
320
+ References
321
+ ----------
322
+ For n_components == 'mle', this class uses the method from:
323
+ `Minka, T. P.. "Automatic choice of dimensionality for PCA".
324
+ In NIPS, pp. 598-604 <https://tminka.github.io/papers/pca/minka-pca.pdf>`_
325
+
326
+ Implements the probabilistic PCA model from:
327
+ `Tipping, M. E., and Bishop, C. M. (1999). "Probabilistic principal
328
+ component analysis". Journal of the Royal Statistical Society:
329
+ Series B (Statistical Methodology), 61(3), 611-622.
330
+ <http://www.miketipping.com/papers/met-mppca.pdf>`_
331
+ via the score and score_samples methods.
332
+
333
+ For svd_solver == 'arpack', refer to `scipy.sparse.linalg.svds`.
334
+
335
+ For svd_solver == 'randomized', see:
336
+ :doi:`Halko, N., Martinsson, P. G., and Tropp, J. A. (2011).
337
+ "Finding structure with randomness: Probabilistic algorithms for
338
+ constructing approximate matrix decompositions".
339
+ SIAM review, 53(2), 217-288.
340
+ <10.1137/090771806>`
341
+ and also
342
+ :doi:`Martinsson, P. G., Rokhlin, V., and Tygert, M. (2011).
343
+ "A randomized algorithm for the decomposition of matrices".
344
+ Applied and Computational Harmonic Analysis, 30(1), 47-68.
345
+ <10.1016/j.acha.2010.02.003>`
346
+
347
+ Examples
348
+ --------
349
+ >>> import numpy as np
350
+ >>> from sklearn.decomposition import PCA
351
+ >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
352
+ >>> pca = PCA(n_components=2)
353
+ >>> pca.fit(X)
354
+ PCA(n_components=2)
355
+ >>> print(pca.explained_variance_ratio_)
356
+ [0.9924 0.0075]
357
+ >>> print(pca.singular_values_)
358
+ [6.30061 0.54980]
359
+
360
+ >>> pca = PCA(n_components=2, svd_solver='full')
361
+ >>> pca.fit(X)
362
+ PCA(n_components=2, svd_solver='full')
363
+ >>> print(pca.explained_variance_ratio_)
364
+ [0.9924 0.00755]
365
+ >>> print(pca.singular_values_)
366
+ [6.30061 0.54980]
367
+
368
+ >>> pca = PCA(n_components=1, svd_solver='arpack')
369
+ >>> pca.fit(X)
370
+ PCA(n_components=1, svd_solver='arpack')
371
+ >>> print(pca.explained_variance_ratio_)
372
+ [0.99244]
373
+ >>> print(pca.singular_values_)
374
+ [6.30061]
375
+ """
376
+
377
+ _parameter_constraints: dict = {
378
+ "n_components": [
379
+ Interval(Integral, 0, None, closed="left"),
380
+ Interval(RealNotInt, 0, 1, closed="neither"),
381
+ StrOptions({"mle"}),
382
+ None,
383
+ ],
384
+ "copy": ["boolean"],
385
+ "whiten": ["boolean"],
386
+ "svd_solver": [
387
+ StrOptions({"auto", "full", "covariance_eigh", "arpack", "randomized"})
388
+ ],
389
+ "tol": [Interval(Real, 0, None, closed="left")],
390
+ "iterated_power": [
391
+ StrOptions({"auto"}),
392
+ Interval(Integral, 0, None, closed="left"),
393
+ ],
394
+ "n_oversamples": [Interval(Integral, 1, None, closed="left")],
395
+ "power_iteration_normalizer": [StrOptions({"auto", "QR", "LU", "none"})],
396
+ "random_state": ["random_state"],
397
+ }
398
+
399
+ def __init__(
400
+ self,
401
+ n_components=None,
402
+ *,
403
+ copy=True,
404
+ whiten=False,
405
+ svd_solver="auto",
406
+ tol=0.0,
407
+ iterated_power="auto",
408
+ n_oversamples=10,
409
+ power_iteration_normalizer="auto",
410
+ random_state=None,
411
+ ):
412
+ self.n_components = n_components
413
+ self.copy = copy
414
+ self.whiten = whiten
415
+ self.svd_solver = svd_solver
416
+ self.tol = tol
417
+ self.iterated_power = iterated_power
418
+ self.n_oversamples = n_oversamples
419
+ self.power_iteration_normalizer = power_iteration_normalizer
420
+ self.random_state = random_state
421
+
422
+ @_fit_context(prefer_skip_nested_validation=True)
423
+ def fit(self, X, y=None):
424
+ """Fit the model with X.
425
+
426
+ Parameters
427
+ ----------
428
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
429
+ Training data, where `n_samples` is the number of samples
430
+ and `n_features` is the number of features.
431
+
432
+ y : Ignored
433
+ Ignored.
434
+
435
+ Returns
436
+ -------
437
+ self : object
438
+ Returns the instance itself.
439
+ """
440
+ self._fit(X)
441
+ return self
442
+
443
+ @_fit_context(prefer_skip_nested_validation=True)
444
+ def fit_transform(self, X, y=None):
445
+ """Fit the model with X and apply the dimensionality reduction on X.
446
+
447
+ Parameters
448
+ ----------
449
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
450
+ Training data, where `n_samples` is the number of samples
451
+ and `n_features` is the number of features.
452
+
453
+ y : Ignored
454
+ Ignored.
455
+
456
+ Returns
457
+ -------
458
+ X_new : ndarray of shape (n_samples, n_components)
459
+ Transformed values.
460
+
461
+ Notes
462
+ -----
463
+ This method returns a Fortran-ordered array. To convert it to a
464
+ C-ordered array, use 'np.ascontiguousarray'.
465
+ """
466
+ U, S, _, X, x_is_centered, xp = self._fit(X)
467
+ if U is not None:
468
+ U = U[:, : self.n_components_]
469
+
470
+ if self.whiten:
471
+ # X_new = X * V / S * sqrt(n_samples) = U * sqrt(n_samples)
472
+ U *= sqrt(X.shape[0] - 1)
473
+ else:
474
+ # X_new = X * V = U * S * Vt * V = U * S
475
+ U *= S[: self.n_components_]
476
+
477
+ return U
478
+ else: # solver="covariance_eigh" does not compute U at fit time.
479
+ return self._transform(X, xp, x_is_centered=x_is_centered)
480
+
481
+ def _fit(self, X):
482
+ """Dispatch to the right submethod depending on the chosen solver."""
483
+ xp, is_array_api_compliant = get_namespace(X)
484
+
485
+ # Raise an error for sparse input and unsupported svd_solver
486
+ if issparse(X) and self.svd_solver not in ["auto", "arpack", "covariance_eigh"]:
487
+ raise TypeError(
488
+ 'PCA only support sparse inputs with the "arpack" and'
489
+ f' "covariance_eigh" solvers, while "{self.svd_solver}" was passed. See'
490
+ " TruncatedSVD for a possible alternative."
491
+ )
492
+ if self.svd_solver == "arpack" and is_array_api_compliant:
493
+ raise ValueError(
494
+ "PCA with svd_solver='arpack' is not supported for Array API inputs."
495
+ )
496
+
497
+ # Validate the data, without ever forcing a copy as any solver that
498
+ # supports sparse input data and the `covariance_eigh` solver are
499
+ # written in a way to avoid the need for any inplace modification of
500
+ # the input data contrary to the other solvers.
501
+ # The copy will happen
502
+ # later, only if needed, once the solver negotiation below is done.
503
+ X = validate_data(
504
+ self,
505
+ X,
506
+ dtype=[xp.float64, xp.float32],
507
+ force_writeable=True,
508
+ accept_sparse=("csr", "csc"),
509
+ ensure_2d=True,
510
+ copy=False,
511
+ )
512
+ self._fit_svd_solver = self.svd_solver
513
+ if self._fit_svd_solver == "auto" and issparse(X):
514
+ self._fit_svd_solver = "arpack"
515
+
516
+ if self.n_components is None:
517
+ if self._fit_svd_solver != "arpack":
518
+ n_components = min(X.shape)
519
+ else:
520
+ n_components = min(X.shape) - 1
521
+ else:
522
+ n_components = self.n_components
523
+
524
+ if self._fit_svd_solver == "auto":
525
+ # Tall and skinny problems are best handled by precomputing the
526
+ # covariance matrix.
527
+ if X.shape[1] <= 1_000 and X.shape[0] >= 10 * X.shape[1]:
528
+ self._fit_svd_solver = "covariance_eigh"
529
+ # Small problem or n_components == 'mle', just call full PCA
530
+ elif max(X.shape) <= 500 or n_components == "mle":
531
+ self._fit_svd_solver = "full"
532
+ elif 1 <= n_components < 0.8 * min(X.shape):
533
+ self._fit_svd_solver = "randomized"
534
+ # This is also the case of n_components in (0, 1)
535
+ else:
536
+ self._fit_svd_solver = "full"
537
+
538
+ # Call different fits for either full or truncated SVD
539
+ if self._fit_svd_solver in ("full", "covariance_eigh"):
540
+ return self._fit_full(X, n_components, xp, is_array_api_compliant)
541
+ elif self._fit_svd_solver in ["arpack", "randomized"]:
542
+ return self._fit_truncated(X, n_components, xp)
543
+
544
+ def _fit_full(self, X, n_components, xp, is_array_api_compliant):
545
+ """Fit the model by computing full SVD on X."""
546
+ n_samples, n_features = X.shape
547
+
548
+ if n_components == "mle":
549
+ if n_samples < n_features:
550
+ raise ValueError(
551
+ "n_components='mle' is only supported if n_samples >= n_features"
552
+ )
553
+ elif not 0 <= n_components <= min(n_samples, n_features):
554
+ raise ValueError(
555
+ f"n_components={n_components} must be between 0 and "
556
+ f"min(n_samples, n_features)={min(n_samples, n_features)} with "
557
+ f"svd_solver={self._fit_svd_solver!r}"
558
+ )
559
+
560
+ self.mean_ = xp.mean(X, axis=0)
561
+ # When X is a scipy sparse matrix, self.mean_ is a numpy matrix, so we need
562
+ # to transform it to a 1D array. Note that this is not the case when X
563
+ # is a scipy sparse array.
564
+ # TODO: remove the following two lines when scikit-learn only depends
565
+ # on scipy versions that no longer support scipy.sparse matrices.
566
+ self.mean_ = xp.reshape(xp.asarray(self.mean_), (-1,))
567
+
568
+ if self._fit_svd_solver == "full":
569
+ X_centered = xp.asarray(X, copy=True) if self.copy else X
570
+ X_centered -= self.mean_
571
+ x_is_centered = not self.copy
572
+
573
+ if not is_array_api_compliant:
574
+ # Use scipy.linalg with NumPy/SciPy inputs for the sake of not
575
+ # introducing unanticipated behavior changes. In the long run we
576
+ # could instead decide to always use xp.linalg.svd for all inputs,
577
+ # but that would make this code rely on numpy's SVD instead of
578
+ # scipy's. It's not 100% clear whether they use the same LAPACK
579
+ # solver by default though (assuming both are built against the
580
+ # same BLAS).
581
+ U, S, Vt = linalg.svd(X_centered, full_matrices=False)
582
+ else:
583
+ U, S, Vt = xp.linalg.svd(X_centered, full_matrices=False)
584
+ explained_variance_ = (S**2) / (n_samples - 1)
585
+
586
+ else:
587
+ assert self._fit_svd_solver == "covariance_eigh"
588
+ # In the following, we center the covariance matrix C afterwards
589
+ # (without centering the data X first) to avoid an unnecessary copy
590
+ # of X. Note that the mean_ attribute is still needed to center
591
+ # test data in the transform method.
592
+ #
593
+ # Note: at the time of writing, `xp.cov` does not exist in the
594
+ # Array API standard:
595
+ # https://github.com/data-apis/array-api/issues/43
596
+ #
597
+ # Besides, using `numpy.cov`, as of numpy 1.26.0, would not be
598
+ # memory efficient for our use case when `n_samples >> n_features`:
599
+ # `numpy.cov` centers a copy of the data before computing the
600
+ # matrix product instead of subtracting a small `(n_features,
601
+ # n_features)` square matrix from the gram matrix X.T @ X, as we do
602
+ # below.
603
+ x_is_centered = False
604
+ C = X.T @ X
605
+ C -= (
606
+ n_samples
607
+ * xp.reshape(self.mean_, (-1, 1))
608
+ * xp.reshape(self.mean_, (1, -1))
609
+ )
610
+ C /= n_samples - 1
611
+ eigenvals, eigenvecs = xp.linalg.eigh(C)
612
+
613
+ # When X is a scipy sparse matrix, the following two datastructures
614
+ # are returned as instances of the soft-deprecated numpy.matrix
615
+ # class. Note that this problem does not occur when X is a scipy
616
+ # sparse array (or another other kind of supported array).
617
+ # TODO: remove the following two lines when scikit-learn only
618
+ # depends on scipy versions that no longer support scipy.sparse
619
+ # matrices.
620
+ eigenvals = xp.reshape(xp.asarray(eigenvals), (-1,))
621
+ eigenvecs = xp.asarray(eigenvecs)
622
+
623
+ eigenvals = xp.flip(eigenvals, axis=0)
624
+ eigenvecs = xp.flip(eigenvecs, axis=1)
625
+
626
+ # The covariance matrix C is positive semi-definite by
627
+ # construction. However, the eigenvalues returned by xp.linalg.eigh
628
+ # can be slightly negative due to numerical errors. This would be
629
+ # an issue for the subsequent sqrt, hence the manual clipping.
630
+ eigenvals[eigenvals < 0.0] = 0.0
631
+ explained_variance_ = eigenvals
632
+
633
+ # Re-construct SVD of centered X indirectly and make it consistent
634
+ # with the other solvers.
635
+ S = xp.sqrt(eigenvals * (n_samples - 1))
636
+ Vt = eigenvecs.T
637
+ U = None
638
+
639
+ # flip eigenvectors' sign to enforce deterministic output
640
+ U, Vt = svd_flip(U, Vt, u_based_decision=False)
641
+
642
+ components_ = Vt
643
+
644
+ # Get variance explained by singular values
645
+ total_var = xp.sum(explained_variance_)
646
+ explained_variance_ratio_ = explained_variance_ / total_var
647
+ singular_values_ = xp.asarray(S, copy=True) # Store the singular values.
648
+
649
+ # Postprocess the number of components required
650
+ if n_components == "mle":
651
+ n_components = _infer_dimension(explained_variance_, n_samples)
652
+ elif 0 < n_components < 1.0:
653
+ # number of components for which the cumulated explained
654
+ # variance percentage is superior to the desired threshold
655
+ # side='right' ensures that number of features selected
656
+ # their variance is always greater than n_components float
657
+ # passed. More discussion in issue: #15669
658
+ if is_array_api_compliant:
659
+ # Convert to numpy as xp.cumsum and xp.searchsorted are not
660
+ # part of the Array API standard yet:
661
+ #
662
+ # https://github.com/data-apis/array-api/issues/597
663
+ # https://github.com/data-apis/array-api/issues/688
664
+ #
665
+ # Furthermore, it's not always safe to call them for namespaces
666
+ # that already implement them: for instance as
667
+ # cupy.searchsorted does not accept a float as second argument.
668
+ explained_variance_ratio_np = _convert_to_numpy(
669
+ explained_variance_ratio_, xp=xp
670
+ )
671
+ else:
672
+ explained_variance_ratio_np = explained_variance_ratio_
673
+ ratio_cumsum = stable_cumsum(explained_variance_ratio_np)
674
+ n_components = np.searchsorted(ratio_cumsum, n_components, side="right") + 1
675
+
676
+ # Compute noise covariance using Probabilistic PCA model
677
+ # The sigma2 maximum likelihood (cf. eq. 12.46)
678
+ if n_components < min(n_features, n_samples):
679
+ self.noise_variance_ = xp.mean(explained_variance_[n_components:])
680
+ else:
681
+ self.noise_variance_ = 0.0
682
+
683
+ self.n_samples_ = n_samples
684
+ self.n_components_ = n_components
685
+ # Assign a copy of the result of the truncation of the components in
686
+ # order to:
687
+ # - release the memory used by the discarded components,
688
+ # - ensure that the kept components are allocated contiguously in
689
+ # memory to make the transform method faster by leveraging cache
690
+ # locality.
691
+ self.components_ = xp.asarray(components_[:n_components, :], copy=True)
692
+
693
+ # We do the same for the other arrays for the sake of consistency.
694
+ self.explained_variance_ = xp.asarray(
695
+ explained_variance_[:n_components], copy=True
696
+ )
697
+ self.explained_variance_ratio_ = xp.asarray(
698
+ explained_variance_ratio_[:n_components], copy=True
699
+ )
700
+ self.singular_values_ = xp.asarray(singular_values_[:n_components], copy=True)
701
+
702
+ return U, S, Vt, X, x_is_centered, xp
703
+
704
+ def _fit_truncated(self, X, n_components, xp):
705
+ """Fit the model by computing truncated SVD (by ARPACK or randomized)
706
+ on X.
707
+ """
708
+ n_samples, n_features = X.shape
709
+
710
+ svd_solver = self._fit_svd_solver
711
+ if isinstance(n_components, str):
712
+ raise ValueError(
713
+ "n_components=%r cannot be a string with svd_solver='%s'"
714
+ % (n_components, svd_solver)
715
+ )
716
+ elif not 1 <= n_components <= min(n_samples, n_features):
717
+ raise ValueError(
718
+ "n_components=%r must be between 1 and "
719
+ "min(n_samples, n_features)=%r with "
720
+ "svd_solver='%s'"
721
+ % (n_components, min(n_samples, n_features), svd_solver)
722
+ )
723
+ elif svd_solver == "arpack" and n_components == min(n_samples, n_features):
724
+ raise ValueError(
725
+ "n_components=%r must be strictly less than "
726
+ "min(n_samples, n_features)=%r with "
727
+ "svd_solver='%s'"
728
+ % (n_components, min(n_samples, n_features), svd_solver)
729
+ )
730
+
731
+ random_state = check_random_state(self.random_state)
732
+
733
+ # Center data
734
+ total_var = None
735
+ if issparse(X):
736
+ self.mean_, var = mean_variance_axis(X, axis=0)
737
+ total_var = var.sum() * n_samples / (n_samples - 1) # ddof=1
738
+ X_centered = _implicit_column_offset(X, self.mean_)
739
+ x_is_centered = False
740
+ else:
741
+ self.mean_ = xp.mean(X, axis=0)
742
+ X_centered = xp.asarray(X, copy=True) if self.copy else X
743
+ X_centered -= self.mean_
744
+ x_is_centered = not self.copy
745
+
746
+ if svd_solver == "arpack":
747
+ v0 = _init_arpack_v0(min(X.shape), random_state)
748
+ U, S, Vt = svds(X_centered, k=n_components, tol=self.tol, v0=v0)
749
+ # svds doesn't abide by scipy.linalg.svd/randomized_svd
750
+ # conventions, so reverse its outputs.
751
+ S = S[::-1]
752
+ # flip eigenvectors' sign to enforce deterministic output
753
+ U, Vt = svd_flip(U[:, ::-1], Vt[::-1], u_based_decision=False)
754
+
755
+ elif svd_solver == "randomized":
756
+ # sign flipping is done inside
757
+ U, S, Vt = _randomized_svd(
758
+ X_centered,
759
+ n_components=n_components,
760
+ n_oversamples=self.n_oversamples,
761
+ n_iter=self.iterated_power,
762
+ power_iteration_normalizer=self.power_iteration_normalizer,
763
+ flip_sign=False,
764
+ random_state=random_state,
765
+ )
766
+ U, Vt = svd_flip(U, Vt, u_based_decision=False)
767
+
768
+ self.n_samples_ = n_samples
769
+ self.components_ = Vt
770
+ self.n_components_ = n_components
771
+
772
+ # Get variance explained by singular values
773
+ self.explained_variance_ = (S**2) / (n_samples - 1)
774
+
775
+ # Workaround in-place variance calculation since at the time numpy
776
+ # did not have a way to calculate variance in-place.
777
+ #
778
+ # TODO: update this code to either:
779
+ # * Use the array-api variance calculation, unless memory usage suffers
780
+ # * Update sklearn.utils.extmath._incremental_mean_and_var to support array-api
781
+ # See: https://github.com/scikit-learn/scikit-learn/pull/18689#discussion_r1335540991
782
+ if total_var is None:
783
+ N = X.shape[0] - 1
784
+ X_centered **= 2
785
+ total_var = xp.sum(X_centered) / N
786
+
787
+ self.explained_variance_ratio_ = self.explained_variance_ / total_var
788
+ self.singular_values_ = xp.asarray(S, copy=True) # Store the singular values.
789
+
790
+ if self.n_components_ < min(n_features, n_samples):
791
+ self.noise_variance_ = total_var - xp.sum(self.explained_variance_)
792
+ self.noise_variance_ /= min(n_features, n_samples) - n_components
793
+ else:
794
+ self.noise_variance_ = 0.0
795
+
796
+ return U, S, Vt, X, x_is_centered, xp
797
+
798
+ def score_samples(self, X):
799
+ """Return the log-likelihood of each sample.
800
+
801
+ See. "Pattern Recognition and Machine Learning"
802
+ by C. Bishop, 12.2.1 p. 574
803
+ or http://www.miketipping.com/papers/met-mppca.pdf
804
+
805
+ Parameters
806
+ ----------
807
+ X : array-like of shape (n_samples, n_features)
808
+ The data.
809
+
810
+ Returns
811
+ -------
812
+ ll : ndarray of shape (n_samples,)
813
+ Log-likelihood of each sample under the current model.
814
+ """
815
+ check_is_fitted(self)
816
+ xp, _ = get_namespace(X)
817
+ X = validate_data(self, X, dtype=[xp.float64, xp.float32], reset=False)
818
+ Xr = X - self.mean_
819
+ n_features = X.shape[1]
820
+ precision = self.get_precision()
821
+ log_like = -0.5 * xp.sum(Xr * (Xr @ precision), axis=1)
822
+ log_like -= 0.5 * (n_features * log(2.0 * np.pi) - fast_logdet(precision))
823
+ return log_like
824
+
825
+ def score(self, X, y=None):
826
+ """Return the average log-likelihood of all samples.
827
+
828
+ See. "Pattern Recognition and Machine Learning"
829
+ by C. Bishop, 12.2.1 p. 574
830
+ or http://www.miketipping.com/papers/met-mppca.pdf
831
+
832
+ Parameters
833
+ ----------
834
+ X : array-like of shape (n_samples, n_features)
835
+ The data.
836
+
837
+ y : Ignored
838
+ Ignored.
839
+
840
+ Returns
841
+ -------
842
+ ll : float
843
+ Average log-likelihood of the samples under the current model.
844
+ """
845
+ xp, _ = get_namespace(X)
846
+ return float(xp.mean(self.score_samples(X)))
847
+
848
+ def __sklearn_tags__(self):
849
+ tags = super().__sklearn_tags__()
850
+ tags.transformer_tags.preserves_dtype = ["float64", "float32"]
851
+ tags.array_api_support = True
852
+ tags.input_tags.sparse = self.svd_solver in (
853
+ "auto",
854
+ "arpack",
855
+ "covariance_eigh",
856
+ )
857
+ return tags
shared/package-files/56/563bae0d769e16d7de0c6d77333e35c68f398272b7223c3890bbdfadbc2d0d76/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:563bae0d769e16d7de0c6d77333e35c68f398272b7223c3890bbdfadbc2d0d76
3
+ size 912912
shared/package-files/56/563cf6e58e87fe2874884136006d246b13bd53c3f07174aba1fcea9cde170702/blob ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import numpy as np
4
+ from numpy.testing import (
5
+ assert_, assert_equal, assert_array_equal, assert_almost_equal,
6
+ assert_array_almost_equal, assert_raises, assert_raises_regex,
7
+ )
8
+ from numpy.lib.index_tricks import (
9
+ mgrid, ogrid, ndenumerate, fill_diagonal, diag_indices, diag_indices_from,
10
+ index_exp, ndindex, r_, s_, ix_
11
+ )
12
+
13
+
14
+ class TestRavelUnravelIndex:
15
+ def test_basic(self):
16
+ assert_equal(np.unravel_index(2, (2, 2)), (1, 0))
17
+
18
+ # test that new shape argument works properly
19
+ assert_equal(np.unravel_index(indices=2,
20
+ shape=(2, 2)),
21
+ (1, 0))
22
+
23
+ # test that an invalid second keyword argument
24
+ # is properly handled, including the old name `dims`.
25
+ with assert_raises(TypeError):
26
+ np.unravel_index(indices=2, hape=(2, 2))
27
+
28
+ with assert_raises(TypeError):
29
+ np.unravel_index(2, hape=(2, 2))
30
+
31
+ with assert_raises(TypeError):
32
+ np.unravel_index(254, ims=(17, 94))
33
+
34
+ with assert_raises(TypeError):
35
+ np.unravel_index(254, dims=(17, 94))
36
+
37
+ assert_equal(np.ravel_multi_index((1, 0), (2, 2)), 2)
38
+ assert_equal(np.unravel_index(254, (17, 94)), (2, 66))
39
+ assert_equal(np.ravel_multi_index((2, 66), (17, 94)), 254)
40
+ assert_raises(ValueError, np.unravel_index, -1, (2, 2))
41
+ assert_raises(TypeError, np.unravel_index, 0.5, (2, 2))
42
+ assert_raises(ValueError, np.unravel_index, 4, (2, 2))
43
+ assert_raises(ValueError, np.ravel_multi_index, (-3, 1), (2, 2))
44
+ assert_raises(ValueError, np.ravel_multi_index, (2, 1), (2, 2))
45
+ assert_raises(ValueError, np.ravel_multi_index, (0, -3), (2, 2))
46
+ assert_raises(ValueError, np.ravel_multi_index, (0, 2), (2, 2))
47
+ assert_raises(TypeError, np.ravel_multi_index, (0.1, 0.), (2, 2))
48
+
49
+ assert_equal(np.unravel_index((2*3 + 1)*6 + 4, (4, 3, 6)), [2, 1, 4])
50
+ assert_equal(
51
+ np.ravel_multi_index([2, 1, 4], (4, 3, 6)), (2*3 + 1)*6 + 4)
52
+
53
+ arr = np.array([[3, 6, 6], [4, 5, 1]])
54
+ assert_equal(np.ravel_multi_index(arr, (7, 6)), [22, 41, 37])
55
+ assert_equal(
56
+ np.ravel_multi_index(arr, (7, 6), order='F'), [31, 41, 13])
57
+ assert_equal(
58
+ np.ravel_multi_index(arr, (4, 6), mode='clip'), [22, 23, 19])
59
+ assert_equal(np.ravel_multi_index(arr, (4, 4), mode=('clip', 'wrap')),
60
+ [12, 13, 13])
61
+ assert_equal(np.ravel_multi_index((3, 1, 4, 1), (6, 7, 8, 9)), 1621)
62
+
63
+ assert_equal(np.unravel_index(np.array([22, 41, 37]), (7, 6)),
64
+ [[3, 6, 6], [4, 5, 1]])
65
+ assert_equal(
66
+ np.unravel_index(np.array([31, 41, 13]), (7, 6), order='F'),
67
+ [[3, 6, 6], [4, 5, 1]])
68
+ assert_equal(np.unravel_index(1621, (6, 7, 8, 9)), [3, 1, 4, 1])
69
+
70
+ def test_empty_indices(self):
71
+ msg1 = 'indices must be integral: the provided empty sequence was'
72
+ msg2 = 'only int indices permitted'
73
+ assert_raises_regex(TypeError, msg1, np.unravel_index, [], (10, 3, 5))
74
+ assert_raises_regex(TypeError, msg1, np.unravel_index, (), (10, 3, 5))
75
+ assert_raises_regex(TypeError, msg2, np.unravel_index, np.array([]),
76
+ (10, 3, 5))
77
+ assert_equal(np.unravel_index(np.array([],dtype=int), (10, 3, 5)),
78
+ [[], [], []])
79
+ assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], []),
80
+ (10, 3))
81
+ assert_raises_regex(TypeError, msg1, np.ravel_multi_index, ([], ['abc']),
82
+ (10, 3))
83
+ assert_raises_regex(TypeError, msg2, np.ravel_multi_index,
84
+ (np.array([]), np.array([])), (5, 3))
85
+ assert_equal(np.ravel_multi_index(
86
+ (np.array([], dtype=int), np.array([], dtype=int)), (5, 3)), [])
87
+ assert_equal(np.ravel_multi_index(np.array([[], []], dtype=int),
88
+ (5, 3)), [])
89
+
90
+ def test_big_indices(self):
91
+ # ravel_multi_index for big indices (issue #7546)
92
+ if np.intp == np.int64:
93
+ arr = ([1, 29], [3, 5], [3, 117], [19, 2],
94
+ [2379, 1284], [2, 2], [0, 1])
95
+ assert_equal(
96
+ np.ravel_multi_index(arr, (41, 7, 120, 36, 2706, 8, 6)),
97
+ [5627771580, 117259570957])
98
+
99
+ # test unravel_index for big indices (issue #9538)
100
+ assert_raises(ValueError, np.unravel_index, 1, (2**32-1, 2**31+1))
101
+
102
+ # test overflow checking for too big array (issue #7546)
103
+ dummy_arr = ([0],[0])
104
+ half_max = np.iinfo(np.intp).max // 2
105
+ assert_equal(
106
+ np.ravel_multi_index(dummy_arr, (half_max, 2)), [0])
107
+ assert_raises(ValueError,
108
+ np.ravel_multi_index, dummy_arr, (half_max+1, 2))
109
+ assert_equal(
110
+ np.ravel_multi_index(dummy_arr, (half_max, 2), order='F'), [0])
111
+ assert_raises(ValueError,
112
+ np.ravel_multi_index, dummy_arr, (half_max+1, 2), order='F')
113
+
114
+ def test_dtypes(self):
115
+ # Test with different data types
116
+ for dtype in [np.int16, np.uint16, np.int32,
117
+ np.uint32, np.int64, np.uint64]:
118
+ coords = np.array(
119
+ [[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0]], dtype=dtype)
120
+ shape = (5, 8)
121
+ uncoords = 8*coords[0]+coords[1]
122
+ assert_equal(np.ravel_multi_index(coords, shape), uncoords)
123
+ assert_equal(coords, np.unravel_index(uncoords, shape))
124
+ uncoords = coords[0]+5*coords[1]
125
+ assert_equal(
126
+ np.ravel_multi_index(coords, shape, order='F'), uncoords)
127
+ assert_equal(coords, np.unravel_index(uncoords, shape, order='F'))
128
+
129
+ coords = np.array(
130
+ [[1, 0, 1, 2, 3, 4], [1, 6, 1, 3, 2, 0], [1, 3, 1, 0, 9, 5]],
131
+ dtype=dtype)
132
+ shape = (5, 8, 10)
133
+ uncoords = 10*(8*coords[0]+coords[1])+coords[2]
134
+ assert_equal(np.ravel_multi_index(coords, shape), uncoords)
135
+ assert_equal(coords, np.unravel_index(uncoords, shape))
136
+ uncoords = coords[0]+5*(coords[1]+8*coords[2])
137
+ assert_equal(
138
+ np.ravel_multi_index(coords, shape, order='F'), uncoords)
139
+ assert_equal(coords, np.unravel_index(uncoords, shape, order='F'))
140
+
141
+ def test_clipmodes(self):
142
+ # Test clipmodes
143
+ assert_equal(
144
+ np.ravel_multi_index([5, 1, -1, 2], (4, 3, 7, 12), mode='wrap'),
145
+ np.ravel_multi_index([1, 1, 6, 2], (4, 3, 7, 12)))
146
+ assert_equal(np.ravel_multi_index([5, 1, -1, 2], (4, 3, 7, 12),
147
+ mode=(
148
+ 'wrap', 'raise', 'clip', 'raise')),
149
+ np.ravel_multi_index([1, 1, 0, 2], (4, 3, 7, 12)))
150
+ assert_raises(
151
+ ValueError, np.ravel_multi_index, [5, 1, -1, 2], (4, 3, 7, 12))
152
+
153
+ def test_writeability(self):
154
+ # See gh-7269
155
+ x, y = np.unravel_index([1, 2, 3], (4, 5))
156
+ assert_(x.flags.writeable)
157
+ assert_(y.flags.writeable)
158
+
159
+ def test_0d(self):
160
+ # gh-580
161
+ x = np.unravel_index(0, ())
162
+ assert_equal(x, ())
163
+
164
+ assert_raises_regex(ValueError, "0d array", np.unravel_index, [0], ())
165
+ assert_raises_regex(
166
+ ValueError, "out of bounds", np.unravel_index, [1], ())
167
+
168
+ @pytest.mark.parametrize("mode", ["clip", "wrap", "raise"])
169
+ def test_empty_array_ravel(self, mode):
170
+ res = np.ravel_multi_index(
171
+ np.zeros((3, 0), dtype=np.intp), (2, 1, 0), mode=mode)
172
+ assert(res.shape == (0,))
173
+
174
+ with assert_raises(ValueError):
175
+ np.ravel_multi_index(
176
+ np.zeros((3, 1), dtype=np.intp), (2, 1, 0), mode=mode)
177
+
178
+ def test_empty_array_unravel(self):
179
+ res = np.unravel_index(np.zeros(0, dtype=np.intp), (2, 1, 0))
180
+ # res is a tuple of three empty arrays
181
+ assert(len(res) == 3)
182
+ assert(all(a.shape == (0,) for a in res))
183
+
184
+ with assert_raises(ValueError):
185
+ np.unravel_index([1], (2, 1, 0))
186
+
187
+ class TestGrid:
188
+ def test_basic(self):
189
+ a = mgrid[-1:1:10j]
190
+ b = mgrid[-1:1:0.1]
191
+ assert_(a.shape == (10,))
192
+ assert_(b.shape == (20,))
193
+ assert_(a[0] == -1)
194
+ assert_almost_equal(a[-1], 1)
195
+ assert_(b[0] == -1)
196
+ assert_almost_equal(b[1]-b[0], 0.1, 11)
197
+ assert_almost_equal(b[-1], b[0]+19*0.1, 11)
198
+ assert_almost_equal(a[1]-a[0], 2.0/9.0, 11)
199
+
200
+ def test_linspace_equivalence(self):
201
+ y, st = np.linspace(2, 10, retstep=True)
202
+ assert_almost_equal(st, 8/49.0)
203
+ assert_array_almost_equal(y, mgrid[2:10:50j], 13)
204
+
205
+ def test_nd(self):
206
+ c = mgrid[-1:1:10j, -2:2:10j]
207
+ d = mgrid[-1:1:0.1, -2:2:0.2]
208
+ assert_(c.shape == (2, 10, 10))
209
+ assert_(d.shape == (2, 20, 20))
210
+ assert_array_equal(c[0][0, :], -np.ones(10, 'd'))
211
+ assert_array_equal(c[1][:, 0], -2*np.ones(10, 'd'))
212
+ assert_array_almost_equal(c[0][-1, :], np.ones(10, 'd'), 11)
213
+ assert_array_almost_equal(c[1][:, -1], 2*np.ones(10, 'd'), 11)
214
+ assert_array_almost_equal(d[0, 1, :] - d[0, 0, :],
215
+ 0.1*np.ones(20, 'd'), 11)
216
+ assert_array_almost_equal(d[1, :, 1] - d[1, :, 0],
217
+ 0.2*np.ones(20, 'd'), 11)
218
+
219
+ def test_sparse(self):
220
+ grid_full = mgrid[-1:1:10j, -2:2:10j]
221
+ grid_sparse = ogrid[-1:1:10j, -2:2:10j]
222
+
223
+ # sparse grids can be made dense by broadcasting
224
+ grid_broadcast = np.broadcast_arrays(*grid_sparse)
225
+ for f, b in zip(grid_full, grid_broadcast):
226
+ assert_equal(f, b)
227
+
228
+ @pytest.mark.parametrize("start, stop, step, expected", [
229
+ (None, 10, 10j, (200, 10)),
230
+ (-10, 20, None, (1800, 30)),
231
+ ])
232
+ def test_mgrid_size_none_handling(self, start, stop, step, expected):
233
+ # regression test None value handling for
234
+ # start and step values used by mgrid;
235
+ # internally, this aims to cover previously
236
+ # unexplored code paths in nd_grid()
237
+ grid = mgrid[start:stop:step, start:stop:step]
238
+ # need a smaller grid to explore one of the
239
+ # untested code paths
240
+ grid_small = mgrid[start:stop:step]
241
+ assert_equal(grid.size, expected[0])
242
+ assert_equal(grid_small.size, expected[1])
243
+
244
+ def test_accepts_npfloating(self):
245
+ # regression test for #16466
246
+ grid64 = mgrid[0.1:0.33:0.1, ]
247
+ grid32 = mgrid[np.float32(0.1):np.float32(0.33):np.float32(0.1), ]
248
+ assert_(grid32.dtype == np.float64)
249
+ assert_array_almost_equal(grid64, grid32)
250
+
251
+ # different code path for single slice
252
+ grid64 = mgrid[0.1:0.33:0.1]
253
+ grid32 = mgrid[np.float32(0.1):np.float32(0.33):np.float32(0.1)]
254
+ assert_(grid32.dtype == np.float64)
255
+ assert_array_almost_equal(grid64, grid32)
256
+
257
+ def test_accepts_longdouble(self):
258
+ # regression tests for #16945
259
+ grid64 = mgrid[0.1:0.33:0.1, ]
260
+ grid128 = mgrid[
261
+ np.longdouble(0.1):np.longdouble(0.33):np.longdouble(0.1),
262
+ ]
263
+ assert_(grid128.dtype == np.longdouble)
264
+ assert_array_almost_equal(grid64, grid128)
265
+
266
+ grid128c_a = mgrid[0:np.longdouble(1):3.4j]
267
+ grid128c_b = mgrid[0:np.longdouble(1):3.4j, ]
268
+ assert_(grid128c_a.dtype == grid128c_b.dtype == np.longdouble)
269
+ assert_array_equal(grid128c_a, grid128c_b[0])
270
+
271
+ # different code path for single slice
272
+ grid64 = mgrid[0.1:0.33:0.1]
273
+ grid128 = mgrid[
274
+ np.longdouble(0.1):np.longdouble(0.33):np.longdouble(0.1)
275
+ ]
276
+ assert_(grid128.dtype == np.longdouble)
277
+ assert_array_almost_equal(grid64, grid128)
278
+
279
+ def test_accepts_npcomplexfloating(self):
280
+ # Related to #16466
281
+ assert_array_almost_equal(
282
+ mgrid[0.1:0.3:3j, ], mgrid[0.1:0.3:np.complex64(3j), ]
283
+ )
284
+
285
+ # different code path for single slice
286
+ assert_array_almost_equal(
287
+ mgrid[0.1:0.3:3j], mgrid[0.1:0.3:np.complex64(3j)]
288
+ )
289
+
290
+ # Related to #16945
291
+ grid64_a = mgrid[0.1:0.3:3.3j]
292
+ grid64_b = mgrid[0.1:0.3:3.3j, ][0]
293
+ assert_(grid64_a.dtype == grid64_b.dtype == np.float64)
294
+ assert_array_equal(grid64_a, grid64_b)
295
+
296
+ grid128_a = mgrid[0.1:0.3:np.clongdouble(3.3j)]
297
+ grid128_b = mgrid[0.1:0.3:np.clongdouble(3.3j), ][0]
298
+ assert_(grid128_a.dtype == grid128_b.dtype == np.longdouble)
299
+ assert_array_equal(grid64_a, grid64_b)
300
+
301
+
302
+ class TestConcatenator:
303
+ def test_1d(self):
304
+ assert_array_equal(r_[1, 2, 3, 4, 5, 6], np.array([1, 2, 3, 4, 5, 6]))
305
+ b = np.ones(5)
306
+ c = r_[b, 0, 0, b]
307
+ assert_array_equal(c, [1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1])
308
+
309
+ def test_mixed_type(self):
310
+ g = r_[10.1, 1:10]
311
+ assert_(g.dtype == 'f8')
312
+
313
+ def test_more_mixed_type(self):
314
+ g = r_[-10.1, np.array([1]), np.array([2, 3, 4]), 10.0]
315
+ assert_(g.dtype == 'f8')
316
+
317
+ def test_complex_step(self):
318
+ # Regression test for #12262
319
+ g = r_[0:36:100j]
320
+ assert_(g.shape == (100,))
321
+
322
+ # Related to #16466
323
+ g = r_[0:36:np.complex64(100j)]
324
+ assert_(g.shape == (100,))
325
+
326
+ def test_2d(self):
327
+ b = np.random.rand(5, 5)
328
+ c = np.random.rand(5, 5)
329
+ d = r_['1', b, c] # append columns
330
+ assert_(d.shape == (5, 10))
331
+ assert_array_equal(d[:, :5], b)
332
+ assert_array_equal(d[:, 5:], c)
333
+ d = r_[b, c]
334
+ assert_(d.shape == (10, 5))
335
+ assert_array_equal(d[:5, :], b)
336
+ assert_array_equal(d[5:, :], c)
337
+
338
+ def test_0d(self):
339
+ assert_equal(r_[0, np.array(1), 2], [0, 1, 2])
340
+ assert_equal(r_[[0, 1, 2], np.array(3)], [0, 1, 2, 3])
341
+ assert_equal(r_[np.array(0), [1, 2, 3]], [0, 1, 2, 3])
342
+
343
+
344
+ class TestNdenumerate:
345
+ def test_basic(self):
346
+ a = np.array([[1, 2], [3, 4]])
347
+ assert_equal(list(ndenumerate(a)),
348
+ [((0, 0), 1), ((0, 1), 2), ((1, 0), 3), ((1, 1), 4)])
349
+
350
+
351
+ class TestIndexExpression:
352
+ def test_regression_1(self):
353
+ # ticket #1196
354
+ a = np.arange(2)
355
+ assert_equal(a[:-1], a[s_[:-1]])
356
+ assert_equal(a[:-1], a[index_exp[:-1]])
357
+
358
+ def test_simple_1(self):
359
+ a = np.random.rand(4, 5, 6)
360
+
361
+ assert_equal(a[:, :3, [1, 2]], a[index_exp[:, :3, [1, 2]]])
362
+ assert_equal(a[:, :3, [1, 2]], a[s_[:, :3, [1, 2]]])
363
+
364
+
365
+ class TestIx_:
366
+ def test_regression_1(self):
367
+ # Test empty untyped inputs create outputs of indexing type, gh-5804
368
+ a, = np.ix_(range(0))
369
+ assert_equal(a.dtype, np.intp)
370
+
371
+ a, = np.ix_([])
372
+ assert_equal(a.dtype, np.intp)
373
+
374
+ # but if the type is specified, don't change it
375
+ a, = np.ix_(np.array([], dtype=np.float32))
376
+ assert_equal(a.dtype, np.float32)
377
+
378
+ def test_shape_and_dtype(self):
379
+ sizes = (4, 5, 3, 2)
380
+ # Test both lists and arrays
381
+ for func in (range, np.arange):
382
+ arrays = np.ix_(*[func(sz) for sz in sizes])
383
+ for k, (a, sz) in enumerate(zip(arrays, sizes)):
384
+ assert_equal(a.shape[k], sz)
385
+ assert_(all(sh == 1 for j, sh in enumerate(a.shape) if j != k))
386
+ assert_(np.issubdtype(a.dtype, np.integer))
387
+
388
+ def test_bool(self):
389
+ bool_a = [True, False, True, True]
390
+ int_a, = np.nonzero(bool_a)
391
+ assert_equal(np.ix_(bool_a)[0], int_a)
392
+
393
+ def test_1d_only(self):
394
+ idx2d = [[1, 2, 3], [4, 5, 6]]
395
+ assert_raises(ValueError, np.ix_, idx2d)
396
+
397
+ def test_repeated_input(self):
398
+ length_of_vector = 5
399
+ x = np.arange(length_of_vector)
400
+ out = ix_(x, x)
401
+ assert_equal(out[0].shape, (length_of_vector, 1))
402
+ assert_equal(out[1].shape, (1, length_of_vector))
403
+ # check that input shape is not modified
404
+ assert_equal(x.shape, (length_of_vector,))
405
+
406
+
407
+ def test_c_():
408
+ a = np.c_[np.array([[1, 2, 3]]), 0, 0, np.array([[4, 5, 6]])]
409
+ assert_equal(a, [[1, 2, 3, 0, 0, 4, 5, 6]])
410
+
411
+
412
+ class TestFillDiagonal:
413
+ def test_basic(self):
414
+ a = np.zeros((3, 3), int)
415
+ fill_diagonal(a, 5)
416
+ assert_array_equal(
417
+ a, np.array([[5, 0, 0],
418
+ [0, 5, 0],
419
+ [0, 0, 5]])
420
+ )
421
+
422
+ def test_tall_matrix(self):
423
+ a = np.zeros((10, 3), int)
424
+ fill_diagonal(a, 5)
425
+ assert_array_equal(
426
+ a, np.array([[5, 0, 0],
427
+ [0, 5, 0],
428
+ [0, 0, 5],
429
+ [0, 0, 0],
430
+ [0, 0, 0],
431
+ [0, 0, 0],
432
+ [0, 0, 0],
433
+ [0, 0, 0],
434
+ [0, 0, 0],
435
+ [0, 0, 0]])
436
+ )
437
+
438
+ def test_tall_matrix_wrap(self):
439
+ a = np.zeros((10, 3), int)
440
+ fill_diagonal(a, 5, True)
441
+ assert_array_equal(
442
+ a, np.array([[5, 0, 0],
443
+ [0, 5, 0],
444
+ [0, 0, 5],
445
+ [0, 0, 0],
446
+ [5, 0, 0],
447
+ [0, 5, 0],
448
+ [0, 0, 5],
449
+ [0, 0, 0],
450
+ [5, 0, 0],
451
+ [0, 5, 0]])
452
+ )
453
+
454
+ def test_wide_matrix(self):
455
+ a = np.zeros((3, 10), int)
456
+ fill_diagonal(a, 5)
457
+ assert_array_equal(
458
+ a, np.array([[5, 0, 0, 0, 0, 0, 0, 0, 0, 0],
459
+ [0, 5, 0, 0, 0, 0, 0, 0, 0, 0],
460
+ [0, 0, 5, 0, 0, 0, 0, 0, 0, 0]])
461
+ )
462
+
463
+ def test_operate_4d_array(self):
464
+ a = np.zeros((3, 3, 3, 3), int)
465
+ fill_diagonal(a, 4)
466
+ i = np.array([0, 1, 2])
467
+ assert_equal(np.where(a != 0), (i, i, i, i))
468
+
469
+ def test_low_dim_handling(self):
470
+ # raise error with low dimensionality
471
+ a = np.zeros(3, int)
472
+ with assert_raises_regex(ValueError, "at least 2-d"):
473
+ fill_diagonal(a, 5)
474
+
475
+ def test_hetero_shape_handling(self):
476
+ # raise error with high dimensionality and
477
+ # shape mismatch
478
+ a = np.zeros((3,3,7,3), int)
479
+ with assert_raises_regex(ValueError, "equal length"):
480
+ fill_diagonal(a, 2)
481
+
482
+
483
+ def test_diag_indices():
484
+ di = diag_indices(4)
485
+ a = np.array([[1, 2, 3, 4],
486
+ [5, 6, 7, 8],
487
+ [9, 10, 11, 12],
488
+ [13, 14, 15, 16]])
489
+ a[di] = 100
490
+ assert_array_equal(
491
+ a, np.array([[100, 2, 3, 4],
492
+ [5, 100, 7, 8],
493
+ [9, 10, 100, 12],
494
+ [13, 14, 15, 100]])
495
+ )
496
+
497
+ # Now, we create indices to manipulate a 3-d array:
498
+ d3 = diag_indices(2, 3)
499
+
500
+ # And use it to set the diagonal of a zeros array to 1:
501
+ a = np.zeros((2, 2, 2), int)
502
+ a[d3] = 1
503
+ assert_array_equal(
504
+ a, np.array([[[1, 0],
505
+ [0, 0]],
506
+ [[0, 0],
507
+ [0, 1]]])
508
+ )
509
+
510
+
511
+ class TestDiagIndicesFrom:
512
+
513
+ def test_diag_indices_from(self):
514
+ x = np.random.random((4, 4))
515
+ r, c = diag_indices_from(x)
516
+ assert_array_equal(r, np.arange(4))
517
+ assert_array_equal(c, np.arange(4))
518
+
519
+ def test_error_small_input(self):
520
+ x = np.ones(7)
521
+ with assert_raises_regex(ValueError, "at least 2-d"):
522
+ diag_indices_from(x)
523
+
524
+ def test_error_shape_mismatch(self):
525
+ x = np.zeros((3, 3, 2, 3), int)
526
+ with assert_raises_regex(ValueError, "equal length"):
527
+ diag_indices_from(x)
528
+
529
+
530
+ def test_ndindex():
531
+ x = list(ndindex(1, 2, 3))
532
+ expected = [ix for ix, e in ndenumerate(np.zeros((1, 2, 3)))]
533
+ assert_array_equal(x, expected)
534
+
535
+ x = list(ndindex((1, 2, 3)))
536
+ assert_array_equal(x, expected)
537
+
538
+ # Test use of scalars and tuples
539
+ x = list(ndindex((3,)))
540
+ assert_array_equal(x, list(ndindex(3)))
541
+
542
+ # Make sure size argument is optional
543
+ x = list(ndindex())
544
+ assert_equal(x, [()])
545
+
546
+ x = list(ndindex(()))
547
+ assert_equal(x, [()])
548
+
549
+ # Make sure 0-sized ndindex works correctly
550
+ x = list(ndindex(*[0]))
551
+ assert_equal(x, [])
shared/package-files/56/563dcf55580ef635d85c2c376da6f3269d00624d3d914e0cde871258b0929f8b/blob ADDED
@@ -0,0 +1,1297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from statsmodels.tools.tools import Bunch
4
+
5
+ llf = np.array([-242.89663276735])
6
+
7
+ nobs = np.array([202])
8
+
9
+ k = np.array([3])
10
+
11
+ k_exog = np.array([1])
12
+
13
+ sigma = np.array([.8053519404535])
14
+
15
+ chi2 = np.array([15723.381396967])
16
+
17
+ df_model = np.array([2])
18
+
19
+ k_ar = np.array([1])
20
+
21
+ k_ma = np.array([1])
22
+
23
+ params = np.array([
24
+ .99479180506163,
25
+ -.84461527652809,
26
+ .64859174799221])
27
+
28
+ cov_params = np.array([
29
+ .00008904968254,
30
+ -.00023560410507,
31
+ .00012795903324,
32
+ -.00023560410507,
33
+ .00131628534915,
34
+ -.00022462340695,
35
+ .00012795903324,
36
+ -.00022462340695,
37
+ .0005651128627]).reshape(3, 3)
38
+
39
+ xb = np.array([
40
+ 0,
41
+ 0,
42
+ .02869686298072,
43
+ .05651443824172,
44
+ .0503994859755,
45
+ .06887971609831,
46
+ .05940540507436,
47
+ .08067328482866,
48
+ .08167565613985,
49
+ .06429278105497,
50
+ .07087650150061,
51
+ .06886467337608,
52
+ .06716959923506,
53
+ .08230647444725,
54
+ .07099691033363,
55
+ .08401278406382,
56
+ .07996553182602,
57
+ .07354256510735,
58
+ .09366323798895,
59
+ .08811800926924,
60
+ .10296355187893,
61
+ .08846370875835,
62
+ .0852297320962,
63
+ .08700425922871,
64
+ .09751411527395,
65
+ .09737934917212,
66
+ .11228405684233,
67
+ .1053489819169,
68
+ .12352022528648,
69
+ .16439816355705,
70
+ .1643835157156,
71
+ .19891132414341,
72
+ .17551273107529,
73
+ .17827558517456,
74
+ .19562774896622,
75
+ .21028305590153,
76
+ .23767858743668,
77
+ .24580039083958,
78
+ .28269505500793,
79
+ .29883882403374,
80
+ .31247469782829,
81
+ .35402658581734,
82
+ .37410452961922,
83
+ .39106267690659,
84
+ .42040377855301,
85
+ .44518512487411,
86
+ .43608102202415,
87
+ .44340893626213,
88
+ .44959822297096,
89
+ .40977239608765,
90
+ .42118826508522,
91
+ .40079545974731,
92
+ .38357082009315,
93
+ .36902260780334,
94
+ .35673499107361,
95
+ .36137464642525,
96
+ .38031083345413,
97
+ .47139286994934,
98
+ .47323387861252,
99
+ .60994738340378,
100
+ .69538277387619,
101
+ .7825602889061,
102
+ .84117436408997,
103
+ .9657689332962,
104
+ 1.0109325647354,
105
+ .95897275209427,
106
+ .96013957262039,
107
+ .9461076259613,
108
+ .9342554807663,
109
+ .83413934707642,
110
+ .83968591690063,
111
+ .84437066316605,
112
+ .83330947160721,
113
+ .8990553021431,
114
+ .87949693202972,
115
+ .86297762393951,
116
+ .89407861232758,
117
+ .93536442518234,
118
+ 1.0303052663803,
119
+ 1.1104937791824,
120
+ 1.1481873989105,
121
+ 1.2851470708847,
122
+ 1.4458787441254,
123
+ 1.5515991449356,
124
+ 1.7309991121292,
125
+ 1.8975404500961,
126
+ 1.8579913377762,
127
+ 1.8846583366394,
128
+ 1.9672524929047,
129
+ 1.9469071626663,
130
+ 2.0048115253448,
131
+ 1.9786299467087,
132
+ 1.8213576078415,
133
+ 1.6284521818161,
134
+ 1.7508568763733,
135
+ 1.5689061880112,
136
+ 1.2950873374939,
137
+ 1.2290096282959,
138
+ 1.1882168054581,
139
+ 1.1537625789642,
140
+ 1.1697143316269,
141
+ 1.1681711673737,
142
+ 1.106795668602,
143
+ 1.0849931240082,
144
+ 1.006507396698,
145
+ 1.0453414916992,
146
+ .98803448677063,
147
+ .95465070009232,
148
+ 1.0165599584579,
149
+ .67838954925537,
150
+ .69311982393265,
151
+ .69054269790649,
152
+ .76345545053482,
153
+ .84005492925644,
154
+ .87471830844879,
155
+ .91901183128357,
156
+ .92638796567917,
157
+ .96265280246735,
158
+ 1.0083012580872,
159
+ 1.0618740320206,
160
+ 1.0921038389206,
161
+ 1.2077431678772,
162
+ 1.2303256988525,
163
+ 1.174311041832,
164
+ 1.3072115182877,
165
+ 1.314337015152,
166
+ 1.3503924608231,
167
+ 1.5760731697083,
168
+ 1.5264053344727,
169
+ 1.34929728508,
170
+ 1.304829955101,
171
+ 1.2522557973862,
172
+ 1.222869515419,
173
+ 1.198047041893,
174
+ 1.1770839691162,
175
+ 1.1743944883347,
176
+ 1.1571066379547,
177
+ 1.1274864673615,
178
+ 1.0574153661728,
179
+ 1.058304309845,
180
+ .99898308515549,
181
+ .9789143204689,
182
+ 1.0070173740387,
183
+ 1.000718832016,
184
+ 1.0104174613953,
185
+ 1.0486439466476,
186
+ 1.0058424472809,
187
+ .98470783233643,
188
+ 1.0119106769562,
189
+ 1.0649236440659,
190
+ 1.0346088409424,
191
+ 1.0540577173233,
192
+ 1.0704846382141,
193
+ .97923594713211,
194
+ .90216588973999,
195
+ .9271782040596,
196
+ .85819715261459,
197
+ .75488126277924,
198
+ .78776079416275,
199
+ .77047789096832,
200
+ .77089905738831,
201
+ .8313245177269,
202
+ .82229107618332,
203
+ .90476810932159,
204
+ .94439232349396,
205
+ 1.0379292964935,
206
+ 1.1469690799713,
207
+ 1.1489590406418,
208
+ 1.2257302999496,
209
+ 1.1554099321365,
210
+ 1.1260533332825,
211
+ .9811190366745,
212
+ .8436843752861,
213
+ .95287209749222,
214
+ .90993344783783,
215
+ .94875508546829,
216
+ 1.0115815401077,
217
+ .94450175762177,
218
+ .87282890081406,
219
+ .91741597652435,
220
+ .98511207103729,
221
+ .9972335100174,
222
+ 1.0975805521011,
223
+ 1.1823329925537,
224
+ 1.1487929821014,
225
+ 1.270641207695,
226
+ 1.2083609104156,
227
+ 1.696394443512,
228
+ 1.4628355503082,
229
+ 1.4307631254196,
230
+ 1.5087975263596,
231
+ 1.1542117595673,
232
+ 1.2262620925903,
233
+ 1.3880327939987,
234
+ 1.3853038549423,
235
+ 1.4396153688431,
236
+ 1.7208145856857,
237
+ 1.678991317749,
238
+ 2.110867023468,
239
+ 1.524417757988,
240
+ .57946246862411,
241
+ .56406193971634,
242
+ .74643105268478])
243
+
244
+ y = np.array([
245
+ np.nan,
246
+ 28.979999542236,
247
+ 29.178695678711,
248
+ 29.40651512146,
249
+ 29.420400619507,
250
+ 29.608880996704,
251
+ 29.609405517578,
252
+ 29.830673217773,
253
+ 29.921676635742,
254
+ 29.874292373657,
255
+ 29.990877151489,
256
+ 30.048864364624,
257
+ 30.10717010498,
258
+ 30.292304992676,
259
+ 30.290996551514,
260
+ 30.464012145996,
261
+ 30.519966125488,
262
+ 30.553541183472,
263
+ 30.783664703369,
264
+ 30.838117599487,
265
+ 31.042964935303,
266
+ 31.038463592529,
267
+ 31.105230331421,
268
+ 31.207004547119,
269
+ 31.377513885498,
270
+ 31.477378845215,
271
+ 31.692283630371,
272
+ 31.755348205566,
273
+ 32.003520965576,
274
+ 32.444396972656,
275
+ 32.61438369751,
276
+ 33.048908233643,
277
+ 33.07551574707,
278
+ 33.278274536133,
279
+ 33.595630645752,
280
+ 33.91028213501,
281
+ 34.337677001953,
282
+ 34.645801544189,
283
+ 35.182697296143,
284
+ 35.598838806152,
285
+ 36.012474060059,
286
+ 36.654026031494,
287
+ 37.174102783203,
288
+ 37.691062927246,
289
+ 38.320404052734,
290
+ 38.94518661499,
291
+ 39.336082458496,
292
+ 39.843410491943,
293
+ 40.349597930908,
294
+ 40.509769439697,
295
+ 41.021186828613,
296
+ 41.300796508789,
297
+ 41.583572387695,
298
+ 41.869022369385,
299
+ 42.156734466553,
300
+ 42.561374664307,
301
+ 43.080310821533,
302
+ 44.171394348145,
303
+ 44.673233032227,
304
+ 46.209945678711,
305
+ 47.495380401611,
306
+ 48.882556915283,
307
+ 50.141174316406,
308
+ 51.965770721436,
309
+ 53.310932159424,
310
+ 53.958972930908,
311
+ 54.960140228271,
312
+ 55.84610748291,
313
+ 56.734252929688,
314
+ 56.934139251709,
315
+ 57.839687347412,
316
+ 58.744373321533,
317
+ 59.533309936523,
318
+ 60.899055480957,
319
+ 61.679496765137,
320
+ 62.46297454834,
321
+ 63.594078063965,
322
+ 64.83536529541,
323
+ 66.530303955078,
324
+ 68.210494995117,
325
+ 69.64818572998,
326
+ 71.885147094727,
327
+ 74.445877075195,
328
+ 76.751594543457,
329
+ 79.731002807617,
330
+ 82.797538757324,
331
+ 84.457992553711,
332
+ 86.584655761719,
333
+ 89.167251586914,
334
+ 91.046905517578,
335
+ 93.504814147949,
336
+ 95.378631591797,
337
+ 96.22135925293,
338
+ 96.628448486328,
339
+ 99.250854492188,
340
+ 99.668907165527,
341
+ 99.195091247559,
342
+ 100.0290145874,
343
+ 100.98822021484,
344
+ 101.95376586914,
345
+ 103.26971435547,
346
+ 104.46817779541,
347
+ 105.20679473877,
348
+ 106.1849899292,
349
+ 106.70650482178,
350
+ 108.0453414917,
351
+ 108.68803405762,
352
+ 109.45465087891,
353
+ 110.91656494141,
354
+ 109.37838745117,
355
+ 110.19312286377,
356
+ 110.89054107666,
357
+ 112.16345977783,
358
+ 113.54005432129,
359
+ 114.67472076416,
360
+ 115.91901397705,
361
+ 116.92639160156,
362
+ 118.16265106201,
363
+ 119.50830078125,
364
+ 120.96187591553,
365
+ 122.29209899902,
366
+ 124.30773925781,
367
+ 125.7303237915,
368
+ 126.57431030273,
369
+ 128.8072052002,
370
+ 130.21432495117,
371
+ 131.85038757324,
372
+ 134.97607421875,
373
+ 136.22640991211,
374
+ 136.44931030273,
375
+ 137.50482177734,
376
+ 138.45225524902,
377
+ 139.5228729248,
378
+ 140.59803771973,
379
+ 141.67707824707,
380
+ 142.87438964844,
381
+ 143.95710754395,
382
+ 144.92749023438,
383
+ 145.55741882324,
384
+ 146.65830993652,
385
+ 147.29898071289,
386
+ 148.17890930176,
387
+ 149.40701293945,
388
+ 150.40071105957,
389
+ 151.51042175293,
390
+ 152.84864807129,
391
+ 153.60585021973,
392
+ 154.48471069336,
393
+ 155.7119140625,
394
+ 157.16493225098,
395
+ 158.03460693359,
396
+ 159.25405883789,
397
+ 160.47047424316,
398
+ 160.87922668457,
399
+ 161.30215454102,
400
+ 162.42718505859,
401
+ 162.85820007324,
402
+ 162.95487976074,
403
+ 163.98776245117,
404
+ 164.67047119141,
405
+ 165.47090148926,
406
+ 166.73132324219,
407
+ 167.52229309082,
408
+ 169.00477600098,
409
+ 170.24440002441,
410
+ 171.93792724609,
411
+ 173.84696960449,
412
+ 175.04895019531,
413
+ 176.82572937012,
414
+ 177.55540466309,
415
+ 178.52604675293,
416
+ 178.58113098145,
417
+ 178.54368591309,
418
+ 180.25286865234,
419
+ 180.90992736816,
420
+ 182.14875793457,
421
+ 183.61158752441,
422
+ 184.14450073242,
423
+ 184.5728302002,
424
+ 185.81741333008,
425
+ 187.28511047363,
426
+ 188.39723205566,
427
+ 190.19758605957,
428
+ 191.98233032227,
429
+ 192.94879150391,
430
+ 195.07064819336,
431
+ 195.90835571289,
432
+ 200.89639282227,
433
+ 200.86282348633,
434
+ 202.13075256348,
435
+ 204.20880126953,
436
+ 203.05419921875,
437
+ 204.80026245117,
438
+ 207.3080291748,
439
+ 208.72329711914,
440
+ 210.57261657715,
441
+ 214.21580505371,
442
+ 215.67597961426,
443
+ 220.72087097168,
444
+ 218.41342163086,
445
+ 212.75346374512,
446
+ 213.23506164551,
447
+ 215.21542358398])
448
+
449
+ resid = np.array([
450
+ np.nan,
451
+ .17000007629395,
452
+ .17130389809608,
453
+ -.03651398047805,
454
+ .11960058659315,
455
+ -.05888139456511,
456
+ .14059536159039,
457
+ .00932686589658,
458
+ -.11167634278536,
459
+ .04570783302188,
460
+ -.0108770346269,
461
+ -.00886330008507,
462
+ .10282856971025,
463
+ -.07230624556541,
464
+ .08900293707848,
465
+ -.0240114107728,
466
+ -.03996651992202,
467
+ .13645842671394,
468
+ -.03366377204657,
469
+ .10188252478838,
470
+ -.09296332299709,
471
+ -.01846401393414,
472
+ .01477065030485,
473
+ .0729955881834,
474
+ .00248436117545,
475
+ .10262141376734,
476
+ -.04228436201811,
477
+ .12465056031942,
478
+ .27647939324379,
479
+ .00560382334515,
480
+ .23561419546604,
481
+ -.1489082723856,
482
+ .02448422275484,
483
+ .12172746658325,
484
+ .10437148809433,
485
+ .18971465528011,
486
+ .06232447177172,
487
+ .25419962406158,
488
+ .11730266362429,
489
+ .10116269439459,
490
+ .2875237762928,
491
+ .14597341418266,
492
+ .12589547038078,
493
+ .20893961191177,
494
+ .17959471046925,
495
+ -.04518361017108,
496
+ .06391899287701,
497
+ .05659105628729,
498
+ -.24960128962994,
499
+ .09022761881351,
500
+ -.12118522822857,
501
+ -.10079623758793,
502
+ -.08357158303261,
503
+ -.06902338564396,
504
+ .04326653853059,
505
+ .13862533867359,
506
+ .61968916654587,
507
+ .02860714122653,
508
+ .92676383256912,
509
+ .59005337953568,
510
+ .60461646318436,
511
+ .41744044423103,
512
+ .85882639884949,
513
+ .33423033356667,
514
+ -.31093180179596,
515
+ .04102724045515,
516
+ -.06013804674149,
517
+ -.04610994458199,
518
+ -.63425624370575,
519
+ .06586220860481,
520
+ .06031560897827,
521
+ -.04437142238021,
522
+ .46668976545334,
523
+ -.09905604273081,
524
+ -.07949769496918,
525
+ .23702463507652,
526
+ .30592212080956,
527
+ .66463404893875,
528
+ .56969320774078,
529
+ .28950771689415,
530
+ .95181107521057,
531
+ 1.1148544549942,
532
+ .75411820411682,
533
+ 1.2484039068222,
534
+ 1.1690024137497,
535
+ -.1975435167551,
536
+ .24200716614723,
537
+ .6153416633606,
538
+ -.06725100427866,
539
+ .45309436321259,
540
+ -.10480991750956,
541
+ -.97863000631332,
542
+ -1.2213591337204,
543
+ .8715478181839,
544
+ -1.1508584022522,
545
+ -1.7689031362534,
546
+ -.39508575201035,
547
+ -.22900961339474,
548
+ -.18821682035923,
549
+ .14623281359673,
550
+ .03029025532305,
551
+ -.36817568540573,
552
+ -.10679569840431,
553
+ -.48499462008476,
554
+ .29349562525749,
555
+ -.34534454345703,
556
+ -.18803144991398,
557
+ .44535079598427,
558
+ -2.2165644168854,
559
+ .12161350995302,
560
+ .00687709869817,
561
+ .50946187973022,
562
+ .53653997182846,
563
+ .25995117425919,
564
+ .32527860999107,
565
+ .08098815381527,
566
+ .27360898256302,
567
+ .33735024929047,
568
+ .39170032739639,
569
+ .23812144994736,
570
+ .80789774656296,
571
+ .19225835800171,
572
+ -.33032417297363,
573
+ .92568749189377,
574
+ .09278241544962,
575
+ .28566908836365,
576
+ 1.5496014356613,
577
+ -.27607008814812,
578
+ -1.1263961791992,
579
+ -.24930645525455,
580
+ -.30482992529869,
581
+ -.15224970877171,
582
+ -.12287864089012,
583
+ -.09804095327854,
584
+ .02291300706565,
585
+ -.07438835501671,
586
+ -.15710659325123,
587
+ -.42748948931694,
588
+ .04259072244167,
589
+ -.35830733180046,
590
+ -.09898918122053,
591
+ .22108262777328,
592
+ -.00701736938208,
593
+ .0992873236537,
594
+ .28958559036255,
595
+ -.24864092469215,
596
+ -.10584850609303,
597
+ .21528913080692,
598
+ .38809850811958,
599
+ -.16492980718613,
600
+ .16538816690445,
601
+ .1459391862154,
602
+ -.57048463821411,
603
+ -.47923597693443,
604
+ .19784018397331,
605
+ -.4271782040596,
606
+ -.65820020437241,
607
+ .24511873722076,
608
+ -.0877638310194,
609
+ .02952514961362,
610
+ .42909786105156,
611
+ -.03132146969438,
612
+ .57771807909012,
613
+ .29522883892059,
614
+ .6555985212326,
615
+ .76207375526428,
616
+ .05302781611681,
617
+ .55105316638947,
618
+ -.42574247717857,
619
+ -.15540990233421,
620
+ -.92604118585587,
621
+ -.88112819194794,
622
+ .75632172822952,
623
+ -.25287514925003,
624
+ .29006350040436,
625
+ .45125409960747,
626
+ -.41159069538116,
627
+ -.44450175762177,
628
+ .32716807723045,
629
+ .48259317874908,
630
+ .11487878113985,
631
+ .70277869701385,
632
+ .60241633653641,
633
+ -.18233296275139,
634
+ .85120695829391,
635
+ -.37064728140831,
636
+ 3.2916390895844,
637
+ -1.4963974952698,
638
+ -.16283248364925,
639
+ .56923681497574,
640
+ -2.3088004589081,
641
+ .51979947090149,
642
+ 1.1197309494019,
643
+ .02996650896966,
644
+ .40969428420067,
645
+ 1.9223841428757,
646
+ -.21881568431854,
647
+ 2.9340152740479,
648
+ -3.8318600654602,
649
+ -6.239429473877,
650
+ -.08245316892862,
651
+ 1.2339268922806,
652
+ 1.1695692539215])
653
+
654
+ yr = np.array([
655
+ np.nan,
656
+ .17000007629395,
657
+ .17130389809608,
658
+ -.03651398047805,
659
+ .11960058659315,
660
+ -.05888139456511,
661
+ .14059536159039,
662
+ .00932686589658,
663
+ -.11167634278536,
664
+ .04570783302188,
665
+ -.0108770346269,
666
+ -.00886330008507,
667
+ .10282856971025,
668
+ -.07230624556541,
669
+ .08900293707848,
670
+ -.0240114107728,
671
+ -.03996651992202,
672
+ .13645842671394,
673
+ -.03366377204657,
674
+ .10188252478838,
675
+ -.09296332299709,
676
+ -.01846401393414,
677
+ .01477065030485,
678
+ .0729955881834,
679
+ .00248436117545,
680
+ .10262141376734,
681
+ -.04228436201811,
682
+ .12465056031942,
683
+ .27647939324379,
684
+ .00560382334515,
685
+ .23561419546604,
686
+ -.1489082723856,
687
+ .02448422275484,
688
+ .12172746658325,
689
+ .10437148809433,
690
+ .18971465528011,
691
+ .06232447177172,
692
+ .25419962406158,
693
+ .11730266362429,
694
+ .10116269439459,
695
+ .2875237762928,
696
+ .14597341418266,
697
+ .12589547038078,
698
+ .20893961191177,
699
+ .17959471046925,
700
+ -.04518361017108,
701
+ .06391899287701,
702
+ .05659105628729,
703
+ -.24960128962994,
704
+ .09022761881351,
705
+ -.12118522822857,
706
+ -.10079623758793,
707
+ -.08357158303261,
708
+ -.06902338564396,
709
+ .04326653853059,
710
+ .13862533867359,
711
+ .61968916654587,
712
+ .02860714122653,
713
+ .92676383256912,
714
+ .59005337953568,
715
+ .60461646318436,
716
+ .41744044423103,
717
+ .85882639884949,
718
+ .33423033356667,
719
+ -.31093180179596,
720
+ .04102724045515,
721
+ -.06013804674149,
722
+ -.04610994458199,
723
+ -.63425624370575,
724
+ .06586220860481,
725
+ .06031560897827,
726
+ -.04437142238021,
727
+ .46668976545334,
728
+ -.09905604273081,
729
+ -.07949769496918,
730
+ .23702463507652,
731
+ .30592212080956,
732
+ .66463404893875,
733
+ .56969320774078,
734
+ .28950771689415,
735
+ .95181107521057,
736
+ 1.1148544549942,
737
+ .75411820411682,
738
+ 1.2484039068222,
739
+ 1.1690024137497,
740
+ -.1975435167551,
741
+ .24200716614723,
742
+ .6153416633606,
743
+ -.06725100427866,
744
+ .45309436321259,
745
+ -.10480991750956,
746
+ -.97863000631332,
747
+ -1.2213591337204,
748
+ .8715478181839,
749
+ -1.1508584022522,
750
+ -1.7689031362534,
751
+ -.39508575201035,
752
+ -.22900961339474,
753
+ -.18821682035923,
754
+ .14623281359673,
755
+ .03029025532305,
756
+ -.36817568540573,
757
+ -.10679569840431,
758
+ -.48499462008476,
759
+ .29349562525749,
760
+ -.34534454345703,
761
+ -.18803144991398,
762
+ .44535079598427,
763
+ -2.2165644168854,
764
+ .12161350995302,
765
+ .00687709869817,
766
+ .50946187973022,
767
+ .53653997182846,
768
+ .25995117425919,
769
+ .32527860999107,
770
+ .08098815381527,
771
+ .27360898256302,
772
+ .33735024929047,
773
+ .39170032739639,
774
+ .23812144994736,
775
+ .80789774656296,
776
+ .19225835800171,
777
+ -.33032417297363,
778
+ .92568749189377,
779
+ .09278241544962,
780
+ .28566908836365,
781
+ 1.5496014356613,
782
+ -.27607008814812,
783
+ -1.1263961791992,
784
+ -.24930645525455,
785
+ -.30482992529869,
786
+ -.15224970877171,
787
+ -.12287864089012,
788
+ -.09804095327854,
789
+ .02291300706565,
790
+ -.07438835501671,
791
+ -.15710659325123,
792
+ -.42748948931694,
793
+ .04259072244167,
794
+ -.35830733180046,
795
+ -.09898918122053,
796
+ .22108262777328,
797
+ -.00701736938208,
798
+ .0992873236537,
799
+ .28958559036255,
800
+ -.24864092469215,
801
+ -.10584850609303,
802
+ .21528913080692,
803
+ .38809850811958,
804
+ -.16492980718613,
805
+ .16538816690445,
806
+ .1459391862154,
807
+ -.57048463821411,
808
+ -.47923597693443,
809
+ .19784018397331,
810
+ -.4271782040596,
811
+ -.65820020437241,
812
+ .24511873722076,
813
+ -.0877638310194,
814
+ .02952514961362,
815
+ .42909786105156,
816
+ -.03132146969438,
817
+ .57771807909012,
818
+ .29522883892059,
819
+ .6555985212326,
820
+ .76207375526428,
821
+ .05302781611681,
822
+ .55105316638947,
823
+ -.42574247717857,
824
+ -.15540990233421,
825
+ -.92604118585587,
826
+ -.88112819194794,
827
+ .75632172822952,
828
+ -.25287514925003,
829
+ .29006350040436,
830
+ .45125409960747,
831
+ -.41159069538116,
832
+ -.44450175762177,
833
+ .32716807723045,
834
+ .48259317874908,
835
+ .11487878113985,
836
+ .70277869701385,
837
+ .60241633653641,
838
+ -.18233296275139,
839
+ .85120695829391,
840
+ -.37064728140831,
841
+ 3.2916390895844,
842
+ -1.4963974952698,
843
+ -.16283248364925,
844
+ .56923681497574,
845
+ -2.3088004589081,
846
+ .51979947090149,
847
+ 1.1197309494019,
848
+ .02996650896966,
849
+ .40969428420067,
850
+ 1.9223841428757,
851
+ -.21881568431854,
852
+ 2.9340152740479,
853
+ -3.8318600654602,
854
+ -6.239429473877,
855
+ -.08245316892862,
856
+ 1.2339268922806,
857
+ 1.1695692539215])
858
+
859
+ mse = np.array([
860
+ 1.1112809181213,
861
+ .6632194519043,
862
+ .65879660844803,
863
+ .65575885772705,
864
+ .65364873409271,
865
+ .65217137336731,
866
+ .65113133192062,
867
+ .6503963470459,
868
+ .64987552165985,
869
+ .64950579404831,
870
+ .64924287796021,
871
+ .64905577898026,
872
+ .64892256259918,
873
+ .64882761240005,
874
+ .64875996112823,
875
+ .64871168136597,
876
+ .64867728948593,
877
+ .64865279197693,
878
+ .64863526821136,
879
+ .64862281084061,
880
+ .64861387014389,
881
+ .64860755205154,
882
+ .64860302209854,
883
+ .64859980344772,
884
+ .64859747886658,
885
+ .64859586954117,
886
+ .64859467744827,
887
+ .64859384298325,
888
+ .6485932469368,
889
+ .64859282970428,
890
+ .64859253168106,
891
+ .64859229326248,
892
+ .64859211444855,
893
+ .64859199523926,
894
+ .64859193563461,
895
+ .64859187602997,
896
+ .64859187602997,
897
+ .64859181642532,
898
+ .64859181642532,
899
+ .64859175682068,
900
+ .64859175682068,
901
+ .64859175682068,
902
+ .64859175682068,
903
+ .64859175682068,
904
+ .64859175682068,
905
+ .64859175682068,
906
+ .64859175682068,
907
+ .64859175682068,
908
+ .64859175682068,
909
+ .64859175682068,
910
+ .64859175682068,
911
+ .64859175682068,
912
+ .64859175682068,
913
+ .64859175682068,
914
+ .64859175682068,
915
+ .64859175682068,
916
+ .64859175682068,
917
+ .64859175682068,
918
+ .64859175682068,
919
+ .64859175682068,
920
+ .64859175682068,
921
+ .64859175682068,
922
+ .64859175682068,
923
+ .64859175682068,
924
+ .64859175682068,
925
+ .64859175682068,
926
+ .64859175682068,
927
+ .64859175682068,
928
+ .64859175682068,
929
+ .64859175682068,
930
+ .64859175682068,
931
+ .64859175682068,
932
+ .64859175682068,
933
+ .64859175682068,
934
+ .64859175682068,
935
+ .64859175682068,
936
+ .64859175682068,
937
+ .64859175682068,
938
+ .64859175682068,
939
+ .64859175682068,
940
+ .64859175682068,
941
+ .64859175682068,
942
+ .64859175682068,
943
+ .64859175682068,
944
+ .64859175682068,
945
+ .64859175682068,
946
+ .64859175682068,
947
+ .64859175682068,
948
+ .64859175682068,
949
+ .64859175682068,
950
+ .64859175682068,
951
+ .64859175682068,
952
+ .64859175682068,
953
+ .64859175682068,
954
+ .64859175682068,
955
+ .64859175682068,
956
+ .64859175682068,
957
+ .64859175682068,
958
+ .64859175682068,
959
+ .64859175682068,
960
+ .64859175682068,
961
+ .64859175682068,
962
+ .64859175682068,
963
+ .64859175682068,
964
+ .64859175682068,
965
+ .64859175682068,
966
+ .64859175682068,
967
+ .64859175682068,
968
+ .64859175682068,
969
+ .64859175682068,
970
+ .64859175682068,
971
+ .64859175682068,
972
+ .64859175682068,
973
+ .64859175682068,
974
+ .64859175682068,
975
+ .64859175682068,
976
+ .64859175682068,
977
+ .64859175682068,
978
+ .64859175682068,
979
+ .64859175682068,
980
+ .64859175682068,
981
+ .64859175682068,
982
+ .64859175682068,
983
+ .64859175682068,
984
+ .64859175682068,
985
+ .64859175682068,
986
+ .64859175682068,
987
+ .64859175682068,
988
+ .64859175682068,
989
+ .64859175682068,
990
+ .64859175682068,
991
+ .64859175682068,
992
+ .64859175682068,
993
+ .64859175682068,
994
+ .64859175682068,
995
+ .64859175682068,
996
+ .64859175682068,
997
+ .64859175682068,
998
+ .64859175682068,
999
+ .64859175682068,
1000
+ .64859175682068,
1001
+ .64859175682068,
1002
+ .64859175682068,
1003
+ .64859175682068,
1004
+ .64859175682068,
1005
+ .64859175682068,
1006
+ .64859175682068,
1007
+ .64859175682068,
1008
+ .64859175682068,
1009
+ .64859175682068,
1010
+ .64859175682068,
1011
+ .64859175682068,
1012
+ .64859175682068,
1013
+ .64859175682068,
1014
+ .64859175682068,
1015
+ .64859175682068,
1016
+ .64859175682068,
1017
+ .64859175682068,
1018
+ .64859175682068,
1019
+ .64859175682068,
1020
+ .64859175682068,
1021
+ .64859175682068,
1022
+ .64859175682068,
1023
+ .64859175682068,
1024
+ .64859175682068,
1025
+ .64859175682068,
1026
+ .64859175682068,
1027
+ .64859175682068,
1028
+ .64859175682068,
1029
+ .64859175682068,
1030
+ .64859175682068,
1031
+ .64859175682068,
1032
+ .64859175682068,
1033
+ .64859175682068,
1034
+ .64859175682068,
1035
+ .64859175682068,
1036
+ .64859175682068,
1037
+ .64859175682068,
1038
+ .64859175682068,
1039
+ .64859175682068,
1040
+ .64859175682068,
1041
+ .64859175682068,
1042
+ .64859175682068,
1043
+ .64859175682068,
1044
+ .64859175682068,
1045
+ .64859175682068,
1046
+ .64859175682068,
1047
+ .64859175682068,
1048
+ .64859175682068,
1049
+ .64859175682068,
1050
+ .64859175682068,
1051
+ .64859175682068,
1052
+ .64859175682068,
1053
+ .64859175682068,
1054
+ .64859175682068,
1055
+ .64859175682068,
1056
+ .64859175682068,
1057
+ .64859175682068,
1058
+ .64859175682068,
1059
+ .64859175682068,
1060
+ .64859175682068,
1061
+ .64859175682068,
1062
+ .64859175682068])
1063
+
1064
+ stdp = np.array([
1065
+ 0,
1066
+ 0,
1067
+ .02869686298072,
1068
+ .05651443824172,
1069
+ .0503994859755,
1070
+ .06887971609831,
1071
+ .05940540507436,
1072
+ .08067328482866,
1073
+ .08167565613985,
1074
+ .06429278105497,
1075
+ .07087650150061,
1076
+ .06886467337608,
1077
+ .06716959923506,
1078
+ .08230647444725,
1079
+ .07099691033363,
1080
+ .08401278406382,
1081
+ .07996553182602,
1082
+ .07354256510735,
1083
+ .09366323798895,
1084
+ .08811800926924,
1085
+ .10296355187893,
1086
+ .08846370875835,
1087
+ .0852297320962,
1088
+ .08700425922871,
1089
+ .09751411527395,
1090
+ .09737934917212,
1091
+ .11228405684233,
1092
+ .1053489819169,
1093
+ .12352022528648,
1094
+ .16439816355705,
1095
+ .1643835157156,
1096
+ .19891132414341,
1097
+ .17551273107529,
1098
+ .17827558517456,
1099
+ .19562774896622,
1100
+ .21028305590153,
1101
+ .23767858743668,
1102
+ .24580039083958,
1103
+ .28269505500793,
1104
+ .29883882403374,
1105
+ .31247469782829,
1106
+ .35402658581734,
1107
+ .37410452961922,
1108
+ .39106267690659,
1109
+ .42040377855301,
1110
+ .44518512487411,
1111
+ .43608102202415,
1112
+ .44340893626213,
1113
+ .44959822297096,
1114
+ .40977239608765,
1115
+ .42118826508522,
1116
+ .40079545974731,
1117
+ .38357082009315,
1118
+ .36902260780334,
1119
+ .35673499107361,
1120
+ .36137464642525,
1121
+ .38031083345413,
1122
+ .47139286994934,
1123
+ .47323387861252,
1124
+ .60994738340378,
1125
+ .69538277387619,
1126
+ .7825602889061,
1127
+ .84117436408997,
1128
+ .9657689332962,
1129
+ 1.0109325647354,
1130
+ .95897275209427,
1131
+ .96013957262039,
1132
+ .9461076259613,
1133
+ .9342554807663,
1134
+ .83413934707642,
1135
+ .83968591690063,
1136
+ .84437066316605,
1137
+ .83330947160721,
1138
+ .8990553021431,
1139
+ .87949693202972,
1140
+ .86297762393951,
1141
+ .89407861232758,
1142
+ .93536442518234,
1143
+ 1.0303052663803,
1144
+ 1.1104937791824,
1145
+ 1.1481873989105,
1146
+ 1.2851470708847,
1147
+ 1.4458787441254,
1148
+ 1.5515991449356,
1149
+ 1.7309991121292,
1150
+ 1.8975404500961,
1151
+ 1.8579913377762,
1152
+ 1.8846583366394,
1153
+ 1.9672524929047,
1154
+ 1.9469071626663,
1155
+ 2.0048115253448,
1156
+ 1.9786299467087,
1157
+ 1.8213576078415,
1158
+ 1.6284521818161,
1159
+ 1.7508568763733,
1160
+ 1.5689061880112,
1161
+ 1.2950873374939,
1162
+ 1.2290096282959,
1163
+ 1.1882168054581,
1164
+ 1.1537625789642,
1165
+ 1.1697143316269,
1166
+ 1.1681711673737,
1167
+ 1.106795668602,
1168
+ 1.0849931240082,
1169
+ 1.006507396698,
1170
+ 1.0453414916992,
1171
+ .98803448677063,
1172
+ .95465070009232,
1173
+ 1.0165599584579,
1174
+ .67838954925537,
1175
+ .69311982393265,
1176
+ .69054269790649,
1177
+ .76345545053482,
1178
+ .84005492925644,
1179
+ .87471830844879,
1180
+ .91901183128357,
1181
+ .92638796567917,
1182
+ .96265280246735,
1183
+ 1.0083012580872,
1184
+ 1.0618740320206,
1185
+ 1.0921038389206,
1186
+ 1.2077431678772,
1187
+ 1.2303256988525,
1188
+ 1.174311041832,
1189
+ 1.3072115182877,
1190
+ 1.314337015152,
1191
+ 1.3503924608231,
1192
+ 1.5760731697083,
1193
+ 1.5264053344727,
1194
+ 1.34929728508,
1195
+ 1.304829955101,
1196
+ 1.2522557973862,
1197
+ 1.222869515419,
1198
+ 1.198047041893,
1199
+ 1.1770839691162,
1200
+ 1.1743944883347,
1201
+ 1.1571066379547,
1202
+ 1.1274864673615,
1203
+ 1.0574153661728,
1204
+ 1.058304309845,
1205
+ .99898308515549,
1206
+ .9789143204689,
1207
+ 1.0070173740387,
1208
+ 1.000718832016,
1209
+ 1.0104174613953,
1210
+ 1.0486439466476,
1211
+ 1.0058424472809,
1212
+ .98470783233643,
1213
+ 1.0119106769562,
1214
+ 1.0649236440659,
1215
+ 1.0346088409424,
1216
+ 1.0540577173233,
1217
+ 1.0704846382141,
1218
+ .97923594713211,
1219
+ .90216588973999,
1220
+ .9271782040596,
1221
+ .85819715261459,
1222
+ .75488126277924,
1223
+ .78776079416275,
1224
+ .77047789096832,
1225
+ .77089905738831,
1226
+ .8313245177269,
1227
+ .82229107618332,
1228
+ .90476810932159,
1229
+ .94439232349396,
1230
+ 1.0379292964935,
1231
+ 1.1469690799713,
1232
+ 1.1489590406418,
1233
+ 1.2257302999496,
1234
+ 1.1554099321365,
1235
+ 1.1260533332825,
1236
+ .9811190366745,
1237
+ .8436843752861,
1238
+ .95287209749222,
1239
+ .90993344783783,
1240
+ .94875508546829,
1241
+ 1.0115815401077,
1242
+ .94450175762177,
1243
+ .87282890081406,
1244
+ .91741597652435,
1245
+ .98511207103729,
1246
+ .9972335100174,
1247
+ 1.0975805521011,
1248
+ 1.1823329925537,
1249
+ 1.1487929821014,
1250
+ 1.270641207695,
1251
+ 1.2083609104156,
1252
+ 1.696394443512,
1253
+ 1.4628355503082,
1254
+ 1.4307631254196,
1255
+ 1.5087975263596,
1256
+ 1.1542117595673,
1257
+ 1.2262620925903,
1258
+ 1.3880327939987,
1259
+ 1.3853038549423,
1260
+ 1.4396153688431,
1261
+ 1.7208145856857,
1262
+ 1.678991317749,
1263
+ 2.110867023468,
1264
+ 1.524417757988,
1265
+ .57946246862411,
1266
+ .56406193971634,
1267
+ .74643105268478])
1268
+
1269
+ icstats = np.array([
1270
+ 202,
1271
+ np.nan,
1272
+ -242.89663276735,
1273
+ 3,
1274
+ 491.79326553469,
1275
+ 501.7180686269])
1276
+
1277
+
1278
+ results = Bunch(
1279
+ llf=llf,
1280
+ nobs=nobs,
1281
+ k=k,
1282
+ k_exog=k_exog,
1283
+ sigma=sigma,
1284
+ chi2=chi2,
1285
+ df_model=df_model,
1286
+ k_ar=k_ar,
1287
+ k_ma=k_ma,
1288
+ params=params,
1289
+ cov_params=cov_params,
1290
+ xb=xb,
1291
+ y=y,
1292
+ resid=resid,
1293
+ yr=yr,
1294
+ mse=mse,
1295
+ stdp=stdp,
1296
+ icstats=icstats
1297
+ )
shared/package-files/56/563e1558fcad6e16795bbefe59ab34fffabc06bf514d4d6f467045ac7f0cdf3c/blob ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/BFloat16.h>
4
+ #include <c10/util/Float8_e4m3fn.h>
5
+ #include <c10/util/Float8_e4m3fnuz.h>
6
+ #include <c10/util/Float8_e5m2.h>
7
+ #include <c10/util/Float8_e5m2fnuz.h>
8
+ #include <c10/util/Half.h>
9
+ #include <torch/csrc/Export.h>
10
+ #include <cstddef>
11
+ #include <cstdint>
12
+
13
+ #ifdef __FreeBSD__
14
+ #include <sys/endian.h>
15
+ #include <sys/types.h>
16
+ #define thp_bswap16(x) bswap16(x)
17
+ #define thp_bswap32(x) bswap32(x)
18
+ #define thp_bswap64(x) bswap64(x)
19
+ #elif defined(__APPLE__)
20
+ #include <libkern/OSByteOrder.h>
21
+ #define thp_bswap16(x) OSSwapInt16(x)
22
+ #define thp_bswap32(x) OSSwapInt32(x)
23
+ #define thp_bswap64(x) OSSwapInt64(x)
24
+ #elif defined(__GNUC__) && !defined(__MINGW32__)
25
+ #include <byteswap.h>
26
+ #define thp_bswap16(x) bswap_16(x)
27
+ #define thp_bswap32(x) bswap_32(x)
28
+ #define thp_bswap64(x) bswap_64(x)
29
+ #elif defined _WIN32 || defined _WIN64
30
+ #define thp_bswap16(x) _byteswap_ushort(x)
31
+ #define thp_bswap32(x) _byteswap_ulong(x)
32
+ #define thp_bswap64(x) _byteswap_uint64(x)
33
+ #endif
34
+
35
+ #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
36
+ #define to_be16(x) thp_bswap16(x)
37
+ #define from_be16(x) thp_bswap16(x)
38
+ #define to_be32(x) thp_bswap32(x)
39
+ #define from_be32(x) thp_bswap32(x)
40
+ #define to_be64(x) thp_bswap64(x)
41
+ #define from_be64(x) thp_bswap64(x)
42
+ #define to_le16(x) (x)
43
+ #define from_le16(x) (x)
44
+ #define to_le32(x) (x)
45
+ #define from_le32(x) (x)
46
+ #define to_le64(x) (x)
47
+ #define from_le64(x) (x)
48
+ #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
49
+ #define to_be16(x) (x)
50
+ #define from_be16(x) (x)
51
+ #define to_be32(x) (x)
52
+ #define from_be32(x) (x)
53
+ #define to_be64(x) (x)
54
+ #define from_be64(x) (x)
55
+ #define to_le16(x) thp_bswap16(x)
56
+ #define from_le16(x) thp_bswap16(x)
57
+ #define to_le32(x) thp_bswap32(x)
58
+ #define from_le32(x) thp_bswap32(x)
59
+ #define to_le64(x) thp_bswap64(x)
60
+ #define from_le64(x) thp_bswap64(x)
61
+ #else
62
+ #error Unexpected or undefined __BYTE_ORDER__
63
+ #endif
64
+
65
+ namespace torch {
66
+ namespace utils {
67
+
68
+ enum THPByteOrder { THP_LITTLE_ENDIAN = 0, THP_BIG_ENDIAN = 1 };
69
+
70
+ TORCH_API THPByteOrder THP_nativeByteOrder();
71
+
72
+ TORCH_API void THP_decodeInt16Buffer(
73
+ int16_t* dst,
74
+ const uint8_t* src,
75
+ bool do_byte_swap,
76
+ size_t len);
77
+ TORCH_API void THP_decodeInt32Buffer(
78
+ int32_t* dst,
79
+ const uint8_t* src,
80
+ bool do_byte_swap,
81
+ size_t len);
82
+ TORCH_API void THP_decodeInt64Buffer(
83
+ int64_t* dst,
84
+ const uint8_t* src,
85
+ bool do_byte_swap,
86
+ size_t len);
87
+ TORCH_API void THP_decodeHalfBuffer(
88
+ c10::Half* dst,
89
+ const uint8_t* src,
90
+ bool do_byte_swap,
91
+ size_t len);
92
+ TORCH_API void THP_decodeFloatBuffer(
93
+ float* dst,
94
+ const uint8_t* src,
95
+ bool do_byte_swap,
96
+ size_t len);
97
+ TORCH_API void THP_decodeDoubleBuffer(
98
+ double* dst,
99
+ const uint8_t* src,
100
+ bool do_byte_swap,
101
+ size_t len);
102
+ TORCH_API void THP_decodeBoolBuffer(
103
+ bool* dst,
104
+ const uint8_t* src,
105
+ bool do_byte_swap,
106
+ size_t len);
107
+ TORCH_API void THP_decodeBFloat16Buffer(
108
+ at::BFloat16* dst,
109
+ const uint8_t* src,
110
+ bool do_byte_swap,
111
+ size_t len);
112
+ TORCH_API void THP_decodeComplexFloatBuffer(
113
+ c10::complex<float>* dst,
114
+ const uint8_t* src,
115
+ bool do_byte_swap,
116
+ size_t len);
117
+ TORCH_API void THP_decodeComplexDoubleBuffer(
118
+ c10::complex<double>* dst,
119
+ const uint8_t* src,
120
+ bool do_byte_swap,
121
+ size_t len);
122
+
123
+ TORCH_API void THP_decodeInt16Buffer(
124
+ int16_t* dst,
125
+ const uint8_t* src,
126
+ THPByteOrder order,
127
+ size_t len);
128
+ TORCH_API void THP_decodeInt32Buffer(
129
+ int32_t* dst,
130
+ const uint8_t* src,
131
+ THPByteOrder order,
132
+ size_t len);
133
+ TORCH_API void THP_decodeInt64Buffer(
134
+ int64_t* dst,
135
+ const uint8_t* src,
136
+ THPByteOrder order,
137
+ size_t len);
138
+ TORCH_API void THP_decodeHalfBuffer(
139
+ c10::Half* dst,
140
+ const uint8_t* src,
141
+ THPByteOrder order,
142
+ size_t len);
143
+ TORCH_API void THP_decodeFloatBuffer(
144
+ float* dst,
145
+ const uint8_t* src,
146
+ THPByteOrder order,
147
+ size_t len);
148
+ TORCH_API void THP_decodeDoubleBuffer(
149
+ double* dst,
150
+ const uint8_t* src,
151
+ THPByteOrder order,
152
+ size_t len);
153
+ TORCH_API void THP_decodeBoolBuffer(
154
+ bool* dst,
155
+ const uint8_t* src,
156
+ THPByteOrder order,
157
+ size_t len);
158
+ TORCH_API void THP_decodeBFloat16Buffer(
159
+ at::BFloat16* dst,
160
+ const uint8_t* src,
161
+ THPByteOrder order,
162
+ size_t len);
163
+ TORCH_API void THP_decodeFloat8_e5m2Buffer(
164
+ at::Float8_e5m2* dst,
165
+ const uint8_t* src,
166
+ size_t len);
167
+ TORCH_API void THP_decodeFloat8_e4m3fnBuffer(
168
+ at::Float8_e4m3fn* dst,
169
+ const uint8_t* src,
170
+ size_t len);
171
+ TORCH_API void THP_decodeFloat8_e5m2fnuzBuffer(
172
+ at::Float8_e5m2fnuz* dst,
173
+ const uint8_t* src,
174
+ size_t len);
175
+ TORCH_API void THP_decodeFloat8_e4m3fnuzBuffer(
176
+ at::Float8_e4m3fnuz* dst,
177
+ const uint8_t* src,
178
+ size_t len);
179
+ TORCH_API void THP_decodeComplexFloatBuffer(
180
+ c10::complex<float>* dst,
181
+ const uint8_t* src,
182
+ THPByteOrder order,
183
+ size_t len);
184
+ TORCH_API void THP_decodeComplexDoubleBuffer(
185
+ c10::complex<double>* dst,
186
+ const uint8_t* src,
187
+ THPByteOrder order,
188
+ size_t len);
189
+
190
+ TORCH_API void THP_encodeInt16Buffer(
191
+ uint8_t* dst,
192
+ const int16_t* src,
193
+ THPByteOrder order,
194
+ size_t len);
195
+ TORCH_API void THP_encodeInt32Buffer(
196
+ uint8_t* dst,
197
+ const int32_t* src,
198
+ THPByteOrder order,
199
+ size_t len);
200
+ TORCH_API void THP_encodeInt64Buffer(
201
+ uint8_t* dst,
202
+ const int64_t* src,
203
+ THPByteOrder order,
204
+ size_t len);
205
+ TORCH_API void THP_encodeFloatBuffer(
206
+ uint8_t* dst,
207
+ const float* src,
208
+ THPByteOrder order,
209
+ size_t len);
210
+ TORCH_API void THP_encodeDoubleBuffer(
211
+ uint8_t* dst,
212
+ const double* src,
213
+ THPByteOrder order,
214
+ size_t len);
215
+ TORCH_API void THP_encodeComplexFloatBuffer(
216
+ uint8_t* dst,
217
+ const c10::complex<float>* src,
218
+ THPByteOrder order,
219
+ size_t len);
220
+ TORCH_API void THP_encodeComplexDoubleBuffer(
221
+ uint8_t* dst,
222
+ const c10::complex<double>* src,
223
+ THPByteOrder order,
224
+ size_t len);
225
+
226
+ } // namespace utils
227
+ } // namespace torch
shared/package-files/56/563e435ddf0f296b765370c217a43555179ae3317e4104ce4494b5b4c3b59e4b/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API det {
18
+ using schema = at::Tensor (const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::det")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "det(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ }} // namespace at::_ops
shared/package-files/56/563fa8988b3ade8702d35f49f4e1940ba66e3adae9fe83cd64743e2e400353a9/blob ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Key bindings, for scrolling up and down through pages.
3
+
4
+ This are separate bindings, because GNU readline doesn't have them, but
5
+ they are very useful for navigating through long multiline buffers, like in
6
+ Vi, Emacs, etc...
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from prompt_toolkit.key_binding.key_processor import KeyPressEvent
11
+
12
+ __all__ = [
13
+ "scroll_forward",
14
+ "scroll_backward",
15
+ "scroll_half_page_up",
16
+ "scroll_half_page_down",
17
+ "scroll_one_line_up",
18
+ "scroll_one_line_down",
19
+ ]
20
+
21
+ E = KeyPressEvent
22
+
23
+
24
+ def scroll_forward(event: E, half: bool = False) -> None:
25
+ """
26
+ Scroll window down.
27
+ """
28
+ w = event.app.layout.current_window
29
+ b = event.app.current_buffer
30
+
31
+ if w and w.render_info:
32
+ info = w.render_info
33
+ ui_content = info.ui_content
34
+
35
+ # Height to scroll.
36
+ scroll_height = info.window_height
37
+ if half:
38
+ scroll_height //= 2
39
+
40
+ # Calculate how many lines is equivalent to that vertical space.
41
+ y = b.document.cursor_position_row + 1
42
+ height = 0
43
+ while y < ui_content.line_count:
44
+ line_height = info.get_height_for_line(y)
45
+
46
+ if height + line_height < scroll_height:
47
+ height += line_height
48
+ y += 1
49
+ else:
50
+ break
51
+
52
+ b.cursor_position = b.document.translate_row_col_to_index(y, 0)
53
+
54
+
55
+ def scroll_backward(event: E, half: bool = False) -> None:
56
+ """
57
+ Scroll window up.
58
+ """
59
+ w = event.app.layout.current_window
60
+ b = event.app.current_buffer
61
+
62
+ if w and w.render_info:
63
+ info = w.render_info
64
+
65
+ # Height to scroll.
66
+ scroll_height = info.window_height
67
+ if half:
68
+ scroll_height //= 2
69
+
70
+ # Calculate how many lines is equivalent to that vertical space.
71
+ y = max(0, b.document.cursor_position_row - 1)
72
+ height = 0
73
+ while y > 0:
74
+ line_height = info.get_height_for_line(y)
75
+
76
+ if height + line_height < scroll_height:
77
+ height += line_height
78
+ y -= 1
79
+ else:
80
+ break
81
+
82
+ b.cursor_position = b.document.translate_row_col_to_index(y, 0)
83
+
84
+
85
+ def scroll_half_page_down(event: E) -> None:
86
+ """
87
+ Same as ControlF, but only scroll half a page.
88
+ """
89
+ scroll_forward(event, half=True)
90
+
91
+
92
+ def scroll_half_page_up(event: E) -> None:
93
+ """
94
+ Same as ControlB, but only scroll half a page.
95
+ """
96
+ scroll_backward(event, half=True)
97
+
98
+
99
+ def scroll_one_line_down(event: E) -> None:
100
+ """
101
+ scroll_offset += 1
102
+ """
103
+ w = event.app.layout.current_window
104
+ b = event.app.current_buffer
105
+
106
+ if w:
107
+ # When the cursor is at the top, move to the next line. (Otherwise, only scroll.)
108
+ if w.render_info:
109
+ info = w.render_info
110
+
111
+ if w.vertical_scroll < info.content_height - info.window_height:
112
+ if info.cursor_position.y <= info.configured_scroll_offsets.top:
113
+ b.cursor_position += b.document.get_cursor_down_position()
114
+
115
+ w.vertical_scroll += 1
116
+
117
+
118
+ def scroll_one_line_up(event: E) -> None:
119
+ """
120
+ scroll_offset -= 1
121
+ """
122
+ w = event.app.layout.current_window
123
+ b = event.app.current_buffer
124
+
125
+ if w:
126
+ # When the cursor is at the bottom, move to the previous line. (Otherwise, only scroll.)
127
+ if w.render_info:
128
+ info = w.render_info
129
+
130
+ if w.vertical_scroll > 0:
131
+ first_line_height = info.get_height_for_line(info.first_visible_line())
132
+
133
+ cursor_up = info.cursor_position.y - (
134
+ info.window_height
135
+ - 1
136
+ - first_line_height
137
+ - info.configured_scroll_offsets.bottom
138
+ )
139
+
140
+ # Move cursor up, as many steps as the height of the first line.
141
+ # TODO: not entirely correct yet, in case of line wrapping and many long lines.
142
+ for _ in range(max(0, cursor_up)):
143
+ b.cursor_position += b.document.get_cursor_up_position()
144
+
145
+ # Scroll window
146
+ w.vertical_scroll -= 1
147
+
148
+
149
+ def scroll_page_down(event: E) -> None:
150
+ """
151
+ Scroll page down. (Prefer the cursor at the top of the page, after scrolling.)
152
+ """
153
+ w = event.app.layout.current_window
154
+ b = event.app.current_buffer
155
+
156
+ if w and w.render_info:
157
+ # Scroll down one page.
158
+ line_index = max(w.render_info.last_visible_line(), w.vertical_scroll + 1)
159
+ w.vertical_scroll = line_index
160
+
161
+ b.cursor_position = b.document.translate_row_col_to_index(line_index, 0)
162
+ b.cursor_position += b.document.get_start_of_line_position(
163
+ after_whitespace=True
164
+ )
165
+
166
+
167
+ def scroll_page_up(event: E) -> None:
168
+ """
169
+ Scroll page up. (Prefer the cursor at the bottom of the page, after scrolling.)
170
+ """
171
+ w = event.app.layout.current_window
172
+ b = event.app.current_buffer
173
+
174
+ if w and w.render_info:
175
+ # Put cursor at the first visible line. (But make sure that the cursor
176
+ # moves at least one line up.)
177
+ line_index = max(
178
+ 0,
179
+ min(w.render_info.first_visible_line(), b.document.cursor_position_row - 1),
180
+ )
181
+
182
+ b.cursor_position = b.document.translate_row_col_to_index(line_index, 0)
183
+ b.cursor_position += b.document.get_start_of_line_position(
184
+ after_whitespace=True
185
+ )
186
+
187
+ # Set the scroll offset. We can safely set it to zero; the Window will
188
+ # make sure that it scrolls at least until the cursor becomes visible.
189
+ w.vertical_scroll = 0
shared/package-files/56/5641a9e909f66d0b990a6d4fb2093bc4490352081f4974b9844e06dbfdfb5822/blob ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <cstdint>
5
+
6
+ namespace at {
7
+ struct TensorIterator;
8
+
9
+ namespace native {
10
+
11
+ using _compute_linear_combination_fn = void(*)(
12
+ TensorIterator& iter,
13
+ int64_t in_stride,
14
+ int64_t coeff_stride,
15
+ int64_t num_summations
16
+ );
17
+
18
+ DECLARE_DISPATCH(_compute_linear_combination_fn, _compute_linear_combination_stub);
19
+
20
+ }} // namespace at::native
shared/package-files/56/5642d1b0a514557a37ceb8405e7f6233ea4ac926c62157f35a8a290e199c78c0/blob ADDED
Binary file (148 Bytes). View file
 
shared/package-files/56/5643ad9376af2ed3a5d23bdae0172e6ec19fbb325d68d62661e90050f4cf118f/blob ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor bmm(const at::Tensor & self, const at::Tensor & mat2);
21
+ TORCH_API at::Tensor & bmm_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mat2);
22
+ TORCH_API at::Tensor & bmm_outf(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out);
23
+
24
+ } // namespace cuda
25
+ } // namespace at
shared/package-files/56/5645a590a79bb3c1ff657da38e6fb44a23430625c5374a0fb6699fdde3e116b5/blob ADDED
Binary file (1.03 kB). View file
 
shared/package-files/56/5646119d7e7043b4628400fa918aa2748fe16fd36028948013419a62e94da476/blob ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+ from urllib.parse import urlparse
3
+
4
+ import dns.asyncbackend
5
+ import dns.asyncquery
6
+ import dns.inet
7
+ import dns.message
8
+ import dns.query
9
+
10
+
11
+ class Nameserver:
12
+ def __init__(self):
13
+ pass
14
+
15
+ def __str__(self):
16
+ raise NotImplementedError
17
+
18
+ def kind(self) -> str:
19
+ raise NotImplementedError
20
+
21
+ def is_always_max_size(self) -> bool:
22
+ raise NotImplementedError
23
+
24
+ def answer_nameserver(self) -> str:
25
+ raise NotImplementedError
26
+
27
+ def answer_port(self) -> int:
28
+ raise NotImplementedError
29
+
30
+ def query(
31
+ self,
32
+ request: dns.message.QueryMessage,
33
+ timeout: float,
34
+ source: Optional[str],
35
+ source_port: int,
36
+ max_size: bool,
37
+ one_rr_per_rrset: bool = False,
38
+ ignore_trailing: bool = False,
39
+ ) -> dns.message.Message:
40
+ raise NotImplementedError
41
+
42
+ async def async_query(
43
+ self,
44
+ request: dns.message.QueryMessage,
45
+ timeout: float,
46
+ source: Optional[str],
47
+ source_port: int,
48
+ max_size: bool,
49
+ backend: dns.asyncbackend.Backend,
50
+ one_rr_per_rrset: bool = False,
51
+ ignore_trailing: bool = False,
52
+ ) -> dns.message.Message:
53
+ raise NotImplementedError
54
+
55
+
56
+ class AddressAndPortNameserver(Nameserver):
57
+ def __init__(self, address: str, port: int):
58
+ super().__init__()
59
+ self.address = address
60
+ self.port = port
61
+
62
+ def kind(self) -> str:
63
+ raise NotImplementedError
64
+
65
+ def is_always_max_size(self) -> bool:
66
+ return False
67
+
68
+ def __str__(self):
69
+ ns_kind = self.kind()
70
+ return f"{ns_kind}:{self.address}@{self.port}"
71
+
72
+ def answer_nameserver(self) -> str:
73
+ return self.address
74
+
75
+ def answer_port(self) -> int:
76
+ return self.port
77
+
78
+
79
+ class Do53Nameserver(AddressAndPortNameserver):
80
+ def __init__(self, address: str, port: int = 53):
81
+ super().__init__(address, port)
82
+
83
+ def kind(self):
84
+ return "Do53"
85
+
86
+ def query(
87
+ self,
88
+ request: dns.message.QueryMessage,
89
+ timeout: float,
90
+ source: Optional[str],
91
+ source_port: int,
92
+ max_size: bool,
93
+ one_rr_per_rrset: bool = False,
94
+ ignore_trailing: bool = False,
95
+ ) -> dns.message.Message:
96
+ if max_size:
97
+ response = dns.query.tcp(
98
+ request,
99
+ self.address,
100
+ timeout=timeout,
101
+ port=self.port,
102
+ source=source,
103
+ source_port=source_port,
104
+ one_rr_per_rrset=one_rr_per_rrset,
105
+ ignore_trailing=ignore_trailing,
106
+ )
107
+ else:
108
+ response = dns.query.udp(
109
+ request,
110
+ self.address,
111
+ timeout=timeout,
112
+ port=self.port,
113
+ source=source,
114
+ source_port=source_port,
115
+ raise_on_truncation=True,
116
+ one_rr_per_rrset=one_rr_per_rrset,
117
+ ignore_trailing=ignore_trailing,
118
+ ignore_errors=True,
119
+ ignore_unexpected=True,
120
+ )
121
+ return response
122
+
123
+ async def async_query(
124
+ self,
125
+ request: dns.message.QueryMessage,
126
+ timeout: float,
127
+ source: Optional[str],
128
+ source_port: int,
129
+ max_size: bool,
130
+ backend: dns.asyncbackend.Backend,
131
+ one_rr_per_rrset: bool = False,
132
+ ignore_trailing: bool = False,
133
+ ) -> dns.message.Message:
134
+ if max_size:
135
+ response = await dns.asyncquery.tcp(
136
+ request,
137
+ self.address,
138
+ timeout=timeout,
139
+ port=self.port,
140
+ source=source,
141
+ source_port=source_port,
142
+ backend=backend,
143
+ one_rr_per_rrset=one_rr_per_rrset,
144
+ ignore_trailing=ignore_trailing,
145
+ )
146
+ else:
147
+ response = await dns.asyncquery.udp(
148
+ request,
149
+ self.address,
150
+ timeout=timeout,
151
+ port=self.port,
152
+ source=source,
153
+ source_port=source_port,
154
+ raise_on_truncation=True,
155
+ backend=backend,
156
+ one_rr_per_rrset=one_rr_per_rrset,
157
+ ignore_trailing=ignore_trailing,
158
+ ignore_errors=True,
159
+ ignore_unexpected=True,
160
+ )
161
+ return response
162
+
163
+
164
+ class DoHNameserver(Nameserver):
165
+ def __init__(
166
+ self,
167
+ url: str,
168
+ bootstrap_address: Optional[str] = None,
169
+ verify: Union[bool, str] = True,
170
+ want_get: bool = False,
171
+ ):
172
+ super().__init__()
173
+ self.url = url
174
+ self.bootstrap_address = bootstrap_address
175
+ self.verify = verify
176
+ self.want_get = want_get
177
+
178
+ def kind(self):
179
+ return "DoH"
180
+
181
+ def is_always_max_size(self) -> bool:
182
+ return True
183
+
184
+ def __str__(self):
185
+ return self.url
186
+
187
+ def answer_nameserver(self) -> str:
188
+ return self.url
189
+
190
+ def answer_port(self) -> int:
191
+ port = urlparse(self.url).port
192
+ if port is None:
193
+ port = 443
194
+ return port
195
+
196
+ def query(
197
+ self,
198
+ request: dns.message.QueryMessage,
199
+ timeout: float,
200
+ source: Optional[str],
201
+ source_port: int,
202
+ max_size: bool = False,
203
+ one_rr_per_rrset: bool = False,
204
+ ignore_trailing: bool = False,
205
+ ) -> dns.message.Message:
206
+ return dns.query.https(
207
+ request,
208
+ self.url,
209
+ timeout=timeout,
210
+ source=source,
211
+ source_port=source_port,
212
+ bootstrap_address=self.bootstrap_address,
213
+ one_rr_per_rrset=one_rr_per_rrset,
214
+ ignore_trailing=ignore_trailing,
215
+ verify=self.verify,
216
+ post=(not self.want_get),
217
+ )
218
+
219
+ async def async_query(
220
+ self,
221
+ request: dns.message.QueryMessage,
222
+ timeout: float,
223
+ source: Optional[str],
224
+ source_port: int,
225
+ max_size: bool,
226
+ backend: dns.asyncbackend.Backend,
227
+ one_rr_per_rrset: bool = False,
228
+ ignore_trailing: bool = False,
229
+ ) -> dns.message.Message:
230
+ return await dns.asyncquery.https(
231
+ request,
232
+ self.url,
233
+ timeout=timeout,
234
+ source=source,
235
+ source_port=source_port,
236
+ bootstrap_address=self.bootstrap_address,
237
+ one_rr_per_rrset=one_rr_per_rrset,
238
+ ignore_trailing=ignore_trailing,
239
+ verify=self.verify,
240
+ post=(not self.want_get),
241
+ )
242
+
243
+
244
+ class DoTNameserver(AddressAndPortNameserver):
245
+ def __init__(
246
+ self,
247
+ address: str,
248
+ port: int = 853,
249
+ hostname: Optional[str] = None,
250
+ verify: Union[bool, str] = True,
251
+ ):
252
+ super().__init__(address, port)
253
+ self.hostname = hostname
254
+ self.verify = verify
255
+
256
+ def kind(self):
257
+ return "DoT"
258
+
259
+ def query(
260
+ self,
261
+ request: dns.message.QueryMessage,
262
+ timeout: float,
263
+ source: Optional[str],
264
+ source_port: int,
265
+ max_size: bool = False,
266
+ one_rr_per_rrset: bool = False,
267
+ ignore_trailing: bool = False,
268
+ ) -> dns.message.Message:
269
+ return dns.query.tls(
270
+ request,
271
+ self.address,
272
+ port=self.port,
273
+ timeout=timeout,
274
+ one_rr_per_rrset=one_rr_per_rrset,
275
+ ignore_trailing=ignore_trailing,
276
+ server_hostname=self.hostname,
277
+ verify=self.verify,
278
+ )
279
+
280
+ async def async_query(
281
+ self,
282
+ request: dns.message.QueryMessage,
283
+ timeout: float,
284
+ source: Optional[str],
285
+ source_port: int,
286
+ max_size: bool,
287
+ backend: dns.asyncbackend.Backend,
288
+ one_rr_per_rrset: bool = False,
289
+ ignore_trailing: bool = False,
290
+ ) -> dns.message.Message:
291
+ return await dns.asyncquery.tls(
292
+ request,
293
+ self.address,
294
+ port=self.port,
295
+ timeout=timeout,
296
+ one_rr_per_rrset=one_rr_per_rrset,
297
+ ignore_trailing=ignore_trailing,
298
+ server_hostname=self.hostname,
299
+ verify=self.verify,
300
+ )
301
+
302
+
303
+ class DoQNameserver(AddressAndPortNameserver):
304
+ def __init__(
305
+ self,
306
+ address: str,
307
+ port: int = 853,
308
+ verify: Union[bool, str] = True,
309
+ server_hostname: Optional[str] = None,
310
+ ):
311
+ super().__init__(address, port)
312
+ self.verify = verify
313
+ self.server_hostname = server_hostname
314
+
315
+ def kind(self):
316
+ return "DoQ"
317
+
318
+ def query(
319
+ self,
320
+ request: dns.message.QueryMessage,
321
+ timeout: float,
322
+ source: Optional[str],
323
+ source_port: int,
324
+ max_size: bool = False,
325
+ one_rr_per_rrset: bool = False,
326
+ ignore_trailing: bool = False,
327
+ ) -> dns.message.Message:
328
+ return dns.query.quic(
329
+ request,
330
+ self.address,
331
+ port=self.port,
332
+ timeout=timeout,
333
+ one_rr_per_rrset=one_rr_per_rrset,
334
+ ignore_trailing=ignore_trailing,
335
+ verify=self.verify,
336
+ server_hostname=self.server_hostname,
337
+ )
338
+
339
+ async def async_query(
340
+ self,
341
+ request: dns.message.QueryMessage,
342
+ timeout: float,
343
+ source: Optional[str],
344
+ source_port: int,
345
+ max_size: bool,
346
+ backend: dns.asyncbackend.Backend,
347
+ one_rr_per_rrset: bool = False,
348
+ ignore_trailing: bool = False,
349
+ ) -> dns.message.Message:
350
+ return await dns.asyncquery.quic(
351
+ request,
352
+ self.address,
353
+ port=self.port,
354
+ timeout=timeout,
355
+ one_rr_per_rrset=one_rr_per_rrset,
356
+ ignore_trailing=ignore_trailing,
357
+ verify=self.verify,
358
+ server_hostname=self.server_hostname,
359
+ )
shared/package-files/56/56496724da7238138ed04b02aa5dfd17e03f3830063abcc620bc2f92b5436833/blob ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Machinery for documenting traitlets config options with Sphinx.
2
+
3
+ This includes:
4
+
5
+ - A Sphinx extension defining directives and roles for config options.
6
+ - A function to generate an rst file given an Application instance.
7
+
8
+ To make this documentation, first set this module as an extension in Sphinx's
9
+ conf.py::
10
+
11
+ extensions = [
12
+ # ...
13
+ 'traitlets.config.sphinxdoc',
14
+ ]
15
+
16
+ Autogenerate the config documentation by running code like this before
17
+ Sphinx builds::
18
+
19
+ from traitlets.config.sphinxdoc import write_doc
20
+ from myapp import MyApplication
21
+
22
+ writedoc('config/options.rst', # File to write
23
+ 'MyApp config options', # Title
24
+ MyApplication()
25
+ )
26
+
27
+ The generated rST syntax looks like this::
28
+
29
+ .. configtrait:: Application.log_datefmt
30
+
31
+ Description goes here.
32
+
33
+ Cross reference like this: :configtrait:`Application.log_datefmt`.
34
+ """
35
+ from collections import defaultdict
36
+ from textwrap import dedent
37
+
38
+ from traitlets import Undefined
39
+ from traitlets.utils.text import indent
40
+
41
+
42
+ def setup(app):
43
+ """Registers the Sphinx extension.
44
+
45
+ You shouldn't need to call this directly; configure Sphinx to use this
46
+ module instead.
47
+ """
48
+ app.add_object_type("configtrait", "configtrait", objname="Config option")
49
+ metadata = {"parallel_read_safe": True, "parallel_write_safe": True}
50
+ return metadata
51
+
52
+
53
+ def interesting_default_value(dv):
54
+ if (dv is None) or (dv is Undefined):
55
+ return False
56
+ if isinstance(dv, (str, list, tuple, dict, set)):
57
+ return bool(dv)
58
+ return True
59
+
60
+
61
+ def format_aliases(aliases):
62
+ fmted = []
63
+ for a in aliases:
64
+ dashes = "-" if len(a) == 1 else "--"
65
+ fmted.append(f"``{dashes}{a}``")
66
+ return ", ".join(fmted)
67
+
68
+
69
+ def class_config_rst_doc(cls, trait_aliases):
70
+ """Generate rST documentation for this class' config options.
71
+
72
+ Excludes traits defined on parent classes.
73
+ """
74
+ lines = []
75
+ classname = cls.__name__
76
+ for _, trait in sorted(cls.class_traits(config=True).items()):
77
+ ttype = trait.__class__.__name__
78
+
79
+ fullname = classname + "." + trait.name
80
+ lines += [".. configtrait:: " + fullname, ""]
81
+
82
+ help = trait.help.rstrip() or "No description"
83
+ lines.append(indent(dedent(help)) + "\n")
84
+
85
+ # Choices or type
86
+ if "Enum" in ttype:
87
+ # include Enum choices
88
+ lines.append(indent(":options: " + ", ".join("``%r``" % x for x in trait.values)))
89
+ else:
90
+ lines.append(indent(":trait type: " + ttype))
91
+
92
+ # Default value
93
+ # Ignore boring default values like None, [] or ''
94
+ if interesting_default_value(trait.default_value):
95
+ try:
96
+ dvr = trait.default_value_repr()
97
+ except Exception:
98
+ dvr = None # ignore defaults we can't construct
99
+ if dvr is not None:
100
+ if len(dvr) > 64:
101
+ dvr = dvr[:61] + "..."
102
+ # Double up backslashes, so they get to the rendered docs
103
+ dvr = dvr.replace("\\n", "\\\\n")
104
+ lines.append(indent(":default: ``%s``" % dvr))
105
+
106
+ # Command line aliases
107
+ if trait_aliases[fullname]:
108
+ fmt_aliases = format_aliases(trait_aliases[fullname])
109
+ lines.append(indent(":CLI option: " + fmt_aliases))
110
+
111
+ # Blank line
112
+ lines.append("")
113
+
114
+ return "\n".join(lines)
115
+
116
+
117
+ def reverse_aliases(app):
118
+ """Produce a mapping of trait names to lists of command line aliases."""
119
+ res = defaultdict(list)
120
+ for alias, trait in app.aliases.items():
121
+ res[trait].append(alias)
122
+
123
+ # Flags also often act as aliases for a boolean trait.
124
+ # Treat flags which set one trait to True as aliases.
125
+ for flag, (cfg, _) in app.flags.items():
126
+ if len(cfg) == 1:
127
+ classname = list(cfg)[0]
128
+ cls_cfg = cfg[classname]
129
+ if len(cls_cfg) == 1:
130
+ traitname = list(cls_cfg)[0]
131
+ if cls_cfg[traitname] is True:
132
+ res[classname + "." + traitname].append(flag)
133
+
134
+ return res
135
+
136
+
137
+ def write_doc(path, title, app, preamble=None):
138
+ """Write a rst file documenting config options for a traitlets application.
139
+
140
+ Parameters
141
+ ----------
142
+ path : str
143
+ The file to be written
144
+ title : str
145
+ The human-readable title of the document
146
+ app : traitlets.config.Application
147
+ An instance of the application class to be documented
148
+ preamble : str
149
+ Extra text to add just after the title (optional)
150
+ """
151
+ trait_aliases = reverse_aliases(app)
152
+ with open(path, "w") as f:
153
+ f.write(title + "\n")
154
+ f.write(("=" * len(title)) + "\n")
155
+ f.write("\n")
156
+ if preamble is not None:
157
+ f.write(preamble + "\n\n")
158
+
159
+ for c in app._classes_inc_parents():
160
+ f.write(class_config_rst_doc(c, trait_aliases))
161
+ f.write("\n")
shared/package-files/56/564c14cab191be17a8429c304e53fe65b464a83d6175f5d304e3232bab785e97/blob ADDED
@@ -0,0 +1,1505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import builtins
5
+ import collections
6
+ import dataclasses
7
+ import enum
8
+ import functools
9
+ import importlib
10
+ import inspect
11
+ import itertools
12
+ import logging
13
+ import math
14
+ import os
15
+ import re
16
+ import sys
17
+ import textwrap
18
+ import types
19
+ import weakref
20
+ from inspect import currentframe, getframeinfo
21
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
22
+ from weakref import ReferenceType
23
+
24
+
25
+ try:
26
+ import numpy as np
27
+ except ModuleNotFoundError:
28
+ np = None # type: ignore[assignment]
29
+
30
+ import torch
31
+ import torch.utils._device
32
+ from torch._dynamo.source import (
33
+ is_from_local_source,
34
+ TensorProperty,
35
+ TensorPropertySource,
36
+ )
37
+
38
+ from torch._guards import (
39
+ DuplicateInputs,
40
+ Guard,
41
+ GuardBuilderBase,
42
+ GuardEnvExpr,
43
+ GuardSource,
44
+ Source,
45
+ )
46
+
47
+ from torch._logging import structured
48
+ from torch.fx.experimental.symbolic_shapes import (
49
+ EqualityConstraint,
50
+ is_symbolic,
51
+ SYMPY_INTERP,
52
+ )
53
+ from torch.utils._traceback import format_frame, report_compile_source_on_error
54
+ from torch.utils.weak import TensorWeakRef
55
+
56
+ from . import config, convert_frame, exc, mutation_guard
57
+ from .eval_frame import set_guard_error_hook
58
+ from .source import AttrSource, DefaultsSource, LocalSource, TypeSource
59
+ from .types import CacheEntry, ExtraState, GuardedCode, GuardFail, GuardFn # noqa: F401
60
+ from .utils import (
61
+ common_constant_types,
62
+ dict_keys_repr,
63
+ guard_failures,
64
+ istype,
65
+ key_is_id,
66
+ key_to_id,
67
+ orig_code_map,
68
+ tensor_always_has_static_shape,
69
+ tuple_iterator_getitem,
70
+ tuple_iterator_len,
71
+ )
72
+
73
+ log = logging.getLogger(__name__)
74
+ guards_log = torch._logging.getArtifactLogger(__name__, "guards")
75
+ recompiles_log = torch._logging.getArtifactLogger(__name__, "recompiles")
76
+ recompiles_verbose_log = torch._logging.getArtifactLogger(
77
+ __name__, "recompiles_verbose"
78
+ )
79
+ verbose_guards_log = torch._logging.getArtifactLogger(__name__, "verbose_guards")
80
+
81
+ TensorGuards = torch._C._dynamo.guards.TensorGuards
82
+ check_obj_id = torch._C._dynamo.guards.check_obj_id
83
+ check_type_id = torch._C._dynamo.guards.check_type_id
84
+ dict_version = torch._C._dynamo.guards.dict_version
85
+
86
+
87
+ # For user stack printing
88
+ @functools.lru_cache(None)
89
+ def uninteresting_files():
90
+ import torch._dynamo.external_utils
91
+
92
+ mods = [
93
+ torch._dynamo.external_utils,
94
+ ]
95
+ return {inspect.getfile(m) for m in mods}
96
+
97
+
98
+ CLOSURE_VARS = {
99
+ "___check_type_id": check_type_id,
100
+ "___check_obj_id": check_obj_id,
101
+ "___odict_getitem": collections.OrderedDict.__getitem__,
102
+ "___key_to_id": key_to_id,
103
+ "___dict_version": dict_version,
104
+ "___dict_contains": lambda a, b: a in b,
105
+ "___tuple_iterator_len": tuple_iterator_len,
106
+ "___tuple_iterator_getitem": tuple_iterator_getitem,
107
+ "__math_isnan": math.isnan,
108
+ "__numpy_isnan": None if np is None else np.isnan,
109
+ "inf": float("inf"),
110
+ "__load_module": importlib.import_module,
111
+ "utils_device": torch.utils._device,
112
+ "device": torch.device,
113
+ "___from_numpy":
114
+ # If not numpy array, piggy back on e.g. tensor guards to check type
115
+ (lambda a: torch.as_tensor(a) if isinstance(a, (np.generic, np.ndarray)) else a),
116
+ "torch": torch,
117
+ "inspect": inspect,
118
+ }
119
+
120
+ if sys.version_info[:2] <= (3, 8):
121
+ # [Note: Python Version <= 3.8]
122
+ # This branch should be dropped when we drop support for Python 3.8.
123
+ # Reason: 'ast.unparse' function was introduced in Python 3.9.
124
+
125
+ try:
126
+ import astunparse # type: ignore[import]
127
+
128
+ def _ast_unparse(node: ast.AST) -> str:
129
+ return astunparse.unparse(node).replace("\n", "")
130
+
131
+ HAS_UNPARSE_FUNCTIONS = True
132
+ except ImportError:
133
+ HAS_UNPARSE_FUNCTIONS = False
134
+ pass
135
+ else:
136
+ HAS_UNPARSE_FUNCTIONS = True
137
+
138
+ def _ast_unparse(node: ast.AST) -> str:
139
+ return ast.unparse(node).replace("\n", "")
140
+
141
+
142
+ def strip_function_call(name):
143
+ """
144
+ "___odict_getitem(a, 1)" => "a"
145
+ "a.layers[slice(2)][0]._xyz" ==> "a"
146
+ "getattr(a.layers[slice(2)][0]._abc, '0')" ==> "a"
147
+ "getattr(getattr(a.x[3], '0'), '3')" ==> "a"
148
+ "a.layers[slice(None, -1, None)][0]._xyz" ==> "a"
149
+ """
150
+ # recursively find valid object name in function
151
+ valid_name = re.compile("[A-Za-z_].*")
152
+ curr = ""
153
+ for char in name:
154
+ if char in " (":
155
+ curr = ""
156
+ elif char in "),[]":
157
+ if curr and curr != "None" and valid_name.match(curr):
158
+ return strip_function_call(curr)
159
+ else:
160
+ curr += char
161
+
162
+ return strip_getattr_getitem(name)
163
+
164
+
165
+ def strip_getattr_getitem(name):
166
+ """
167
+ "a[1]" => "a"
168
+ "a.foo" => "a"
169
+ """
170
+ return re.split(r"[.\[]", name)[0]
171
+
172
+
173
+ def get_verbose_code_part(code_part, guard):
174
+ extra = ""
175
+ if guard.user_stack:
176
+ for fs in reversed(guard.user_stack):
177
+ if fs.filename not in uninteresting_files():
178
+ extra = f" # {format_frame(fs, line=True)}"
179
+ break
180
+ elif guard.stack:
181
+ extra = f" # {format_frame(guard.stack.summary()[-1])}"
182
+
183
+ return f"{code_part:<60}{extra}"
184
+
185
+
186
+ def convert_to_concrete_values(size_or_stride):
187
+ converted: List[Optional[int]] = []
188
+ for dim in size_or_stride:
189
+ if not is_symbolic(dim):
190
+ converted.append(dim)
191
+ else:
192
+ assert isinstance(dim, torch.SymInt)
193
+ converted.append(dim.node.maybe_as_int())
194
+ return converted
195
+
196
+
197
+ def get_tensor_guard_code_part(value, name, sizes, strides):
198
+ pytype = type(value)
199
+ dispatch_key = (
200
+ torch._C._dispatch_keys(value) | torch._C._dispatch_tls_local_include_set()
201
+ ) - torch._C._dispatch_tls_local_exclude_set()
202
+ dtype = value.dtype
203
+ device_index = value.device.index
204
+ requires_grad = value.requires_grad
205
+ guard_str = (
206
+ f"check_tensor({name}, {pytype.__qualname__}, {dispatch_key}, {dtype}, "
207
+ f"device={device_index}, requires_grad={requires_grad}, size={sizes}, stride={strides})"
208
+ )
209
+ return guard_str
210
+
211
+
212
+ # The ready to eval generated code (possibly multiple parts) for a guard, plus
213
+ # the original guard object that created it for provenance
214
+ @dataclasses.dataclass
215
+ class GuardCodeList:
216
+ code_list: List[str]
217
+ guard: Guard
218
+
219
+
220
+ class GuardBuilder(GuardBuilderBase):
221
+ def __init__(
222
+ self,
223
+ id_ref: Callable[[Any], str],
224
+ source_ref: Callable[[Source], str],
225
+ lookup_weakrefs: Callable[[object], ReferenceType[object]],
226
+ local_scope: Dict[str, object],
227
+ global_scope: Dict[str, object],
228
+ check_fn_manager: CheckFunctionManager,
229
+ ):
230
+ self.id_ref = id_ref
231
+ self.source_ref = source_ref
232
+ self.lookup_weakrefs = lookup_weakrefs
233
+ self.scope: Dict[str, Dict[str, object]] = {"L": local_scope, "G": global_scope}
234
+ self.scope["__builtins__"] = builtins.__dict__.copy()
235
+ for (
236
+ name,
237
+ package_module,
238
+ ) in torch.package.package_importer._package_imported_modules.items():
239
+ name = name.replace(">", "_").replace("<", "_").replace(".", "_dot_")
240
+ # Write the package module into the scope so that we can import it
241
+ self.scope["__builtins__"][name] = package_module
242
+ # Write the demangled name to the scope so that we can use it
243
+ self.scope[name] = package_module
244
+
245
+ self.argnames: List[str] = []
246
+ # Code is python expression strings generated for each guard
247
+ self.code: List[GuardCodeList] = []
248
+ # shape_env_code is only used by builder and is used for
249
+ # shape env code. This exists only because we need to make sure
250
+ # shape env guards get run after tensor match guards (since the
251
+ # tensor match guards make sure we actually have tensors)
252
+ self.shape_env_code: List[GuardCodeList] = []
253
+
254
+ # [Note - On Eager Tensor Guards]
255
+ # Most of the time, we generate Python code in a guard to directly
256
+ # check various properties. However, tensors are a bit special;
257
+ # it is too slow to check their properties one-by-one in Python.
258
+ # Instead, there is a C++ function TensorGuards.check which takes
259
+ # all of the tensor arguments and checks them all against compile-time
260
+ # examples entirely in C++. Thus, every time we process a
261
+ # TENSOR_MATCH guard, we just add another entry to
262
+ # tensor_check_names/tensor_check_examples, saying "for this local,
263
+ # check it against this example", and it all ends up getting
264
+ # swept up into a single call to ___check_tensors. Invariant:
265
+ # len(tensor_check_names) == len(tensor_check_examples).
266
+ # TODO: something here
267
+ self.tensor_check_names: List[str] = []
268
+ self.tensor_check_examples: List[torch.Tensor] = []
269
+ self.tensor_check_guards: List[Guard] = []
270
+
271
+ self.check_fn_manager: CheckFunctionManager = check_fn_manager
272
+ # Keep track of weak references of objects with ID_MATCH guard. This
273
+ # info is stored alongside optimized_code and check_fn and is used to
274
+ # limit the number of cache entries with same ID_MATCH'd object.
275
+ self.id_matched_objs: Dict[str, ReferenceType[object]] = {}
276
+
277
+ # Warning: use this with care! This lets you access what the current
278
+ # value of the value you are guarding on is. You probably don't want
279
+ # to actually durably save this value though (because it's specific
280
+ # to this frame!) Instead, you should be reading out some property
281
+ # (like its type) which is what you permanently install into the
282
+ # guard code.
283
+ def get(self, name: str) -> Any:
284
+ return eval(name, self.scope, CLOSURE_VARS)
285
+
286
+ # Registers the usage of the source name referenced by the
287
+ # string (or stored in the Guard) as being guarded upon. It's important
288
+ # to call this before generating some code that makes use of 'guard',
289
+ # because without this call, we won't actually bind the variable
290
+ # you reference in the actual guard closure (oops!)
291
+ def arg_ref(self, guard: Union[str, Guard]) -> str:
292
+ name: str
293
+ if isinstance(guard, str):
294
+ name = guard
295
+ else:
296
+ name = guard.name
297
+ base = strip_getattr_getitem(strip_function_call(name))
298
+ if base not in self.argnames:
299
+ if re.match(r"[a-zA-Z0-9_]+", base):
300
+ if re.match(r"^\d+$", base):
301
+ log.warning("invalid var name: %s", guard)
302
+ self.argnames.append(base)
303
+
304
+ return name
305
+
306
+ def _guard_on_attribute(self, guard: Guard, attr_name: str, guard_fn):
307
+ attr_source = AttrSource(guard.originating_source, attr_name)
308
+ # Copy the stack info
309
+ new_guard = Guard(
310
+ attr_source, guard_fn, stack=guard.stack, user_stack=guard.user_stack
311
+ )
312
+ new_guard.create(self)
313
+
314
+ def TYPE_MATCH(self, guard: Guard) -> None:
315
+ # ___check_type_id is same as `id(type(x)) == y`
316
+ t = type(self.get(guard.name))
317
+ obj_id = self.id_ref(t)
318
+ code = f"___check_type_id({self.arg_ref(guard)}, {obj_id})"
319
+ self._produce_guard_code(guard, [code])
320
+
321
+ def DICT_VERSION(self, guard: Guard):
322
+ # ___check_dict_version is same as `dict_version(x) == y`
323
+ ref = self.arg_ref(guard)
324
+ version = dict_version(self.get(guard.name))
325
+ code = f"___dict_version({ref}) == {version}"
326
+ self._produce_guard_code(guard, [code])
327
+
328
+ def DICT_CONTAINS(self, guard: Guard, key: str, invert: bool):
329
+ dict_ref = self.arg_ref(guard)
330
+
331
+ maybe_not = "not " if invert else ""
332
+ code = f"{maybe_not}___dict_contains({key!r}, {dict_ref})"
333
+ return self._produce_guard_code(guard, [code])
334
+
335
+ def BOOL_FALSE(self, guard: Guard):
336
+ # Guard on the runtime value being 'False',
337
+ # can be faster than seemingly equivalent checks like DICT_KEYS for empty dict
338
+ #
339
+ # WARNING: this guard is not safe to use generally. It only works if the runtime
340
+ # value is of a type that supports bool(), and some types e.g. Tensor do not.
341
+ # Only use this guard in cases you can guarantee the runtime type will be friendly.
342
+ # (e.g. Specialized NNModule with mutation protection via setattr)
343
+ #
344
+ # Why not simply check the runtime type inside this guard? It's slow enough to defeat
345
+ # the purpose of using this guard, which itself is supposed to be a faster alternative
346
+ # to DICT_KEYS.
347
+ ref = self.arg_ref(guard)
348
+ code = f"not {ref}"
349
+ self._produce_guard_code(guard, [code])
350
+
351
+ def ID_MATCH(self, guard: Guard):
352
+ # ___check_obj_id is same as `id(x) == y`
353
+ if isinstance(guard.originating_source, TypeSource):
354
+ # optional optimization to produce cleaner/faster guard code
355
+ return self.TYPE_MATCH(
356
+ Guard(guard.originating_source.base, GuardBuilder.TYPE_MATCH) # type: ignore[arg-type]
357
+ )
358
+
359
+ ref = self.arg_ref(guard)
360
+ val = self.get(guard.name)
361
+ code = f"___check_obj_id({ref}, {self.id_ref(val)})"
362
+ self._produce_guard_code(guard, [code])
363
+
364
+ # Keep track of ID_MATCH'd objects. This will be used to modify the
365
+ # cache size logic
366
+ if isinstance(guard.originating_source, LocalSource):
367
+ # TODO(janimesh) - This is currently restricted to nn.Module objects
368
+ # because many other ID_MATCH'd objects fail - like DeviceMesh.
369
+ # Increase the scope of ID_MATCH'd objects.
370
+ if isinstance(val, torch.nn.Module):
371
+ local_name = guard.originating_source.local_name
372
+ weak_id = self.lookup_weakrefs(val)
373
+ if weak_id is not None:
374
+ self.id_matched_objs[local_name] = weak_id
375
+
376
+ def NAME_MATCH(self, guard: Guard):
377
+ obj = self.get(guard.name)
378
+ self._guard_on_attribute(guard, "__name__", GuardBuilder.EQUALS_MATCH)
379
+
380
+ def DATA_PTR_MATCH(self, guard: Guard):
381
+ obj = self.get(guard.name)
382
+ code = f"{self.arg_ref(guard)}.data_ptr() == {obj.data_ptr()}"
383
+ self._produce_guard_code(guard, [code])
384
+
385
+ def HASATTR(self, guard: Guard):
386
+ assert isinstance(
387
+ guard.originating_source, AttrSource
388
+ ), f"invalid source {guard.name}"
389
+ base_source = guard.originating_source.base
390
+ base = base_source.name()
391
+ attr = guard.originating_source.member
392
+
393
+ ref = self.arg_ref(base)
394
+ val = hasattr(self.get(base), attr)
395
+ code = None
396
+ if val:
397
+ code = f"hasattr({ref}, {attr!r})"
398
+ else:
399
+ code = f"not hasattr({ref}, {attr!r})"
400
+
401
+ self._produce_guard_code(guard, [code], provided_guarded_object=self.get(base))
402
+
403
+ def FUNCTORCH_STACK_MATCH(self, guard: Guard):
404
+ # Invalidate functorch code if current level is different than
405
+ # the one when FX graph was generated
406
+ # if torch._C._functorch.peek_interpreter_stack() is not None:
407
+ cis = torch._functorch.pyfunctorch.retrieve_all_functorch_interpreters()
408
+ states = [ci.get_state() for ci in cis]
409
+ code = [f"torch._functorch.pyfunctorch.compare_functorch_state({states})"]
410
+ self._produce_guard_code(guard, code)
411
+
412
+ def EQUALS_MATCH(self, guard: Guard):
413
+ ref = self.arg_ref(guard)
414
+ val = self.get(guard.name)
415
+ t = type(val)
416
+ if np:
417
+ np_types: Tuple[Type[Any], ...] = (
418
+ np.int8,
419
+ np.int16,
420
+ np.int32,
421
+ np.int64,
422
+ np.uint8,
423
+ np.uint16,
424
+ np.uint32,
425
+ np.uint64,
426
+ np.float16,
427
+ np.float32,
428
+ np.float64,
429
+ )
430
+ else:
431
+ np_types = ()
432
+ ok_types = tuple(
433
+ common_constant_types
434
+ | {
435
+ type,
436
+ list,
437
+ tuple,
438
+ set,
439
+ frozenset,
440
+ slice,
441
+ range,
442
+ torch.Size,
443
+ *np_types,
444
+ }
445
+ )
446
+ if istype(val, dict):
447
+ assert all(
448
+ istype(x, ok_types) for x in itertools.chain(val.keys(), val.values())
449
+ )
450
+ else:
451
+ assert istype(
452
+ val,
453
+ ok_types,
454
+ ), f"Unexpected type {type(val)}, not in {ok_types}"
455
+
456
+ # Special case for nan because float("nan") == float("nan") evaluates to False
457
+ if istype(val, float) and math.isnan(val):
458
+ self.TYPE_MATCH(guard)
459
+ code = list()
460
+ code.append(f"__math_isnan({ref})")
461
+ self._produce_guard_code(guard, code)
462
+ return
463
+ # Python math library doesn't support complex nan, so we need to use numpy
464
+ elif istype(val, complex) and np.isnan(val):
465
+ self.TYPE_MATCH(guard)
466
+ code = list()
467
+ code.append(f"__numpy_isnan({ref})")
468
+ self._produce_guard_code(guard, code)
469
+ return
470
+
471
+ code = list()
472
+
473
+ # If matching equality against list/tuple, we must also check that
474
+ # the internal types match. (TODO: what about nested lists?)
475
+ if istype(val, (list, tuple)):
476
+ # NB: SEQUENCE_LENGTH takes care of the outer __check_type_id test
477
+ self.SEQUENCE_LENGTH(guard)
478
+
479
+ for idx, elem in enumerate(val):
480
+ code.append(
481
+ f"___check_type_id({ref}[{idx}], {self.id_ref(type(elem))})"
482
+ )
483
+ else:
484
+ # Add type check to prevent equality check between tensor and non-tensor.
485
+ self.TYPE_MATCH(guard)
486
+
487
+ if istype(val, torch.Size):
488
+ val = tuple(val)
489
+
490
+ # Code object can not be compared against their string representation
491
+ # I.e `eval(f"{compile('2+2','','exec')!r}")` raises SyntaxError
492
+ assert not istype(val, types.CodeType)
493
+
494
+ # TODO: It feels like it would be better to just implement our own
495
+ # equality test in C that handles all of the necessary type checking
496
+ # and NaN tests
497
+ code.append(f"{ref} == {val!r}")
498
+ self._produce_guard_code(guard, code)
499
+
500
+ def CONSTANT_MATCH(self, guard: Guard):
501
+ val = self.get(guard.name)
502
+ if istype(val, (bool, type(None), types.CodeType)):
503
+ self.ID_MATCH(guard)
504
+ else:
505
+ self.EQUALS_MATCH(guard)
506
+
507
+ def NN_MODULE(self, guard: Guard):
508
+ self.ID_MATCH(guard)
509
+ ref = self.arg_ref(guard)
510
+ val = self.get(guard.name)
511
+
512
+ def setup_guard():
513
+ assert istype(val.training, bool)
514
+ self._guard_on_attribute(guard, "training", GuardBuilder.CONSTANT_MATCH)
515
+
516
+ if hasattr(val, "training"):
517
+ # There are cases where a monkeypatched object has a guard made between __new__ and __init__
518
+ setup_guard()
519
+ else:
520
+ exc.unimplemented(f"Guard setup for uninitialized class {type(val)}")
521
+
522
+ def FUNCTION_MATCH(self, guard: Guard):
523
+ """things like torch.add and user defined functions"""
524
+ if guard.is_local():
525
+ return self.ID_MATCH(guard)
526
+
527
+ def CLOSURE_MATCH(self, guard: Guard):
528
+ """matches a closure by __code__ id."""
529
+ if guard.is_local():
530
+ val = self.get(guard.name)
531
+ # Strictly only want user-defined functions
532
+ if type(val) == types.FunctionType and hasattr(val, "__code__"):
533
+ self._guard_on_attribute(guard, "__code__", GuardBuilder.HASATTR)
534
+ self._guard_on_attribute(guard, "__code__", GuardBuilder.FUNCTION_MATCH)
535
+ else:
536
+ self.FUNCTION_MATCH(guard)
537
+
538
+ def BUILTIN_MATCH(self, guard: Guard):
539
+ return self.FUNCTION_MATCH(guard)
540
+
541
+ def PYMODULE_MATCH(self, guard: Guard):
542
+ return self.FUNCTION_MATCH(guard)
543
+
544
+ def SEQUENCE_LENGTH(self, guard):
545
+ # This guard is used to check lenght of PySequence objects like list,
546
+ # tuple, collections.deque etc
547
+ ref = self.arg_ref(guard)
548
+ value = self.get(guard.name)
549
+ t = type(value)
550
+
551
+ self.TYPE_MATCH(guard)
552
+ code = list()
553
+ if len(value) == 0:
554
+ code.append(f"not {ref}")
555
+ else:
556
+ code.append(f"len({ref}) == {len(value)}")
557
+
558
+ self._produce_guard_code(guard, code)
559
+
560
+ def DICT_LENGTH(self, guard):
561
+ self.SEQUENCE_LENGTH(guard)
562
+
563
+ def TUPLE_ITERATOR_LEN(self, guard):
564
+ ref = self.arg_ref(guard)
565
+ value = self.get(guard.name)
566
+ t = type(value)
567
+
568
+ self.TYPE_MATCH(guard)
569
+ code = list()
570
+ code.append(f"___tuple_iterator_len({ref}) == {tuple_iterator_len(value)}")
571
+
572
+ self._produce_guard_code(guard, code)
573
+
574
+ # TODO(voz): Deduplicate w/ AOTAutograd dupe input guards
575
+ def DUPLICATE_INPUT(self, guard, source_b):
576
+ ref_a = self.arg_ref(guard)
577
+ ref_b = self.arg_ref(source_b.name())
578
+
579
+ code = [f"{ref_b} is {ref_a}"]
580
+ self._produce_guard_code(guard, code)
581
+
582
+ def DICT_KEYS(self, guard):
583
+ # Guard on the keys and their order
584
+ ref = self.arg_ref(guard)
585
+ value = self.get(guard.name)
586
+ t = type(value)
587
+
588
+ self.TYPE_MATCH(guard)
589
+ code = list()
590
+ any_key_is_id = any(key_is_id(k) for k in value.keys())
591
+ const_keys_repr = dict_keys_repr(
592
+ key_to_id(value),
593
+ local=is_from_local_source(guard.originating_source),
594
+ )
595
+ if any_key_is_id:
596
+ code.append(f"___key_to_id({ref}) == {const_keys_repr}")
597
+ else:
598
+ code.append(f"list({ref}.keys()) == {const_keys_repr}")
599
+
600
+ self._produce_guard_code(guard, code)
601
+
602
+ def WEAKREF_ALIVE(self, guard):
603
+ self._produce_guard_code(guard, [f"{self.arg_ref(guard)} is not None"])
604
+
605
+ def NN_MODULE_PARAM_NAMES(self, guard):
606
+ ref = self.arg_ref(guard)
607
+ value = self.get(guard.name)
608
+ t = type(value)
609
+ keys = {k for k, v in value.named_parameters()}
610
+
611
+ self.TYPE_MATCH(guard)
612
+ code = list()
613
+ code.append(f"{{k for k, v in {ref}.named_parameters()}} == {keys!r}")
614
+
615
+ self._produce_guard_code(guard, code)
616
+
617
+ def DICT_CONST_KEYS(self, guard):
618
+ """Constant keys match"""
619
+ ref = self.arg_ref(guard)
620
+ value = self.get(guard.name)
621
+ t = type(value)
622
+
623
+ self.TYPE_MATCH(guard)
624
+ code = list()
625
+ code.append(f"list({ref}.keys()) == {list(value.keys())!r}")
626
+
627
+ self._produce_guard_code(guard, code)
628
+
629
+ def OBJECT_MUTATION(self, guard: Guard):
630
+ mutation_guard.watch(self.get(guard.name), self.check_fn_manager)
631
+
632
+ def GRAD_MODE(self, guard: Guard):
633
+ pass # we always guard on this via GlobalStateGuard()
634
+
635
+ def DETERMINISTIC_ALGORITHMS(self, guard: Guard):
636
+ pass # we always guard on this via GlobalStateGuard()
637
+
638
+ def TORCH_FUNCTION_STATE(self, guard: Guard):
639
+ pass # we always guard on this via GlobalStateGuard()
640
+
641
+ def DEFAULT_DEVICE(self, guard: Guard):
642
+ """Guard on CURRENT_DEVICE per torch.utils._device"""
643
+ assert guard.source is GuardSource.GLOBAL
644
+ import torch.utils._device as m
645
+
646
+ self._produce_guard_code(
647
+ guard, [f"utils_device.CURRENT_DEVICE == {m.CURRENT_DEVICE!r}"]
648
+ )
649
+
650
+ def BACKEND_MATCH(self, guard: Guard):
651
+ """Guard on backend matching based on id of current_backend"""
652
+ assert guard.source is GuardSource.GLOBAL
653
+ backend_id = (
654
+ f"{id(torch._dynamo.eval_frame.guarded_backend_cache.current_backend)}"
655
+ )
656
+ code = [f"___check_current_backend({backend_id})"]
657
+ self._produce_guard_code(guard, code)
658
+
659
+ def SHAPE_ENV(self, guard: Guard):
660
+ # Let's handle ShapeEnv guards. To do this, we will resolve
661
+ # shape variables to sources from tracked_fakes. This must happen after
662
+ # tensor checks.
663
+ assert guard.name == ""
664
+ output_graph = self.check_fn_manager.output_graph
665
+ # NB: self.output_graph can be None in the debug_nops tests
666
+ fs = output_graph.tracked_fakes
667
+ input_contexts = [a.symbolic_context for a in fs]
668
+
669
+ def get_sources(t_id, dim):
670
+ # Looks up base sources mapped to a tensor id and uses them to create
671
+ # sources for the corresponding tensor dimension.
672
+ return [
673
+ TensorPropertySource(source, TensorProperty.SIZE, dim)
674
+ for source in output_graph.tracked_fakes_id_to_source[t_id]
675
+ ]
676
+
677
+ if output_graph.export_constraints:
678
+ from sympy import Symbol
679
+
680
+ source_pairs: List[Tuple[Source, Source]] = []
681
+ derived_equalities: List[ # type: ignore[type-arg]
682
+ Tuple[Source, Union[Source, Symbol], Callable]
683
+ ] = []
684
+ phantom_symbols: Dict[str, Symbol] = {}
685
+ for constraint in output_graph.export_constraints:
686
+ if constraint.t_id in output_graph.tracked_fakes_id_to_source:
687
+ torch.export.dynamic_shapes._process_equalities(
688
+ constraint,
689
+ get_sources,
690
+ output_graph.shape_env,
691
+ source_pairs,
692
+ derived_equalities,
693
+ phantom_symbols,
694
+ )
695
+ else:
696
+ log.warning("Untracked tensor used in export constraints")
697
+ equalities_inputs = EqualityConstraint(
698
+ source_pairs=source_pairs,
699
+ derived_equalities=derived_equalities,
700
+ phantom_symbols=list(phantom_symbols.values()),
701
+ warn_only=False,
702
+ )
703
+ else:
704
+ equalities_inputs = None
705
+ guards = output_graph.shape_env.produce_guards(
706
+ [a.fake for a in fs],
707
+ [a.source for a in fs],
708
+ input_contexts=input_contexts,
709
+ equalities_inputs=equalities_inputs,
710
+ source_ref=self.source_ref,
711
+ # Export keeps static.
712
+ ignore_static=(not self.check_fn_manager.output_graph.export),
713
+ )
714
+ # When exporting, we may work with the shape constraints some more in
715
+ # postprocessing, so don't freeze yet
716
+ if not self.check_fn_manager.output_graph.export:
717
+ output_graph.shape_env.freeze()
718
+ for shape_guard in guards:
719
+ self._produce_guard_code(guard, [shape_guard], shape_env=True)
720
+
721
+ def TENSOR_MATCH(self, guard: Guard, value=None):
722
+ if guard.is_nn_module() or guard.originating_source.is_dict_key():
723
+ self.ID_MATCH(guard)
724
+ else:
725
+ if isinstance(value, TensorWeakRef):
726
+ value = value()
727
+
728
+ value = value if value is not None else self.get(guard.name)
729
+ assert isinstance(value, torch.Tensor)
730
+
731
+ tensor_name = self.arg_ref(guard)
732
+ # [Note - On Export Tensor Guards]
733
+ #
734
+ # In eager mode, tensor guards are evaluated through C++, in guards.cpp
735
+ # see [Note - On Eager Tensor Guards] for more info.
736
+ #
737
+ # In export mode, we instead maintain parallel logic between C++ and python
738
+ # here, with an exception of checking the dispatch key - with the idea that a dispatch key
739
+ # is an entirely runtime notion that would make no sense to keep in an exported graph.
740
+ #
741
+ # Now, this idea is okay, but to paraphrase @ezyang, this mental model is sufficient for now, although
742
+ # not entirely true.
743
+ # For example, suppose one of the input tensors had the negative dispatch key.
744
+ # You should end up with a graph that is specialized for tensors that have a negative dispatch key.
745
+ # If you allow a Tensor that does NOT have this bit set, you will accidentally run it "as if" it were negated.
746
+ # Now, negative key only shows up for complex numbers, and most likely, the exported to target doesn't
747
+ # support this feature at all, but the point stands that :some: tensor state only shows up on dispatch key.
748
+ # TODO(voz): Either populate a dispatch_key check into the guards, or error on users passing in an unsupported
749
+ # subset of keys during export.
750
+ #
751
+ # The list of tensor fields and calls we care about can be found in `terms` below.
752
+ # TODO(voz): We are missing storage offset in all our tensor guards?
753
+ code: List[str] = list()
754
+ if self.check_fn_manager.output_graph.export:
755
+ self.TYPE_MATCH(guard)
756
+ terms = [
757
+ "dtype",
758
+ "device",
759
+ "requires_grad",
760
+ "ndimension()",
761
+ ]
762
+
763
+ for term in terms:
764
+ real_value = self.get(tensor_name + "." + term)
765
+ if istype(real_value, (torch.device, torch.dtype)):
766
+ # copy pasted from EQUALS_MATCH
767
+ code.append(f"str({tensor_name}.{term}) == {str(real_value)!r}")
768
+ else:
769
+ code.append(f"{tensor_name}.{term} == {real_value}")
770
+ else:
771
+ self.tensor_check_names.append(tensor_name)
772
+ self.tensor_check_examples.append(value)
773
+ self.tensor_check_guards.append(guard)
774
+
775
+ # A frame is valid for reuse with dynamic dimensions if the new
776
+ # (user-requested) dynamic dimensions are a subset of the old
777
+ # (already compiled) dynamic dimensions.
778
+ #
779
+ # It's a little non-obvious why you'd want this: in particular,
780
+ # if an already compiled frame matches all of the guards, why
781
+ # not just use it, why force a recompile?
782
+ #
783
+ # We force it for two reasons:
784
+ #
785
+ # - The user *required* us to compile with a new dynamic dimension,
786
+ # we should not ignore that and serve up the old, specialized
787
+ # frame. Listen to the user!
788
+ #
789
+ # - In fact, we are obligated to *raise an error* if we fail to
790
+ # make the requested dimension dynamic. If we don't
791
+ # recompile, we can't tell if that dimension can actually be
792
+ # made dynamic.
793
+ #
794
+ # If the new dynamic dims are a subset of the old, we already know
795
+ # we can make them dynamic (since we made them dynamic in old).
796
+ # This is slightly unsound, because maybe your input size is
797
+ # [s0, s0, s1] and so you can do it dynamic if you say dynamic
798
+ # dims {0, 1, 2} but you can't if you only do {0, 2} (because now
799
+ # the second s0 is specialized). But we're not entirely sure if
800
+ # this is a good idea anyway lol... (if you want to try removing
801
+ # this logic, be my guest! -- ezyang 2024)
802
+ #
803
+ assert guard.source is not None
804
+ static, reason = tensor_always_has_static_shape(
805
+ value, is_tensor=True, guard_source=guard.source
806
+ )
807
+ if not static:
808
+ if hasattr(value, "_dynamo_dynamic_indices"):
809
+ code.append(
810
+ f"(({tensor_name}._dynamo_dynamic_indices.issubset({value._dynamo_dynamic_indices})) if hasattr({tensor_name}, '_dynamo_dynamic_indices') else True)" # noqa: B950
811
+ )
812
+ # In the case of us not having any dynamic dimension indices, we compiled the frame with no chance of
813
+ # raising for this specific tensor - and any inputs with more dynamic user directives specified must be recompiled.
814
+ else:
815
+ code.append(
816
+ f"hasattr({tensor_name}, '_dynamo_dynamic_indices') == False"
817
+ )
818
+ if len(code) > 0:
819
+ self._produce_guard_code(guard, code)
820
+
821
+ # A util that appends guarded code, or, in the case of export, adds data onto guards
822
+ def _produce_guard_code(
823
+ self, guard, code_list, provided_guarded_object=None, shape_env=False
824
+ ):
825
+ # WARNING: It is important that cur_frame/caller do NOT stay in
826
+ # the current frame, because they will keep things live longer
827
+ # than they should. See TestMisc.test_release_module_memory
828
+ cur_frame = currentframe()
829
+ assert cur_frame is not None
830
+ caller = cur_frame.f_back
831
+ del cur_frame
832
+ assert caller is not None
833
+ func_name = getframeinfo(caller)[2]
834
+ del caller
835
+ # We use func_name for export, so might as well get a nice defensive check out of it
836
+ assert func_name in dir(
837
+ self.__class__
838
+ ), f"_produce_guard_code must be called from inside GuardedCode. Called from {func_name}"
839
+
840
+ if shape_env:
841
+ self.shape_env_code.append(GuardCodeList(code_list, guard))
842
+ else:
843
+ self.code.append(GuardCodeList(code_list, guard))
844
+
845
+ # Not all guards have names, some can be installed globally (see asserts on HAS_GRAD)
846
+ if provided_guarded_object is None:
847
+ name_valid = guard.name is not None and guard.name != ""
848
+
849
+ guarded_object = self.get(guard.name) if name_valid else None
850
+ else:
851
+ guarded_object = provided_guarded_object
852
+
853
+ guarded_object_type = (
854
+ weakref.ref(type(guarded_object)) if guarded_object is not None else None
855
+ )
856
+ obj_ref = None
857
+ # Not necessary to have weakref for Enum type, but there is a bug that
858
+ # makes hasattr(guarded_object.__class__, "__weakref__") return True.
859
+ if hasattr(guarded_object.__class__, "__weakref__") and not isinstance(
860
+ guarded_object, enum.Enum
861
+ ):
862
+ obj_ref = weakref.ref(guarded_object)
863
+
864
+ guard.set_export_info(
865
+ func_name,
866
+ guarded_object_type,
867
+ code_list,
868
+ obj_ref,
869
+ )
870
+
871
+
872
+ # Common Sub-Expression Elimination for Python expressions.
873
+ #
874
+ # There are 2 steps to this pass:
875
+ # 1. Count the frequency of each sub-expression (i.e. inner
876
+ # node in the AST tree)
877
+ #
878
+ # 2. Replace those that occur more than once by a fresh variable 'v'.
879
+ # 'v' will be defined in the 'preface' list (output argument to
880
+ # 'NodeTransformer')
881
+ #
882
+ # NB: the use of 'ast.unparse' while visiting the nodes makes this pass
883
+ # quadratic on the depth of the tree.
884
+ #
885
+ # NB: this pass creates a new variable for each AST node that is repeated
886
+ # more than 'USE_THRESHOLD'. e.g. if 'a.b.c.d' is used 10 times, 'a.b.c'
887
+ # and 'a.b' are also used 10 times. So, there will be a new variable for
888
+ # each of them.
889
+ class PyExprCSEPass:
890
+ # Maximum number of times a given expression can be used without being
891
+ # replaced by a fresh variable.
892
+ USE_THRESHOLD = 1
893
+
894
+ # Ad-Hoc: AST nodes this pass focuses on.
895
+ ALLOWED_NODE_TYPES = (ast.Attribute, ast.Call, ast.Subscript)
896
+
897
+ @dataclasses.dataclass
898
+ class Config:
899
+ expr_count: Dict[str, int]
900
+ expr_to_name: Dict[str, str]
901
+
902
+ class ExprCounter(ast.NodeVisitor):
903
+ def __init__(self, config: PyExprCSEPass.Config) -> None:
904
+ self._config = config
905
+
906
+ def visit(self, node: ast.AST) -> Any:
907
+ if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES):
908
+ self._config.expr_count[_ast_unparse(node)] += 1
909
+ super().visit(node)
910
+
911
+ class Replacer(ast.NodeTransformer):
912
+ def __init__(
913
+ self,
914
+ config: PyExprCSEPass.Config,
915
+ gen_name: Callable[[], str],
916
+ ) -> None:
917
+ super().__init__()
918
+ self._config = config
919
+ self._gen_name = gen_name
920
+ self.preface: List[str] = []
921
+
922
+ def visit(self, node: ast.AST) -> Any:
923
+ if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES):
924
+ expr = _ast_unparse(node)
925
+
926
+ # Replacement only occurs if a given expression is used more
927
+ # than once.
928
+ if self._config.expr_count[expr] > PyExprCSEPass.USE_THRESHOLD:
929
+ if expr not in self._config.expr_to_name:
930
+ # Parent 'visit' is called so that we CSE the inner expressions first.
931
+ #
932
+ # The resulting expression is used as right-hand-side of the variable
933
+ # assignment. i.e. we are CSE-ing the children before the parents.
934
+ #
935
+ # Indexing still uses the old 'node', since that's what was counted
936
+ # by the 'NodeVisitor'.
937
+ node_ = super().visit(node)
938
+ expr_ = _ast_unparse(node_)
939
+ var_name = self._gen_name()
940
+ self.preface.append(f"{var_name} = {expr_}")
941
+ self._config.expr_to_name[expr] = var_name
942
+ else:
943
+ var_name = self._config.expr_to_name[expr]
944
+ return ast.Name(var_name, ast.Load())
945
+
946
+ return super().visit(node)
947
+
948
+ def __init__(self) -> None:
949
+ self._counter = 0
950
+ self._config = self.Config(
951
+ expr_count=collections.defaultdict(lambda: 0), expr_to_name={}
952
+ )
953
+
954
+ def _new_var(self, prefix: str = "_var") -> str:
955
+ name = f"{prefix}{self._counter}"
956
+ self._counter += 1
957
+ return name
958
+
959
+ def count(self, exprs: List[str]) -> None:
960
+ counter = self.ExprCounter(self._config)
961
+ for e in exprs:
962
+ try:
963
+ counter.visit(ast.parse(e))
964
+ except SyntaxError as ex:
965
+ log.exception("Failed to visit expr at line %s.\n%s", ex.lineno, e)
966
+ raise
967
+
968
+ def replace(self, expr: str) -> Tuple[List[str], str]:
969
+ replacer = self.Replacer(self._config, self._new_var)
970
+ new_node = replacer.visit(ast.parse(expr))
971
+ return replacer.preface, _ast_unparse(new_node)
972
+
973
+
974
+ def must_add_nn_module_guards(guard):
975
+ # For config.guard_nn_modules=False, we can skip all the guards that
976
+ # originate from inside of nn module except for a few categories.
977
+ return (
978
+ # Guard for defaults
979
+ isinstance(guard.originating_source, DefaultsSource)
980
+ # Guard using dict tags if the config flag is set
981
+ or (
982
+ config.guard_nn_modules_using_dict_tags
983
+ and guard.create_fn is GuardBuilder.NN_MODULE
984
+ )
985
+ )
986
+
987
+
988
+ class DeletedGuardFn:
989
+ pass
990
+
991
+
992
+ # NB: Naively, you'd expect this to only be a function that produces
993
+ # the callable that constitutes the guard. However, there is some
994
+ # delicate handling for invalidating this check function when the
995
+ # locals/globals get invalidated, so there's some extra state
996
+ # we have to hold in this manager class.
997
+ class CheckFunctionManager:
998
+ def __init__(
999
+ self,
1000
+ output_graph=None,
1001
+ guard_fail_fn: Optional[Callable[[GuardFail], None]] = None,
1002
+ ):
1003
+ guards = output_graph.guards if output_graph else None
1004
+ self._weakrefs: Dict[int, ReferenceType[object]] = {}
1005
+ self.output_graph = output_graph
1006
+ w_builder = None
1007
+
1008
+ def source_ref(source):
1009
+ guard_source = source.guard_source()
1010
+ if guard_source is GuardSource.CONSTANT:
1011
+ # No need to track constants
1012
+ return source.name()
1013
+ assert w_builder
1014
+ r_builder = w_builder()
1015
+ assert r_builder is not None
1016
+ return r_builder.arg_ref(source.name())
1017
+
1018
+ builder = GuardBuilder(
1019
+ self.id_ref,
1020
+ source_ref,
1021
+ self.lookup_weakrefs,
1022
+ output_graph.local_scope,
1023
+ output_graph.global_scope,
1024
+ self,
1025
+ )
1026
+
1027
+ # Break retain cycle. See test_release_scope_memory
1028
+ def cleanup_builder(weak_b):
1029
+ b = weak_b()
1030
+ if b:
1031
+ b.scope = None
1032
+
1033
+ # Break retain cycle. See test_release_input_memory
1034
+ w_builder = weakref.ref(builder, cleanup_builder)
1035
+
1036
+ for guard in sorted(guards or [], key=Guard.sort_key):
1037
+ if (
1038
+ not config.guard_nn_modules
1039
+ and guard.is_nn_module()
1040
+ # Default func args must be guarded on.
1041
+ # TODO: we could make use of 'DefaultsSource' and offer a .guard.is_defaults() API
1042
+ and "__defaults__" not in guard.name
1043
+ and "__kwdefaults__" not in guard.name
1044
+ and (config.skip_nnmodule_hook_guards or "hooks" not in guard.name)
1045
+ ):
1046
+ continue
1047
+
1048
+ guard.create(builder)
1049
+ self.check_fn = self.compile_check_fn(builder, guards, guard_fail_fn)
1050
+ # Keep track of weak references of objects with ID_MATCH guard. This
1051
+ # info is stored alongside optimized_code and check_fn and is used to
1052
+ # limit the number of cache entries with same ID_MATCH'd object.
1053
+ # TODO(janimesh) - Currently this information is stored as an attr on
1054
+ # the check_fn itself to avoid changing CacehEntry datastructure in
1055
+ # eval_frame.c. In future, we should probably replace check_fn with a
1056
+ # queryable data structure such that this information is already present
1057
+ # in some form.
1058
+ self.check_fn.id_matched_objs = builder.id_matched_objs
1059
+
1060
+ # NB - We have to very careful of cleaning up here. Because of the
1061
+ # invalidate function, we can create a weakref finalizer that keeps
1062
+ # `self` alive for very long. Sometimes by mistake, we can run
1063
+ # invalidate for a type/object (check id_ref method) that Python can
1064
+ # leak by design, preventing us from calling the finalizer. In that
1065
+ # case, the `self` will be alive even though the cache entry will be
1066
+ # deleted (check invalidate method), which can cause a memory leak,
1067
+ # e.g., not setting output_graph = None can keep hold of nn_modules.
1068
+ self._weakrefs.clear()
1069
+ self.output_graph = None
1070
+
1071
+ def compile_check_fn(self, builder, guards_out, guard_fail_fn):
1072
+ # see parallel handling of ".0" / "___implicit0" in _eval_frame.c
1073
+ largs = builder.argnames
1074
+ largs += ["**___kwargs_ignored"]
1075
+
1076
+ guards_log.debug("GUARDS:")
1077
+
1078
+ # Don't report this guard, it's always the same, useless!
1079
+ code_parts = ["___check_global_state()"]
1080
+ verbose_code_parts = code_parts[:]
1081
+ structured_guard_fns = []
1082
+
1083
+ def add_code_part(code_part, guard, log_only=False):
1084
+ verbose_code_part = get_verbose_code_part(code_part, guard)
1085
+ guards_log.debug("%s", verbose_code_part)
1086
+
1087
+ structured_guard_fns.append(
1088
+ lambda: {
1089
+ "code": code_part,
1090
+ "stack": structured.from_traceback(guard.stack.summary())
1091
+ if guard.stack
1092
+ else None,
1093
+ "user_stack": structured.from_traceback(guard.user_stack)
1094
+ if guard.user_stack
1095
+ else None,
1096
+ }
1097
+ )
1098
+
1099
+ if verbose_guards_log.isEnabledFor(logging.DEBUG):
1100
+ maybe_stack = ""
1101
+ maybe_user_stack = ""
1102
+ if guard is not None:
1103
+ if guard.stack:
1104
+ maybe_stack = f"\nStack:\n{''.join(guard.stack.format())}"
1105
+ if guard.user_stack:
1106
+ maybe_user_stack = (
1107
+ f"\nUser stack:\n{''.join(guard.user_stack.format())}"
1108
+ )
1109
+ verbose_guards_log.debug(
1110
+ "Guard: %s%s%s",
1111
+ code_part,
1112
+ maybe_stack,
1113
+ maybe_user_stack,
1114
+ )
1115
+
1116
+ if not log_only:
1117
+ code_parts.append(code_part)
1118
+ verbose_code_parts.append(verbose_code_part)
1119
+
1120
+ seen = set()
1121
+ for gcl in builder.code:
1122
+ for code in gcl.code_list:
1123
+ if code not in seen:
1124
+ add_code_part(code, gcl.guard)
1125
+ seen.add(code)
1126
+
1127
+ tensor_check_names = builder.tensor_check_names
1128
+ check_tensors_fn = None
1129
+ check_tensors_verbose_fn = None
1130
+ if tensor_check_names:
1131
+ assert (
1132
+ not self.output_graph.export
1133
+ ), "Illegal to set tensor_check_names in export."
1134
+ tensor_check_examples = builder.tensor_check_examples
1135
+
1136
+ dynamic_dims_sizes = [
1137
+ convert_to_concrete_values(
1138
+ self.output_graph.tensor_weakref_to_sizes_strides[t]["size"]
1139
+ )
1140
+ for t in tensor_check_examples
1141
+ ]
1142
+
1143
+ dynamic_dims_strides = [
1144
+ convert_to_concrete_values(
1145
+ self.output_graph.tensor_weakref_to_sizes_strides[t]["stride"]
1146
+ )
1147
+ for t in tensor_check_examples
1148
+ ]
1149
+
1150
+ tensor_guards = TensorGuards(
1151
+ *tensor_check_examples,
1152
+ dynamic_dims_sizes=dynamic_dims_sizes,
1153
+ dynamic_dims_strides=dynamic_dims_strides,
1154
+ )
1155
+ check_tensors_fn = tensor_guards.check
1156
+ check_tensors_verbose_fn = tensor_guards.check_verbose
1157
+ tensor_check_args = ", ".join(
1158
+ tensor_check_names + ["tensor_check_names=tensor_check_names"]
1159
+ )
1160
+ # Do this manually, to un-stagger the guards in log message
1161
+ code_parts.append(f"___check_tensors({tensor_check_args})")
1162
+ verbose_code_parts.append(f"___check_tensors({tensor_check_args})")
1163
+ tensor_check_guards = builder.tensor_check_guards
1164
+
1165
+ for i, name in enumerate(tensor_check_names):
1166
+ # This is a copy of what guards.cpp checks against
1167
+ # Keep this in sync with TensorCheck constructor
1168
+ t = tensor_check_examples[i]
1169
+ sizes = dynamic_dims_sizes[i]
1170
+ strides = dynamic_dims_strides[i]
1171
+ code_part = get_tensor_guard_code_part(t, name, sizes, strides)
1172
+ add_code_part(code_part, tensor_check_guards[i], log_only=True)
1173
+
1174
+ aotautograd_guards: List[GuardEnvExpr] = (
1175
+ self.output_graph.tracing_context.guards_context.aotautograd_guards
1176
+ if self.output_graph
1177
+ else []
1178
+ )
1179
+ for guard in aotautograd_guards:
1180
+ if isinstance(guard, DuplicateInputs):
1181
+ source_a = guard.input_source_a
1182
+ source_b = guard.input_source_b
1183
+ add_code_part(f"{source_a.name()} is {source_b.name()}", None)
1184
+ else:
1185
+ raise RuntimeError(f"Unknown GuardEnvExpr: {guard}")
1186
+
1187
+ # TODO: the "guard" here is actually just the top level SHAPE_ENV
1188
+ # which is useless. Get ShapeEnv to pass in more provenance.
1189
+ for gcl in builder.shape_env_code:
1190
+ for code in gcl.code_list:
1191
+ add_code_part(code, gcl.guard)
1192
+
1193
+ # OK, all done generating guards
1194
+ torch._logging.trace_structured(
1195
+ "dynamo_guards", payload_fn=lambda: [f() for f in structured_guard_fns]
1196
+ )
1197
+
1198
+ global_state = convert_frame.initial_global_state
1199
+ if global_state is None:
1200
+ # we should only hit this case in NopTests()
1201
+ global_state = convert_frame.GlobalStateGuard()
1202
+ closure_vars = {
1203
+ "___check_tensors": check_tensors_fn,
1204
+ "___check_tensors_verbose": check_tensors_verbose_fn,
1205
+ "___check_global_state": global_state.check,
1206
+ "___check_current_backend": torch._dynamo.eval_frame.check_current_backend,
1207
+ "tensor_check_names": tensor_check_names,
1208
+ **SYMPY_INTERP,
1209
+ **CLOSURE_VARS,
1210
+ }
1211
+
1212
+ unique_code_parts = list(unique(code_parts))
1213
+ make_guard_fn_args = ", ".join(closure_vars.keys())
1214
+ guard_body, pycode = build_guard_function(unique_code_parts, make_guard_fn_args)
1215
+
1216
+ if os.environ.get("TORCHDYNAMO_PRINT_GUARDS", None) == "1":
1217
+ print("GUARDS\n", guard_body)
1218
+
1219
+ out: Dict[str, Any] = dict()
1220
+
1221
+ # We don't put builder.scope as the globals in exec call because
1222
+ # guard_fn.__globals__ becomes equal to builder.scope. This causes
1223
+ # guard_fn to hold a referece to f_locals sitting in builder.scope["L"]
1224
+ globals_for_guard_fn = {"G": builder.scope["G"]}
1225
+ try:
1226
+ exec(pycode, globals_for_guard_fn, out)
1227
+ except SyntaxError as ex:
1228
+ log.exception("Failed to exec guard at line %s.\n%s", ex.lineno, pycode)
1229
+ raise
1230
+ guard_fn = out["___make_guard_fn"](*closure_vars.values())
1231
+ guard_fn.closure_vars = closure_vars
1232
+ # TODO(whc) maybe '.code_parts' was only kept around for the guard callback? so we don't need both
1233
+ guard_fn.args = largs
1234
+ guard_fn.code_parts = code_parts
1235
+ guard_fn.verbose_code_parts = verbose_code_parts
1236
+ # Grab only G, but preserve "G" because guards access it as "G"
1237
+ guard_fn.global_scope = globals_for_guard_fn
1238
+ guard_fn.guard_fail_fn = guard_fail_fn
1239
+ # will be populated by a non-owning reference to CacheEntry/ExtraState
1240
+ # when the CacheEntry is constructed
1241
+ guard_fn.cache_entry = None
1242
+ guard_fn.extra_state = None
1243
+ return guard_fn
1244
+
1245
+ def invalidate(self):
1246
+ # Some tests reveal that CheckFunctionManager has no attribute
1247
+ # check_fn, but this case should not be of any concern.
1248
+ # This case doesn't seem easy to repro.
1249
+ if (
1250
+ hasattr(self, "check_fn")
1251
+ and self.check_fn is not DeletedGuardFn
1252
+ and (cache_entry := self.check_fn.cache_entry) is not None
1253
+ and (extra_state := self.check_fn.extra_state) is not None
1254
+ ):
1255
+ assert isinstance(cache_entry, CacheEntry)
1256
+ assert isinstance(extra_state, ExtraState)
1257
+ extra_state.invalidate(cache_entry)
1258
+ self.check_fn.cache_entry = None
1259
+ self.check_fn.extra_state = None
1260
+ self.check_fn = DeletedGuardFn
1261
+
1262
+ def id_ref(self, obj):
1263
+ """add a weakref, return the id"""
1264
+ try:
1265
+ if id(obj) not in self._weakrefs:
1266
+ # We will clear the _weakrefs dict at the end of __init__
1267
+ # function, which will delete the callbacks as well. Therefore,
1268
+ # we are using a finalizer which is kept alive.
1269
+ self._weakrefs[id(obj)] = weakref.ref(obj)
1270
+ weakref.finalize(obj, self.invalidate)
1271
+ except TypeError:
1272
+ pass # cannot weakref bool object
1273
+ return id(obj)
1274
+
1275
+ def lookup_weakrefs(self, obj):
1276
+ """Lookup the _weakrefs created in id_ref function for ID_MATCH'd objects"""
1277
+ if id(obj) in self._weakrefs:
1278
+ return self._weakrefs[id(obj)]
1279
+ return None
1280
+
1281
+
1282
+ def build_guard_function(code_parts, closure_args) -> Tuple[str, str]:
1283
+ from torch._inductor.utils import IndentedBuffer
1284
+
1285
+ if HAS_UNPARSE_FUNCTIONS:
1286
+ csepass = PyExprCSEPass()
1287
+ csepass.count(code_parts)
1288
+
1289
+ def replace(expr: str) -> Tuple[List[str], str]:
1290
+ return csepass.replace(expr)
1291
+
1292
+ else:
1293
+
1294
+ def replace(expr: str) -> Tuple[List[str], str]:
1295
+ return [], expr
1296
+
1297
+ # Generate the inner body of the guard function.
1298
+ # i.e. if-chain of the guard expressions.
1299
+ guard_body = IndentedBuffer()
1300
+ for expr in code_parts:
1301
+ preface, expr = replace(expr)
1302
+ guard_body.writelines(preface)
1303
+ guard_body.writeline(f"if not ({expr}):")
1304
+ with guard_body.indent():
1305
+ guard_body.writeline("return False")
1306
+
1307
+ # Wrap the inner body into the actual guard function.
1308
+ guard = IndentedBuffer()
1309
+ guard.writeline("def guard(L):")
1310
+ with guard.indent():
1311
+ guard.splice(guard_body)
1312
+ guard.writeline("return True")
1313
+
1314
+ # Wrap the whole guard function into another function
1315
+ # with the closure variables.
1316
+ make_guard_fn = IndentedBuffer()
1317
+ make_guard_fn.writeline(f"def ___make_guard_fn({closure_args}):")
1318
+ with make_guard_fn.indent():
1319
+ make_guard_fn.splice(guard)
1320
+ make_guard_fn.writeline("return guard")
1321
+
1322
+ return guard_body.getvalue(), make_guard_fn.getvalue()
1323
+
1324
+
1325
+ def is_recompiles_enabled():
1326
+ return torch._logging._internal.log_state.is_artifact_enabled("recompiles")
1327
+
1328
+
1329
+ def is_recompiles_verbose_enabled():
1330
+ return torch._logging._internal.log_state.is_artifact_enabled("recompiles_verbose")
1331
+
1332
+
1333
+ def get_guard_fail_reason(
1334
+ guard_fn: GuardFn,
1335
+ code: types.CodeType,
1336
+ f_locals: Dict[str, object],
1337
+ ) -> str:
1338
+ """
1339
+ Return the reason why `guard_fn` failed.
1340
+ Updates `guard_failures` with the generated reason.
1341
+ Only the first failed check of guard_fn is reported.
1342
+ """
1343
+ scope = {"L": f_locals, "G": guard_fn.global_scope["G"]}
1344
+ scope.update(guard_fn.closure_vars)
1345
+ scope["___check_tensors"] = scope["___check_tensors_verbose"]
1346
+ reasons: List[str] = []
1347
+ for part in guard_fn.verbose_code_parts:
1348
+ global_scope = dict(guard_fn.global_scope)
1349
+ global_scope["__compile_source__"] = part
1350
+ with report_compile_source_on_error():
1351
+ try:
1352
+ fail_reason = eval(part, global_scope, scope)
1353
+ except Exception as e:
1354
+ if is_recompiles_verbose_enabled():
1355
+ continue
1356
+ else:
1357
+ raise
1358
+ # Only ___check_tensors knows how to return a fancy fail reason;
1359
+ # for everything else we just report the code that failed
1360
+
1361
+ if isinstance(fail_reason, bool) and not fail_reason:
1362
+ fail_reason = part
1363
+ if isinstance(fail_reason, str):
1364
+ reasons.append(fail_reason)
1365
+ if not is_recompiles_verbose_enabled():
1366
+ break
1367
+
1368
+ reason_str = "\n".join(reasons)
1369
+ guard_failures[orig_code_map[code]].append(reason_str)
1370
+
1371
+ try:
1372
+ if guard_fn.guard_fail_fn is not None:
1373
+ guard_fn.guard_fail_fn(
1374
+ GuardFail(reason_str or "unknown reason", orig_code_map[code])
1375
+ )
1376
+ except Exception as e:
1377
+ log.exception(
1378
+ "Failure in guard_fail_fn callback - raising here will cause a NULL Error on guard eval",
1379
+ )
1380
+
1381
+ return reason_str
1382
+
1383
+
1384
+ def get_and_maybe_log_recompilation_reason(
1385
+ cache_entry, frame: types.FrameType
1386
+ ) -> List[str]:
1387
+ """
1388
+ Return the list of guard failure reasons using cache_entry.
1389
+ Logs the recompilation reason if `recompiles` logging is enabled.
1390
+ Raises a RecompileError if `config.error_on_recompile` is enabled.
1391
+ """
1392
+ reasons = []
1393
+ while cache_entry is not None:
1394
+ reason = get_guard_fail_reason(
1395
+ cache_entry.check_fn, cache_entry.code, frame.f_locals
1396
+ )
1397
+ if reason:
1398
+ reasons.append(reason)
1399
+ cache_entry = cache_entry.next
1400
+
1401
+ code = frame.f_code
1402
+
1403
+ # at least one of "recompiles" or "recompiles_verbose" is enabled
1404
+ do_recompiles_log = is_recompiles_enabled() or is_recompiles_verbose_enabled()
1405
+
1406
+ if do_recompiles_log or config.error_on_recompile:
1407
+ if is_recompiles_verbose_enabled():
1408
+ failures = "\n\n".join(
1409
+ f"guard {i} failures:\n" + textwrap.indent(reason, "- ")
1410
+ for i, reason in enumerate(reasons)
1411
+ )
1412
+ else:
1413
+ failures = textwrap.indent("\n".join(reasons), "- ")
1414
+ guard_failure_details = (
1415
+ f"triggered by the following guard failure(s):\n{failures}"
1416
+ )
1417
+ message = (
1418
+ f"Recompiling function {code.co_name} in {code.co_filename}:{code.co_firstlineno}\n"
1419
+ f"{textwrap.indent(guard_failure_details, ' ')}"
1420
+ )
1421
+ if do_recompiles_log:
1422
+ if is_recompiles_verbose_enabled():
1423
+ recompiles_verbose_log.debug(message)
1424
+ else:
1425
+ recompiles_log.debug(message)
1426
+ if config.error_on_recompile:
1427
+ raise exc.RecompileError(message)
1428
+
1429
+ return reasons
1430
+
1431
+
1432
+ def guard_error_hook(
1433
+ guard_fn: GuardFn,
1434
+ code: types.CodeType,
1435
+ f_locals: Dict[str, object],
1436
+ index: int,
1437
+ last: bool,
1438
+ ):
1439
+ print(
1440
+ f"ERROR RUNNING GUARDS {code.co_name} {code.co_filename}:{code.co_firstlineno}"
1441
+ )
1442
+ print("lambda " + ", ".join(guard_fn.args) + ":")
1443
+ print(" ", " and\n ".join(guard_fn.code_parts))
1444
+ local_scope = {"L": f_locals, **guard_fn.closure_vars}
1445
+ for guard in guard_fn.code_parts:
1446
+ try:
1447
+ eval(guard, guard_fn.global_scope, local_scope)
1448
+ except: # noqa: B001,E722
1449
+ print(f"Malformed guard:\n{guard}")
1450
+
1451
+
1452
+ set_guard_error_hook(guard_error_hook)
1453
+
1454
+
1455
+ def unique(seq):
1456
+ seen = set()
1457
+ for x in seq:
1458
+ if x not in seen:
1459
+ yield x
1460
+ seen.add(x)
1461
+
1462
+
1463
+ def make_dupe_guard(obj_source, dupe_source):
1464
+ # Note - we may end up in a situation where we invoke something like
1465
+ # def fn(x, y)
1466
+ # with fn(x, x)
1467
+ # Prior to the addition of tracking to all relevant objects, we would handle this just fine by
1468
+ # eagerly re-entering VB and rewrapping inputs, correctly creating graphargs and placeholders. However,
1469
+ # with tracking on inputs, duplicate inputs or aliased relationships may end up getting erased here -
1470
+ # In the fn(x, x) example call above look like a graph with a single input.
1471
+ # In order to ensure that we do not reuse fn(x, x) for fn(x, y), we create a duplicate input guard.
1472
+
1473
+ # Note - we may not have a source, that is fine, it just means we had an object that is safe to have
1474
+ # leave unsourced - like a local list created and discharged entirely within a local scope.
1475
+ if dupe_source and dupe_source != obj_source:
1476
+ ser_source_is_local = is_from_local_source(dupe_source)
1477
+ source_is_local = is_from_local_source(obj_source)
1478
+ # Note - both must be local, or global, or we will run afoul of a lack of merging in how we currently
1479
+ # reconcile guards builder scopes in compile_check_fn. This technically means we miss a guard here,
1480
+ # so maybe we should do this refactor before we land this...
1481
+ # TODO(voz): Combine local and global guard builders.
1482
+ if ser_source_is_local == source_is_local:
1483
+ # Note - this is a little aggressive - these being duplicate input does not always matter.
1484
+ # However, this should always be a sound guard to add here.
1485
+ return functools.partial(GuardBuilder.DUPLICATE_INPUT, source_b=dupe_source)
1486
+ return None
1487
+
1488
+
1489
+ def install_guard(*guards, skip=0):
1490
+ """
1491
+ Add dynamo guards to the current tracing context.
1492
+
1493
+ Args:
1494
+ guards: guard(s) to add
1495
+ skip: number of stack frames to ignore for debug stack trace
1496
+ """
1497
+ from torch._guards import TracingContext
1498
+
1499
+ collect_debug_stack = guards_log.isEnabledFor(
1500
+ logging.DEBUG
1501
+ ) or verbose_guards_log.isEnabledFor(logging.DEBUG)
1502
+ add = TracingContext.get().guards_context.dynamo_guards.add
1503
+ for guard in guards:
1504
+ assert isinstance(guard, Guard)
1505
+ add(guard, collect_debug_stack=collect_debug_stack, skip=skip + 1)
shared/package-files/56/564d6cca251b3adad0ba10b91ca657e113d82ad7406f2a53b17f9f668c7c1ad7/blob ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ @generated by mypy-protobuf. Do not edit manually!
3
+ isort:skip_file
4
+ """
5
+ from google.protobuf.descriptor import (
6
+ Descriptor as google___protobuf___descriptor___Descriptor,
7
+ FileDescriptor as google___protobuf___descriptor___FileDescriptor,
8
+ )
9
+
10
+ from google.protobuf.internal.containers import (
11
+ RepeatedCompositeFieldContainer as google___protobuf___internal___containers___RepeatedCompositeFieldContainer,
12
+ )
13
+
14
+ from google.protobuf.message import (
15
+ Message as google___protobuf___message___Message,
16
+ )
17
+
18
+ from google.protobuf.source_context_pb2 import (
19
+ SourceContext as google___protobuf___source_context_pb2___SourceContext,
20
+ )
21
+
22
+ from google.protobuf.type_pb2 import (
23
+ Option as google___protobuf___type_pb2___Option,
24
+ SyntaxValue as google___protobuf___type_pb2___SyntaxValue,
25
+ )
26
+
27
+ from typing import (
28
+ Iterable as typing___Iterable,
29
+ Optional as typing___Optional,
30
+ Text as typing___Text,
31
+ )
32
+
33
+ from typing_extensions import (
34
+ Literal as typing_extensions___Literal,
35
+ )
36
+
37
+
38
+ builtin___bool = bool
39
+ builtin___bytes = bytes
40
+ builtin___float = float
41
+ builtin___int = int
42
+
43
+
44
+ DESCRIPTOR: google___protobuf___descriptor___FileDescriptor = ...
45
+
46
+ class Api(google___protobuf___message___Message):
47
+ DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
48
+ name: typing___Text = ...
49
+ version: typing___Text = ...
50
+ syntax: google___protobuf___type_pb2___SyntaxValue = ...
51
+
52
+ @property
53
+ def methods(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___Method]: ...
54
+
55
+ @property
56
+ def options(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[google___protobuf___type_pb2___Option]: ...
57
+
58
+ @property
59
+ def source_context(self) -> google___protobuf___source_context_pb2___SourceContext: ...
60
+
61
+ @property
62
+ def mixins(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[type___Mixin]: ...
63
+
64
+ def __init__(self,
65
+ *,
66
+ name : typing___Optional[typing___Text] = None,
67
+ methods : typing___Optional[typing___Iterable[type___Method]] = None,
68
+ options : typing___Optional[typing___Iterable[google___protobuf___type_pb2___Option]] = None,
69
+ version : typing___Optional[typing___Text] = None,
70
+ source_context : typing___Optional[google___protobuf___source_context_pb2___SourceContext] = None,
71
+ mixins : typing___Optional[typing___Iterable[type___Mixin]] = None,
72
+ syntax : typing___Optional[google___protobuf___type_pb2___SyntaxValue] = None,
73
+ ) -> None: ...
74
+ def HasField(self, field_name: typing_extensions___Literal[u"source_context",b"source_context"]) -> builtin___bool: ...
75
+ def ClearField(self, field_name: typing_extensions___Literal[u"methods",b"methods",u"mixins",b"mixins",u"name",b"name",u"options",b"options",u"source_context",b"source_context",u"syntax",b"syntax",u"version",b"version"]) -> None: ...
76
+ type___Api = Api
77
+
78
+ class Method(google___protobuf___message___Message):
79
+ DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
80
+ name: typing___Text = ...
81
+ request_type_url: typing___Text = ...
82
+ request_streaming: builtin___bool = ...
83
+ response_type_url: typing___Text = ...
84
+ response_streaming: builtin___bool = ...
85
+ syntax: google___protobuf___type_pb2___SyntaxValue = ...
86
+
87
+ @property
88
+ def options(self) -> google___protobuf___internal___containers___RepeatedCompositeFieldContainer[google___protobuf___type_pb2___Option]: ...
89
+
90
+ def __init__(self,
91
+ *,
92
+ name : typing___Optional[typing___Text] = None,
93
+ request_type_url : typing___Optional[typing___Text] = None,
94
+ request_streaming : typing___Optional[builtin___bool] = None,
95
+ response_type_url : typing___Optional[typing___Text] = None,
96
+ response_streaming : typing___Optional[builtin___bool] = None,
97
+ options : typing___Optional[typing___Iterable[google___protobuf___type_pb2___Option]] = None,
98
+ syntax : typing___Optional[google___protobuf___type_pb2___SyntaxValue] = None,
99
+ ) -> None: ...
100
+ def ClearField(self, field_name: typing_extensions___Literal[u"name",b"name",u"options",b"options",u"request_streaming",b"request_streaming",u"request_type_url",b"request_type_url",u"response_streaming",b"response_streaming",u"response_type_url",b"response_type_url",u"syntax",b"syntax"]) -> None: ...
101
+ type___Method = Method
102
+
103
+ class Mixin(google___protobuf___message___Message):
104
+ DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
105
+ name: typing___Text = ...
106
+ root: typing___Text = ...
107
+
108
+ def __init__(self,
109
+ *,
110
+ name : typing___Optional[typing___Text] = None,
111
+ root : typing___Optional[typing___Text] = None,
112
+ ) -> None: ...
113
+ def ClearField(self, field_name: typing_extensions___Literal[u"name",b"name",u"root",b"root"]) -> None: ...
114
+ type___Mixin = Mixin
shared/package-files/56/564f153bbe095146991ef7a3be45890519e693ece9987c2392c3026680435837/blob ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os.path
2
+ from pathlib import Path
3
+ from typing import Any, Callable, Optional, Tuple, Union
4
+
5
+ import numpy as np
6
+ from PIL import Image
7
+
8
+ from .utils import check_integrity, download_url, verify_str_arg
9
+ from .vision import VisionDataset
10
+
11
+
12
+ class SVHN(VisionDataset):
13
+ """`SVHN <http://ufldl.stanford.edu/housenumbers/>`_ Dataset.
14
+ Note: The SVHN dataset assigns the label `10` to the digit `0`. However, in this Dataset,
15
+ we assign the label `0` to the digit `0` to be compatible with PyTorch loss functions which
16
+ expect the class labels to be in the range `[0, C-1]`
17
+
18
+ .. warning::
19
+
20
+ This class needs `scipy <https://docs.scipy.org/doc/>`_ to load data from `.mat` format.
21
+
22
+ Args:
23
+ root (str or ``pathlib.Path``): Root directory of the dataset where the data is stored.
24
+ split (string): One of {'train', 'test', 'extra'}.
25
+ Accordingly dataset is selected. 'extra' is Extra training set.
26
+ transform (callable, optional): A function/transform that takes in a PIL image
27
+ and returns a transformed version. E.g, ``transforms.RandomCrop``
28
+ target_transform (callable, optional): A function/transform that takes in the
29
+ target and transforms it.
30
+ download (bool, optional): If true, downloads the dataset from the internet and
31
+ puts it in root directory. If dataset is already downloaded, it is not
32
+ downloaded again.
33
+
34
+ """
35
+
36
+ split_list = {
37
+ "train": [
38
+ "http://ufldl.stanford.edu/housenumbers/train_32x32.mat",
39
+ "train_32x32.mat",
40
+ "e26dedcc434d2e4c54c9b2d4a06d8373",
41
+ ],
42
+ "test": [
43
+ "http://ufldl.stanford.edu/housenumbers/test_32x32.mat",
44
+ "test_32x32.mat",
45
+ "eb5a983be6a315427106f1b164d9cef3",
46
+ ],
47
+ "extra": [
48
+ "http://ufldl.stanford.edu/housenumbers/extra_32x32.mat",
49
+ "extra_32x32.mat",
50
+ "a93ce644f1a588dc4d68dda5feec44a7",
51
+ ],
52
+ }
53
+
54
+ def __init__(
55
+ self,
56
+ root: Union[str, Path],
57
+ split: str = "train",
58
+ transform: Optional[Callable] = None,
59
+ target_transform: Optional[Callable] = None,
60
+ download: bool = False,
61
+ ) -> None:
62
+ super().__init__(root, transform=transform, target_transform=target_transform)
63
+ self.split = verify_str_arg(split, "split", tuple(self.split_list.keys()))
64
+ self.url = self.split_list[split][0]
65
+ self.filename = self.split_list[split][1]
66
+ self.file_md5 = self.split_list[split][2]
67
+
68
+ if download:
69
+ self.download()
70
+
71
+ if not self._check_integrity():
72
+ raise RuntimeError("Dataset not found or corrupted. You can use download=True to download it")
73
+
74
+ # import here rather than at top of file because this is
75
+ # an optional dependency for torchvision
76
+ import scipy.io as sio
77
+
78
+ # reading(loading) mat file as array
79
+ loaded_mat = sio.loadmat(os.path.join(self.root, self.filename))
80
+
81
+ self.data = loaded_mat["X"]
82
+ # loading from the .mat file gives an np.ndarray of type np.uint8
83
+ # converting to np.int64, so that we have a LongTensor after
84
+ # the conversion from the numpy array
85
+ # the squeeze is needed to obtain a 1D tensor
86
+ self.labels = loaded_mat["y"].astype(np.int64).squeeze()
87
+
88
+ # the svhn dataset assigns the class label "10" to the digit 0
89
+ # this makes it inconsistent with several loss functions
90
+ # which expect the class labels to be in the range [0, C-1]
91
+ np.place(self.labels, self.labels == 10, 0)
92
+ self.data = np.transpose(self.data, (3, 2, 0, 1))
93
+
94
+ def __getitem__(self, index: int) -> Tuple[Any, Any]:
95
+ """
96
+ Args:
97
+ index (int): Index
98
+
99
+ Returns:
100
+ tuple: (image, target) where target is index of the target class.
101
+ """
102
+ img, target = self.data[index], int(self.labels[index])
103
+
104
+ # doing this so that it is consistent with all other datasets
105
+ # to return a PIL Image
106
+ img = Image.fromarray(np.transpose(img, (1, 2, 0)))
107
+
108
+ if self.transform is not None:
109
+ img = self.transform(img)
110
+
111
+ if self.target_transform is not None:
112
+ target = self.target_transform(target)
113
+
114
+ return img, target
115
+
116
+ def __len__(self) -> int:
117
+ return len(self.data)
118
+
119
+ def _check_integrity(self) -> bool:
120
+ root = self.root
121
+ md5 = self.split_list[self.split][2]
122
+ fpath = os.path.join(root, self.filename)
123
+ return check_integrity(fpath, md5)
124
+
125
+ def download(self) -> None:
126
+ md5 = self.split_list[self.split][2]
127
+ download_url(self.url, self.root, self.filename, md5)
128
+
129
+ def extra_repr(self) -> str:
130
+ return "Split: {split}".format(**self.__dict__)
shared/package-files/56/5652bcc2d84bb33915968e96a2b1f17c53beb242a11ed79abd839a80779d0821/blob ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NOTE: This test is sensitive to line numbers as it checks breakpoints
2
+ from numba import njit, types
3
+ import numpy as np
4
+ from numba.tests.gdb_support import GdbMIDriver
5
+ from numba.tests.support import TestCase, needs_subprocess
6
+ import unittest
7
+
8
+
9
+ @needs_subprocess
10
+ class Test(TestCase):
11
+
12
+ def test(self):
13
+ @njit(debug=True)
14
+ def foo(x):
15
+ z = np.ones_like(x) # break here
16
+ return x, z
17
+
18
+ tmp = np.ones(5)
19
+ foo(tmp)
20
+
21
+ driver = GdbMIDriver(__file__)
22
+ driver.set_breakpoint(line=15)
23
+ driver.run()
24
+ driver.check_hit_breakpoint(1)
25
+ driver.stack_list_arguments(2)
26
+ llvm_intp = f"i{types.intp.bitwidth}"
27
+ expect = (
28
+ '[frame={level="0",args=[{name="x",type="array(float64, 1d, C) '
29
+ f'({{i8*, i8*, {llvm_intp}, {llvm_intp}, double*, '
30
+ f'[1 x {llvm_intp}], [1 x {llvm_intp}]}})"}}]}}]'
31
+ )
32
+ driver.assert_output(expect)
33
+ driver.stack_list_variables(1)
34
+ # 'z' should be zero-init
35
+ expect = ('{name="z",value="{meminfo = 0x0, parent = 0x0, nitems = 0, '
36
+ 'itemsize = 0, data = 0x0, shape = {0}, strides = {0}}"}')
37
+ driver.assert_output(expect)
38
+ driver.set_breakpoint(line=16)
39
+ driver.cont()
40
+ driver.check_hit_breakpoint(2)
41
+ driver.stack_list_variables(1)
42
+ # 'z' should be populated
43
+ expect = (r'^.*\{name="z",value="\{meminfo = 0x[0-9a-f]+ .*, '
44
+ r'parent = 0x0, nitems = 5, itemsize = 8, '
45
+ r'data = 0x[0-9a-f]+, shape = \{5\}, strides = \{8\}\}.*$')
46
+ driver.assert_regex_output(expect)
47
+ driver.quit()
48
+
49
+
50
+ if __name__ == '__main__':
51
+ unittest.main()
shared/package-files/56/565454d155b79ca728b997f7ca4b7c23e8ad2bd520ed89561831c99d8b95b438/blob ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeMetaFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ struct TORCH_API structured_scatter_reduce_two : public at::impl::MetaBase {
21
+
22
+
23
+ void meta(const at::Tensor & self, int64_t dim, const at::Tensor & index, const at::Tensor & src, c10::string_view reduce, bool include_self);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
shared/package-files/56/56549f6a15910c6ee83b2922aefd8b06bbe24d0c739afb966802d06cf10023b5/blob ADDED
Binary file (2.01 kB). View file
 
shared/package-files/56/5659af72d45a42d8ee62f42ea1edaddae7e26fbe13b9affbaac895aecde3fa9d/blob ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from pytest import raises as assert_raises
3
+
4
+ import scipy.sparse.linalg._isolve.utils as utils
5
+
6
+
7
+ def test_make_system_bad_shape():
8
+ assert_raises(ValueError,
9
+ utils.make_system, np.zeros((5,3)), None, np.zeros(4), np.zeros(4))
shared/package-files/56/565b18e09c1951c905e6ec43ad596b2510559ef4e6bae6a3774877ec13246cea/blob ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ import io
19
+ import os
20
+ import re
21
+ import sys
22
+ import types
23
+
24
+ import pytest
25
+ from unittest import mock
26
+
27
+ import pyarrow as pa
28
+
29
+ try:
30
+ import pyarrow.parquet as pq
31
+ from pyarrow.tests.parquet.common import _write_table
32
+ except ImportError:
33
+ pq = None
34
+
35
+ try:
36
+ import pandas as pd
37
+ import pandas.testing as tm
38
+
39
+ from pyarrow.tests.parquet.common import alltypes_sample
40
+ except ImportError:
41
+ pd = tm = None
42
+
43
+
44
+ # Marks all of the tests in this module
45
+ # Ignore these with pytest ... -m 'not parquet'
46
+ pytestmark = pytest.mark.parquet
47
+
48
+
49
+ @pytest.mark.pandas
50
+ def test_pass_separate_metadata():
51
+ # ARROW-471
52
+ df = alltypes_sample(size=10000)
53
+
54
+ a_table = pa.Table.from_pandas(df)
55
+
56
+ buf = io.BytesIO()
57
+ _write_table(a_table, buf, compression='snappy', version='2.6')
58
+
59
+ buf.seek(0)
60
+ metadata = pq.read_metadata(buf)
61
+
62
+ buf.seek(0)
63
+
64
+ fileh = pq.ParquetFile(buf, metadata=metadata)
65
+
66
+ tm.assert_frame_equal(df, fileh.read().to_pandas())
67
+
68
+
69
+ @pytest.mark.pandas
70
+ def test_read_single_row_group():
71
+ # ARROW-471
72
+ N, K = 10000, 4
73
+ df = alltypes_sample(size=N)
74
+
75
+ a_table = pa.Table.from_pandas(df)
76
+
77
+ buf = io.BytesIO()
78
+ _write_table(a_table, buf, row_group_size=N / K,
79
+ compression='snappy', version='2.6')
80
+
81
+ buf.seek(0)
82
+
83
+ pf = pq.ParquetFile(buf)
84
+
85
+ assert pf.num_row_groups == K
86
+
87
+ row_groups = [pf.read_row_group(i) for i in range(K)]
88
+ result = pa.concat_tables(row_groups)
89
+ tm.assert_frame_equal(df, result.to_pandas())
90
+
91
+
92
+ @pytest.mark.pandas
93
+ def test_read_single_row_group_with_column_subset():
94
+ N, K = 10000, 4
95
+ df = alltypes_sample(size=N)
96
+ a_table = pa.Table.from_pandas(df)
97
+
98
+ buf = io.BytesIO()
99
+ _write_table(a_table, buf, row_group_size=N / K,
100
+ compression='snappy', version='2.6')
101
+
102
+ buf.seek(0)
103
+ pf = pq.ParquetFile(buf)
104
+
105
+ cols = list(df.columns[:2])
106
+ row_groups = [pf.read_row_group(i, columns=cols) for i in range(K)]
107
+ result = pa.concat_tables(row_groups)
108
+ tm.assert_frame_equal(df[cols], result.to_pandas())
109
+
110
+ # ARROW-4267: Selection of duplicate columns still leads to these columns
111
+ # being read uniquely.
112
+ row_groups = [pf.read_row_group(i, columns=cols + cols) for i in range(K)]
113
+ result = pa.concat_tables(row_groups)
114
+ tm.assert_frame_equal(df[cols], result.to_pandas())
115
+
116
+
117
+ @pytest.mark.pandas
118
+ def test_read_multiple_row_groups():
119
+ N, K = 10000, 4
120
+ df = alltypes_sample(size=N)
121
+
122
+ a_table = pa.Table.from_pandas(df)
123
+
124
+ buf = io.BytesIO()
125
+ _write_table(a_table, buf, row_group_size=N / K,
126
+ compression='snappy', version='2.6')
127
+
128
+ buf.seek(0)
129
+
130
+ pf = pq.ParquetFile(buf)
131
+
132
+ assert pf.num_row_groups == K
133
+
134
+ result = pf.read_row_groups(range(K))
135
+ tm.assert_frame_equal(df, result.to_pandas())
136
+
137
+
138
+ @pytest.mark.pandas
139
+ def test_read_multiple_row_groups_with_column_subset():
140
+ N, K = 10000, 4
141
+ df = alltypes_sample(size=N)
142
+ a_table = pa.Table.from_pandas(df)
143
+
144
+ buf = io.BytesIO()
145
+ _write_table(a_table, buf, row_group_size=N / K,
146
+ compression='snappy', version='2.6')
147
+
148
+ buf.seek(0)
149
+ pf = pq.ParquetFile(buf)
150
+
151
+ cols = list(df.columns[:2])
152
+ result = pf.read_row_groups(range(K), columns=cols)
153
+ tm.assert_frame_equal(df[cols], result.to_pandas())
154
+
155
+ # ARROW-4267: Selection of duplicate columns still leads to these columns
156
+ # being read uniquely.
157
+ result = pf.read_row_groups(range(K), columns=cols + cols)
158
+ tm.assert_frame_equal(df[cols], result.to_pandas())
159
+
160
+
161
+ @pytest.mark.pandas
162
+ def test_scan_contents():
163
+ N, K = 10000, 4
164
+ df = alltypes_sample(size=N)
165
+ a_table = pa.Table.from_pandas(df)
166
+
167
+ buf = io.BytesIO()
168
+ _write_table(a_table, buf, row_group_size=N / K,
169
+ compression='snappy', version='2.6')
170
+
171
+ buf.seek(0)
172
+ pf = pq.ParquetFile(buf)
173
+
174
+ assert pf.scan_contents() == 10000
175
+ assert pf.scan_contents(df.columns[:4]) == 10000
176
+
177
+
178
+ def test_parquet_file_pass_directory_instead_of_file(tempdir):
179
+ # ARROW-7208
180
+ path = tempdir / 'directory'
181
+ os.mkdir(str(path))
182
+
183
+ msg = f"Cannot open for reading: path '{str(path)}' is a directory"
184
+ with pytest.raises(IOError) as exc:
185
+ pq.ParquetFile(path)
186
+ if exc.errisinstance(PermissionError) and sys.platform == 'win32':
187
+ return # Windows CI can get a PermissionError here.
188
+ exc.match(msg)
189
+
190
+
191
+ def test_read_column_invalid_index():
192
+ table = pa.table([pa.array([4, 5]), pa.array(["foo", "bar"])],
193
+ names=['ints', 'strs'])
194
+ bio = pa.BufferOutputStream()
195
+ pq.write_table(table, bio)
196
+ f = pq.ParquetFile(bio.getvalue())
197
+ assert f.reader.read_column(0).to_pylist() == [4, 5]
198
+ assert f.reader.read_column(1).to_pylist() == ["foo", "bar"]
199
+ for index in (-1, 2):
200
+ with pytest.raises((ValueError, IndexError)):
201
+ f.reader.read_column(index)
202
+
203
+
204
+ @pytest.mark.pandas
205
+ @pytest.mark.parametrize('batch_size', [300, 1000, 1300])
206
+ def test_iter_batches_columns_reader(tempdir, batch_size):
207
+ total_size = 3000
208
+ chunk_size = 1000
209
+ # TODO: Add categorical support
210
+ df = alltypes_sample(size=total_size)
211
+
212
+ filename = tempdir / 'pandas_roundtrip.parquet'
213
+ arrow_table = pa.Table.from_pandas(df)
214
+ _write_table(arrow_table, filename, version='2.6',
215
+ chunk_size=chunk_size)
216
+
217
+ file_ = pq.ParquetFile(filename)
218
+ for columns in [df.columns[:10], df.columns[10:]]:
219
+ batches = file_.iter_batches(batch_size=batch_size, columns=columns)
220
+ batch_starts = range(0, total_size+batch_size, batch_size)
221
+ for batch, start in zip(batches, batch_starts):
222
+ end = min(total_size, start + batch_size)
223
+ tm.assert_frame_equal(
224
+ batch.to_pandas(),
225
+ df.iloc[start:end, :].loc[:, columns].reset_index(drop=True)
226
+ )
227
+
228
+
229
+ @pytest.mark.pandas
230
+ @pytest.mark.parametrize('chunk_size', [1000])
231
+ def test_iter_batches_reader(tempdir, chunk_size):
232
+ df = alltypes_sample(size=10000, categorical=True)
233
+
234
+ filename = tempdir / 'pandas_roundtrip.parquet'
235
+ arrow_table = pa.Table.from_pandas(df)
236
+ assert arrow_table.schema.pandas_metadata is not None
237
+
238
+ _write_table(arrow_table, filename, version='2.6',
239
+ chunk_size=chunk_size)
240
+
241
+ file_ = pq.ParquetFile(filename)
242
+
243
+ def get_all_batches(f):
244
+ for row_group in range(f.num_row_groups):
245
+ batches = f.iter_batches(
246
+ batch_size=900,
247
+ row_groups=[row_group],
248
+ )
249
+
250
+ for batch in batches:
251
+ yield batch
252
+
253
+ batches = list(get_all_batches(file_))
254
+ batch_no = 0
255
+
256
+ for i in range(file_.num_row_groups):
257
+ tm.assert_frame_equal(
258
+ batches[batch_no].to_pandas(),
259
+ file_.read_row_groups([i]).to_pandas().head(900)
260
+ )
261
+
262
+ batch_no += 1
263
+
264
+ tm.assert_frame_equal(
265
+ batches[batch_no].to_pandas().reset_index(drop=True),
266
+ file_.read_row_groups([i]).to_pandas().iloc[900:].reset_index(
267
+ drop=True
268
+ )
269
+ )
270
+
271
+ batch_no += 1
272
+
273
+
274
+ @pytest.mark.pandas
275
+ @pytest.mark.parametrize('pre_buffer', [False, True])
276
+ def test_pre_buffer(pre_buffer):
277
+ N, K = 10000, 4
278
+ df = alltypes_sample(size=N)
279
+ a_table = pa.Table.from_pandas(df)
280
+
281
+ buf = io.BytesIO()
282
+ _write_table(a_table, buf, row_group_size=N / K,
283
+ compression='snappy', version='2.6')
284
+
285
+ buf.seek(0)
286
+ pf = pq.ParquetFile(buf, pre_buffer=pre_buffer)
287
+ assert pf.read().num_rows == N
288
+
289
+
290
+ def test_parquet_file_explicitly_closed(tempdir):
291
+ """
292
+ Unopened files should be closed explicitly after use,
293
+ and previously opened files should be left open.
294
+ Applies to read_table, ParquetDataset, and ParquetFile
295
+ """
296
+ # create test parquet file
297
+ fn = tempdir.joinpath('file.parquet')
298
+ table = pa.table({'col1': [0, 1], 'col2': [0, 1]})
299
+ pq.write_table(table, fn)
300
+
301
+ # ParquetFile with opened file (will leave open)
302
+ with open(fn, 'rb') as f:
303
+ with pq.ParquetFile(f) as p:
304
+ p.read()
305
+ assert not f.closed
306
+ assert not p.closed
307
+ assert not f.closed # opened input file was not closed
308
+ assert not p.closed # parquet file obj reports as not closed
309
+ assert f.closed
310
+ assert p.closed # parquet file being closed reflects underlying file
311
+
312
+ # ParquetFile with unopened file (will close)
313
+ with pq.ParquetFile(fn) as p:
314
+ p.read()
315
+ assert not p.closed
316
+ assert p.closed # parquet file obj reports as closed
317
+
318
+
319
+ @pytest.mark.s3
320
+ @pytest.mark.parametrize("use_uri", (True, False))
321
+ def test_parquet_file_with_filesystem(s3_example_fs, use_uri):
322
+ s3_fs, s3_uri, s3_path = s3_example_fs
323
+
324
+ args = (s3_uri if use_uri else s3_path,)
325
+ kwargs = {} if use_uri else dict(filesystem=s3_fs)
326
+
327
+ table = pa.table({"a": range(10)})
328
+ pq.write_table(table, s3_path, filesystem=s3_fs)
329
+
330
+ parquet_file = pq.ParquetFile(*args, **kwargs)
331
+ assert parquet_file.read() == table
332
+ assert not parquet_file.closed
333
+ parquet_file.close()
334
+ assert parquet_file.closed
335
+
336
+ with pq.ParquetFile(*args, **kwargs) as f:
337
+ assert f.read() == table
338
+ assert not f.closed
339
+ assert f.closed
340
+
341
+
342
+ def test_read_statistics():
343
+ table = pa.table({"value": pa.array([-1, None, 3])})
344
+ buf = io.BytesIO()
345
+ _write_table(table, buf)
346
+ buf.seek(0)
347
+
348
+ statistics = pq.ParquetFile(buf).read().columns[0].chunks[0].statistics
349
+ assert statistics.is_null_count_exact is True
350
+ assert statistics.null_count == 1
351
+ assert statistics.distinct_count is None
352
+ # TODO: add tests for is_distinct_count_exact == None and True
353
+ # once Python API allows
354
+ assert statistics.is_distinct_count_exact is False
355
+ assert statistics.min == -1
356
+ assert statistics.is_min_exact
357
+ assert statistics.max == 3
358
+ assert statistics.is_max_exact
359
+ assert repr(statistics) == ("arrow.ArrayStatistics<"
360
+ "null_count=1, distinct_count=None, "
361
+ "min=-1, is_min_exact=True, "
362
+ "max=3, is_max_exact=True>")
363
+
364
+
365
+ def test_read_undefined_logical_type(parquet_test_datadir):
366
+ test_file = f"{parquet_test_datadir}/unknown-logical-type.parquet"
367
+
368
+ table = pq.ParquetFile(test_file).read()
369
+ assert table.column_names == ["column with known type", "column with unknown type"]
370
+ assert table["column with unknown type"].to_pylist() == [
371
+ b"unknown string 1",
372
+ b"unknown string 2",
373
+ b"unknown string 3"
374
+ ]
375
+
376
+
377
+ def test_parquet_file_fsspec_support():
378
+ pytest.importorskip("fsspec")
379
+
380
+ table = pa.table({"a": range(10)})
381
+ pq.write_table(table, "fsspec+memory://example.parquet")
382
+ table2 = pq.read_table("fsspec+memory://example.parquet")
383
+ assert table.equals(table2)
384
+
385
+ msg = "Unrecognized filesystem type in URI"
386
+ with pytest.raises(pa.ArrowInvalid, match=msg):
387
+ pq.read_table("non-existing://example.parquet")
388
+
389
+
390
+ def test_parquet_file_fsspec_support_through_filesystem_argument():
391
+ try:
392
+ from fsspec.implementations.memory import MemoryFileSystem
393
+ except ImportError:
394
+ pytest.skip("fsspec is not installed, skipping test")
395
+
396
+ table = pa.table({"b": range(10)})
397
+
398
+ fs = MemoryFileSystem()
399
+ fs.mkdir("/path/to/prefix", create_parents=True)
400
+ assert fs.exists("/path/to/prefix")
401
+
402
+ fs_str = "fsspec+memory://path/to/prefix"
403
+ pq.write_table(table, "b.parquet", filesystem=fs_str)
404
+ table2 = pq.read_table("fsspec+memory://path/to/prefix/b.parquet")
405
+ assert table.equals(table2)
406
+
407
+
408
+ def test_parquet_file_hugginface_support():
409
+ try:
410
+ from fsspec.implementations.memory import MemoryFileSystem
411
+ except ImportError:
412
+ pytest.skip("fsspec is not installed, skipping Hugging Face test")
413
+
414
+ fake_hf_module = types.ModuleType("huggingface_hub")
415
+ fake_hf_module.HfFileSystem = MemoryFileSystem
416
+ with mock.patch.dict("sys.modules", {"huggingface_hub": fake_hf_module}):
417
+ uri = "hf://datasets/apache/arrow/test.parquet"
418
+ table = pa.table({"a": range(10)})
419
+ pq.write_table(table, uri)
420
+ table2 = pq.read_table(uri)
421
+ assert table.equals(table2)
422
+
423
+
424
+ def test_fsspec_uri_raises_if_fsspec_is_not_available():
425
+ # sadly cannot patch sys.modules because cython will still be able to import fsspec
426
+ try:
427
+ import fsspec # noqa: F401
428
+ except ImportError:
429
+ pass
430
+ else:
431
+ pytest.skip("fsspec is available, skipping test")
432
+
433
+ msg = re.escape(
434
+ "`fsspec` is required to handle `fsspec+<filesystem>://` and `hf://` URIs.")
435
+ with pytest.raises(ImportError, match=msg):
436
+ pq.read_table("fsspec+memory://example.parquet")
437
+
438
+
439
+ def test_iter_batches_raises_batch_size_zero(tempdir):
440
+ # See https://github.com/apache/arrow/issues/46811
441
+ schema = pa.schema([])
442
+ empty_table = pa.Table.from_batches([], schema=schema)
443
+ parquet_file_path = tempdir / "empty_file.parquet"
444
+ pq.write_table(empty_table, parquet_file_path)
445
+ parquet_file = pq.ParquetFile(parquet_file_path)
446
+ with pytest.raises(ValueError):
447
+ parquet_file.iter_batches(batch_size=0)
shared/package-files/56/565ef8fb81829dc98a4be79bd3ac584d2e4a66d9a63a5ff80e55dc78583f95b6/blob ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from yaml.error import MarkedYAMLError
4
+
5
+ class ComposerError(MarkedYAMLError): ...
6
+
7
+ class Composer:
8
+ anchors: Any
9
+ def __init__(self) -> None: ...
10
+ def check_node(self): ...
11
+ def get_node(self): ...
12
+ def get_single_node(self): ...
13
+ def compose_document(self): ...
14
+ def compose_node(self, parent, index): ...
15
+ def compose_scalar_node(self, anchor): ...
16
+ def compose_sequence_node(self, anchor): ...
17
+ def compose_mapping_node(self, anchor): ...
shared/package-files/56/566141a62fbfb4d6bccb3366bbf7ee7dec263d39c253ac9c34219c377e1405c7/blob ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .geometry import cauchy_geometry, spider_geometry
2
+ from .optim import (
3
+ tangential_byrd_omojokun,
4
+ constrained_tangential_byrd_omojokun,
5
+ normal_byrd_omojokun,
6
+ )
7
+
8
+ __all__ = [
9
+ "cauchy_geometry",
10
+ "spider_geometry",
11
+ "tangential_byrd_omojokun",
12
+ "constrained_tangential_byrd_omojokun",
13
+ "normal_byrd_omojokun",
14
+ ]
shared/package-files/56/566520ef07b56189e8e87e331e08c2a0f63ba533b7cf314792714c0bca18c047/blob ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from socket import _RetAddress, socket
2
+ from threading import Thread
3
+ from typing import Dict, Protocol, Tuple
4
+
5
+ from paramiko.channel import Channel
6
+ from paramiko.message import Message
7
+ from paramiko.pkey import PKey
8
+ from paramiko.transport import Transport
9
+
10
+ class _AgentProxy(Protocol):
11
+ def connect(self) -> None: ...
12
+ def close(self) -> None: ...
13
+
14
+ cSSH2_AGENTC_REQUEST_IDENTITIES: bytes
15
+ SSH2_AGENT_IDENTITIES_ANSWER: int
16
+ cSSH2_AGENTC_SIGN_REQUEST: bytes
17
+ SSH2_AGENT_SIGN_RESPONSE: int
18
+
19
+ class AgentSSH:
20
+ def __init__(self) -> None: ...
21
+ def get_keys(self) -> Tuple[AgentKey, ...]: ...
22
+
23
+ class AgentProxyThread(Thread):
24
+ def __init__(self, agent: _AgentProxy) -> None: ...
25
+ def run(self) -> None: ...
26
+
27
+ class AgentLocalProxy(AgentProxyThread):
28
+ def __init__(self, agent: AgentServerProxy) -> None: ...
29
+ def get_connection(self) -> Tuple[socket, _RetAddress]: ...
30
+
31
+ class AgentRemoteProxy(AgentProxyThread):
32
+ def __init__(self, agent: AgentClientProxy, chan: Channel) -> None: ...
33
+ def get_connection(self) -> Tuple[socket, _RetAddress]: ...
34
+
35
+ class AgentClientProxy:
36
+ thread: Thread
37
+ def __init__(self, chanRemote: Channel) -> None: ...
38
+ def __del__(self) -> None: ...
39
+ def connect(self) -> None: ...
40
+ def close(self) -> None: ...
41
+
42
+ class AgentServerProxy(AgentSSH):
43
+ thread: Thread
44
+ def __init__(self, t: Transport) -> None: ...
45
+ def __del__(self) -> None: ...
46
+ def connect(self) -> None: ...
47
+ def close(self) -> None: ...
48
+ def get_env(self) -> Dict[str, str]: ...
49
+
50
+ class AgentRequestHandler:
51
+ def __init__(self, chanClient: Channel) -> None: ...
52
+ def __del__(self) -> None: ...
53
+ def close(self) -> None: ...
54
+
55
+ class Agent(AgentSSH):
56
+ def __init__(self) -> None: ...
57
+ def close(self) -> None: ...
58
+
59
+ class AgentKey(PKey):
60
+ agent: AgentSSH
61
+ blob: bytes
62
+ public_blob: None
63
+ name: str
64
+ def __init__(self, agent: AgentSSH, blob: bytes) -> None: ...
65
+ def asbytes(self) -> bytes: ...
66
+ def get_name(self) -> str: ...
67
+ def sign_ssh_data(self, data: bytes) -> Message: ...
shared/package-files/56/56664ff52e693ee705c72a80395f74f049965d066f8028162e6949253525d0b1/blob ADDED
Binary file (588 Bytes). View file
 
shared/package-files/56/5666818020fce78b306322e8b8330725fe0b2fa8943606a310e41fd295231e38/blob ADDED
Binary file (7.9 kB). View file
 
shared/package-files/56/5666bb7eda54f19534e85cecf9cca49fce014790c8cd7bb2eaf3b1646851eba8/blob ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ import getpass
3
+ import sys, os, pickle
4
+ import tempfile
5
+ import types
6
+ import re
7
+ from typing import (
8
+ TypeVar, Type, List, Dict, Iterator, Callable, Union, Optional, Sequence,
9
+ Tuple, Iterable, IO, Any, TYPE_CHECKING, Collection
10
+ )
11
+ if TYPE_CHECKING:
12
+ from .parsers.lalr_interactive_parser import InteractiveParser
13
+ from .tree import ParseTree
14
+ from .visitors import Transformer
15
+ if sys.version_info >= (3, 8):
16
+ from typing import Literal
17
+ else:
18
+ from typing_extensions import Literal
19
+ from .parser_frontends import ParsingFrontend
20
+
21
+ from .exceptions import ConfigurationError, assert_config, UnexpectedInput
22
+ from .utils import Serialize, SerializeMemoizer, FS, isascii, logger
23
+ from .load_grammar import load_grammar, FromPackageLoader, Grammar, verify_used_files, PackageResource, sha256_digest
24
+ from .tree import Tree
25
+ from .common import LexerConf, ParserConf, _ParserArgType, _LexerArgType
26
+
27
+ from .lexer import Lexer, BasicLexer, TerminalDef, LexerThread, Token
28
+ from .parse_tree_builder import ParseTreeBuilder
29
+ from .parser_frontends import _validate_frontend_args, _get_lexer_callbacks, _deserialize_parsing_frontend, _construct_parsing_frontend
30
+ from .grammar import Rule
31
+
32
+
33
+ try:
34
+ import regex
35
+ _has_regex = True
36
+ except ImportError:
37
+ _has_regex = False
38
+
39
+
40
+ ###{standalone
41
+
42
+
43
+ class PostLex(ABC):
44
+ @abstractmethod
45
+ def process(self, stream: Iterator[Token]) -> Iterator[Token]:
46
+ return stream
47
+
48
+ always_accept: Iterable[str] = ()
49
+
50
+ class LarkOptions(Serialize):
51
+ """Specifies the options for Lark
52
+
53
+ """
54
+
55
+ start: List[str]
56
+ debug: bool
57
+ strict: bool
58
+ transformer: 'Optional[Transformer]'
59
+ propagate_positions: Union[bool, str]
60
+ maybe_placeholders: bool
61
+ cache: Union[bool, str]
62
+ regex: bool
63
+ g_regex_flags: int
64
+ keep_all_tokens: bool
65
+ tree_class: Optional[Callable[[str, List], Any]]
66
+ parser: _ParserArgType
67
+ lexer: _LexerArgType
68
+ ambiguity: 'Literal["auto", "resolve", "explicit", "forest"]'
69
+ postlex: Optional[PostLex]
70
+ priority: 'Optional[Literal["auto", "normal", "invert"]]'
71
+ lexer_callbacks: Dict[str, Callable[[Token], Token]]
72
+ use_bytes: bool
73
+ ordered_sets: bool
74
+ edit_terminals: Optional[Callable[[TerminalDef], TerminalDef]]
75
+ import_paths: 'List[Union[str, Callable[[Union[None, str, PackageResource], str], Tuple[str, str]]]]'
76
+ source_path: Optional[str]
77
+
78
+ OPTIONS_DOC = r"""
79
+ **=== General Options ===**
80
+
81
+ start
82
+ The start symbol. Either a string, or a list of strings for multiple possible starts (Default: "start")
83
+ debug
84
+ Display debug information and extra warnings. Use only when debugging (Default: ``False``)
85
+ When used with Earley, it generates a forest graph as "sppf.png", if 'dot' is installed.
86
+ strict
87
+ Throw an exception on any potential ambiguity, including shift/reduce conflicts, and regex collisions.
88
+ transformer
89
+ Applies the transformer to every parse tree (equivalent to applying it after the parse, but faster)
90
+ propagate_positions
91
+ Propagates positional attributes into the 'meta' attribute of all tree branches.
92
+ Sets attributes: (line, column, end_line, end_column, start_pos, end_pos,
93
+ container_line, container_column, container_end_line, container_end_column)
94
+ Accepts ``False``, ``True``, or a callable, which will filter which nodes to ignore when propagating.
95
+ maybe_placeholders
96
+ When ``True``, the ``[]`` operator returns ``None`` when not matched.
97
+ When ``False``, ``[]`` behaves like the ``?`` operator, and returns no value at all.
98
+ (default= ``True``)
99
+ cache
100
+ Cache the results of the Lark grammar analysis, for x2 to x3 faster loading. LALR only for now.
101
+
102
+ - When ``False``, does nothing (default)
103
+ - When ``True``, caches to a temporary file in the local directory
104
+ - When given a string, caches to the path pointed by the string
105
+ regex
106
+ When True, uses the ``regex`` module instead of the stdlib ``re``.
107
+ g_regex_flags
108
+ Flags that are applied to all terminals (both regex and strings)
109
+ keep_all_tokens
110
+ Prevent the tree builder from automagically removing "punctuation" tokens (Default: ``False``)
111
+ tree_class
112
+ Lark will produce trees comprised of instances of this class instead of the default ``lark.Tree``.
113
+
114
+ **=== Algorithm Options ===**
115
+
116
+ parser
117
+ Decides which parser engine to use. Accepts "earley" or "lalr". (Default: "earley").
118
+ (there is also a "cyk" option for legacy)
119
+ lexer
120
+ Decides whether or not to use a lexer stage
121
+
122
+ - "auto" (default): Choose for me based on the parser
123
+ - "basic": Use a basic lexer
124
+ - "contextual": Stronger lexer (only works with parser="lalr")
125
+ - "dynamic": Flexible and powerful (only with parser="earley")
126
+ - "dynamic_complete": Same as dynamic, but tries *every* variation of tokenizing possible.
127
+ ambiguity
128
+ Decides how to handle ambiguity in the parse. Only relevant if parser="earley"
129
+
130
+ - "resolve": The parser will automatically choose the simplest derivation
131
+ (it chooses consistently: greedy for tokens, non-greedy for rules)
132
+ - "explicit": The parser will return all derivations wrapped in "_ambig" tree nodes (i.e. a forest).
133
+ - "forest": The parser will return the root of the shared packed parse forest.
134
+
135
+ **=== Misc. / Domain Specific Options ===**
136
+
137
+ postlex
138
+ Lexer post-processing (Default: ``None``) Only works with the basic and contextual lexers.
139
+ priority
140
+ How priorities should be evaluated - "auto", ``None``, "normal", "invert" (Default: "auto")
141
+ lexer_callbacks
142
+ Dictionary of callbacks for the lexer. May alter tokens during lexing. Use with caution.
143
+ use_bytes
144
+ Accept an input of type ``bytes`` instead of ``str``.
145
+ ordered_sets
146
+ Should Earley use ordered-sets to achieve stable output (~10% slower than regular sets. Default: True)
147
+ edit_terminals
148
+ A callback for editing the terminals before parse.
149
+ import_paths
150
+ A List of either paths or loader functions to specify from where grammars are imported
151
+ source_path
152
+ Override the source of from where the grammar was loaded. Useful for relative imports and unconventional grammar loading
153
+ **=== End of Options ===**
154
+ """
155
+ if __doc__:
156
+ __doc__ += OPTIONS_DOC
157
+
158
+
159
+ # Adding a new option needs to be done in multiple places:
160
+ # - In the dictionary below. This is the primary truth of which options `Lark.__init__` accepts
161
+ # - In the docstring above. It is used both for the docstring of `LarkOptions` and `Lark`, and in readthedocs
162
+ # - As an attribute of `LarkOptions` above
163
+ # - Potentially in `_LOAD_ALLOWED_OPTIONS` below this class, when the option doesn't change how the grammar is loaded
164
+ # - Potentially in `lark.tools.__init__`, if it makes sense, and it can easily be passed as a cmd argument
165
+ _defaults: Dict[str, Any] = {
166
+ 'debug': False,
167
+ 'strict': False,
168
+ 'keep_all_tokens': False,
169
+ 'tree_class': None,
170
+ 'cache': False,
171
+ 'postlex': None,
172
+ 'parser': 'earley',
173
+ 'lexer': 'auto',
174
+ 'transformer': None,
175
+ 'start': 'start',
176
+ 'priority': 'auto',
177
+ 'ambiguity': 'auto',
178
+ 'regex': False,
179
+ 'propagate_positions': False,
180
+ 'lexer_callbacks': {},
181
+ 'maybe_placeholders': True,
182
+ 'edit_terminals': None,
183
+ 'g_regex_flags': 0,
184
+ 'use_bytes': False,
185
+ 'ordered_sets': True,
186
+ 'import_paths': [],
187
+ 'source_path': None,
188
+ '_plugins': {},
189
+ }
190
+
191
+ def __init__(self, options_dict: Dict[str, Any]) -> None:
192
+ o = dict(options_dict)
193
+
194
+ options = {}
195
+ for name, default in self._defaults.items():
196
+ if name in o:
197
+ value = o.pop(name)
198
+ if isinstance(default, bool) and name not in ('cache', 'use_bytes', 'propagate_positions'):
199
+ value = bool(value)
200
+ else:
201
+ value = default
202
+
203
+ options[name] = value
204
+
205
+ if isinstance(options['start'], str):
206
+ options['start'] = [options['start']]
207
+
208
+ self.__dict__['options'] = options
209
+
210
+
211
+ assert_config(self.parser, ('earley', 'lalr', 'cyk', None))
212
+
213
+ if self.parser == 'earley' and self.transformer:
214
+ raise ConfigurationError('Cannot specify an embedded transformer when using the Earley algorithm. '
215
+ 'Please use your transformer on the resulting parse tree, or use a different algorithm (i.e. LALR)')
216
+
217
+ if o:
218
+ raise ConfigurationError("Unknown options: %s" % o.keys())
219
+
220
+ def __getattr__(self, name: str) -> Any:
221
+ try:
222
+ return self.__dict__['options'][name]
223
+ except KeyError as e:
224
+ raise AttributeError(e)
225
+
226
+ def __setattr__(self, name: str, value: str) -> None:
227
+ assert_config(name, self.options.keys(), "%r isn't a valid option. Expected one of: %s")
228
+ self.options[name] = value
229
+
230
+ def serialize(self, memo = None) -> Dict[str, Any]:
231
+ return self.options
232
+
233
+ @classmethod
234
+ def deserialize(cls, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]]) -> "LarkOptions":
235
+ return cls(data)
236
+
237
+
238
+ # Options that can be passed to the Lark parser, even when it was loaded from cache/standalone.
239
+ # These options are only used outside of `load_grammar`.
240
+ _LOAD_ALLOWED_OPTIONS = {'postlex', 'transformer', 'lexer_callbacks', 'use_bytes', 'debug', 'g_regex_flags', 'regex', 'propagate_positions', 'tree_class', '_plugins'}
241
+
242
+ _VALID_PRIORITY_OPTIONS = ('auto', 'normal', 'invert', None)
243
+ _VALID_AMBIGUITY_OPTIONS = ('auto', 'resolve', 'explicit', 'forest')
244
+
245
+
246
+ _T = TypeVar('_T', bound="Lark")
247
+
248
+ class Lark(Serialize):
249
+ """Main interface for the library.
250
+
251
+ It's mostly a thin wrapper for the many different parsers, and for the tree constructor.
252
+
253
+ Parameters:
254
+ grammar: a string or file-object containing the grammar spec (using Lark's ebnf syntax)
255
+ options: a dictionary controlling various aspects of Lark.
256
+
257
+ Example:
258
+ >>> Lark(r'''start: "foo" ''')
259
+ Lark(...)
260
+ """
261
+
262
+ source_path: str
263
+ source_grammar: str
264
+ grammar: 'Grammar'
265
+ options: LarkOptions
266
+ lexer: Lexer
267
+ parser: 'ParsingFrontend'
268
+ terminals: Collection[TerminalDef]
269
+
270
+ def __init__(self, grammar: 'Union[Grammar, str, IO[str]]', **options) -> None:
271
+ self.options = LarkOptions(options)
272
+ re_module: types.ModuleType
273
+
274
+ # Set regex or re module
275
+ use_regex = self.options.regex
276
+ if use_regex:
277
+ if _has_regex:
278
+ re_module = regex
279
+ else:
280
+ raise ImportError('`regex` module must be installed if calling `Lark(regex=True)`.')
281
+ else:
282
+ re_module = re
283
+
284
+ # Some, but not all file-like objects have a 'name' attribute
285
+ if self.options.source_path is None:
286
+ try:
287
+ self.source_path = grammar.name # type: ignore[union-attr]
288
+ except AttributeError:
289
+ self.source_path = '<string>'
290
+ else:
291
+ self.source_path = self.options.source_path
292
+
293
+ # Drain file-like objects to get their contents
294
+ try:
295
+ read = grammar.read # type: ignore[union-attr]
296
+ except AttributeError:
297
+ pass
298
+ else:
299
+ grammar = read()
300
+
301
+ cache_fn = None
302
+ cache_sha256 = None
303
+ if isinstance(grammar, str):
304
+ self.source_grammar = grammar
305
+ if self.options.use_bytes:
306
+ if not isascii(grammar):
307
+ raise ConfigurationError("Grammar must be ascii only, when use_bytes=True")
308
+
309
+ if self.options.cache:
310
+ if self.options.parser != 'lalr':
311
+ raise ConfigurationError("cache only works with parser='lalr' for now")
312
+
313
+ unhashable = ('transformer', 'postlex', 'lexer_callbacks', 'edit_terminals', '_plugins')
314
+ options_str = ''.join(k+str(v) for k, v in options.items() if k not in unhashable)
315
+ from . import __version__
316
+ s = grammar + options_str + __version__ + str(sys.version_info[:2])
317
+ cache_sha256 = sha256_digest(s)
318
+
319
+ if isinstance(self.options.cache, str):
320
+ cache_fn = self.options.cache
321
+ else:
322
+ if self.options.cache is not True:
323
+ raise ConfigurationError("cache argument must be bool or str")
324
+
325
+ try:
326
+ username = getpass.getuser()
327
+ except Exception:
328
+ # The exception raised may be ImportError or OSError in
329
+ # the future. For the cache, we don't care about the
330
+ # specific reason - we just want a username.
331
+ username = "unknown"
332
+
333
+ cache_fn = tempfile.gettempdir() + "/.lark_cache_%s_%s_%s_%s.tmp" % (username, cache_sha256, *sys.version_info[:2])
334
+
335
+ old_options = self.options
336
+ try:
337
+ with FS.open(cache_fn, 'rb') as f:
338
+ logger.debug('Loading grammar from cache: %s', cache_fn)
339
+ # Remove options that aren't relevant for loading from cache
340
+ for name in (set(options) - _LOAD_ALLOWED_OPTIONS):
341
+ del options[name]
342
+ file_sha256 = f.readline().rstrip(b'\n')
343
+ cached_used_files = pickle.load(f)
344
+ if file_sha256 == cache_sha256.encode('utf8') and verify_used_files(cached_used_files):
345
+ cached_parser_data = pickle.load(f)
346
+ self._load(cached_parser_data, **options)
347
+ return
348
+ except FileNotFoundError:
349
+ # The cache file doesn't exist; parse and compose the grammar as normal
350
+ pass
351
+ except Exception: # We should probably narrow done which errors we catch here.
352
+ logger.exception("Failed to load Lark from cache: %r. We will try to carry on.", cache_fn)
353
+
354
+ # In theory, the Lark instance might have been messed up by the call to `_load`.
355
+ # In practice the only relevant thing that might have been overwritten should be `options`
356
+ self.options = old_options
357
+
358
+
359
+ # Parse the grammar file and compose the grammars
360
+ self.grammar, used_files = load_grammar(grammar, self.source_path, self.options.import_paths, self.options.keep_all_tokens)
361
+ else:
362
+ assert isinstance(grammar, Grammar)
363
+ self.grammar = grammar
364
+
365
+
366
+ if self.options.lexer == 'auto':
367
+ if self.options.parser == 'lalr':
368
+ self.options.lexer = 'contextual'
369
+ elif self.options.parser == 'earley':
370
+ if self.options.postlex is not None:
371
+ logger.info("postlex can't be used with the dynamic lexer, so we use 'basic' instead. "
372
+ "Consider using lalr with contextual instead of earley")
373
+ self.options.lexer = 'basic'
374
+ else:
375
+ self.options.lexer = 'dynamic'
376
+ elif self.options.parser == 'cyk':
377
+ self.options.lexer = 'basic'
378
+ else:
379
+ assert False, self.options.parser
380
+ lexer = self.options.lexer
381
+ if isinstance(lexer, type):
382
+ assert issubclass(lexer, Lexer) # XXX Is this really important? Maybe just ensure interface compliance
383
+ else:
384
+ assert_config(lexer, ('basic', 'contextual', 'dynamic', 'dynamic_complete'))
385
+ if self.options.postlex is not None and 'dynamic' in lexer:
386
+ raise ConfigurationError("Can't use postlex with a dynamic lexer. Use basic or contextual instead")
387
+
388
+ if self.options.ambiguity == 'auto':
389
+ if self.options.parser == 'earley':
390
+ self.options.ambiguity = 'resolve'
391
+ else:
392
+ assert_config(self.options.parser, ('earley', 'cyk'), "%r doesn't support disambiguation. Use one of these parsers instead: %s")
393
+
394
+ if self.options.priority == 'auto':
395
+ self.options.priority = 'normal'
396
+
397
+ if self.options.priority not in _VALID_PRIORITY_OPTIONS:
398
+ raise ConfigurationError("invalid priority option: %r. Must be one of %r" % (self.options.priority, _VALID_PRIORITY_OPTIONS))
399
+ if self.options.ambiguity not in _VALID_AMBIGUITY_OPTIONS:
400
+ raise ConfigurationError("invalid ambiguity option: %r. Must be one of %r" % (self.options.ambiguity, _VALID_AMBIGUITY_OPTIONS))
401
+
402
+ if self.options.parser is None:
403
+ terminals_to_keep = '*'
404
+ elif self.options.postlex is not None:
405
+ terminals_to_keep = set(self.options.postlex.always_accept)
406
+ else:
407
+ terminals_to_keep = set()
408
+
409
+ # Compile the EBNF grammar into BNF
410
+ self.terminals, self.rules, self.ignore_tokens = self.grammar.compile(self.options.start, terminals_to_keep)
411
+
412
+ if self.options.edit_terminals:
413
+ for t in self.terminals:
414
+ self.options.edit_terminals(t)
415
+
416
+ self._terminals_dict = {t.name: t for t in self.terminals}
417
+
418
+ # If the user asked to invert the priorities, negate them all here.
419
+ if self.options.priority == 'invert':
420
+ for rule in self.rules:
421
+ if rule.options.priority is not None:
422
+ rule.options.priority = -rule.options.priority
423
+ for term in self.terminals:
424
+ term.priority = -term.priority
425
+ # Else, if the user asked to disable priorities, strip them from the
426
+ # rules and terminals. This allows the Earley parsers to skip an extra forest walk
427
+ # for improved performance, if you don't need them (or didn't specify any).
428
+ elif self.options.priority is None:
429
+ for rule in self.rules:
430
+ if rule.options.priority is not None:
431
+ rule.options.priority = None
432
+ for term in self.terminals:
433
+ term.priority = 0
434
+
435
+ # TODO Deprecate lexer_callbacks?
436
+ self.lexer_conf = LexerConf(
437
+ self.terminals, re_module, self.ignore_tokens, self.options.postlex,
438
+ self.options.lexer_callbacks, self.options.g_regex_flags, use_bytes=self.options.use_bytes, strict=self.options.strict
439
+ )
440
+
441
+ if self.options.parser:
442
+ self.parser = self._build_parser()
443
+ elif lexer:
444
+ self.lexer = self._build_lexer()
445
+
446
+ if cache_fn:
447
+ logger.debug('Saving grammar to cache: %s', cache_fn)
448
+ try:
449
+ with FS.open(cache_fn, 'wb') as f:
450
+ assert cache_sha256 is not None
451
+ f.write(cache_sha256.encode('utf8') + b'\n')
452
+ pickle.dump(used_files, f)
453
+ self.save(f, _LOAD_ALLOWED_OPTIONS)
454
+ except IOError as e:
455
+ logger.exception("Failed to save Lark to cache: %r.", cache_fn, e)
456
+
457
+ if __doc__:
458
+ __doc__ += "\n\n" + LarkOptions.OPTIONS_DOC
459
+
460
+ __serialize_fields__ = 'parser', 'rules', 'options'
461
+
462
+ def _build_lexer(self, dont_ignore: bool=False) -> BasicLexer:
463
+ lexer_conf = self.lexer_conf
464
+ if dont_ignore:
465
+ from copy import copy
466
+ lexer_conf = copy(lexer_conf)
467
+ lexer_conf.ignore = ()
468
+ return BasicLexer(lexer_conf)
469
+
470
+ def _prepare_callbacks(self) -> None:
471
+ self._callbacks = {}
472
+ # we don't need these callbacks if we aren't building a tree
473
+ if self.options.ambiguity != 'forest':
474
+ self._parse_tree_builder = ParseTreeBuilder(
475
+ self.rules,
476
+ self.options.tree_class or Tree,
477
+ self.options.propagate_positions,
478
+ self.options.parser != 'lalr' and self.options.ambiguity == 'explicit',
479
+ self.options.maybe_placeholders
480
+ )
481
+ self._callbacks = self._parse_tree_builder.create_callback(self.options.transformer)
482
+ self._callbacks.update(_get_lexer_callbacks(self.options.transformer, self.terminals))
483
+
484
+ def _build_parser(self) -> "ParsingFrontend":
485
+ self._prepare_callbacks()
486
+ _validate_frontend_args(self.options.parser, self.options.lexer)
487
+ parser_conf = ParserConf(self.rules, self._callbacks, self.options.start)
488
+ return _construct_parsing_frontend(
489
+ self.options.parser,
490
+ self.options.lexer,
491
+ self.lexer_conf,
492
+ parser_conf,
493
+ options=self.options
494
+ )
495
+
496
+ def save(self, f, exclude_options: Collection[str] = ()) -> None:
497
+ """Saves the instance into the given file object
498
+
499
+ Useful for caching and multiprocessing.
500
+ """
501
+ if self.options.parser != 'lalr':
502
+ raise NotImplementedError("Lark.save() is only implemented for the LALR(1) parser.")
503
+ data, m = self.memo_serialize([TerminalDef, Rule])
504
+ if exclude_options:
505
+ data["options"] = {n: v for n, v in data["options"].items() if n not in exclude_options}
506
+ pickle.dump({'data': data, 'memo': m}, f, protocol=pickle.HIGHEST_PROTOCOL)
507
+
508
+ @classmethod
509
+ def load(cls: Type[_T], f) -> _T:
510
+ """Loads an instance from the given file object
511
+
512
+ Useful for caching and multiprocessing.
513
+ """
514
+ inst = cls.__new__(cls)
515
+ return inst._load(f)
516
+
517
+ def _deserialize_lexer_conf(self, data: Dict[str, Any], memo: Dict[int, Union[TerminalDef, Rule]], options: LarkOptions) -> LexerConf:
518
+ lexer_conf = LexerConf.deserialize(data['lexer_conf'], memo)
519
+ lexer_conf.callbacks = options.lexer_callbacks or {}
520
+ lexer_conf.re_module = regex if options.regex else re
521
+ lexer_conf.use_bytes = options.use_bytes
522
+ lexer_conf.g_regex_flags = options.g_regex_flags
523
+ lexer_conf.skip_validation = True
524
+ lexer_conf.postlex = options.postlex
525
+ return lexer_conf
526
+
527
+ def _load(self: _T, f: Any, **kwargs) -> _T:
528
+ if isinstance(f, dict):
529
+ d = f
530
+ else:
531
+ d = pickle.load(f)
532
+ memo_json = d['memo']
533
+ data = d['data']
534
+
535
+ assert memo_json
536
+ memo = SerializeMemoizer.deserialize(memo_json, {'Rule': Rule, 'TerminalDef': TerminalDef}, {})
537
+ options = dict(data['options'])
538
+ if (set(kwargs) - _LOAD_ALLOWED_OPTIONS) & set(LarkOptions._defaults):
539
+ raise ConfigurationError("Some options are not allowed when loading a Parser: {}"
540
+ .format(set(kwargs) - _LOAD_ALLOWED_OPTIONS))
541
+ options.update(kwargs)
542
+ self.options = LarkOptions.deserialize(options, memo)
543
+ self.rules = [Rule.deserialize(r, memo) for r in data['rules']]
544
+ self.source_path = '<deserialized>'
545
+ _validate_frontend_args(self.options.parser, self.options.lexer)
546
+ self.lexer_conf = self._deserialize_lexer_conf(data['parser'], memo, self.options)
547
+ self.terminals = self.lexer_conf.terminals
548
+ self._prepare_callbacks()
549
+ self._terminals_dict = {t.name: t for t in self.terminals}
550
+ self.parser = _deserialize_parsing_frontend(
551
+ data['parser'],
552
+ memo,
553
+ self.lexer_conf,
554
+ self._callbacks,
555
+ self.options, # Not all, but multiple attributes are used
556
+ )
557
+ return self
558
+
559
+ @classmethod
560
+ def _load_from_dict(cls, data, memo, **kwargs):
561
+ inst = cls.__new__(cls)
562
+ return inst._load({'data': data, 'memo': memo}, **kwargs)
563
+
564
+ @classmethod
565
+ def open(cls: Type[_T], grammar_filename: str, rel_to: Optional[str]=None, **options) -> _T:
566
+ """Create an instance of Lark with the grammar given by its filename
567
+
568
+ If ``rel_to`` is provided, the function will find the grammar filename in relation to it.
569
+
570
+ Example:
571
+
572
+ >>> Lark.open("grammar_file.lark", rel_to=__file__, parser="lalr")
573
+ Lark(...)
574
+
575
+ """
576
+ if rel_to:
577
+ basepath = os.path.dirname(rel_to)
578
+ grammar_filename = os.path.join(basepath, grammar_filename)
579
+ with open(grammar_filename, encoding='utf8') as f:
580
+ return cls(f, **options)
581
+
582
+ @classmethod
583
+ def open_from_package(cls: Type[_T], package: str, grammar_path: str, search_paths: 'Sequence[str]'=[""], **options) -> _T:
584
+ """Create an instance of Lark with the grammar loaded from within the package `package`.
585
+ This allows grammar loading from zipapps.
586
+
587
+ Imports in the grammar will use the `package` and `search_paths` provided, through `FromPackageLoader`
588
+
589
+ Example:
590
+
591
+ Lark.open_from_package(__name__, "example.lark", ("grammars",), parser=...)
592
+ """
593
+ package_loader = FromPackageLoader(package, search_paths)
594
+ full_path, text = package_loader(None, grammar_path)
595
+ options.setdefault('source_path', full_path)
596
+ options.setdefault('import_paths', [])
597
+ options['import_paths'].append(package_loader)
598
+ return cls(text, **options)
599
+
600
+ def __repr__(self):
601
+ return 'Lark(open(%r), parser=%r, lexer=%r, ...)' % (self.source_path, self.options.parser, self.options.lexer)
602
+
603
+
604
+ def lex(self, text: str, dont_ignore: bool=False) -> Iterator[Token]:
605
+ """Only lex (and postlex) the text, without parsing it. Only relevant when lexer='basic'
606
+
607
+ When dont_ignore=True, the lexer will return all tokens, even those marked for %ignore.
608
+
609
+ :raises UnexpectedCharacters: In case the lexer cannot find a suitable match.
610
+ """
611
+ lexer: Lexer
612
+ if not hasattr(self, 'lexer') or dont_ignore:
613
+ lexer = self._build_lexer(dont_ignore)
614
+ else:
615
+ lexer = self.lexer
616
+ lexer_thread = LexerThread.from_text(lexer, text)
617
+ stream = lexer_thread.lex(None)
618
+ if self.options.postlex:
619
+ return self.options.postlex.process(stream)
620
+ return stream
621
+
622
+ def get_terminal(self, name: str) -> TerminalDef:
623
+ """Get information about a terminal"""
624
+ return self._terminals_dict[name]
625
+
626
+ def parse_interactive(self, text: Optional[str]=None, start: Optional[str]=None) -> 'InteractiveParser':
627
+ """Start an interactive parsing session.
628
+
629
+ Parameters:
630
+ text (str, optional): Text to be parsed. Required for ``resume_parse()``.
631
+ start (str, optional): Start symbol
632
+
633
+ Returns:
634
+ A new InteractiveParser instance.
635
+
636
+ See Also: ``Lark.parse()``
637
+ """
638
+ return self.parser.parse_interactive(text, start=start)
639
+
640
+ def parse(self, text: str, start: Optional[str]=None, on_error: 'Optional[Callable[[UnexpectedInput], bool]]'=None) -> 'ParseTree':
641
+ """Parse the given text, according to the options provided.
642
+
643
+ Parameters:
644
+ text (str): Text to be parsed.
645
+ start (str, optional): Required if Lark was given multiple possible start symbols (using the start option).
646
+ on_error (function, optional): if provided, will be called on UnexpectedToken error. Return true to resume parsing.
647
+ LALR only. See examples/advanced/error_handling.py for an example of how to use on_error.
648
+
649
+ Returns:
650
+ If a transformer is supplied to ``__init__``, returns whatever is the
651
+ result of the transformation. Otherwise, returns a Tree instance.
652
+
653
+ :raises UnexpectedInput: On a parse error, one of these sub-exceptions will rise:
654
+ ``UnexpectedCharacters``, ``UnexpectedToken``, or ``UnexpectedEOF``.
655
+ For convenience, these sub-exceptions also inherit from ``ParserError`` and ``LexerError``.
656
+
657
+ """
658
+ return self.parser.parse(text, start=start, on_error=on_error)
659
+
660
+
661
+ ###}
shared/package-files/56/56678668d6a1892cc1253e114d7301f010ea40bbce65c8d67bfc518a620f3f62/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeimplicitautograd {
19
+
20
+ TORCH_API at::Tensor conj_physical(const at::Tensor & self);
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
shared/package-files/56/5667c31dcece0b6d20cad709faa0d16a2a57ee42563742cfa16ea8c0cca4dc48/blob ADDED
@@ -0,0 +1,1331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from datetime import timedelta
4
+ import operator
5
+ from typing import (
6
+ TYPE_CHECKING,
7
+ Any,
8
+ Callable,
9
+ Literal,
10
+ TypeVar,
11
+ cast,
12
+ overload,
13
+ )
14
+ import warnings
15
+
16
+ import numpy as np
17
+
18
+ from pandas._libs import (
19
+ algos as libalgos,
20
+ lib,
21
+ )
22
+ from pandas._libs.arrays import NDArrayBacked
23
+ from pandas._libs.tslibs import (
24
+ BaseOffset,
25
+ NaT,
26
+ NaTType,
27
+ Timedelta,
28
+ add_overflowsafe,
29
+ astype_overflowsafe,
30
+ dt64arr_to_periodarr as c_dt64arr_to_periodarr,
31
+ get_unit_from_dtype,
32
+ iNaT,
33
+ parsing,
34
+ period as libperiod,
35
+ to_offset,
36
+ )
37
+ from pandas._libs.tslibs.dtypes import (
38
+ FreqGroup,
39
+ PeriodDtypeBase,
40
+ freq_to_period_freqstr,
41
+ )
42
+ from pandas._libs.tslibs.fields import isleapyear_arr
43
+ from pandas._libs.tslibs.offsets import (
44
+ Tick,
45
+ delta_to_tick,
46
+ )
47
+ from pandas._libs.tslibs.period import (
48
+ DIFFERENT_FREQ,
49
+ IncompatibleFrequency,
50
+ Period,
51
+ get_period_field_arr,
52
+ period_asfreq_arr,
53
+ )
54
+ from pandas.util._decorators import (
55
+ cache_readonly,
56
+ doc,
57
+ )
58
+ from pandas.util._exceptions import find_stack_level
59
+
60
+ from pandas.core.dtypes.common import (
61
+ ensure_object,
62
+ pandas_dtype,
63
+ )
64
+ from pandas.core.dtypes.dtypes import (
65
+ DatetimeTZDtype,
66
+ PeriodDtype,
67
+ )
68
+ from pandas.core.dtypes.generic import (
69
+ ABCIndex,
70
+ ABCPeriodIndex,
71
+ ABCSeries,
72
+ ABCTimedeltaArray,
73
+ )
74
+ from pandas.core.dtypes.missing import isna
75
+
76
+ from pandas.core.arrays import datetimelike as dtl
77
+ import pandas.core.common as com
78
+
79
+ if TYPE_CHECKING:
80
+ from collections.abc import Sequence
81
+
82
+ from pandas._typing import (
83
+ AnyArrayLike,
84
+ Dtype,
85
+ FillnaOptions,
86
+ NpDtype,
87
+ NumpySorter,
88
+ NumpyValueArrayLike,
89
+ Self,
90
+ npt,
91
+ )
92
+
93
+ from pandas.core.arrays import (
94
+ DatetimeArray,
95
+ TimedeltaArray,
96
+ )
97
+ from pandas.core.arrays.base import ExtensionArray
98
+
99
+
100
+ BaseOffsetT = TypeVar("BaseOffsetT", bound=BaseOffset)
101
+
102
+
103
+ _shared_doc_kwargs = {
104
+ "klass": "PeriodArray",
105
+ }
106
+
107
+
108
+ def _field_accessor(name: str, docstring: str | None = None):
109
+ def f(self):
110
+ base = self.dtype._dtype_code
111
+ result = get_period_field_arr(name, self.asi8, base)
112
+ return result
113
+
114
+ f.__name__ = name
115
+ f.__doc__ = docstring
116
+ return property(f)
117
+
118
+
119
+ # error: Definition of "_concat_same_type" in base class "NDArrayBacked" is
120
+ # incompatible with definition in base class "ExtensionArray"
121
+ class PeriodArray(dtl.DatelikeOps, libperiod.PeriodMixin): # type: ignore[misc]
122
+ """
123
+ Pandas ExtensionArray for storing Period data.
124
+
125
+ Users should use :func:`~pandas.array` to create new instances.
126
+
127
+ Parameters
128
+ ----------
129
+ values : Union[PeriodArray, Series[period], ndarray[int], PeriodIndex]
130
+ The data to store. These should be arrays that can be directly
131
+ converted to ordinals without inference or copy (PeriodArray,
132
+ ndarray[int64]), or a box around such an array (Series[period],
133
+ PeriodIndex).
134
+ dtype : PeriodDtype, optional
135
+ A PeriodDtype instance from which to extract a `freq`. If both
136
+ `freq` and `dtype` are specified, then the frequencies must match.
137
+ freq : str or DateOffset
138
+ The `freq` to use for the array. Mostly applicable when `values`
139
+ is an ndarray of integers, when `freq` is required. When `values`
140
+ is a PeriodArray (or box around), it's checked that ``values.freq``
141
+ matches `freq`.
142
+ copy : bool, default False
143
+ Whether to copy the ordinals before storing.
144
+
145
+ Attributes
146
+ ----------
147
+ None
148
+
149
+ Methods
150
+ -------
151
+ None
152
+
153
+ See Also
154
+ --------
155
+ Period: Represents a period of time.
156
+ PeriodIndex : Immutable Index for period data.
157
+ period_range: Create a fixed-frequency PeriodArray.
158
+ array: Construct a pandas array.
159
+
160
+ Notes
161
+ -----
162
+ There are two components to a PeriodArray
163
+
164
+ - ordinals : integer ndarray
165
+ - freq : pd.tseries.offsets.Offset
166
+
167
+ The values are physically stored as a 1-D ndarray of integers. These are
168
+ called "ordinals" and represent some kind of offset from a base.
169
+
170
+ The `freq` indicates the span covered by each element of the array.
171
+ All elements in the PeriodArray have the same `freq`.
172
+
173
+ Examples
174
+ --------
175
+ >>> pd.arrays.PeriodArray(pd.PeriodIndex(['2023-01-01',
176
+ ... '2023-01-02'], freq='D'))
177
+ <PeriodArray>
178
+ ['2023-01-01', '2023-01-02']
179
+ Length: 2, dtype: period[D]
180
+ """
181
+
182
+ # array priority higher than numpy scalars
183
+ __array_priority__ = 1000
184
+ _typ = "periodarray" # ABCPeriodArray
185
+ _internal_fill_value = np.int64(iNaT)
186
+ _recognized_scalars = (Period,)
187
+ _is_recognized_dtype = lambda x: isinstance(
188
+ x, PeriodDtype
189
+ ) # check_compatible_with checks freq match
190
+ _infer_matches = ("period",)
191
+
192
+ @property
193
+ def _scalar_type(self) -> type[Period]:
194
+ return Period
195
+
196
+ # Names others delegate to us
197
+ _other_ops: list[str] = []
198
+ _bool_ops: list[str] = ["is_leap_year"]
199
+ _object_ops: list[str] = ["start_time", "end_time", "freq"]
200
+ _field_ops: list[str] = [
201
+ "year",
202
+ "month",
203
+ "day",
204
+ "hour",
205
+ "minute",
206
+ "second",
207
+ "weekofyear",
208
+ "weekday",
209
+ "week",
210
+ "dayofweek",
211
+ "day_of_week",
212
+ "dayofyear",
213
+ "day_of_year",
214
+ "quarter",
215
+ "qyear",
216
+ "days_in_month",
217
+ "daysinmonth",
218
+ ]
219
+ _datetimelike_ops: list[str] = _field_ops + _object_ops + _bool_ops
220
+ _datetimelike_methods: list[str] = ["strftime", "to_timestamp", "asfreq"]
221
+
222
+ _dtype: PeriodDtype
223
+
224
+ # --------------------------------------------------------------------
225
+ # Constructors
226
+
227
+ def __init__(
228
+ self, values, dtype: Dtype | None = None, freq=None, copy: bool = False
229
+ ) -> None:
230
+ if freq is not None:
231
+ # GH#52462
232
+ warnings.warn(
233
+ "The 'freq' keyword in the PeriodArray constructor is deprecated "
234
+ "and will be removed in a future version. Pass 'dtype' instead",
235
+ FutureWarning,
236
+ stacklevel=find_stack_level(),
237
+ )
238
+ freq = validate_dtype_freq(dtype, freq)
239
+ dtype = PeriodDtype(freq)
240
+
241
+ if dtype is not None:
242
+ dtype = pandas_dtype(dtype)
243
+ if not isinstance(dtype, PeriodDtype):
244
+ raise ValueError(f"Invalid dtype {dtype} for PeriodArray")
245
+
246
+ if isinstance(values, ABCSeries):
247
+ values = values._values
248
+ if not isinstance(values, type(self)):
249
+ raise TypeError("Incorrect dtype")
250
+
251
+ elif isinstance(values, ABCPeriodIndex):
252
+ values = values._values
253
+
254
+ if isinstance(values, type(self)):
255
+ if dtype is not None and dtype != values.dtype:
256
+ raise raise_on_incompatible(values, dtype.freq)
257
+ values, dtype = values._ndarray, values.dtype
258
+
259
+ if not copy:
260
+ values = np.asarray(values, dtype="int64")
261
+ else:
262
+ values = np.array(values, dtype="int64", copy=copy)
263
+ if dtype is None:
264
+ raise ValueError("dtype is not specified and cannot be inferred")
265
+ dtype = cast(PeriodDtype, dtype)
266
+ NDArrayBacked.__init__(self, values, dtype)
267
+
268
+ # error: Signature of "_simple_new" incompatible with supertype "NDArrayBacked"
269
+ @classmethod
270
+ def _simple_new( # type: ignore[override]
271
+ cls,
272
+ values: npt.NDArray[np.int64],
273
+ dtype: PeriodDtype,
274
+ ) -> Self:
275
+ # alias for PeriodArray.__init__
276
+ assertion_msg = "Should be numpy array of type i8"
277
+ assert isinstance(values, np.ndarray) and values.dtype == "i8", assertion_msg
278
+ return cls(values, dtype=dtype)
279
+
280
+ @classmethod
281
+ def _from_sequence(
282
+ cls,
283
+ scalars,
284
+ *,
285
+ dtype: Dtype | None = None,
286
+ copy: bool = False,
287
+ ) -> Self:
288
+ if dtype is not None:
289
+ dtype = pandas_dtype(dtype)
290
+ if dtype and isinstance(dtype, PeriodDtype):
291
+ freq = dtype.freq
292
+ else:
293
+ freq = None
294
+
295
+ if isinstance(scalars, cls):
296
+ validate_dtype_freq(scalars.dtype, freq)
297
+ if copy:
298
+ scalars = scalars.copy()
299
+ return scalars
300
+
301
+ periods = np.asarray(scalars, dtype=object)
302
+
303
+ freq = freq or libperiod.extract_freq(periods)
304
+ ordinals = libperiod.extract_ordinals(periods, freq)
305
+ dtype = PeriodDtype(freq)
306
+ return cls(ordinals, dtype=dtype)
307
+
308
+ @classmethod
309
+ def _from_sequence_of_strings(
310
+ cls, strings, *, dtype: Dtype | None = None, copy: bool = False
311
+ ) -> Self:
312
+ return cls._from_sequence(strings, dtype=dtype, copy=copy)
313
+
314
+ @classmethod
315
+ def _from_datetime64(cls, data, freq, tz=None) -> Self:
316
+ """
317
+ Construct a PeriodArray from a datetime64 array
318
+
319
+ Parameters
320
+ ----------
321
+ data : ndarray[datetime64[ns], datetime64[ns, tz]]
322
+ freq : str or Tick
323
+ tz : tzinfo, optional
324
+
325
+ Returns
326
+ -------
327
+ PeriodArray[freq]
328
+ """
329
+ if isinstance(freq, BaseOffset):
330
+ freq = freq_to_period_freqstr(freq.n, freq.name)
331
+ data, freq = dt64arr_to_periodarr(data, freq, tz)
332
+ dtype = PeriodDtype(freq)
333
+ return cls(data, dtype=dtype)
334
+
335
+ @classmethod
336
+ def _generate_range(cls, start, end, periods, freq):
337
+ periods = dtl.validate_periods(periods)
338
+
339
+ if freq is not None:
340
+ freq = Period._maybe_convert_freq(freq)
341
+
342
+ if start is not None or end is not None:
343
+ subarr, freq = _get_ordinal_range(start, end, periods, freq)
344
+ else:
345
+ raise ValueError("Not enough parameters to construct Period range")
346
+
347
+ return subarr, freq
348
+
349
+ @classmethod
350
+ def _from_fields(cls, *, fields: dict, freq) -> Self:
351
+ subarr, freq = _range_from_fields(freq=freq, **fields)
352
+ dtype = PeriodDtype(freq)
353
+ return cls._simple_new(subarr, dtype=dtype)
354
+
355
+ # -----------------------------------------------------------------
356
+ # DatetimeLike Interface
357
+
358
+ # error: Argument 1 of "_unbox_scalar" is incompatible with supertype
359
+ # "DatetimeLikeArrayMixin"; supertype defines the argument type as
360
+ # "Union[Union[Period, Any, Timedelta], NaTType]"
361
+ def _unbox_scalar( # type: ignore[override]
362
+ self,
363
+ value: Period | NaTType,
364
+ ) -> np.int64:
365
+ if value is NaT:
366
+ # error: Item "Period" of "Union[Period, NaTType]" has no attribute "value"
367
+ return np.int64(value._value) # type: ignore[union-attr]
368
+ elif isinstance(value, self._scalar_type):
369
+ self._check_compatible_with(value)
370
+ return np.int64(value.ordinal)
371
+ else:
372
+ raise ValueError(f"'value' should be a Period. Got '{value}' instead.")
373
+
374
+ def _scalar_from_string(self, value: str) -> Period:
375
+ return Period(value, freq=self.freq)
376
+
377
+ # error: Argument 1 of "_check_compatible_with" is incompatible with
378
+ # supertype "DatetimeLikeArrayMixin"; supertype defines the argument type
379
+ # as "Period | Timestamp | Timedelta | NaTType"
380
+ def _check_compatible_with(self, other: Period | NaTType | PeriodArray) -> None: # type: ignore[override]
381
+ if other is NaT:
382
+ return
383
+ # error: Item "NaTType" of "Period | NaTType | PeriodArray" has no
384
+ # attribute "freq"
385
+ self._require_matching_freq(other.freq) # type: ignore[union-attr]
386
+
387
+ # --------------------------------------------------------------------
388
+ # Data / Attributes
389
+
390
+ @cache_readonly
391
+ def dtype(self) -> PeriodDtype:
392
+ return self._dtype
393
+
394
+ # error: Cannot override writeable attribute with read-only property
395
+ @property # type: ignore[override]
396
+ def freq(self) -> BaseOffset:
397
+ """
398
+ Return the frequency object for this PeriodArray.
399
+ """
400
+ return self.dtype.freq
401
+
402
+ @property
403
+ def freqstr(self) -> str:
404
+ return freq_to_period_freqstr(self.freq.n, self.freq.name)
405
+
406
+ def __array__(
407
+ self, dtype: NpDtype | None = None, copy: bool | None = None
408
+ ) -> np.ndarray:
409
+ if dtype == "i8":
410
+ # For NumPy 1.x compatibility we cannot use copy=None. And
411
+ # `copy=False` has the meaning of `copy=None` here:
412
+ if not copy:
413
+ return np.asarray(self.asi8, dtype=dtype)
414
+ else:
415
+ return np.array(self.asi8, dtype=dtype)
416
+
417
+ if copy is False:
418
+ warnings.warn(
419
+ "Starting with NumPy 2.0, the behavior of the 'copy' keyword has "
420
+ "changed and passing 'copy=False' raises an error when returning "
421
+ "a zero-copy NumPy array is not possible. pandas will follow "
422
+ "this behavior starting with pandas 3.0.\nThis conversion to "
423
+ "NumPy requires a copy, but 'copy=False' was passed. Consider "
424
+ "using 'np.asarray(..)' instead.",
425
+ FutureWarning,
426
+ stacklevel=find_stack_level(),
427
+ )
428
+
429
+ if dtype == bool:
430
+ return ~self._isnan
431
+
432
+ # This will raise TypeError for non-object dtypes
433
+ return np.array(list(self), dtype=object)
434
+
435
+ def __arrow_array__(self, type=None):
436
+ """
437
+ Convert myself into a pyarrow Array.
438
+ """
439
+ import pyarrow
440
+
441
+ from pandas.core.arrays.arrow.extension_types import ArrowPeriodType
442
+
443
+ if type is not None:
444
+ if pyarrow.types.is_integer(type):
445
+ return pyarrow.array(self._ndarray, mask=self.isna(), type=type)
446
+ elif isinstance(type, ArrowPeriodType):
447
+ # ensure we have the same freq
448
+ if self.freqstr != type.freq:
449
+ raise TypeError(
450
+ "Not supported to convert PeriodArray to array with different "
451
+ f"'freq' ({self.freqstr} vs {type.freq})"
452
+ )
453
+ else:
454
+ raise TypeError(
455
+ f"Not supported to convert PeriodArray to '{type}' type"
456
+ )
457
+
458
+ period_type = ArrowPeriodType(self.freqstr)
459
+ storage_array = pyarrow.array(self._ndarray, mask=self.isna(), type="int64")
460
+ return pyarrow.ExtensionArray.from_storage(period_type, storage_array)
461
+
462
+ # --------------------------------------------------------------------
463
+ # Vectorized analogues of Period properties
464
+
465
+ year = _field_accessor(
466
+ "year",
467
+ """
468
+ The year of the period.
469
+
470
+ Examples
471
+ --------
472
+ >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
473
+ >>> idx.year
474
+ Index([2023, 2024, 2025], dtype='int64')
475
+ """,
476
+ )
477
+ month = _field_accessor(
478
+ "month",
479
+ """
480
+ The month as January=1, December=12.
481
+
482
+ Examples
483
+ --------
484
+ >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
485
+ >>> idx.month
486
+ Index([1, 2, 3], dtype='int64')
487
+ """,
488
+ )
489
+ day = _field_accessor(
490
+ "day",
491
+ """
492
+ The days of the period.
493
+
494
+ Examples
495
+ --------
496
+ >>> idx = pd.PeriodIndex(['2020-01-31', '2020-02-28'], freq='D')
497
+ >>> idx.day
498
+ Index([31, 28], dtype='int64')
499
+ """,
500
+ )
501
+ hour = _field_accessor(
502
+ "hour",
503
+ """
504
+ The hour of the period.
505
+
506
+ Examples
507
+ --------
508
+ >>> idx = pd.PeriodIndex(["2023-01-01 10:00", "2023-01-01 11:00"], freq='h')
509
+ >>> idx.hour
510
+ Index([10, 11], dtype='int64')
511
+ """,
512
+ )
513
+ minute = _field_accessor(
514
+ "minute",
515
+ """
516
+ The minute of the period.
517
+
518
+ Examples
519
+ --------
520
+ >>> idx = pd.PeriodIndex(["2023-01-01 10:30:00",
521
+ ... "2023-01-01 11:50:00"], freq='min')
522
+ >>> idx.minute
523
+ Index([30, 50], dtype='int64')
524
+ """,
525
+ )
526
+ second = _field_accessor(
527
+ "second",
528
+ """
529
+ The second of the period.
530
+
531
+ Examples
532
+ --------
533
+ >>> idx = pd.PeriodIndex(["2023-01-01 10:00:30",
534
+ ... "2023-01-01 10:00:31"], freq='s')
535
+ >>> idx.second
536
+ Index([30, 31], dtype='int64')
537
+ """,
538
+ )
539
+ weekofyear = _field_accessor(
540
+ "week",
541
+ """
542
+ The week ordinal of the year.
543
+
544
+ Examples
545
+ --------
546
+ >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
547
+ >>> idx.week # It can be written `weekofyear`
548
+ Index([5, 9, 13], dtype='int64')
549
+ """,
550
+ )
551
+ week = weekofyear
552
+ day_of_week = _field_accessor(
553
+ "day_of_week",
554
+ """
555
+ The day of the week with Monday=0, Sunday=6.
556
+
557
+ Examples
558
+ --------
559
+ >>> idx = pd.PeriodIndex(["2023-01-01", "2023-01-02", "2023-01-03"], freq="D")
560
+ >>> idx.weekday
561
+ Index([6, 0, 1], dtype='int64')
562
+ """,
563
+ )
564
+ dayofweek = day_of_week
565
+ weekday = dayofweek
566
+ dayofyear = day_of_year = _field_accessor(
567
+ "day_of_year",
568
+ """
569
+ The ordinal day of the year.
570
+
571
+ Examples
572
+ --------
573
+ >>> idx = pd.PeriodIndex(["2023-01-10", "2023-02-01", "2023-03-01"], freq="D")
574
+ >>> idx.dayofyear
575
+ Index([10, 32, 60], dtype='int64')
576
+
577
+ >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
578
+ >>> idx
579
+ PeriodIndex(['2023', '2024', '2025'], dtype='period[Y-DEC]')
580
+ >>> idx.dayofyear
581
+ Index([365, 366, 365], dtype='int64')
582
+ """,
583
+ )
584
+ quarter = _field_accessor(
585
+ "quarter",
586
+ """
587
+ The quarter of the date.
588
+
589
+ Examples
590
+ --------
591
+ >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
592
+ >>> idx.quarter
593
+ Index([1, 1, 1], dtype='int64')
594
+ """,
595
+ )
596
+ qyear = _field_accessor("qyear")
597
+ days_in_month = _field_accessor(
598
+ "days_in_month",
599
+ """
600
+ The number of days in the month.
601
+
602
+ Examples
603
+ --------
604
+ For Series:
605
+
606
+ >>> period = pd.period_range('2020-1-1 00:00', '2020-3-1 00:00', freq='M')
607
+ >>> s = pd.Series(period)
608
+ >>> s
609
+ 0 2020-01
610
+ 1 2020-02
611
+ 2 2020-03
612
+ dtype: period[M]
613
+ >>> s.dt.days_in_month
614
+ 0 31
615
+ 1 29
616
+ 2 31
617
+ dtype: int64
618
+
619
+ For PeriodIndex:
620
+
621
+ >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
622
+ >>> idx.days_in_month # It can be also entered as `daysinmonth`
623
+ Index([31, 28, 31], dtype='int64')
624
+ """,
625
+ )
626
+ daysinmonth = days_in_month
627
+
628
+ @property
629
+ def is_leap_year(self) -> npt.NDArray[np.bool_]:
630
+ """
631
+ Logical indicating if the date belongs to a leap year.
632
+
633
+ Examples
634
+ --------
635
+ >>> idx = pd.PeriodIndex(["2023", "2024", "2025"], freq="Y")
636
+ >>> idx.is_leap_year
637
+ array([False, True, False])
638
+ """
639
+ return isleapyear_arr(np.asarray(self.year))
640
+
641
+ def to_timestamp(self, freq=None, how: str = "start") -> DatetimeArray:
642
+ """
643
+ Cast to DatetimeArray/Index.
644
+
645
+ Parameters
646
+ ----------
647
+ freq : str or DateOffset, optional
648
+ Target frequency. The default is 'D' for week or longer,
649
+ 's' otherwise.
650
+ how : {'s', 'e', 'start', 'end'}
651
+ Whether to use the start or end of the time period being converted.
652
+
653
+ Returns
654
+ -------
655
+ DatetimeArray/Index
656
+
657
+ Examples
658
+ --------
659
+ >>> idx = pd.PeriodIndex(["2023-01", "2023-02", "2023-03"], freq="M")
660
+ >>> idx.to_timestamp()
661
+ DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'],
662
+ dtype='datetime64[ns]', freq='MS')
663
+ """
664
+ from pandas.core.arrays import DatetimeArray
665
+
666
+ how = libperiod.validate_end_alias(how)
667
+
668
+ end = how == "E"
669
+ if end:
670
+ if freq == "B" or self.freq == "B":
671
+ # roll forward to ensure we land on B date
672
+ adjust = Timedelta(1, "D") - Timedelta(1, "ns")
673
+ return self.to_timestamp(how="start") + adjust
674
+ else:
675
+ adjust = Timedelta(1, "ns")
676
+ return (self + self.freq).to_timestamp(how="start") - adjust
677
+
678
+ if freq is None:
679
+ freq_code = self._dtype._get_to_timestamp_base()
680
+ dtype = PeriodDtypeBase(freq_code, 1)
681
+ freq = dtype._freqstr
682
+ base = freq_code
683
+ else:
684
+ freq = Period._maybe_convert_freq(freq)
685
+ base = freq._period_dtype_code
686
+
687
+ new_parr = self.asfreq(freq, how=how)
688
+
689
+ new_data = libperiod.periodarr_to_dt64arr(new_parr.asi8, base)
690
+ dta = DatetimeArray._from_sequence(new_data)
691
+
692
+ if self.freq.name == "B":
693
+ # See if we can retain BDay instead of Day in cases where
694
+ # len(self) is too small for infer_freq to distinguish between them
695
+ diffs = libalgos.unique_deltas(self.asi8)
696
+ if len(diffs) == 1:
697
+ diff = diffs[0]
698
+ if diff == self.dtype._n:
699
+ dta._freq = self.freq
700
+ elif diff == 1:
701
+ dta._freq = self.freq.base
702
+ # TODO: other cases?
703
+ return dta
704
+ else:
705
+ return dta._with_freq("infer")
706
+
707
+ # --------------------------------------------------------------------
708
+
709
+ def _box_func(self, x) -> Period | NaTType:
710
+ return Period._from_ordinal(ordinal=x, freq=self.freq)
711
+
712
+ @doc(**_shared_doc_kwargs, other="PeriodIndex", other_name="PeriodIndex")
713
+ def asfreq(self, freq=None, how: str = "E") -> Self:
714
+ """
715
+ Convert the {klass} to the specified frequency `freq`.
716
+
717
+ Equivalent to applying :meth:`pandas.Period.asfreq` with the given arguments
718
+ to each :class:`~pandas.Period` in this {klass}.
719
+
720
+ Parameters
721
+ ----------
722
+ freq : str
723
+ A frequency.
724
+ how : str {{'E', 'S'}}, default 'E'
725
+ Whether the elements should be aligned to the end
726
+ or start within pa period.
727
+
728
+ * 'E', 'END', or 'FINISH' for end,
729
+ * 'S', 'START', or 'BEGIN' for start.
730
+
731
+ January 31st ('END') vs. January 1st ('START') for example.
732
+
733
+ Returns
734
+ -------
735
+ {klass}
736
+ The transformed {klass} with the new frequency.
737
+
738
+ See Also
739
+ --------
740
+ {other}.asfreq: Convert each Period in a {other_name} to the given frequency.
741
+ Period.asfreq : Convert a :class:`~pandas.Period` object to the given frequency.
742
+
743
+ Examples
744
+ --------
745
+ >>> pidx = pd.period_range('2010-01-01', '2015-01-01', freq='Y')
746
+ >>> pidx
747
+ PeriodIndex(['2010', '2011', '2012', '2013', '2014', '2015'],
748
+ dtype='period[Y-DEC]')
749
+
750
+ >>> pidx.asfreq('M')
751
+ PeriodIndex(['2010-12', '2011-12', '2012-12', '2013-12', '2014-12',
752
+ '2015-12'], dtype='period[M]')
753
+
754
+ >>> pidx.asfreq('M', how='S')
755
+ PeriodIndex(['2010-01', '2011-01', '2012-01', '2013-01', '2014-01',
756
+ '2015-01'], dtype='period[M]')
757
+ """
758
+ how = libperiod.validate_end_alias(how)
759
+ if isinstance(freq, BaseOffset) and hasattr(freq, "_period_dtype_code"):
760
+ freq = PeriodDtype(freq)._freqstr
761
+ freq = Period._maybe_convert_freq(freq)
762
+
763
+ base1 = self._dtype._dtype_code
764
+ base2 = freq._period_dtype_code
765
+
766
+ asi8 = self.asi8
767
+ # self.freq.n can't be negative or 0
768
+ end = how == "E"
769
+ if end:
770
+ ordinal = asi8 + self.dtype._n - 1
771
+ else:
772
+ ordinal = asi8
773
+
774
+ new_data = period_asfreq_arr(ordinal, base1, base2, end)
775
+
776
+ if self._hasna:
777
+ new_data[self._isnan] = iNaT
778
+
779
+ dtype = PeriodDtype(freq)
780
+ return type(self)(new_data, dtype=dtype)
781
+
782
+ # ------------------------------------------------------------------
783
+ # Rendering Methods
784
+
785
+ def _formatter(self, boxed: bool = False):
786
+ if boxed:
787
+ return str
788
+ return "'{}'".format
789
+
790
+ def _format_native_types(
791
+ self, *, na_rep: str | float = "NaT", date_format=None, **kwargs
792
+ ) -> npt.NDArray[np.object_]:
793
+ """
794
+ actually format my specific types
795
+ """
796
+ return libperiod.period_array_strftime(
797
+ self.asi8, self.dtype._dtype_code, na_rep, date_format
798
+ )
799
+
800
+ # ------------------------------------------------------------------
801
+
802
+ def astype(self, dtype, copy: bool = True):
803
+ # We handle Period[T] -> Period[U]
804
+ # Our parent handles everything else.
805
+ dtype = pandas_dtype(dtype)
806
+ if dtype == self._dtype:
807
+ if not copy:
808
+ return self
809
+ else:
810
+ return self.copy()
811
+ if isinstance(dtype, PeriodDtype):
812
+ return self.asfreq(dtype.freq)
813
+
814
+ if lib.is_np_dtype(dtype, "M") or isinstance(dtype, DatetimeTZDtype):
815
+ # GH#45038 match PeriodIndex behavior.
816
+ tz = getattr(dtype, "tz", None)
817
+ unit = dtl.dtype_to_unit(dtype)
818
+ return self.to_timestamp().tz_localize(tz).as_unit(unit)
819
+
820
+ return super().astype(dtype, copy=copy)
821
+
822
+ def searchsorted(
823
+ self,
824
+ value: NumpyValueArrayLike | ExtensionArray,
825
+ side: Literal["left", "right"] = "left",
826
+ sorter: NumpySorter | None = None,
827
+ ) -> npt.NDArray[np.intp] | np.intp:
828
+ npvalue = self._validate_setitem_value(value).view("M8[ns]")
829
+
830
+ # Cast to M8 to get datetime-like NaT placement,
831
+ # similar to dtl._period_dispatch
832
+ m8arr = self._ndarray.view("M8[ns]")
833
+ return m8arr.searchsorted(npvalue, side=side, sorter=sorter)
834
+
835
+ def _pad_or_backfill(
836
+ self,
837
+ *,
838
+ method: FillnaOptions,
839
+ limit: int | None = None,
840
+ limit_area: Literal["inside", "outside"] | None = None,
841
+ copy: bool = True,
842
+ ) -> Self:
843
+ # view as dt64 so we get treated as timelike in core.missing,
844
+ # similar to dtl._period_dispatch
845
+ dta = self.view("M8[ns]")
846
+ result = dta._pad_or_backfill(
847
+ method=method, limit=limit, limit_area=limit_area, copy=copy
848
+ )
849
+ if copy:
850
+ return cast("Self", result.view(self.dtype))
851
+ else:
852
+ return self
853
+
854
+ def fillna(
855
+ self, value=None, method=None, limit: int | None = None, copy: bool = True
856
+ ) -> Self:
857
+ if method is not None:
858
+ # view as dt64 so we get treated as timelike in core.missing,
859
+ # similar to dtl._period_dispatch
860
+ dta = self.view("M8[ns]")
861
+ result = dta.fillna(value=value, method=method, limit=limit, copy=copy)
862
+ # error: Incompatible return value type (got "Union[ExtensionArray,
863
+ # ndarray[Any, Any]]", expected "PeriodArray")
864
+ return result.view(self.dtype) # type: ignore[return-value]
865
+ return super().fillna(value=value, method=method, limit=limit, copy=copy)
866
+
867
+ # ------------------------------------------------------------------
868
+ # Arithmetic Methods
869
+
870
+ def _addsub_int_array_or_scalar(
871
+ self, other: np.ndarray | int, op: Callable[[Any, Any], Any]
872
+ ) -> Self:
873
+ """
874
+ Add or subtract array of integers.
875
+
876
+ Parameters
877
+ ----------
878
+ other : np.ndarray[int64] or int
879
+ op : {operator.add, operator.sub}
880
+
881
+ Returns
882
+ -------
883
+ result : PeriodArray
884
+ """
885
+ assert op in [operator.add, operator.sub]
886
+ if op is operator.sub:
887
+ other = -other
888
+ res_values = add_overflowsafe(self.asi8, np.asarray(other, dtype="i8"))
889
+ return type(self)(res_values, dtype=self.dtype)
890
+
891
+ def _add_offset(self, other: BaseOffset):
892
+ assert not isinstance(other, Tick)
893
+
894
+ self._require_matching_freq(other, base=True)
895
+ return self._addsub_int_array_or_scalar(other.n, operator.add)
896
+
897
+ # TODO: can we de-duplicate with Period._add_timedeltalike_scalar?
898
+ def _add_timedeltalike_scalar(self, other):
899
+ """
900
+ Parameters
901
+ ----------
902
+ other : timedelta, Tick, np.timedelta64
903
+
904
+ Returns
905
+ -------
906
+ PeriodArray
907
+ """
908
+ if not isinstance(self.freq, Tick):
909
+ # We cannot add timedelta-like to non-tick PeriodArray
910
+ raise raise_on_incompatible(self, other)
911
+
912
+ if isna(other):
913
+ # i.e. np.timedelta64("NaT")
914
+ return super()._add_timedeltalike_scalar(other)
915
+
916
+ td = np.asarray(Timedelta(other).asm8)
917
+ return self._add_timedelta_arraylike(td)
918
+
919
+ def _add_timedelta_arraylike(
920
+ self, other: TimedeltaArray | npt.NDArray[np.timedelta64]
921
+ ) -> Self:
922
+ """
923
+ Parameters
924
+ ----------
925
+ other : TimedeltaArray or ndarray[timedelta64]
926
+
927
+ Returns
928
+ -------
929
+ PeriodArray
930
+ """
931
+ if not self.dtype._is_tick_like():
932
+ # We cannot add timedelta-like to non-tick PeriodArray
933
+ raise TypeError(
934
+ f"Cannot add or subtract timedelta64[ns] dtype from {self.dtype}"
935
+ )
936
+
937
+ dtype = np.dtype(f"m8[{self.dtype._td64_unit}]")
938
+
939
+ # Similar to _check_timedeltalike_freq_compat, but we raise with a
940
+ # more specific exception message if necessary.
941
+ try:
942
+ delta = astype_overflowsafe(
943
+ np.asarray(other), dtype=dtype, copy=False, round_ok=False
944
+ )
945
+ except ValueError as err:
946
+ # e.g. if we have minutes freq and try to add 30s
947
+ # "Cannot losslessly convert units"
948
+ raise IncompatibleFrequency(
949
+ "Cannot add/subtract timedelta-like from PeriodArray that is "
950
+ "not an integer multiple of the PeriodArray's freq."
951
+ ) from err
952
+
953
+ res_values = add_overflowsafe(self.asi8, np.asarray(delta.view("i8")))
954
+ return type(self)(res_values, dtype=self.dtype)
955
+
956
+ def _check_timedeltalike_freq_compat(self, other):
957
+ """
958
+ Arithmetic operations with timedelta-like scalars or array `other`
959
+ are only valid if `other` is an integer multiple of `self.freq`.
960
+ If the operation is valid, find that integer multiple. Otherwise,
961
+ raise because the operation is invalid.
962
+
963
+ Parameters
964
+ ----------
965
+ other : timedelta, np.timedelta64, Tick,
966
+ ndarray[timedelta64], TimedeltaArray, TimedeltaIndex
967
+
968
+ Returns
969
+ -------
970
+ multiple : int or ndarray[int64]
971
+
972
+ Raises
973
+ ------
974
+ IncompatibleFrequency
975
+ """
976
+ assert self.dtype._is_tick_like() # checked by calling function
977
+
978
+ dtype = np.dtype(f"m8[{self.dtype._td64_unit}]")
979
+
980
+ if isinstance(other, (timedelta, np.timedelta64, Tick)):
981
+ td = np.asarray(Timedelta(other).asm8)
982
+ else:
983
+ td = np.asarray(other)
984
+
985
+ try:
986
+ delta = astype_overflowsafe(td, dtype=dtype, copy=False, round_ok=False)
987
+ except ValueError as err:
988
+ raise raise_on_incompatible(self, other) from err
989
+
990
+ delta = delta.view("i8")
991
+ return lib.item_from_zerodim(delta)
992
+
993
+
994
+ def raise_on_incompatible(left, right) -> IncompatibleFrequency:
995
+ """
996
+ Helper function to render a consistent error message when raising
997
+ IncompatibleFrequency.
998
+
999
+ Parameters
1000
+ ----------
1001
+ left : PeriodArray
1002
+ right : None, DateOffset, Period, ndarray, or timedelta-like
1003
+
1004
+ Returns
1005
+ -------
1006
+ IncompatibleFrequency
1007
+ Exception to be raised by the caller.
1008
+ """
1009
+ # GH#24283 error message format depends on whether right is scalar
1010
+ if isinstance(right, (np.ndarray, ABCTimedeltaArray)) or right is None:
1011
+ other_freq = None
1012
+ elif isinstance(right, BaseOffset):
1013
+ other_freq = freq_to_period_freqstr(right.n, right.name)
1014
+ elif isinstance(right, (ABCPeriodIndex, PeriodArray, Period)):
1015
+ other_freq = right.freqstr
1016
+ else:
1017
+ other_freq = delta_to_tick(Timedelta(right)).freqstr
1018
+
1019
+ own_freq = freq_to_period_freqstr(left.freq.n, left.freq.name)
1020
+ msg = DIFFERENT_FREQ.format(
1021
+ cls=type(left).__name__, own_freq=own_freq, other_freq=other_freq
1022
+ )
1023
+ return IncompatibleFrequency(msg)
1024
+
1025
+
1026
+ # -------------------------------------------------------------------
1027
+ # Constructor Helpers
1028
+
1029
+
1030
+ def period_array(
1031
+ data: Sequence[Period | str | None] | AnyArrayLike,
1032
+ freq: str | Tick | BaseOffset | None = None,
1033
+ copy: bool = False,
1034
+ ) -> PeriodArray:
1035
+ """
1036
+ Construct a new PeriodArray from a sequence of Period scalars.
1037
+
1038
+ Parameters
1039
+ ----------
1040
+ data : Sequence of Period objects
1041
+ A sequence of Period objects. These are required to all have
1042
+ the same ``freq.`` Missing values can be indicated by ``None``
1043
+ or ``pandas.NaT``.
1044
+ freq : str, Tick, or Offset
1045
+ The frequency of every element of the array. This can be specified
1046
+ to avoid inferring the `freq` from `data`.
1047
+ copy : bool, default False
1048
+ Whether to ensure a copy of the data is made.
1049
+
1050
+ Returns
1051
+ -------
1052
+ PeriodArray
1053
+
1054
+ See Also
1055
+ --------
1056
+ PeriodArray
1057
+ pandas.PeriodIndex
1058
+
1059
+ Examples
1060
+ --------
1061
+ >>> period_array([pd.Period('2017', freq='Y'),
1062
+ ... pd.Period('2018', freq='Y')])
1063
+ <PeriodArray>
1064
+ ['2017', '2018']
1065
+ Length: 2, dtype: period[Y-DEC]
1066
+
1067
+ >>> period_array([pd.Period('2017', freq='Y'),
1068
+ ... pd.Period('2018', freq='Y'),
1069
+ ... pd.NaT])
1070
+ <PeriodArray>
1071
+ ['2017', '2018', 'NaT']
1072
+ Length: 3, dtype: period[Y-DEC]
1073
+
1074
+ Integers that look like years are handled
1075
+
1076
+ >>> period_array([2000, 2001, 2002], freq='D')
1077
+ <PeriodArray>
1078
+ ['2000-01-01', '2001-01-01', '2002-01-01']
1079
+ Length: 3, dtype: period[D]
1080
+
1081
+ Datetime-like strings may also be passed
1082
+
1083
+ >>> period_array(['2000-Q1', '2000-Q2', '2000-Q3', '2000-Q4'], freq='Q')
1084
+ <PeriodArray>
1085
+ ['2000Q1', '2000Q2', '2000Q3', '2000Q4']
1086
+ Length: 4, dtype: period[Q-DEC]
1087
+ """
1088
+ data_dtype = getattr(data, "dtype", None)
1089
+
1090
+ if lib.is_np_dtype(data_dtype, "M"):
1091
+ return PeriodArray._from_datetime64(data, freq)
1092
+ if isinstance(data_dtype, PeriodDtype):
1093
+ out = PeriodArray(data)
1094
+ if freq is not None:
1095
+ if freq == data_dtype.freq:
1096
+ return out
1097
+ return out.asfreq(freq)
1098
+ return out
1099
+
1100
+ # other iterable of some kind
1101
+ if not isinstance(data, (np.ndarray, list, tuple, ABCSeries)):
1102
+ data = list(data)
1103
+
1104
+ arrdata = np.asarray(data)
1105
+
1106
+ dtype: PeriodDtype | None
1107
+ if freq:
1108
+ dtype = PeriodDtype(freq)
1109
+ else:
1110
+ dtype = None
1111
+
1112
+ if arrdata.dtype.kind == "f" and len(arrdata) > 0:
1113
+ raise TypeError("PeriodIndex does not allow floating point in construction")
1114
+
1115
+ if arrdata.dtype.kind in "iu":
1116
+ arr = arrdata.astype(np.int64, copy=False)
1117
+ # error: Argument 2 to "from_ordinals" has incompatible type "Union[str,
1118
+ # Tick, None]"; expected "Union[timedelta, BaseOffset, str]"
1119
+ ordinals = libperiod.from_ordinals(arr, freq) # type: ignore[arg-type]
1120
+ return PeriodArray(ordinals, dtype=dtype)
1121
+
1122
+ data = ensure_object(arrdata)
1123
+ if freq is None:
1124
+ freq = libperiod.extract_freq(data)
1125
+ dtype = PeriodDtype(freq)
1126
+ return PeriodArray._from_sequence(data, dtype=dtype)
1127
+
1128
+
1129
+ @overload
1130
+ def validate_dtype_freq(dtype, freq: BaseOffsetT) -> BaseOffsetT:
1131
+ ...
1132
+
1133
+
1134
+ @overload
1135
+ def validate_dtype_freq(dtype, freq: timedelta | str | None) -> BaseOffset:
1136
+ ...
1137
+
1138
+
1139
+ def validate_dtype_freq(
1140
+ dtype, freq: BaseOffsetT | BaseOffset | timedelta | str | None
1141
+ ) -> BaseOffsetT:
1142
+ """
1143
+ If both a dtype and a freq are available, ensure they match. If only
1144
+ dtype is available, extract the implied freq.
1145
+
1146
+ Parameters
1147
+ ----------
1148
+ dtype : dtype
1149
+ freq : DateOffset or None
1150
+
1151
+ Returns
1152
+ -------
1153
+ freq : DateOffset
1154
+
1155
+ Raises
1156
+ ------
1157
+ ValueError : non-period dtype
1158
+ IncompatibleFrequency : mismatch between dtype and freq
1159
+ """
1160
+ if freq is not None:
1161
+ freq = to_offset(freq, is_period=True)
1162
+
1163
+ if dtype is not None:
1164
+ dtype = pandas_dtype(dtype)
1165
+ if not isinstance(dtype, PeriodDtype):
1166
+ raise ValueError("dtype must be PeriodDtype")
1167
+ if freq is None:
1168
+ freq = dtype.freq
1169
+ elif freq != dtype.freq:
1170
+ raise IncompatibleFrequency("specified freq and dtype are different")
1171
+ # error: Incompatible return value type (got "Union[BaseOffset, Any, None]",
1172
+ # expected "BaseOffset")
1173
+ return freq # type: ignore[return-value]
1174
+
1175
+
1176
+ def dt64arr_to_periodarr(
1177
+ data, freq, tz=None
1178
+ ) -> tuple[npt.NDArray[np.int64], BaseOffset]:
1179
+ """
1180
+ Convert an datetime-like array to values Period ordinals.
1181
+
1182
+ Parameters
1183
+ ----------
1184
+ data : Union[Series[datetime64[ns]], DatetimeIndex, ndarray[datetime64ns]]
1185
+ freq : Optional[Union[str, Tick]]
1186
+ Must match the `freq` on the `data` if `data` is a DatetimeIndex
1187
+ or Series.
1188
+ tz : Optional[tzinfo]
1189
+
1190
+ Returns
1191
+ -------
1192
+ ordinals : ndarray[int64]
1193
+ freq : Tick
1194
+ The frequency extracted from the Series or DatetimeIndex if that's
1195
+ used.
1196
+
1197
+ """
1198
+ if not isinstance(data.dtype, np.dtype) or data.dtype.kind != "M":
1199
+ raise ValueError(f"Wrong dtype: {data.dtype}")
1200
+
1201
+ if freq is None:
1202
+ if isinstance(data, ABCIndex):
1203
+ data, freq = data._values, data.freq
1204
+ elif isinstance(data, ABCSeries):
1205
+ data, freq = data._values, data.dt.freq
1206
+
1207
+ elif isinstance(data, (ABCIndex, ABCSeries)):
1208
+ data = data._values
1209
+
1210
+ reso = get_unit_from_dtype(data.dtype)
1211
+ freq = Period._maybe_convert_freq(freq)
1212
+ base = freq._period_dtype_code
1213
+ return c_dt64arr_to_periodarr(data.view("i8"), base, tz, reso=reso), freq
1214
+
1215
+
1216
+ def _get_ordinal_range(start, end, periods, freq, mult: int = 1):
1217
+ if com.count_not_none(start, end, periods) != 2:
1218
+ raise ValueError(
1219
+ "Of the three parameters: start, end, and periods, "
1220
+ "exactly two must be specified"
1221
+ )
1222
+
1223
+ if freq is not None:
1224
+ freq = to_offset(freq, is_period=True)
1225
+ mult = freq.n
1226
+
1227
+ if start is not None:
1228
+ start = Period(start, freq)
1229
+ if end is not None:
1230
+ end = Period(end, freq)
1231
+
1232
+ is_start_per = isinstance(start, Period)
1233
+ is_end_per = isinstance(end, Period)
1234
+
1235
+ if is_start_per and is_end_per and start.freq != end.freq:
1236
+ raise ValueError("start and end must have same freq")
1237
+ if start is NaT or end is NaT:
1238
+ raise ValueError("start and end must not be NaT")
1239
+
1240
+ if freq is None:
1241
+ if is_start_per:
1242
+ freq = start.freq
1243
+ elif is_end_per:
1244
+ freq = end.freq
1245
+ else: # pragma: no cover
1246
+ raise ValueError("Could not infer freq from start/end")
1247
+ mult = freq.n
1248
+
1249
+ if periods is not None:
1250
+ periods = periods * mult
1251
+ if start is None:
1252
+ data = np.arange(
1253
+ end.ordinal - periods + mult, end.ordinal + 1, mult, dtype=np.int64
1254
+ )
1255
+ else:
1256
+ data = np.arange(
1257
+ start.ordinal, start.ordinal + periods, mult, dtype=np.int64
1258
+ )
1259
+ else:
1260
+ data = np.arange(start.ordinal, end.ordinal + 1, mult, dtype=np.int64)
1261
+
1262
+ return data, freq
1263
+
1264
+
1265
+ def _range_from_fields(
1266
+ year=None,
1267
+ month=None,
1268
+ quarter=None,
1269
+ day=None,
1270
+ hour=None,
1271
+ minute=None,
1272
+ second=None,
1273
+ freq=None,
1274
+ ) -> tuple[np.ndarray, BaseOffset]:
1275
+ if hour is None:
1276
+ hour = 0
1277
+ if minute is None:
1278
+ minute = 0
1279
+ if second is None:
1280
+ second = 0
1281
+ if day is None:
1282
+ day = 1
1283
+
1284
+ ordinals = []
1285
+
1286
+ if quarter is not None:
1287
+ if freq is None:
1288
+ freq = to_offset("Q", is_period=True)
1289
+ base = FreqGroup.FR_QTR.value
1290
+ else:
1291
+ freq = to_offset(freq, is_period=True)
1292
+ base = libperiod.freq_to_dtype_code(freq)
1293
+ if base != FreqGroup.FR_QTR.value:
1294
+ raise AssertionError("base must equal FR_QTR")
1295
+
1296
+ freqstr = freq.freqstr
1297
+ year, quarter = _make_field_arrays(year, quarter)
1298
+ for y, q in zip(year, quarter):
1299
+ calendar_year, calendar_month = parsing.quarter_to_myear(y, q, freqstr)
1300
+ val = libperiod.period_ordinal(
1301
+ calendar_year, calendar_month, 1, 1, 1, 1, 0, 0, base
1302
+ )
1303
+ ordinals.append(val)
1304
+ else:
1305
+ freq = to_offset(freq, is_period=True)
1306
+ base = libperiod.freq_to_dtype_code(freq)
1307
+ arrays = _make_field_arrays(year, month, day, hour, minute, second)
1308
+ for y, mth, d, h, mn, s in zip(*arrays):
1309
+ ordinals.append(libperiod.period_ordinal(y, mth, d, h, mn, s, 0, 0, base))
1310
+
1311
+ return np.array(ordinals, dtype=np.int64), freq
1312
+
1313
+
1314
+ def _make_field_arrays(*fields) -> list[np.ndarray]:
1315
+ length = None
1316
+ for x in fields:
1317
+ if isinstance(x, (list, np.ndarray, ABCSeries)):
1318
+ if length is not None and len(x) != length:
1319
+ raise ValueError("Mismatched Period array lengths")
1320
+ if length is None:
1321
+ length = len(x)
1322
+
1323
+ # error: Argument 2 to "repeat" has incompatible type "Optional[int]"; expected
1324
+ # "Union[Union[int, integer[Any]], Union[bool, bool_], ndarray, Sequence[Union[int,
1325
+ # integer[Any]]], Sequence[Union[bool, bool_]], Sequence[Sequence[Any]]]"
1326
+ return [
1327
+ np.asarray(x)
1328
+ if isinstance(x, (np.ndarray, list, ABCSeries))
1329
+ else np.repeat(x, length) # type: ignore[arg-type]
1330
+ for x in fields
1331
+ ]