s42chen commited on
Commit
42e4d79
·
verified ·
1 Parent(s): f914454

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

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 +34 -0
  2. shared/package-files/e8/e8059553d1bb6d12e9ded94e62ae652b9157bac6bd4de19456222bcb1ce8b07c/blob +0 -0
  3. shared/package-files/e8/e8085bc4b1d0c1d161f296e06d9c2772c7940123edf9281af20776c432fe3e1c/blob +27 -0
  4. shared/package-files/e8/e80aa7dba68a509a7be6e9c5a820337ac2eafed58fb10a69dab09fb5ab92392f/blob +122 -0
  5. shared/package-files/e8/e80acaf24b2c84b6050ce0e8f7543be7f72acc58e7d26373437f9375e7eee32e/blob +4 -0
  6. shared/package-files/e8/e80b8396342dbdff3d0d3354c9633b937a1494ffe5abbd0d53e20d28ab5e3816/blob +82 -0
  7. shared/package-files/e8/e80c37ff6bdd6e1e2eac4450e8d68f85ff5afd3d68d68e9c8e6ddf6f9677fd81/blob +1453 -0
  8. shared/package-files/e8/e80c8e10b956fe80ee78ff62f32be2ae1b7405d24ed22b4dc7df9d7ae31809e0/blob +23 -0
  9. shared/package-files/e8/e80e52ad42441141f16c6b5bb1cc14d8da42cb3fb7ced883946587a51461b09f/blob +96 -0
  10. shared/package-files/e8/e8113bf187bc526547cadf16bf09028cff2d70ccdabf8838fbece436baf51d47/blob +124 -0
  11. shared/package-files/e8/e81297c5189fb59005aca7a41b4186c5822f9a59a38d0527dfc3304846aba8cc/blob +39 -0
  12. shared/package-files/e8/e814839fc75010db274ae034f45b0fff7e529ccb702319048545fef84c2045b7/blob +182 -0
  13. shared/package-files/e8/e815d8c21cd4c9b61586d522884109fdeea0440f80bd51e61a450f5856586ad2/blob +39 -0
  14. shared/package-files/e8/e8162b49bbcd0e4acaf9156c6f5e9180b76819b6c47df6d577843d171ec30eea/blob +15 -0
  15. shared/package-files/e8/e8164a62a51e74047e8de1dc220b097a5247156ba8ba09a5d9cd4d3629711998/blob +28 -0
  16. shared/package-files/e8/e818372669488c876e21f6867cd55cc0d7d2ae01222ceb3370df163f3b1736a1/blob +617 -0
  17. shared/package-files/e8/e81e7bc654e45d69f9297f6e309cc3a54eb0d75395c8b36cb9fc23d697110e5e/blob +37 -0
  18. shared/package-files/e8/e81edfb3d9e2b8dd90632c6354d5f7dd62c126f1764896510a7e922274c8cf48/blob +24 -0
  19. shared/package-files/e8/e820f64f81dea6f4b2c3f19132b088ef33c6455101680b3667eef47d4e42d549/blob +81 -0
  20. shared/package-files/e8/e821fbd5ae150dc9fdb616ae5a213504904e5416febcde421739f3fe52769c0c/blob +1965 -0
  21. shared/package-files/e8/e824710623cecb1ffe9dde0ebba059cb75caaad8a04ea01bf7205804e4f383a9/blob +28 -0
  22. shared/package-files/e8/e82e72e88701c0d0b06cca36c8a4063b351e9f685d9a218ee582c29bf939817c/blob +206 -0
  23. shared/package-files/e8/e8326dc8c0e6c22fe084eac3babc956a465013116af8c20a8ae262fc2afb91d3/blob +128 -0
  24. shared/package-files/e8/e8341442a21a6f654cbf9ae45d1c1586b63fec776b1f094fc6dc3828f96fa3a4/blob +21 -0
  25. shared/package-files/e8/e8355db5428feebe72dd569f397e5295a4e29adc6e4fe3a540a6112c10fe1e71/blob +337 -0
  26. shared/package-files/e8/e839c74603a302a4c72f60d7d9b1880e797b388481b35d2593416b425a99c186/blob +425 -0
  27. shared/package-files/e8/e83b45c9e4464254e67478ace520de72b9d9c80b283f248319b9325a2b3673ce/blob +25 -0
  28. shared/package-files/e8/e83d8bdd6c985e1b92a38cc20f6c8863a72bc450b79dbef56b340266d8358ca4/blob +28 -0
  29. shared/package-files/e8/e83dda6442dc809ae9dd07ff1e2b00228c1cc319c2cc08827d37fbed836c6eb8/blob +185 -0
  30. shared/package-files/e8/e8411cdce118a7e22e4a889d2fa9f0a5a1e0fbe1b19f36c02539858b3efb08d1/blob +111 -0
  31. shared/package-files/e8/e841ab4e3a557ebad1498959185cf6052184aa9cb2ca8714a665d87513942a30/blob +206 -0
  32. shared/package-files/e8/e843f6435ade7369dc3ebd9ff4a9e271223af1a0b955cbdbc704a533c582f958/blob +25 -0
  33. shared/package-files/e8/e84514c2e33210c163840c4be67168ec7f9c87e78de243bdc7a2c04055b32033/blob +3 -0
  34. shared/package-files/e8/e84663e68207f710f8f49d970931685a13ac008694ec96b9ff430017fa46999a/blob +0 -0
  35. shared/package-files/e8/e848f3c9d665ba02337e210d2ad0b8c9c67635c92df19420e6fe83ead5f54a25/blob +1887 -0
  36. shared/package-files/e8/e84a407dd098ad1fb759018e47c8be69ce14518cc9a5276fbe6a2da4c8a45c79/blob +0 -0
  37. shared/package-files/e8/e84c42c1830fa80754bc231d74f16e3a9d6b6d5683eb3d8fdc693564502d63a6/blob +955 -0
  38. shared/package-files/e8/e84dba71cf3bdaf0ed4825f40755d01801d45bf6a3c18702b4a2a0fa3ade8c98/blob +50 -0
  39. shared/package-files/e8/e8522f362e3c0c4324f7cce8594cae103c699aae567b80c05f808641f333d7bc/blob +28 -0
  40. shared/package-files/e8/e8533dc7083fa346bda1933d60ea4a83b67d0945bceaf1b3541f82b4a0e2c6a0/blob +3 -0
  41. shared/package-files/e8/e8555eeb8cf86bd7896b8293255c208a27f8fed90bd755f9fedd70a716c4e59d/blob +50 -0
  42. shared/package-files/e8/e855b49714731f353906c33bb6ebcbac7ddfac7977d8ef8afb026c296de64333/blob +295 -0
  43. shared/package-files/e8/e8574af88880b26b2c210e989092cc9a2317f992ba12bf44483b9c53408ee790/blob +3 -0
  44. shared/package-files/e8/e857e89d3355ec8a63035d771855b5646877df9f5d9d6282861b904821e23a8d/blob +23 -0
  45. shared/package-files/e8/e8587dc55feecf64d65e94d59eeec4496cb17d75e323a724026c2302ca692cb4/blob +886 -0
  46. shared/package-files/e8/e85cf30a42362172d12af10796925627a8e253724d750d64c379f066e67248bf/blob +28 -0
  47. shared/package-files/e8/e85d6d736adc29a0999a07d5c2c13a39b21efcfbb1db799455803ed83f700857/blob +87 -0
  48. shared/package-files/e8/e85f3d181896a0de17274e65d0f770e8b8c0b029a6abc2bb933d59bb76b6be87/blob +0 -0
  49. shared/package-files/e8/e8610e5f6cb42b523373df00a23b7ca425d2db551caeee84f93ff7de5454f76b/blob +936 -0
  50. shared/package-files/e8/e86148ee87aff5c65ac861d2989bbc72a23acbddd311af6003b16f5f490ee6b6/blob +42 -0
.gitattributes CHANGED
@@ -1043,3 +1043,37 @@ shared/package-files/e7/e78a192f91686d6b9ab849a678653b708e41a07cfe9892881a44048b
1043
  shared/package-files/e7/e78f082d2597c696138ed32ea948a027a01907ae1acb89fc4ace711662c35384/blob filter=lfs diff=lfs merge=lfs -text
1044
  shared/package-files/e7/e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779/blob filter=lfs diff=lfs merge=lfs -text
1045
  shared/package-files/e8/e8031c410a8fd049afb011a6e84abea5ad85f0da99de201543eed1fcd5a51471/blob filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1043
  shared/package-files/e7/e78f082d2597c696138ed32ea948a027a01907ae1acb89fc4ace711662c35384/blob filter=lfs diff=lfs merge=lfs -text
1044
  shared/package-files/e7/e79f4ba38486541ccd3e0129f65c0579475319567a5d01e2a92d62ec6027c779/blob filter=lfs diff=lfs merge=lfs -text
1045
  shared/package-files/e8/e8031c410a8fd049afb011a6e84abea5ad85f0da99de201543eed1fcd5a51471/blob filter=lfs diff=lfs merge=lfs -text
1046
+ shared/package-files/e8/e84514c2e33210c163840c4be67168ec7f9c87e78de243bdc7a2c04055b32033/blob filter=lfs diff=lfs merge=lfs -text
1047
+ shared/package-files/e8/e8533dc7083fa346bda1933d60ea4a83b67d0945bceaf1b3541f82b4a0e2c6a0/blob filter=lfs diff=lfs merge=lfs -text
1048
+ shared/package-files/e8/e8574af88880b26b2c210e989092cc9a2317f992ba12bf44483b9c53408ee790/blob filter=lfs diff=lfs merge=lfs -text
1049
+ shared/package-files/e8/e89ff784ad3eb82a53de3d68f26b838eea10a32b636c0fc96ef5fa4d191f71bc/blob filter=lfs diff=lfs merge=lfs -text
1050
+ shared/package-files/e8/e8a4dc6be1c8f72b7214e5b89ef8269cef872cf5bd1179e82df1e8217497ddcf/blob filter=lfs diff=lfs merge=lfs -text
1051
+ shared/package-files/e8/e8b78ca5a8f791b359c94275a103e216d4d4e83082c9f32fd9d9bb85830a73a3/blob filter=lfs diff=lfs merge=lfs -text
1052
+ shared/package-files/e8/e8fbfcff2d9810aecb2d94e8e1f25fd68a6165da45de8f463ad225fbff1aa10e/blob filter=lfs diff=lfs merge=lfs -text
1053
+ shared/package-files/e9/e9114f3f1647fc56a61162ce30b78ce12d0657143166dc1d51dc8213a3400cec/blob filter=lfs diff=lfs merge=lfs -text
1054
+ shared/package-files/e9/e9a9b9d25e5df38e032cf23ee012de98ef50c3ca5411f4480a9f09427ae90152/blob filter=lfs diff=lfs merge=lfs -text
1055
+ shared/package-files/e9/e9b0cccf1dceb3bf4ef0f0c346352913ccab0f89f1e6bb9bf7fde46ff9b3bfb0/blob filter=lfs diff=lfs merge=lfs -text
1056
+ shared/package-files/e9/e9cf97f0c3d27ce570880ce13f6e3a3a175fcfe4fac5c47ca1c972a61a6716e3/blob filter=lfs diff=lfs merge=lfs -text
1057
+ shared/package-files/ea/ea079a6864ca10a6f8ea7d2d312c71121f5c966dc8e334f713a3bc8eb242ee49/blob filter=lfs diff=lfs merge=lfs -text
1058
+ shared/package-files/ea/ea139c1ea37d1fa8ad61b38c8f755849c6a9976d6248aa7321aa43bc65a95d3f/blob filter=lfs diff=lfs merge=lfs -text
1059
+ shared/package-files/ea/ea1d34cf994ec0590d810cbe37fa509bc88febd96bd3ba9117b6d6e6e28ab23b/blob filter=lfs diff=lfs merge=lfs -text
1060
+ shared/package-files/ea/ea3bb28deaae8b95f10e8fcfe83ae5f1884eac7c3ecfece4ba5669a31d3e304f/blob filter=lfs diff=lfs merge=lfs -text
1061
+ shared/package-files/ea/ea4ec3637cf0b2016e1a43fdc2026563586650c9282c777d80f21728cd9c3378/blob filter=lfs diff=lfs merge=lfs -text
1062
+ shared/package-files/ea/eaf0e2c2edf67ac17b6d6f5e0186cc988b430bf2c335d8a03d73232f51fd65e1/blob filter=lfs diff=lfs merge=lfs -text
1063
+ shared/package-files/eb/eb36df12a66137362404095eef74be201c69f6852b15f0229f19f447cacb2e22/blob filter=lfs diff=lfs merge=lfs -text
1064
+ shared/package-files/eb/eb9182c7f7185adbd8d6e2c8cba225265c39841c51f5ce748dcf6caaa6b4fda9/blob filter=lfs diff=lfs merge=lfs -text
1065
+ shared/package-files/eb/ebaee9a3763507c9f06122eaa6d4c90b03ffb9afb3d15a6f277b6aa815e4e899/blob filter=lfs diff=lfs merge=lfs -text
1066
+ shared/package-files/eb/ebc69697b8aa392cb96a655b300cbeddf0605492638fa0c1e5ba915134d8d5bd/blob filter=lfs diff=lfs merge=lfs -text
1067
+ shared/package-files/ec/ec502b49f1c3b5704b2aea54d6e8368ca03240562b0af0b8fd97a27c8ba3721e/blob filter=lfs diff=lfs merge=lfs -text
1068
+ shared/package-files/ec/ec5b97356da1464691a722b09972010f3253a8b6fad83cd6b98ef0b054c17481/blob filter=lfs diff=lfs merge=lfs -text
1069
+ shared/package-files/ec/ec621acd762f264d0e8c01646cc031113a5f447e829396f6098d0c6add8593da/blob filter=lfs diff=lfs merge=lfs -text
1070
+ shared/package-files/ec/ec694d81202442f37649baadd3b3b49da34483cf9c4d3e980df869cf08821444/blob filter=lfs diff=lfs merge=lfs -text
1071
+ shared/package-files/ec/ecb064469fde8686bd0d222fba57a7184fd84efe4874fe39e7b6553f30944ae3/blob filter=lfs diff=lfs merge=lfs -text
1072
+ shared/package-files/ed/ed0504703697cfe5b6d9c1d82bb0ca131838929f3f9b12644506a9daba165a94/blob filter=lfs diff=lfs merge=lfs -text
1073
+ shared/package-files/ee/ee10d4ebc850f1faff94c7643e224b2d4dd0562bd23ac8b012cc9391bf48e0f7/blob filter=lfs diff=lfs merge=lfs -text
1074
+ shared/package-files/ee/ee3416b1de7a7648cf446fbd40a58e54726547f7b4bef71970e53ffbfa3b4a9d/blob filter=lfs diff=lfs merge=lfs -text
1075
+ shared/package-files/ee/ee93fd001b43c74b28fbc834dc6cdab1723000e00ebf2b627711c491bce7a0d6/blob filter=lfs diff=lfs merge=lfs -text
1076
+ shared/package-files/ee/eec82f88b87b28ceb9241d062d6db9188a878c5255658e9ba0979be282ce2d6d/blob filter=lfs diff=lfs merge=lfs -text
1077
+ shared/package-files/ee/eef91a5645a47c386298404e350696bc23d3f8675df730e71549b0856a5fe8a9/blob filter=lfs diff=lfs merge=lfs -text
1078
+ shared/package-files/ef/ef3f0747d01e4106a23d7b9422f19aedc157936ee326a2d16386ce8e4a601f59/blob filter=lfs diff=lfs merge=lfs -text
1079
+ shared/package-files/ef/ef9f1cefedccbb04d7349c039d79185ddcc3f4ef70d5f6f1f7b3cab71376f168/blob filter=lfs diff=lfs merge=lfs -text
shared/package-files/e8/e8059553d1bb6d12e9ded94e62ae652b9157bac6bd4de19456222bcb1ce8b07c/blob ADDED
Binary file (25.8 kB). View file
 
shared/package-files/e8/e8085bc4b1d0c1d161f296e06d9c2772c7940123edf9281af20776c432fe3e1c/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_silu_backward : public TensorIteratorBase {
21
+
22
+
23
+ void meta(const at::Tensor & grad_output, const at::Tensor & self);
24
+ };
25
+
26
+ } // namespace native
27
+ } // namespace at
shared/package-files/e8/e80aa7dba68a509a7be6e9c5a820337ac2eafed58fb10a69dab09fb5ab92392f/blob ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.optimize import _lbfgsb, minimize
3
+
4
+
5
+ def objfun(x):
6
+ """simplified objective func to test lbfgsb bound violation"""
7
+ x0 = [0.8750000000000278,
8
+ 0.7500000000000153,
9
+ 0.9499999999999722,
10
+ 0.8214285714285992,
11
+ 0.6363636363636085]
12
+ x1 = [1.0, 0.0, 1.0, 0.0, 0.0]
13
+ x2 = [1.0,
14
+ 0.0,
15
+ 0.9889733043149325,
16
+ 0.0,
17
+ 0.026353554421041155]
18
+ x3 = [1.0,
19
+ 0.0,
20
+ 0.9889917442915558,
21
+ 0.0,
22
+ 0.020341986743231205]
23
+
24
+ f0 = 5163.647901211178
25
+ f1 = 5149.8181642072905
26
+ f2 = 5149.379332309634
27
+ f3 = 5149.374490771297
28
+
29
+ g0 = np.array([-0.5934820547965749,
30
+ 1.6251549718258351,
31
+ -71.99168459202559,
32
+ 5.346636965797545,
33
+ 37.10732723092604])
34
+ g1 = np.array([-0.43295349282641515,
35
+ 1.008607936794592,
36
+ 18.223666726602975,
37
+ 31.927010036981997,
38
+ -19.667512518739386])
39
+ g2 = np.array([-0.4699874455100256,
40
+ 0.9466285353668347,
41
+ -0.016874360242016825,
42
+ 48.44999161133457,
43
+ 5.819631620590712])
44
+ g3 = np.array([-0.46970678696829116,
45
+ 0.9612719312174818,
46
+ 0.006129809488833699,
47
+ 48.43557729419473,
48
+ 6.005481418498221])
49
+
50
+ if np.allclose(x, x0):
51
+ f = f0
52
+ g = g0
53
+ elif np.allclose(x, x1):
54
+ f = f1
55
+ g = g1
56
+ elif np.allclose(x, x2):
57
+ f = f2
58
+ g = g2
59
+ elif np.allclose(x, x3):
60
+ f = f3
61
+ g = g3
62
+ else:
63
+ raise ValueError(
64
+ 'Simplified objective function not defined '
65
+ 'at requested point')
66
+ return (np.copy(f), np.copy(g))
67
+
68
+
69
+ def test_setulb_floatround():
70
+ """test if setulb() violates bounds
71
+
72
+ checks for violation due to floating point rounding error
73
+ """
74
+
75
+ n = 5
76
+ m = 10
77
+ factr = 1e7
78
+ pgtol = 1e-5
79
+ maxls = 20
80
+ nbd = np.full(shape=(n,), fill_value=2, dtype=np.int32)
81
+ low_bnd = np.zeros(n, dtype=np.float64)
82
+ upper_bnd = np.ones(n, dtype=np.float64)
83
+
84
+ x0 = np.array(
85
+ [0.8750000000000278,
86
+ 0.7500000000000153,
87
+ 0.9499999999999722,
88
+ 0.8214285714285992,
89
+ 0.6363636363636085])
90
+ x = np.copy(x0)
91
+
92
+ f = np.array(0.0, dtype=np.float64)
93
+ g = np.zeros(n, dtype=np.float64)
94
+
95
+ wa = np.zeros(2*m*n + 5*n + 11*m*m + 8*m, dtype=np.float64)
96
+ iwa = np.zeros(3*n, dtype=np.int32)
97
+ task = np.zeros(2, dtype=np.int32)
98
+ ln_task = np.zeros(2, dtype=np.int32)
99
+ lsave = np.zeros(4, dtype=np.int32)
100
+ isave = np.zeros(44, dtype=np.int32)
101
+ dsave = np.zeros(29, dtype=np.float64)
102
+
103
+ for n_iter in range(7): # 7 steps required to reproduce error
104
+ f, g = objfun(x)
105
+
106
+ _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa,
107
+ iwa, task, lsave, isave, dsave, maxls, ln_task)
108
+
109
+ assert (x <= upper_bnd).all() and (x >= low_bnd).all(), (
110
+ "_lbfgsb.setulb() stepped to a point outside of the bounds")
111
+
112
+
113
+ def test_gh_issue18730():
114
+ # issue 18730 reported that l-bfgs-b did not work with objectives
115
+ # returning single precision gradient arrays
116
+ def fun_single_precision(x):
117
+ x = x.astype(np.float32)
118
+ return np.sum(x**2), (2*x)
119
+
120
+ res = minimize(fun_single_precision, x0=np.array([1., 1.]), jac=True,
121
+ method="l-bfgs-b")
122
+ np.testing.assert_allclose(res.fun, 0., atol=1e-15)
shared/package-files/e8/e80acaf24b2c84b6050ce0e8f7543be7f72acc58e7d26373437f9375e7eee32e/blob ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/autograd/profiler_kineto.h>
4
+ #include <torch/csrc/autograd/profiler_legacy.h>
shared/package-files/e8/e80b8396342dbdff3d0d3354c9633b937a1494ffe5abbd0d53e20d28ab5e3816/blob ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pygments
3
+ ~~~~~~~~
4
+
5
+ Pygments is a syntax highlighting package written in Python.
6
+
7
+ It is a generic syntax highlighter for general use in all kinds of software
8
+ such as forum systems, wikis or other applications that need to prettify
9
+ source code. Highlights are:
10
+
11
+ * a wide range of common languages and markup formats is supported
12
+ * special attention is paid to details, increasing quality by a fair amount
13
+ * support for new languages and formats are added easily
14
+ * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image
15
+ formats that PIL supports, and ANSI sequences
16
+ * it is usable as a command-line tool and as a library
17
+ * ... and it highlights even Brainfuck!
18
+
19
+ The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``.
20
+
21
+ .. _Pygments master branch:
22
+ https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev
23
+
24
+ :copyright: Copyright 2006-2023 by the Pygments team, see AUTHORS.
25
+ :license: BSD, see LICENSE for details.
26
+ """
27
+ from io import StringIO, BytesIO
28
+
29
+ __version__ = '2.15.1'
30
+ __docformat__ = 'restructuredtext'
31
+
32
+ __all__ = ['lex', 'format', 'highlight']
33
+
34
+
35
+ def lex(code, lexer):
36
+ """
37
+ Lex `code` with the `lexer` (must be a `Lexer` instance)
38
+ and return an iterable of tokens. Currently, this only calls
39
+ `lexer.get_tokens()`.
40
+ """
41
+ try:
42
+ return lexer.get_tokens(code)
43
+ except TypeError:
44
+ # Heuristic to catch a common mistake.
45
+ from pip._vendor.pygments.lexer import RegexLexer
46
+ if isinstance(lexer, type) and issubclass(lexer, RegexLexer):
47
+ raise TypeError('lex() argument must be a lexer instance, '
48
+ 'not a class')
49
+ raise
50
+
51
+
52
+ def format(tokens, formatter, outfile=None): # pylint: disable=redefined-builtin
53
+ """
54
+ Format ``tokens`` (an iterable of tokens) with the formatter ``formatter``
55
+ (a `Formatter` instance).
56
+
57
+ If ``outfile`` is given and a valid file object (an object with a
58
+ ``write`` method), the result will be written to it, otherwise it
59
+ is returned as a string.
60
+ """
61
+ try:
62
+ if not outfile:
63
+ realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()
64
+ formatter.format(tokens, realoutfile)
65
+ return realoutfile.getvalue()
66
+ else:
67
+ formatter.format(tokens, outfile)
68
+ except TypeError:
69
+ # Heuristic to catch a common mistake.
70
+ from pip._vendor.pygments.formatter import Formatter
71
+ if isinstance(formatter, type) and issubclass(formatter, Formatter):
72
+ raise TypeError('format() argument must be a formatter instance, '
73
+ 'not a class')
74
+ raise
75
+
76
+
77
+ def highlight(code, lexer, formatter, outfile=None):
78
+ """
79
+ This is the most high-level highlighting function. It combines `lex` and
80
+ `format` in one function.
81
+ """
82
+ return format(lex(code, lexer), formatter, outfile)
shared/package-files/e8/e80c37ff6bdd6e1e2eac4450e8d68f85ff5afd3d68d68e9c8e6ddf6f9677fd81/blob ADDED
@@ -0,0 +1,1453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions to operate on polynomials.
3
+
4
+ """
5
+ __all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd',
6
+ 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d',
7
+ 'polyfit', 'RankWarning']
8
+
9
+ import functools
10
+ import re
11
+ import warnings
12
+
13
+ from .._utils import set_module
14
+ import numpy.core.numeric as NX
15
+
16
+ from numpy.core import (isscalar, abs, finfo, atleast_1d, hstack, dot, array,
17
+ ones)
18
+ from numpy.core import overrides
19
+ from numpy.lib.twodim_base import diag, vander
20
+ from numpy.lib.function_base import trim_zeros
21
+ from numpy.lib.type_check import iscomplex, real, imag, mintypecode
22
+ from numpy.linalg import eigvals, lstsq, inv
23
+
24
+
25
+ array_function_dispatch = functools.partial(
26
+ overrides.array_function_dispatch, module='numpy')
27
+
28
+
29
+ @set_module('numpy')
30
+ class RankWarning(UserWarning):
31
+ """
32
+ Issued by `polyfit` when the Vandermonde matrix is rank deficient.
33
+
34
+ For more information, a way to suppress the warning, and an example of
35
+ `RankWarning` being issued, see `polyfit`.
36
+
37
+ """
38
+ pass
39
+
40
+
41
+ def _poly_dispatcher(seq_of_zeros):
42
+ return seq_of_zeros
43
+
44
+
45
+ @array_function_dispatch(_poly_dispatcher)
46
+ def poly(seq_of_zeros):
47
+ """
48
+ Find the coefficients of a polynomial with the given sequence of roots.
49
+
50
+ .. note::
51
+ This forms part of the old polynomial API. Since version 1.4, the
52
+ new polynomial API defined in `numpy.polynomial` is preferred.
53
+ A summary of the differences can be found in the
54
+ :doc:`transition guide </reference/routines.polynomials>`.
55
+
56
+ Returns the coefficients of the polynomial whose leading coefficient
57
+ is one for the given sequence of zeros (multiple roots must be included
58
+ in the sequence as many times as their multiplicity; see Examples).
59
+ A square matrix (or array, which will be treated as a matrix) can also
60
+ be given, in which case the coefficients of the characteristic polynomial
61
+ of the matrix are returned.
62
+
63
+ Parameters
64
+ ----------
65
+ seq_of_zeros : array_like, shape (N,) or (N, N)
66
+ A sequence of polynomial roots, or a square array or matrix object.
67
+
68
+ Returns
69
+ -------
70
+ c : ndarray
71
+ 1D array of polynomial coefficients from highest to lowest degree:
72
+
73
+ ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]``
74
+ where c[0] always equals 1.
75
+
76
+ Raises
77
+ ------
78
+ ValueError
79
+ If input is the wrong shape (the input must be a 1-D or square
80
+ 2-D array).
81
+
82
+ See Also
83
+ --------
84
+ polyval : Compute polynomial values.
85
+ roots : Return the roots of a polynomial.
86
+ polyfit : Least squares polynomial fit.
87
+ poly1d : A one-dimensional polynomial class.
88
+
89
+ Notes
90
+ -----
91
+ Specifying the roots of a polynomial still leaves one degree of
92
+ freedom, typically represented by an undetermined leading
93
+ coefficient. [1]_ In the case of this function, that coefficient -
94
+ the first one in the returned array - is always taken as one. (If
95
+ for some reason you have one other point, the only automatic way
96
+ presently to leverage that information is to use ``polyfit``.)
97
+
98
+ The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n`
99
+ matrix **A** is given by
100
+
101
+ :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`,
102
+
103
+ where **I** is the `n`-by-`n` identity matrix. [2]_
104
+
105
+ References
106
+ ----------
107
+ .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trigonometry,
108
+ Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996.
109
+
110
+ .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition,"
111
+ Academic Press, pg. 182, 1980.
112
+
113
+ Examples
114
+ --------
115
+ Given a sequence of a polynomial's zeros:
116
+
117
+ >>> np.poly((0, 0, 0)) # Multiple root example
118
+ array([1., 0., 0., 0.])
119
+
120
+ The line above represents z**3 + 0*z**2 + 0*z + 0.
121
+
122
+ >>> np.poly((-1./2, 0, 1./2))
123
+ array([ 1. , 0. , -0.25, 0. ])
124
+
125
+ The line above represents z**3 - z/4
126
+
127
+ >>> np.poly((np.random.random(1)[0], 0, np.random.random(1)[0]))
128
+ array([ 1. , -0.77086955, 0.08618131, 0. ]) # random
129
+
130
+ Given a square array object:
131
+
132
+ >>> P = np.array([[0, 1./3], [-1./2, 0]])
133
+ >>> np.poly(P)
134
+ array([1. , 0. , 0.16666667])
135
+
136
+ Note how in all cases the leading coefficient is always 1.
137
+
138
+ """
139
+ seq_of_zeros = atleast_1d(seq_of_zeros)
140
+ sh = seq_of_zeros.shape
141
+
142
+ if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0:
143
+ seq_of_zeros = eigvals(seq_of_zeros)
144
+ elif len(sh) == 1:
145
+ dt = seq_of_zeros.dtype
146
+ # Let object arrays slip through, e.g. for arbitrary precision
147
+ if dt != object:
148
+ seq_of_zeros = seq_of_zeros.astype(mintypecode(dt.char))
149
+ else:
150
+ raise ValueError("input must be 1d or non-empty square 2d array.")
151
+
152
+ if len(seq_of_zeros) == 0:
153
+ return 1.0
154
+ dt = seq_of_zeros.dtype
155
+ a = ones((1,), dtype=dt)
156
+ for zero in seq_of_zeros:
157
+ a = NX.convolve(a, array([1, -zero], dtype=dt), mode='full')
158
+
159
+ if issubclass(a.dtype.type, NX.complexfloating):
160
+ # if complex roots are all complex conjugates, the roots are real.
161
+ roots = NX.asarray(seq_of_zeros, complex)
162
+ if NX.all(NX.sort(roots) == NX.sort(roots.conjugate())):
163
+ a = a.real.copy()
164
+
165
+ return a
166
+
167
+
168
+ def _roots_dispatcher(p):
169
+ return p
170
+
171
+
172
+ @array_function_dispatch(_roots_dispatcher)
173
+ def roots(p):
174
+ """
175
+ Return the roots of a polynomial with coefficients given in p.
176
+
177
+ .. note::
178
+ This forms part of the old polynomial API. Since version 1.4, the
179
+ new polynomial API defined in `numpy.polynomial` is preferred.
180
+ A summary of the differences can be found in the
181
+ :doc:`transition guide </reference/routines.polynomials>`.
182
+
183
+ The values in the rank-1 array `p` are coefficients of a polynomial.
184
+ If the length of `p` is n+1 then the polynomial is described by::
185
+
186
+ p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n]
187
+
188
+ Parameters
189
+ ----------
190
+ p : array_like
191
+ Rank-1 array of polynomial coefficients.
192
+
193
+ Returns
194
+ -------
195
+ out : ndarray
196
+ An array containing the roots of the polynomial.
197
+
198
+ Raises
199
+ ------
200
+ ValueError
201
+ When `p` cannot be converted to a rank-1 array.
202
+
203
+ See also
204
+ --------
205
+ poly : Find the coefficients of a polynomial with a given sequence
206
+ of roots.
207
+ polyval : Compute polynomial values.
208
+ polyfit : Least squares polynomial fit.
209
+ poly1d : A one-dimensional polynomial class.
210
+
211
+ Notes
212
+ -----
213
+ The algorithm relies on computing the eigenvalues of the
214
+ companion matrix [1]_.
215
+
216
+ References
217
+ ----------
218
+ .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK:
219
+ Cambridge University Press, 1999, pp. 146-7.
220
+
221
+ Examples
222
+ --------
223
+ >>> coeff = [3.2, 2, 1]
224
+ >>> np.roots(coeff)
225
+ array([-0.3125+0.46351241j, -0.3125-0.46351241j])
226
+
227
+ """
228
+ # If input is scalar, this makes it an array
229
+ p = atleast_1d(p)
230
+ if p.ndim != 1:
231
+ raise ValueError("Input must be a rank-1 array.")
232
+
233
+ # find non-zero array entries
234
+ non_zero = NX.nonzero(NX.ravel(p))[0]
235
+
236
+ # Return an empty array if polynomial is all zeros
237
+ if len(non_zero) == 0:
238
+ return NX.array([])
239
+
240
+ # find the number of trailing zeros -- this is the number of roots at 0.
241
+ trailing_zeros = len(p) - non_zero[-1] - 1
242
+
243
+ # strip leading and trailing zeros
244
+ p = p[int(non_zero[0]):int(non_zero[-1])+1]
245
+
246
+ # casting: if incoming array isn't floating point, make it floating point.
247
+ if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)):
248
+ p = p.astype(float)
249
+
250
+ N = len(p)
251
+ if N > 1:
252
+ # build companion matrix and find its eigenvalues (the roots)
253
+ A = diag(NX.ones((N-2,), p.dtype), -1)
254
+ A[0,:] = -p[1:] / p[0]
255
+ roots = eigvals(A)
256
+ else:
257
+ roots = NX.array([])
258
+
259
+ # tack any zeros onto the back of the array
260
+ roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype)))
261
+ return roots
262
+
263
+
264
+ def _polyint_dispatcher(p, m=None, k=None):
265
+ return (p,)
266
+
267
+
268
+ @array_function_dispatch(_polyint_dispatcher)
269
+ def polyint(p, m=1, k=None):
270
+ """
271
+ Return an antiderivative (indefinite integral) of a polynomial.
272
+
273
+ .. note::
274
+ This forms part of the old polynomial API. Since version 1.4, the
275
+ new polynomial API defined in `numpy.polynomial` is preferred.
276
+ A summary of the differences can be found in the
277
+ :doc:`transition guide </reference/routines.polynomials>`.
278
+
279
+ The returned order `m` antiderivative `P` of polynomial `p` satisfies
280
+ :math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1`
281
+ integration constants `k`. The constants determine the low-order
282
+ polynomial part
283
+
284
+ .. math:: \\frac{k_{m-1}}{0!} x^0 + \\ldots + \\frac{k_0}{(m-1)!}x^{m-1}
285
+
286
+ of `P` so that :math:`P^{(j)}(0) = k_{m-j-1}`.
287
+
288
+ Parameters
289
+ ----------
290
+ p : array_like or poly1d
291
+ Polynomial to integrate.
292
+ A sequence is interpreted as polynomial coefficients, see `poly1d`.
293
+ m : int, optional
294
+ Order of the antiderivative. (Default: 1)
295
+ k : list of `m` scalars or scalar, optional
296
+ Integration constants. They are given in the order of integration:
297
+ those corresponding to highest-order terms come first.
298
+
299
+ If ``None`` (default), all constants are assumed to be zero.
300
+ If `m = 1`, a single scalar can be given instead of a list.
301
+
302
+ See Also
303
+ --------
304
+ polyder : derivative of a polynomial
305
+ poly1d.integ : equivalent method
306
+
307
+ Examples
308
+ --------
309
+ The defining property of the antiderivative:
310
+
311
+ >>> p = np.poly1d([1,1,1])
312
+ >>> P = np.polyint(p)
313
+ >>> P
314
+ poly1d([ 0.33333333, 0.5 , 1. , 0. ]) # may vary
315
+ >>> np.polyder(P) == p
316
+ True
317
+
318
+ The integration constants default to zero, but can be specified:
319
+
320
+ >>> P = np.polyint(p, 3)
321
+ >>> P(0)
322
+ 0.0
323
+ >>> np.polyder(P)(0)
324
+ 0.0
325
+ >>> np.polyder(P, 2)(0)
326
+ 0.0
327
+ >>> P = np.polyint(p, 3, k=[6,5,3])
328
+ >>> P
329
+ poly1d([ 0.01666667, 0.04166667, 0.16666667, 3. , 5. , 3. ]) # may vary
330
+
331
+ Note that 3 = 6 / 2!, and that the constants are given in the order of
332
+ integrations. Constant of the highest-order polynomial term comes first:
333
+
334
+ >>> np.polyder(P, 2)(0)
335
+ 6.0
336
+ >>> np.polyder(P, 1)(0)
337
+ 5.0
338
+ >>> P(0)
339
+ 3.0
340
+
341
+ """
342
+ m = int(m)
343
+ if m < 0:
344
+ raise ValueError("Order of integral must be positive (see polyder)")
345
+ if k is None:
346
+ k = NX.zeros(m, float)
347
+ k = atleast_1d(k)
348
+ if len(k) == 1 and m > 1:
349
+ k = k[0]*NX.ones(m, float)
350
+ if len(k) < m:
351
+ raise ValueError(
352
+ "k must be a scalar or a rank-1 array of length 1 or >m.")
353
+
354
+ truepoly = isinstance(p, poly1d)
355
+ p = NX.asarray(p)
356
+ if m == 0:
357
+ if truepoly:
358
+ return poly1d(p)
359
+ return p
360
+ else:
361
+ # Note: this must work also with object and integer arrays
362
+ y = NX.concatenate((p.__truediv__(NX.arange(len(p), 0, -1)), [k[0]]))
363
+ val = polyint(y, m - 1, k=k[1:])
364
+ if truepoly:
365
+ return poly1d(val)
366
+ return val
367
+
368
+
369
+ def _polyder_dispatcher(p, m=None):
370
+ return (p,)
371
+
372
+
373
+ @array_function_dispatch(_polyder_dispatcher)
374
+ def polyder(p, m=1):
375
+ """
376
+ Return the derivative of the specified order of a polynomial.
377
+
378
+ .. note::
379
+ This forms part of the old polynomial API. Since version 1.4, the
380
+ new polynomial API defined in `numpy.polynomial` is preferred.
381
+ A summary of the differences can be found in the
382
+ :doc:`transition guide </reference/routines.polynomials>`.
383
+
384
+ Parameters
385
+ ----------
386
+ p : poly1d or sequence
387
+ Polynomial to differentiate.
388
+ A sequence is interpreted as polynomial coefficients, see `poly1d`.
389
+ m : int, optional
390
+ Order of differentiation (default: 1)
391
+
392
+ Returns
393
+ -------
394
+ der : poly1d
395
+ A new polynomial representing the derivative.
396
+
397
+ See Also
398
+ --------
399
+ polyint : Anti-derivative of a polynomial.
400
+ poly1d : Class for one-dimensional polynomials.
401
+
402
+ Examples
403
+ --------
404
+ The derivative of the polynomial :math:`x^3 + x^2 + x^1 + 1` is:
405
+
406
+ >>> p = np.poly1d([1,1,1,1])
407
+ >>> p2 = np.polyder(p)
408
+ >>> p2
409
+ poly1d([3, 2, 1])
410
+
411
+ which evaluates to:
412
+
413
+ >>> p2(2.)
414
+ 17.0
415
+
416
+ We can verify this, approximating the derivative with
417
+ ``(f(x + h) - f(x))/h``:
418
+
419
+ >>> (p(2. + 0.001) - p(2.)) / 0.001
420
+ 17.007000999997857
421
+
422
+ The fourth-order derivative of a 3rd-order polynomial is zero:
423
+
424
+ >>> np.polyder(p, 2)
425
+ poly1d([6, 2])
426
+ >>> np.polyder(p, 3)
427
+ poly1d([6])
428
+ >>> np.polyder(p, 4)
429
+ poly1d([0])
430
+
431
+ """
432
+ m = int(m)
433
+ if m < 0:
434
+ raise ValueError("Order of derivative must be positive (see polyint)")
435
+
436
+ truepoly = isinstance(p, poly1d)
437
+ p = NX.asarray(p)
438
+ n = len(p) - 1
439
+ y = p[:-1] * NX.arange(n, 0, -1)
440
+ if m == 0:
441
+ val = p
442
+ else:
443
+ val = polyder(y, m - 1)
444
+ if truepoly:
445
+ val = poly1d(val)
446
+ return val
447
+
448
+
449
+ def _polyfit_dispatcher(x, y, deg, rcond=None, full=None, w=None, cov=None):
450
+ return (x, y, w)
451
+
452
+
453
+ @array_function_dispatch(_polyfit_dispatcher)
454
+ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
455
+ """
456
+ Least squares polynomial fit.
457
+
458
+ .. note::
459
+ This forms part of the old polynomial API. Since version 1.4, the
460
+ new polynomial API defined in `numpy.polynomial` is preferred.
461
+ A summary of the differences can be found in the
462
+ :doc:`transition guide </reference/routines.polynomials>`.
463
+
464
+ Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`
465
+ to points `(x, y)`. Returns a vector of coefficients `p` that minimises
466
+ the squared error in the order `deg`, `deg-1`, ... `0`.
467
+
468
+ The `Polynomial.fit <numpy.polynomial.polynomial.Polynomial.fit>` class
469
+ method is recommended for new code as it is more stable numerically. See
470
+ the documentation of the method for more information.
471
+
472
+ Parameters
473
+ ----------
474
+ x : array_like, shape (M,)
475
+ x-coordinates of the M sample points ``(x[i], y[i])``.
476
+ y : array_like, shape (M,) or (M, K)
477
+ y-coordinates of the sample points. Several data sets of sample
478
+ points sharing the same x-coordinates can be fitted at once by
479
+ passing in a 2D-array that contains one dataset per column.
480
+ deg : int
481
+ Degree of the fitting polynomial
482
+ rcond : float, optional
483
+ Relative condition number of the fit. Singular values smaller than
484
+ this relative to the largest singular value will be ignored. The
485
+ default value is len(x)*eps, where eps is the relative precision of
486
+ the float type, about 2e-16 in most cases.
487
+ full : bool, optional
488
+ Switch determining nature of return value. When it is False (the
489
+ default) just the coefficients are returned, when True diagnostic
490
+ information from the singular value decomposition is also returned.
491
+ w : array_like, shape (M,), optional
492
+ Weights. If not None, the weight ``w[i]`` applies to the unsquared
493
+ residual ``y[i] - y_hat[i]`` at ``x[i]``. Ideally the weights are
494
+ chosen so that the errors of the products ``w[i]*y[i]`` all have the
495
+ same variance. When using inverse-variance weighting, use
496
+ ``w[i] = 1/sigma(y[i])``. The default value is None.
497
+ cov : bool or str, optional
498
+ If given and not `False`, return not just the estimate but also its
499
+ covariance matrix. By default, the covariance are scaled by
500
+ chi2/dof, where dof = M - (deg + 1), i.e., the weights are presumed
501
+ to be unreliable except in a relative sense and everything is scaled
502
+ such that the reduced chi2 is unity. This scaling is omitted if
503
+ ``cov='unscaled'``, as is relevant for the case that the weights are
504
+ w = 1/sigma, with sigma known to be a reliable estimate of the
505
+ uncertainty.
506
+
507
+ Returns
508
+ -------
509
+ p : ndarray, shape (deg + 1,) or (deg + 1, K)
510
+ Polynomial coefficients, highest power first. If `y` was 2-D, the
511
+ coefficients for `k`-th data set are in ``p[:,k]``.
512
+
513
+ residuals, rank, singular_values, rcond
514
+ These values are only returned if ``full == True``
515
+
516
+ - residuals -- sum of squared residuals of the least squares fit
517
+ - rank -- the effective rank of the scaled Vandermonde
518
+ coefficient matrix
519
+ - singular_values -- singular values of the scaled Vandermonde
520
+ coefficient matrix
521
+ - rcond -- value of `rcond`.
522
+
523
+ For more details, see `numpy.linalg.lstsq`.
524
+
525
+ V : ndarray, shape (M,M) or (M,M,K)
526
+ Present only if ``full == False`` and ``cov == True``. The covariance
527
+ matrix of the polynomial coefficient estimates. The diagonal of
528
+ this matrix are the variance estimates for each coefficient. If y
529
+ is a 2-D array, then the covariance matrix for the `k`-th data set
530
+ are in ``V[:,:,k]``
531
+
532
+
533
+ Warns
534
+ -----
535
+ RankWarning
536
+ The rank of the coefficient matrix in the least-squares fit is
537
+ deficient. The warning is only raised if ``full == False``.
538
+
539
+ The warnings can be turned off by
540
+
541
+ >>> import warnings
542
+ >>> warnings.simplefilter('ignore', np.RankWarning)
543
+
544
+ See Also
545
+ --------
546
+ polyval : Compute polynomial values.
547
+ linalg.lstsq : Computes a least-squares fit.
548
+ scipy.interpolate.UnivariateSpline : Computes spline fits.
549
+
550
+ Notes
551
+ -----
552
+ The solution minimizes the squared error
553
+
554
+ .. math::
555
+ E = \\sum_{j=0}^k |p(x_j) - y_j|^2
556
+
557
+ in the equations::
558
+
559
+ x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
560
+ x[1]**n * p[0] + ... + x[1] * p[n-1] + p[n] = y[1]
561
+ ...
562
+ x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]
563
+
564
+ The coefficient matrix of the coefficients `p` is a Vandermonde matrix.
565
+
566
+ `polyfit` issues a `RankWarning` when the least-squares fit is badly
567
+ conditioned. This implies that the best fit is not well-defined due
568
+ to numerical error. The results may be improved by lowering the polynomial
569
+ degree or by replacing `x` by `x` - `x`.mean(). The `rcond` parameter
570
+ can also be set to a value smaller than its default, but the resulting
571
+ fit may be spurious: including contributions from the small singular
572
+ values can add numerical noise to the result.
573
+
574
+ Note that fitting polynomial coefficients is inherently badly conditioned
575
+ when the degree of the polynomial is large or the interval of sample points
576
+ is badly centered. The quality of the fit should always be checked in these
577
+ cases. When polynomial fits are not satisfactory, splines may be a good
578
+ alternative.
579
+
580
+ References
581
+ ----------
582
+ .. [1] Wikipedia, "Curve fitting",
583
+ https://en.wikipedia.org/wiki/Curve_fitting
584
+ .. [2] Wikipedia, "Polynomial interpolation",
585
+ https://en.wikipedia.org/wiki/Polynomial_interpolation
586
+
587
+ Examples
588
+ --------
589
+ >>> import warnings
590
+ >>> x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
591
+ >>> y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
592
+ >>> z = np.polyfit(x, y, 3)
593
+ >>> z
594
+ array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) # may vary
595
+
596
+ It is convenient to use `poly1d` objects for dealing with polynomials:
597
+
598
+ >>> p = np.poly1d(z)
599
+ >>> p(0.5)
600
+ 0.6143849206349179 # may vary
601
+ >>> p(3.5)
602
+ -0.34732142857143039 # may vary
603
+ >>> p(10)
604
+ 22.579365079365115 # may vary
605
+
606
+ High-order polynomials may oscillate wildly:
607
+
608
+ >>> with warnings.catch_warnings():
609
+ ... warnings.simplefilter('ignore', np.RankWarning)
610
+ ... p30 = np.poly1d(np.polyfit(x, y, 30))
611
+ ...
612
+ >>> p30(4)
613
+ -0.80000000000000204 # may vary
614
+ >>> p30(5)
615
+ -0.99999999999999445 # may vary
616
+ >>> p30(4.5)
617
+ -0.10547061179440398 # may vary
618
+
619
+ Illustration:
620
+
621
+ >>> import matplotlib.pyplot as plt
622
+ >>> xp = np.linspace(-2, 6, 100)
623
+ >>> _ = plt.plot(x, y, '.', xp, p(xp), '-', xp, p30(xp), '--')
624
+ >>> plt.ylim(-2,2)
625
+ (-2, 2)
626
+ >>> plt.show()
627
+
628
+ """
629
+ order = int(deg) + 1
630
+ x = NX.asarray(x) + 0.0
631
+ y = NX.asarray(y) + 0.0
632
+
633
+ # check arguments.
634
+ if deg < 0:
635
+ raise ValueError("expected deg >= 0")
636
+ if x.ndim != 1:
637
+ raise TypeError("expected 1D vector for x")
638
+ if x.size == 0:
639
+ raise TypeError("expected non-empty vector for x")
640
+ if y.ndim < 1 or y.ndim > 2:
641
+ raise TypeError("expected 1D or 2D array for y")
642
+ if x.shape[0] != y.shape[0]:
643
+ raise TypeError("expected x and y to have same length")
644
+
645
+ # set rcond
646
+ if rcond is None:
647
+ rcond = len(x)*finfo(x.dtype).eps
648
+
649
+ # set up least squares equation for powers of x
650
+ lhs = vander(x, order)
651
+ rhs = y
652
+
653
+ # apply weighting
654
+ if w is not None:
655
+ w = NX.asarray(w) + 0.0
656
+ if w.ndim != 1:
657
+ raise TypeError("expected a 1-d array for weights")
658
+ if w.shape[0] != y.shape[0]:
659
+ raise TypeError("expected w and y to have the same length")
660
+ lhs *= w[:, NX.newaxis]
661
+ if rhs.ndim == 2:
662
+ rhs *= w[:, NX.newaxis]
663
+ else:
664
+ rhs *= w
665
+
666
+ # scale lhs to improve condition number and solve
667
+ scale = NX.sqrt((lhs*lhs).sum(axis=0))
668
+ lhs /= scale
669
+ c, resids, rank, s = lstsq(lhs, rhs, rcond)
670
+ c = (c.T/scale).T # broadcast scale coefficients
671
+
672
+ # warn on rank reduction, which indicates an ill conditioned matrix
673
+ if rank != order and not full:
674
+ msg = "Polyfit may be poorly conditioned"
675
+ warnings.warn(msg, RankWarning, stacklevel=2)
676
+
677
+ if full:
678
+ return c, resids, rank, s, rcond
679
+ elif cov:
680
+ Vbase = inv(dot(lhs.T, lhs))
681
+ Vbase /= NX.outer(scale, scale)
682
+ if cov == "unscaled":
683
+ fac = 1
684
+ else:
685
+ if len(x) <= order:
686
+ raise ValueError("the number of data points must exceed order "
687
+ "to scale the covariance matrix")
688
+ # note, this used to be: fac = resids / (len(x) - order - 2.0)
689
+ # it was deciced that the "- 2" (originally justified by "Bayesian
690
+ # uncertainty analysis") is not what the user expects
691
+ # (see gh-11196 and gh-11197)
692
+ fac = resids / (len(x) - order)
693
+ if y.ndim == 1:
694
+ return c, Vbase * fac
695
+ else:
696
+ return c, Vbase[:,:, NX.newaxis] * fac
697
+ else:
698
+ return c
699
+
700
+
701
+ def _polyval_dispatcher(p, x):
702
+ return (p, x)
703
+
704
+
705
+ @array_function_dispatch(_polyval_dispatcher)
706
+ def polyval(p, x):
707
+ """
708
+ Evaluate a polynomial at specific values.
709
+
710
+ .. note::
711
+ This forms part of the old polynomial API. Since version 1.4, the
712
+ new polynomial API defined in `numpy.polynomial` is preferred.
713
+ A summary of the differences can be found in the
714
+ :doc:`transition guide </reference/routines.polynomials>`.
715
+
716
+ If `p` is of length N, this function returns the value:
717
+
718
+ ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]``
719
+
720
+ If `x` is a sequence, then ``p(x)`` is returned for each element of ``x``.
721
+ If `x` is another polynomial then the composite polynomial ``p(x(t))``
722
+ is returned.
723
+
724
+ Parameters
725
+ ----------
726
+ p : array_like or poly1d object
727
+ 1D array of polynomial coefficients (including coefficients equal
728
+ to zero) from highest degree to the constant term, or an
729
+ instance of poly1d.
730
+ x : array_like or poly1d object
731
+ A number, an array of numbers, or an instance of poly1d, at
732
+ which to evaluate `p`.
733
+
734
+ Returns
735
+ -------
736
+ values : ndarray or poly1d
737
+ If `x` is a poly1d instance, the result is the composition of the two
738
+ polynomials, i.e., `x` is "substituted" in `p` and the simplified
739
+ result is returned. In addition, the type of `x` - array_like or
740
+ poly1d - governs the type of the output: `x` array_like => `values`
741
+ array_like, `x` a poly1d object => `values` is also.
742
+
743
+ See Also
744
+ --------
745
+ poly1d: A polynomial class.
746
+
747
+ Notes
748
+ -----
749
+ Horner's scheme [1]_ is used to evaluate the polynomial. Even so,
750
+ for polynomials of high degree the values may be inaccurate due to
751
+ rounding errors. Use carefully.
752
+
753
+ If `x` is a subtype of `ndarray` the return value will be of the same type.
754
+
755
+ References
756
+ ----------
757
+ .. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng.
758
+ trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand
759
+ Reinhold Co., 1985, pg. 720.
760
+
761
+ Examples
762
+ --------
763
+ >>> np.polyval([3,0,1], 5) # 3 * 5**2 + 0 * 5**1 + 1
764
+ 76
765
+ >>> np.polyval([3,0,1], np.poly1d(5))
766
+ poly1d([76])
767
+ >>> np.polyval(np.poly1d([3,0,1]), 5)
768
+ 76
769
+ >>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
770
+ poly1d([76])
771
+
772
+ """
773
+ p = NX.asarray(p)
774
+ if isinstance(x, poly1d):
775
+ y = 0
776
+ else:
777
+ x = NX.asanyarray(x)
778
+ y = NX.zeros_like(x)
779
+ for pv in p:
780
+ y = y * x + pv
781
+ return y
782
+
783
+
784
+ def _binary_op_dispatcher(a1, a2):
785
+ return (a1, a2)
786
+
787
+
788
+ @array_function_dispatch(_binary_op_dispatcher)
789
+ def polyadd(a1, a2):
790
+ """
791
+ Find the sum of two polynomials.
792
+
793
+ .. note::
794
+ This forms part of the old polynomial API. Since version 1.4, the
795
+ new polynomial API defined in `numpy.polynomial` is preferred.
796
+ A summary of the differences can be found in the
797
+ :doc:`transition guide </reference/routines.polynomials>`.
798
+
799
+ Returns the polynomial resulting from the sum of two input polynomials.
800
+ Each input must be either a poly1d object or a 1D sequence of polynomial
801
+ coefficients, from highest to lowest degree.
802
+
803
+ Parameters
804
+ ----------
805
+ a1, a2 : array_like or poly1d object
806
+ Input polynomials.
807
+
808
+ Returns
809
+ -------
810
+ out : ndarray or poly1d object
811
+ The sum of the inputs. If either input is a poly1d object, then the
812
+ output is also a poly1d object. Otherwise, it is a 1D array of
813
+ polynomial coefficients from highest to lowest degree.
814
+
815
+ See Also
816
+ --------
817
+ poly1d : A one-dimensional polynomial class.
818
+ poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval
819
+
820
+ Examples
821
+ --------
822
+ >>> np.polyadd([1, 2], [9, 5, 4])
823
+ array([9, 6, 6])
824
+
825
+ Using poly1d objects:
826
+
827
+ >>> p1 = np.poly1d([1, 2])
828
+ >>> p2 = np.poly1d([9, 5, 4])
829
+ >>> print(p1)
830
+ 1 x + 2
831
+ >>> print(p2)
832
+ 2
833
+ 9 x + 5 x + 4
834
+ >>> print(np.polyadd(p1, p2))
835
+ 2
836
+ 9 x + 6 x + 6
837
+
838
+ """
839
+ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
840
+ a1 = atleast_1d(a1)
841
+ a2 = atleast_1d(a2)
842
+ diff = len(a2) - len(a1)
843
+ if diff == 0:
844
+ val = a1 + a2
845
+ elif diff > 0:
846
+ zr = NX.zeros(diff, a1.dtype)
847
+ val = NX.concatenate((zr, a1)) + a2
848
+ else:
849
+ zr = NX.zeros(abs(diff), a2.dtype)
850
+ val = a1 + NX.concatenate((zr, a2))
851
+ if truepoly:
852
+ val = poly1d(val)
853
+ return val
854
+
855
+
856
+ @array_function_dispatch(_binary_op_dispatcher)
857
+ def polysub(a1, a2):
858
+ """
859
+ Difference (subtraction) of two polynomials.
860
+
861
+ .. note::
862
+ This forms part of the old polynomial API. Since version 1.4, the
863
+ new polynomial API defined in `numpy.polynomial` is preferred.
864
+ A summary of the differences can be found in the
865
+ :doc:`transition guide </reference/routines.polynomials>`.
866
+
867
+ Given two polynomials `a1` and `a2`, returns ``a1 - a2``.
868
+ `a1` and `a2` can be either array_like sequences of the polynomials'
869
+ coefficients (including coefficients equal to zero), or `poly1d` objects.
870
+
871
+ Parameters
872
+ ----------
873
+ a1, a2 : array_like or poly1d
874
+ Minuend and subtrahend polynomials, respectively.
875
+
876
+ Returns
877
+ -------
878
+ out : ndarray or poly1d
879
+ Array or `poly1d` object of the difference polynomial's coefficients.
880
+
881
+ See Also
882
+ --------
883
+ polyval, polydiv, polymul, polyadd
884
+
885
+ Examples
886
+ --------
887
+ .. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2)
888
+
889
+ >>> np.polysub([2, 10, -2], [3, 10, -4])
890
+ array([-1, 0, 2])
891
+
892
+ """
893
+ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
894
+ a1 = atleast_1d(a1)
895
+ a2 = atleast_1d(a2)
896
+ diff = len(a2) - len(a1)
897
+ if diff == 0:
898
+ val = a1 - a2
899
+ elif diff > 0:
900
+ zr = NX.zeros(diff, a1.dtype)
901
+ val = NX.concatenate((zr, a1)) - a2
902
+ else:
903
+ zr = NX.zeros(abs(diff), a2.dtype)
904
+ val = a1 - NX.concatenate((zr, a2))
905
+ if truepoly:
906
+ val = poly1d(val)
907
+ return val
908
+
909
+
910
+ @array_function_dispatch(_binary_op_dispatcher)
911
+ def polymul(a1, a2):
912
+ """
913
+ Find the product of two polynomials.
914
+
915
+ .. note::
916
+ This forms part of the old polynomial API. Since version 1.4, the
917
+ new polynomial API defined in `numpy.polynomial` is preferred.
918
+ A summary of the differences can be found in the
919
+ :doc:`transition guide </reference/routines.polynomials>`.
920
+
921
+ Finds the polynomial resulting from the multiplication of the two input
922
+ polynomials. Each input must be either a poly1d object or a 1D sequence
923
+ of polynomial coefficients, from highest to lowest degree.
924
+
925
+ Parameters
926
+ ----------
927
+ a1, a2 : array_like or poly1d object
928
+ Input polynomials.
929
+
930
+ Returns
931
+ -------
932
+ out : ndarray or poly1d object
933
+ The polynomial resulting from the multiplication of the inputs. If
934
+ either inputs is a poly1d object, then the output is also a poly1d
935
+ object. Otherwise, it is a 1D array of polynomial coefficients from
936
+ highest to lowest degree.
937
+
938
+ See Also
939
+ --------
940
+ poly1d : A one-dimensional polynomial class.
941
+ poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval
942
+ convolve : Array convolution. Same output as polymul, but has parameter
943
+ for overlap mode.
944
+
945
+ Examples
946
+ --------
947
+ >>> np.polymul([1, 2, 3], [9, 5, 1])
948
+ array([ 9, 23, 38, 17, 3])
949
+
950
+ Using poly1d objects:
951
+
952
+ >>> p1 = np.poly1d([1, 2, 3])
953
+ >>> p2 = np.poly1d([9, 5, 1])
954
+ >>> print(p1)
955
+ 2
956
+ 1 x + 2 x + 3
957
+ >>> print(p2)
958
+ 2
959
+ 9 x + 5 x + 1
960
+ >>> print(np.polymul(p1, p2))
961
+ 4 3 2
962
+ 9 x + 23 x + 38 x + 17 x + 3
963
+
964
+ """
965
+ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
966
+ a1, a2 = poly1d(a1), poly1d(a2)
967
+ val = NX.convolve(a1, a2)
968
+ if truepoly:
969
+ val = poly1d(val)
970
+ return val
971
+
972
+
973
+ def _polydiv_dispatcher(u, v):
974
+ return (u, v)
975
+
976
+
977
+ @array_function_dispatch(_polydiv_dispatcher)
978
+ def polydiv(u, v):
979
+ """
980
+ Returns the quotient and remainder of polynomial division.
981
+
982
+ .. note::
983
+ This forms part of the old polynomial API. Since version 1.4, the
984
+ new polynomial API defined in `numpy.polynomial` is preferred.
985
+ A summary of the differences can be found in the
986
+ :doc:`transition guide </reference/routines.polynomials>`.
987
+
988
+ The input arrays are the coefficients (including any coefficients
989
+ equal to zero) of the "numerator" (dividend) and "denominator"
990
+ (divisor) polynomials, respectively.
991
+
992
+ Parameters
993
+ ----------
994
+ u : array_like or poly1d
995
+ Dividend polynomial's coefficients.
996
+
997
+ v : array_like or poly1d
998
+ Divisor polynomial's coefficients.
999
+
1000
+ Returns
1001
+ -------
1002
+ q : ndarray
1003
+ Coefficients, including those equal to zero, of the quotient.
1004
+ r : ndarray
1005
+ Coefficients, including those equal to zero, of the remainder.
1006
+
1007
+ See Also
1008
+ --------
1009
+ poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub
1010
+ polyval
1011
+
1012
+ Notes
1013
+ -----
1014
+ Both `u` and `v` must be 0-d or 1-d (ndim = 0 or 1), but `u.ndim` need
1015
+ not equal `v.ndim`. In other words, all four possible combinations -
1016
+ ``u.ndim = v.ndim = 0``, ``u.ndim = v.ndim = 1``,
1017
+ ``u.ndim = 1, v.ndim = 0``, and ``u.ndim = 0, v.ndim = 1`` - work.
1018
+
1019
+ Examples
1020
+ --------
1021
+ .. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25
1022
+
1023
+ >>> x = np.array([3.0, 5.0, 2.0])
1024
+ >>> y = np.array([2.0, 1.0])
1025
+ >>> np.polydiv(x, y)
1026
+ (array([1.5 , 1.75]), array([0.25]))
1027
+
1028
+ """
1029
+ truepoly = (isinstance(u, poly1d) or isinstance(v, poly1d))
1030
+ u = atleast_1d(u) + 0.0
1031
+ v = atleast_1d(v) + 0.0
1032
+ # w has the common type
1033
+ w = u[0] + v[0]
1034
+ m = len(u) - 1
1035
+ n = len(v) - 1
1036
+ scale = 1. / v[0]
1037
+ q = NX.zeros((max(m - n + 1, 1),), w.dtype)
1038
+ r = u.astype(w.dtype)
1039
+ for k in range(0, m-n+1):
1040
+ d = scale * r[k]
1041
+ q[k] = d
1042
+ r[k:k+n+1] -= d*v
1043
+ while NX.allclose(r[0], 0, rtol=1e-14) and (r.shape[-1] > 1):
1044
+ r = r[1:]
1045
+ if truepoly:
1046
+ return poly1d(q), poly1d(r)
1047
+ return q, r
1048
+
1049
+ _poly_mat = re.compile(r"\*\*([0-9]*)")
1050
+ def _raise_power(astr, wrap=70):
1051
+ n = 0
1052
+ line1 = ''
1053
+ line2 = ''
1054
+ output = ' '
1055
+ while True:
1056
+ mat = _poly_mat.search(astr, n)
1057
+ if mat is None:
1058
+ break
1059
+ span = mat.span()
1060
+ power = mat.groups()[0]
1061
+ partstr = astr[n:span[0]]
1062
+ n = span[1]
1063
+ toadd2 = partstr + ' '*(len(power)-1)
1064
+ toadd1 = ' '*(len(partstr)-1) + power
1065
+ if ((len(line2) + len(toadd2) > wrap) or
1066
+ (len(line1) + len(toadd1) > wrap)):
1067
+ output += line1 + "\n" + line2 + "\n "
1068
+ line1 = toadd1
1069
+ line2 = toadd2
1070
+ else:
1071
+ line2 += partstr + ' '*(len(power)-1)
1072
+ line1 += ' '*(len(partstr)-1) + power
1073
+ output += line1 + "\n" + line2
1074
+ return output + astr[n:]
1075
+
1076
+
1077
+ @set_module('numpy')
1078
+ class poly1d:
1079
+ """
1080
+ A one-dimensional polynomial class.
1081
+
1082
+ .. note::
1083
+ This forms part of the old polynomial API. Since version 1.4, the
1084
+ new polynomial API defined in `numpy.polynomial` is preferred.
1085
+ A summary of the differences can be found in the
1086
+ :doc:`transition guide </reference/routines.polynomials>`.
1087
+
1088
+ A convenience class, used to encapsulate "natural" operations on
1089
+ polynomials so that said operations may take on their customary
1090
+ form in code (see Examples).
1091
+
1092
+ Parameters
1093
+ ----------
1094
+ c_or_r : array_like
1095
+ The polynomial's coefficients, in decreasing powers, or if
1096
+ the value of the second parameter is True, the polynomial's
1097
+ roots (values where the polynomial evaluates to 0). For example,
1098
+ ``poly1d([1, 2, 3])`` returns an object that represents
1099
+ :math:`x^2 + 2x + 3`, whereas ``poly1d([1, 2, 3], True)`` returns
1100
+ one that represents :math:`(x-1)(x-2)(x-3) = x^3 - 6x^2 + 11x -6`.
1101
+ r : bool, optional
1102
+ If True, `c_or_r` specifies the polynomial's roots; the default
1103
+ is False.
1104
+ variable : str, optional
1105
+ Changes the variable used when printing `p` from `x` to `variable`
1106
+ (see Examples).
1107
+
1108
+ Examples
1109
+ --------
1110
+ Construct the polynomial :math:`x^2 + 2x + 3`:
1111
+
1112
+ >>> p = np.poly1d([1, 2, 3])
1113
+ >>> print(np.poly1d(p))
1114
+ 2
1115
+ 1 x + 2 x + 3
1116
+
1117
+ Evaluate the polynomial at :math:`x = 0.5`:
1118
+
1119
+ >>> p(0.5)
1120
+ 4.25
1121
+
1122
+ Find the roots:
1123
+
1124
+ >>> p.r
1125
+ array([-1.+1.41421356j, -1.-1.41421356j])
1126
+ >>> p(p.r)
1127
+ array([ -4.44089210e-16+0.j, -4.44089210e-16+0.j]) # may vary
1128
+
1129
+ These numbers in the previous line represent (0, 0) to machine precision
1130
+
1131
+ Show the coefficients:
1132
+
1133
+ >>> p.c
1134
+ array([1, 2, 3])
1135
+
1136
+ Display the order (the leading zero-coefficients are removed):
1137
+
1138
+ >>> p.order
1139
+ 2
1140
+
1141
+ Show the coefficient of the k-th power in the polynomial
1142
+ (which is equivalent to ``p.c[-(i+1)]``):
1143
+
1144
+ >>> p[1]
1145
+ 2
1146
+
1147
+ Polynomials can be added, subtracted, multiplied, and divided
1148
+ (returns quotient and remainder):
1149
+
1150
+ >>> p * p
1151
+ poly1d([ 1, 4, 10, 12, 9])
1152
+
1153
+ >>> (p**3 + 4) / p
1154
+ (poly1d([ 1., 4., 10., 12., 9.]), poly1d([4.]))
1155
+
1156
+ ``asarray(p)`` gives the coefficient array, so polynomials can be
1157
+ used in all functions that accept arrays:
1158
+
1159
+ >>> p**2 # square of polynomial
1160
+ poly1d([ 1, 4, 10, 12, 9])
1161
+
1162
+ >>> np.square(p) # square of individual coefficients
1163
+ array([1, 4, 9])
1164
+
1165
+ The variable used in the string representation of `p` can be modified,
1166
+ using the `variable` parameter:
1167
+
1168
+ >>> p = np.poly1d([1,2,3], variable='z')
1169
+ >>> print(p)
1170
+ 2
1171
+ 1 z + 2 z + 3
1172
+
1173
+ Construct a polynomial from its roots:
1174
+
1175
+ >>> np.poly1d([1, 2], True)
1176
+ poly1d([ 1., -3., 2.])
1177
+
1178
+ This is the same polynomial as obtained by:
1179
+
1180
+ >>> np.poly1d([1, -1]) * np.poly1d([1, -2])
1181
+ poly1d([ 1, -3, 2])
1182
+
1183
+ """
1184
+ __hash__ = None
1185
+
1186
+ @property
1187
+ def coeffs(self):
1188
+ """ The polynomial coefficients """
1189
+ return self._coeffs
1190
+
1191
+ @coeffs.setter
1192
+ def coeffs(self, value):
1193
+ # allowing this makes p.coeffs *= 2 legal
1194
+ if value is not self._coeffs:
1195
+ raise AttributeError("Cannot set attribute")
1196
+
1197
+ @property
1198
+ def variable(self):
1199
+ """ The name of the polynomial variable """
1200
+ return self._variable
1201
+
1202
+ # calculated attributes
1203
+ @property
1204
+ def order(self):
1205
+ """ The order or degree of the polynomial """
1206
+ return len(self._coeffs) - 1
1207
+
1208
+ @property
1209
+ def roots(self):
1210
+ """ The roots of the polynomial, where self(x) == 0 """
1211
+ return roots(self._coeffs)
1212
+
1213
+ # our internal _coeffs property need to be backed by __dict__['coeffs'] for
1214
+ # scipy to work correctly.
1215
+ @property
1216
+ def _coeffs(self):
1217
+ return self.__dict__['coeffs']
1218
+ @_coeffs.setter
1219
+ def _coeffs(self, coeffs):
1220
+ self.__dict__['coeffs'] = coeffs
1221
+
1222
+ # alias attributes
1223
+ r = roots
1224
+ c = coef = coefficients = coeffs
1225
+ o = order
1226
+
1227
+ def __init__(self, c_or_r, r=False, variable=None):
1228
+ if isinstance(c_or_r, poly1d):
1229
+ self._variable = c_or_r._variable
1230
+ self._coeffs = c_or_r._coeffs
1231
+
1232
+ if set(c_or_r.__dict__) - set(self.__dict__):
1233
+ msg = ("In the future extra properties will not be copied "
1234
+ "across when constructing one poly1d from another")
1235
+ warnings.warn(msg, FutureWarning, stacklevel=2)
1236
+ self.__dict__.update(c_or_r.__dict__)
1237
+
1238
+ if variable is not None:
1239
+ self._variable = variable
1240
+ return
1241
+ if r:
1242
+ c_or_r = poly(c_or_r)
1243
+ c_or_r = atleast_1d(c_or_r)
1244
+ if c_or_r.ndim > 1:
1245
+ raise ValueError("Polynomial must be 1d only.")
1246
+ c_or_r = trim_zeros(c_or_r, trim='f')
1247
+ if len(c_or_r) == 0:
1248
+ c_or_r = NX.array([0], dtype=c_or_r.dtype)
1249
+ self._coeffs = c_or_r
1250
+ if variable is None:
1251
+ variable = 'x'
1252
+ self._variable = variable
1253
+
1254
+ def __array__(self, t=None):
1255
+ if t:
1256
+ return NX.asarray(self.coeffs, t)
1257
+ else:
1258
+ return NX.asarray(self.coeffs)
1259
+
1260
+ def __repr__(self):
1261
+ vals = repr(self.coeffs)
1262
+ vals = vals[6:-1]
1263
+ return "poly1d(%s)" % vals
1264
+
1265
+ def __len__(self):
1266
+ return self.order
1267
+
1268
+ def __str__(self):
1269
+ thestr = "0"
1270
+ var = self.variable
1271
+
1272
+ # Remove leading zeros
1273
+ coeffs = self.coeffs[NX.logical_or.accumulate(self.coeffs != 0)]
1274
+ N = len(coeffs)-1
1275
+
1276
+ def fmt_float(q):
1277
+ s = '%.4g' % q
1278
+ if s.endswith('.0000'):
1279
+ s = s[:-5]
1280
+ return s
1281
+
1282
+ for k, coeff in enumerate(coeffs):
1283
+ if not iscomplex(coeff):
1284
+ coefstr = fmt_float(real(coeff))
1285
+ elif real(coeff) == 0:
1286
+ coefstr = '%sj' % fmt_float(imag(coeff))
1287
+ else:
1288
+ coefstr = '(%s + %sj)' % (fmt_float(real(coeff)),
1289
+ fmt_float(imag(coeff)))
1290
+
1291
+ power = (N-k)
1292
+ if power == 0:
1293
+ if coefstr != '0':
1294
+ newstr = '%s' % (coefstr,)
1295
+ else:
1296
+ if k == 0:
1297
+ newstr = '0'
1298
+ else:
1299
+ newstr = ''
1300
+ elif power == 1:
1301
+ if coefstr == '0':
1302
+ newstr = ''
1303
+ elif coefstr == 'b':
1304
+ newstr = var
1305
+ else:
1306
+ newstr = '%s %s' % (coefstr, var)
1307
+ else:
1308
+ if coefstr == '0':
1309
+ newstr = ''
1310
+ elif coefstr == 'b':
1311
+ newstr = '%s**%d' % (var, power,)
1312
+ else:
1313
+ newstr = '%s %s**%d' % (coefstr, var, power)
1314
+
1315
+ if k > 0:
1316
+ if newstr != '':
1317
+ if newstr.startswith('-'):
1318
+ thestr = "%s - %s" % (thestr, newstr[1:])
1319
+ else:
1320
+ thestr = "%s + %s" % (thestr, newstr)
1321
+ else:
1322
+ thestr = newstr
1323
+ return _raise_power(thestr)
1324
+
1325
+ def __call__(self, val):
1326
+ return polyval(self.coeffs, val)
1327
+
1328
+ def __neg__(self):
1329
+ return poly1d(-self.coeffs)
1330
+
1331
+ def __pos__(self):
1332
+ return self
1333
+
1334
+ def __mul__(self, other):
1335
+ if isscalar(other):
1336
+ return poly1d(self.coeffs * other)
1337
+ else:
1338
+ other = poly1d(other)
1339
+ return poly1d(polymul(self.coeffs, other.coeffs))
1340
+
1341
+ def __rmul__(self, other):
1342
+ if isscalar(other):
1343
+ return poly1d(other * self.coeffs)
1344
+ else:
1345
+ other = poly1d(other)
1346
+ return poly1d(polymul(self.coeffs, other.coeffs))
1347
+
1348
+ def __add__(self, other):
1349
+ other = poly1d(other)
1350
+ return poly1d(polyadd(self.coeffs, other.coeffs))
1351
+
1352
+ def __radd__(self, other):
1353
+ other = poly1d(other)
1354
+ return poly1d(polyadd(self.coeffs, other.coeffs))
1355
+
1356
+ def __pow__(self, val):
1357
+ if not isscalar(val) or int(val) != val or val < 0:
1358
+ raise ValueError("Power to non-negative integers only.")
1359
+ res = [1]
1360
+ for _ in range(val):
1361
+ res = polymul(self.coeffs, res)
1362
+ return poly1d(res)
1363
+
1364
+ def __sub__(self, other):
1365
+ other = poly1d(other)
1366
+ return poly1d(polysub(self.coeffs, other.coeffs))
1367
+
1368
+ def __rsub__(self, other):
1369
+ other = poly1d(other)
1370
+ return poly1d(polysub(other.coeffs, self.coeffs))
1371
+
1372
+ def __div__(self, other):
1373
+ if isscalar(other):
1374
+ return poly1d(self.coeffs/other)
1375
+ else:
1376
+ other = poly1d(other)
1377
+ return polydiv(self, other)
1378
+
1379
+ __truediv__ = __div__
1380
+
1381
+ def __rdiv__(self, other):
1382
+ if isscalar(other):
1383
+ return poly1d(other/self.coeffs)
1384
+ else:
1385
+ other = poly1d(other)
1386
+ return polydiv(other, self)
1387
+
1388
+ __rtruediv__ = __rdiv__
1389
+
1390
+ def __eq__(self, other):
1391
+ if not isinstance(other, poly1d):
1392
+ return NotImplemented
1393
+ if self.coeffs.shape != other.coeffs.shape:
1394
+ return False
1395
+ return (self.coeffs == other.coeffs).all()
1396
+
1397
+ def __ne__(self, other):
1398
+ if not isinstance(other, poly1d):
1399
+ return NotImplemented
1400
+ return not self.__eq__(other)
1401
+
1402
+
1403
+ def __getitem__(self, val):
1404
+ ind = self.order - val
1405
+ if val > self.order:
1406
+ return self.coeffs.dtype.type(0)
1407
+ if val < 0:
1408
+ return self.coeffs.dtype.type(0)
1409
+ return self.coeffs[ind]
1410
+
1411
+ def __setitem__(self, key, val):
1412
+ ind = self.order - key
1413
+ if key < 0:
1414
+ raise ValueError("Does not support negative powers.")
1415
+ if key > self.order:
1416
+ zr = NX.zeros(key-self.order, self.coeffs.dtype)
1417
+ self._coeffs = NX.concatenate((zr, self.coeffs))
1418
+ ind = 0
1419
+ self._coeffs[ind] = val
1420
+ return
1421
+
1422
+ def __iter__(self):
1423
+ return iter(self.coeffs)
1424
+
1425
+ def integ(self, m=1, k=0):
1426
+ """
1427
+ Return an antiderivative (indefinite integral) of this polynomial.
1428
+
1429
+ Refer to `polyint` for full documentation.
1430
+
1431
+ See Also
1432
+ --------
1433
+ polyint : equivalent function
1434
+
1435
+ """
1436
+ return poly1d(polyint(self.coeffs, m=m, k=k))
1437
+
1438
+ def deriv(self, m=1):
1439
+ """
1440
+ Return a derivative of this polynomial.
1441
+
1442
+ Refer to `polyder` for full documentation.
1443
+
1444
+ See Also
1445
+ --------
1446
+ polyder : equivalent function
1447
+
1448
+ """
1449
+ return poly1d(polyder(self.coeffs, m=m))
1450
+
1451
+ # Stuff to do on module import
1452
+
1453
+ warnings.simplefilter('always', RankWarning)
shared/package-files/e8/e80c8e10b956fe80ee78ff62f32be2ae1b7405d24ed22b4dc7df9d7ae31809e0/blob ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ class sha384(object):
4
+ name: str
5
+ block_size: int
6
+ digest_size: int
7
+ digestsize: int
8
+ def __init__(self, init: Optional[str]) -> None: ...
9
+ def copy(self) -> sha384: ...
10
+ def digest(self) -> str: ...
11
+ def hexdigest(self) -> str: ...
12
+ def update(self, arg: str) -> None: ...
13
+
14
+ class sha512(object):
15
+ name: str
16
+ block_size: int
17
+ digest_size: int
18
+ digestsize: int
19
+ def __init__(self, init: Optional[str]) -> None: ...
20
+ def copy(self) -> sha512: ...
21
+ def digest(self) -> str: ...
22
+ def hexdigest(self) -> str: ...
23
+ def update(self, arg: str) -> None: ...
shared/package-files/e8/e80e52ad42441141f16c6b5bb1cc14d8da42cb3fb7ced883946587a51461b09f/blob ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Generator
2
+
3
+ from pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response
4
+
5
+ from pip._internal.exceptions import NetworkConnectionError
6
+
7
+ # The following comments and HTTP headers were originally added by
8
+ # Donald Stufft in git commit 22c562429a61bb77172039e480873fb239dd8c03.
9
+ #
10
+ # We use Accept-Encoding: identity here because requests defaults to
11
+ # accepting compressed responses. This breaks in a variety of ways
12
+ # depending on how the server is configured.
13
+ # - Some servers will notice that the file isn't a compressible file
14
+ # and will leave the file alone and with an empty Content-Encoding
15
+ # - Some servers will notice that the file is already compressed and
16
+ # will leave the file alone, adding a Content-Encoding: gzip header
17
+ # - Some servers won't notice anything at all and will take a file
18
+ # that's already been compressed and compress it again, and set
19
+ # the Content-Encoding: gzip header
20
+ # By setting this to request only the identity encoding we're hoping
21
+ # to eliminate the third case. Hopefully there does not exist a server
22
+ # which when given a file will notice it is already compressed and that
23
+ # you're not asking for a compressed file and will then decompress it
24
+ # before sending because if that's the case I don't think it'll ever be
25
+ # possible to make this work.
26
+ HEADERS: Dict[str, str] = {"Accept-Encoding": "identity"}
27
+
28
+
29
+ def raise_for_status(resp: Response) -> None:
30
+ http_error_msg = ""
31
+ if isinstance(resp.reason, bytes):
32
+ # We attempt to decode utf-8 first because some servers
33
+ # choose to localize their reason strings. If the string
34
+ # isn't utf-8, we fall back to iso-8859-1 for all other
35
+ # encodings.
36
+ try:
37
+ reason = resp.reason.decode("utf-8")
38
+ except UnicodeDecodeError:
39
+ reason = resp.reason.decode("iso-8859-1")
40
+ else:
41
+ reason = resp.reason
42
+
43
+ if 400 <= resp.status_code < 500:
44
+ http_error_msg = (
45
+ f"{resp.status_code} Client Error: {reason} for url: {resp.url}"
46
+ )
47
+
48
+ elif 500 <= resp.status_code < 600:
49
+ http_error_msg = (
50
+ f"{resp.status_code} Server Error: {reason} for url: {resp.url}"
51
+ )
52
+
53
+ if http_error_msg:
54
+ raise NetworkConnectionError(http_error_msg, response=resp)
55
+
56
+
57
+ def response_chunks(
58
+ response: Response, chunk_size: int = CONTENT_CHUNK_SIZE
59
+ ) -> Generator[bytes, None, None]:
60
+ """Given a requests Response, provide the data chunks."""
61
+ try:
62
+ # Special case for urllib3.
63
+ for chunk in response.raw.stream(
64
+ chunk_size,
65
+ # We use decode_content=False here because we don't
66
+ # want urllib3 to mess with the raw bytes we get
67
+ # from the server. If we decompress inside of
68
+ # urllib3 then we cannot verify the checksum
69
+ # because the checksum will be of the compressed
70
+ # file. This breakage will only occur if the
71
+ # server adds a Content-Encoding header, which
72
+ # depends on how the server was configured:
73
+ # - Some servers will notice that the file isn't a
74
+ # compressible file and will leave the file alone
75
+ # and with an empty Content-Encoding
76
+ # - Some servers will notice that the file is
77
+ # already compressed and will leave the file
78
+ # alone and will add a Content-Encoding: gzip
79
+ # header
80
+ # - Some servers won't notice anything at all and
81
+ # will take a file that's already been compressed
82
+ # and compress it again and set the
83
+ # Content-Encoding: gzip header
84
+ #
85
+ # By setting this not to decode automatically we
86
+ # hope to eliminate problems with the second case.
87
+ decode_content=False,
88
+ ):
89
+ yield chunk
90
+ except AttributeError:
91
+ # Standard file-like object.
92
+ while True:
93
+ chunk = response.raw.read(chunk_size)
94
+ if not chunk:
95
+ break
96
+ yield chunk
shared/package-files/e8/e8113bf187bc526547cadf16bf09028cff2d70ccdabf8838fbece436baf51d47/blob ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Implementation for async generators.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ from asyncio import get_running_loop
7
+ from contextlib import asynccontextmanager
8
+ from queue import Empty, Full, Queue
9
+ from typing import Any, AsyncGenerator, Callable, Iterable, TypeVar
10
+
11
+ from .utils import run_in_executor_with_context
12
+
13
+ __all__ = [
14
+ "aclosing",
15
+ "generator_to_async_generator",
16
+ ]
17
+
18
+ _T_Generator = TypeVar("_T_Generator", bound=AsyncGenerator[Any, None])
19
+
20
+
21
+ @asynccontextmanager
22
+ async def aclosing(
23
+ thing: _T_Generator,
24
+ ) -> AsyncGenerator[_T_Generator, None]:
25
+ "Similar to `contextlib.aclosing`, in Python 3.10."
26
+ try:
27
+ yield thing
28
+ finally:
29
+ await thing.aclose()
30
+
31
+
32
+ # By default, choose a buffer size that's a good balance between having enough
33
+ # throughput, but not consuming too much memory. We use this to consume a sync
34
+ # generator of completions as an async generator. If the queue size is very
35
+ # small (like 1), consuming the completions goes really slow (when there are a
36
+ # lot of items). If the queue size would be unlimited or too big, this can
37
+ # cause overconsumption of memory, and cause CPU time spent producing items
38
+ # that are no longer needed (if the consumption of the async generator stops at
39
+ # some point). We need a fixed size in order to get some back pressure from the
40
+ # async consumer to the sync producer. We choose 1000 by default here. If we
41
+ # have around 50k completions, measurements show that 1000 is still
42
+ # significantly faster than a buffer of 100.
43
+ DEFAULT_BUFFER_SIZE: int = 1000
44
+
45
+ _T = TypeVar("_T")
46
+
47
+
48
+ class _Done:
49
+ pass
50
+
51
+
52
+ async def generator_to_async_generator(
53
+ get_iterable: Callable[[], Iterable[_T]],
54
+ buffer_size: int = DEFAULT_BUFFER_SIZE,
55
+ ) -> AsyncGenerator[_T, None]:
56
+ """
57
+ Turn a generator or iterable into an async generator.
58
+
59
+ This works by running the generator in a background thread.
60
+
61
+ :param get_iterable: Function that returns a generator or iterable when
62
+ called.
63
+ :param buffer_size: Size of the queue between the async consumer and the
64
+ synchronous generator that produces items.
65
+ """
66
+ quitting = False
67
+ # NOTE: We are limiting the queue size in order to have back-pressure.
68
+ q: Queue[_T | _Done] = Queue(maxsize=buffer_size)
69
+ loop = get_running_loop()
70
+
71
+ def runner() -> None:
72
+ """
73
+ Consume the generator in background thread.
74
+ When items are received, they'll be pushed to the queue.
75
+ """
76
+ try:
77
+ for item in get_iterable():
78
+ # When this async generator was cancelled (closed), stop this
79
+ # thread.
80
+ if quitting:
81
+ return
82
+
83
+ while True:
84
+ try:
85
+ q.put(item, timeout=1)
86
+ except Full:
87
+ if quitting:
88
+ return
89
+ continue
90
+ else:
91
+ break
92
+
93
+ finally:
94
+ while True:
95
+ try:
96
+ q.put(_Done(), timeout=1)
97
+ except Full:
98
+ if quitting:
99
+ return
100
+ continue
101
+ else:
102
+ break
103
+
104
+ # Start background thread.
105
+ runner_f = run_in_executor_with_context(runner)
106
+
107
+ try:
108
+ while True:
109
+ try:
110
+ item = q.get_nowait()
111
+ except Empty:
112
+ item = await loop.run_in_executor(None, q.get)
113
+ if isinstance(item, _Done):
114
+ break
115
+ else:
116
+ yield item
117
+ finally:
118
+ # When this async generator is closed (GeneratorExit exception, stop
119
+ # the background thread as well. - we don't need that anymore.)
120
+ quitting = True
121
+
122
+ # Wait for the background thread to finish. (should happen right after
123
+ # the last item is yielded).
124
+ await runner_f
shared/package-files/e8/e81297c5189fb59005aca7a41b4186c5822f9a59a38d0527dfc3304846aba8cc/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/special_round_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::special_round(Tensor self, *, int decimals=0) -> Tensor
26
+ inline at::Tensor special_round(const at::Tensor & self, int64_t decimals=0) {
27
+ return at::_ops::special_round::call(self, decimals);
28
+ }
29
+
30
+ // aten::special_round.out(Tensor self, *, int decimals=0, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & special_round_out(at::Tensor & out, const at::Tensor & self, int64_t decimals=0) {
32
+ return at::_ops::special_round_out::call(self, decimals, out);
33
+ }
34
+ // aten::special_round.out(Tensor self, *, int decimals=0, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & special_round_outf(const at::Tensor & self, int64_t decimals, at::Tensor & out) {
36
+ return at::_ops::special_round_out::call(self, decimals, out);
37
+ }
38
+
39
+ }
shared/package-files/e8/e814839fc75010db274ae034f45b0fff7e529ccb702319048545fef84c2045b7/blob ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cache lines from Python source files.
2
+
3
+ This is intended to read lines from modules imported -- hence if a filename
4
+ is not found, it will look down the module search path for a file by
5
+ that name.
6
+ """
7
+
8
+ import functools
9
+ import sys
10
+ import os
11
+ import tokenize
12
+
13
+ __all__ = ["getline", "clearcache", "checkcache", "lazycache"]
14
+
15
+
16
+ # The cache. Maps filenames to either a thunk which will provide source code,
17
+ # or a tuple (size, mtime, lines, fullname) once loaded.
18
+ cache = {}
19
+
20
+
21
+ def clearcache():
22
+ """Clear the cache entirely."""
23
+ cache.clear()
24
+
25
+
26
+ def getline(filename, lineno, module_globals=None):
27
+ """Get a line for a Python source file from the cache.
28
+ Update the cache if it doesn't contain an entry for this file already."""
29
+
30
+ lines = getlines(filename, module_globals)
31
+ if 1 <= lineno <= len(lines):
32
+ return lines[lineno - 1]
33
+ return ''
34
+
35
+
36
+ def getlines(filename, module_globals=None):
37
+ """Get the lines for a Python source file from the cache.
38
+ Update the cache if it doesn't contain an entry for this file already."""
39
+
40
+ if filename in cache:
41
+ entry = cache[filename]
42
+ if len(entry) != 1:
43
+ return cache[filename][2]
44
+
45
+ try:
46
+ return updatecache(filename, module_globals)
47
+ except MemoryError:
48
+ clearcache()
49
+ return []
50
+
51
+
52
+ def checkcache(filename=None):
53
+ """Discard cache entries that are out of date.
54
+ (This is not checked upon each call!)"""
55
+
56
+ if filename is None:
57
+ filenames = list(cache.keys())
58
+ elif filename in cache:
59
+ filenames = [filename]
60
+ else:
61
+ return
62
+
63
+ for filename in filenames:
64
+ entry = cache[filename]
65
+ if len(entry) == 1:
66
+ # lazy cache entry, leave it lazy.
67
+ continue
68
+ size, mtime, lines, fullname = entry
69
+ if mtime is None:
70
+ continue # no-op for files loaded via a __loader__
71
+ try:
72
+ stat = os.stat(fullname)
73
+ except OSError:
74
+ cache.pop(filename, None)
75
+ continue
76
+ if size != stat.st_size or mtime != stat.st_mtime:
77
+ cache.pop(filename, None)
78
+
79
+
80
+ def updatecache(filename, module_globals=None):
81
+ """Update a cache entry and return its list of lines.
82
+ If something's wrong, print a message, discard the cache entry,
83
+ and return an empty list."""
84
+
85
+ if filename in cache:
86
+ if len(cache[filename]) != 1:
87
+ cache.pop(filename, None)
88
+ if not filename or (filename.startswith('<') and filename.endswith('>')):
89
+ return []
90
+
91
+ fullname = filename
92
+ try:
93
+ stat = os.stat(fullname)
94
+ except OSError:
95
+ basename = filename
96
+
97
+ # Realise a lazy loader based lookup if there is one
98
+ # otherwise try to lookup right now.
99
+ if lazycache(filename, module_globals):
100
+ try:
101
+ data = cache[filename][0]()
102
+ except (ImportError, OSError):
103
+ pass
104
+ else:
105
+ if data is None:
106
+ # No luck, the PEP302 loader cannot find the source
107
+ # for this module.
108
+ return []
109
+ cache[filename] = (
110
+ len(data),
111
+ None,
112
+ [line + '\n' for line in data.splitlines()],
113
+ fullname
114
+ )
115
+ return cache[filename][2]
116
+
117
+ # Try looking through the module search path, which is only useful
118
+ # when handling a relative filename.
119
+ if os.path.isabs(filename):
120
+ return []
121
+
122
+ for dirname in sys.path:
123
+ try:
124
+ fullname = os.path.join(dirname, basename)
125
+ except (TypeError, AttributeError):
126
+ # Not sufficiently string-like to do anything useful with.
127
+ continue
128
+ try:
129
+ stat = os.stat(fullname)
130
+ break
131
+ except OSError:
132
+ pass
133
+ else:
134
+ return []
135
+ try:
136
+ with tokenize.open(fullname) as fp:
137
+ lines = fp.readlines()
138
+ except (OSError, UnicodeDecodeError, SyntaxError):
139
+ return []
140
+ if lines and not lines[-1].endswith('\n'):
141
+ lines[-1] += '\n'
142
+ size, mtime = stat.st_size, stat.st_mtime
143
+ cache[filename] = size, mtime, lines, fullname
144
+ return lines
145
+
146
+
147
+ def lazycache(filename, module_globals):
148
+ """Seed the cache for filename with module_globals.
149
+
150
+ The module loader will be asked for the source only when getlines is
151
+ called, not immediately.
152
+
153
+ If there is an entry in the cache already, it is not altered.
154
+
155
+ :return: True if a lazy load is registered in the cache,
156
+ otherwise False. To register such a load a module loader with a
157
+ get_source method must be found, the filename must be a cacheable
158
+ filename, and the filename must not be already cached.
159
+ """
160
+ if filename in cache:
161
+ if len(cache[filename]) == 1:
162
+ return True
163
+ else:
164
+ return False
165
+ if not filename or (filename.startswith('<') and filename.endswith('>')):
166
+ return False
167
+ # Try for a __loader__, if available
168
+ if module_globals and '__name__' in module_globals:
169
+ name = module_globals['__name__']
170
+ if (loader := module_globals.get('__loader__')) is None:
171
+ if spec := module_globals.get('__spec__'):
172
+ try:
173
+ loader = spec.loader
174
+ except AttributeError:
175
+ pass
176
+ get_source = getattr(loader, 'get_source', None)
177
+
178
+ if name and get_source:
179
+ get_lines = functools.partial(get_source, name)
180
+ cache[filename] = (get_lines,)
181
+ return True
182
+ return False
shared/package-files/e8/e815d8c21cd4c9b61586d522884109fdeea0440f80bd51e61a450f5856586ad2/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 empty_quantized {
18
+ using schema = at::Tensor (at::IntArrayRef, const at::Tensor &, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>, c10::optional<at::MemoryFormat>);
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::empty_quantized")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "empty_quantized(int[] size, Tensor qtensor, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor")
24
+ static at::Tensor call(at::IntArrayRef size, const at::Tensor & qtensor, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory, c10::optional<at::MemoryFormat> memory_format);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::IntArrayRef size, const at::Tensor & qtensor, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory, c10::optional<at::MemoryFormat> memory_format);
26
+ };
27
+
28
+ struct TORCH_API empty_quantized_out {
29
+ using schema = at::Tensor & (at::IntArrayRef, const at::Tensor &, c10::optional<at::MemoryFormat>, 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::empty_quantized")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "empty_quantized.out(int[] size, Tensor qtensor, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(at::IntArrayRef size, const at::Tensor & qtensor, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::IntArrayRef size, const at::Tensor & qtensor, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/e8/e8162b49bbcd0e4acaf9156c6f5e9180b76819b6c47df6d577843d171ec30eea/blob ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+
3
+
4
+ def connect(dburi="cache.db"):
5
+ """
6
+ Get database connection.
7
+
8
+ dburi: uri-style sqlite database filename; accepts certain ?= parameters.
9
+ """
10
+ conn = sqlite3.connect(dburi, uri=True)
11
+ conn.row_factory = sqlite3.Row
12
+ conn.execute("PRAGMA journal_mode = WAL")
13
+ conn.execute("PRAGMA synchronous = 1") # less fsync, good for WAL mode
14
+ conn.execute("PRAGMA foreign_keys = ON")
15
+ return conn
shared/package-files/e8/e8164a62a51e74047e8de1dc220b097a5247156ba8ba09a5d9cd4d3629711998/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.sorting import default_sort_key, ordered
2
+ from sympy.testing.pytest import raises
3
+
4
+ from sympy.abc import x
5
+
6
+
7
+ def test_default_sort_key():
8
+ func = lambda x: x
9
+ assert sorted([func, x, func], key=default_sort_key) == [func, func, x]
10
+
11
+ class C:
12
+ def __repr__(self):
13
+ return 'x.y'
14
+ func = C()
15
+ assert sorted([x, func], key=default_sort_key) == [func, x]
16
+
17
+
18
+ def test_ordered():
19
+ # Issue 7210 - this had been failing with python2/3 problems
20
+ assert (list(ordered([{1:3, 2:4, 9:10}, {1:3}])) == \
21
+ [{1: 3}, {1: 3, 2: 4, 9: 10}])
22
+ # warnings should not be raised for identical items
23
+ l = [1, 1]
24
+ assert list(ordered(l, warn=True)) == l
25
+ l = [[1], [2], [1]]
26
+ assert list(ordered(l, warn=True)) == [[1], [1], [2]]
27
+ raises(ValueError, lambda: list(ordered(['a', 'ab'], keys=[lambda x: x[0]],
28
+ default=False, warn=True)))
shared/package-files/e8/e818372669488c876e21f6867cd55cc0d7d2ae01222ceb3370df163f3b1736a1/blob ADDED
@@ -0,0 +1,617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, Dummy, pi
2
+ from sympy.functions.combinatorial.factorials import factorial
3
+ from sympy.functions.elementary.trigonometric import sin, cos
4
+ from sympy.functions.elementary.miscellaneous import sqrt
5
+ from sympy.functions.special.gamma_functions import gamma
6
+ from sympy.polys.orthopolys import (legendre_poly, laguerre_poly,
7
+ hermite_poly, jacobi_poly)
8
+ from sympy.polys.rootoftools import RootOf
9
+
10
+
11
+ def gauss_legendre(n, n_digits):
12
+ r"""
13
+ Computes the Gauss-Legendre quadrature [1]_ points and weights.
14
+
15
+ Explanation
16
+ ===========
17
+
18
+ The Gauss-Legendre quadrature approximates the integral:
19
+
20
+ .. math::
21
+ \int_{-1}^1 f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i)
22
+
23
+ The nodes `x_i` of an order `n` quadrature rule are the roots of `P_n`
24
+ and the weights `w_i` are given by:
25
+
26
+ .. math::
27
+ w_i = \frac{2}{\left(1-x_i^2\right) \left(P'_n(x_i)\right)^2}
28
+
29
+ Parameters
30
+ ==========
31
+
32
+ n :
33
+ The order of quadrature.
34
+ n_digits :
35
+ Number of significant digits of the points and weights to return.
36
+
37
+ Returns
38
+ =======
39
+
40
+ (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
41
+ The points `x_i` and weights `w_i` are returned as ``(x, w)``
42
+ tuple of lists.
43
+
44
+ Examples
45
+ ========
46
+
47
+ >>> from sympy.integrals.quadrature import gauss_legendre
48
+ >>> x, w = gauss_legendre(3, 5)
49
+ >>> x
50
+ [-0.7746, 0, 0.7746]
51
+ >>> w
52
+ [0.55556, 0.88889, 0.55556]
53
+ >>> x, w = gauss_legendre(4, 5)
54
+ >>> x
55
+ [-0.86114, -0.33998, 0.33998, 0.86114]
56
+ >>> w
57
+ [0.34785, 0.65215, 0.65215, 0.34785]
58
+
59
+ See Also
60
+ ========
61
+
62
+ gauss_laguerre, gauss_gen_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
63
+
64
+ References
65
+ ==========
66
+
67
+ .. [1] https://en.wikipedia.org/wiki/Gaussian_quadrature
68
+ .. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/legendre_rule/legendre_rule.html
69
+ """
70
+ x = Dummy("x")
71
+ p = legendre_poly(n, x, polys=True)
72
+ pd = p.diff(x)
73
+ xi = []
74
+ w = []
75
+ for r in p.real_roots():
76
+ if isinstance(r, RootOf):
77
+ r = r.eval_rational(S.One/10**(n_digits+2))
78
+ xi.append(r.n(n_digits))
79
+ w.append((2/((1-r**2) * pd.subs(x, r)**2)).n(n_digits))
80
+ return xi, w
81
+
82
+
83
+ def gauss_laguerre(n, n_digits):
84
+ r"""
85
+ Computes the Gauss-Laguerre quadrature [1]_ points and weights.
86
+
87
+ Explanation
88
+ ===========
89
+
90
+ The Gauss-Laguerre quadrature approximates the integral:
91
+
92
+ .. math::
93
+ \int_0^{\infty} e^{-x} f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i)
94
+
95
+
96
+ The nodes `x_i` of an order `n` quadrature rule are the roots of `L_n`
97
+ and the weights `w_i` are given by:
98
+
99
+ .. math::
100
+ w_i = \frac{x_i}{(n+1)^2 \left(L_{n+1}(x_i)\right)^2}
101
+
102
+ Parameters
103
+ ==========
104
+
105
+ n :
106
+ The order of quadrature.
107
+ n_digits :
108
+ Number of significant digits of the points and weights to return.
109
+
110
+ Returns
111
+ =======
112
+
113
+ (x, w) : The ``x`` and ``w`` are lists of points and weights as Floats.
114
+ The points `x_i` and weights `w_i` are returned as ``(x, w)``
115
+ tuple of lists.
116
+
117
+ Examples
118
+ ========
119
+
120
+ >>> from sympy.integrals.quadrature import gauss_laguerre
121
+ >>> x, w = gauss_laguerre(3, 5)
122
+ >>> x
123
+ [0.41577, 2.2943, 6.2899]
124
+ >>> w
125
+ [0.71109, 0.27852, 0.010389]
126
+ >>> x, w = gauss_laguerre(6, 5)
127
+ >>> x
128
+ [0.22285, 1.1889, 2.9927, 5.7751, 9.8375, 15.983]
129
+ >>> w
130
+ [0.45896, 0.417, 0.11337, 0.010399, 0.00026102, 8.9855e-7]
131
+
132
+ See Also
133
+ ========
134
+
135
+ gauss_legendre, gauss_gen_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
136
+
137
+ References
138
+ ==========
139
+
140
+ .. [1] https://en.wikipedia.org/wiki/Gauss%E2%80%93Laguerre_quadrature
141
+ .. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/laguerre_rule/laguerre_rule.html
142
+ """
143
+ x = Dummy("x")
144
+ p = laguerre_poly(n, x, polys=True)
145
+ p1 = laguerre_poly(n+1, x, polys=True)
146
+ xi = []
147
+ w = []
148
+ for r in p.real_roots():
149
+ if isinstance(r, RootOf):
150
+ r = r.eval_rational(S.One/10**(n_digits+2))
151
+ xi.append(r.n(n_digits))
152
+ w.append((r/((n+1)**2 * p1.subs(x, r)**2)).n(n_digits))
153
+ return xi, w
154
+
155
+
156
+ def gauss_hermite(n, n_digits):
157
+ r"""
158
+ Computes the Gauss-Hermite quadrature [1]_ points and weights.
159
+
160
+ Explanation
161
+ ===========
162
+
163
+ The Gauss-Hermite quadrature approximates the integral:
164
+
165
+ .. math::
166
+ \int_{-\infty}^{\infty} e^{-x^2} f(x)\,dx \approx
167
+ \sum_{i=1}^n w_i f(x_i)
168
+
169
+ The nodes `x_i` of an order `n` quadrature rule are the roots of `H_n`
170
+ and the weights `w_i` are given by:
171
+
172
+ .. math::
173
+ w_i = \frac{2^{n-1} n! \sqrt{\pi}}{n^2 \left(H_{n-1}(x_i)\right)^2}
174
+
175
+ Parameters
176
+ ==========
177
+
178
+ n :
179
+ The order of quadrature.
180
+ n_digits :
181
+ Number of significant digits of the points and weights to return.
182
+
183
+ Returns
184
+ =======
185
+
186
+ (x, w) : The ``x`` and ``w`` are lists of points and weights as Floats.
187
+ The points `x_i` and weights `w_i` are returned as ``(x, w)``
188
+ tuple of lists.
189
+
190
+ Examples
191
+ ========
192
+
193
+ >>> from sympy.integrals.quadrature import gauss_hermite
194
+ >>> x, w = gauss_hermite(3, 5)
195
+ >>> x
196
+ [-1.2247, 0, 1.2247]
197
+ >>> w
198
+ [0.29541, 1.1816, 0.29541]
199
+
200
+ >>> x, w = gauss_hermite(6, 5)
201
+ >>> x
202
+ [-2.3506, -1.3358, -0.43608, 0.43608, 1.3358, 2.3506]
203
+ >>> w
204
+ [0.00453, 0.15707, 0.72463, 0.72463, 0.15707, 0.00453]
205
+
206
+ See Also
207
+ ========
208
+
209
+ gauss_legendre, gauss_laguerre, gauss_gen_laguerre, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
210
+
211
+ References
212
+ ==========
213
+
214
+ .. [1] https://en.wikipedia.org/wiki/Gauss-Hermite_Quadrature
215
+ .. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/hermite_rule/hermite_rule.html
216
+ .. [3] https://people.sc.fsu.edu/~jburkardt/cpp_src/gen_hermite_rule/gen_hermite_rule.html
217
+ """
218
+ x = Dummy("x")
219
+ p = hermite_poly(n, x, polys=True)
220
+ p1 = hermite_poly(n-1, x, polys=True)
221
+ xi = []
222
+ w = []
223
+ for r in p.real_roots():
224
+ if isinstance(r, RootOf):
225
+ r = r.eval_rational(S.One/10**(n_digits+2))
226
+ xi.append(r.n(n_digits))
227
+ w.append(((2**(n-1) * factorial(n) * sqrt(pi)) /
228
+ (n**2 * p1.subs(x, r)**2)).n(n_digits))
229
+ return xi, w
230
+
231
+
232
+ def gauss_gen_laguerre(n, alpha, n_digits):
233
+ r"""
234
+ Computes the generalized Gauss-Laguerre quadrature [1]_ points and weights.
235
+
236
+ Explanation
237
+ ===========
238
+
239
+ The generalized Gauss-Laguerre quadrature approximates the integral:
240
+
241
+ .. math::
242
+ \int_{0}^\infty x^{\alpha} e^{-x} f(x)\,dx \approx
243
+ \sum_{i=1}^n w_i f(x_i)
244
+
245
+ The nodes `x_i` of an order `n` quadrature rule are the roots of
246
+ `L^{\alpha}_n` and the weights `w_i` are given by:
247
+
248
+ .. math::
249
+ w_i = \frac{\Gamma(\alpha+n)}
250
+ {n \Gamma(n) L^{\alpha}_{n-1}(x_i) L^{\alpha+1}_{n-1}(x_i)}
251
+
252
+ Parameters
253
+ ==========
254
+
255
+ n :
256
+ The order of quadrature.
257
+
258
+ alpha :
259
+ The exponent of the singularity, `\alpha > -1`.
260
+
261
+ n_digits :
262
+ Number of significant digits of the points and weights to return.
263
+
264
+ Returns
265
+ =======
266
+
267
+ (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
268
+ The points `x_i` and weights `w_i` are returned as ``(x, w)``
269
+ tuple of lists.
270
+
271
+ Examples
272
+ ========
273
+
274
+ >>> from sympy import S
275
+ >>> from sympy.integrals.quadrature import gauss_gen_laguerre
276
+ >>> x, w = gauss_gen_laguerre(3, -S.Half, 5)
277
+ >>> x
278
+ [0.19016, 1.7845, 5.5253]
279
+ >>> w
280
+ [1.4493, 0.31413, 0.00906]
281
+
282
+ >>> x, w = gauss_gen_laguerre(4, 3*S.Half, 5)
283
+ >>> x
284
+ [0.97851, 2.9904, 6.3193, 11.712]
285
+ >>> w
286
+ [0.53087, 0.67721, 0.11895, 0.0023152]
287
+
288
+ See Also
289
+ ========
290
+
291
+ gauss_legendre, gauss_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
292
+
293
+ References
294
+ ==========
295
+
296
+ .. [1] https://en.wikipedia.org/wiki/Gauss%E2%80%93Laguerre_quadrature
297
+ .. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/gen_laguerre_rule/gen_laguerre_rule.html
298
+ """
299
+ x = Dummy("x")
300
+ p = laguerre_poly(n, x, alpha=alpha, polys=True)
301
+ p1 = laguerre_poly(n-1, x, alpha=alpha, polys=True)
302
+ p2 = laguerre_poly(n-1, x, alpha=alpha+1, polys=True)
303
+ xi = []
304
+ w = []
305
+ for r in p.real_roots():
306
+ if isinstance(r, RootOf):
307
+ r = r.eval_rational(S.One/10**(n_digits+2))
308
+ xi.append(r.n(n_digits))
309
+ w.append((gamma(alpha+n) /
310
+ (n*gamma(n)*p1.subs(x, r)*p2.subs(x, r))).n(n_digits))
311
+ return xi, w
312
+
313
+
314
+ def gauss_chebyshev_t(n, n_digits):
315
+ r"""
316
+ Computes the Gauss-Chebyshev quadrature [1]_ points and weights of
317
+ the first kind.
318
+
319
+ Explanation
320
+ ===========
321
+
322
+ The Gauss-Chebyshev quadrature of the first kind approximates the integral:
323
+
324
+ .. math::
325
+ \int_{-1}^{1} \frac{1}{\sqrt{1-x^2}} f(x)\,dx \approx
326
+ \sum_{i=1}^n w_i f(x_i)
327
+
328
+ The nodes `x_i` of an order `n` quadrature rule are the roots of `T_n`
329
+ and the weights `w_i` are given by:
330
+
331
+ .. math::
332
+ w_i = \frac{\pi}{n}
333
+
334
+ Parameters
335
+ ==========
336
+
337
+ n :
338
+ The order of quadrature.
339
+
340
+ n_digits :
341
+ Number of significant digits of the points and weights to return.
342
+
343
+ Returns
344
+ =======
345
+
346
+ (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
347
+ The points `x_i` and weights `w_i` are returned as ``(x, w)``
348
+ tuple of lists.
349
+
350
+ Examples
351
+ ========
352
+
353
+ >>> from sympy.integrals.quadrature import gauss_chebyshev_t
354
+ >>> x, w = gauss_chebyshev_t(3, 5)
355
+ >>> x
356
+ [0.86602, 0, -0.86602]
357
+ >>> w
358
+ [1.0472, 1.0472, 1.0472]
359
+
360
+ >>> x, w = gauss_chebyshev_t(6, 5)
361
+ >>> x
362
+ [0.96593, 0.70711, 0.25882, -0.25882, -0.70711, -0.96593]
363
+ >>> w
364
+ [0.5236, 0.5236, 0.5236, 0.5236, 0.5236, 0.5236]
365
+
366
+ See Also
367
+ ========
368
+
369
+ gauss_legendre, gauss_laguerre, gauss_hermite, gauss_gen_laguerre, gauss_chebyshev_u, gauss_jacobi, gauss_lobatto
370
+
371
+ References
372
+ ==========
373
+
374
+ .. [1] https://en.wikipedia.org/wiki/Chebyshev%E2%80%93Gauss_quadrature
375
+ .. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/chebyshev1_rule/chebyshev1_rule.html
376
+ """
377
+ xi = []
378
+ w = []
379
+ for i in range(1, n+1):
380
+ xi.append((cos((2*i-S.One)/(2*n)*S.Pi)).n(n_digits))
381
+ w.append((S.Pi/n).n(n_digits))
382
+ return xi, w
383
+
384
+
385
+ def gauss_chebyshev_u(n, n_digits):
386
+ r"""
387
+ Computes the Gauss-Chebyshev quadrature [1]_ points and weights of
388
+ the second kind.
389
+
390
+ Explanation
391
+ ===========
392
+
393
+ The Gauss-Chebyshev quadrature of the second kind approximates the
394
+ integral:
395
+
396
+ .. math::
397
+ \int_{-1}^{1} \sqrt{1-x^2} f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i)
398
+
399
+ The nodes `x_i` of an order `n` quadrature rule are the roots of `U_n`
400
+ and the weights `w_i` are given by:
401
+
402
+ .. math::
403
+ w_i = \frac{\pi}{n+1} \sin^2 \left(\frac{i}{n+1}\pi\right)
404
+
405
+ Parameters
406
+ ==========
407
+
408
+ n : the order of quadrature
409
+
410
+ n_digits : number of significant digits of the points and weights to return
411
+
412
+ Returns
413
+ =======
414
+
415
+ (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
416
+ The points `x_i` and weights `w_i` are returned as ``(x, w)``
417
+ tuple of lists.
418
+
419
+ Examples
420
+ ========
421
+
422
+ >>> from sympy.integrals.quadrature import gauss_chebyshev_u
423
+ >>> x, w = gauss_chebyshev_u(3, 5)
424
+ >>> x
425
+ [0.70711, 0, -0.70711]
426
+ >>> w
427
+ [0.3927, 0.7854, 0.3927]
428
+
429
+ >>> x, w = gauss_chebyshev_u(6, 5)
430
+ >>> x
431
+ [0.90097, 0.62349, 0.22252, -0.22252, -0.62349, -0.90097]
432
+ >>> w
433
+ [0.084489, 0.27433, 0.42658, 0.42658, 0.27433, 0.084489]
434
+
435
+ See Also
436
+ ========
437
+
438
+ gauss_legendre, gauss_laguerre, gauss_hermite, gauss_gen_laguerre, gauss_chebyshev_t, gauss_jacobi, gauss_lobatto
439
+
440
+ References
441
+ ==========
442
+
443
+ .. [1] https://en.wikipedia.org/wiki/Chebyshev%E2%80%93Gauss_quadrature
444
+ .. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/chebyshev2_rule/chebyshev2_rule.html
445
+ """
446
+ xi = []
447
+ w = []
448
+ for i in range(1, n+1):
449
+ xi.append((cos(i/(n+S.One)*S.Pi)).n(n_digits))
450
+ w.append((S.Pi/(n+S.One)*sin(i*S.Pi/(n+S.One))**2).n(n_digits))
451
+ return xi, w
452
+
453
+
454
+ def gauss_jacobi(n, alpha, beta, n_digits):
455
+ r"""
456
+ Computes the Gauss-Jacobi quadrature [1]_ points and weights.
457
+
458
+ Explanation
459
+ ===========
460
+
461
+ The Gauss-Jacobi quadrature of the first kind approximates the integral:
462
+
463
+ .. math::
464
+ \int_{-1}^1 (1-x)^\alpha (1+x)^\beta f(x)\,dx \approx
465
+ \sum_{i=1}^n w_i f(x_i)
466
+
467
+ The nodes `x_i` of an order `n` quadrature rule are the roots of
468
+ `P^{(\alpha,\beta)}_n` and the weights `w_i` are given by:
469
+
470
+ .. math::
471
+ w_i = -\frac{2n+\alpha+\beta+2}{n+\alpha+\beta+1}
472
+ \frac{\Gamma(n+\alpha+1)\Gamma(n+\beta+1)}
473
+ {\Gamma(n+\alpha+\beta+1)(n+1)!}
474
+ \frac{2^{\alpha+\beta}}{P'_n(x_i)
475
+ P^{(\alpha,\beta)}_{n+1}(x_i)}
476
+
477
+ Parameters
478
+ ==========
479
+
480
+ n : the order of quadrature
481
+
482
+ alpha : the first parameter of the Jacobi Polynomial, `\alpha > -1`
483
+
484
+ beta : the second parameter of the Jacobi Polynomial, `\beta > -1`
485
+
486
+ n_digits : number of significant digits of the points and weights to return
487
+
488
+ Returns
489
+ =======
490
+
491
+ (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
492
+ The points `x_i` and weights `w_i` are returned as ``(x, w)``
493
+ tuple of lists.
494
+
495
+ Examples
496
+ ========
497
+
498
+ >>> from sympy import S
499
+ >>> from sympy.integrals.quadrature import gauss_jacobi
500
+ >>> x, w = gauss_jacobi(3, S.Half, -S.Half, 5)
501
+ >>> x
502
+ [-0.90097, -0.22252, 0.62349]
503
+ >>> w
504
+ [1.7063, 1.0973, 0.33795]
505
+
506
+ >>> x, w = gauss_jacobi(6, 1, 1, 5)
507
+ >>> x
508
+ [-0.87174, -0.5917, -0.2093, 0.2093, 0.5917, 0.87174]
509
+ >>> w
510
+ [0.050584, 0.22169, 0.39439, 0.39439, 0.22169, 0.050584]
511
+
512
+ See Also
513
+ ========
514
+
515
+ gauss_legendre, gauss_laguerre, gauss_hermite, gauss_gen_laguerre,
516
+ gauss_chebyshev_t, gauss_chebyshev_u, gauss_lobatto
517
+
518
+ References
519
+ ==========
520
+
521
+ .. [1] https://en.wikipedia.org/wiki/Gauss%E2%80%93Jacobi_quadrature
522
+ .. [2] https://people.sc.fsu.edu/~jburkardt/cpp_src/jacobi_rule/jacobi_rule.html
523
+ .. [3] https://people.sc.fsu.edu/~jburkardt/cpp_src/gegenbauer_rule/gegenbauer_rule.html
524
+ """
525
+ x = Dummy("x")
526
+ p = jacobi_poly(n, alpha, beta, x, polys=True)
527
+ pd = p.diff(x)
528
+ pn = jacobi_poly(n+1, alpha, beta, x, polys=True)
529
+ xi = []
530
+ w = []
531
+ for r in p.real_roots():
532
+ if isinstance(r, RootOf):
533
+ r = r.eval_rational(S.One/10**(n_digits+2))
534
+ xi.append(r.n(n_digits))
535
+ w.append((
536
+ - (2*n+alpha+beta+2) / (n+alpha+beta+S.One) *
537
+ (gamma(n+alpha+1)*gamma(n+beta+1)) /
538
+ (gamma(n+alpha+beta+S.One)*gamma(n+2)) *
539
+ 2**(alpha+beta) / (pd.subs(x, r) * pn.subs(x, r))).n(n_digits))
540
+ return xi, w
541
+
542
+
543
+ def gauss_lobatto(n, n_digits):
544
+ r"""
545
+ Computes the Gauss-Lobatto quadrature [1]_ points and weights.
546
+
547
+ Explanation
548
+ ===========
549
+
550
+ The Gauss-Lobatto quadrature approximates the integral:
551
+
552
+ .. math::
553
+ \int_{-1}^1 f(x)\,dx \approx \sum_{i=1}^n w_i f(x_i)
554
+
555
+ The nodes `x_i` of an order `n` quadrature rule are the roots of `P'_(n-1)`
556
+ and the weights `w_i` are given by:
557
+
558
+ .. math::
559
+ &w_i = \frac{2}{n(n-1) \left[P_{n-1}(x_i)\right]^2},\quad x\neq\pm 1\\
560
+ &w_i = \frac{2}{n(n-1)},\quad x=\pm 1
561
+
562
+ Parameters
563
+ ==========
564
+
565
+ n : the order of quadrature
566
+
567
+ n_digits : number of significant digits of the points and weights to return
568
+
569
+ Returns
570
+ =======
571
+
572
+ (x, w) : the ``x`` and ``w`` are lists of points and weights as Floats.
573
+ The points `x_i` and weights `w_i` are returned as ``(x, w)``
574
+ tuple of lists.
575
+
576
+ Examples
577
+ ========
578
+
579
+ >>> from sympy.integrals.quadrature import gauss_lobatto
580
+ >>> x, w = gauss_lobatto(3, 5)
581
+ >>> x
582
+ [-1, 0, 1]
583
+ >>> w
584
+ [0.33333, 1.3333, 0.33333]
585
+ >>> x, w = gauss_lobatto(4, 5)
586
+ >>> x
587
+ [-1, -0.44721, 0.44721, 1]
588
+ >>> w
589
+ [0.16667, 0.83333, 0.83333, 0.16667]
590
+
591
+ See Also
592
+ ========
593
+
594
+ gauss_legendre,gauss_laguerre, gauss_gen_laguerre, gauss_hermite, gauss_chebyshev_t, gauss_chebyshev_u, gauss_jacobi
595
+
596
+ References
597
+ ==========
598
+
599
+ .. [1] https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Lobatto_rules
600
+ .. [2] https://web.archive.org/web/20200118141346/http://people.math.sfu.ca/~cbm/aands/page_888.htm
601
+ """
602
+ x = Dummy("x")
603
+ p = legendre_poly(n-1, x, polys=True)
604
+ pd = p.diff(x)
605
+ xi = []
606
+ w = []
607
+ for r in pd.real_roots():
608
+ if isinstance(r, RootOf):
609
+ r = r.eval_rational(S.One/10**(n_digits+2))
610
+ xi.append(r.n(n_digits))
611
+ w.append((2/(n*(n-1) * p.subs(x, r)**2)).n(n_digits))
612
+
613
+ xi.insert(0, -1)
614
+ xi.append(1)
615
+ w.insert(0, (S(2)/(n*(n-1))).n(n_digits))
616
+ w.append((S(2)/(n*(n-1))).n(n_digits))
617
+ return xi, w
shared/package-files/e8/e81e7bc654e45d69f9297f6e309cc3a54eb0d75395c8b36cb9fc23d697110e5e/blob ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <limits>
4
+ #include <c10/util/Exception.h>
5
+
6
+ namespace at::cuda::detail {
7
+
8
+ // CUDA: grid stride looping
9
+ //
10
+ // int64_t _i_n_d_e_x specifically prevents overflow in the loop increment.
11
+ // If input.numel() < INT_MAX, _i_n_d_e_x < INT_MAX, except after the final
12
+ // iteration of the loop where _i_n_d_e_x += blockDim.x * gridDim.x can be
13
+ // greater than INT_MAX. But in that case _i_n_d_e_x >= n, so there are no
14
+ // further iterations and the overflowed value in i=_i_n_d_e_x is not used.
15
+ #define CUDA_KERNEL_LOOP_TYPE(i, n, index_type) \
16
+ int64_t _i_n_d_e_x = blockIdx.x * blockDim.x + threadIdx.x; \
17
+ for (index_type i=_i_n_d_e_x; _i_n_d_e_x < (n); _i_n_d_e_x+=blockDim.x * gridDim.x, i=_i_n_d_e_x)
18
+
19
+ #define CUDA_KERNEL_LOOP(i, n) CUDA_KERNEL_LOOP_TYPE(i, n, int)
20
+
21
+
22
+ // Use 1024 threads per block, which requires cuda sm_2x or above
23
+ constexpr int CUDA_NUM_THREADS = 1024;
24
+
25
+ // CUDA: number of blocks for threads.
26
+ inline int GET_BLOCKS(const int64_t N, const int64_t max_threads_per_block=CUDA_NUM_THREADS) {
27
+ TORCH_INTERNAL_ASSERT(N > 0, "CUDA kernel launch blocks must be positive, but got N=", N);
28
+ constexpr int64_t max_int = std::numeric_limits<int>::max();
29
+
30
+ // Round up division for positive number that cannot cause integer overflow
31
+ auto block_num = (N - 1) / max_threads_per_block + 1;
32
+ TORCH_INTERNAL_ASSERT(block_num <= max_int, "Can't schedule too many blocks on CUDA device");
33
+
34
+ return static_cast<int>(block_num);
35
+ }
36
+
37
+ } // namespace at::cuda::detail
shared/package-files/e8/e81edfb3d9e2b8dd90632c6354d5f7dd62c126f1764896510a7e922274c8cf48/blob ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from pandas import (
4
+ Categorical,
5
+ Series,
6
+ )
7
+
8
+
9
+ def test_nunique():
10
+ # basics.rst doc example
11
+ series = Series(np.random.default_rng(2).standard_normal(500))
12
+ series[20:500] = np.nan
13
+ series[10:20] = 5000
14
+ result = series.nunique()
15
+ assert result == 11
16
+
17
+
18
+ def test_nunique_categorical():
19
+ # GH#18051
20
+ ser = Series(Categorical([]))
21
+ assert ser.nunique() == 0
22
+
23
+ ser = Series(Categorical([np.nan]))
24
+ assert ser.nunique() == 0
shared/package-files/e8/e820f64f81dea6f4b2c3f19132b088ef33c6455101680b3667eef47d4e42d549/blob ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/all_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::all.dim(Tensor self, int dim, bool keepdim=False) -> Tensor
26
+ inline at::Tensor all(const at::Tensor & self, int64_t dim, bool keepdim=false) {
27
+ return at::_ops::all_dim::call(self, dim, keepdim);
28
+ }
29
+
30
+ // aten::all.dims(Tensor self, int[]? dim=None, bool keepdim=False) -> Tensor
31
+ inline at::Tensor all(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false) {
32
+ return at::_ops::all_dims::call(self, dim, keepdim);
33
+ }
34
+
35
+ // aten::all.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
36
+ inline at::Tensor & all_out(at::Tensor & out, const at::Tensor & self, int64_t dim, bool keepdim=false) {
37
+ return at::_ops::all_out::call(self, dim, keepdim, out);
38
+ }
39
+ // aten::all.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
40
+ inline at::Tensor & all_outf(const at::Tensor & self, int64_t dim, bool keepdim, at::Tensor & out) {
41
+ return at::_ops::all_out::call(self, dim, keepdim, out);
42
+ }
43
+
44
+ // aten::all.dims_out(Tensor self, int[]? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
45
+ inline at::Tensor & all_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false) {
46
+ return at::_ops::all_dims_out::call(self, dim, keepdim, out);
47
+ }
48
+ // aten::all.dims_out(Tensor self, int[]? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
49
+ inline at::Tensor & all_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, at::Tensor & out) {
50
+ return at::_ops::all_dims_out::call(self, dim, keepdim, out);
51
+ }
52
+
53
+ // aten::all.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor
54
+ inline at::Tensor all(const at::Tensor & self, at::Dimname dim, bool keepdim=false) {
55
+ return at::_ops::all_dimname::call(self, dim, keepdim);
56
+ }
57
+
58
+ // aten::all.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
59
+ inline at::Tensor & all_out(at::Tensor & out, const at::Tensor & self, at::Dimname dim, bool keepdim=false) {
60
+ return at::_ops::all_dimname_out::call(self, dim, keepdim, out);
61
+ }
62
+ // aten::all.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)
63
+ inline at::Tensor & all_outf(const at::Tensor & self, at::Dimname dim, bool keepdim, at::Tensor & out) {
64
+ return at::_ops::all_dimname_out::call(self, dim, keepdim, out);
65
+ }
66
+
67
+ // aten::all(Tensor self) -> Tensor
68
+ inline at::Tensor all(const at::Tensor & self) {
69
+ return at::_ops::all::call(self);
70
+ }
71
+
72
+ // aten::all.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
73
+ inline at::Tensor & all_out(at::Tensor & out, const at::Tensor & self) {
74
+ return at::_ops::all_all_out::call(self, out);
75
+ }
76
+ // aten::all.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
77
+ inline at::Tensor & all_outf(const at::Tensor & self, at::Tensor & out) {
78
+ return at::_ops::all_all_out::call(self, out);
79
+ }
80
+
81
+ }
shared/package-files/e8/e821fbd5ae150dc9fdb616ae5a213504904e5416febcde421739f3fe52769c0c/blob ADDED
@@ -0,0 +1,1965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2003-2005 Peter J. Verveer
2
+ #
3
+ # Redistribution and use in source and binary forms, with or without
4
+ # modification, are permitted provided that the following conditions
5
+ # are met:
6
+ #
7
+ # 1. Redistributions of source code must retain the above copyright
8
+ # notice, this list of conditions and the following disclaimer.
9
+ #
10
+ # 2. Redistributions in binary form must reproduce the above
11
+ # copyright notice, this list of conditions and the following
12
+ # disclaimer in the documentation and/or other materials provided
13
+ # with the distribution.
14
+ #
15
+ # 3. The name of the author may not be used to endorse or promote
16
+ # products derived from this software without specific prior
17
+ # written permission.
18
+ #
19
+ # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
20
+ # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22
+ # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
23
+ # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25
+ # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27
+ # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ from collections.abc import Iterable
32
+ import numbers
33
+ import warnings
34
+ import numpy as np
35
+ import operator
36
+
37
+ from scipy._lib._util import normalize_axis_index
38
+ from . import _ni_support
39
+ from . import _nd_image
40
+ from . import _ni_docstrings
41
+ from . import _rank_filter_1d
42
+
43
+ __all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter',
44
+ 'prewitt', 'sobel', 'generic_laplace', 'laplace',
45
+ 'gaussian_laplace', 'generic_gradient_magnitude',
46
+ 'gaussian_gradient_magnitude', 'correlate', 'convolve',
47
+ 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
48
+ 'maximum_filter1d', 'minimum_filter', 'maximum_filter',
49
+ 'rank_filter', 'median_filter', 'percentile_filter',
50
+ 'generic_filter1d', 'generic_filter']
51
+
52
+
53
+ def _invalid_origin(origin, lenw):
54
+ return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2)
55
+
56
+
57
+ def _complex_via_real_components(func, input, weights, output, cval, **kwargs):
58
+ """Complex convolution via a linear combination of real convolutions."""
59
+ complex_input = input.dtype.kind == 'c'
60
+ complex_weights = weights.dtype.kind == 'c'
61
+ if complex_input and complex_weights:
62
+ # real component of the output
63
+ func(input.real, weights.real, output=output.real,
64
+ cval=np.real(cval), **kwargs)
65
+ output.real -= func(input.imag, weights.imag, output=None,
66
+ cval=np.imag(cval), **kwargs)
67
+ # imaginary component of the output
68
+ func(input.real, weights.imag, output=output.imag,
69
+ cval=np.real(cval), **kwargs)
70
+ output.imag += func(input.imag, weights.real, output=None,
71
+ cval=np.imag(cval), **kwargs)
72
+ elif complex_input:
73
+ func(input.real, weights, output=output.real, cval=np.real(cval),
74
+ **kwargs)
75
+ func(input.imag, weights, output=output.imag, cval=np.imag(cval),
76
+ **kwargs)
77
+ else:
78
+ if np.iscomplexobj(cval):
79
+ raise ValueError("Cannot provide a complex-valued cval when the "
80
+ "input is real.")
81
+ func(input, weights.real, output=output.real, cval=cval, **kwargs)
82
+ func(input, weights.imag, output=output.imag, cval=cval, **kwargs)
83
+ return output
84
+
85
+
86
+ def _expand_origin(ndim_image, axes, origin):
87
+ num_axes = len(axes)
88
+ origins = _ni_support._normalize_sequence(origin, num_axes)
89
+ if num_axes < ndim_image:
90
+ # set origin = 0 for any axes not being filtered
91
+ origins_temp = [0,] * ndim_image
92
+ for o, ax in zip(origins, axes):
93
+ origins_temp[ax] = o
94
+ origins = origins_temp
95
+ return origins
96
+
97
+
98
+ def _expand_footprint(ndim_image, axes, footprint,
99
+ footprint_name="footprint"):
100
+ num_axes = len(axes)
101
+ if num_axes < ndim_image:
102
+ if footprint.ndim != num_axes:
103
+ raise RuntimeError(f"{footprint_name}.ndim ({footprint.ndim}) "
104
+ f"must match len(axes) ({num_axes})")
105
+
106
+ footprint = np.expand_dims(
107
+ footprint,
108
+ tuple(ax for ax in range(ndim_image) if ax not in axes)
109
+ )
110
+ return footprint
111
+
112
+
113
+ def _expand_mode(ndim_image, axes, mode):
114
+ num_axes = len(axes)
115
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
116
+ # set mode = 'constant' for any axes not being filtered
117
+ modes = _ni_support._normalize_sequence(mode, num_axes)
118
+ modes_temp = ['constant'] * ndim_image
119
+ for m, ax in zip(modes, axes):
120
+ modes_temp[ax] = m
121
+ mode = modes_temp
122
+ return mode
123
+
124
+
125
+ @_ni_docstrings.docfiller
126
+ def correlate1d(input, weights, axis=-1, output=None, mode="reflect",
127
+ cval=0.0, origin=0):
128
+ """Calculate a 1-D correlation along the given axis.
129
+
130
+ The lines of the array along the given axis are correlated with the
131
+ given weights.
132
+
133
+ Parameters
134
+ ----------
135
+ %(input)s
136
+ weights : array
137
+ 1-D sequence of numbers.
138
+ %(axis)s
139
+ %(output)s
140
+ %(mode_reflect)s
141
+ %(cval)s
142
+ %(origin)s
143
+
144
+ Returns
145
+ -------
146
+ result : ndarray
147
+ Correlation result. Has the same shape as `input`.
148
+
149
+ Examples
150
+ --------
151
+ >>> from scipy.ndimage import correlate1d
152
+ >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
153
+ array([ 8, 26, 8, 12, 7, 28, 36, 9])
154
+ """
155
+ input = np.asarray(input)
156
+ weights = np.asarray(weights)
157
+ complex_input = input.dtype.kind == 'c'
158
+ complex_weights = weights.dtype.kind == 'c'
159
+ if complex_input or complex_weights:
160
+ if complex_weights:
161
+ weights = weights.conj()
162
+ weights = weights.astype(np.complex128, copy=False)
163
+ kwargs = dict(axis=axis, mode=mode, origin=origin)
164
+ output = _ni_support._get_output(output, input, complex_output=True)
165
+ return _complex_via_real_components(correlate1d, input, weights,
166
+ output, cval, **kwargs)
167
+
168
+ output = _ni_support._get_output(output, input)
169
+ weights = np.asarray(weights, dtype=np.float64)
170
+ if weights.ndim != 1 or weights.shape[0] < 1:
171
+ raise RuntimeError('no filter weights given')
172
+ if not weights.flags.contiguous:
173
+ weights = weights.copy()
174
+ axis = normalize_axis_index(axis, input.ndim)
175
+ if _invalid_origin(origin, len(weights)):
176
+ raise ValueError('Invalid origin; origin must satisfy '
177
+ '-(len(weights) // 2) <= origin <= '
178
+ '(len(weights)-1) // 2')
179
+ mode = _ni_support._extend_mode_to_code(mode)
180
+ _nd_image.correlate1d(input, weights, axis, output, mode, cval,
181
+ origin)
182
+ return output
183
+
184
+
185
+ @_ni_docstrings.docfiller
186
+ def convolve1d(input, weights, axis=-1, output=None, mode="reflect",
187
+ cval=0.0, origin=0):
188
+ """Calculate a 1-D convolution along the given axis.
189
+
190
+ The lines of the array along the given axis are convolved with the
191
+ given weights.
192
+
193
+ Parameters
194
+ ----------
195
+ %(input)s
196
+ weights : ndarray
197
+ 1-D sequence of numbers.
198
+ %(axis)s
199
+ %(output)s
200
+ %(mode_reflect)s
201
+ %(cval)s
202
+ %(origin)s
203
+
204
+ Returns
205
+ -------
206
+ convolve1d : ndarray
207
+ Convolved array with same shape as input
208
+
209
+ Examples
210
+ --------
211
+ >>> from scipy.ndimage import convolve1d
212
+ >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
213
+ array([14, 24, 4, 13, 12, 36, 27, 0])
214
+ """
215
+ weights = np.asarray(weights)
216
+ weights = weights[::-1]
217
+ origin = -origin
218
+ if not weights.shape[0] & 1:
219
+ origin -= 1
220
+ if weights.dtype.kind == 'c':
221
+ # pre-conjugate here to counteract the conjugation in correlate1d
222
+ weights = weights.conj()
223
+ return correlate1d(input, weights, axis, output, mode, cval, origin)
224
+
225
+
226
+ def _gaussian_kernel1d(sigma, order, radius):
227
+ """
228
+ Computes a 1-D Gaussian convolution kernel.
229
+ """
230
+ if order < 0:
231
+ raise ValueError('order must be non-negative')
232
+ exponent_range = np.arange(order + 1)
233
+ sigma2 = sigma * sigma
234
+ x = np.arange(-radius, radius+1)
235
+ phi_x = np.exp(-0.5 / sigma2 * x ** 2)
236
+ phi_x = phi_x / phi_x.sum()
237
+
238
+ if order == 0:
239
+ return phi_x
240
+ else:
241
+ # f(x) = q(x) * phi(x) = q(x) * exp(p(x))
242
+ # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x)
243
+ # p'(x) = -1 / sigma ** 2
244
+ # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the
245
+ # coefficients of q(x)
246
+ q = np.zeros(order + 1)
247
+ q[0] = 1
248
+ D = np.diag(exponent_range[1:], 1) # D @ q(x) = q'(x)
249
+ P = np.diag(np.ones(order)/-sigma2, -1) # P @ q(x) = q(x) * p'(x)
250
+ Q_deriv = D + P
251
+ for _ in range(order):
252
+ q = Q_deriv.dot(q)
253
+ q = (x[:, None] ** exponent_range).dot(q)
254
+ return q * phi_x
255
+
256
+
257
+ @_ni_docstrings.docfiller
258
+ def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None,
259
+ mode="reflect", cval=0.0, truncate=4.0, *, radius=None):
260
+ """1-D Gaussian filter.
261
+
262
+ Parameters
263
+ ----------
264
+ %(input)s
265
+ sigma : scalar
266
+ standard deviation for Gaussian kernel
267
+ %(axis)s
268
+ order : int, optional
269
+ An order of 0 corresponds to convolution with a Gaussian
270
+ kernel. A positive order corresponds to convolution with
271
+ that derivative of a Gaussian.
272
+ %(output)s
273
+ %(mode_reflect)s
274
+ %(cval)s
275
+ truncate : float, optional
276
+ Truncate the filter at this many standard deviations.
277
+ Default is 4.0.
278
+ radius : None or int, optional
279
+ Radius of the Gaussian kernel. If specified, the size of
280
+ the kernel will be ``2*radius + 1``, and `truncate` is ignored.
281
+ Default is None.
282
+
283
+ Returns
284
+ -------
285
+ gaussian_filter1d : ndarray
286
+
287
+ Notes
288
+ -----
289
+ The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
290
+ `radius` is None, a default ``radius = round(truncate * sigma)`` will be
291
+ used.
292
+
293
+ Examples
294
+ --------
295
+ >>> from scipy.ndimage import gaussian_filter1d
296
+ >>> import numpy as np
297
+ >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 1)
298
+ array([ 1.42704095, 2.06782203, 3. , 3.93217797, 4.57295905])
299
+ >>> gaussian_filter1d([1.0, 2.0, 3.0, 4.0, 5.0], 4)
300
+ array([ 2.91948343, 2.95023502, 3. , 3.04976498, 3.08051657])
301
+ >>> import matplotlib.pyplot as plt
302
+ >>> rng = np.random.default_rng()
303
+ >>> x = rng.standard_normal(101).cumsum()
304
+ >>> y3 = gaussian_filter1d(x, 3)
305
+ >>> y6 = gaussian_filter1d(x, 6)
306
+ >>> plt.plot(x, 'k', label='original data')
307
+ >>> plt.plot(y3, '--', label='filtered, sigma=3')
308
+ >>> plt.plot(y6, ':', label='filtered, sigma=6')
309
+ >>> plt.legend()
310
+ >>> plt.grid()
311
+ >>> plt.show()
312
+
313
+ """
314
+ sd = float(sigma)
315
+ # make the radius of the filter equal to truncate standard deviations
316
+ lw = int(truncate * sd + 0.5)
317
+ if radius is not None:
318
+ lw = radius
319
+ if not isinstance(lw, numbers.Integral) or lw < 0:
320
+ raise ValueError('Radius must be a nonnegative integer.')
321
+ # Since we are calling correlate, not convolve, revert the kernel
322
+ weights = _gaussian_kernel1d(sigma, order, lw)[::-1]
323
+ return correlate1d(input, weights, axis, output, mode, cval, 0)
324
+
325
+
326
+ @_ni_docstrings.docfiller
327
+ def gaussian_filter(input, sigma, order=0, output=None,
328
+ mode="reflect", cval=0.0, truncate=4.0, *, radius=None,
329
+ axes=None):
330
+ """Multidimensional Gaussian filter.
331
+
332
+ Parameters
333
+ ----------
334
+ %(input)s
335
+ sigma : scalar or sequence of scalars
336
+ Standard deviation for Gaussian kernel. The standard
337
+ deviations of the Gaussian filter are given for each axis as a
338
+ sequence, or as a single number, in which case it is equal for
339
+ all axes.
340
+ order : int or sequence of ints, optional
341
+ The order of the filter along each axis is given as a sequence
342
+ of integers, or as a single number. An order of 0 corresponds
343
+ to convolution with a Gaussian kernel. A positive order
344
+ corresponds to convolution with that derivative of a Gaussian.
345
+ %(output)s
346
+ %(mode_multiple)s
347
+ %(cval)s
348
+ truncate : float, optional
349
+ Truncate the filter at this many standard deviations.
350
+ Default is 4.0.
351
+ radius : None or int or sequence of ints, optional
352
+ Radius of the Gaussian kernel. The radius are given for each axis
353
+ as a sequence, or as a single number, in which case it is equal
354
+ for all axes. If specified, the size of the kernel along each axis
355
+ will be ``2*radius + 1``, and `truncate` is ignored.
356
+ Default is None.
357
+ axes : tuple of int or None, optional
358
+ If None, `input` is filtered along all axes. Otherwise,
359
+ `input` is filtered along the specified axes. When `axes` is
360
+ specified, any tuples used for `sigma`, `order`, `mode` and/or `radius`
361
+ must match the length of `axes`. The ith entry in any of these tuples
362
+ corresponds to the ith entry in `axes`.
363
+
364
+ Returns
365
+ -------
366
+ gaussian_filter : ndarray
367
+ Returned array of same shape as `input`.
368
+
369
+ Notes
370
+ -----
371
+ The multidimensional filter is implemented as a sequence of
372
+ 1-D convolution filters. The intermediate arrays are
373
+ stored in the same data type as the output. Therefore, for output
374
+ types with a limited precision, the results may be imprecise
375
+ because intermediate results may be stored with insufficient
376
+ precision.
377
+
378
+ The Gaussian kernel will have size ``2*radius + 1`` along each axis. If
379
+ `radius` is None, the default ``radius = round(truncate * sigma)`` will be
380
+ used.
381
+
382
+ Examples
383
+ --------
384
+ >>> from scipy.ndimage import gaussian_filter
385
+ >>> import numpy as np
386
+ >>> a = np.arange(50, step=2).reshape((5,5))
387
+ >>> a
388
+ array([[ 0, 2, 4, 6, 8],
389
+ [10, 12, 14, 16, 18],
390
+ [20, 22, 24, 26, 28],
391
+ [30, 32, 34, 36, 38],
392
+ [40, 42, 44, 46, 48]])
393
+ >>> gaussian_filter(a, sigma=1)
394
+ array([[ 4, 6, 8, 9, 11],
395
+ [10, 12, 14, 15, 17],
396
+ [20, 22, 24, 25, 27],
397
+ [29, 31, 33, 34, 36],
398
+ [35, 37, 39, 40, 42]])
399
+
400
+ >>> from scipy import datasets
401
+ >>> import matplotlib.pyplot as plt
402
+ >>> fig = plt.figure()
403
+ >>> plt.gray() # show the filtered result in grayscale
404
+ >>> ax1 = fig.add_subplot(121) # left side
405
+ >>> ax2 = fig.add_subplot(122) # right side
406
+ >>> ascent = datasets.ascent()
407
+ >>> result = gaussian_filter(ascent, sigma=5)
408
+ >>> ax1.imshow(ascent)
409
+ >>> ax2.imshow(result)
410
+ >>> plt.show()
411
+ """
412
+ input = np.asarray(input)
413
+ output = _ni_support._get_output(output, input)
414
+
415
+ axes = _ni_support._check_axes(axes, input.ndim)
416
+ num_axes = len(axes)
417
+ orders = _ni_support._normalize_sequence(order, num_axes)
418
+ sigmas = _ni_support._normalize_sequence(sigma, num_axes)
419
+ modes = _ni_support._normalize_sequence(mode, num_axes)
420
+ radiuses = _ni_support._normalize_sequence(radius, num_axes)
421
+ axes = [(axes[ii], sigmas[ii], orders[ii], modes[ii], radiuses[ii])
422
+ for ii in range(num_axes) if sigmas[ii] > 1e-15]
423
+ if len(axes) > 0:
424
+ for axis, sigma, order, mode, radius in axes:
425
+ gaussian_filter1d(input, sigma, axis, order, output,
426
+ mode, cval, truncate, radius=radius)
427
+ input = output
428
+ else:
429
+ output[...] = input[...]
430
+ return output
431
+
432
+
433
+ @_ni_docstrings.docfiller
434
+ def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0):
435
+ """Calculate a Prewitt filter.
436
+
437
+ Parameters
438
+ ----------
439
+ %(input)s
440
+ %(axis)s
441
+ %(output)s
442
+ %(mode_multiple)s
443
+ %(cval)s
444
+
445
+ Returns
446
+ -------
447
+ prewitt : ndarray
448
+ Filtered array. Has the same shape as `input`.
449
+
450
+ See Also
451
+ --------
452
+ sobel: Sobel filter
453
+
454
+ Notes
455
+ -----
456
+ This function computes the one-dimensional Prewitt filter.
457
+ Horizontal edges are emphasised with the horizontal transform (axis=0),
458
+ vertical edges with the vertical transform (axis=1), and so on for higher
459
+ dimensions. These can be combined to give the magnitude.
460
+
461
+ Examples
462
+ --------
463
+ >>> from scipy import ndimage, datasets
464
+ >>> import matplotlib.pyplot as plt
465
+ >>> import numpy as np
466
+ >>> ascent = datasets.ascent()
467
+ >>> prewitt_h = ndimage.prewitt(ascent, axis=0)
468
+ >>> prewitt_v = ndimage.prewitt(ascent, axis=1)
469
+ >>> magnitude = np.sqrt(prewitt_h ** 2 + prewitt_v ** 2)
470
+ >>> magnitude *= 255 / np.max(magnitude) # Normalization
471
+ >>> fig, axes = plt.subplots(2, 2, figsize = (8, 8))
472
+ >>> plt.gray()
473
+ >>> axes[0, 0].imshow(ascent)
474
+ >>> axes[0, 1].imshow(prewitt_h)
475
+ >>> axes[1, 0].imshow(prewitt_v)
476
+ >>> axes[1, 1].imshow(magnitude)
477
+ >>> titles = ["original", "horizontal", "vertical", "magnitude"]
478
+ >>> for i, ax in enumerate(axes.ravel()):
479
+ ... ax.set_title(titles[i])
480
+ ... ax.axis("off")
481
+ >>> plt.show()
482
+
483
+ """
484
+ input = np.asarray(input)
485
+ axis = normalize_axis_index(axis, input.ndim)
486
+ output = _ni_support._get_output(output, input)
487
+ modes = _ni_support._normalize_sequence(mode, input.ndim)
488
+ correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
489
+ axes = [ii for ii in range(input.ndim) if ii != axis]
490
+ for ii in axes:
491
+ correlate1d(output, [1, 1, 1], ii, output, modes[ii], cval, 0,)
492
+ return output
493
+
494
+
495
+ @_ni_docstrings.docfiller
496
+ def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
497
+ """Calculate a Sobel filter.
498
+
499
+ Parameters
500
+ ----------
501
+ %(input)s
502
+ %(axis)s
503
+ %(output)s
504
+ %(mode_multiple)s
505
+ %(cval)s
506
+
507
+ Returns
508
+ -------
509
+ sobel : ndarray
510
+ Filtered array. Has the same shape as `input`.
511
+
512
+ Notes
513
+ -----
514
+ This function computes the axis-specific Sobel gradient.
515
+ The horizontal edges can be emphasised with the horizontal transform (axis=0),
516
+ the vertical edges with the vertical transform (axis=1) and so on for higher
517
+ dimensions. These can be combined to give the magnitude.
518
+
519
+ Examples
520
+ --------
521
+ >>> from scipy import ndimage, datasets
522
+ >>> import matplotlib.pyplot as plt
523
+ >>> import numpy as np
524
+ >>> ascent = datasets.ascent().astype('int32')
525
+ >>> sobel_h = ndimage.sobel(ascent, 0) # horizontal gradient
526
+ >>> sobel_v = ndimage.sobel(ascent, 1) # vertical gradient
527
+ >>> magnitude = np.sqrt(sobel_h**2 + sobel_v**2)
528
+ >>> magnitude *= 255.0 / np.max(magnitude) # normalization
529
+ >>> fig, axs = plt.subplots(2, 2, figsize=(8, 8))
530
+ >>> plt.gray() # show the filtered result in grayscale
531
+ >>> axs[0, 0].imshow(ascent)
532
+ >>> axs[0, 1].imshow(sobel_h)
533
+ >>> axs[1, 0].imshow(sobel_v)
534
+ >>> axs[1, 1].imshow(magnitude)
535
+ >>> titles = ["original", "horizontal", "vertical", "magnitude"]
536
+ >>> for i, ax in enumerate(axs.ravel()):
537
+ ... ax.set_title(titles[i])
538
+ ... ax.axis("off")
539
+ >>> plt.show()
540
+
541
+ """
542
+ input = np.asarray(input)
543
+ axis = normalize_axis_index(axis, input.ndim)
544
+ output = _ni_support._get_output(output, input)
545
+ modes = _ni_support._normalize_sequence(mode, input.ndim)
546
+ correlate1d(input, [-1, 0, 1], axis, output, modes[axis], cval, 0)
547
+ axes = [ii for ii in range(input.ndim) if ii != axis]
548
+ for ii in axes:
549
+ correlate1d(output, [1, 2, 1], ii, output, modes[ii], cval, 0)
550
+ return output
551
+
552
+
553
+ @_ni_docstrings.docfiller
554
+ def generic_laplace(input, derivative2, output=None, mode="reflect",
555
+ cval=0.0,
556
+ extra_arguments=(),
557
+ extra_keywords=None,
558
+ *, axes=None):
559
+ """
560
+ N-D Laplace filter using a provided second derivative function.
561
+
562
+ Parameters
563
+ ----------
564
+ %(input)s
565
+ derivative2 : callable
566
+ Callable with the following signature::
567
+
568
+ derivative2(input, axis, output, mode, cval,
569
+ *extra_arguments, **extra_keywords)
570
+
571
+ See `extra_arguments`, `extra_keywords` below.
572
+ %(output)s
573
+ %(mode_multiple)s
574
+ %(cval)s
575
+ %(extra_keywords)s
576
+ %(extra_arguments)s
577
+ axes : tuple of int or None
578
+ The axes over which to apply the filter. If a `mode` tuple is
579
+ provided, its length must match the number of axes.
580
+
581
+ Returns
582
+ -------
583
+ generic_laplace : ndarray
584
+ Filtered array. Has the same shape as `input`.
585
+
586
+ """
587
+ if extra_keywords is None:
588
+ extra_keywords = {}
589
+ input = np.asarray(input)
590
+ output = _ni_support._get_output(output, input)
591
+ axes = _ni_support._check_axes(axes, input.ndim)
592
+ if len(axes) > 0:
593
+ modes = _ni_support._normalize_sequence(mode, len(axes))
594
+ derivative2(input, axes[0], output, modes[0], cval,
595
+ *extra_arguments, **extra_keywords)
596
+ for ii in range(1, len(axes)):
597
+ tmp = derivative2(input, axes[ii], output.dtype, modes[ii], cval,
598
+ *extra_arguments, **extra_keywords)
599
+ output += tmp
600
+ else:
601
+ output[...] = input[...]
602
+ return output
603
+
604
+
605
+ @_ni_docstrings.docfiller
606
+ def laplace(input, output=None, mode="reflect", cval=0.0, *, axes=None):
607
+ """N-D Laplace filter based on approximate second derivatives.
608
+
609
+ Parameters
610
+ ----------
611
+ %(input)s
612
+ %(output)s
613
+ %(mode_multiple)s
614
+ %(cval)s
615
+ axes : tuple of int or None
616
+ The axes over which to apply the filter. If a `mode` tuple is
617
+ provided, its length must match the number of axes.
618
+
619
+ Returns
620
+ -------
621
+ laplace : ndarray
622
+ Filtered array. Has the same shape as `input`.
623
+
624
+ Examples
625
+ --------
626
+ >>> from scipy import ndimage, datasets
627
+ >>> import matplotlib.pyplot as plt
628
+ >>> fig = plt.figure()
629
+ >>> plt.gray() # show the filtered result in grayscale
630
+ >>> ax1 = fig.add_subplot(121) # left side
631
+ >>> ax2 = fig.add_subplot(122) # right side
632
+ >>> ascent = datasets.ascent()
633
+ >>> result = ndimage.laplace(ascent)
634
+ >>> ax1.imshow(ascent)
635
+ >>> ax2.imshow(result)
636
+ >>> plt.show()
637
+ """
638
+ def derivative2(input, axis, output, mode, cval):
639
+ return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
640
+ return generic_laplace(input, derivative2, output, mode, cval, axes=axes)
641
+
642
+
643
+ @_ni_docstrings.docfiller
644
+ def gaussian_laplace(input, sigma, output=None, mode="reflect",
645
+ cval=0.0, *, axes=None, **kwargs):
646
+ """Multidimensional Laplace filter using Gaussian second derivatives.
647
+
648
+ Parameters
649
+ ----------
650
+ %(input)s
651
+ sigma : scalar or sequence of scalars
652
+ The standard deviations of the Gaussian filter are given for
653
+ each axis as a sequence, or as a single number, in which case
654
+ it is equal for all axes.
655
+ %(output)s
656
+ %(mode_multiple)s
657
+ %(cval)s
658
+ axes : tuple of int or None
659
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
660
+ are provided, their length must match the number of axes.
661
+ Extra keyword arguments will be passed to gaussian_filter().
662
+
663
+ Returns
664
+ -------
665
+ gaussian_laplace : ndarray
666
+ Filtered array. Has the same shape as `input`.
667
+
668
+ Examples
669
+ --------
670
+ >>> from scipy import ndimage, datasets
671
+ >>> import matplotlib.pyplot as plt
672
+ >>> ascent = datasets.ascent()
673
+
674
+ >>> fig = plt.figure()
675
+ >>> plt.gray() # show the filtered result in grayscale
676
+ >>> ax1 = fig.add_subplot(121) # left side
677
+ >>> ax2 = fig.add_subplot(122) # right side
678
+
679
+ >>> result = ndimage.gaussian_laplace(ascent, sigma=1)
680
+ >>> ax1.imshow(result)
681
+
682
+ >>> result = ndimage.gaussian_laplace(ascent, sigma=3)
683
+ >>> ax2.imshow(result)
684
+ >>> plt.show()
685
+ """
686
+ input = np.asarray(input)
687
+
688
+ def derivative2(input, axis, output, mode, cval, sigma, **kwargs):
689
+ order = [0] * input.ndim
690
+ order[axis] = 2
691
+ return gaussian_filter(input, sigma, order, output, mode, cval,
692
+ **kwargs)
693
+
694
+ axes = _ni_support._check_axes(axes, input.ndim)
695
+ num_axes = len(axes)
696
+ sigma = _ni_support._normalize_sequence(sigma, num_axes)
697
+ if num_axes < input.ndim:
698
+ # set sigma = 0 for any axes not being filtered
699
+ sigma_temp = [0,] * input.ndim
700
+ for s, ax in zip(sigma, axes):
701
+ sigma_temp[ax] = s
702
+ sigma = sigma_temp
703
+
704
+ return generic_laplace(input, derivative2, output, mode, cval,
705
+ extra_arguments=(sigma,),
706
+ extra_keywords=kwargs,
707
+ axes=axes)
708
+
709
+
710
+ @_ni_docstrings.docfiller
711
+ def generic_gradient_magnitude(input, derivative, output=None,
712
+ mode="reflect", cval=0.0,
713
+ extra_arguments=(), extra_keywords=None,
714
+ *, axes=None):
715
+ """Gradient magnitude using a provided gradient function.
716
+
717
+ Parameters
718
+ ----------
719
+ %(input)s
720
+ derivative : callable
721
+ Callable with the following signature::
722
+
723
+ derivative(input, axis, output, mode, cval,
724
+ *extra_arguments, **extra_keywords)
725
+
726
+ See `extra_arguments`, `extra_keywords` below.
727
+ `derivative` can assume that `input` and `output` are ndarrays.
728
+ Note that the output from `derivative` is modified inplace;
729
+ be careful to copy important inputs before returning them.
730
+ %(output)s
731
+ %(mode_multiple)s
732
+ %(cval)s
733
+ %(extra_keywords)s
734
+ %(extra_arguments)s
735
+ axes : tuple of int or None
736
+ The axes over which to apply the filter. If a `mode` tuple is
737
+ provided, its length must match the number of axes.
738
+
739
+ Returns
740
+ -------
741
+ generic_gradient_matnitude : ndarray
742
+ Filtered array. Has the same shape as `input`.
743
+
744
+ """
745
+ if extra_keywords is None:
746
+ extra_keywords = {}
747
+ input = np.asarray(input)
748
+ output = _ni_support._get_output(output, input)
749
+ axes = _ni_support._check_axes(axes, input.ndim)
750
+ if len(axes) > 0:
751
+ modes = _ni_support._normalize_sequence(mode, len(axes))
752
+ derivative(input, axes[0], output, modes[0], cval,
753
+ *extra_arguments, **extra_keywords)
754
+ np.multiply(output, output, output)
755
+ for ii in range(1, len(axes)):
756
+ tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval,
757
+ *extra_arguments, **extra_keywords)
758
+ np.multiply(tmp, tmp, tmp)
759
+ output += tmp
760
+ # This allows the sqrt to work with a different default casting
761
+ np.sqrt(output, output, casting='unsafe')
762
+ else:
763
+ output[...] = input[...]
764
+ return output
765
+
766
+
767
+ @_ni_docstrings.docfiller
768
+ def gaussian_gradient_magnitude(input, sigma, output=None,
769
+ mode="reflect", cval=0.0, *, axes=None,
770
+ **kwargs):
771
+ """Multidimensional gradient magnitude using Gaussian derivatives.
772
+
773
+ Parameters
774
+ ----------
775
+ %(input)s
776
+ sigma : scalar or sequence of scalars
777
+ The standard deviations of the Gaussian filter are given for
778
+ each axis as a sequence, or as a single number, in which case
779
+ it is equal for all axes.
780
+ %(output)s
781
+ %(mode_multiple)s
782
+ %(cval)s
783
+ axes : tuple of int or None
784
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
785
+ are provided, their length must match the number of axes.
786
+ Extra keyword arguments will be passed to gaussian_filter().
787
+
788
+ Returns
789
+ -------
790
+ gaussian_gradient_magnitude : ndarray
791
+ Filtered array. Has the same shape as `input`.
792
+
793
+ Examples
794
+ --------
795
+ >>> from scipy import ndimage, datasets
796
+ >>> import matplotlib.pyplot as plt
797
+ >>> fig = plt.figure()
798
+ >>> plt.gray() # show the filtered result in grayscale
799
+ >>> ax1 = fig.add_subplot(121) # left side
800
+ >>> ax2 = fig.add_subplot(122) # right side
801
+ >>> ascent = datasets.ascent()
802
+ >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5)
803
+ >>> ax1.imshow(ascent)
804
+ >>> ax2.imshow(result)
805
+ >>> plt.show()
806
+ """
807
+ input = np.asarray(input)
808
+
809
+ def derivative(input, axis, output, mode, cval, sigma, **kwargs):
810
+ order = [0] * input.ndim
811
+ order[axis] = 1
812
+ return gaussian_filter(input, sigma, order, output, mode,
813
+ cval, **kwargs)
814
+
815
+ return generic_gradient_magnitude(input, derivative, output, mode,
816
+ cval, extra_arguments=(sigma,),
817
+ extra_keywords=kwargs, axes=axes)
818
+
819
+
820
+ def _correlate_or_convolve(input, weights, output, mode, cval, origin,
821
+ convolution, axes):
822
+ input = np.asarray(input)
823
+ weights = np.asarray(weights)
824
+ complex_input = input.dtype.kind == 'c'
825
+ complex_weights = weights.dtype.kind == 'c'
826
+ if complex_input or complex_weights:
827
+ if complex_weights and not convolution:
828
+ # As for np.correlate, conjugate weights rather than input.
829
+ weights = weights.conj()
830
+ kwargs = dict(
831
+ mode=mode, origin=origin, convolution=convolution, axes=axes
832
+ )
833
+ output = _ni_support._get_output(output, input, complex_output=True)
834
+
835
+ return _complex_via_real_components(_correlate_or_convolve, input,
836
+ weights, output, cval, **kwargs)
837
+
838
+ axes = _ni_support._check_axes(axes, input.ndim)
839
+ weights = np.asarray(weights, dtype=np.float64)
840
+
841
+ # expand weights and origins if num_axes < input.ndim
842
+ weights = _expand_footprint(input.ndim, axes, weights, "weights")
843
+ origins = _expand_origin(input.ndim, axes, origin)
844
+
845
+ wshape = [ii for ii in weights.shape if ii > 0]
846
+ if len(wshape) != input.ndim:
847
+ raise RuntimeError(f"weights.ndim ({len(wshape)}) must match "
848
+ f"len(axes) ({len(axes)})")
849
+ if convolution:
850
+ weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
851
+ for ii in range(len(origins)):
852
+ origins[ii] = -origins[ii]
853
+ if not weights.shape[ii] & 1:
854
+ origins[ii] -= 1
855
+ for origin, lenw in zip(origins, wshape):
856
+ if _invalid_origin(origin, lenw):
857
+ raise ValueError('Invalid origin; origin must satisfy '
858
+ '-(weights.shape[k] // 2) <= origin[k] <= '
859
+ '(weights.shape[k]-1) // 2')
860
+
861
+ if not weights.flags.contiguous:
862
+ weights = weights.copy()
863
+ output = _ni_support._get_output(output, input)
864
+ temp_needed = np.may_share_memory(input, output)
865
+ if temp_needed:
866
+ # input and output arrays cannot share memory
867
+ temp = output
868
+ output = _ni_support._get_output(output.dtype, input)
869
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
870
+ raise RuntimeError("A sequence of modes is not supported")
871
+ mode = _ni_support._extend_mode_to_code(mode)
872
+ _nd_image.correlate(input, weights, output, mode, cval, origins)
873
+ if temp_needed:
874
+ temp[...] = output
875
+ output = temp
876
+ return output
877
+
878
+
879
+ @_ni_docstrings.docfiller
880
+ def correlate(input, weights, output=None, mode='reflect', cval=0.0,
881
+ origin=0, *, axes=None):
882
+ """
883
+ Multidimensional correlation.
884
+
885
+ The array is correlated with the given kernel.
886
+
887
+ Parameters
888
+ ----------
889
+ %(input)s
890
+ weights : ndarray
891
+ array of weights, same number of dimensions as input
892
+ %(output)s
893
+ %(mode_reflect)s
894
+ %(cval)s
895
+ %(origin_multiple)s
896
+ axes : tuple of int or None, optional
897
+ If None, `input` is filtered along all axes. Otherwise,
898
+ `input` is filtered along the specified axes. When `axes` is
899
+ specified, any tuples used for `mode` or `origin` must match the length
900
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
901
+ entry in `axes`.
902
+
903
+ Returns
904
+ -------
905
+ result : ndarray
906
+ The result of correlation of `input` with `weights`.
907
+
908
+ See Also
909
+ --------
910
+ convolve : Convolve an image with a kernel.
911
+
912
+ Examples
913
+ --------
914
+ Correlation is the process of moving a filter mask often referred to
915
+ as kernel over the image and computing the sum of products at each location.
916
+
917
+ >>> from scipy.ndimage import correlate
918
+ >>> import numpy as np
919
+ >>> input_img = np.arange(25).reshape(5,5)
920
+ >>> print(input_img)
921
+ [[ 0 1 2 3 4]
922
+ [ 5 6 7 8 9]
923
+ [10 11 12 13 14]
924
+ [15 16 17 18 19]
925
+ [20 21 22 23 24]]
926
+
927
+ Define a kernel (weights) for correlation. In this example, it is for sum of
928
+ center and up, down, left and right next elements.
929
+
930
+ >>> weights = [[0, 1, 0],
931
+ ... [1, 1, 1],
932
+ ... [0, 1, 0]]
933
+
934
+ We can calculate a correlation result:
935
+ For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``.
936
+
937
+ >>> correlate(input_img, weights)
938
+ array([[ 6, 10, 15, 20, 24],
939
+ [ 26, 30, 35, 40, 44],
940
+ [ 51, 55, 60, 65, 69],
941
+ [ 76, 80, 85, 90, 94],
942
+ [ 96, 100, 105, 110, 114]])
943
+
944
+ """
945
+ return _correlate_or_convolve(input, weights, output, mode, cval,
946
+ origin, False, axes)
947
+
948
+
949
+ @_ni_docstrings.docfiller
950
+ def convolve(input, weights, output=None, mode='reflect', cval=0.0,
951
+ origin=0, *, axes=None):
952
+ """
953
+ Multidimensional convolution.
954
+
955
+ The array is convolved with the given kernel.
956
+
957
+ Parameters
958
+ ----------
959
+ %(input)s
960
+ weights : array_like
961
+ Array of weights, same number of dimensions as input
962
+ %(output)s
963
+ %(mode_reflect)s
964
+ cval : scalar, optional
965
+ Value to fill past edges of input if `mode` is 'constant'. Default
966
+ is 0.0
967
+ origin : int or sequence, optional
968
+ Controls the placement of the filter on the input array's pixels.
969
+ A value of 0 (the default) centers the filter over the pixel, with
970
+ positive values shifting the filter to the right, and negative ones
971
+ to the left. By passing a sequence of origins with length equal to
972
+ the number of dimensions of the input array, different shifts can
973
+ be specified along each axis.
974
+ axes : tuple of int or None, optional
975
+ If None, `input` is filtered along all axes. Otherwise,
976
+ `input` is filtered along the specified axes. When `axes` is
977
+ specified, any tuples used for `mode` or `origin` must match the length
978
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
979
+ entry in `axes`.
980
+
981
+ Returns
982
+ -------
983
+ result : ndarray
984
+ The result of convolution of `input` with `weights`.
985
+
986
+ See Also
987
+ --------
988
+ correlate : Correlate an image with a kernel.
989
+
990
+ Notes
991
+ -----
992
+ Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
993
+ W is the `weights` kernel,
994
+ j is the N-D spatial index over :math:`W`,
995
+ I is the `input` and k is the coordinate of the center of
996
+ W, specified by `origin` in the input parameters.
997
+
998
+ Examples
999
+ --------
1000
+ Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
1001
+ because in this case borders (i.e., where the `weights` kernel, centered
1002
+ on any one value, extends beyond an edge of `input`) are treated as zeros.
1003
+
1004
+ >>> import numpy as np
1005
+ >>> a = np.array([[1, 2, 0, 0],
1006
+ ... [5, 3, 0, 4],
1007
+ ... [0, 0, 0, 7],
1008
+ ... [9, 3, 0, 0]])
1009
+ >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
1010
+ >>> from scipy import ndimage
1011
+ >>> ndimage.convolve(a, k, mode='constant', cval=0.0)
1012
+ array([[11, 10, 7, 4],
1013
+ [10, 3, 11, 11],
1014
+ [15, 12, 14, 7],
1015
+ [12, 3, 7, 0]])
1016
+
1017
+ Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
1018
+ with 1.0's (and then extracting only the original region of the result).
1019
+
1020
+ >>> ndimage.convolve(a, k, mode='constant', cval=1.0)
1021
+ array([[13, 11, 8, 7],
1022
+ [11, 3, 11, 14],
1023
+ [16, 12, 14, 10],
1024
+ [15, 6, 10, 5]])
1025
+
1026
+ With ``mode='reflect'`` (the default), outer values are reflected at the
1027
+ edge of `input` to fill in missing values.
1028
+
1029
+ >>> b = np.array([[2, 0, 0],
1030
+ ... [1, 0, 0],
1031
+ ... [0, 0, 0]])
1032
+ >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
1033
+ >>> ndimage.convolve(b, k, mode='reflect')
1034
+ array([[5, 0, 0],
1035
+ [3, 0, 0],
1036
+ [1, 0, 0]])
1037
+
1038
+ This includes diagonally at the corners.
1039
+
1040
+ >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
1041
+ >>> ndimage.convolve(b, k)
1042
+ array([[4, 2, 0],
1043
+ [3, 2, 0],
1044
+ [1, 1, 0]])
1045
+
1046
+ With ``mode='nearest'``, the single nearest value in to an edge in
1047
+ `input` is repeated as many times as needed to match the overlapping
1048
+ `weights`.
1049
+
1050
+ >>> c = np.array([[2, 0, 1],
1051
+ ... [1, 0, 0],
1052
+ ... [0, 0, 0]])
1053
+ >>> k = np.array([[0, 1, 0],
1054
+ ... [0, 1, 0],
1055
+ ... [0, 1, 0],
1056
+ ... [0, 1, 0],
1057
+ ... [0, 1, 0]])
1058
+ >>> ndimage.convolve(c, k, mode='nearest')
1059
+ array([[7, 0, 3],
1060
+ [5, 0, 2],
1061
+ [3, 0, 1]])
1062
+
1063
+ """
1064
+ return _correlate_or_convolve(input, weights, output, mode, cval,
1065
+ origin, True, axes)
1066
+
1067
+
1068
+ @_ni_docstrings.docfiller
1069
+ def uniform_filter1d(input, size, axis=-1, output=None,
1070
+ mode="reflect", cval=0.0, origin=0):
1071
+ """Calculate a 1-D uniform filter along the given axis.
1072
+
1073
+ The lines of the array along the given axis are filtered with a
1074
+ uniform filter of given size.
1075
+
1076
+ Parameters
1077
+ ----------
1078
+ %(input)s
1079
+ size : int
1080
+ length of uniform filter
1081
+ %(axis)s
1082
+ %(output)s
1083
+ %(mode_reflect)s
1084
+ %(cval)s
1085
+ %(origin)s
1086
+
1087
+ Returns
1088
+ -------
1089
+ result : ndarray
1090
+ Filtered array. Has same shape as `input`.
1091
+
1092
+ Examples
1093
+ --------
1094
+ >>> from scipy.ndimage import uniform_filter1d
1095
+ >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1096
+ array([4, 3, 4, 1, 4, 6, 6, 3])
1097
+ """
1098
+ input = np.asarray(input)
1099
+ axis = normalize_axis_index(axis, input.ndim)
1100
+ if size < 1:
1101
+ raise RuntimeError('incorrect filter size')
1102
+ complex_output = input.dtype.kind == 'c'
1103
+ output = _ni_support._get_output(output, input,
1104
+ complex_output=complex_output)
1105
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1106
+ raise ValueError('invalid origin')
1107
+ mode = _ni_support._extend_mode_to_code(mode)
1108
+ if not complex_output:
1109
+ _nd_image.uniform_filter1d(input, size, axis, output, mode, cval,
1110
+ origin)
1111
+ else:
1112
+ _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode,
1113
+ np.real(cval), origin)
1114
+ _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode,
1115
+ np.imag(cval), origin)
1116
+ return output
1117
+
1118
+
1119
+ @_ni_docstrings.docfiller
1120
+ def uniform_filter(input, size=3, output=None, mode="reflect",
1121
+ cval=0.0, origin=0, *, axes=None):
1122
+ """Multidimensional uniform filter.
1123
+
1124
+ Parameters
1125
+ ----------
1126
+ %(input)s
1127
+ size : int or sequence of ints, optional
1128
+ The sizes of the uniform filter are given for each axis as a
1129
+ sequence, or as a single number, in which case the size is
1130
+ equal for all axes.
1131
+ %(output)s
1132
+ %(mode_multiple)s
1133
+ %(cval)s
1134
+ %(origin_multiple)s
1135
+ axes : tuple of int or None, optional
1136
+ If None, `input` is filtered along all axes. Otherwise,
1137
+ `input` is filtered along the specified axes. When `axes` is
1138
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1139
+ must match the length of `axes`. The ith entry in any of these tuples
1140
+ corresponds to the ith entry in `axes`.
1141
+
1142
+ Returns
1143
+ -------
1144
+ uniform_filter : ndarray
1145
+ Filtered array. Has the same shape as `input`.
1146
+
1147
+ Notes
1148
+ -----
1149
+ The multidimensional filter is implemented as a sequence of
1150
+ 1-D uniform filters. The intermediate arrays are stored
1151
+ in the same data type as the output. Therefore, for output types
1152
+ with a limited precision, the results may be imprecise because
1153
+ intermediate results may be stored with insufficient precision.
1154
+
1155
+ Examples
1156
+ --------
1157
+ >>> from scipy import ndimage, datasets
1158
+ >>> import matplotlib.pyplot as plt
1159
+ >>> fig = plt.figure()
1160
+ >>> plt.gray() # show the filtered result in grayscale
1161
+ >>> ax1 = fig.add_subplot(121) # left side
1162
+ >>> ax2 = fig.add_subplot(122) # right side
1163
+ >>> ascent = datasets.ascent()
1164
+ >>> result = ndimage.uniform_filter(ascent, size=20)
1165
+ >>> ax1.imshow(ascent)
1166
+ >>> ax2.imshow(result)
1167
+ >>> plt.show()
1168
+ """
1169
+ input = np.asarray(input)
1170
+ output = _ni_support._get_output(output, input,
1171
+ complex_output=input.dtype.kind == 'c')
1172
+ axes = _ni_support._check_axes(axes, input.ndim)
1173
+ num_axes = len(axes)
1174
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1175
+ origins = _ni_support._normalize_sequence(origin, num_axes)
1176
+ modes = _ni_support._normalize_sequence(mode, num_axes)
1177
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
1178
+ for ii in range(num_axes) if sizes[ii] > 1]
1179
+ if len(axes) > 0:
1180
+ for axis, size, origin, mode in axes:
1181
+ uniform_filter1d(input, int(size), axis, output, mode,
1182
+ cval, origin)
1183
+ input = output
1184
+ else:
1185
+ output[...] = input[...]
1186
+ return output
1187
+
1188
+
1189
+ @_ni_docstrings.docfiller
1190
+ def minimum_filter1d(input, size, axis=-1, output=None,
1191
+ mode="reflect", cval=0.0, origin=0):
1192
+ """Calculate a 1-D minimum filter along the given axis.
1193
+
1194
+ The lines of the array along the given axis are filtered with a
1195
+ minimum filter of given size.
1196
+
1197
+ Parameters
1198
+ ----------
1199
+ %(input)s
1200
+ size : int
1201
+ length along which to calculate 1D minimum
1202
+ %(axis)s
1203
+ %(output)s
1204
+ %(mode_reflect)s
1205
+ %(cval)s
1206
+ %(origin)s
1207
+
1208
+ Returns
1209
+ -------
1210
+ result : ndarray.
1211
+ Filtered image. Has the same shape as `input`.
1212
+
1213
+ Notes
1214
+ -----
1215
+ This function implements the MINLIST algorithm [1]_, as described by
1216
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
1217
+ the `input` length, regardless of filter size.
1218
+
1219
+ References
1220
+ ----------
1221
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
1222
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
1223
+
1224
+
1225
+ Examples
1226
+ --------
1227
+ >>> from scipy.ndimage import minimum_filter1d
1228
+ >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1229
+ array([2, 0, 0, 0, 1, 1, 0, 0])
1230
+ """
1231
+ input = np.asarray(input)
1232
+ if np.iscomplexobj(input):
1233
+ raise TypeError('Complex type not supported')
1234
+ axis = normalize_axis_index(axis, input.ndim)
1235
+ if size < 1:
1236
+ raise RuntimeError('incorrect filter size')
1237
+ output = _ni_support._get_output(output, input)
1238
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1239
+ raise ValueError('invalid origin')
1240
+ mode = _ni_support._extend_mode_to_code(mode)
1241
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
1242
+ origin, 1)
1243
+ return output
1244
+
1245
+
1246
+ @_ni_docstrings.docfiller
1247
+ def maximum_filter1d(input, size, axis=-1, output=None,
1248
+ mode="reflect", cval=0.0, origin=0):
1249
+ """Calculate a 1-D maximum filter along the given axis.
1250
+
1251
+ The lines of the array along the given axis are filtered with a
1252
+ maximum filter of given size.
1253
+
1254
+ Parameters
1255
+ ----------
1256
+ %(input)s
1257
+ size : int
1258
+ Length along which to calculate the 1-D maximum.
1259
+ %(axis)s
1260
+ %(output)s
1261
+ %(mode_reflect)s
1262
+ %(cval)s
1263
+ %(origin)s
1264
+
1265
+ Returns
1266
+ -------
1267
+ maximum1d : ndarray, None
1268
+ Maximum-filtered array with same shape as input.
1269
+ None if `output` is not None
1270
+
1271
+ Notes
1272
+ -----
1273
+ This function implements the MAXLIST algorithm [1]_, as described by
1274
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
1275
+ the `input` length, regardless of filter size.
1276
+
1277
+ References
1278
+ ----------
1279
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
1280
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
1281
+
1282
+ Examples
1283
+ --------
1284
+ >>> from scipy.ndimage import maximum_filter1d
1285
+ >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
1286
+ array([8, 8, 8, 4, 9, 9, 9, 9])
1287
+ """
1288
+ input = np.asarray(input)
1289
+ if np.iscomplexobj(input):
1290
+ raise TypeError('Complex type not supported')
1291
+ axis = normalize_axis_index(axis, input.ndim)
1292
+ if size < 1:
1293
+ raise RuntimeError('incorrect filter size')
1294
+ output = _ni_support._get_output(output, input)
1295
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
1296
+ raise ValueError('invalid origin')
1297
+ mode = _ni_support._extend_mode_to_code(mode)
1298
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
1299
+ origin, 0)
1300
+ return output
1301
+
1302
+
1303
+ def _min_or_max_filter(input, size, footprint, structure, output, mode,
1304
+ cval, origin, minimum, axes=None):
1305
+ if (size is not None) and (footprint is not None):
1306
+ warnings.warn("ignoring size because footprint is set",
1307
+ UserWarning, stacklevel=3)
1308
+ if structure is None:
1309
+ if footprint is None:
1310
+ if size is None:
1311
+ raise RuntimeError("no footprint provided")
1312
+ separable = True
1313
+ else:
1314
+ footprint = np.asarray(footprint, dtype=bool)
1315
+ if not footprint.any():
1316
+ raise ValueError("All-zero footprint is not supported.")
1317
+ if footprint.all():
1318
+ size = footprint.shape
1319
+ footprint = None
1320
+ separable = True
1321
+ else:
1322
+ separable = False
1323
+ else:
1324
+ structure = np.asarray(structure, dtype=np.float64)
1325
+ separable = False
1326
+ if footprint is None:
1327
+ footprint = np.ones(structure.shape, bool)
1328
+ else:
1329
+ footprint = np.asarray(footprint, dtype=bool)
1330
+ input = np.asarray(input)
1331
+ if np.iscomplexobj(input):
1332
+ raise TypeError("Complex type not supported")
1333
+ output = _ni_support._get_output(output, input)
1334
+ temp_needed = np.may_share_memory(input, output)
1335
+ if temp_needed:
1336
+ # input and output arrays cannot share memory
1337
+ temp = output
1338
+ output = _ni_support._get_output(output.dtype, input)
1339
+ axes = _ni_support._check_axes(axes, input.ndim)
1340
+ num_axes = len(axes)
1341
+ if separable:
1342
+ origins = _ni_support._normalize_sequence(origin, num_axes)
1343
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1344
+ modes = _ni_support._normalize_sequence(mode, num_axes)
1345
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
1346
+ for ii in range(len(axes)) if sizes[ii] > 1]
1347
+ if minimum:
1348
+ filter_ = minimum_filter1d
1349
+ else:
1350
+ filter_ = maximum_filter1d
1351
+ if len(axes) > 0:
1352
+ for axis, size, origin, mode in axes:
1353
+ filter_(input, int(size), axis, output, mode, cval, origin)
1354
+ input = output
1355
+ else:
1356
+ output[...] = input[...]
1357
+ else:
1358
+ # expand origins and footprint if num_axes < input.ndim
1359
+ footprint = _expand_footprint(input.ndim, axes, footprint)
1360
+ origins = _expand_origin(input.ndim, axes, origin)
1361
+
1362
+ fshape = [ii for ii in footprint.shape if ii > 0]
1363
+ if len(fshape) != input.ndim:
1364
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
1365
+ f"len(axes) ({len(axes)})")
1366
+ for origin, lenf in zip(origins, fshape):
1367
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
1368
+ raise ValueError("invalid origin")
1369
+ if not footprint.flags.contiguous:
1370
+ footprint = footprint.copy()
1371
+ if structure is not None:
1372
+ if len(structure.shape) != num_axes:
1373
+ raise RuntimeError("structure array has incorrect shape")
1374
+ if num_axes != structure.ndim:
1375
+ structure = np.expand_dims(
1376
+ structure,
1377
+ tuple(ax for ax in range(structure.ndim) if ax not in axes)
1378
+ )
1379
+ if not structure.flags.contiguous:
1380
+ structure = structure.copy()
1381
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
1382
+ raise RuntimeError(
1383
+ "A sequence of modes is not supported for non-separable "
1384
+ "footprints")
1385
+ mode = _ni_support._extend_mode_to_code(mode)
1386
+ _nd_image.min_or_max_filter(input, footprint, structure, output,
1387
+ mode, cval, origins, minimum)
1388
+ if temp_needed:
1389
+ temp[...] = output
1390
+ output = temp
1391
+ return output
1392
+
1393
+
1394
+ @_ni_docstrings.docfiller
1395
+ def minimum_filter(input, size=None, footprint=None, output=None,
1396
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
1397
+ """Calculate a multidimensional minimum filter.
1398
+
1399
+ Parameters
1400
+ ----------
1401
+ %(input)s
1402
+ %(size_foot)s
1403
+ %(output)s
1404
+ %(mode_multiple)s
1405
+ %(cval)s
1406
+ %(origin_multiple)s
1407
+ axes : tuple of int or None, optional
1408
+ If None, `input` is filtered along all axes. Otherwise,
1409
+ `input` is filtered along the specified axes. When `axes` is
1410
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1411
+ must match the length of `axes`. The ith entry in any of these tuples
1412
+ corresponds to the ith entry in `axes`.
1413
+
1414
+ Returns
1415
+ -------
1416
+ minimum_filter : ndarray
1417
+ Filtered array. Has the same shape as `input`.
1418
+
1419
+ Notes
1420
+ -----
1421
+ A sequence of modes (one per axis) is only supported when the footprint is
1422
+ separable. Otherwise, a single mode string must be provided.
1423
+
1424
+ Examples
1425
+ --------
1426
+ >>> from scipy import ndimage, datasets
1427
+ >>> import matplotlib.pyplot as plt
1428
+ >>> fig = plt.figure()
1429
+ >>> plt.gray() # show the filtered result in grayscale
1430
+ >>> ax1 = fig.add_subplot(121) # left side
1431
+ >>> ax2 = fig.add_subplot(122) # right side
1432
+ >>> ascent = datasets.ascent()
1433
+ >>> result = ndimage.minimum_filter(ascent, size=20)
1434
+ >>> ax1.imshow(ascent)
1435
+ >>> ax2.imshow(result)
1436
+ >>> plt.show()
1437
+ """
1438
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
1439
+ cval, origin, 1, axes)
1440
+
1441
+
1442
+ @_ni_docstrings.docfiller
1443
+ def maximum_filter(input, size=None, footprint=None, output=None,
1444
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
1445
+ """Calculate a multidimensional maximum filter.
1446
+
1447
+ Parameters
1448
+ ----------
1449
+ %(input)s
1450
+ %(size_foot)s
1451
+ %(output)s
1452
+ %(mode_multiple)s
1453
+ %(cval)s
1454
+ %(origin_multiple)s
1455
+ axes : tuple of int or None, optional
1456
+ If None, `input` is filtered along all axes. Otherwise,
1457
+ `input` is filtered along the specified axes. When `axes` is
1458
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1459
+ must match the length of `axes`. The ith entry in any of these tuples
1460
+ corresponds to the ith entry in `axes`.
1461
+
1462
+ Returns
1463
+ -------
1464
+ maximum_filter : ndarray
1465
+ Filtered array. Has the same shape as `input`.
1466
+
1467
+ Notes
1468
+ -----
1469
+ A sequence of modes (one per axis) is only supported when the footprint is
1470
+ separable. Otherwise, a single mode string must be provided.
1471
+
1472
+ Examples
1473
+ --------
1474
+ >>> from scipy import ndimage, datasets
1475
+ >>> import matplotlib.pyplot as plt
1476
+ >>> fig = plt.figure()
1477
+ >>> plt.gray() # show the filtered result in grayscale
1478
+ >>> ax1 = fig.add_subplot(121) # left side
1479
+ >>> ax2 = fig.add_subplot(122) # right side
1480
+ >>> ascent = datasets.ascent()
1481
+ >>> result = ndimage.maximum_filter(ascent, size=20)
1482
+ >>> ax1.imshow(ascent)
1483
+ >>> ax2.imshow(result)
1484
+ >>> plt.show()
1485
+ """
1486
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
1487
+ cval, origin, 0, axes)
1488
+
1489
+
1490
+ @_ni_docstrings.docfiller
1491
+ def _rank_filter(input, rank, size=None, footprint=None, output=None,
1492
+ mode="reflect", cval=0.0, origin=0, operation='rank',
1493
+ axes=None):
1494
+ if (size is not None) and (footprint is not None):
1495
+ warnings.warn("ignoring size because footprint is set",
1496
+ UserWarning, stacklevel=3)
1497
+ input = np.asarray(input)
1498
+ if np.iscomplexobj(input):
1499
+ raise TypeError('Complex type not supported')
1500
+ axes = _ni_support._check_axes(axes, input.ndim)
1501
+ num_axes = len(axes)
1502
+ if footprint is None:
1503
+ if size is None:
1504
+ raise RuntimeError("no footprint or filter size provided")
1505
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1506
+ footprint = np.ones(sizes, dtype=bool)
1507
+ else:
1508
+ footprint = np.asarray(footprint, dtype=bool)
1509
+ # expand origins, footprint and modes if num_axes < input.ndim
1510
+ footprint = _expand_footprint(input.ndim, axes, footprint)
1511
+ origins = _expand_origin(input.ndim, axes, origin)
1512
+ mode = _expand_mode(input.ndim, axes, mode)
1513
+
1514
+ fshape = [ii for ii in footprint.shape if ii > 0]
1515
+ if len(fshape) != input.ndim:
1516
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
1517
+ f"len(axes) ({len(axes)})")
1518
+ for origin, lenf in zip(origins, fshape):
1519
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
1520
+ raise ValueError('invalid origin')
1521
+ if not footprint.flags.contiguous:
1522
+ footprint = footprint.copy()
1523
+ filter_size = np.where(footprint, 1, 0).sum()
1524
+ if operation == 'median':
1525
+ rank = filter_size // 2
1526
+ elif operation == 'percentile':
1527
+ percentile = rank
1528
+ if percentile < 0.0:
1529
+ percentile += 100.0
1530
+ if percentile < 0 or percentile > 100:
1531
+ raise RuntimeError('invalid percentile')
1532
+ if percentile == 100.0:
1533
+ rank = filter_size - 1
1534
+ else:
1535
+ rank = int(float(filter_size) * percentile / 100.0)
1536
+ if rank < 0:
1537
+ rank += filter_size
1538
+ if rank < 0 or rank >= filter_size:
1539
+ raise RuntimeError('rank not within filter footprint size')
1540
+ if rank == 0:
1541
+ return minimum_filter(input, None, footprint, output, mode, cval,
1542
+ origins, axes=None)
1543
+ elif rank == filter_size - 1:
1544
+ return maximum_filter(input, None, footprint, output, mode, cval,
1545
+ origins, axes=None)
1546
+ else:
1547
+ output = _ni_support._get_output(output, input)
1548
+ temp_needed = np.may_share_memory(input, output)
1549
+ if temp_needed:
1550
+ # input and output arrays cannot share memory
1551
+ temp = output
1552
+ output = _ni_support._get_output(output.dtype, input)
1553
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
1554
+ raise RuntimeError(
1555
+ "A sequence of modes is not supported by non-separable rank "
1556
+ "filters")
1557
+ mode = _ni_support._extend_mode_to_code(mode, is_filter=True)
1558
+ if input.ndim == 1:
1559
+ if input.dtype in (np.int64, np.float64, np.float32):
1560
+ x = input
1561
+ x_out = output
1562
+ elif input.dtype == np.float16:
1563
+ x = input.astype('float32')
1564
+ x_out = np.empty(x.shape, dtype='float32')
1565
+ elif np.result_type(input, np.int64) == np.int64:
1566
+ x = input.astype('int64')
1567
+ x_out = np.empty(x.shape, dtype='int64')
1568
+ elif input.dtype.kind in 'biu':
1569
+ # cast any other boolean, integer or unsigned type to int64
1570
+ x = input.astype('int64')
1571
+ x_out = np.empty(x.shape, dtype='int64')
1572
+ else:
1573
+ raise RuntimeError('Unsupported array type')
1574
+ cval = x.dtype.type(cval)
1575
+ _rank_filter_1d.rank_filter(x, rank, footprint.size, x_out, mode, cval,
1576
+ origin)
1577
+ if input.dtype not in (np.int64, np.float64, np.float32):
1578
+ np.copyto(output, x_out, casting='unsafe')
1579
+ else:
1580
+ _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins)
1581
+ if temp_needed:
1582
+ temp[...] = output
1583
+ output = temp
1584
+ return output
1585
+
1586
+
1587
+ @_ni_docstrings.docfiller
1588
+ def rank_filter(input, rank, size=None, footprint=None, output=None,
1589
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
1590
+ """Calculate a multidimensional rank filter.
1591
+
1592
+ Parameters
1593
+ ----------
1594
+ %(input)s
1595
+ rank : int
1596
+ The rank parameter may be less than zero, i.e., rank = -1
1597
+ indicates the largest element.
1598
+ %(size_foot)s
1599
+ %(output)s
1600
+ %(mode_reflect)s
1601
+ %(cval)s
1602
+ %(origin_multiple)s
1603
+ axes : tuple of int or None, optional
1604
+ If None, `input` is filtered along all axes. Otherwise,
1605
+ `input` is filtered along the specified axes. When `axes` is
1606
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1607
+ must match the length of `axes`. The ith entry in any of these tuples
1608
+ corresponds to the ith entry in `axes`.
1609
+
1610
+ Returns
1611
+ -------
1612
+ rank_filter : ndarray
1613
+ Filtered array. Has the same shape as `input`.
1614
+
1615
+ Examples
1616
+ --------
1617
+ >>> from scipy import ndimage, datasets
1618
+ >>> import matplotlib.pyplot as plt
1619
+ >>> fig = plt.figure()
1620
+ >>> plt.gray() # show the filtered result in grayscale
1621
+ >>> ax1 = fig.add_subplot(121) # left side
1622
+ >>> ax2 = fig.add_subplot(122) # right side
1623
+ >>> ascent = datasets.ascent()
1624
+ >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
1625
+ >>> ax1.imshow(ascent)
1626
+ >>> ax2.imshow(result)
1627
+ >>> plt.show()
1628
+ """
1629
+ rank = operator.index(rank)
1630
+ return _rank_filter(input, rank, size, footprint, output, mode, cval,
1631
+ origin, 'rank', axes=axes)
1632
+
1633
+
1634
+ @_ni_docstrings.docfiller
1635
+ def median_filter(input, size=None, footprint=None, output=None,
1636
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
1637
+ """
1638
+ Calculate a multidimensional median filter.
1639
+
1640
+ Parameters
1641
+ ----------
1642
+ %(input)s
1643
+ %(size_foot)s
1644
+ %(output)s
1645
+ %(mode_reflect)s
1646
+ %(cval)s
1647
+ %(origin_multiple)s
1648
+ axes : tuple of int or None, optional
1649
+ If None, `input` is filtered along all axes. Otherwise,
1650
+ `input` is filtered along the specified axes. When `axes` is
1651
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1652
+ must match the length of `axes`. The ith entry in any of these tuples
1653
+ corresponds to the ith entry in `axes`.
1654
+
1655
+ Returns
1656
+ -------
1657
+ median_filter : ndarray
1658
+ Filtered array. Has the same shape as `input`.
1659
+
1660
+ See Also
1661
+ --------
1662
+ scipy.signal.medfilt2d
1663
+
1664
+ Notes
1665
+ -----
1666
+ For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes
1667
+ the specialised function `scipy.signal.medfilt2d` may be faster. It is
1668
+ however limited to constant mode with ``cval=0``.
1669
+
1670
+ Examples
1671
+ --------
1672
+ >>> from scipy import ndimage, datasets
1673
+ >>> import matplotlib.pyplot as plt
1674
+ >>> fig = plt.figure()
1675
+ >>> plt.gray() # show the filtered result in grayscale
1676
+ >>> ax1 = fig.add_subplot(121) # left side
1677
+ >>> ax2 = fig.add_subplot(122) # right side
1678
+ >>> ascent = datasets.ascent()
1679
+ >>> result = ndimage.median_filter(ascent, size=20)
1680
+ >>> ax1.imshow(ascent)
1681
+ >>> ax2.imshow(result)
1682
+ >>> plt.show()
1683
+ """
1684
+ return _rank_filter(input, 0, size, footprint, output, mode, cval,
1685
+ origin, 'median', axes=axes)
1686
+
1687
+
1688
+ @_ni_docstrings.docfiller
1689
+ def percentile_filter(input, percentile, size=None, footprint=None,
1690
+ output=None, mode="reflect", cval=0.0, origin=0, *,
1691
+ axes=None):
1692
+ """Calculate a multidimensional percentile filter.
1693
+
1694
+ Parameters
1695
+ ----------
1696
+ %(input)s
1697
+ percentile : scalar
1698
+ The percentile parameter may be less than zero, i.e.,
1699
+ percentile = -20 equals percentile = 80
1700
+ %(size_foot)s
1701
+ %(output)s
1702
+ %(mode_reflect)s
1703
+ %(cval)s
1704
+ %(origin_multiple)s
1705
+ axes : tuple of int or None, optional
1706
+ If None, `input` is filtered along all axes. Otherwise,
1707
+ `input` is filtered along the specified axes. When `axes` is
1708
+ specified, any tuples used for `size`, `origin`, and/or `mode`
1709
+ must match the length of `axes`. The ith entry in any of these tuples
1710
+ corresponds to the ith entry in `axes`.
1711
+
1712
+ Returns
1713
+ -------
1714
+ percentile_filter : ndarray
1715
+ Filtered array. Has the same shape as `input`.
1716
+
1717
+ Examples
1718
+ --------
1719
+ >>> from scipy import ndimage, datasets
1720
+ >>> import matplotlib.pyplot as plt
1721
+ >>> fig = plt.figure()
1722
+ >>> plt.gray() # show the filtered result in grayscale
1723
+ >>> ax1 = fig.add_subplot(121) # left side
1724
+ >>> ax2 = fig.add_subplot(122) # right side
1725
+ >>> ascent = datasets.ascent()
1726
+ >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
1727
+ >>> ax1.imshow(ascent)
1728
+ >>> ax2.imshow(result)
1729
+ >>> plt.show()
1730
+ """
1731
+ return _rank_filter(input, percentile, size, footprint, output, mode,
1732
+ cval, origin, 'percentile', axes=axes)
1733
+
1734
+
1735
+ @_ni_docstrings.docfiller
1736
+ def generic_filter1d(input, function, filter_size, axis=-1,
1737
+ output=None, mode="reflect", cval=0.0, origin=0,
1738
+ extra_arguments=(), extra_keywords=None):
1739
+ """Calculate a 1-D filter along the given axis.
1740
+
1741
+ `generic_filter1d` iterates over the lines of the array, calling the
1742
+ given function at each line. The arguments of the line are the
1743
+ input line, and the output line. The input and output lines are 1-D
1744
+ double arrays. The input line is extended appropriately according
1745
+ to the filter size and origin. The output line must be modified
1746
+ in-place with the result.
1747
+
1748
+ Parameters
1749
+ ----------
1750
+ %(input)s
1751
+ function : {callable, scipy.LowLevelCallable}
1752
+ Function to apply along given axis.
1753
+ filter_size : scalar
1754
+ Length of the filter.
1755
+ %(axis)s
1756
+ %(output)s
1757
+ %(mode_reflect)s
1758
+ %(cval)s
1759
+ %(origin)s
1760
+ %(extra_arguments)s
1761
+ %(extra_keywords)s
1762
+
1763
+ Returns
1764
+ -------
1765
+ generic_filter1d : ndarray
1766
+ Filtered array. Has the same shape as `input`.
1767
+
1768
+ Notes
1769
+ -----
1770
+ This function also accepts low-level callback functions with one of
1771
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
1772
+
1773
+ .. code:: c
1774
+
1775
+ int function(double *input_line, npy_intp input_length,
1776
+ double *output_line, npy_intp output_length,
1777
+ void *user_data)
1778
+ int function(double *input_line, intptr_t input_length,
1779
+ double *output_line, intptr_t output_length,
1780
+ void *user_data)
1781
+
1782
+ The calling function iterates over the lines of the input and output
1783
+ arrays, calling the callback function at each line. The current line
1784
+ is extended according to the border conditions set by the calling
1785
+ function, and the result is copied into the array that is passed
1786
+ through ``input_line``. The length of the input line (after extension)
1787
+ is passed through ``input_length``. The callback function should apply
1788
+ the filter and store the result in the array passed through
1789
+ ``output_line``. The length of the output line is passed through
1790
+ ``output_length``. ``user_data`` is the data pointer provided
1791
+ to `scipy.LowLevelCallable` as-is.
1792
+
1793
+ The callback function must return an integer error status that is zero
1794
+ if something went wrong and one otherwise. If an error occurs, you should
1795
+ normally set the python error status with an informative message
1796
+ before returning, otherwise a default error message is set by the
1797
+ calling function.
1798
+
1799
+ In addition, some other low-level function pointer specifications
1800
+ are accepted, but these are for backward compatibility only and should
1801
+ not be used in new code.
1802
+
1803
+ """
1804
+ if extra_keywords is None:
1805
+ extra_keywords = {}
1806
+ input = np.asarray(input)
1807
+ if np.iscomplexobj(input):
1808
+ raise TypeError('Complex type not supported')
1809
+ output = _ni_support._get_output(output, input)
1810
+ if filter_size < 1:
1811
+ raise RuntimeError('invalid filter size')
1812
+ axis = normalize_axis_index(axis, input.ndim)
1813
+ if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >=
1814
+ filter_size):
1815
+ raise ValueError('invalid origin')
1816
+ mode = _ni_support._extend_mode_to_code(mode)
1817
+ _nd_image.generic_filter1d(input, function, filter_size, axis, output,
1818
+ mode, cval, origin, extra_arguments,
1819
+ extra_keywords)
1820
+ return output
1821
+
1822
+
1823
+ @_ni_docstrings.docfiller
1824
+ def generic_filter(input, function, size=None, footprint=None,
1825
+ output=None, mode="reflect", cval=0.0, origin=0,
1826
+ extra_arguments=(), extra_keywords=None, *, axes=None):
1827
+ """Calculate a multidimensional filter using the given function.
1828
+
1829
+ At each element the provided function is called. The input values
1830
+ within the filter footprint at that element are passed to the function
1831
+ as a 1-D array of double values.
1832
+
1833
+ Parameters
1834
+ ----------
1835
+ %(input)s
1836
+ function : {callable, scipy.LowLevelCallable}
1837
+ Function to apply at each element.
1838
+ %(size_foot)s
1839
+ %(output)s
1840
+ %(mode_reflect)s
1841
+ %(cval)s
1842
+ %(origin_multiple)s
1843
+ %(extra_arguments)s
1844
+ %(extra_keywords)s
1845
+ axes : tuple of int or None, optional
1846
+ If None, `input` is filtered along all axes. Otherwise,
1847
+ `input` is filtered along the specified axes. When `axes` is
1848
+ specified, any tuples used for `size` or `origin` must match the length
1849
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
1850
+ entry in `axes`.
1851
+
1852
+ Returns
1853
+ -------
1854
+ generic_filter : ndarray
1855
+ Filtered array. Has the same shape as `input`.
1856
+
1857
+ Notes
1858
+ -----
1859
+ This function also accepts low-level callback functions with one of
1860
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
1861
+
1862
+ .. code:: c
1863
+
1864
+ int callback(double *buffer, npy_intp filter_size,
1865
+ double *return_value, void *user_data)
1866
+ int callback(double *buffer, intptr_t filter_size,
1867
+ double *return_value, void *user_data)
1868
+
1869
+ The calling function iterates over the elements of the input and
1870
+ output arrays, calling the callback function at each element. The
1871
+ elements within the footprint of the filter at the current element are
1872
+ passed through the ``buffer`` parameter, and the number of elements
1873
+ within the footprint through ``filter_size``. The calculated value is
1874
+ returned in ``return_value``. ``user_data`` is the data pointer provided
1875
+ to `scipy.LowLevelCallable` as-is.
1876
+
1877
+ The callback function must return an integer error status that is zero
1878
+ if something went wrong and one otherwise. If an error occurs, you should
1879
+ normally set the python error status with an informative message
1880
+ before returning, otherwise a default error message is set by the
1881
+ calling function.
1882
+
1883
+ In addition, some other low-level function pointer specifications
1884
+ are accepted, but these are for backward compatibility only and should
1885
+ not be used in new code.
1886
+
1887
+ Examples
1888
+ --------
1889
+ Import the necessary modules and load the example image used for
1890
+ filtering.
1891
+
1892
+ >>> import numpy as np
1893
+ >>> from scipy import datasets
1894
+ >>> from scipy.ndimage import zoom, generic_filter
1895
+ >>> import matplotlib.pyplot as plt
1896
+ >>> ascent = zoom(datasets.ascent(), 0.5)
1897
+
1898
+ Compute a maximum filter with kernel size 5 by passing a simple NumPy
1899
+ aggregation function as argument to `function`.
1900
+
1901
+ >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5])
1902
+
1903
+ While a maximum filter could also directly be obtained using
1904
+ `maximum_filter`, `generic_filter` allows generic Python function or
1905
+ `scipy.LowLevelCallable` to be used as a filter. Here, we compute the
1906
+ range between maximum and minimum value as an example for a kernel size
1907
+ of 5.
1908
+
1909
+ >>> def custom_filter(image):
1910
+ ... return np.amax(image) - np.amin(image)
1911
+ >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5])
1912
+
1913
+ Plot the original and filtered images.
1914
+
1915
+ >>> fig, axes = plt.subplots(3, 1, figsize=(3, 9))
1916
+ >>> plt.gray() # show the filtered result in grayscale
1917
+ >>> top, middle, bottom = axes
1918
+ >>> for ax in axes:
1919
+ ... ax.set_axis_off() # remove coordinate system
1920
+ >>> top.imshow(ascent)
1921
+ >>> top.set_title("Original image")
1922
+ >>> middle.imshow(maximum_filter_result)
1923
+ >>> middle.set_title("Maximum filter, Kernel: 5x5")
1924
+ >>> bottom.imshow(custom_filter_result)
1925
+ >>> bottom.set_title("Custom filter, Kernel: 5x5")
1926
+ >>> fig.tight_layout()
1927
+
1928
+ """
1929
+ if (size is not None) and (footprint is not None):
1930
+ warnings.warn("ignoring size because footprint is set",
1931
+ UserWarning, stacklevel=2)
1932
+ if extra_keywords is None:
1933
+ extra_keywords = {}
1934
+ input = np.asarray(input)
1935
+ if np.iscomplexobj(input):
1936
+ raise TypeError('Complex type not supported')
1937
+ axes = _ni_support._check_axes(axes, input.ndim)
1938
+ num_axes = len(axes)
1939
+ if footprint is None:
1940
+ if size is None:
1941
+ raise RuntimeError("no footprint or filter size provided")
1942
+ sizes = _ni_support._normalize_sequence(size, num_axes)
1943
+ footprint = np.ones(sizes, dtype=bool)
1944
+ else:
1945
+ footprint = np.asarray(footprint, dtype=bool)
1946
+
1947
+ # expand origins, footprint if num_axes < input.ndim
1948
+ footprint = _expand_footprint(input.ndim, axes, footprint)
1949
+ origins = _expand_origin(input.ndim, axes, origin)
1950
+
1951
+ fshape = [ii for ii in footprint.shape if ii > 0]
1952
+ if len(fshape) != input.ndim:
1953
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) "
1954
+ f"must match len(axes) ({num_axes})")
1955
+ for origin, lenf in zip(origins, fshape):
1956
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
1957
+ raise ValueError('invalid origin')
1958
+ if not footprint.flags.contiguous:
1959
+ footprint = footprint.copy()
1960
+ output = _ni_support._get_output(output, input)
1961
+
1962
+ mode = _ni_support._extend_mode_to_code(mode)
1963
+ _nd_image.generic_filter(input, function, footprint, output, mode,
1964
+ cval, origins, extra_arguments, extra_keywords)
1965
+ return output
shared/package-files/e8/e824710623cecb1ffe9dde0ebba059cb75caaad8a04ea01bf7205804e4f383a9/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & view_copy_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef size);
21
+ TORCH_API at::Tensor & view_copy_outf(const at::Tensor & self, at::IntArrayRef size, at::Tensor & out);
22
+ TORCH_API at::Tensor & view_copy_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef size);
23
+ TORCH_API at::Tensor & view_copy_symint_outf(const at::Tensor & self, c10::SymIntArrayRef size, at::Tensor & out);
24
+ TORCH_API at::Tensor & view_copy_out(at::Tensor & out, const at::Tensor & self, at::ScalarType dtype);
25
+ TORCH_API at::Tensor & view_copy_outf(const at::Tensor & self, at::ScalarType dtype, at::Tensor & out);
26
+
27
+ } // namespace compositeexplicitautograd
28
+ } // namespace at
shared/package-files/e8/e82e72e88701c0d0b06cca36c8a4063b351e9f685d9a218ee582c29bf939817c/blob ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <array>
5
+ #include <cstddef>
6
+ #include <cstdint>
7
+ #include <forward_list>
8
+ #include <new>
9
+ #include <utility>
10
+
11
+ #include <c10/macros/Macros.h>
12
+ #include <c10/util/ArrayRef.h>
13
+ #include <c10/util/Exception.h>
14
+
15
+ namespace torch {
16
+ namespace profiler {
17
+ namespace impl {
18
+
19
+ // ============================================================================
20
+ // == AppendOnlyList ==========================================================
21
+ // ============================================================================
22
+ // During profiling, we have a very predictable access pattern: we only
23
+ // append to the end of the container. We can specialize and outperform both
24
+ // std::vector (which must realloc) and std::deque (which performs a double
25
+ // indirection), and this class of operation is sufficiently important to the
26
+ // profiling hot path to warrant specializing:
27
+ // https://godbolt.org/z/rTjozf1c4
28
+ // https://quick-bench.com/q/mmfuu71ogwaiULDCJyHdKnHZms4 (Prototype #1,
29
+ // int) https://quick-bench.com/q/5vWDW6jjdXVdoffev2zst8D09no (Prototype
30
+ // #1, int pair) https://quick-bench.com/q/IfEkfAQMeJSNBA52xtMP6Agcl-Q
31
+ // (Prototype #2, int pair)
32
+ // https://quick-bench.com/q/wJV2lKmuXL4XyGJzcI5hs4gEHFg (Prototype #3, int
33
+ // pair) https://quick-bench.com/q/xiO8ZaBEkYRYUA9dFrMuPLlW9fo (Full impl,
34
+ // int pair)
35
+ // AppendOnlyList has 2x lower emplace overhead compared to more generic STL
36
+ // containers.
37
+ //
38
+ // The optimal value of `ChunkSize` will vary by use case, but testing shows
39
+ // that a value of 1024 does a good job amortizing the `malloc` cost of growth.
40
+ // Performance drops off for larger values, so testing on a case-by-case basis
41
+ // is recommended if performance is absolutely critical.
42
+
43
+ template <
44
+ typename T,
45
+ size_t ChunkSize,
46
+ template <typename U, size_t N> class block_t = std::array>
47
+ class AppendOnlyList {
48
+ public:
49
+ using array_t = block_t<T, ChunkSize>;
50
+ static_assert(
51
+ std::is_base_of_v<std::array<T, ChunkSize>, array_t>,
52
+ "AppendOnlyList expects raw low level pointer storage.");
53
+ static_assert(ChunkSize > 0, "Block cannot be empty.");
54
+
55
+ AppendOnlyList() : buffer_last_{buffer_.before_begin()} {}
56
+ AppendOnlyList(const AppendOnlyList&) = delete;
57
+ AppendOnlyList& operator=(const AppendOnlyList&) = delete;
58
+
59
+ size_t size() const {
60
+ return n_blocks_ * ChunkSize - (size_t)(end_ - next_);
61
+ }
62
+
63
+ template <class... Args>
64
+ T* emplace_back(Args&&... args) {
65
+ maybe_grow();
66
+ if constexpr (
67
+ std::is_trivially_destructible_v<T> &&
68
+ std::is_trivially_destructible_v<array_t>) {
69
+ ::new ((void*)next_) T{std::forward<Args>(args)...};
70
+ } else {
71
+ *next_ = T{std::forward<Args>(args)...};
72
+ }
73
+ return next_++;
74
+ }
75
+
76
+ template <typename T0>
77
+ typename std::enable_if<
78
+ std::is_same<T0, T>::value && std::is_trivially_copyable<T>::value>::type
79
+ copy(c10::ArrayRef<T0> src) {
80
+ size_t n = src.size();
81
+ if (C10_UNLIKELY(n == 0)) {
82
+ return;
83
+ }
84
+ maybe_grow();
85
+ if (C10_LIKELY(next_ && (next_ + n <= end_))) {
86
+ std::memcpy((void*)next_, (void*)src.begin(), n * sizeof(T0));
87
+ next_ += n;
88
+ } else {
89
+ // We could chunk this into several `memcpy`s, but because we expect this
90
+ // fallback to be infrequent (n << ChunkSize) the performance impact is
91
+ // negligible.
92
+ for (auto i : src) {
93
+ emplace_back(i);
94
+ }
95
+ }
96
+ }
97
+
98
+ void clear() {
99
+ buffer_.clear();
100
+ buffer_last_ = buffer_.before_begin();
101
+ n_blocks_ = 0;
102
+ next_ = nullptr;
103
+ end_ = nullptr;
104
+ }
105
+
106
+ struct Iterator {
107
+ using iterator_category = std::forward_iterator_tag;
108
+ using difference_type = std::ptrdiff_t;
109
+ using value_type = T;
110
+ using pointer = T*;
111
+ using reference = T&;
112
+
113
+ Iterator(std::forward_list<array_t>& buffer, const size_t size)
114
+ : block_{buffer.begin()}, size_{size} {}
115
+
116
+ // End iterator.
117
+ Iterator() = default;
118
+
119
+ bool exhausted() const {
120
+ return current_ >= size_;
121
+ }
122
+
123
+ reference operator*() const {
124
+ return *current_ptr(/*checked=*/true);
125
+ }
126
+ pointer operator->() {
127
+ return current_ptr(/*checked=*/true);
128
+ }
129
+
130
+ // Prefix increment
131
+ Iterator& operator++() {
132
+ if (!(++current_ % ChunkSize)) {
133
+ block_++;
134
+ }
135
+ return *this;
136
+ }
137
+
138
+ // Postfix increment
139
+ Iterator operator++(int) {
140
+ Iterator tmp = *this;
141
+ ++(*this);
142
+ return tmp;
143
+ }
144
+
145
+ friend bool operator==(const Iterator& a, const Iterator& b) {
146
+ return a.current_ptr() == b.current_ptr();
147
+ }
148
+ friend bool operator!=(const Iterator& a, const Iterator& b) {
149
+ return a.current_ptr() != b.current_ptr();
150
+ }
151
+
152
+ std::pair<array_t*, size_t> address() const {
153
+ if (current_ >= size_) {
154
+ return {nullptr, 0};
155
+ }
156
+ return {&(*block_), current_ % ChunkSize};
157
+ }
158
+
159
+ private:
160
+ T* current_ptr(bool checked = false) const {
161
+ auto a = address();
162
+ if (a.first == nullptr) {
163
+ TORCH_INTERNAL_ASSERT(!checked, "Invalid access on AppendOnlyList.");
164
+ return nullptr;
165
+ }
166
+ return a.first->data() + a.second;
167
+ }
168
+
169
+ typename std::forward_list<array_t>::iterator block_;
170
+ size_t current_{0};
171
+ size_t size_{0};
172
+ };
173
+
174
+ Iterator begin() {
175
+ return Iterator(buffer_, size());
176
+ }
177
+ Iterator end() {
178
+ return Iterator();
179
+ }
180
+ // TODO: cbegin and cend()
181
+
182
+ private:
183
+ void maybe_grow() {
184
+ if (C10_UNLIKELY(next_ == end_)) {
185
+ buffer_last_ = buffer_.emplace_after(buffer_last_);
186
+ n_blocks_++;
187
+ next_ = buffer_last_->data();
188
+ end_ = next_ + ChunkSize;
189
+ }
190
+ }
191
+
192
+ std::forward_list<array_t> buffer_;
193
+
194
+ // We maintain a pointer to the last element of `buffer_` so that we can
195
+ // insert at the end in O(1) time.
196
+ size_t n_blocks_{0};
197
+ T* next_{nullptr};
198
+ T* end_{nullptr};
199
+
200
+ protected:
201
+ typename std::forward_list<array_t>::iterator buffer_last_;
202
+ };
203
+
204
+ } // namespace impl
205
+ } // namespace profiler
206
+ } // namespace torch
shared/package-files/e8/e8326dc8c0e6c22fe084eac3babc956a465013116af8c20a8ae262fc2afb91d3/blob ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from scipy.datasets._registry import registry
2
+ from scipy.datasets._fetchers import data_fetcher
3
+ from scipy.datasets._utils import _clear_cache
4
+ from scipy.datasets import ascent, face, electrocardiogram, download_all
5
+ from numpy.testing import assert_equal, assert_almost_equal
6
+ import os
7
+ from threading import get_ident
8
+ import pytest
9
+
10
+ try:
11
+ import pooch
12
+ except ImportError:
13
+ raise ImportError("Missing optional dependency 'pooch' required "
14
+ "for scipy.datasets module. Please use pip or "
15
+ "conda to install 'pooch'.")
16
+
17
+
18
+ data_dir = data_fetcher.path # type: ignore
19
+
20
+
21
+ def _has_hash(path, expected_hash):
22
+ """Check if the provided path has the expected hash."""
23
+ if not os.path.exists(path):
24
+ return False
25
+ return pooch.file_hash(path) == expected_hash
26
+
27
+
28
+ class TestDatasets:
29
+
30
+ @pytest.fixture(scope='module', autouse=True)
31
+ def test_download_all(self):
32
+ # This fixture requires INTERNET CONNECTION
33
+
34
+ # test_setup phase
35
+ download_all()
36
+
37
+ yield
38
+
39
+ @pytest.mark.fail_slow(10)
40
+ def test_existence_all(self):
41
+ assert len(os.listdir(data_dir)) >= len(registry)
42
+
43
+ def test_ascent(self):
44
+ assert_equal(ascent().shape, (512, 512))
45
+
46
+ # hash check
47
+ assert _has_hash(os.path.join(data_dir, "ascent.dat"),
48
+ registry["ascent.dat"])
49
+
50
+ def test_face(self):
51
+ assert_equal(face().shape, (768, 1024, 3))
52
+
53
+ # hash check
54
+ assert _has_hash(os.path.join(data_dir, "face.dat"),
55
+ registry["face.dat"])
56
+
57
+ def test_electrocardiogram(self):
58
+ # Test shape, dtype and stats of signal
59
+ ecg = electrocardiogram()
60
+ assert_equal(ecg.dtype, float)
61
+ assert_equal(ecg.shape, (108000,))
62
+ assert_almost_equal(ecg.mean(), -0.16510875)
63
+ assert_almost_equal(ecg.std(), 0.5992473991177294)
64
+
65
+ # hash check
66
+ assert _has_hash(os.path.join(data_dir, "ecg.dat"),
67
+ registry["ecg.dat"])
68
+
69
+
70
+ def test_clear_cache(tmp_path):
71
+ # Note: `tmp_path` is a pytest fixture, it handles cleanup
72
+ thread_basepath = tmp_path / str(get_ident())
73
+ thread_basepath.mkdir()
74
+
75
+ dummy_basepath = thread_basepath / "dummy_cache_dir"
76
+ dummy_basepath.mkdir()
77
+
78
+ # Create three dummy dataset files for dummy dataset methods
79
+ dummy_method_map = {}
80
+ for i in range(4):
81
+ dummy_method_map[f"data{i}"] = [f"data{i}.dat"]
82
+ data_filepath = dummy_basepath / f"data{i}.dat"
83
+ data_filepath.write_text("")
84
+
85
+ # clear files associated to single dataset method data0
86
+ # also test callable argument instead of list of callables
87
+ def data0():
88
+ pass
89
+ _clear_cache(datasets=data0, cache_dir=dummy_basepath,
90
+ method_map=dummy_method_map)
91
+ assert not os.path.exists(dummy_basepath/"data0.dat")
92
+
93
+ # clear files associated to multiple dataset methods "data3" and "data4"
94
+ def data1():
95
+ pass
96
+
97
+ def data2():
98
+ pass
99
+ _clear_cache(datasets=[data1, data2], cache_dir=dummy_basepath,
100
+ method_map=dummy_method_map)
101
+ assert not os.path.exists(dummy_basepath/"data1.dat")
102
+ assert not os.path.exists(dummy_basepath/"data2.dat")
103
+
104
+ # clear multiple dataset files "data3_0.dat" and "data3_1.dat"
105
+ # associated with dataset method "data3"
106
+ def data4():
107
+ pass
108
+ # create files
109
+ (dummy_basepath / "data4_0.dat").write_text("")
110
+ (dummy_basepath / "data4_1.dat").write_text("")
111
+
112
+ dummy_method_map["data4"] = ["data4_0.dat", "data4_1.dat"]
113
+ _clear_cache(datasets=[data4], cache_dir=dummy_basepath,
114
+ method_map=dummy_method_map)
115
+ assert not os.path.exists(dummy_basepath/"data4_0.dat")
116
+ assert not os.path.exists(dummy_basepath/"data4_1.dat")
117
+
118
+ # wrong dataset method should raise ValueError since it
119
+ # doesn't exist in the dummy_method_map
120
+ def data5():
121
+ pass
122
+ with pytest.raises(ValueError):
123
+ _clear_cache(datasets=[data5], cache_dir=dummy_basepath,
124
+ method_map=dummy_method_map)
125
+
126
+ # remove all dataset cache
127
+ _clear_cache(datasets=None, cache_dir=dummy_basepath)
128
+ assert not os.path.exists(dummy_basepath)
shared/package-files/e8/e8341442a21a6f654cbf9ae45d1c1586b63fec776b1f094fc6dc3828f96fa3a4/blob ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> _thnn_differentiable_lstm_cell_backward(const c10::optional<at::Tensor> & grad_hy, const c10::optional<at::Tensor> & grad_cy, const at::Tensor & input_gates, const at::Tensor & hidden_gates, const c10::optional<at::Tensor> & input_bias, const c10::optional<at::Tensor> & hidden_bias, const at::Tensor & cx, const at::Tensor & cy);
20
+ } // namespace native
21
+ } // namespace at
shared/package-files/e8/e8355db5428feebe72dd569f397e5295a4e29adc6e4fe3a540a6112c10fe1e71/blob ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Common tests for metaestimators"""
2
+
3
+ import functools
4
+ from contextlib import suppress
5
+ from inspect import signature
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ from sklearn.base import BaseEstimator, is_regressor
11
+ from sklearn.datasets import make_classification
12
+ from sklearn.ensemble import BaggingClassifier
13
+ from sklearn.exceptions import NotFittedError
14
+ from sklearn.feature_extraction.text import TfidfVectorizer
15
+ from sklearn.feature_selection import RFE, RFECV
16
+ from sklearn.linear_model import LogisticRegression, Ridge
17
+ from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
18
+ from sklearn.pipeline import Pipeline, make_pipeline
19
+ from sklearn.preprocessing import MaxAbsScaler, StandardScaler
20
+ from sklearn.semi_supervised import SelfTrainingClassifier
21
+ from sklearn.utils import all_estimators
22
+ from sklearn.utils._test_common.instance_generator import _construct_instances
23
+ from sklearn.utils._testing import SkipTest, set_random_state
24
+ from sklearn.utils.estimator_checks import (
25
+ _enforce_estimator_tags_X,
26
+ _enforce_estimator_tags_y,
27
+ )
28
+ from sklearn.utils.validation import check_is_fitted
29
+
30
+
31
+ class DelegatorData:
32
+ def __init__(
33
+ self,
34
+ name,
35
+ construct,
36
+ skip_methods=(),
37
+ fit_args=make_classification(random_state=0),
38
+ ):
39
+ self.name = name
40
+ self.construct = construct
41
+ self.fit_args = fit_args
42
+ self.skip_methods = skip_methods
43
+
44
+
45
+ # For the following meta estimators we check for the existence of relevant
46
+ # methods only if the sub estimator also contains them. Any methods that
47
+ # are implemented in the meta estimator themselves and are not dependent
48
+ # on the sub estimator are specified in the `skip_methods` parameter.
49
+ DELEGATING_METAESTIMATORS = [
50
+ DelegatorData("Pipeline", lambda est: Pipeline([("est", est)])),
51
+ DelegatorData(
52
+ "GridSearchCV",
53
+ lambda est: GridSearchCV(est, param_grid={"param": [5]}, cv=2),
54
+ skip_methods=["score"],
55
+ ),
56
+ DelegatorData(
57
+ "RandomizedSearchCV",
58
+ lambda est: RandomizedSearchCV(
59
+ est, param_distributions={"param": [5]}, cv=2, n_iter=1
60
+ ),
61
+ skip_methods=["score"],
62
+ ),
63
+ DelegatorData("RFE", RFE, skip_methods=["transform", "inverse_transform"]),
64
+ DelegatorData(
65
+ "RFECV", RFECV, skip_methods=["transform", "inverse_transform", "score"]
66
+ ),
67
+ DelegatorData(
68
+ "BaggingClassifier",
69
+ BaggingClassifier,
70
+ skip_methods=[
71
+ "transform",
72
+ "inverse_transform",
73
+ "score",
74
+ "predict_proba",
75
+ "predict_log_proba",
76
+ "predict",
77
+ ],
78
+ ),
79
+ DelegatorData(
80
+ "SelfTrainingClassifier",
81
+ lambda est: SelfTrainingClassifier(est),
82
+ skip_methods=["transform", "inverse_transform", "predict_proba"],
83
+ ),
84
+ ]
85
+
86
+
87
+ def test_metaestimator_delegation():
88
+ # Ensures specified metaestimators have methods iff subestimator does
89
+ def hides(method):
90
+ @property
91
+ def wrapper(obj):
92
+ if obj.hidden_method == method.__name__:
93
+ raise AttributeError("%r is hidden" % obj.hidden_method)
94
+ return functools.partial(method, obj)
95
+
96
+ return wrapper
97
+
98
+ class SubEstimator(BaseEstimator):
99
+ def __init__(self, param=1, hidden_method=None):
100
+ self.param = param
101
+ self.hidden_method = hidden_method
102
+
103
+ def fit(self, X, y=None, *args, **kwargs):
104
+ self.coef_ = np.arange(X.shape[1])
105
+ self.classes_ = []
106
+ return True
107
+
108
+ def _check_fit(self):
109
+ check_is_fitted(self)
110
+
111
+ @hides
112
+ def inverse_transform(self, X, *args, **kwargs):
113
+ self._check_fit()
114
+ return X
115
+
116
+ @hides
117
+ def transform(self, X, *args, **kwargs):
118
+ self._check_fit()
119
+ return X
120
+
121
+ @hides
122
+ def predict(self, X, *args, **kwargs):
123
+ self._check_fit()
124
+ return np.ones(X.shape[0])
125
+
126
+ @hides
127
+ def predict_proba(self, X, *args, **kwargs):
128
+ self._check_fit()
129
+ return np.ones(X.shape[0])
130
+
131
+ @hides
132
+ def predict_log_proba(self, X, *args, **kwargs):
133
+ self._check_fit()
134
+ return np.ones(X.shape[0])
135
+
136
+ @hides
137
+ def decision_function(self, X, *args, **kwargs):
138
+ self._check_fit()
139
+ return np.ones(X.shape[0])
140
+
141
+ @hides
142
+ def score(self, X, y, *args, **kwargs):
143
+ self._check_fit()
144
+ return 1.0
145
+
146
+ methods = [
147
+ k
148
+ for k in SubEstimator.__dict__.keys()
149
+ if not k.startswith("_") and not k.startswith("fit")
150
+ ]
151
+ methods.sort()
152
+
153
+ for delegator_data in DELEGATING_METAESTIMATORS:
154
+ delegate = SubEstimator()
155
+ delegator = delegator_data.construct(delegate)
156
+ for method in methods:
157
+ if method in delegator_data.skip_methods:
158
+ continue
159
+ assert hasattr(delegate, method)
160
+ assert hasattr(delegator, method), (
161
+ "%s does not have method %r when its delegate does"
162
+ % (
163
+ delegator_data.name,
164
+ method,
165
+ )
166
+ )
167
+ # delegation before fit raises a NotFittedError
168
+ if method == "score":
169
+ with pytest.raises(NotFittedError):
170
+ getattr(delegator, method)(
171
+ delegator_data.fit_args[0], delegator_data.fit_args[1]
172
+ )
173
+ else:
174
+ with pytest.raises(NotFittedError):
175
+ getattr(delegator, method)(delegator_data.fit_args[0])
176
+
177
+ delegator.fit(*delegator_data.fit_args)
178
+ for method in methods:
179
+ if method in delegator_data.skip_methods:
180
+ continue
181
+ # smoke test delegation
182
+ if method == "score":
183
+ getattr(delegator, method)(
184
+ delegator_data.fit_args[0], delegator_data.fit_args[1]
185
+ )
186
+ else:
187
+ getattr(delegator, method)(delegator_data.fit_args[0])
188
+
189
+ for method in methods:
190
+ if method in delegator_data.skip_methods:
191
+ continue
192
+ delegate = SubEstimator(hidden_method=method)
193
+ delegator = delegator_data.construct(delegate)
194
+ assert not hasattr(delegate, method)
195
+ assert not hasattr(delegator, method), (
196
+ "%s has method %r when its delegate does not"
197
+ % (
198
+ delegator_data.name,
199
+ method,
200
+ )
201
+ )
202
+
203
+
204
+ def _get_instance_with_pipeline(meta_estimator, init_params):
205
+ """Given a single meta-estimator instance, generate an instance with a pipeline"""
206
+ if {"estimator", "base_estimator", "regressor"} & init_params:
207
+ if is_regressor(meta_estimator):
208
+ estimator = make_pipeline(TfidfVectorizer(), Ridge())
209
+ param_grid = {"ridge__alpha": [0.1, 1.0]}
210
+ else:
211
+ estimator = make_pipeline(TfidfVectorizer(), LogisticRegression())
212
+ param_grid = {"logisticregression__C": [0.1, 1.0]}
213
+
214
+ if init_params.intersection(
215
+ {"param_grid", "param_distributions"}
216
+ ): # SearchCV estimators
217
+ extra_params = {"n_iter": 2} if "n_iter" in init_params else {}
218
+ return type(meta_estimator)(estimator, param_grid, **extra_params)
219
+ else:
220
+ return type(meta_estimator)(estimator)
221
+
222
+ if "transformer_list" in init_params:
223
+ # FeatureUnion
224
+ transformer_list = [
225
+ ("trans1", make_pipeline(TfidfVectorizer(), MaxAbsScaler())),
226
+ (
227
+ "trans2",
228
+ make_pipeline(TfidfVectorizer(), StandardScaler(with_mean=False)),
229
+ ),
230
+ ]
231
+ return type(meta_estimator)(transformer_list)
232
+
233
+ if "estimators" in init_params:
234
+ # stacking, voting
235
+ if is_regressor(meta_estimator):
236
+ estimator = [
237
+ ("est1", make_pipeline(TfidfVectorizer(), Ridge(alpha=0.1))),
238
+ ("est2", make_pipeline(TfidfVectorizer(), Ridge(alpha=1))),
239
+ ]
240
+ else:
241
+ estimator = [
242
+ (
243
+ "est1",
244
+ make_pipeline(TfidfVectorizer(), LogisticRegression(C=0.1)),
245
+ ),
246
+ ("est2", make_pipeline(TfidfVectorizer(), LogisticRegression(C=1))),
247
+ ]
248
+ return type(meta_estimator)(estimator)
249
+
250
+
251
+ def _generate_meta_estimator_instances_with_pipeline():
252
+ """Generate instances of meta-estimators fed with a pipeline
253
+
254
+ Are considered meta-estimators all estimators accepting one of "estimator",
255
+ "base_estimator" or "estimators".
256
+ """
257
+ print("estimators: ", len(all_estimators()))
258
+ for _, Estimator in sorted(all_estimators()):
259
+ sig = set(signature(Estimator).parameters)
260
+
261
+ print("\n", Estimator.__name__, sig)
262
+ if not sig.intersection(
263
+ {
264
+ "estimator",
265
+ "base_estimator",
266
+ "regressor",
267
+ "transformer_list",
268
+ "estimators",
269
+ }
270
+ ):
271
+ continue
272
+
273
+ with suppress(SkipTest):
274
+ for meta_estimator in _construct_instances(Estimator):
275
+ print(meta_estimator)
276
+ yield _get_instance_with_pipeline(meta_estimator, sig)
277
+
278
+
279
+ # TODO: remove data validation for the following estimators
280
+ # They should be able to work on any data and delegate data validation to
281
+ # their inner estimator(s).
282
+ DATA_VALIDATION_META_ESTIMATORS_TO_IGNORE = [
283
+ "AdaBoostClassifier",
284
+ "AdaBoostRegressor",
285
+ "BaggingClassifier",
286
+ "BaggingRegressor",
287
+ "ClassifierChain", # data validation is necessary
288
+ "FrozenEstimator", # this estimator cannot be tested like others.
289
+ "IterativeImputer",
290
+ "OneVsOneClassifier", # input validation can't be avoided
291
+ "RANSACRegressor",
292
+ "RFE",
293
+ "RFECV",
294
+ "RegressorChain", # data validation is necessary
295
+ "SelfTrainingClassifier",
296
+ "SequentialFeatureSelector", # not applicable (2D data mandatory)
297
+ ]
298
+
299
+ DATA_VALIDATION_META_ESTIMATORS = [
300
+ est
301
+ for est in _generate_meta_estimator_instances_with_pipeline()
302
+ if est.__class__.__name__ not in DATA_VALIDATION_META_ESTIMATORS_TO_IGNORE
303
+ ]
304
+
305
+
306
+ def _get_meta_estimator_id(estimator):
307
+ return estimator.__class__.__name__
308
+
309
+
310
+ @pytest.mark.parametrize(
311
+ "estimator", DATA_VALIDATION_META_ESTIMATORS, ids=_get_meta_estimator_id
312
+ )
313
+ def test_meta_estimators_delegate_data_validation(estimator):
314
+ # Check that meta-estimators delegate data validation to the inner
315
+ # estimator(s).
316
+ rng = np.random.RandomState(0)
317
+ set_random_state(estimator)
318
+
319
+ n_samples = 30
320
+ X = rng.choice(np.array(["aa", "bb", "cc"], dtype=object), size=n_samples)
321
+
322
+ if is_regressor(estimator):
323
+ y = rng.normal(size=n_samples)
324
+ else:
325
+ y = rng.randint(3, size=n_samples)
326
+
327
+ # We convert to lists to make sure it works on array-like
328
+ X = _enforce_estimator_tags_X(estimator, X).tolist()
329
+ y = _enforce_estimator_tags_y(estimator, y).tolist()
330
+
331
+ # Calling fit should not raise any data validation exception since X is a
332
+ # valid input datastructure for the first step of the pipeline passed as
333
+ # base estimator to the meta estimator.
334
+ estimator.fit(X, y)
335
+
336
+ # n_features_in_ should not be defined since data is not tabular data.
337
+ assert not hasattr(estimator, "n_features_in_")
shared/package-files/e8/e839c74603a302a4c72f60d7d9b1880e797b388481b35d2593416b425a99c186/blob ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cross-validation classes for GAM
3
+
4
+ Author: Luca Puggini
5
+
6
+ """
7
+
8
+ from statsmodels.compat.python import with_metaclass
9
+
10
+ from abc import ABCMeta, abstractmethod
11
+ import itertools
12
+
13
+ import numpy as np
14
+
15
+ from statsmodels.gam.smooth_basis import GenericSmoothers, UnivariateGenericSmoother
16
+
17
+
18
+ class BaseCV(with_metaclass(ABCMeta)):
19
+ """
20
+ Base class for cross validation over a given model
21
+
22
+ Computes the cross validation error of a given model. All the cross
23
+ validation classes can be derived from this one (e.g., GamCV, LassoCV,...)
24
+
25
+ Parameters
26
+ ----------
27
+ cv_iterator : instance of cross-validation iterator
28
+ Iterator used to split the data into train and test indices.
29
+ endog : ndarray
30
+ dependent (response) variable of the model
31
+ exog : ndarray
32
+ design matrix, used only to determine the number of observations
33
+ passed to ``cv_iterator.split``
34
+
35
+ Attributes
36
+ ----------
37
+ cv_iterator : instance of cross-validation iterator
38
+ Iterator used to split the data into train and test indices.
39
+ endog : ndarray
40
+ dependent (response) variable of the model
41
+ exog : ndarray
42
+ design matrix, used only to determine the number of observations
43
+ passed to ``cv_iterator.split``
44
+ train_test_cv_indices : generator
45
+ generator of (train_index, test_index) pairs produced by
46
+ ``cv_iterator.split``
47
+ """
48
+
49
+ def __init__(self, cv_iterator, endog, exog):
50
+ self.cv_iterator = cv_iterator
51
+ self.exog = exog
52
+ self.endog = endog
53
+ # TODO: cv_iterator.split only needs nobs from endog or exog
54
+ self.train_test_cv_indices = self.cv_iterator.split(
55
+ self.exog, self.endog, label=None
56
+ )
57
+
58
+ def fit(self, **kwargs):
59
+ """
60
+ Compute the cross validation error over all train/test splits
61
+
62
+ Parameters
63
+ ----------
64
+ **kwargs
65
+ Keyword arguments passed to the ``fit`` method of the
66
+ cross-validated model.
67
+
68
+ Returns
69
+ -------
70
+ cv_err : ndarray
71
+ array of the errors computed on each test fold
72
+ """
73
+ cv_err = []
74
+
75
+ for train_index, test_index in self.train_test_cv_indices:
76
+ cv_err.append(self._error(train_index, test_index, **kwargs))
77
+
78
+ return np.array(cv_err)
79
+
80
+ @abstractmethod
81
+ def _error(self, train_index, test_index, **kwargs):
82
+ """
83
+ Train the model on the train set and return the error on the test set
84
+
85
+ Parameters
86
+ ----------
87
+ train_index : ndarray
88
+ index or boolean mask selecting the training observations
89
+ test_index : ndarray
90
+ index or boolean mask selecting the test observations
91
+ **kwargs
92
+ Keyword arguments passed to the ``fit`` method of the
93
+ cross-validated model.
94
+
95
+ Returns
96
+ -------
97
+ error : float
98
+ prediction error evaluated on the test set
99
+ """
100
+
101
+
102
+ def _split_train_test_smoothers(x, smoothers, train_index, test_index):
103
+ """
104
+ Split smoothers in test and train sets and create GenericSmoothers
105
+
106
+ Parameters
107
+ ----------
108
+ x : ndarray
109
+ values of the independent variables for all the smoothers
110
+ smoothers : instance
111
+ additive smoother instance whose components are split
112
+ train_index : ndarray
113
+ index or boolean mask selecting the training observations
114
+ test_index : ndarray
115
+ index or boolean mask selecting the test observations
116
+
117
+ Returns
118
+ -------
119
+ train_multivariate_smoothers : GenericSmoothers
120
+ smoothers evaluated on the training observations
121
+ test_multivariate_smoothers : GenericSmoothers
122
+ smoothers evaluated on the test observations
123
+
124
+ Notes
125
+ -----
126
+ This does not take exog_linear into account.
127
+ """
128
+ train_smoothers = []
129
+ test_smoothers = []
130
+ for smoother in smoothers.smoothers:
131
+ train_basis = smoother.basis[train_index]
132
+ train_der_basis = smoother.der_basis[train_index]
133
+ train_der2_basis = smoother.der2_basis[train_index]
134
+ train_cov_der2 = smoother.cov_der2
135
+ # TODO: Double check this part. cov_der2 is calculated with all data
136
+ train_x = smoother.x[train_index]
137
+
138
+ train_smoothers.append(
139
+ UnivariateGenericSmoother(
140
+ train_x,
141
+ train_basis,
142
+ train_der_basis,
143
+ train_der2_basis,
144
+ train_cov_der2,
145
+ smoother.variable_name + " train",
146
+ )
147
+ )
148
+
149
+ test_basis = smoother.basis[test_index]
150
+ test_der_basis = smoother.der_basis[test_index]
151
+ test_cov_der2 = smoother.cov_der2
152
+ # TODO: Double check this part. cov_der2 is calculated with all data
153
+ test_x = smoother.x[test_index]
154
+
155
+ test_smoothers.append(
156
+ UnivariateGenericSmoother(
157
+ test_x,
158
+ test_basis,
159
+ test_der_basis,
160
+ train_der2_basis,
161
+ test_cov_der2,
162
+ smoother.variable_name + " test",
163
+ )
164
+ )
165
+
166
+ train_multivariate_smoothers = GenericSmoothers(x[train_index], train_smoothers)
167
+ test_multivariate_smoothers = GenericSmoothers(x[test_index], test_smoothers)
168
+
169
+ return train_multivariate_smoothers, test_multivariate_smoothers
170
+
171
+
172
+ class MultivariateGAMCV(BaseCV):
173
+ """
174
+ Cross validation error of a multivariate additive model
175
+
176
+ Parameters
177
+ ----------
178
+ smoother : additive smoother instance
179
+ smoother providing the basis for the smooth terms of the model
180
+ alphas : list of float
181
+ penalty weights, one for each smooth term
182
+ gam : model class
183
+ model class for creating a model with the training data
184
+ cost : callable
185
+ cost function used to compute the prediction error
186
+ endog : ndarray
187
+ dependent (response) variable of the model
188
+ exog : ndarray or None
189
+ design matrix of the linear (non-smooth) terms of the model
190
+ cv_iterator : instance of cross-validation iterator
191
+ iterator used to split the data into train and test indices
192
+
193
+ Attributes
194
+ ----------
195
+ cost : callable
196
+ cost function used to compute the prediction error
197
+ gam : model class
198
+ model class for creating a model with the training data
199
+ smoother : additive smoother instance
200
+ smoother providing the basis for the smooth terms of the model
201
+ exog_linear : ndarray or None
202
+ design matrix of the linear (non-smooth) terms of the model
203
+ alphas : list of float
204
+ penalty weights, one for each smooth term
205
+ cv_iterator : instance of cross-validation iterator
206
+ iterator used to split the data into train and test indices
207
+ """
208
+
209
+ def __init__(self, smoother, alphas, gam, cost, endog, exog, cv_iterator):
210
+ self.cost = cost
211
+ self.gam = gam
212
+ self.smoother = smoother
213
+ self.exog_linear = exog
214
+ self.alphas = alphas
215
+ self.cv_iterator = cv_iterator
216
+ # TODO: super does not do anything with endog, exog, except get nobs
217
+ # refactor to clean up what where `exog` and `exog_linear` is attached
218
+ # exog is not used in super
219
+ super().__init__(cv_iterator, endog, self.smoother.basis)
220
+
221
+ def _error(self, train_index, test_index, **kwargs):
222
+ """
223
+ Train the model on the train set and return the error on the test set
224
+
225
+ Parameters
226
+ ----------
227
+ train_index : ndarray
228
+ index or boolean mask selecting the training observations
229
+ test_index : ndarray
230
+ index or boolean mask selecting the test observations
231
+ **kwargs
232
+ Keyword arguments passed to the ``fit`` method of the gam model.
233
+
234
+ Returns
235
+ -------
236
+ error : float
237
+ prediction error, evaluated with ``cost``, on the test set
238
+ """
239
+ train_smoother, test_smoother = _split_train_test_smoothers(
240
+ self.smoother.x, self.smoother, train_index, test_index
241
+ )
242
+
243
+ endog_train = self.endog[train_index]
244
+ endog_test = self.endog[test_index]
245
+ if self.exog_linear is not None:
246
+ exog_linear_train = self.exog_linear[train_index]
247
+ exog_linear_test = self.exog_linear[test_index]
248
+ else:
249
+ exog_linear_train = None
250
+ exog_linear_test = None
251
+
252
+ gam = self.gam(
253
+ endog_train,
254
+ exog=exog_linear_train,
255
+ smoother=train_smoother,
256
+ alpha=self.alphas,
257
+ )
258
+ gam_res = gam.fit(**kwargs)
259
+ # exog_linear_test and test_smoother.basis will be column_stacked
260
+ # but not transformed in predict
261
+ endog_est = gam_res.predict(
262
+ exog_linear_test, test_smoother.basis, transform=False
263
+ )
264
+
265
+ return self.cost(endog_test, endog_est)
266
+
267
+
268
+ class BasePenaltiesPathCV(with_metaclass(ABCMeta)):
269
+ """
270
+ Base class for cross validation over a grid of parameters
271
+
272
+ The best parameter is saved in ``alpha_cv``.
273
+
274
+ Parameters
275
+ ----------
276
+ alphas : list of float
277
+ grid of penalty weights to search over
278
+
279
+ Attributes
280
+ ----------
281
+ alphas : list of float
282
+ grid of penalty weights to search over
283
+ alpha_cv : float or None
284
+ best penalty weight found by cross-validation
285
+ cv_error : ndarray or None
286
+ cross-validation error for each value in ``alphas``
287
+ cv_std : ndarray or None
288
+ standard deviation of the cross-validation error for each value in
289
+ ``alphas``
290
+
291
+ Notes
292
+ -----
293
+ This class is currently not used.
294
+ """
295
+
296
+ def __init__(self, alphas):
297
+ self.alphas = alphas
298
+ self.alpha_cv = None
299
+ self.cv_error = None
300
+ self.cv_std = None
301
+
302
+ def plot_path(self):
303
+ """Plot the cross validation error and standard deviation over the alphas grid"""
304
+ from statsmodels.graphics.utils import _import_mpl
305
+
306
+ plt = _import_mpl()
307
+ plt.plot(self.alphas, self.cv_error, c="black")
308
+ plt.plot(self.alphas, self.cv_error + 1.96 * self.cv_std, c="blue")
309
+ plt.plot(self.alphas, self.cv_error - 1.96 * self.cv_std, c="blue")
310
+
311
+ plt.plot(self.alphas, self.cv_error, "o", c="black")
312
+ plt.plot(self.alphas, self.cv_error + 1.96 * self.cv_std, "o", c="blue")
313
+ plt.plot(self.alphas, self.cv_error - 1.96 * self.cv_std, "o", c="blue")
314
+
315
+ # TODO add return
316
+
317
+
318
+ class MultivariateGAMCVPath:
319
+ """
320
+ K-fold cross-validation for GAM
321
+
322
+ Parameters
323
+ ----------
324
+ smoother : additive smoother instance
325
+ smoother providing the basis for the smooth terms of the model
326
+ alphas : list of iterable
327
+ list of alpha for smooths. The product space will be used as alpha
328
+ grid for cross-validation
329
+ gam : model class
330
+ model class for creating a model with k-fold training data
331
+ cost : callable
332
+ cost function for the prediction error
333
+ endog : ndarray
334
+ dependent (response) variable of the model
335
+ exog : ndarray or None
336
+ design matrix of the linear (non-smooth) terms of the model
337
+ cv_iterator : instance of cross-validation iterator
338
+ iterator used to split the data into train and test indices
339
+
340
+ Attributes
341
+ ----------
342
+ cost : callable
343
+ cost function for the prediction error
344
+ smoother : additive smoother instance
345
+ smoother providing the basis for the smooth terms of the model
346
+ gam : model class
347
+ model class for creating a model with k-fold training data
348
+ alphas : list of iterable
349
+ list of alpha for smooths
350
+ alphas_grid : list of tuple
351
+ product space of ``alphas`` searched during cross-validation
352
+ endog : ndarray
353
+ dependent (response) variable of the model
354
+ exog : ndarray or None
355
+ design matrix of the linear (non-smooth) terms of the model
356
+ cv_iterator : instance of cross-validation iterator
357
+ iterator used to split the data into train and test indices
358
+ cv_error : ndarray
359
+ mean cross-validation error for each element of ``alphas_grid``
360
+ cv_std : ndarray
361
+ standard deviation of the cross-validation error for each element
362
+ of ``alphas_grid``
363
+ alpha_cv : tuple or None
364
+ element of ``alphas_grid`` with the smallest cross-validation error
365
+
366
+ Warnings
367
+ --------
368
+ The API of this class is preliminary and will change.
369
+ """
370
+
371
+ def __init__(self, smoother, alphas, gam, cost, endog, exog, cv_iterator):
372
+ self.cost = cost
373
+ self.smoother = smoother
374
+ self.gam = gam
375
+ self.alphas = alphas
376
+ self.alphas_grid = list(itertools.product(*self.alphas))
377
+ self.endog = endog
378
+ self.exog = exog
379
+ self.cv_iterator = cv_iterator
380
+ self.cv_error = np.zeros(
381
+ shape=(
382
+ len(
383
+ self.alphas_grid,
384
+ )
385
+ )
386
+ )
387
+ self.cv_std = np.zeros(
388
+ shape=(
389
+ len(
390
+ self.alphas_grid,
391
+ )
392
+ )
393
+ )
394
+ self.alpha_cv = None
395
+
396
+ def fit(self, **kwargs):
397
+ """
398
+ Perform the cross-validation search over the alphas grid
399
+
400
+ Parameters
401
+ ----------
402
+ **kwargs
403
+ Keyword arguments passed to the ``fit`` method of the gam model.
404
+
405
+ Returns
406
+ -------
407
+ self : MultivariateGAMCVPath
408
+ instance with ``cv_error``, ``cv_std`` and ``alpha_cv`` set
409
+ """
410
+ for i, alphas_i in enumerate(self.alphas_grid):
411
+ gam_cv = MultivariateGAMCV(
412
+ smoother=self.smoother,
413
+ alphas=alphas_i,
414
+ gam=self.gam,
415
+ cost=self.cost,
416
+ endog=self.endog,
417
+ exog=self.exog,
418
+ cv_iterator=self.cv_iterator,
419
+ )
420
+ cv_err = gam_cv.fit(**kwargs)
421
+ self.cv_error[i] = cv_err.mean()
422
+ self.cv_std[i] = cv_err.std()
423
+
424
+ self.alpha_cv = self.alphas_grid[np.argmin(self.cv_error)]
425
+ return self
shared/package-files/e8/e83b45c9e4464254e67478ace520de72b9d9c80b283f248319b9325a2b3673ce/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 mean(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false, c10::optional<at::ScalarType> dtype=c10::nullopt);
21
+ TORCH_API at::Tensor & mean_out(at::Tensor & out, const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim=false, c10::optional<at::ScalarType> dtype=c10::nullopt);
22
+ TORCH_API at::Tensor & mean_outf(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, c10::optional<at::ScalarType> dtype, at::Tensor & out);
23
+
24
+ } // namespace cuda
25
+ } // namespace at
shared/package-files/e8/e83d8bdd6c985e1b92a38cc20f6c8863a72bc450b79dbef56b340266d8358ca4/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 _cummax_helper {
18
+ using schema = void (const at::Tensor &, at::Tensor &, at::Tensor &, int64_t);
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::_cummax_helper")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_cummax_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()")
24
+ static void call(const at::Tensor & self, at::Tensor & values, at::Tensor & indices, int64_t dim);
25
+ static void redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & values, at::Tensor & indices, int64_t dim);
26
+ };
27
+
28
+ }} // namespace at::_ops
shared/package-files/e8/e83dda6442dc809ae9dd07ff1e2b00228c1cc319c2cc08827d37fbed836c6eb8/blob ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2010 David Fong and Michael Saunders
3
+ Distributed under the same license as SciPy
4
+
5
+ Testing Code for LSMR.
6
+
7
+ 03 Jun 2010: First version release with lsmr.py
8
+
9
+ David Chin-lung Fong clfong@stanford.edu
10
+ Institute for Computational and Mathematical Engineering
11
+ Stanford University
12
+
13
+ Michael Saunders saunders@stanford.edu
14
+ Systems Optimization Laboratory
15
+ Dept of MS&E, Stanford University.
16
+
17
+ """
18
+
19
+ from numpy import array, arange, eye, zeros, ones, transpose, hstack
20
+ from numpy.linalg import norm
21
+ from numpy.testing import assert_allclose
22
+ import pytest
23
+ from scipy.sparse import coo_array
24
+ from scipy.sparse.linalg._interface import aslinearoperator
25
+ from scipy.sparse.linalg import lsmr
26
+ from .test_lsqr import G, b
27
+
28
+
29
+ class TestLSMR:
30
+ def setup_method(self):
31
+ self.n = 10
32
+ self.m = 10
33
+
34
+ def assertCompatibleSystem(self, A, xtrue):
35
+ Afun = aslinearoperator(A)
36
+ b = Afun.matvec(xtrue)
37
+ x = lsmr(A, b)[0]
38
+ assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
39
+
40
+ def testIdentityACase1(self):
41
+ A = eye(self.n)
42
+ xtrue = zeros((self.n, 1))
43
+ self.assertCompatibleSystem(A, xtrue)
44
+
45
+ def testIdentityACase2(self):
46
+ A = eye(self.n)
47
+ xtrue = ones((self.n,1))
48
+ self.assertCompatibleSystem(A, xtrue)
49
+
50
+ def testIdentityACase3(self):
51
+ A = eye(self.n)
52
+ xtrue = transpose(arange(self.n,0,-1))
53
+ self.assertCompatibleSystem(A, xtrue)
54
+
55
+ def testBidiagonalA(self):
56
+ A = lowerBidiagonalMatrix(20,self.n)
57
+ xtrue = transpose(arange(self.n,0,-1))
58
+ self.assertCompatibleSystem(A,xtrue)
59
+
60
+ def testScalarB(self):
61
+ A = array([[1.0, 2.0]])
62
+ b = 3.0
63
+ x = lsmr(A, b)[0]
64
+ assert norm(A.dot(x) - b) == pytest.approx(0)
65
+
66
+ def testComplexX(self):
67
+ A = eye(self.n)
68
+ xtrue = transpose(arange(self.n, 0, -1) * (1 + 1j))
69
+ self.assertCompatibleSystem(A, xtrue)
70
+
71
+ def testComplexX0(self):
72
+ A = 4 * eye(self.n) + ones((self.n, self.n))
73
+ xtrue = transpose(arange(self.n, 0, -1))
74
+ b = aslinearoperator(A).matvec(xtrue)
75
+ x0 = zeros(self.n, dtype=complex)
76
+ x = lsmr(A, b, x0=x0)[0]
77
+ assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
78
+
79
+ def testComplexA(self):
80
+ A = 4 * eye(self.n) + 1j * ones((self.n, self.n))
81
+ xtrue = transpose(arange(self.n, 0, -1).astype(complex))
82
+ self.assertCompatibleSystem(A, xtrue)
83
+
84
+ def testComplexB(self):
85
+ A = 4 * eye(self.n) + ones((self.n, self.n))
86
+ xtrue = transpose(arange(self.n, 0, -1) * (1 + 1j))
87
+ b = aslinearoperator(A).matvec(xtrue)
88
+ x = lsmr(A, b)[0]
89
+ assert norm(x - xtrue) == pytest.approx(0, abs=1e-5)
90
+
91
+ def testColumnB(self):
92
+ A = eye(self.n)
93
+ b = ones((self.n, 1))
94
+ x = lsmr(A, b)[0]
95
+ assert norm(A.dot(x) - b.ravel()) == pytest.approx(0)
96
+
97
+ def testInitialization(self):
98
+ # Test that the default setting is not modified
99
+ x_ref, _, itn_ref, normr_ref, *_ = lsmr(G, b)
100
+ assert_allclose(norm(b - G@x_ref), normr_ref, atol=1e-6)
101
+
102
+ # Test passing zeros yields similar result
103
+ x0 = zeros(b.shape)
104
+ x = lsmr(G, b, x0=x0)[0]
105
+ assert_allclose(x, x_ref)
106
+
107
+ # Test warm-start with single iteration
108
+ x0 = lsmr(G, b, maxiter=1)[0]
109
+
110
+ x, _, itn, normr, *_ = lsmr(G, b, x0=x0)
111
+ assert_allclose(norm(b - G@x), normr, atol=1e-6)
112
+
113
+ # NOTE(gh-12139): This doesn't always converge to the same value as
114
+ # ref because error estimates will be slightly different when calculated
115
+ # from zeros vs x0 as a result only compare norm and itn (not x).
116
+
117
+ # x generally converges 1 iteration faster because it started at x0.
118
+ # itn == itn_ref means that lsmr(x0) took an extra iteration see above.
119
+ # -1 is technically possible but is rare (1 in 100000) so it's more
120
+ # likely to be an error elsewhere.
121
+ assert itn - itn_ref in (0, 1)
122
+
123
+ # If an extra iteration is performed normr may be 0, while normr_ref
124
+ # may be much larger.
125
+ assert normr < normr_ref * (1 + 1e-6)
126
+
127
+
128
+ class TestLSMRReturns:
129
+ def setup_method(self):
130
+ self.n = 10
131
+ self.A = lowerBidiagonalMatrix(20, self.n)
132
+ self.xtrue = transpose(arange(self.n, 0, -1))
133
+ self.Afun = aslinearoperator(self.A)
134
+ self.b = self.Afun.matvec(self.xtrue)
135
+ self.x0 = ones(self.n)
136
+ self.x00 = self.x0.copy()
137
+ self.returnValues = lsmr(self.A, self.b)
138
+ self.returnValuesX0 = lsmr(self.A, self.b, x0=self.x0)
139
+
140
+ def test_unchanged_x0(self):
141
+ x, istop, itn, normr, normar, normA, condA, normx = self.returnValuesX0
142
+ assert_allclose(self.x00, self.x0)
143
+
144
+ def testNormr(self):
145
+ x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
146
+ assert norm(self.b - self.Afun.matvec(x)) == pytest.approx(normr)
147
+
148
+ def testNormar(self):
149
+ x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
150
+ assert (norm(self.Afun.rmatvec(self.b - self.Afun.matvec(x)))
151
+ == pytest.approx(normar))
152
+
153
+ def testNormx(self):
154
+ x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
155
+ assert norm(x) == pytest.approx(normx)
156
+
157
+
158
+ def lowerBidiagonalMatrix(m, n):
159
+ # This is a simple example for testing LSMR.
160
+ # It uses the leading m*n submatrix from
161
+ # A = [ 1
162
+ # 1 2
163
+ # 2 3
164
+ # 3 4
165
+ # ...
166
+ # n ]
167
+ # suitably padded by zeros.
168
+ #
169
+ # 04 Jun 2010: First version for distribution with lsmr.py
170
+ if m <= n:
171
+ row = hstack((arange(m, dtype=int),
172
+ arange(1, m, dtype=int)))
173
+ col = hstack((arange(m, dtype=int),
174
+ arange(m-1, dtype=int)))
175
+ data = hstack((arange(1, m+1, dtype=float),
176
+ arange(1,m, dtype=float)))
177
+ return coo_array((data, (row, col)), shape=(m,n))
178
+ else:
179
+ row = hstack((arange(n, dtype=int),
180
+ arange(1, n+1, dtype=int)))
181
+ col = hstack((arange(n, dtype=int),
182
+ arange(n, dtype=int)))
183
+ data = hstack((arange(1, n+1, dtype=float),
184
+ arange(1,n+1, dtype=float)))
185
+ return coo_array((data,(row, col)), shape=(m,n))
shared/package-files/e8/e8411cdce118a7e22e4a889d2fa9f0a5a1e0fbe1b19f36c02539858b3efb08d1/blob ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Support for wildcard pattern matching in object inspection.
3
+
4
+ Authors
5
+ -------
6
+ - Jörgen Stenarson <jorgen.stenarson@bostream.nu>
7
+ - Thomas Kluyver
8
+ """
9
+
10
+ #*****************************************************************************
11
+ # Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu>
12
+ #
13
+ # Distributed under the terms of the BSD License. The full license is in
14
+ # the file COPYING, distributed as part of this software.
15
+ #*****************************************************************************
16
+
17
+ import re
18
+ import types
19
+
20
+ from IPython.utils.dir2 import dir2
21
+
22
+ def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]):
23
+ """Return dictionaries mapping lower case typename (e.g. 'tuple') to type
24
+ objects from the types package, and vice versa."""
25
+ typenamelist = [tname for tname in dir(types) if tname.endswith("Type")]
26
+ typestr2type, type2typestr = {}, {}
27
+
28
+ for tname in typenamelist:
29
+ name = tname[:-4].lower() # Cut 'Type' off the end of the name
30
+ obj = getattr(types, tname)
31
+ typestr2type[name] = obj
32
+ if name not in dont_include_in_type2typestr:
33
+ type2typestr[obj] = name
34
+ return typestr2type, type2typestr
35
+
36
+ typestr2type, type2typestr = create_typestr2type_dicts()
37
+
38
+ def is_type(obj, typestr_or_type):
39
+ """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It
40
+ can take strings or actual python types for the second argument, i.e.
41
+ 'tuple'<->TupleType. 'all' matches all types.
42
+
43
+ TODO: Should be extended for choosing more than one type."""
44
+ if typestr_or_type == "all":
45
+ return True
46
+ if type(typestr_or_type) == type:
47
+ test_type = typestr_or_type
48
+ else:
49
+ test_type = typestr2type.get(typestr_or_type, False)
50
+ if test_type:
51
+ return isinstance(obj, test_type)
52
+ return False
53
+
54
+ def show_hidden(str, show_all=False):
55
+ """Return true for strings starting with single _ if show_all is true."""
56
+ return show_all or str.startswith("__") or not str.startswith("_")
57
+
58
+ def dict_dir(obj):
59
+ """Produce a dictionary of an object's attributes. Builds on dir2 by
60
+ checking that a getattr() call actually succeeds."""
61
+ ns = {}
62
+ for key in dir2(obj):
63
+ # This seemingly unnecessary try/except is actually needed
64
+ # because there is code out there with metaclasses that
65
+ # create 'write only' attributes, where a getattr() call
66
+ # will fail even if the attribute appears listed in the
67
+ # object's dictionary. Properties can actually do the same
68
+ # thing. In particular, Traits use this pattern
69
+ try:
70
+ ns[key] = getattr(obj, key)
71
+ except AttributeError:
72
+ pass
73
+ return ns
74
+
75
+ def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True,
76
+ show_all=True):
77
+ """Filter a namespace dictionary by name pattern and item type."""
78
+ pattern = name_pattern.replace("*",".*").replace("?",".")
79
+ if ignore_case:
80
+ reg = re.compile(pattern+"$", re.I)
81
+ else:
82
+ reg = re.compile(pattern+"$")
83
+
84
+ # Check each one matches regex; shouldn't be hidden; of correct type.
85
+ return dict((key,obj) for key, obj in ns.items() if reg.match(key) \
86
+ and show_hidden(key, show_all) \
87
+ and is_type(obj, type_pattern) )
88
+
89
+ def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False):
90
+ """Return dictionary of all objects in a namespace dictionary that match
91
+ type_pattern and filter."""
92
+ pattern_list=filter.split(".")
93
+ if len(pattern_list) == 1:
94
+ return filter_ns(namespace, name_pattern=pattern_list[0],
95
+ type_pattern=type_pattern,
96
+ ignore_case=ignore_case, show_all=show_all)
97
+ else:
98
+ # This is where we can change if all objects should be searched or
99
+ # only modules. Just change the type_pattern to module to search only
100
+ # modules
101
+ filtered = filter_ns(namespace, name_pattern=pattern_list[0],
102
+ type_pattern="all",
103
+ ignore_case=ignore_case, show_all=show_all)
104
+ results = {}
105
+ for name, obj in filtered.items():
106
+ ns = list_namespace(dict_dir(obj), type_pattern,
107
+ ".".join(pattern_list[1:]),
108
+ ignore_case=ignore_case, show_all=show_all)
109
+ for inner_name, inner_obj in ns.items():
110
+ results["%s.%s"%(name,inner_name)] = inner_obj
111
+ return results
shared/package-files/e8/e841ab4e3a557ebad1498959185cf6052184aa9cb2ca8714a665d87513942a30/blob ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python
7
+ # torchgen/fuse_attention_patterns/gen_attention_patterns.py
8
+
9
+ import torch
10
+ import torch._inductor
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
35
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
36
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
37
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
38
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
39
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
40
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
41
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
42
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
43
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, Ignored())
44
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
45
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
46
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
47
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
48
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
49
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=2)
50
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
51
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
52
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
53
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
54
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
55
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
56
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
57
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
58
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
59
+ permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored())
60
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1)
61
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
62
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
63
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored())
64
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
65
+ clone_default = CallFunction(aten.clone.default, mul_Tensor_3, memory_format=torch.contiguous_format)
66
+ alias_default = CallFunction(aten.alias.default, div_Tensor_1)
67
+ alias_default_1 = CallFunction(aten.alias.default, alias_default)
68
+ alias_default_2 = CallFunction(aten.alias.default, alias_default_1)
69
+ alias_default_3 = CallFunction(aten.alias.default, alias_default_2, _users=2)
70
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, clone_default, alias_default_3, _users=2)
71
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
72
+ mul_Tensor_5 = CallFunction(aten.mul.Tensor, alias_default_3, sum_dim_IntList_1)
73
+ sub_Tensor_1 = CallFunction(aten.sub.Tensor, mul_Tensor_4, mul_Tensor_5)
74
+ div_Tensor_2 = CallFunction(aten.div.Tensor, sub_Tensor_1, Ignored())
75
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
76
+ permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored())
77
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2)
78
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
79
+ permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored())
80
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8)
81
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
82
+ permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored())
83
+ permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored())
84
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6)
85
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
86
+ _sfdp_pattern_6_training = MultiOutputPattern([view_default_5,
87
+ view_default_9,
88
+ permute_default_4,
89
+ view_default_11,
90
+ None,
91
+ None
92
+ ])
93
+
94
+
95
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
96
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
97
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
98
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
99
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
100
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
101
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
102
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, Ignored())
103
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
104
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
105
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
106
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
107
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
108
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
109
+ clone_default = CallFunction(aten.clone.default, div_Tensor_1)
110
+ expand_default_2 = CallFunction(aten.expand.default, clone_default, Ignored())
111
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
112
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
113
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
114
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
115
+ _sfdp_pattern_6_inference = CallFunction(aten.view.default, bmm_default_1, Ignored())
116
+
117
+
118
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
119
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
120
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
121
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
122
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
123
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
124
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
125
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
126
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
127
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, Ignored())
128
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))
129
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)
130
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
131
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
132
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
133
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
134
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
135
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
136
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1)
137
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
138
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
139
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
140
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
141
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
142
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
143
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
144
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
145
+ permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored())
146
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1)
147
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
148
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
149
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored())
150
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
151
+ clone_default = CallFunction(aten.clone.default, mul_Tensor_3, memory_format=torch.contiguous_format)
152
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, clone_default, Ignored())
153
+ alias_default = CallFunction(aten.alias.default, convert_element_type_default_1)
154
+ alias_default_1 = CallFunction(aten.alias.default, alias_default)
155
+ alias_default_2 = CallFunction(aten.alias.default, alias_default_1)
156
+ alias_default_3 = CallFunction(aten.alias.default, alias_default_2)
157
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, alias_default_3, Ignored(), _users=2)
158
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_4, _users=2)
159
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
160
+ mul_Tensor_5 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, sum_dim_IntList_1)
161
+ sub_Tensor_1 = CallFunction(aten.sub.Tensor, mul_Tensor_4, mul_Tensor_5)
162
+ convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, sub_Tensor_1, Ignored())
163
+ div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_5, Ignored())
164
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
165
+ permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored())
166
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2)
167
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
168
+ permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored())
169
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8)
170
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
171
+ permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored())
172
+ permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored())
173
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6)
174
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
175
+ _sfdp_pattern_6_half_training = MultiOutputPattern([view_default_5,
176
+ view_default_9,
177
+ permute_default_4,
178
+ view_default_11,
179
+ None,
180
+ None
181
+ ])
182
+
183
+
184
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
185
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
186
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
187
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
188
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
189
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
190
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
191
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, Ignored())
192
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))
193
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)
194
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
195
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
196
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
197
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
198
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
199
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
200
+ clone_default = CallFunction(aten.clone.default, convert_element_type_default_1)
201
+ expand_default_2 = CallFunction(aten.expand.default, clone_default, Ignored())
202
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
203
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
204
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
205
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
206
+ _sfdp_pattern_6_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored())
shared/package-files/e8/e843f6435ade7369dc3ebd9ff4a9e271223af1a0b955cbdbc704a533c582f958/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 meta {
19
+
20
+ TORCH_API at::Tensor special_bessel_y0(const at::Tensor & self);
21
+ TORCH_API at::Tensor & special_bessel_y0_out(at::Tensor & out, const at::Tensor & self);
22
+ TORCH_API at::Tensor & special_bessel_y0_outf(const at::Tensor & self, at::Tensor & out);
23
+
24
+ } // namespace meta
25
+ } // namespace at
shared/package-files/e8/e84514c2e33210c163840c4be67168ec7f9c87e78de243bdc7a2c04055b32033/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e84514c2e33210c163840c4be67168ec7f9c87e78de243bdc7a2c04055b32033
3
+ size 828890
shared/package-files/e8/e84663e68207f710f8f49d970931685a13ac008694ec96b9ff430017fa46999a/blob ADDED
The diff for this file is too large to render. See raw diff
 
shared/package-files/e8/e848f3c9d665ba02337e210d2ad0b8c9c67635c92df19420e6fe83ead5f54a25/blob ADDED
@@ -0,0 +1,1887 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions that ignore NaN.
3
+
4
+ Functions
5
+ ---------
6
+
7
+ - `nanmin` -- minimum non-NaN value
8
+ - `nanmax` -- maximum non-NaN value
9
+ - `nanargmin` -- index of minimum non-NaN value
10
+ - `nanargmax` -- index of maximum non-NaN value
11
+ - `nansum` -- sum of non-NaN values
12
+ - `nanprod` -- product of non-NaN values
13
+ - `nancumsum` -- cumulative sum of non-NaN values
14
+ - `nancumprod` -- cumulative product of non-NaN values
15
+ - `nanmean` -- mean of non-NaN values
16
+ - `nanvar` -- variance of non-NaN values
17
+ - `nanstd` -- standard deviation of non-NaN values
18
+ - `nanmedian` -- median of non-NaN values
19
+ - `nanquantile` -- qth quantile of non-NaN values
20
+ - `nanpercentile` -- qth percentile of non-NaN values
21
+
22
+ """
23
+ import functools
24
+ import warnings
25
+ import numpy as np
26
+ from numpy.lib import function_base
27
+ from numpy.core import overrides
28
+
29
+
30
+ array_function_dispatch = functools.partial(
31
+ overrides.array_function_dispatch, module='numpy')
32
+
33
+
34
+ __all__ = [
35
+ 'nansum', 'nanmax', 'nanmin', 'nanargmax', 'nanargmin', 'nanmean',
36
+ 'nanmedian', 'nanpercentile', 'nanvar', 'nanstd', 'nanprod',
37
+ 'nancumsum', 'nancumprod', 'nanquantile'
38
+ ]
39
+
40
+
41
+ def _nan_mask(a, out=None):
42
+ """
43
+ Parameters
44
+ ----------
45
+ a : array-like
46
+ Input array with at least 1 dimension.
47
+ out : ndarray, optional
48
+ Alternate output array in which to place the result. The default
49
+ is ``None``; if provided, it must have the same shape as the
50
+ expected output and will prevent the allocation of a new array.
51
+
52
+ Returns
53
+ -------
54
+ y : bool ndarray or True
55
+ A bool array where ``np.nan`` positions are marked with ``False``
56
+ and other positions are marked with ``True``. If the type of ``a``
57
+ is such that it can't possibly contain ``np.nan``, returns ``True``.
58
+ """
59
+ # we assume that a is an array for this private function
60
+
61
+ if a.dtype.kind not in 'fc':
62
+ return True
63
+
64
+ y = np.isnan(a, out=out)
65
+ y = np.invert(y, out=y)
66
+ return y
67
+
68
+ def _replace_nan(a, val):
69
+ """
70
+ If `a` is of inexact type, make a copy of `a`, replace NaNs with
71
+ the `val` value, and return the copy together with a boolean mask
72
+ marking the locations where NaNs were present. If `a` is not of
73
+ inexact type, do nothing and return `a` together with a mask of None.
74
+
75
+ Note that scalars will end up as array scalars, which is important
76
+ for using the result as the value of the out argument in some
77
+ operations.
78
+
79
+ Parameters
80
+ ----------
81
+ a : array-like
82
+ Input array.
83
+ val : float
84
+ NaN values are set to val before doing the operation.
85
+
86
+ Returns
87
+ -------
88
+ y : ndarray
89
+ If `a` is of inexact type, return a copy of `a` with the NaNs
90
+ replaced by the fill value, otherwise return `a`.
91
+ mask: {bool, None}
92
+ If `a` is of inexact type, return a boolean mask marking locations of
93
+ NaNs, otherwise return None.
94
+
95
+ """
96
+ a = np.asanyarray(a)
97
+
98
+ if a.dtype == np.object_:
99
+ # object arrays do not support `isnan` (gh-9009), so make a guess
100
+ mask = np.not_equal(a, a, dtype=bool)
101
+ elif issubclass(a.dtype.type, np.inexact):
102
+ mask = np.isnan(a)
103
+ else:
104
+ mask = None
105
+
106
+ if mask is not None:
107
+ a = np.array(a, subok=True, copy=True)
108
+ np.copyto(a, val, where=mask)
109
+
110
+ return a, mask
111
+
112
+
113
+ def _copyto(a, val, mask):
114
+ """
115
+ Replace values in `a` with NaN where `mask` is True. This differs from
116
+ copyto in that it will deal with the case where `a` is a numpy scalar.
117
+
118
+ Parameters
119
+ ----------
120
+ a : ndarray or numpy scalar
121
+ Array or numpy scalar some of whose values are to be replaced
122
+ by val.
123
+ val : numpy scalar
124
+ Value used a replacement.
125
+ mask : ndarray, scalar
126
+ Boolean array. Where True the corresponding element of `a` is
127
+ replaced by `val`. Broadcasts.
128
+
129
+ Returns
130
+ -------
131
+ res : ndarray, scalar
132
+ Array with elements replaced or scalar `val`.
133
+
134
+ """
135
+ if isinstance(a, np.ndarray):
136
+ np.copyto(a, val, where=mask, casting='unsafe')
137
+ else:
138
+ a = a.dtype.type(val)
139
+ return a
140
+
141
+
142
+ def _remove_nan_1d(arr1d, overwrite_input=False):
143
+ """
144
+ Equivalent to arr1d[~arr1d.isnan()], but in a different order
145
+
146
+ Presumably faster as it incurs fewer copies
147
+
148
+ Parameters
149
+ ----------
150
+ arr1d : ndarray
151
+ Array to remove nans from
152
+ overwrite_input : bool
153
+ True if `arr1d` can be modified in place
154
+
155
+ Returns
156
+ -------
157
+ res : ndarray
158
+ Array with nan elements removed
159
+ overwrite_input : bool
160
+ True if `res` can be modified in place, given the constraint on the
161
+ input
162
+ """
163
+ if arr1d.dtype == object:
164
+ # object arrays do not support `isnan` (gh-9009), so make a guess
165
+ c = np.not_equal(arr1d, arr1d, dtype=bool)
166
+ else:
167
+ c = np.isnan(arr1d)
168
+
169
+ s = np.nonzero(c)[0]
170
+ if s.size == arr1d.size:
171
+ warnings.warn("All-NaN slice encountered", RuntimeWarning,
172
+ stacklevel=6)
173
+ return arr1d[:0], True
174
+ elif s.size == 0:
175
+ return arr1d, overwrite_input
176
+ else:
177
+ if not overwrite_input:
178
+ arr1d = arr1d.copy()
179
+ # select non-nans at end of array
180
+ enonan = arr1d[-s.size:][~c[-s.size:]]
181
+ # fill nans in beginning of array with non-nans of end
182
+ arr1d[s[:enonan.size]] = enonan
183
+
184
+ return arr1d[:-s.size], True
185
+
186
+
187
+ def _divide_by_count(a, b, out=None):
188
+ """
189
+ Compute a/b ignoring invalid results. If `a` is an array the division
190
+ is done in place. If `a` is a scalar, then its type is preserved in the
191
+ output. If out is None, then a is used instead so that the division
192
+ is in place. Note that this is only called with `a` an inexact type.
193
+
194
+ Parameters
195
+ ----------
196
+ a : {ndarray, numpy scalar}
197
+ Numerator. Expected to be of inexact type but not checked.
198
+ b : {ndarray, numpy scalar}
199
+ Denominator.
200
+ out : ndarray, optional
201
+ Alternate output array in which to place the result. The default
202
+ is ``None``; if provided, it must have the same shape as the
203
+ expected output, but the type will be cast if necessary.
204
+
205
+ Returns
206
+ -------
207
+ ret : {ndarray, numpy scalar}
208
+ The return value is a/b. If `a` was an ndarray the division is done
209
+ in place. If `a` is a numpy scalar, the division preserves its type.
210
+
211
+ """
212
+ with np.errstate(invalid='ignore', divide='ignore'):
213
+ if isinstance(a, np.ndarray):
214
+ if out is None:
215
+ return np.divide(a, b, out=a, casting='unsafe')
216
+ else:
217
+ return np.divide(a, b, out=out, casting='unsafe')
218
+ else:
219
+ if out is None:
220
+ # Precaution against reduced object arrays
221
+ try:
222
+ return a.dtype.type(a / b)
223
+ except AttributeError:
224
+ return a / b
225
+ else:
226
+ # This is questionable, but currently a numpy scalar can
227
+ # be output to a zero dimensional array.
228
+ return np.divide(a, b, out=out, casting='unsafe')
229
+
230
+
231
+ def _nanmin_dispatcher(a, axis=None, out=None, keepdims=None,
232
+ initial=None, where=None):
233
+ return (a, out)
234
+
235
+
236
+ @array_function_dispatch(_nanmin_dispatcher)
237
+ def nanmin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
238
+ where=np._NoValue):
239
+ """
240
+ Return minimum of an array or minimum along an axis, ignoring any NaNs.
241
+ When all-NaN slices are encountered a ``RuntimeWarning`` is raised and
242
+ Nan is returned for that slice.
243
+
244
+ Parameters
245
+ ----------
246
+ a : array_like
247
+ Array containing numbers whose minimum is desired. If `a` is not an
248
+ array, a conversion is attempted.
249
+ axis : {int, tuple of int, None}, optional
250
+ Axis or axes along which the minimum is computed. The default is to compute
251
+ the minimum of the flattened array.
252
+ out : ndarray, optional
253
+ Alternate output array in which to place the result. The default
254
+ is ``None``; if provided, it must have the same shape as the
255
+ expected output, but the type will be cast if necessary. See
256
+ :ref:`ufuncs-output-type` for more details.
257
+
258
+ .. versionadded:: 1.8.0
259
+ keepdims : bool, optional
260
+ If this is set to True, the axes which are reduced are left
261
+ in the result as dimensions with size one. With this option,
262
+ the result will broadcast correctly against the original `a`.
263
+
264
+ If the value is anything but the default, then
265
+ `keepdims` will be passed through to the `min` method
266
+ of sub-classes of `ndarray`. If the sub-classes methods
267
+ does not implement `keepdims` any exceptions will be raised.
268
+
269
+ .. versionadded:: 1.8.0
270
+ initial : scalar, optional
271
+ The maximum value of an output element. Must be present to allow
272
+ computation on empty slice. See `~numpy.ufunc.reduce` for details.
273
+
274
+ .. versionadded:: 1.22.0
275
+ where : array_like of bool, optional
276
+ Elements to compare for the minimum. See `~numpy.ufunc.reduce`
277
+ for details.
278
+
279
+ .. versionadded:: 1.22.0
280
+
281
+ Returns
282
+ -------
283
+ nanmin : ndarray
284
+ An array with the same shape as `a`, with the specified axis
285
+ removed. If `a` is a 0-d array, or if axis is None, an ndarray
286
+ scalar is returned. The same dtype as `a` is returned.
287
+
288
+ See Also
289
+ --------
290
+ nanmax :
291
+ The maximum value of an array along a given axis, ignoring any NaNs.
292
+ amin :
293
+ The minimum value of an array along a given axis, propagating any NaNs.
294
+ fmin :
295
+ Element-wise minimum of two arrays, ignoring any NaNs.
296
+ minimum :
297
+ Element-wise minimum of two arrays, propagating any NaNs.
298
+ isnan :
299
+ Shows which elements are Not a Number (NaN).
300
+ isfinite:
301
+ Shows which elements are neither NaN nor infinity.
302
+
303
+ amax, fmax, maximum
304
+
305
+ Notes
306
+ -----
307
+ NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
308
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
309
+ Positive infinity is treated as a very large number and negative
310
+ infinity is treated as a very small (i.e. negative) number.
311
+
312
+ If the input has a integer type the function is equivalent to np.min.
313
+
314
+ Examples
315
+ --------
316
+ >>> a = np.array([[1, 2], [3, np.nan]])
317
+ >>> np.nanmin(a)
318
+ 1.0
319
+ >>> np.nanmin(a, axis=0)
320
+ array([1., 2.])
321
+ >>> np.nanmin(a, axis=1)
322
+ array([1., 3.])
323
+
324
+ When positive infinity and negative infinity are present:
325
+
326
+ >>> np.nanmin([1, 2, np.nan, np.inf])
327
+ 1.0
328
+ >>> np.nanmin([1, 2, np.nan, np.NINF])
329
+ -inf
330
+
331
+ """
332
+ kwargs = {}
333
+ if keepdims is not np._NoValue:
334
+ kwargs['keepdims'] = keepdims
335
+ if initial is not np._NoValue:
336
+ kwargs['initial'] = initial
337
+ if where is not np._NoValue:
338
+ kwargs['where'] = where
339
+
340
+ if type(a) is np.ndarray and a.dtype != np.object_:
341
+ # Fast, but not safe for subclasses of ndarray, or object arrays,
342
+ # which do not implement isnan (gh-9009), or fmin correctly (gh-8975)
343
+ res = np.fmin.reduce(a, axis=axis, out=out, **kwargs)
344
+ if np.isnan(res).any():
345
+ warnings.warn("All-NaN slice encountered", RuntimeWarning,
346
+ stacklevel=2)
347
+ else:
348
+ # Slow, but safe for subclasses of ndarray
349
+ a, mask = _replace_nan(a, +np.inf)
350
+ res = np.amin(a, axis=axis, out=out, **kwargs)
351
+ if mask is None:
352
+ return res
353
+
354
+ # Check for all-NaN axis
355
+ kwargs.pop("initial", None)
356
+ mask = np.all(mask, axis=axis, **kwargs)
357
+ if np.any(mask):
358
+ res = _copyto(res, np.nan, mask)
359
+ warnings.warn("All-NaN axis encountered", RuntimeWarning,
360
+ stacklevel=2)
361
+ return res
362
+
363
+
364
+ def _nanmax_dispatcher(a, axis=None, out=None, keepdims=None,
365
+ initial=None, where=None):
366
+ return (a, out)
367
+
368
+
369
+ @array_function_dispatch(_nanmax_dispatcher)
370
+ def nanmax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
371
+ where=np._NoValue):
372
+ """
373
+ Return the maximum of an array or maximum along an axis, ignoring any
374
+ NaNs. When all-NaN slices are encountered a ``RuntimeWarning`` is
375
+ raised and NaN is returned for that slice.
376
+
377
+ Parameters
378
+ ----------
379
+ a : array_like
380
+ Array containing numbers whose maximum is desired. If `a` is not an
381
+ array, a conversion is attempted.
382
+ axis : {int, tuple of int, None}, optional
383
+ Axis or axes along which the maximum is computed. The default is to compute
384
+ the maximum of the flattened array.
385
+ out : ndarray, optional
386
+ Alternate output array in which to place the result. The default
387
+ is ``None``; if provided, it must have the same shape as the
388
+ expected output, but the type will be cast if necessary. See
389
+ :ref:`ufuncs-output-type` for more details.
390
+
391
+ .. versionadded:: 1.8.0
392
+ keepdims : bool, optional
393
+ If this is set to True, the axes which are reduced are left
394
+ in the result as dimensions with size one. With this option,
395
+ the result will broadcast correctly against the original `a`.
396
+
397
+ If the value is anything but the default, then
398
+ `keepdims` will be passed through to the `max` method
399
+ of sub-classes of `ndarray`. If the sub-classes methods
400
+ does not implement `keepdims` any exceptions will be raised.
401
+
402
+ .. versionadded:: 1.8.0
403
+ initial : scalar, optional
404
+ The minimum value of an output element. Must be present to allow
405
+ computation on empty slice. See `~numpy.ufunc.reduce` for details.
406
+
407
+ .. versionadded:: 1.22.0
408
+ where : array_like of bool, optional
409
+ Elements to compare for the maximum. See `~numpy.ufunc.reduce`
410
+ for details.
411
+
412
+ .. versionadded:: 1.22.0
413
+
414
+ Returns
415
+ -------
416
+ nanmax : ndarray
417
+ An array with the same shape as `a`, with the specified axis removed.
418
+ If `a` is a 0-d array, or if axis is None, an ndarray scalar is
419
+ returned. The same dtype as `a` is returned.
420
+
421
+ See Also
422
+ --------
423
+ nanmin :
424
+ The minimum value of an array along a given axis, ignoring any NaNs.
425
+ amax :
426
+ The maximum value of an array along a given axis, propagating any NaNs.
427
+ fmax :
428
+ Element-wise maximum of two arrays, ignoring any NaNs.
429
+ maximum :
430
+ Element-wise maximum of two arrays, propagating any NaNs.
431
+ isnan :
432
+ Shows which elements are Not a Number (NaN).
433
+ isfinite:
434
+ Shows which elements are neither NaN nor infinity.
435
+
436
+ amin, fmin, minimum
437
+
438
+ Notes
439
+ -----
440
+ NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
441
+ (IEEE 754). This means that Not a Number is not equivalent to infinity.
442
+ Positive infinity is treated as a very large number and negative
443
+ infinity is treated as a very small (i.e. negative) number.
444
+
445
+ If the input has a integer type the function is equivalent to np.max.
446
+
447
+ Examples
448
+ --------
449
+ >>> a = np.array([[1, 2], [3, np.nan]])
450
+ >>> np.nanmax(a)
451
+ 3.0
452
+ >>> np.nanmax(a, axis=0)
453
+ array([3., 2.])
454
+ >>> np.nanmax(a, axis=1)
455
+ array([2., 3.])
456
+
457
+ When positive infinity and negative infinity are present:
458
+
459
+ >>> np.nanmax([1, 2, np.nan, np.NINF])
460
+ 2.0
461
+ >>> np.nanmax([1, 2, np.nan, np.inf])
462
+ inf
463
+
464
+ """
465
+ kwargs = {}
466
+ if keepdims is not np._NoValue:
467
+ kwargs['keepdims'] = keepdims
468
+ if initial is not np._NoValue:
469
+ kwargs['initial'] = initial
470
+ if where is not np._NoValue:
471
+ kwargs['where'] = where
472
+
473
+ if type(a) is np.ndarray and a.dtype != np.object_:
474
+ # Fast, but not safe for subclasses of ndarray, or object arrays,
475
+ # which do not implement isnan (gh-9009), or fmax correctly (gh-8975)
476
+ res = np.fmax.reduce(a, axis=axis, out=out, **kwargs)
477
+ if np.isnan(res).any():
478
+ warnings.warn("All-NaN slice encountered", RuntimeWarning,
479
+ stacklevel=2)
480
+ else:
481
+ # Slow, but safe for subclasses of ndarray
482
+ a, mask = _replace_nan(a, -np.inf)
483
+ res = np.amax(a, axis=axis, out=out, **kwargs)
484
+ if mask is None:
485
+ return res
486
+
487
+ # Check for all-NaN axis
488
+ kwargs.pop("initial", None)
489
+ mask = np.all(mask, axis=axis, **kwargs)
490
+ if np.any(mask):
491
+ res = _copyto(res, np.nan, mask)
492
+ warnings.warn("All-NaN axis encountered", RuntimeWarning,
493
+ stacklevel=2)
494
+ return res
495
+
496
+
497
+ def _nanargmin_dispatcher(a, axis=None, out=None, *, keepdims=None):
498
+ return (a,)
499
+
500
+
501
+ @array_function_dispatch(_nanargmin_dispatcher)
502
+ def nanargmin(a, axis=None, out=None, *, keepdims=np._NoValue):
503
+ """
504
+ Return the indices of the minimum values in the specified axis ignoring
505
+ NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
506
+ cannot be trusted if a slice contains only NaNs and Infs.
507
+
508
+ Parameters
509
+ ----------
510
+ a : array_like
511
+ Input data.
512
+ axis : int, optional
513
+ Axis along which to operate. By default flattened input is used.
514
+ out : array, optional
515
+ If provided, the result will be inserted into this array. It should
516
+ be of the appropriate shape and dtype.
517
+
518
+ .. versionadded:: 1.22.0
519
+ keepdims : bool, optional
520
+ If this is set to True, the axes which are reduced are left
521
+ in the result as dimensions with size one. With this option,
522
+ the result will broadcast correctly against the array.
523
+
524
+ .. versionadded:: 1.22.0
525
+
526
+ Returns
527
+ -------
528
+ index_array : ndarray
529
+ An array of indices or a single index value.
530
+
531
+ See Also
532
+ --------
533
+ argmin, nanargmax
534
+
535
+ Examples
536
+ --------
537
+ >>> a = np.array([[np.nan, 4], [2, 3]])
538
+ >>> np.argmin(a)
539
+ 0
540
+ >>> np.nanargmin(a)
541
+ 2
542
+ >>> np.nanargmin(a, axis=0)
543
+ array([1, 1])
544
+ >>> np.nanargmin(a, axis=1)
545
+ array([1, 0])
546
+
547
+ """
548
+ a, mask = _replace_nan(a, np.inf)
549
+ if mask is not None:
550
+ mask = np.all(mask, axis=axis)
551
+ if np.any(mask):
552
+ raise ValueError("All-NaN slice encountered")
553
+ res = np.argmin(a, axis=axis, out=out, keepdims=keepdims)
554
+ return res
555
+
556
+
557
+ def _nanargmax_dispatcher(a, axis=None, out=None, *, keepdims=None):
558
+ return (a,)
559
+
560
+
561
+ @array_function_dispatch(_nanargmax_dispatcher)
562
+ def nanargmax(a, axis=None, out=None, *, keepdims=np._NoValue):
563
+ """
564
+ Return the indices of the maximum values in the specified axis ignoring
565
+ NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
566
+ results cannot be trusted if a slice contains only NaNs and -Infs.
567
+
568
+
569
+ Parameters
570
+ ----------
571
+ a : array_like
572
+ Input data.
573
+ axis : int, optional
574
+ Axis along which to operate. By default flattened input is used.
575
+ out : array, optional
576
+ If provided, the result will be inserted into this array. It should
577
+ be of the appropriate shape and dtype.
578
+
579
+ .. versionadded:: 1.22.0
580
+ keepdims : bool, optional
581
+ If this is set to True, the axes which are reduced are left
582
+ in the result as dimensions with size one. With this option,
583
+ the result will broadcast correctly against the array.
584
+
585
+ .. versionadded:: 1.22.0
586
+
587
+ Returns
588
+ -------
589
+ index_array : ndarray
590
+ An array of indices or a single index value.
591
+
592
+ See Also
593
+ --------
594
+ argmax, nanargmin
595
+
596
+ Examples
597
+ --------
598
+ >>> a = np.array([[np.nan, 4], [2, 3]])
599
+ >>> np.argmax(a)
600
+ 0
601
+ >>> np.nanargmax(a)
602
+ 1
603
+ >>> np.nanargmax(a, axis=0)
604
+ array([1, 0])
605
+ >>> np.nanargmax(a, axis=1)
606
+ array([1, 1])
607
+
608
+ """
609
+ a, mask = _replace_nan(a, -np.inf)
610
+ if mask is not None:
611
+ mask = np.all(mask, axis=axis)
612
+ if np.any(mask):
613
+ raise ValueError("All-NaN slice encountered")
614
+ res = np.argmax(a, axis=axis, out=out, keepdims=keepdims)
615
+ return res
616
+
617
+
618
+ def _nansum_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
619
+ initial=None, where=None):
620
+ return (a, out)
621
+
622
+
623
+ @array_function_dispatch(_nansum_dispatcher)
624
+ def nansum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
625
+ initial=np._NoValue, where=np._NoValue):
626
+ """
627
+ Return the sum of array elements over a given axis treating Not a
628
+ Numbers (NaNs) as zero.
629
+
630
+ In NumPy versions <= 1.9.0 Nan is returned for slices that are all-NaN or
631
+ empty. In later versions zero is returned.
632
+
633
+ Parameters
634
+ ----------
635
+ a : array_like
636
+ Array containing numbers whose sum is desired. If `a` is not an
637
+ array, a conversion is attempted.
638
+ axis : {int, tuple of int, None}, optional
639
+ Axis or axes along which the sum is computed. The default is to compute the
640
+ sum of the flattened array.
641
+ dtype : data-type, optional
642
+ The type of the returned array and of the accumulator in which the
643
+ elements are summed. By default, the dtype of `a` is used. An
644
+ exception is when `a` has an integer type with less precision than
645
+ the platform (u)intp. In that case, the default will be either
646
+ (u)int32 or (u)int64 depending on whether the platform is 32 or 64
647
+ bits. For inexact inputs, dtype must be inexact.
648
+
649
+ .. versionadded:: 1.8.0
650
+ out : ndarray, optional
651
+ Alternate output array in which to place the result. The default
652
+ is ``None``. If provided, it must have the same shape as the
653
+ expected output, but the type will be cast if necessary. See
654
+ :ref:`ufuncs-output-type` for more details. The casting of NaN to integer
655
+ can yield unexpected results.
656
+
657
+ .. versionadded:: 1.8.0
658
+ keepdims : bool, optional
659
+ If this is set to True, the axes which are reduced are left
660
+ in the result as dimensions with size one. With this option,
661
+ the result will broadcast correctly against the original `a`.
662
+
663
+
664
+ If the value is anything but the default, then
665
+ `keepdims` will be passed through to the `mean` or `sum` methods
666
+ of sub-classes of `ndarray`. If the sub-classes methods
667
+ does not implement `keepdims` any exceptions will be raised.
668
+
669
+ .. versionadded:: 1.8.0
670
+ initial : scalar, optional
671
+ Starting value for the sum. See `~numpy.ufunc.reduce` for details.
672
+
673
+ .. versionadded:: 1.22.0
674
+ where : array_like of bool, optional
675
+ Elements to include in the sum. See `~numpy.ufunc.reduce` for details.
676
+
677
+ .. versionadded:: 1.22.0
678
+
679
+ Returns
680
+ -------
681
+ nansum : ndarray.
682
+ A new array holding the result is returned unless `out` is
683
+ specified, in which it is returned. The result has the same
684
+ size as `a`, and the same shape as `a` if `axis` is not None
685
+ or `a` is a 1-d array.
686
+
687
+ See Also
688
+ --------
689
+ numpy.sum : Sum across array propagating NaNs.
690
+ isnan : Show which elements are NaN.
691
+ isfinite : Show which elements are not NaN or +/-inf.
692
+
693
+ Notes
694
+ -----
695
+ If both positive and negative infinity are present, the sum will be Not
696
+ A Number (NaN).
697
+
698
+ Examples
699
+ --------
700
+ >>> np.nansum(1)
701
+ 1
702
+ >>> np.nansum([1])
703
+ 1
704
+ >>> np.nansum([1, np.nan])
705
+ 1.0
706
+ >>> a = np.array([[1, 1], [1, np.nan]])
707
+ >>> np.nansum(a)
708
+ 3.0
709
+ >>> np.nansum(a, axis=0)
710
+ array([2., 1.])
711
+ >>> np.nansum([1, np.nan, np.inf])
712
+ inf
713
+ >>> np.nansum([1, np.nan, np.NINF])
714
+ -inf
715
+ >>> from numpy.testing import suppress_warnings
716
+ >>> with suppress_warnings() as sup:
717
+ ... sup.filter(RuntimeWarning)
718
+ ... np.nansum([1, np.nan, np.inf, -np.inf]) # both +/- infinity present
719
+ nan
720
+
721
+ """
722
+ a, mask = _replace_nan(a, 0)
723
+ return np.sum(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims,
724
+ initial=initial, where=where)
725
+
726
+
727
+ def _nanprod_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
728
+ initial=None, where=None):
729
+ return (a, out)
730
+
731
+
732
+ @array_function_dispatch(_nanprod_dispatcher)
733
+ def nanprod(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
734
+ initial=np._NoValue, where=np._NoValue):
735
+ """
736
+ Return the product of array elements over a given axis treating Not a
737
+ Numbers (NaNs) as ones.
738
+
739
+ One is returned for slices that are all-NaN or empty.
740
+
741
+ .. versionadded:: 1.10.0
742
+
743
+ Parameters
744
+ ----------
745
+ a : array_like
746
+ Array containing numbers whose product is desired. If `a` is not an
747
+ array, a conversion is attempted.
748
+ axis : {int, tuple of int, None}, optional
749
+ Axis or axes along which the product is computed. The default is to compute
750
+ the product of the flattened array.
751
+ dtype : data-type, optional
752
+ The type of the returned array and of the accumulator in which the
753
+ elements are summed. By default, the dtype of `a` is used. An
754
+ exception is when `a` has an integer type with less precision than
755
+ the platform (u)intp. In that case, the default will be either
756
+ (u)int32 or (u)int64 depending on whether the platform is 32 or 64
757
+ bits. For inexact inputs, dtype must be inexact.
758
+ out : ndarray, optional
759
+ Alternate output array in which to place the result. The default
760
+ is ``None``. If provided, it must have the same shape as the
761
+ expected output, but the type will be cast if necessary. See
762
+ :ref:`ufuncs-output-type` for more details. The casting of NaN to integer
763
+ can yield unexpected results.
764
+ keepdims : bool, optional
765
+ If True, the axes which are reduced are left in the result as
766
+ dimensions with size one. With this option, the result will
767
+ broadcast correctly against the original `arr`.
768
+ initial : scalar, optional
769
+ The starting value for this product. See `~numpy.ufunc.reduce`
770
+ for details.
771
+
772
+ .. versionadded:: 1.22.0
773
+ where : array_like of bool, optional
774
+ Elements to include in the product. See `~numpy.ufunc.reduce`
775
+ for details.
776
+
777
+ .. versionadded:: 1.22.0
778
+
779
+ Returns
780
+ -------
781
+ nanprod : ndarray
782
+ A new array holding the result is returned unless `out` is
783
+ specified, in which case it is returned.
784
+
785
+ See Also
786
+ --------
787
+ numpy.prod : Product across array propagating NaNs.
788
+ isnan : Show which elements are NaN.
789
+
790
+ Examples
791
+ --------
792
+ >>> np.nanprod(1)
793
+ 1
794
+ >>> np.nanprod([1])
795
+ 1
796
+ >>> np.nanprod([1, np.nan])
797
+ 1.0
798
+ >>> a = np.array([[1, 2], [3, np.nan]])
799
+ >>> np.nanprod(a)
800
+ 6.0
801
+ >>> np.nanprod(a, axis=0)
802
+ array([3., 2.])
803
+
804
+ """
805
+ a, mask = _replace_nan(a, 1)
806
+ return np.prod(a, axis=axis, dtype=dtype, out=out, keepdims=keepdims,
807
+ initial=initial, where=where)
808
+
809
+
810
+ def _nancumsum_dispatcher(a, axis=None, dtype=None, out=None):
811
+ return (a, out)
812
+
813
+
814
+ @array_function_dispatch(_nancumsum_dispatcher)
815
+ def nancumsum(a, axis=None, dtype=None, out=None):
816
+ """
817
+ Return the cumulative sum of array elements over a given axis treating Not a
818
+ Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are
819
+ encountered and leading NaNs are replaced by zeros.
820
+
821
+ Zeros are returned for slices that are all-NaN or empty.
822
+
823
+ .. versionadded:: 1.12.0
824
+
825
+ Parameters
826
+ ----------
827
+ a : array_like
828
+ Input array.
829
+ axis : int, optional
830
+ Axis along which the cumulative sum is computed. The default
831
+ (None) is to compute the cumsum over the flattened array.
832
+ dtype : dtype, optional
833
+ Type of the returned array and of the accumulator in which the
834
+ elements are summed. If `dtype` is not specified, it defaults
835
+ to the dtype of `a`, unless `a` has an integer dtype with a
836
+ precision less than that of the default platform integer. In
837
+ that case, the default platform integer is used.
838
+ out : ndarray, optional
839
+ Alternative output array in which to place the result. It must
840
+ have the same shape and buffer length as the expected output
841
+ but the type will be cast if necessary. See :ref:`ufuncs-output-type` for
842
+ more details.
843
+
844
+ Returns
845
+ -------
846
+ nancumsum : ndarray.
847
+ A new array holding the result is returned unless `out` is
848
+ specified, in which it is returned. The result has the same
849
+ size as `a`, and the same shape as `a` if `axis` is not None
850
+ or `a` is a 1-d array.
851
+
852
+ See Also
853
+ --------
854
+ numpy.cumsum : Cumulative sum across array propagating NaNs.
855
+ isnan : Show which elements are NaN.
856
+
857
+ Examples
858
+ --------
859
+ >>> np.nancumsum(1)
860
+ array([1])
861
+ >>> np.nancumsum([1])
862
+ array([1])
863
+ >>> np.nancumsum([1, np.nan])
864
+ array([1., 1.])
865
+ >>> a = np.array([[1, 2], [3, np.nan]])
866
+ >>> np.nancumsum(a)
867
+ array([1., 3., 6., 6.])
868
+ >>> np.nancumsum(a, axis=0)
869
+ array([[1., 2.],
870
+ [4., 2.]])
871
+ >>> np.nancumsum(a, axis=1)
872
+ array([[1., 3.],
873
+ [3., 3.]])
874
+
875
+ """
876
+ a, mask = _replace_nan(a, 0)
877
+ return np.cumsum(a, axis=axis, dtype=dtype, out=out)
878
+
879
+
880
+ def _nancumprod_dispatcher(a, axis=None, dtype=None, out=None):
881
+ return (a, out)
882
+
883
+
884
+ @array_function_dispatch(_nancumprod_dispatcher)
885
+ def nancumprod(a, axis=None, dtype=None, out=None):
886
+ """
887
+ Return the cumulative product of array elements over a given axis treating Not a
888
+ Numbers (NaNs) as one. The cumulative product does not change when NaNs are
889
+ encountered and leading NaNs are replaced by ones.
890
+
891
+ Ones are returned for slices that are all-NaN or empty.
892
+
893
+ .. versionadded:: 1.12.0
894
+
895
+ Parameters
896
+ ----------
897
+ a : array_like
898
+ Input array.
899
+ axis : int, optional
900
+ Axis along which the cumulative product is computed. By default
901
+ the input is flattened.
902
+ dtype : dtype, optional
903
+ Type of the returned array, as well as of the accumulator in which
904
+ the elements are multiplied. If *dtype* is not specified, it
905
+ defaults to the dtype of `a`, unless `a` has an integer dtype with
906
+ a precision less than that of the default platform integer. In
907
+ that case, the default platform integer is used instead.
908
+ out : ndarray, optional
909
+ Alternative output array in which to place the result. It must
910
+ have the same shape and buffer length as the expected output
911
+ but the type of the resulting values will be cast if necessary.
912
+
913
+ Returns
914
+ -------
915
+ nancumprod : ndarray
916
+ A new array holding the result is returned unless `out` is
917
+ specified, in which case it is returned.
918
+
919
+ See Also
920
+ --------
921
+ numpy.cumprod : Cumulative product across array propagating NaNs.
922
+ isnan : Show which elements are NaN.
923
+
924
+ Examples
925
+ --------
926
+ >>> np.nancumprod(1)
927
+ array([1])
928
+ >>> np.nancumprod([1])
929
+ array([1])
930
+ >>> np.nancumprod([1, np.nan])
931
+ array([1., 1.])
932
+ >>> a = np.array([[1, 2], [3, np.nan]])
933
+ >>> np.nancumprod(a)
934
+ array([1., 2., 6., 6.])
935
+ >>> np.nancumprod(a, axis=0)
936
+ array([[1., 2.],
937
+ [3., 2.]])
938
+ >>> np.nancumprod(a, axis=1)
939
+ array([[1., 2.],
940
+ [3., 3.]])
941
+
942
+ """
943
+ a, mask = _replace_nan(a, 1)
944
+ return np.cumprod(a, axis=axis, dtype=dtype, out=out)
945
+
946
+
947
+ def _nanmean_dispatcher(a, axis=None, dtype=None, out=None, keepdims=None,
948
+ *, where=None):
949
+ return (a, out)
950
+
951
+
952
+ @array_function_dispatch(_nanmean_dispatcher)
953
+ def nanmean(a, axis=None, dtype=None, out=None, keepdims=np._NoValue,
954
+ *, where=np._NoValue):
955
+ """
956
+ Compute the arithmetic mean along the specified axis, ignoring NaNs.
957
+
958
+ Returns the average of the array elements. The average is taken over
959
+ the flattened array by default, otherwise over the specified axis.
960
+ `float64` intermediate and return values are used for integer inputs.
961
+
962
+ For all-NaN slices, NaN is returned and a `RuntimeWarning` is raised.
963
+
964
+ .. versionadded:: 1.8.0
965
+
966
+ Parameters
967
+ ----------
968
+ a : array_like
969
+ Array containing numbers whose mean is desired. If `a` is not an
970
+ array, a conversion is attempted.
971
+ axis : {int, tuple of int, None}, optional
972
+ Axis or axes along which the means are computed. The default is to compute
973
+ the mean of the flattened array.
974
+ dtype : data-type, optional
975
+ Type to use in computing the mean. For integer inputs, the default
976
+ is `float64`; for inexact inputs, it is the same as the input
977
+ dtype.
978
+ out : ndarray, optional
979
+ Alternate output array in which to place the result. The default
980
+ is ``None``; if provided, it must have the same shape as the
981
+ expected output, but the type will be cast if necessary. See
982
+ :ref:`ufuncs-output-type` for more details.
983
+ keepdims : bool, optional
984
+ If this is set to True, the axes which are reduced are left
985
+ in the result as dimensions with size one. With this option,
986
+ the result will broadcast correctly against the original `a`.
987
+
988
+ If the value is anything but the default, then
989
+ `keepdims` will be passed through to the `mean` or `sum` methods
990
+ of sub-classes of `ndarray`. If the sub-classes methods
991
+ does not implement `keepdims` any exceptions will be raised.
992
+ where : array_like of bool, optional
993
+ Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
994
+
995
+ .. versionadded:: 1.22.0
996
+
997
+ Returns
998
+ -------
999
+ m : ndarray, see dtype parameter above
1000
+ If `out=None`, returns a new array containing the mean values,
1001
+ otherwise a reference to the output array is returned. Nan is
1002
+ returned for slices that contain only NaNs.
1003
+
1004
+ See Also
1005
+ --------
1006
+ average : Weighted average
1007
+ mean : Arithmetic mean taken while not ignoring NaNs
1008
+ var, nanvar
1009
+
1010
+ Notes
1011
+ -----
1012
+ The arithmetic mean is the sum of the non-NaN elements along the axis
1013
+ divided by the number of non-NaN elements.
1014
+
1015
+ Note that for floating-point input, the mean is computed using the same
1016
+ precision the input has. Depending on the input data, this can cause
1017
+ the results to be inaccurate, especially for `float32`. Specifying a
1018
+ higher-precision accumulator using the `dtype` keyword can alleviate
1019
+ this issue.
1020
+
1021
+ Examples
1022
+ --------
1023
+ >>> a = np.array([[1, np.nan], [3, 4]])
1024
+ >>> np.nanmean(a)
1025
+ 2.6666666666666665
1026
+ >>> np.nanmean(a, axis=0)
1027
+ array([2., 4.])
1028
+ >>> np.nanmean(a, axis=1)
1029
+ array([1., 3.5]) # may vary
1030
+
1031
+ """
1032
+ arr, mask = _replace_nan(a, 0)
1033
+ if mask is None:
1034
+ return np.mean(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims,
1035
+ where=where)
1036
+
1037
+ if dtype is not None:
1038
+ dtype = np.dtype(dtype)
1039
+ if dtype is not None and not issubclass(dtype.type, np.inexact):
1040
+ raise TypeError("If a is inexact, then dtype must be inexact")
1041
+ if out is not None and not issubclass(out.dtype.type, np.inexact):
1042
+ raise TypeError("If a is inexact, then out must be inexact")
1043
+
1044
+ cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=keepdims,
1045
+ where=where)
1046
+ tot = np.sum(arr, axis=axis, dtype=dtype, out=out, keepdims=keepdims,
1047
+ where=where)
1048
+ avg = _divide_by_count(tot, cnt, out=out)
1049
+
1050
+ isbad = (cnt == 0)
1051
+ if isbad.any():
1052
+ warnings.warn("Mean of empty slice", RuntimeWarning, stacklevel=2)
1053
+ # NaN is the only possible bad value, so no further
1054
+ # action is needed to handle bad results.
1055
+ return avg
1056
+
1057
+
1058
+ def _nanmedian1d(arr1d, overwrite_input=False):
1059
+ """
1060
+ Private function for rank 1 arrays. Compute the median ignoring NaNs.
1061
+ See nanmedian for parameter usage
1062
+ """
1063
+ arr1d_parsed, overwrite_input = _remove_nan_1d(
1064
+ arr1d, overwrite_input=overwrite_input,
1065
+ )
1066
+
1067
+ if arr1d_parsed.size == 0:
1068
+ # Ensure that a nan-esque scalar of the appropriate type (and unit)
1069
+ # is returned for `timedelta64` and `complexfloating`
1070
+ return arr1d[-1]
1071
+
1072
+ return np.median(arr1d_parsed, overwrite_input=overwrite_input)
1073
+
1074
+
1075
+ def _nanmedian(a, axis=None, out=None, overwrite_input=False):
1076
+ """
1077
+ Private function that doesn't support extended axis or keepdims.
1078
+ These methods are extended to this function using _ureduce
1079
+ See nanmedian for parameter usage
1080
+
1081
+ """
1082
+ if axis is None or a.ndim == 1:
1083
+ part = a.ravel()
1084
+ if out is None:
1085
+ return _nanmedian1d(part, overwrite_input)
1086
+ else:
1087
+ out[...] = _nanmedian1d(part, overwrite_input)
1088
+ return out
1089
+ else:
1090
+ # for small medians use sort + indexing which is still faster than
1091
+ # apply_along_axis
1092
+ # benchmarked with shuffled (50, 50, x) containing a few NaN
1093
+ if a.shape[axis] < 600:
1094
+ return _nanmedian_small(a, axis, out, overwrite_input)
1095
+ result = np.apply_along_axis(_nanmedian1d, axis, a, overwrite_input)
1096
+ if out is not None:
1097
+ out[...] = result
1098
+ return result
1099
+
1100
+
1101
+ def _nanmedian_small(a, axis=None, out=None, overwrite_input=False):
1102
+ """
1103
+ sort + indexing median, faster for small medians along multiple
1104
+ dimensions due to the high overhead of apply_along_axis
1105
+
1106
+ see nanmedian for parameter usage
1107
+ """
1108
+ a = np.ma.masked_array(a, np.isnan(a))
1109
+ m = np.ma.median(a, axis=axis, overwrite_input=overwrite_input)
1110
+ for i in range(np.count_nonzero(m.mask.ravel())):
1111
+ warnings.warn("All-NaN slice encountered", RuntimeWarning,
1112
+ stacklevel=5)
1113
+
1114
+ fill_value = np.timedelta64("NaT") if m.dtype.kind == "m" else np.nan
1115
+ if out is not None:
1116
+ out[...] = m.filled(fill_value)
1117
+ return out
1118
+ return m.filled(fill_value)
1119
+
1120
+
1121
+ def _nanmedian_dispatcher(
1122
+ a, axis=None, out=None, overwrite_input=None, keepdims=None):
1123
+ return (a, out)
1124
+
1125
+
1126
+ @array_function_dispatch(_nanmedian_dispatcher)
1127
+ def nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=np._NoValue):
1128
+ """
1129
+ Compute the median along the specified axis, while ignoring NaNs.
1130
+
1131
+ Returns the median of the array elements.
1132
+
1133
+ .. versionadded:: 1.9.0
1134
+
1135
+ Parameters
1136
+ ----------
1137
+ a : array_like
1138
+ Input array or object that can be converted to an array.
1139
+ axis : {int, sequence of int, None}, optional
1140
+ Axis or axes along which the medians are computed. The default
1141
+ is to compute the median along a flattened version of the array.
1142
+ A sequence of axes is supported since version 1.9.0.
1143
+ out : ndarray, optional
1144
+ Alternative output array in which to place the result. It must
1145
+ have the same shape and buffer length as the expected output,
1146
+ but the type (of the output) will be cast if necessary.
1147
+ overwrite_input : bool, optional
1148
+ If True, then allow use of memory of input array `a` for
1149
+ calculations. The input array will be modified by the call to
1150
+ `median`. This will save memory when you do not need to preserve
1151
+ the contents of the input array. Treat the input as undefined,
1152
+ but it will probably be fully or partially sorted. Default is
1153
+ False. If `overwrite_input` is ``True`` and `a` is not already an
1154
+ `ndarray`, an error will be raised.
1155
+ keepdims : bool, optional
1156
+ If this is set to True, the axes which are reduced are left
1157
+ in the result as dimensions with size one. With this option,
1158
+ the result will broadcast correctly against the original `a`.
1159
+
1160
+ If this is anything but the default value it will be passed
1161
+ through (in the special case of an empty array) to the
1162
+ `mean` function of the underlying array. If the array is
1163
+ a sub-class and `mean` does not have the kwarg `keepdims` this
1164
+ will raise a RuntimeError.
1165
+
1166
+ Returns
1167
+ -------
1168
+ median : ndarray
1169
+ A new array holding the result. If the input contains integers
1170
+ or floats smaller than ``float64``, then the output data-type is
1171
+ ``np.float64``. Otherwise, the data-type of the output is the
1172
+ same as that of the input. If `out` is specified, that array is
1173
+ returned instead.
1174
+
1175
+ See Also
1176
+ --------
1177
+ mean, median, percentile
1178
+
1179
+ Notes
1180
+ -----
1181
+ Given a vector ``V`` of length ``N``, the median of ``V`` is the
1182
+ middle value of a sorted copy of ``V``, ``V_sorted`` - i.e.,
1183
+ ``V_sorted[(N-1)/2]``, when ``N`` is odd and the average of the two
1184
+ middle values of ``V_sorted`` when ``N`` is even.
1185
+
1186
+ Examples
1187
+ --------
1188
+ >>> a = np.array([[10.0, 7, 4], [3, 2, 1]])
1189
+ >>> a[0, 1] = np.nan
1190
+ >>> a
1191
+ array([[10., nan, 4.],
1192
+ [ 3., 2., 1.]])
1193
+ >>> np.median(a)
1194
+ nan
1195
+ >>> np.nanmedian(a)
1196
+ 3.0
1197
+ >>> np.nanmedian(a, axis=0)
1198
+ array([6.5, 2. , 2.5])
1199
+ >>> np.median(a, axis=1)
1200
+ array([nan, 2.])
1201
+ >>> b = a.copy()
1202
+ >>> np.nanmedian(b, axis=1, overwrite_input=True)
1203
+ array([7., 2.])
1204
+ >>> assert not np.all(a==b)
1205
+ >>> b = a.copy()
1206
+ >>> np.nanmedian(b, axis=None, overwrite_input=True)
1207
+ 3.0
1208
+ >>> assert not np.all(a==b)
1209
+
1210
+ """
1211
+ a = np.asanyarray(a)
1212
+ # apply_along_axis in _nanmedian doesn't handle empty arrays well,
1213
+ # so deal them upfront
1214
+ if a.size == 0:
1215
+ return np.nanmean(a, axis, out=out, keepdims=keepdims)
1216
+
1217
+ return function_base._ureduce(a, func=_nanmedian, keepdims=keepdims,
1218
+ axis=axis, out=out,
1219
+ overwrite_input=overwrite_input)
1220
+
1221
+
1222
+ def _nanpercentile_dispatcher(
1223
+ a, q, axis=None, out=None, overwrite_input=None,
1224
+ method=None, keepdims=None, *, interpolation=None):
1225
+ return (a, q, out)
1226
+
1227
+
1228
+ @array_function_dispatch(_nanpercentile_dispatcher)
1229
+ def nanpercentile(
1230
+ a,
1231
+ q,
1232
+ axis=None,
1233
+ out=None,
1234
+ overwrite_input=False,
1235
+ method="linear",
1236
+ keepdims=np._NoValue,
1237
+ *,
1238
+ interpolation=None,
1239
+ ):
1240
+ """
1241
+ Compute the qth percentile of the data along the specified axis,
1242
+ while ignoring nan values.
1243
+
1244
+ Returns the qth percentile(s) of the array elements.
1245
+
1246
+ .. versionadded:: 1.9.0
1247
+
1248
+ Parameters
1249
+ ----------
1250
+ a : array_like
1251
+ Input array or object that can be converted to an array, containing
1252
+ nan values to be ignored.
1253
+ q : array_like of float
1254
+ Percentile or sequence of percentiles to compute, which must be
1255
+ between 0 and 100 inclusive.
1256
+ axis : {int, tuple of int, None}, optional
1257
+ Axis or axes along which the percentiles are computed. The default
1258
+ is to compute the percentile(s) along a flattened version of the
1259
+ array.
1260
+ out : ndarray, optional
1261
+ Alternative output array in which to place the result. It must have
1262
+ the same shape and buffer length as the expected output, but the
1263
+ type (of the output) will be cast if necessary.
1264
+ overwrite_input : bool, optional
1265
+ If True, then allow the input array `a` to be modified by
1266
+ intermediate calculations, to save memory. In this case, the
1267
+ contents of the input `a` after this function completes is
1268
+ undefined.
1269
+ method : str, optional
1270
+ This parameter specifies the method to use for estimating the
1271
+ percentile. There are many different methods, some unique to NumPy.
1272
+ See the notes for explanation. The options sorted by their R type
1273
+ as summarized in the H&F paper [1]_ are:
1274
+
1275
+ 1. 'inverted_cdf'
1276
+ 2. 'averaged_inverted_cdf'
1277
+ 3. 'closest_observation'
1278
+ 4. 'interpolated_inverted_cdf'
1279
+ 5. 'hazen'
1280
+ 6. 'weibull'
1281
+ 7. 'linear' (default)
1282
+ 8. 'median_unbiased'
1283
+ 9. 'normal_unbiased'
1284
+
1285
+ The first three methods are discontinuous. NumPy further defines the
1286
+ following discontinuous variations of the default 'linear' (7.) option:
1287
+
1288
+ * 'lower'
1289
+ * 'higher',
1290
+ * 'midpoint'
1291
+ * 'nearest'
1292
+
1293
+ .. versionchanged:: 1.22.0
1294
+ This argument was previously called "interpolation" and only
1295
+ offered the "linear" default and last four options.
1296
+
1297
+ keepdims : bool, optional
1298
+ If this is set to True, the axes which are reduced are left in
1299
+ the result as dimensions with size one. With this option, the
1300
+ result will broadcast correctly against the original array `a`.
1301
+
1302
+ If this is anything but the default value it will be passed
1303
+ through (in the special case of an empty array) to the
1304
+ `mean` function of the underlying array. If the array is
1305
+ a sub-class and `mean` does not have the kwarg `keepdims` this
1306
+ will raise a RuntimeError.
1307
+
1308
+ interpolation : str, optional
1309
+ Deprecated name for the method keyword argument.
1310
+
1311
+ .. deprecated:: 1.22.0
1312
+
1313
+ Returns
1314
+ -------
1315
+ percentile : scalar or ndarray
1316
+ If `q` is a single percentile and `axis=None`, then the result
1317
+ is a scalar. If multiple percentiles are given, first axis of
1318
+ the result corresponds to the percentiles. The other axes are
1319
+ the axes that remain after the reduction of `a`. If the input
1320
+ contains integers or floats smaller than ``float64``, the output
1321
+ data-type is ``float64``. Otherwise, the output data-type is the
1322
+ same as that of the input. If `out` is specified, that array is
1323
+ returned instead.
1324
+
1325
+ See Also
1326
+ --------
1327
+ nanmean
1328
+ nanmedian : equivalent to ``nanpercentile(..., 50)``
1329
+ percentile, median, mean
1330
+ nanquantile : equivalent to nanpercentile, except q in range [0, 1].
1331
+
1332
+ Notes
1333
+ -----
1334
+ For more information please see `numpy.percentile`
1335
+
1336
+ Examples
1337
+ --------
1338
+ >>> a = np.array([[10., 7., 4.], [3., 2., 1.]])
1339
+ >>> a[0][1] = np.nan
1340
+ >>> a
1341
+ array([[10., nan, 4.],
1342
+ [ 3., 2., 1.]])
1343
+ >>> np.percentile(a, 50)
1344
+ nan
1345
+ >>> np.nanpercentile(a, 50)
1346
+ 3.0
1347
+ >>> np.nanpercentile(a, 50, axis=0)
1348
+ array([6.5, 2. , 2.5])
1349
+ >>> np.nanpercentile(a, 50, axis=1, keepdims=True)
1350
+ array([[7.],
1351
+ [2.]])
1352
+ >>> m = np.nanpercentile(a, 50, axis=0)
1353
+ >>> out = np.zeros_like(m)
1354
+ >>> np.nanpercentile(a, 50, axis=0, out=out)
1355
+ array([6.5, 2. , 2.5])
1356
+ >>> m
1357
+ array([6.5, 2. , 2.5])
1358
+
1359
+ >>> b = a.copy()
1360
+ >>> np.nanpercentile(b, 50, axis=1, overwrite_input=True)
1361
+ array([7., 2.])
1362
+ >>> assert not np.all(a==b)
1363
+
1364
+ References
1365
+ ----------
1366
+ .. [1] R. J. Hyndman and Y. Fan,
1367
+ "Sample quantiles in statistical packages,"
1368
+ The American Statistician, 50(4), pp. 361-365, 1996
1369
+
1370
+ """
1371
+ if interpolation is not None:
1372
+ method = function_base._check_interpolation_as_method(
1373
+ method, interpolation, "nanpercentile")
1374
+
1375
+ a = np.asanyarray(a)
1376
+ if a.dtype.kind == "c":
1377
+ raise TypeError("a must be an array of real numbers")
1378
+
1379
+ q = np.true_divide(q, 100.0)
1380
+ # undo any decay that the ufunc performed (see gh-13105)
1381
+ q = np.asanyarray(q)
1382
+ if not function_base._quantile_is_valid(q):
1383
+ raise ValueError("Percentiles must be in the range [0, 100]")
1384
+ return _nanquantile_unchecked(
1385
+ a, q, axis, out, overwrite_input, method, keepdims)
1386
+
1387
+
1388
+ def _nanquantile_dispatcher(a, q, axis=None, out=None, overwrite_input=None,
1389
+ method=None, keepdims=None, *, interpolation=None):
1390
+ return (a, q, out)
1391
+
1392
+
1393
+ @array_function_dispatch(_nanquantile_dispatcher)
1394
+ def nanquantile(
1395
+ a,
1396
+ q,
1397
+ axis=None,
1398
+ out=None,
1399
+ overwrite_input=False,
1400
+ method="linear",
1401
+ keepdims=np._NoValue,
1402
+ *,
1403
+ interpolation=None,
1404
+ ):
1405
+ """
1406
+ Compute the qth quantile of the data along the specified axis,
1407
+ while ignoring nan values.
1408
+ Returns the qth quantile(s) of the array elements.
1409
+
1410
+ .. versionadded:: 1.15.0
1411
+
1412
+ Parameters
1413
+ ----------
1414
+ a : array_like
1415
+ Input array or object that can be converted to an array, containing
1416
+ nan values to be ignored
1417
+ q : array_like of float
1418
+ Probability or sequence of probabilities for the quantiles to compute.
1419
+ Values must be between 0 and 1 inclusive.
1420
+ axis : {int, tuple of int, None}, optional
1421
+ Axis or axes along which the quantiles are computed. The
1422
+ default is to compute the quantile(s) along a flattened
1423
+ version of the array.
1424
+ out : ndarray, optional
1425
+ Alternative output array in which to place the result. It must
1426
+ have the same shape and buffer length as the expected output,
1427
+ but the type (of the output) will be cast if necessary.
1428
+ overwrite_input : bool, optional
1429
+ If True, then allow the input array `a` to be modified by intermediate
1430
+ calculations, to save memory. In this case, the contents of the input
1431
+ `a` after this function completes is undefined.
1432
+ method : str, optional
1433
+ This parameter specifies the method to use for estimating the
1434
+ quantile. There are many different methods, some unique to NumPy.
1435
+ See the notes for explanation. The options sorted by their R type
1436
+ as summarized in the H&F paper [1]_ are:
1437
+
1438
+ 1. 'inverted_cdf'
1439
+ 2. 'averaged_inverted_cdf'
1440
+ 3. 'closest_observation'
1441
+ 4. 'interpolated_inverted_cdf'
1442
+ 5. 'hazen'
1443
+ 6. 'weibull'
1444
+ 7. 'linear' (default)
1445
+ 8. 'median_unbiased'
1446
+ 9. 'normal_unbiased'
1447
+
1448
+ The first three methods are discontinuous. NumPy further defines the
1449
+ following discontinuous variations of the default 'linear' (7.) option:
1450
+
1451
+ * 'lower'
1452
+ * 'higher',
1453
+ * 'midpoint'
1454
+ * 'nearest'
1455
+
1456
+ .. versionchanged:: 1.22.0
1457
+ This argument was previously called "interpolation" and only
1458
+ offered the "linear" default and last four options.
1459
+
1460
+ keepdims : bool, optional
1461
+ If this is set to True, the axes which are reduced are left in
1462
+ the result as dimensions with size one. With this option, the
1463
+ result will broadcast correctly against the original array `a`.
1464
+
1465
+ If this is anything but the default value it will be passed
1466
+ through (in the special case of an empty array) to the
1467
+ `mean` function of the underlying array. If the array is
1468
+ a sub-class and `mean` does not have the kwarg `keepdims` this
1469
+ will raise a RuntimeError.
1470
+
1471
+ interpolation : str, optional
1472
+ Deprecated name for the method keyword argument.
1473
+
1474
+ .. deprecated:: 1.22.0
1475
+
1476
+ Returns
1477
+ -------
1478
+ quantile : scalar or ndarray
1479
+ If `q` is a single probability and `axis=None`, then the result
1480
+ is a scalar. If multiple probability levels are given, first axis of
1481
+ the result corresponds to the quantiles. The other axes are
1482
+ the axes that remain after the reduction of `a`. If the input
1483
+ contains integers or floats smaller than ``float64``, the output
1484
+ data-type is ``float64``. Otherwise, the output data-type is the
1485
+ same as that of the input. If `out` is specified, that array is
1486
+ returned instead.
1487
+
1488
+ See Also
1489
+ --------
1490
+ quantile
1491
+ nanmean, nanmedian
1492
+ nanmedian : equivalent to ``nanquantile(..., 0.5)``
1493
+ nanpercentile : same as nanquantile, but with q in the range [0, 100].
1494
+
1495
+ Notes
1496
+ -----
1497
+ For more information please see `numpy.quantile`
1498
+
1499
+ Examples
1500
+ --------
1501
+ >>> a = np.array([[10., 7., 4.], [3., 2., 1.]])
1502
+ >>> a[0][1] = np.nan
1503
+ >>> a
1504
+ array([[10., nan, 4.],
1505
+ [ 3., 2., 1.]])
1506
+ >>> np.quantile(a, 0.5)
1507
+ nan
1508
+ >>> np.nanquantile(a, 0.5)
1509
+ 3.0
1510
+ >>> np.nanquantile(a, 0.5, axis=0)
1511
+ array([6.5, 2. , 2.5])
1512
+ >>> np.nanquantile(a, 0.5, axis=1, keepdims=True)
1513
+ array([[7.],
1514
+ [2.]])
1515
+ >>> m = np.nanquantile(a, 0.5, axis=0)
1516
+ >>> out = np.zeros_like(m)
1517
+ >>> np.nanquantile(a, 0.5, axis=0, out=out)
1518
+ array([6.5, 2. , 2.5])
1519
+ >>> m
1520
+ array([6.5, 2. , 2.5])
1521
+ >>> b = a.copy()
1522
+ >>> np.nanquantile(b, 0.5, axis=1, overwrite_input=True)
1523
+ array([7., 2.])
1524
+ >>> assert not np.all(a==b)
1525
+
1526
+ References
1527
+ ----------
1528
+ .. [1] R. J. Hyndman and Y. Fan,
1529
+ "Sample quantiles in statistical packages,"
1530
+ The American Statistician, 50(4), pp. 361-365, 1996
1531
+
1532
+ """
1533
+
1534
+ if interpolation is not None:
1535
+ method = function_base._check_interpolation_as_method(
1536
+ method, interpolation, "nanquantile")
1537
+
1538
+ a = np.asanyarray(a)
1539
+ if a.dtype.kind == "c":
1540
+ raise TypeError("a must be an array of real numbers")
1541
+
1542
+ q = np.asanyarray(q)
1543
+ if not function_base._quantile_is_valid(q):
1544
+ raise ValueError("Quantiles must be in the range [0, 1]")
1545
+ return _nanquantile_unchecked(
1546
+ a, q, axis, out, overwrite_input, method, keepdims)
1547
+
1548
+
1549
+ def _nanquantile_unchecked(
1550
+ a,
1551
+ q,
1552
+ axis=None,
1553
+ out=None,
1554
+ overwrite_input=False,
1555
+ method="linear",
1556
+ keepdims=np._NoValue,
1557
+ ):
1558
+ """Assumes that q is in [0, 1], and is an ndarray"""
1559
+ # apply_along_axis in _nanpercentile doesn't handle empty arrays well,
1560
+ # so deal them upfront
1561
+ if a.size == 0:
1562
+ return np.nanmean(a, axis, out=out, keepdims=keepdims)
1563
+ return function_base._ureduce(a,
1564
+ func=_nanquantile_ureduce_func,
1565
+ q=q,
1566
+ keepdims=keepdims,
1567
+ axis=axis,
1568
+ out=out,
1569
+ overwrite_input=overwrite_input,
1570
+ method=method)
1571
+
1572
+
1573
+ def _nanquantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False,
1574
+ method="linear"):
1575
+ """
1576
+ Private function that doesn't support extended axis or keepdims.
1577
+ These methods are extended to this function using _ureduce
1578
+ See nanpercentile for parameter usage
1579
+ """
1580
+ if axis is None or a.ndim == 1:
1581
+ part = a.ravel()
1582
+ result = _nanquantile_1d(part, q, overwrite_input, method)
1583
+ else:
1584
+ result = np.apply_along_axis(_nanquantile_1d, axis, a, q,
1585
+ overwrite_input, method)
1586
+ # apply_along_axis fills in collapsed axis with results.
1587
+ # Move that axis to the beginning to match percentile's
1588
+ # convention.
1589
+ if q.ndim != 0:
1590
+ result = np.moveaxis(result, axis, 0)
1591
+
1592
+ if out is not None:
1593
+ out[...] = result
1594
+ return result
1595
+
1596
+
1597
+ def _nanquantile_1d(arr1d, q, overwrite_input=False, method="linear"):
1598
+ """
1599
+ Private function for rank 1 arrays. Compute quantile ignoring NaNs.
1600
+ See nanpercentile for parameter usage
1601
+ """
1602
+ arr1d, overwrite_input = _remove_nan_1d(arr1d,
1603
+ overwrite_input=overwrite_input)
1604
+ if arr1d.size == 0:
1605
+ # convert to scalar
1606
+ return np.full(q.shape, np.nan, dtype=arr1d.dtype)[()]
1607
+
1608
+ return function_base._quantile_unchecked(
1609
+ arr1d, q, overwrite_input=overwrite_input, method=method)
1610
+
1611
+
1612
+ def _nanvar_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
1613
+ keepdims=None, *, where=None):
1614
+ return (a, out)
1615
+
1616
+
1617
+ @array_function_dispatch(_nanvar_dispatcher)
1618
+ def nanvar(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue,
1619
+ *, where=np._NoValue):
1620
+ """
1621
+ Compute the variance along the specified axis, while ignoring NaNs.
1622
+
1623
+ Returns the variance of the array elements, a measure of the spread of
1624
+ a distribution. The variance is computed for the flattened array by
1625
+ default, otherwise over the specified axis.
1626
+
1627
+ For all-NaN slices or slices with zero degrees of freedom, NaN is
1628
+ returned and a `RuntimeWarning` is raised.
1629
+
1630
+ .. versionadded:: 1.8.0
1631
+
1632
+ Parameters
1633
+ ----------
1634
+ a : array_like
1635
+ Array containing numbers whose variance is desired. If `a` is not an
1636
+ array, a conversion is attempted.
1637
+ axis : {int, tuple of int, None}, optional
1638
+ Axis or axes along which the variance is computed. The default is to compute
1639
+ the variance of the flattened array.
1640
+ dtype : data-type, optional
1641
+ Type to use in computing the variance. For arrays of integer type
1642
+ the default is `float64`; for arrays of float types it is the same as
1643
+ the array type.
1644
+ out : ndarray, optional
1645
+ Alternate output array in which to place the result. It must have
1646
+ the same shape as the expected output, but the type is cast if
1647
+ necessary.
1648
+ ddof : int, optional
1649
+ "Delta Degrees of Freedom": the divisor used in the calculation is
1650
+ ``N - ddof``, where ``N`` represents the number of non-NaN
1651
+ elements. By default `ddof` is zero.
1652
+ keepdims : bool, optional
1653
+ If this is set to True, the axes which are reduced are left
1654
+ in the result as dimensions with size one. With this option,
1655
+ the result will broadcast correctly against the original `a`.
1656
+ where : array_like of bool, optional
1657
+ Elements to include in the variance. See `~numpy.ufunc.reduce` for
1658
+ details.
1659
+
1660
+ .. versionadded:: 1.22.0
1661
+
1662
+ Returns
1663
+ -------
1664
+ variance : ndarray, see dtype parameter above
1665
+ If `out` is None, return a new array containing the variance,
1666
+ otherwise return a reference to the output array. If ddof is >= the
1667
+ number of non-NaN elements in a slice or the slice contains only
1668
+ NaNs, then the result for that slice is NaN.
1669
+
1670
+ See Also
1671
+ --------
1672
+ std : Standard deviation
1673
+ mean : Average
1674
+ var : Variance while not ignoring NaNs
1675
+ nanstd, nanmean
1676
+ :ref:`ufuncs-output-type`
1677
+
1678
+ Notes
1679
+ -----
1680
+ The variance is the average of the squared deviations from the mean,
1681
+ i.e., ``var = mean(abs(x - x.mean())**2)``.
1682
+
1683
+ The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
1684
+ If, however, `ddof` is specified, the divisor ``N - ddof`` is used
1685
+ instead. In standard statistical practice, ``ddof=1`` provides an
1686
+ unbiased estimator of the variance of a hypothetical infinite
1687
+ population. ``ddof=0`` provides a maximum likelihood estimate of the
1688
+ variance for normally distributed variables.
1689
+
1690
+ Note that for complex numbers, the absolute value is taken before
1691
+ squaring, so that the result is always real and nonnegative.
1692
+
1693
+ For floating-point input, the variance is computed using the same
1694
+ precision the input has. Depending on the input data, this can cause
1695
+ the results to be inaccurate, especially for `float32` (see example
1696
+ below). Specifying a higher-accuracy accumulator using the ``dtype``
1697
+ keyword can alleviate this issue.
1698
+
1699
+ For this function to work on sub-classes of ndarray, they must define
1700
+ `sum` with the kwarg `keepdims`
1701
+
1702
+ Examples
1703
+ --------
1704
+ >>> a = np.array([[1, np.nan], [3, 4]])
1705
+ >>> np.nanvar(a)
1706
+ 1.5555555555555554
1707
+ >>> np.nanvar(a, axis=0)
1708
+ array([1., 0.])
1709
+ >>> np.nanvar(a, axis=1)
1710
+ array([0., 0.25]) # may vary
1711
+
1712
+ """
1713
+ arr, mask = _replace_nan(a, 0)
1714
+ if mask is None:
1715
+ return np.var(arr, axis=axis, dtype=dtype, out=out, ddof=ddof,
1716
+ keepdims=keepdims, where=where)
1717
+
1718
+ if dtype is not None:
1719
+ dtype = np.dtype(dtype)
1720
+ if dtype is not None and not issubclass(dtype.type, np.inexact):
1721
+ raise TypeError("If a is inexact, then dtype must be inexact")
1722
+ if out is not None and not issubclass(out.dtype.type, np.inexact):
1723
+ raise TypeError("If a is inexact, then out must be inexact")
1724
+
1725
+ # Compute mean
1726
+ if type(arr) is np.matrix:
1727
+ _keepdims = np._NoValue
1728
+ else:
1729
+ _keepdims = True
1730
+ # we need to special case matrix for reverse compatibility
1731
+ # in order for this to work, these sums need to be called with
1732
+ # keepdims=True, however matrix now raises an error in this case, but
1733
+ # the reason that it drops the keepdims kwarg is to force keepdims=True
1734
+ # so this used to work by serendipity.
1735
+ cnt = np.sum(~mask, axis=axis, dtype=np.intp, keepdims=_keepdims,
1736
+ where=where)
1737
+ avg = np.sum(arr, axis=axis, dtype=dtype, keepdims=_keepdims, where=where)
1738
+ avg = _divide_by_count(avg, cnt)
1739
+
1740
+ # Compute squared deviation from mean.
1741
+ np.subtract(arr, avg, out=arr, casting='unsafe', where=where)
1742
+ arr = _copyto(arr, 0, mask)
1743
+ if issubclass(arr.dtype.type, np.complexfloating):
1744
+ sqr = np.multiply(arr, arr.conj(), out=arr, where=where).real
1745
+ else:
1746
+ sqr = np.multiply(arr, arr, out=arr, where=where)
1747
+
1748
+ # Compute variance.
1749
+ var = np.sum(sqr, axis=axis, dtype=dtype, out=out, keepdims=keepdims,
1750
+ where=where)
1751
+
1752
+ # Precaution against reduced object arrays
1753
+ try:
1754
+ var_ndim = var.ndim
1755
+ except AttributeError:
1756
+ var_ndim = np.ndim(var)
1757
+ if var_ndim < cnt.ndim:
1758
+ # Subclasses of ndarray may ignore keepdims, so check here.
1759
+ cnt = cnt.squeeze(axis)
1760
+ dof = cnt - ddof
1761
+ var = _divide_by_count(var, dof)
1762
+
1763
+ isbad = (dof <= 0)
1764
+ if np.any(isbad):
1765
+ warnings.warn("Degrees of freedom <= 0 for slice.", RuntimeWarning,
1766
+ stacklevel=2)
1767
+ # NaN, inf, or negative numbers are all possible bad
1768
+ # values, so explicitly replace them with NaN.
1769
+ var = _copyto(var, np.nan, isbad)
1770
+ return var
1771
+
1772
+
1773
+ def _nanstd_dispatcher(a, axis=None, dtype=None, out=None, ddof=None,
1774
+ keepdims=None, *, where=None):
1775
+ return (a, out)
1776
+
1777
+
1778
+ @array_function_dispatch(_nanstd_dispatcher)
1779
+ def nanstd(a, axis=None, dtype=None, out=None, ddof=0, keepdims=np._NoValue,
1780
+ *, where=np._NoValue):
1781
+ """
1782
+ Compute the standard deviation along the specified axis, while
1783
+ ignoring NaNs.
1784
+
1785
+ Returns the standard deviation, a measure of the spread of a
1786
+ distribution, of the non-NaN array elements. The standard deviation is
1787
+ computed for the flattened array by default, otherwise over the
1788
+ specified axis.
1789
+
1790
+ For all-NaN slices or slices with zero degrees of freedom, NaN is
1791
+ returned and a `RuntimeWarning` is raised.
1792
+
1793
+ .. versionadded:: 1.8.0
1794
+
1795
+ Parameters
1796
+ ----------
1797
+ a : array_like
1798
+ Calculate the standard deviation of the non-NaN values.
1799
+ axis : {int, tuple of int, None}, optional
1800
+ Axis or axes along which the standard deviation is computed. The default is
1801
+ to compute the standard deviation of the flattened array.
1802
+ dtype : dtype, optional
1803
+ Type to use in computing the standard deviation. For arrays of
1804
+ integer type the default is float64, for arrays of float types it
1805
+ is the same as the array type.
1806
+ out : ndarray, optional
1807
+ Alternative output array in which to place the result. It must have
1808
+ the same shape as the expected output but the type (of the
1809
+ calculated values) will be cast if necessary.
1810
+ ddof : int, optional
1811
+ Means Delta Degrees of Freedom. The divisor used in calculations
1812
+ is ``N - ddof``, where ``N`` represents the number of non-NaN
1813
+ elements. By default `ddof` is zero.
1814
+
1815
+ keepdims : bool, optional
1816
+ If this is set to True, the axes which are reduced are left
1817
+ in the result as dimensions with size one. With this option,
1818
+ the result will broadcast correctly against the original `a`.
1819
+
1820
+ If this value is anything but the default it is passed through
1821
+ as-is to the relevant functions of the sub-classes. If these
1822
+ functions do not have a `keepdims` kwarg, a RuntimeError will
1823
+ be raised.
1824
+ where : array_like of bool, optional
1825
+ Elements to include in the standard deviation.
1826
+ See `~numpy.ufunc.reduce` for details.
1827
+
1828
+ .. versionadded:: 1.22.0
1829
+
1830
+ Returns
1831
+ -------
1832
+ standard_deviation : ndarray, see dtype parameter above.
1833
+ If `out` is None, return a new array containing the standard
1834
+ deviation, otherwise return a reference to the output array. If
1835
+ ddof is >= the number of non-NaN elements in a slice or the slice
1836
+ contains only NaNs, then the result for that slice is NaN.
1837
+
1838
+ See Also
1839
+ --------
1840
+ var, mean, std
1841
+ nanvar, nanmean
1842
+ :ref:`ufuncs-output-type`
1843
+
1844
+ Notes
1845
+ -----
1846
+ The standard deviation is the square root of the average of the squared
1847
+ deviations from the mean: ``std = sqrt(mean(abs(x - x.mean())**2))``.
1848
+
1849
+ The average squared deviation is normally calculated as
1850
+ ``x.sum() / N``, where ``N = len(x)``. If, however, `ddof` is
1851
+ specified, the divisor ``N - ddof`` is used instead. In standard
1852
+ statistical practice, ``ddof=1`` provides an unbiased estimator of the
1853
+ variance of the infinite population. ``ddof=0`` provides a maximum
1854
+ likelihood estimate of the variance for normally distributed variables.
1855
+ The standard deviation computed in this function is the square root of
1856
+ the estimated variance, so even with ``ddof=1``, it will not be an
1857
+ unbiased estimate of the standard deviation per se.
1858
+
1859
+ Note that, for complex numbers, `std` takes the absolute value before
1860
+ squaring, so that the result is always real and nonnegative.
1861
+
1862
+ For floating-point input, the *std* is computed using the same
1863
+ precision the input has. Depending on the input data, this can cause
1864
+ the results to be inaccurate, especially for float32 (see example
1865
+ below). Specifying a higher-accuracy accumulator using the `dtype`
1866
+ keyword can alleviate this issue.
1867
+
1868
+ Examples
1869
+ --------
1870
+ >>> a = np.array([[1, np.nan], [3, 4]])
1871
+ >>> np.nanstd(a)
1872
+ 1.247219128924647
1873
+ >>> np.nanstd(a, axis=0)
1874
+ array([1., 0.])
1875
+ >>> np.nanstd(a, axis=1)
1876
+ array([0., 0.5]) # may vary
1877
+
1878
+ """
1879
+ var = nanvar(a, axis=axis, dtype=dtype, out=out, ddof=ddof,
1880
+ keepdims=keepdims, where=where)
1881
+ if isinstance(var, np.ndarray):
1882
+ std = np.sqrt(var, out=var)
1883
+ elif hasattr(var, 'dtype'):
1884
+ std = var.dtype.type(np.sqrt(var))
1885
+ else:
1886
+ std = np.sqrt(var)
1887
+ return std
shared/package-files/e8/e84a407dd098ad1fb759018e47c8be69ce14518cc9a5276fbe6a2da4c8a45c79/blob ADDED
Binary file (90 Bytes). View file
 
shared/package-files/e8/e84c42c1830fa80754bc231d74f16e3a9d6b6d5683eb3d8fdc693564502d63a6/blob ADDED
@@ -0,0 +1,955 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests that use cross-checks for generic methods
2
+
3
+ Should be easy to check consistency across models
4
+ Does not cover tsa
5
+
6
+ Initial cases copied from test_shrink_pickle
7
+
8
+ Created on Wed Oct 30 14:01:27 2013
9
+
10
+ Author: Josef Perktold
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from statsmodels.compat.pandas import assert_index_equal, assert_series_equal
16
+ from statsmodels.compat.platform import (
17
+ PLATFORM_OSX,
18
+ PLATFORM_WIN32,
19
+ )
20
+ from statsmodels.compat.pytest import pytest_warns
21
+ from statsmodels.compat.python import PYTHON_IMPL_WASM
22
+
23
+ import numpy as np
24
+ from numpy.testing import (
25
+ assert_,
26
+ assert_allclose,
27
+ assert_array_equal,
28
+ assert_equal,
29
+ )
30
+ import pandas as pd
31
+ import pytest
32
+
33
+ import statsmodels.api as sm
34
+ from statsmodels.formula._manager import FormulaManager
35
+ from statsmodels.formula.api import glm, ols
36
+ import statsmodels.tools._testing as smt
37
+ from statsmodels.tools.sm_exceptions import (
38
+ HessianInversionWarning,
39
+ SingularMatrixWarning,
40
+ )
41
+
42
+
43
+ class CheckGenericMixinBase:
44
+
45
+ def setup_method(self):
46
+ nobs = 500
47
+ rs = np.random.RandomState(987689)
48
+ x = rs.randn(nobs, 3)
49
+ x = sm.add_constant(x)
50
+ self.exog = x
51
+ self.xf = 0.25 * np.ones((2, 4))
52
+ self.predict_kwds = {}
53
+ self.transform_index = None
54
+
55
+ def test_ttest_tvalues(self):
56
+ # test that t_test has same results a params, bse, tvalues, ...
57
+ smt.check_ttest_tvalues(self.results)
58
+
59
+ res = self.results
60
+ mat = np.eye(len(res.params))
61
+
62
+ tt = res.t_test(mat[0])
63
+
64
+ def string_confint(alpha):
65
+ return f"[{(alpha / 2):4.3F} {(1 - alpha / 2):4.3F}]"
66
+
67
+ summ = tt.summary() # smoke test for #1323
68
+ assert_allclose(tt.pvalue, res.pvalues[0], rtol=5e-10)
69
+ assert_(string_confint(0.05) in str(summ))
70
+
71
+ # issue #3116 alpha not used in column headers
72
+ summ = tt.summary(alpha=0.1)
73
+ ss = "[0.05 0.95]" # different formatting
74
+ assert_(ss in str(summ))
75
+
76
+ summf = tt.summary_frame(alpha=0.1)
77
+ pvstring_use_t = "P>|z|" if res.use_t is False else "P>|t|"
78
+ tstring_use_t = "z" if res.use_t is False else "t"
79
+ cols = [
80
+ "coef",
81
+ "std err",
82
+ tstring_use_t,
83
+ pvstring_use_t,
84
+ "Conf. Int. Low",
85
+ "Conf. Int. Upp.",
86
+ ]
87
+ assert_array_equal(summf.columns.values, cols)
88
+
89
+ def test_ftest_pvalues(self):
90
+ smt.check_ftest_pvalues(self.results)
91
+
92
+ def test_fitted(self):
93
+ smt.check_fitted(self.results)
94
+
95
+ def test_predict_types(self):
96
+ smt.check_predict_types(self.results)
97
+
98
+ def _get_constrained(self, keep_index, keep_index_p):
99
+ # override in some test classes, no fit_kwds yet, e.g., cov_type
100
+ mod2 = self.results.model
101
+ mod_cls = mod2.__class__
102
+ init_kwds = mod2._get_init_kwds()
103
+ mod = mod_cls(mod2.endog, mod2.exog[:, keep_index], **init_kwds)
104
+ if self.use_start_params:
105
+ res = mod.fit(start_params=self.results.params[keep_index_p], maxiter=500)
106
+ else:
107
+ res = mod.fit(maxiter=500)
108
+ return res
109
+
110
+ @pytest.mark.thread_unsafe(reason="Model is mutable including using del")
111
+ def test_zero_collinear(self):
112
+ # not completely generic yet
113
+ if isinstance(self.results.model, (sm.GEE)):
114
+ pytest.skip("Not completely generic yet")
115
+
116
+ use_start_params = not isinstance(
117
+ self.results.model, (sm.RLM, sm.OLS, sm.WLS, sm.GLM)
118
+ )
119
+ self.use_start_params = use_start_params # attach for _get_constrained
120
+ keep_index = list(range(self.results.model.exog.shape[1]))
121
+ # index for params might include extra params
122
+ keep_index_p = list(range(self.results.params.shape[0]))
123
+ drop_index = []
124
+ for i in drop_index:
125
+ del keep_index[i]
126
+ del keep_index_p[i]
127
+
128
+ keep_index_p = list(range(self.results.params.shape[0]))
129
+
130
+ # create collinear model
131
+ mod2 = self.results.model
132
+ mod_cls = mod2.__class__
133
+ init_kwds = mod2._get_init_kwds()
134
+ ex = np.column_stack((mod2.exog, mod2.exog))
135
+ mod = mod_cls(mod2.endog, ex, **init_kwds)
136
+
137
+ keep_index = list(range(self.results.model.exog.shape[1]))
138
+ keep_index_p = list(range(self.results.model.exog.shape[1]))
139
+ k_vars = ex.shape[1]
140
+ k_extra = 0
141
+ if hasattr(mod, "k_extra") and mod.k_extra > 0:
142
+ keep_index_p += list(range(k_vars, k_vars + mod.k_extra))
143
+ k_extra = mod.k_extra
144
+
145
+ # TODO: Can we choose a test case without this issue?
146
+ # If not, should we be getting this warning for all
147
+ # model subclasses?
148
+ # TODO: Investigate how to resolve unseen warnings for Pyodide
149
+ # Most likely coming from NumPy.linalg + lack of fp exceptions
150
+ # support under WASM
151
+ if isinstance(mod, sm.GLM) and not PYTHON_IMPL_WASM:
152
+ warn_cls = HessianInversionWarning
153
+ elif self.__class__.__name__ == "TestGenericOLSOneExog" and PYTHON_IMPL_WASM:
154
+ # Workaround for likely bug in WASM
155
+ warn_cls = None
156
+ elif isinstance(mod, (sm.WLS, sm.GLS, sm.RLM)):
157
+ warn_cls = SingularMatrixWarning
158
+ else:
159
+ warn_cls = None
160
+
161
+ cov_types = ["nonrobust", "HC0"]
162
+
163
+ for cov_type in cov_types:
164
+ # Note: for RLM we only check default when cov_type is 'nonrobust'
165
+ # cov_type is otherwise ignored
166
+ if cov_type != "nonrobust" and (isinstance(self.results.model, sm.RLM)):
167
+ return
168
+
169
+ if use_start_params:
170
+ start_params = np.zeros(k_vars + k_extra)
171
+ method = self.results.mle_settings["optimizer"]
172
+ # string in `method` is not mutable, so no need for copy
173
+ sp = self.results.mle_settings["start_params"].copy()
174
+ if self.transform_index is not None:
175
+ # work around internal transform_params, currently in NB
176
+ sp[self.transform_index] = np.exp(sp[self.transform_index])
177
+
178
+ start_params[keep_index_p] = sp
179
+ with pytest_warns(warn_cls):
180
+ res1 = mod._fit_collinear(
181
+ cov_type=cov_type,
182
+ start_params=start_params,
183
+ method=method,
184
+ disp=0,
185
+ )
186
+ if cov_type != "nonrobust":
187
+ # reestimate original model to get robust cov
188
+ with pytest_warns(warn_cls):
189
+ res2 = self.results.model.fit(
190
+ cov_type=cov_type, start_params=sp, method=method, disp=0
191
+ )
192
+ else:
193
+ # TODO: _fit_collinear is clearly broken with OLS/WLS/GLS/RLM
194
+ # Should be fixed in one of these classes.
195
+ # For now just skip the test for these classes
196
+ with pytest_warns(warn_cls):
197
+ # more special casing RLM
198
+ if isinstance(self.results.model, (sm.RLM)):
199
+ res1 = mod._fit_collinear()
200
+ else:
201
+ res1 = mod._fit_collinear(cov_type=cov_type)
202
+ if cov_type != "nonrobust":
203
+ # reestimate original model to get robust cov
204
+ res2 = self.results.model.fit(cov_type=cov_type)
205
+
206
+ if cov_type == "nonrobust":
207
+ res2 = self.results
208
+
209
+ # check fit optimizer arguments, if mle_settings is available
210
+ if hasattr(res2, "mle_settings"):
211
+ assert_equal(
212
+ res1.results_constrained.mle_settings["optimizer"],
213
+ res2.mle_settings["optimizer"],
214
+ )
215
+ if "start_params" in res2.mle_settings:
216
+ spc = res1.results_constrained.mle_settings["start_params"]
217
+ assert_allclose(
218
+ spc, res2.mle_settings["start_params"], rtol=1e-10, atol=1e-20
219
+ )
220
+ assert_equal(
221
+ res1.mle_settings["optimizer"], res2.mle_settings["optimizer"]
222
+ )
223
+ assert_allclose(
224
+ res1.mle_settings["start_params"],
225
+ res2.mle_settings["start_params"],
226
+ rtol=1e-10,
227
+ atol=1e-20,
228
+ )
229
+
230
+ # Poisson has reduced precision in params, difficult optimization?
231
+ assert_allclose(res1.params[keep_index_p], res2.params, rtol=1e-6)
232
+ assert_allclose(res1.params[drop_index], 0, rtol=1e-10)
233
+ assert_allclose(res1.bse[keep_index_p], res2.bse, rtol=1e-8)
234
+ assert_allclose(res1.bse[drop_index], 0, rtol=1e-10)
235
+ tvals1 = res1.tvalues[keep_index_p]
236
+ assert_allclose(tvals1, res2.tvalues, rtol=5e-8)
237
+
238
+ # See gh5993
239
+ pvals1 = res1.pvalues[keep_index_p]
240
+ assert_allclose(pvals1, res2.pvalues, rtol=1e-6, atol=1e-30)
241
+
242
+ if hasattr(res1, "resid"):
243
+ # discrete models, Logit do not have `resid` yet
244
+ assert_allclose(res1.resid, res2.resid, rtol=1e-5, atol=1e-10)
245
+
246
+ ex = res1.model.exog.mean(0)
247
+ predicted1 = res1.predict(ex, **self.predict_kwds)
248
+ predicted2 = res2.predict(ex[keep_index], **self.predict_kwds)
249
+ assert_allclose(predicted1, predicted2, rtol=1e-8, atol=1e-11)
250
+
251
+ ex = res1.model.exog[:5]
252
+ kwds = getattr(self, "predict_kwds_5", {})
253
+
254
+ predicted1 = res1.predict(ex, **kwds)
255
+ predicted2 = res2.predict(ex[:, keep_index], **kwds)
256
+ assert_allclose(predicted1, predicted2, rtol=1e-8, atol=1e-11)
257
+
258
+
259
+ # subclasses for individual models, unchanged from test_shrink_pickle
260
+ # TODO: check if setup_class is faster than setup
261
+
262
+
263
+ class CheckGenericMixin(CheckGenericMixinBase):
264
+ def test_zero_constrained(self):
265
+ # not completely generic yet
266
+ if isinstance(self.results.model, (sm.GEE)):
267
+ # GEE does not subclass LikelihoodModel
268
+ pytest.skip("GEE does not subclass LikelihoodModel")
269
+
270
+ use_start_params = not isinstance(self.results.model, (sm.RLM, sm.OLS, sm.WLS))
271
+ self.use_start_params = use_start_params # attach for _get_constrained
272
+
273
+ keep_index = list(range(self.results.model.exog.shape[1]))
274
+ # index for params might include extra params
275
+ keep_index_p = list(range(self.results.params.shape[0]))
276
+ drop_index = [1]
277
+ for i in drop_index:
278
+ del keep_index[i]
279
+ del keep_index_p[i]
280
+
281
+ if use_start_params:
282
+ res1 = self.results.model._fit_zeros(
283
+ keep_index, maxiter=500, start_params=self.results.params
284
+ )
285
+ else:
286
+ res1 = self.results.model._fit_zeros(keep_index, maxiter=500)
287
+
288
+ res2 = self._get_constrained(keep_index, keep_index_p)
289
+
290
+ assert_allclose(res1.params[keep_index_p], res2.params, rtol=1e-10, atol=1e-10)
291
+ assert_equal(res1.params[drop_index], 0)
292
+ assert_allclose(res1.bse[keep_index_p], res2.bse, rtol=1e-10, atol=1e-10)
293
+ assert_equal(res1.bse[drop_index], 0)
294
+ # OSX has many slight failures on this test
295
+ tol = 1e-8 if PLATFORM_OSX else 1e-10
296
+ tvals1 = res1.tvalues[keep_index_p]
297
+ assert_allclose(tvals1, res2.tvalues, rtol=tol, atol=tol)
298
+
299
+ # See gh5993
300
+ pvals1 = res1.pvalues[keep_index_p]
301
+ assert_allclose(pvals1, res2.pvalues, rtol=tol, atol=tol)
302
+
303
+ if hasattr(res1, "resid"):
304
+ # discrete models, Logit do not have `resid` yet
305
+ # atol discussion at gh-5158
306
+ rtol = 1e-10
307
+ atol = 1e-12
308
+ if PLATFORM_OSX or PLATFORM_WIN32:
309
+ # GH 5628
310
+ rtol = 1e-8
311
+ atol = 1e-10
312
+ assert_allclose(res1.resid, res2.resid, rtol=rtol, atol=atol)
313
+
314
+ ex = self.results.model.exog.mean(0)
315
+ predicted1 = res1.predict(ex, **self.predict_kwds)
316
+ predicted2 = res2.predict(ex[keep_index], **self.predict_kwds)
317
+ assert_allclose(predicted1, predicted2, rtol=1e-10)
318
+
319
+ ex = self.results.model.exog[:5]
320
+ predicted1 = res1.predict(ex, **self.predict_kwds)
321
+ predicted2 = res2.predict(ex[:, keep_index], **self.predict_kwds)
322
+ assert_allclose(predicted1, predicted2, rtol=1e-10)
323
+
324
+
325
+ @pytest.fixture
326
+ def data():
327
+ nobs = 500
328
+ rs = np.random.RandomState(987689)
329
+ x = rs.randn(nobs, 3)
330
+ x = sm.add_constant(x)
331
+ xf = 0.25 * np.ones((2, 4))
332
+ predict_kwds = {}
333
+ transform_index = None
334
+ return x, xf, predict_kwds, transform_index
335
+
336
+
337
+ @pytest.fixture
338
+ def fit_model(data):
339
+ x, _, _, _ = data
340
+ rs = np.random.RandomState(987689)
341
+ y = x.sum(axis=1) + rs.randn(x.shape[0])
342
+ res = sm.OLS(y, x).fit()
343
+ return res
344
+
345
+
346
+ def test_ttest_tvalues(fit_model):
347
+ # test that t_test has same results a params, bse, tvalues, ...
348
+ smt.check_ttest_tvalues(fit_model)
349
+
350
+ res = fit_model
351
+ mat = np.eye(len(res.params))
352
+
353
+ tt = res.t_test(mat[0])
354
+
355
+ def string_confint(alpha):
356
+ return f"[{(alpha / 2):4.3F} {(1 - alpha / 2):4.3F}]"
357
+
358
+ summ = tt.summary() # smoke test for #1323
359
+ assert_allclose(tt.pvalue, res.pvalues[0], rtol=5e-10)
360
+ assert_(string_confint(0.05) in str(summ))
361
+
362
+ # issue #3116 alpha not used in column headers
363
+ summ = tt.summary(alpha=0.1)
364
+ ss = "[0.05 0.95]" # different formatting
365
+ assert_(ss in str(summ))
366
+
367
+ summf = tt.summary_frame(alpha=0.1)
368
+ pvstring_use_t = "P>|z|" if res.use_t is False else "P>|t|"
369
+ tstring_use_t = "z" if res.use_t is False else "t"
370
+ cols = [
371
+ "coef",
372
+ "std err",
373
+ tstring_use_t,
374
+ pvstring_use_t,
375
+ "Conf. Int. Low",
376
+ "Conf. Int. Upp.",
377
+ ]
378
+ assert_array_equal(summf.columns.values, cols)
379
+
380
+
381
+ class TestGenericOLS(CheckGenericMixin):
382
+
383
+ def setup_method(self):
384
+ # fit for each test, because results will be changed by test
385
+ super().setup_method()
386
+ x = self.exog
387
+ rs = np.random.RandomState(987689)
388
+ y = x.sum(axis=1) + rs.randn(x.shape[0])
389
+ self.results = sm.OLS(y, self.exog).fit()
390
+
391
+
392
+ class TestGenericOLSOneExog(CheckGenericMixin):
393
+ # check with single regressor (no constant)
394
+
395
+ def setup_method(self):
396
+ # fit for each test, because results will be changed by test
397
+ super().setup_method()
398
+ x = self.exog[:, 1]
399
+ rs = np.random.RandomState(987689)
400
+ y = x + rs.randn(x.shape[0])
401
+ self.results = sm.OLS(y, x).fit()
402
+
403
+ def test_zero_constrained(self):
404
+ # override, we cannot remove the only regressor
405
+ pytest.skip("Override since cannot remove the only regressor")
406
+
407
+
408
+ class TestGenericWLS(CheckGenericMixin):
409
+
410
+ def setup_method(self):
411
+ # fit for each test, because results will be changed by test
412
+ super().setup_method()
413
+ x = self.exog
414
+ rs = np.random.RandomState(987689)
415
+ y = x.sum(axis=1) + rs.randn(x.shape[0])
416
+ self.results = sm.WLS(y, self.exog, weights=np.ones(len(y))).fit()
417
+
418
+
419
+ class TestGenericPoisson(CheckGenericMixin):
420
+
421
+ def setup_method(self):
422
+ # fit for each test, because results will be changed by test
423
+ super().setup_method()
424
+ x = self.exog
425
+ rs = np.random.RandomState(987689)
426
+ y_count = rs.poisson(np.exp(x.sum(1) - x.mean()))
427
+ model = sm.Poisson(y_count, x)
428
+ # use start_params to converge faster
429
+ start_params = np.array([0.75334818, 0.99425553, 1.00494724, 1.00247112])
430
+ self.results = model.fit(start_params=start_params, method="bfgs", disp=0)
431
+
432
+
433
+ class TestGenericPoissonOffset(CheckGenericMixin):
434
+
435
+ def setup_method(self):
436
+ # fit for each test, because results will be changed by test
437
+ super().setup_method()
438
+ x = self.exog
439
+ nobs = x.shape[0]
440
+ rs = np.random.RandomState(987689)
441
+ y_count = rs.poisson(np.exp(x.sum(1) - x.mean()))
442
+ model = sm.Poisson(
443
+ y_count, x, offset=0.01 * np.ones(nobs), exposure=np.ones(nobs)
444
+ ) # bug with default
445
+ # use start_params to converge faster
446
+ start_params = np.array([0.75334818, 0.99425553, 1.00494724, 1.00247112])
447
+ self.results = model.fit(start_params=start_params, method="bfgs", disp=0)
448
+
449
+ self.predict_kwds_5 = dict(exposure=0.01 * np.ones(5), offset=np.ones(5))
450
+ self.predict_kwds = dict(exposure=1, offset=0)
451
+
452
+
453
+ class TestGenericNegativeBinomial(CheckGenericMixin):
454
+
455
+ def setup_method(self):
456
+ # fit for each test, because results will be changed by test
457
+ super().setup_method()
458
+ data = sm.datasets.randhie.load()
459
+ data.exog = np.asarray(data.exog)
460
+ data.endog = np.asarray(data.endog)
461
+ exog = sm.add_constant(data.exog, prepend=False)
462
+ mod = sm.NegativeBinomial(data.endog, exog)
463
+ start_params = np.array(
464
+ [
465
+ -0.05783623,
466
+ -0.26655806,
467
+ 0.04109148,
468
+ -0.03815837,
469
+ 0.2685168,
470
+ 0.03811594,
471
+ -0.04426238,
472
+ 0.01614795,
473
+ 0.17490962,
474
+ 0.66461151,
475
+ 1.29259570,
476
+ ]
477
+ )
478
+ self.results = mod.fit(start_params=start_params, disp=0, maxiter=500)
479
+ self.transform_index = -1
480
+
481
+
482
+ class TestGenericLogit(CheckGenericMixin):
483
+
484
+ def setup_method(self):
485
+ # fit for each test, because results will be changed by test
486
+ super().setup_method()
487
+ x = self.exog
488
+ nobs = x.shape[0]
489
+ rs = np.random.RandomState(987689)
490
+ y_bin = (rs.rand(nobs) < 1.0 / (1 + np.exp(x.sum(1) - x.mean()))).astype(int)
491
+ model = sm.Logit(y_bin, x) # ,exposure=np.ones(nobs), offset=np.zeros(nobs))
492
+ # # bug with default
493
+ # use start_params to converge faster
494
+ start_params = np.array([-0.73403806, -1.00901514, -0.97754543, -0.95648212])
495
+ with pytest.warns(FutureWarning, match="Keyword arguments have been passed"):
496
+ self.results = model.fit(
497
+ start_params=start_params, method="bfgs", disp=0, tol=1e-5
498
+ )
499
+
500
+
501
+ class TestGenericRLM(CheckGenericMixin):
502
+
503
+ def setup_method(self):
504
+ # fit for each test, because results will be changed by test
505
+ super().setup_method()
506
+ x = self.exog
507
+ rs = np.random.RandomState(987689)
508
+ y = x.sum(axis=1) + rs.randn(x.shape[0])
509
+ self.results = sm.RLM(y, self.exog).fit()
510
+
511
+
512
+ class TestGenericGLM(CheckGenericMixin):
513
+
514
+ def setup_method(self):
515
+ # fit for each test, because results will be changed by test
516
+ super().setup_method()
517
+ x = self.exog
518
+ rs = np.random.RandomState(987689)
519
+ y = x.sum(axis=1) + rs.randn(x.shape[0])
520
+ self.results = sm.GLM(y, self.exog).fit()
521
+
522
+ @pytest.mark.thread_unsafe(reason="Modifies the model object in test")
523
+ def test_zero_constrained(self):
524
+ super().test_zero_constrained()
525
+
526
+
527
+ class TestGenericGLMPoissonOffset(CheckGenericMixin):
528
+
529
+ def setup_method(self):
530
+ # fit for each test, because results will be changed by test
531
+ super().setup_method()
532
+ x = self.exog
533
+ nobs = x.shape[0]
534
+ rs = np.random.RandomState(987689)
535
+ y_count = rs.poisson(np.exp(x.sum(1) - x.mean()))
536
+ model = sm.GLM(
537
+ y_count,
538
+ x,
539
+ family=sm.families.Poisson(),
540
+ offset=0.01 * np.ones(nobs),
541
+ exposure=np.ones(nobs),
542
+ )
543
+ # use start_params to converge faster
544
+ start_params = np.array([0.75334818, 0.99425553, 1.00494724, 1.00247112])
545
+ self.results = model.fit(start_params=start_params, method="bfgs", disp=0)
546
+
547
+ self.predict_kwds_5 = dict(exposure=0.01 * np.ones(5), offset=np.ones(5))
548
+ self.predict_kwds = dict(exposure=1, offset=0)
549
+
550
+ @pytest.mark.thread_unsafe(reason="Modifies the model object in test")
551
+ def test_zero_constrained(self):
552
+ super().test_zero_constrained()
553
+
554
+
555
+ class TestGenericGEEPoisson(CheckGenericMixin):
556
+
557
+ def setup_method(self):
558
+ # fit for each test, because results will be changed by test
559
+ super().setup_method()
560
+ x = self.exog
561
+ rs = np.random.RandomState(987689)
562
+ y_count = rs.poisson(np.exp(x.sum(1) - x.mean()))
563
+ groups = rs.randint(0, 4, size=x.shape[0])
564
+ # use start_params to speed up test, difficult convergence not tested
565
+
566
+ start_params = np.array([0.0, 1.0, 1.0, 1.0])
567
+
568
+ vi = sm.cov_struct.Independence()
569
+ family = sm.families.Poisson()
570
+ self.results = sm.GEE(
571
+ y_count, self.exog, groups, family=family, cov_struct=vi
572
+ ).fit(start_params=start_params)
573
+
574
+
575
+ class TestGenericGEEPoissonNaive(CheckGenericMixin):
576
+
577
+ def setup_method(self):
578
+ # fit for each test, because results will be changed by test
579
+ super().setup_method()
580
+ x = self.exog
581
+ rs = np.random.RandomState(987689)
582
+ # y_count = rs.poisson(np.exp(x.sum(1) - x.mean()))
583
+
584
+ y_count = rs.poisson(np.exp(x.sum(1) - x.sum(1).mean(0)))
585
+ groups = rs.randint(0, 4, size=x.shape[0])
586
+ # use start_params to speed up test, difficult convergence not tested
587
+
588
+ start_params = np.array([0.0, 1.0, 1.0, 1.0])
589
+
590
+ vi = sm.cov_struct.Independence()
591
+ family = sm.families.Poisson()
592
+ self.results = sm.GEE(
593
+ y_count, self.exog, groups, family=family, cov_struct=vi
594
+ ).fit(start_params=start_params, cov_type="naive")
595
+
596
+
597
+ class TestGenericGEEPoissonBC(CheckGenericMixin):
598
+
599
+ def setup_method(self):
600
+ # fit for each test, because results will be changed by test
601
+ super().setup_method()
602
+ x = self.exog
603
+ rs = np.random.RandomState(987689)
604
+ # y_count = rs.poisson(np.exp(x.sum(1) - x.mean()))
605
+ y_count = rs.poisson(np.exp(x.sum(1) - x.sum(1).mean(0)))
606
+ groups = rs.randint(0, 4, size=x.shape[0])
607
+ # use start_params to speed up test, difficult convergence not tested
608
+ start_params = np.array([0.0, 1.0, 1.0, 1.0])
609
+ # params_est = np.array([-0.0063238 , 0.99463752, 1.02790201, 0.98080081])
610
+
611
+ vi = sm.cov_struct.Independence()
612
+ family = sm.families.Poisson()
613
+ mod = sm.GEE(y_count, self.exog, groups, family=family, cov_struct=vi)
614
+ self.results = mod.fit(start_params=start_params, cov_type="bias_reduced")
615
+
616
+
617
+ # Other test classes
618
+
619
+
620
+ class CheckAnovaMixin:
621
+
622
+ def setup_method(self):
623
+ import statsmodels.stats.tests.test_anova as ttmod
624
+
625
+ self.data = ttmod.kidney_table.drop([0, 1, 2])
626
+ self.initialize()
627
+
628
+ def test_combined(self):
629
+ res = self.res
630
+ wa = res.wald_test_terms(
631
+ skip_single=False, combine_terms=["Duration", "Weight"], scalar=True
632
+ )
633
+ eye = np.eye(len(res.params))
634
+ c_const = eye[0]
635
+ c_w = eye[[2, 3]]
636
+ c_d = eye[1]
637
+ c_dw = eye[[4, 5]]
638
+ c_weight = eye[2:6]
639
+ c_duration = eye[[1, 4, 5]]
640
+
641
+ compare_waldres(res, wa, [c_const, c_d, c_w, c_dw, c_duration, c_weight])
642
+
643
+ def test_categories(self):
644
+ # test only multicolumn terms
645
+ res = self.res
646
+ wa = res.wald_test_terms(skip_single=True, scalar=True)
647
+ eye = np.eye(len(res.params))
648
+ c_w = eye[[2, 3]]
649
+ c_dw = eye[[4, 5]]
650
+
651
+ compare_waldres(res, wa, [c_w, c_dw])
652
+
653
+
654
+ def compare_waldres(res, wa, constrasts):
655
+ for i, c in enumerate(constrasts):
656
+ wt = res.wald_test(c, scalar=True)
657
+ assert_allclose(wa.table.values[i, 0], wt.statistic)
658
+ assert_allclose(wa.table.values[i, 1], wt.pvalue)
659
+ # df should match the rank-adjusted value from wald_test
660
+ if res.use_t:
661
+ df = int(wt.df_num)
662
+ else:
663
+ df = int(wt.df_denom)
664
+ assert_equal(wa.table.values[i, 2], df)
665
+ # attributes
666
+ assert_allclose(wa.statistic[i], wt.statistic)
667
+ assert_allclose(wa.pvalues[i], wt.pvalue)
668
+ assert_equal(wa.df_constraints[i], df)
669
+ if res.use_t:
670
+ assert_equal(wa.df_denom[i], res.df_resid)
671
+
672
+ col_names = wa.col_names
673
+ if res.use_t:
674
+ assert_equal(wa.distribution, "F")
675
+ assert_equal(col_names[0], "F")
676
+ assert_equal(col_names[1], "P>F")
677
+ else:
678
+ assert_equal(wa.distribution, "chi2")
679
+ assert_equal(col_names[0], "chi2")
680
+ assert_equal(col_names[1], "P>chi2")
681
+
682
+ # SMOKETEST
683
+ wa.summary_frame()
684
+
685
+
686
+ class TestWaldAnovaOLS(CheckAnovaMixin):
687
+
688
+ def initialize(self):
689
+ mod = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", self.data)
690
+ self.res = mod.fit(use_t=False)
691
+
692
+ def test_noformula(self):
693
+ # this verifies single and composite constraints against explicit
694
+ # wald test
695
+ endog = self.res.model.endog
696
+ exog = self.res.model.data.orig_exog
697
+ exog = pd.DataFrame(exog)
698
+
699
+ res = sm.OLS(endog, exog).fit()
700
+ wa = res.wald_test_terms(
701
+ skip_single=False, combine_terms=["Duration", "Weight"], scalar=True
702
+ )
703
+ eye = np.eye(len(res.params))
704
+
705
+ c_single = list(eye)
706
+ c_weight = eye[2:6]
707
+ c_duration = eye[[1, 4, 5]]
708
+
709
+ compare_waldres(res, wa, c_single + [c_duration, c_weight])
710
+
711
+ # assert correct df_constraints, see #5475 for bug in single constraint
712
+ df_constraints = [1] * len(c_single) + [3, 4]
713
+ assert_equal(wa.df_constraints, df_constraints)
714
+
715
+
716
+ class TestWaldAnovaOLSF(CheckAnovaMixin):
717
+
718
+ def initialize(self):
719
+ mod = ols("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", self.data)
720
+ self.res = mod.fit() # default use_t=True
721
+
722
+ def test_predict_missing(self):
723
+ ex = self.data[:5].copy()
724
+ ex.iloc[0, 1] = np.nan
725
+ predicted1 = self.res.predict(ex)
726
+ predicted2 = self.res.predict(ex[1:])
727
+
728
+ assert_index_equal(predicted1.index, ex.index)
729
+ assert_series_equal(predicted1.iloc[1:], predicted2)
730
+ assert_equal(predicted1.values[0], np.nan)
731
+
732
+
733
+ class TestWaldAnovaGLM(CheckAnovaMixin):
734
+
735
+ def initialize(self):
736
+ mod = glm("np.log(Days+1) ~ C(Duration, Sum)*C(Weight, Sum)", self.data)
737
+ self.res = mod.fit(use_t=False)
738
+
739
+
740
+ class TestWaldAnovaPoisson(CheckAnovaMixin):
741
+
742
+ def initialize(self):
743
+ from statsmodels.discrete.discrete_model import Poisson
744
+
745
+ mod = Poisson.from_formula("Days ~ C(Duration, Sum)*C(Weight, Sum)", self.data)
746
+ self.res = mod.fit(cov_type="HC0")
747
+
748
+
749
+ class TestWaldAnovaNegBin(CheckAnovaMixin):
750
+
751
+ def initialize(self):
752
+ from statsmodels.discrete.discrete_model import NegativeBinomial
753
+
754
+ formula = "Days ~ C(Duration, Sum)*C(Weight, Sum)"
755
+ mod = NegativeBinomial.from_formula(formula, self.data, loglike_method="nb2")
756
+ self.res = mod.fit()
757
+
758
+
759
+ class TestWaldAnovaNegBin1(CheckAnovaMixin):
760
+
761
+ def initialize(self):
762
+ from statsmodels.discrete.discrete_model import NegativeBinomial
763
+
764
+ formula = "Days ~ C(Duration, Sum)*C(Weight, Sum)"
765
+ mod = NegativeBinomial.from_formula(formula, self.data, loglike_method="nb1")
766
+ self.res = mod.fit(cov_type="HC0")
767
+
768
+
769
+ class CheckPairwise:
770
+
771
+ def test_default(self):
772
+ res = self.res
773
+
774
+ tt = res.t_test(self.constraints)
775
+
776
+ pw = res.t_test_pairwise(self.term_name)
777
+ pw_frame = pw.result_frame
778
+ assert_allclose(pw_frame.iloc[:, :6].values, tt.summary_frame().values)
779
+
780
+
781
+ class TestTTestPairwiseOLS(CheckPairwise):
782
+
783
+ def setup_method(self):
784
+ from statsmodels.formula.api import ols
785
+ import statsmodels.stats.tests.test_anova as ttmod
786
+
787
+ test = ttmod.TestAnova3()
788
+ test.setup_class()
789
+ self.data = test.data.drop([0, 1, 2])
790
+
791
+ mod = ols("np.log(Days+1) ~ C(Duration) + C(Weight)", self.data)
792
+ self.res = mod.fit()
793
+ self.term_name = "C(Weight)"
794
+ self.constraints = [
795
+ "C(Weight)[T.2]",
796
+ "C(Weight)[T.3]",
797
+ "C(Weight)[T.3] - C(Weight)[T.2]",
798
+ ]
799
+
800
+ def test_alpha(self):
801
+ pw1 = self.res.t_test_pairwise(
802
+ self.term_name, method="hommel", factor_labels="A B C".split()
803
+ )
804
+ pw2 = self.res.t_test_pairwise(self.term_name, method="hommel", alpha=0.01)
805
+ assert_allclose(
806
+ pw1.result_frame.iloc[:, :7].values,
807
+ pw2.result_frame.iloc[:, :7].values,
808
+ rtol=1e-10,
809
+ )
810
+ assert_equal(pw1.result_frame.iloc[:, -1].values, [True] * 3)
811
+ assert_equal(pw2.result_frame.iloc[:, -1].values, [False, True, False])
812
+
813
+ assert_equal(
814
+ pw1.result_frame.index.values, np.array(["B-A", "C-A", "C-B"], dtype=object)
815
+ )
816
+
817
+
818
+ class TestTTestPairwiseOLS2(CheckPairwise):
819
+
820
+ def setup_method(self):
821
+ from statsmodels.formula.api import ols
822
+ import statsmodels.stats.tests.test_anova as ttmod
823
+
824
+ test = ttmod.TestAnova3()
825
+ test.setup_class()
826
+ self.data = test.data.drop([0, 1, 2])
827
+
828
+ mod = ols("np.log(Days+1) ~ C(Weight) + C(Duration)", self.data)
829
+ self.res = mod.fit()
830
+ self.term_name = "C(Weight)"
831
+ self.constraints = [
832
+ "C(Weight)[T.2]",
833
+ "C(Weight)[T.3]",
834
+ "C(Weight)[T.3] - C(Weight)[T.2]",
835
+ ]
836
+
837
+
838
+ class TestTTestPairwiseOLS3(CheckPairwise):
839
+
840
+ def setup_method(self):
841
+ from statsmodels.formula.api import ols
842
+ import statsmodels.stats.tests.test_anova as ttmod
843
+
844
+ test = ttmod.TestAnova3()
845
+ test.setup_class()
846
+ self.data = test.data.drop([0, 1, 2])
847
+
848
+ mod = ols("np.log(Days+1) ~ C(Weight) + C(Duration) - 1", self.data)
849
+ self.res = mod.fit()
850
+ self.term_name = "C(Weight)"
851
+ self.constraints = [
852
+ "C(Weight)[2] - C(Weight)[1]",
853
+ "C(Weight)[3] - C(Weight)[1]",
854
+ "C(Weight)[3] - C(Weight)[2]",
855
+ ]
856
+
857
+
858
+ class TestTTestPairwiseOLS4(CheckPairwise):
859
+
860
+ def setup_method(self):
861
+ from statsmodels.formula.api import ols
862
+ import statsmodels.stats.tests.test_anova as ttmod
863
+
864
+ test = ttmod.TestAnova3()
865
+ test.setup_class()
866
+ self.data = test.data.drop([0, 1, 2])
867
+
868
+ mod = ols("np.log(Days+1) ~ C(Weight, Treatment(2)) + C(Duration)", self.data)
869
+ self.res = mod.fit()
870
+ self.term_name = "C(Weight, Treatment(2))"
871
+ self.constraints = [
872
+ "-C(Weight, Treatment(2))[T.1]",
873
+ "C(Weight, Treatment(2))[T.3] - C(Weight, Treatment(2))[T.1]",
874
+ "C(Weight, Treatment(2))[T.3]",
875
+ ]
876
+
877
+
878
+ class TestTTestPairwisePoisson(CheckPairwise):
879
+
880
+ def setup_method(self):
881
+ from statsmodels.discrete.discrete_model import Poisson
882
+ import statsmodels.stats.tests.test_anova as ttmod
883
+
884
+ test = ttmod.TestAnova3()
885
+ test.setup_class()
886
+ self.data = test.data.drop([0, 1, 2])
887
+
888
+ mod = Poisson.from_formula("Days ~ C(Duration) + C(Weight)", self.data)
889
+ self.res = mod.fit(cov_type="HC0")
890
+ self.term_name = "C(Weight)"
891
+ self.constraints = [
892
+ "C(Weight)[T.2]",
893
+ "C(Weight)[T.3]",
894
+ "C(Weight)[T.3] - C(Weight)[T.2]",
895
+ ]
896
+
897
+
898
+ class TestWaldAnovaRankDeficient:
899
+ """Test wald_test_terms reports rank-adjusted df for rank-deficient models.
900
+
901
+ Regression test for GH#9686.
902
+ """
903
+
904
+ def setup_method(self):
905
+ rs = np.random.RandomState(4567)
906
+ n = 60
907
+ fertilizer = np.repeat(["A", "B", "C"], n // 3)
908
+ # tech0 is nested: not all fertilizer x tech0 combos exist
909
+ tech0 = []
910
+ for f in fertilizer:
911
+ if f == "A":
912
+ tech0.append(rs.choice(["t1", "t2"]))
913
+ elif f == "B":
914
+ tech0.append(rs.choice(["t1", "t3"]))
915
+ else:
916
+ tech0.append(rs.choice(["t2", "t3"]))
917
+
918
+ data = pd.DataFrame({
919
+ "y": rs.randn(n),
920
+ "fertilizer": fertilizer,
921
+ "tech0": tech0,
922
+ })
923
+ mod = ols("y ~ C(fertilizer) * C(tech0)", data)
924
+ with pytest.warns(SingularMatrixWarning, match="rank-deficient"):
925
+ # Intentionally singular, _fit_collinear doesn't even work
926
+ self.res = mod._fit_collinear()
927
+
928
+ def test_df_rank_adjusted(self):
929
+ # The interaction term has 4 columns but only 1 is non-redundant
930
+ res = self.res
931
+ wa = res.wald_test_terms(scalar=True)
932
+
933
+ # Check each term's df matches what wald_test returns
934
+ mgr = FormulaManager()
935
+ model_spec = getattr(res.model.data, "model_spec", None)
936
+ identity = np.eye(len(res.params))
937
+
938
+ for i, term in enumerate(model_spec.terms):
939
+ cols = mgr.get_slice(model_spec, term)
940
+ constraint = identity[cols]
941
+ wt = res.wald_test(constraint, scalar=True)
942
+ expected_df = int(wt.df_num)
943
+ reported_df = int(wa.table.iloc[i]["df_constraint"])
944
+ assert_equal(
945
+ reported_df, expected_df,
946
+ err_msg=f"df_constraint mismatch for term {i}"
947
+ )
948
+
949
+ def test_interaction_df_less_than_nominal(self):
950
+ # The interaction has 4 constraint rows but rank < 4
951
+ res = self.res
952
+ wa = res.wald_test_terms(scalar=True)
953
+ interaction_df = int(wa.table.iloc[-1]["df_constraint"])
954
+ # With missing cells, the interaction rank is less than 4
955
+ assert interaction_df < 4
shared/package-files/e8/e84dba71cf3bdaf0ed4825f40755d01801d45bf6a3c18702b4a2a0fa3ade8c98/blob ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ RepeatedScalarFieldContainer as google___protobuf___internal___containers___RepeatedScalarFieldContainer,
12
+ )
13
+
14
+ from google.protobuf.internal.well_known_types import (
15
+ FieldMask as google___protobuf___internal___well_known_types___FieldMask,
16
+ )
17
+
18
+ from google.protobuf.message import (
19
+ Message as google___protobuf___message___Message,
20
+ )
21
+
22
+ from typing import (
23
+ Iterable as typing___Iterable,
24
+ Optional as typing___Optional,
25
+ Text as typing___Text,
26
+ )
27
+
28
+ from typing_extensions import (
29
+ Literal as typing_extensions___Literal,
30
+ )
31
+
32
+
33
+ builtin___bool = bool
34
+ builtin___bytes = bytes
35
+ builtin___float = float
36
+ builtin___int = int
37
+
38
+
39
+ DESCRIPTOR: google___protobuf___descriptor___FileDescriptor = ...
40
+
41
+ class FieldMask(google___protobuf___message___Message, google___protobuf___internal___well_known_types___FieldMask):
42
+ DESCRIPTOR: google___protobuf___descriptor___Descriptor = ...
43
+ paths: google___protobuf___internal___containers___RepeatedScalarFieldContainer[typing___Text] = ...
44
+
45
+ def __init__(self,
46
+ *,
47
+ paths : typing___Optional[typing___Iterable[typing___Text]] = None,
48
+ ) -> None: ...
49
+ def ClearField(self, field_name: typing_extensions___Literal[u"paths",b"paths"]) -> None: ...
50
+ type___FieldMask = FieldMask
shared/package-files/e8/e8522f362e3c0c4324f7cce8594cae103c699aae567b80c05f808641f333d7bc/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 _saturate_weight_to_fp16 {
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::_saturate_weight_to_fp16")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_saturate_weight_to_fp16(Tensor weight) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & weight);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & weight);
26
+ };
27
+
28
+ }} // namespace at::_ops
shared/package-files/e8/e8533dc7083fa346bda1933d60ea4a83b67d0945bceaf1b3541f82b4a0e2c6a0/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8533dc7083fa346bda1933d60ea4a83b67d0945bceaf1b3541f82b4a0e2c6a0
3
+ size 237360
shared/package-files/e8/e8555eeb8cf86bd7896b8293255c208a27f8fed90bd755f9fedd70a716c4e59d/blob ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API lcm_out {
18
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, 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::lcm")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lcm.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
26
+ };
27
+
28
+ struct TORCH_API lcm {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::lcm")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lcm(Tensor self, Tensor other) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & other);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other);
37
+ };
38
+
39
+ struct TORCH_API lcm_ {
40
+ using schema = at::Tensor & (at::Tensor &, const at::Tensor &);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::lcm_")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lcm_(Tensor(a!) self, Tensor other) -> Tensor(a!)")
46
+ static at::Tensor & call(at::Tensor & self, const at::Tensor & other);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other);
48
+ };
49
+
50
+ }} // namespace at::_ops
shared/package-files/e8/e855b49714731f353906c33bb6ebcbac7ddfac7977d8ef8afb026c296de64333/blob ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is part of Patsy
2
+ # Copyright (C) 2011 Nathaniel Smith <njs@pobox.com>
3
+ # See file LICENSE.txt for license information.
4
+
5
+ # This file defines a parser for a simple language based on S/R "formulas"
6
+ # (which are described in sections 2.3 and 2.4 in Chambers & Hastie, 1992). It
7
+ # uses the machinery in patsy.parse_core to do the heavy-lifting -- its
8
+ # biggest job is to handle tokenization.
9
+
10
+
11
+ __all__ = ["parse_formula"]
12
+
13
+ # The Python tokenizer
14
+ import tokenize
15
+
16
+ from io import StringIO
17
+
18
+ from patsy import PatsyError
19
+ from patsy.origin import Origin
20
+ from patsy.infix_parser import Token, Operator, infix_parse, ParseNode
21
+ from patsy.tokens import python_tokenize, pretty_untokenize
22
+ from patsy.util import PushbackAdapter
23
+
24
+ _atomic_token_types = ["PYTHON_EXPR", "ZERO", "ONE", "NUMBER"]
25
+
26
+
27
+ def _is_a(f, v):
28
+ try:
29
+ f(v)
30
+ except ValueError:
31
+ return False
32
+ else:
33
+ return True
34
+
35
+
36
+ # Helper function for _tokenize_formula:
37
+ def _read_python_expr(it, end_tokens):
38
+ # Read out a full python expression, stopping when we hit an
39
+ # unnested end token.
40
+ pytypes = []
41
+ token_strings = []
42
+ origins = []
43
+ bracket_level = 0
44
+ for pytype, token_string, origin in it:
45
+ assert bracket_level >= 0
46
+ if bracket_level == 0 and token_string in end_tokens:
47
+ it.push_back((pytype, token_string, origin))
48
+ break
49
+ if token_string in ("(", "[", "{"):
50
+ bracket_level += 1
51
+ if token_string in (")", "]", "}"):
52
+ bracket_level -= 1
53
+ if bracket_level < 0:
54
+ raise PatsyError("unmatched close bracket", origin)
55
+ pytypes.append(pytype)
56
+ token_strings.append(token_string)
57
+ origins.append(origin)
58
+ # Either we found an end_token, or we hit the end of the string
59
+ if bracket_level == 0:
60
+ expr_text = pretty_untokenize(zip(pytypes, token_strings))
61
+ if expr_text == "0":
62
+ token_type = "ZERO"
63
+ elif expr_text == "1":
64
+ token_type = "ONE"
65
+ elif _is_a(int, expr_text) or _is_a(float, expr_text):
66
+ token_type = "NUMBER"
67
+ else:
68
+ token_type = "PYTHON_EXPR"
69
+ return Token(token_type, Origin.combine(origins), extra=expr_text)
70
+ else:
71
+ raise PatsyError(
72
+ "unclosed bracket in embedded Python expression", Origin.combine(origins)
73
+ )
74
+
75
+
76
+ def _tokenize_formula(code, operator_strings):
77
+ assert "(" not in operator_strings
78
+ assert ")" not in operator_strings
79
+ magic_token_types = {
80
+ "(": Token.LPAREN,
81
+ ")": Token.RPAREN,
82
+ }
83
+ for operator_string in operator_strings:
84
+ magic_token_types[operator_string] = operator_string
85
+ # Once we enter a Python expression, a ( does not end it, but any other
86
+ # "magic" token does:
87
+ end_tokens = set(magic_token_types)
88
+ end_tokens.remove("(")
89
+
90
+ it = PushbackAdapter(python_tokenize(code))
91
+ for pytype, token_string, origin in it:
92
+ if token_string in magic_token_types:
93
+ yield Token(magic_token_types[token_string], origin)
94
+ else:
95
+ it.push_back((pytype, token_string, origin))
96
+ yield _read_python_expr(it, end_tokens)
97
+
98
+
99
+ def test__tokenize_formula():
100
+ code = "y ~ a + (foo(b,c + 2)) + -1 + 0 + 10"
101
+ tokens = list(_tokenize_formula(code, ["+", "-", "~"]))
102
+ expecteds = [
103
+ ("PYTHON_EXPR", Origin(code, 0, 1), "y"),
104
+ ("~", Origin(code, 2, 3), None),
105
+ ("PYTHON_EXPR", Origin(code, 4, 5), "a"),
106
+ ("+", Origin(code, 6, 7), None),
107
+ (Token.LPAREN, Origin(code, 8, 9), None),
108
+ ("PYTHON_EXPR", Origin(code, 9, 23), "foo(b, c + 2)"),
109
+ (Token.RPAREN, Origin(code, 23, 24), None),
110
+ ("+", Origin(code, 25, 26), None),
111
+ ("-", Origin(code, 27, 28), None),
112
+ ("ONE", Origin(code, 28, 29), "1"),
113
+ ("+", Origin(code, 30, 31), None),
114
+ ("ZERO", Origin(code, 32, 33), "0"),
115
+ ("+", Origin(code, 34, 35), None),
116
+ ("NUMBER", Origin(code, 36, 38), "10"),
117
+ ]
118
+ for got, expected in zip(tokens, expecteds):
119
+ assert isinstance(got, Token)
120
+ assert got.type == expected[0]
121
+ assert got.origin == expected[1]
122
+ assert got.extra == expected[2]
123
+
124
+
125
+ _unary_tilde = Operator("~", 1, -100)
126
+ _default_ops = [
127
+ _unary_tilde,
128
+ Operator("~", 2, -100),
129
+ Operator("+", 2, 100),
130
+ Operator("-", 2, 100),
131
+ Operator("*", 2, 200),
132
+ Operator("/", 2, 200),
133
+ Operator(":", 2, 300),
134
+ Operator("**", 2, 500),
135
+ Operator("+", 1, 100),
136
+ Operator("-", 1, 100),
137
+ ]
138
+
139
+
140
+ def parse_formula(code, extra_operators=[]):
141
+ if not code.strip():
142
+ code = "~ 1"
143
+
144
+ for op in extra_operators:
145
+ if op.precedence < 0:
146
+ raise ValueError("all operators must have precedence >= 0")
147
+
148
+ operators = _default_ops + extra_operators
149
+ operator_strings = [op.token_type for op in operators]
150
+ tree = infix_parse(
151
+ _tokenize_formula(code, operator_strings), operators, _atomic_token_types
152
+ )
153
+ if not isinstance(tree, ParseNode) or tree.type != "~":
154
+ tree = ParseNode("~", None, [tree], tree.origin)
155
+ return tree
156
+
157
+
158
+ #############
159
+
160
+ _parser_tests = {
161
+ "": ["~", "1"],
162
+ " ": ["~", "1"],
163
+ " \n ": ["~", "1"],
164
+ "1": ["~", "1"],
165
+ "a": ["~", "a"],
166
+ "a ~ b": ["~", "a", "b"],
167
+ "(a ~ b)": ["~", "a", "b"],
168
+ "a ~ ((((b))))": ["~", "a", "b"],
169
+ "a ~ ((((+b))))": ["~", "a", ["+", "b"]],
170
+ "a + b + c": ["~", ["+", ["+", "a", "b"], "c"]],
171
+ "a + (b ~ c) + d": ["~", ["+", ["+", "a", ["~", "b", "c"]], "d"]],
172
+ "a + np.log(a, base=10)": ["~", ["+", "a", "np.log(a, base=10)"]],
173
+ # Note different spacing:
174
+ "a + np . log(a , base = 10)": ["~", ["+", "a", "np.log(a, base=10)"]],
175
+ # Check precedence
176
+ "a + b ~ c * d": ["~", ["+", "a", "b"], ["*", "c", "d"]],
177
+ "a + b * c": ["~", ["+", "a", ["*", "b", "c"]]],
178
+ "-a**2": ["~", ["-", ["**", "a", "2"]]],
179
+ "-a:b": ["~", ["-", [":", "a", "b"]]],
180
+ "a + b:c": ["~", ["+", "a", [":", "b", "c"]]],
181
+ "(a + b):c": ["~", [":", ["+", "a", "b"], "c"]],
182
+ "a*b:c": ["~", ["*", "a", [":", "b", "c"]]],
183
+ "a+b / c": ["~", ["+", "a", ["/", "b", "c"]]],
184
+ "~ a": ["~", "a"],
185
+ "-1": ["~", ["-", "1"]],
186
+ }
187
+
188
+
189
+ def _compare_trees(got, expected):
190
+ assert isinstance(got, ParseNode)
191
+ if got.args:
192
+ assert got.type == expected[0]
193
+ for arg, expected_arg in zip(got.args, expected[1:]):
194
+ _compare_trees(arg, expected_arg)
195
+ else:
196
+ assert got.type in _atomic_token_types
197
+ assert got.token.extra == expected
198
+
199
+
200
+ def _do_parse_test(test_cases, extra_operators):
201
+ for code, expected in test_cases.items():
202
+ actual = parse_formula(code, extra_operators=extra_operators)
203
+ print(repr(code), repr(expected))
204
+ print(actual)
205
+ _compare_trees(actual, expected)
206
+
207
+
208
+ def test_parse_formula():
209
+ _do_parse_test(_parser_tests, [])
210
+
211
+
212
+ def test_parse_origin():
213
+ tree = parse_formula("a ~ b + c")
214
+ assert tree.origin == Origin("a ~ b + c", 0, 9)
215
+ assert tree.token.origin == Origin("a ~ b + c", 2, 3)
216
+ assert tree.args[0].origin == Origin("a ~ b + c", 0, 1)
217
+ assert tree.args[1].origin == Origin("a ~ b + c", 4, 9)
218
+ assert tree.args[1].token.origin == Origin("a ~ b + c", 6, 7)
219
+ assert tree.args[1].args[0].origin == Origin("a ~ b + c", 4, 5)
220
+ assert tree.args[1].args[1].origin == Origin("a ~ b + c", 8, 9)
221
+
222
+
223
+ # <> mark off where the error should be reported:
224
+ _parser_error_tests = [
225
+ "a <+>",
226
+ "a + <(>",
227
+ "a + b <# asdf>",
228
+ "<)>",
229
+ "a + <)>",
230
+ "<*> a",
231
+ "a + <*>",
232
+ "a + <foo[bar>",
233
+ "a + <foo{bar>",
234
+ "a + <foo(bar>",
235
+ "a + <[bar>",
236
+ "a + <{bar>",
237
+ "a + <{bar[]>",
238
+ "a + foo<]>bar",
239
+ "a + foo[]<]>bar",
240
+ "a + foo{}<}>bar",
241
+ "a + foo<)>bar",
242
+ "a + b<)>",
243
+ "(a) <.>",
244
+ "<(>a + b",
245
+ "a +< >'foo", # Not the best placement for the error
246
+ ]
247
+
248
+
249
+ # Split out so it can also be used by tests of the evaluator (which also
250
+ # raises PatsyError's)
251
+ def _parsing_error_test(parse_fn, error_descs): # pragma: no cover
252
+ for error_desc in error_descs:
253
+ letters = []
254
+ start = None
255
+ end = None
256
+ for letter in error_desc:
257
+ if letter == "<":
258
+ start = len(letters)
259
+ elif letter == ">":
260
+ end = len(letters)
261
+ else:
262
+ letters.append(letter)
263
+ bad_code = "".join(letters)
264
+ assert start is not None and end is not None
265
+ print(error_desc)
266
+ print(repr(bad_code), start, end)
267
+ try:
268
+ parse_fn(bad_code)
269
+ except PatsyError as e:
270
+ print(e)
271
+ assert e.origin.code == bad_code
272
+ assert e.origin.start in (0, start)
273
+ assert e.origin.end in (end, len(bad_code))
274
+ else:
275
+ assert False, "parser failed to report an error!"
276
+
277
+
278
+ def test_parse_errors(extra_operators=[]):
279
+ def parse_fn(code):
280
+ return parse_formula(code, extra_operators=extra_operators)
281
+
282
+ _parsing_error_test(parse_fn, _parser_error_tests)
283
+
284
+
285
+ _extra_op_parser_tests = {
286
+ "a | b": ["~", ["|", "a", "b"]],
287
+ "a * b|c": ["~", ["*", "a", ["|", "b", "c"]]],
288
+ }
289
+
290
+
291
+ def test_parse_extra_op():
292
+ extra_operators = [Operator("|", 2, 250)]
293
+ _do_parse_test(_parser_tests, extra_operators=extra_operators)
294
+ _do_parse_test(_extra_op_parser_tests, extra_operators=extra_operators)
295
+ test_parse_errors(extra_operators=extra_operators)
shared/package-files/e8/e8574af88880b26b2c210e989092cc9a2317f992ba12bf44483b9c53408ee790/blob ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8574af88880b26b2c210e989092cc9a2317f992ba12bf44483b9c53408ee790
3
+ size 2071644
shared/package-files/e8/e857e89d3355ec8a63035d771855b5646877df9f5d9d6282861b904821e23a8d/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 ::std::tuple<at::Tensor,at::Tensor> _weight_norm_differentiable_backward(const at::Tensor & grad_w, const at::Tensor & saved_v, const at::Tensor & saved_g, const at::Tensor & saved_norms, int64_t dim);
21
+
22
+ } // namespace compositeimplicitautograd
23
+ } // namespace at
shared/package-files/e8/e8587dc55feecf64d65e94d59eeec4496cb17d75e323a724026c2302ca692cb4/blob ADDED
@@ -0,0 +1,886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ import collections
4
+ import dataclasses
5
+ import functools
6
+ import inspect
7
+ import itertools
8
+ import sys
9
+ import types
10
+ from typing import Dict, List
11
+
12
+ import torch._C
13
+ import torch._numpy as tnp
14
+ import torch.utils._pytree as pytree
15
+ from .. import config, variables
16
+ from ..bytecode_transformation import create_call_function, create_instruction
17
+ from ..exc import unimplemented
18
+ from ..guards import GuardBuilder, install_guard
19
+ from ..source import AttrSource, GetItemSource, ODictGetItemSource, TypeSource
20
+ from ..utils import (
21
+ check_constant_args,
22
+ check_unspec_python_args,
23
+ identity,
24
+ is_tensor_base_attr_getter,
25
+ proxy_args_kwargs,
26
+ )
27
+ from .base import VariableTracker
28
+ from .functions import NestedUserFunctionVariable, UserFunctionVariable
29
+ from .user_defined import UserDefinedObjectVariable
30
+
31
+
32
+ class SuperVariable(VariableTracker):
33
+ def __init__(self, typevar, objvar=None, specialized=False, **kwargs):
34
+ super().__init__(**kwargs)
35
+ # typevar is the fist argument to super(). In the case where no argument
36
+ # is provided to super(), it is the __class__ object where
37
+ # the super() function is being called
38
+ self.typevar = typevar
39
+ # objvar here must be an instance or subtype of typevar.
40
+ # In the case where super() is called without arguments, it is the first argument
41
+ # to the current function where super() is called from (self for regular method,
42
+ # cls for a classmethod)
43
+ self.objvar = objvar
44
+ self.specialized = specialized # directly get attr from self.typevar if true
45
+
46
+ def reconstruct(self, codegen):
47
+ codegen(variables.BuiltinVariable(super))
48
+ codegen(self.typevar)
49
+ if self.objvar is not None:
50
+ codegen(self.objvar)
51
+ codegen.extend_output(create_call_function(2, True))
52
+ else:
53
+ codegen.extend_output(create_call_function(1, True))
54
+
55
+ def _resolved_getattr_and_source(self, tx, name):
56
+ assert self.objvar, "1-arg super not implemented"
57
+ if self.specialized:
58
+ return getattr(self.typevar.as_python_constant(), name)
59
+ search_type = self.typevar.as_python_constant()
60
+
61
+ # The rest of this function does two things:
62
+ # - Walk the mro to find where the attribute comes from to be
63
+ # able to provide accurate source
64
+ # - Call the getattr to get the object
65
+
66
+ # Find the class object, where the function lives.
67
+ # When objvar is "self", use type(self), when objvar is "cls", use it as-is
68
+ type_to_use = self.objvar.python_type()
69
+ type_to_use_source = (
70
+ TypeSource(self.objvar.source) if self.objvar.source else None
71
+ )
72
+ if issubclass(type_to_use, type):
73
+ type_to_use = self.objvar.value
74
+ type_to_use_source = self.objvar.source
75
+
76
+ source = None
77
+ if self.objvar.source is not None:
78
+ # Walk the mro tuple to find out the actual class where the
79
+ # attribute resides.
80
+ search_mro = type_to_use.__mro__
81
+ start_index = search_mro.index(search_type) + 1
82
+ for index in range(start_index, len(search_mro)):
83
+ if hasattr(search_mro[index], name):
84
+ # Equivalent of something like type(L['self']).__mro__[1].attr_name
85
+ source = AttrSource(
86
+ GetItemSource(AttrSource(type_to_use_source, "__mro__"), index),
87
+ name,
88
+ )
89
+ break
90
+
91
+ # TODO(jansel): there is a small chance this could trigger user code, prevent that
92
+ return getattr(super(search_type, type_to_use), name), source
93
+
94
+ def var_getattr(self, tx, name: str) -> "VariableTracker":
95
+ # Check if getattr is a constant. If not, delay the actual work by
96
+ # wrapping the result in GetAttrVariable. Mostly super is called with a
97
+ # method, so most of the work is delayed to call_function.
98
+ #
99
+ # We could have just implemented a const_getattr. However, super is
100
+ # special when it comes to finding sources. Compared to other VTs, super
101
+ # requires the attr name to walk the mro and find the actual source (and
102
+ # not just AttrSource).
103
+ value, source = self._resolved_getattr_and_source(self, name)
104
+ if not variables.ConstantVariable.is_literal(value):
105
+ return GetAttrVariable(self, name)
106
+ if source:
107
+ install_guard(source.make_guard(GuardBuilder.CONSTANT_MATCH))
108
+ return variables.ConstantVariable.create(value, source=source)
109
+ return variables.ConstantVariable.create(value)
110
+
111
+ def call_method(
112
+ self,
113
+ tx,
114
+ name,
115
+ args: "List[VariableTracker]",
116
+ kwargs: "Dict[str, VariableTracker]",
117
+ ) -> "VariableTracker":
118
+ inner_fn, source = self._resolved_getattr_and_source(self, name)
119
+
120
+ if inner_fn is object.__init__:
121
+ return LambdaVariable(identity)
122
+ elif inner_fn is torch.nn.Module.__init__:
123
+ objvar = self.objvar
124
+ from ..side_effects import AttributeMutationNew
125
+
126
+ if (
127
+ isinstance(objvar, variables.UserDefinedObjectVariable)
128
+ and isinstance(objvar.mutable_local, AttributeMutationNew)
129
+ and not (args or kwargs)
130
+ ):
131
+ tx.output.side_effects.store_attr(
132
+ objvar,
133
+ "__call_nn_module_init",
134
+ variables.ConstantVariable.create(True),
135
+ )
136
+ return variables.ConstantVariable.create(None)
137
+ else:
138
+ unimplemented("super() nn.Module.__init__")
139
+ elif isinstance(inner_fn, types.FunctionType):
140
+ return variables.UserFunctionVariable(
141
+ inner_fn, source=source
142
+ ).call_function(tx, [self.objvar] + args, kwargs)
143
+ elif isinstance(inner_fn, types.MethodType):
144
+ return variables.UserMethodVariable(
145
+ inner_fn.__func__, self.objvar, source=source
146
+ ).call_function(tx, args, kwargs)
147
+ elif (
148
+ inner_fn is collections.OrderedDict.__getitem__
149
+ and isinstance(self.objvar, variables.UserDefinedObjectVariable)
150
+ and self.objvar.source
151
+ and len(args) == 1
152
+ and len(kwargs) == 0
153
+ and args[0].is_python_constant()
154
+ ):
155
+ from .builder import VariableBuilder
156
+
157
+ key = args[0].as_python_constant()
158
+ return VariableBuilder(tx, ODictGetItemSource(self.objvar.source, key))(
159
+ collections.OrderedDict.__getitem__(self.objvar.value, key)
160
+ )
161
+ elif inner_fn in (
162
+ collections.OrderedDict.__setitem__,
163
+ object.__setattr__,
164
+ ) and isinstance(self.objvar, variables.CustomizedDictVariable):
165
+ assert not kwargs and len(args) == 2
166
+ return super(variables.CustomizedDictVariable, self.objvar).call_method(
167
+ tx, "__setitem__", args, kwargs
168
+ )
169
+ else:
170
+ unimplemented(f"non-function or method super: {inner_fn}")
171
+
172
+
173
+ class UnknownVariable(VariableTracker):
174
+ """
175
+ It could be anything!
176
+ """
177
+
178
+
179
+ class DelayGraphBreakVariable(UnknownVariable):
180
+ """
181
+ Used to insert a dummy variable in the stack to do the graph break at CALL_FUNCTION.
182
+ """
183
+
184
+
185
+ class ComptimeVariable(VariableTracker):
186
+ """
187
+ This variable is special, it lets you execute arbitrary code at
188
+ Dynamo compile time
189
+ """
190
+
191
+ def reconstruct(self, codegen):
192
+ raise NotImplementedError("comptime is special form")
193
+
194
+ def var_getattr(self, tx, name: str) -> "VariableTracker":
195
+ from ..comptime import comptime
196
+
197
+ # To support the comptime.print_graph convenience accessors
198
+ from .functions import UserFunctionVariable
199
+
200
+ return UserFunctionVariable(
201
+ getattr(comptime, name), source=AttrSource(self.source, name)
202
+ )
203
+
204
+ def call_function(
205
+ self, tx, args: "List[VariableTracker]", kwargs: "Dict[str, VariableTracker]"
206
+ ) -> "VariableTracker":
207
+ from ..comptime import ComptimeContext
208
+
209
+ # TODO: support an expression form as well
210
+
211
+ assert not kwargs
212
+ assert len(args) == 1
213
+ fn = args[0]
214
+ if isinstance(fn, UserFunctionVariable):
215
+ fn.get_function()(ComptimeContext(tx))
216
+ elif isinstance(fn, NestedUserFunctionVariable):
217
+ # We have to manually bind the freevars ourselves
218
+ code = fn.get_code()
219
+ assert not fn.closure, (
220
+ "comptime function must not have free variables, "
221
+ f"but these variables were free: {code.co_freevars}"
222
+ )
223
+ func = types.FunctionType(
224
+ code,
225
+ fn.f_globals,
226
+ fn.fn_name.as_python_constant(),
227
+ tuple(fn.defaults.items) if fn.defaults else None,
228
+ # We could automatically promote free variables into
229
+ # ComptimeVar but this is confusing if you access
230
+ # a free variable that we actually DO have the runtime
231
+ # value for
232
+ # tuple(make_cell(ComptimeVar(i)) for i in fn.closure.items)
233
+ tuple(),
234
+ )
235
+ func(ComptimeContext(tx))
236
+ else:
237
+ raise RuntimeError(f"unsupported argument to comptime: {type(fn)}")
238
+
239
+ return variables.ConstantVariable.create(None)
240
+
241
+
242
+ class ClosureVariable(UnknownVariable):
243
+ def __init__(self, name, **kwargs):
244
+ super().__init__(**kwargs)
245
+ self.name = name
246
+
247
+ def reconstruct(self, codegen):
248
+ codegen.append_output(codegen.create_load_closure(self.name))
249
+
250
+
251
+ # closure variable created by an inlined function
252
+ class InlinedClosureVariable(UnknownVariable):
253
+ def __init__(self, name, **kwargs):
254
+ super().__init__(**kwargs)
255
+ self.name = name
256
+
257
+ def reconstruct(self, codegen):
258
+ codegen.append_output(codegen.create_load_closure(self.name))
259
+
260
+
261
+ class NewCellVariable(VariableTracker):
262
+ def __init__(self, **kwargs):
263
+ super().__init__(**kwargs)
264
+
265
+
266
+ class NewGlobalVariable(VariableTracker):
267
+ def __init__(self, **kwargs):
268
+ super().__init__(**kwargs)
269
+
270
+
271
+ class InspectSignatureVariable(VariableTracker):
272
+ """represents inspect.signature(...)"""
273
+
274
+ @staticmethod
275
+ def create(callable, **kwargs):
276
+ if kwargs:
277
+ unimplemented(f"inspect.signature with {kwargs}")
278
+ return InspectSignatureVariable(callable)
279
+
280
+ def __init__(self, inspected: VariableTracker, **kwargs):
281
+ super().__init__(**kwargs)
282
+ self.inspected = inspected
283
+
284
+ def var_getattr(self, tx, name: str) -> "VariableTracker":
285
+ if name == "parameters":
286
+ return variables.ConstDictVariable(
287
+ {
288
+ variables.ConstantVariable.create(name): InspectParameterVariable()
289
+ for name in self.inspected.inspect_parameter_names()
290
+ },
291
+ user_cls=dict,
292
+ )
293
+ return super().var_getattr(tx, name)
294
+
295
+
296
+ class InspectParameterVariable(VariableTracker):
297
+ """This is not implemented, if used will graph break."""
298
+
299
+ pass
300
+
301
+
302
+ def produce_trampoline_autograd_apply(fn_cls):
303
+ def trampoline_autograd_apply(*args, **kwargs):
304
+ return fn_cls.apply(*args, **kwargs)
305
+
306
+ trampoline_autograd_apply._origin = produce_trampoline_autograd_apply
307
+ return trampoline_autograd_apply
308
+
309
+
310
+ class AutogradFunctionVariable(VariableTracker):
311
+ """represents a torch.autograd.Function subclass"""
312
+
313
+ def __init__(self, fn_cls, **kwargs):
314
+ super().__init__(**kwargs)
315
+ self.fn_cls = fn_cls
316
+
317
+ def call_apply(self, tx, args, kwargs):
318
+ requires_grad = False
319
+
320
+ def visit(node):
321
+ nonlocal requires_grad
322
+ if isinstance(node, variables.TensorVariable):
323
+ if node.requires_grad is not False:
324
+ requires_grad = True
325
+ if isinstance(node, variables.NNModuleVariable):
326
+ if node.is_training(tx):
327
+ requires_grad = True
328
+ return node
329
+
330
+ VariableTracker.apply(visit, (args, kwargs))
331
+
332
+ if (
333
+ requires_grad
334
+ and torch.is_grad_enabled()
335
+ and config.capture_autograd_function
336
+ ):
337
+ # Note - this is the same check used in autograd/function.py, except inverted.
338
+ # If we want to support functorch transforms here, we will need to enable this.
339
+ if (
340
+ self.fn_cls.setup_context
341
+ != torch.autograd.function._SingleLevelFunction.setup_context
342
+ ):
343
+ unimplemented(
344
+ "NYI - autograd.Function with custom setup_context method"
345
+ )
346
+
347
+ vjp_fn = self.fn_cls.vjp # type: ignore[attr-defined]
348
+ if vjp_fn is not torch.autograd.Function.vjp:
349
+ unimplemented("NYI - User defind vjp")
350
+
351
+ jvp_fn = self.fn_cls.jvp # type: ignore[attr-defined]
352
+ if jvp_fn is not torch.autograd.Function.jvp:
353
+ unimplemented("NYI - User defind jvp")
354
+
355
+ from .higher_order_ops import AutogradFunctionApplyVariable
356
+
357
+ source = self.source
358
+ if source is None:
359
+ source = AttrSource(
360
+ tx.import_source(self.fn_cls.__module__), self.fn_cls.__name__
361
+ )
362
+
363
+ return AutogradFunctionApplyVariable(
364
+ self.fn_cls.forward,
365
+ self.fn_cls.backward,
366
+ source,
367
+ source=AttrSource(source, member="apply"),
368
+ ).call_function(tx, args, kwargs)
369
+
370
+ if self.source:
371
+ source = AttrSource(self.source, "forward")
372
+ else:
373
+ source = None
374
+
375
+ fn = self.fn_cls.forward
376
+ ctx = AutogradFunctionContextVariable.create(tx)
377
+ args = [ctx, *args]
378
+ if isinstance(fn, types.FunctionType):
379
+ return variables.UserFunctionVariable(fn, source=source).call_function(
380
+ tx, args, kwargs
381
+ )
382
+ elif isinstance(fn, types.MethodType):
383
+ return variables.UserMethodVariable(
384
+ fn.__func__,
385
+ variables.UserDefinedClassVariable(self.fn_cls),
386
+ source=source,
387
+ ).call_function(tx, args, kwargs)
388
+ else:
389
+ unimplemented(
390
+ f"non-function or method in subclass of torch.autograd.Function: {fn}"
391
+ )
392
+
393
+ def call_function(self, tx, args, kwargs):
394
+ return AutogradFunctionVariable(self.fn_cls)
395
+
396
+ def call_method(
397
+ self,
398
+ tx,
399
+ name,
400
+ args: "List[VariableTracker]",
401
+ kwargs: "Dict[str, VariableTracker]",
402
+ ):
403
+ from ..trace_rules import is_callable_allowed
404
+ from .builder import wrap_fx_proxy
405
+
406
+ if name == "apply":
407
+ if is_callable_allowed(self.fn_cls):
408
+ trampoline_autograd_apply = produce_trampoline_autograd_apply(
409
+ self.fn_cls
410
+ )
411
+ return wrap_fx_proxy(
412
+ tx=tx,
413
+ proxy=tx.output.create_proxy(
414
+ "call_function",
415
+ trampoline_autograd_apply,
416
+ *proxy_args_kwargs(args, kwargs),
417
+ ),
418
+ )
419
+ else:
420
+ return self.call_apply(tx, args, kwargs)
421
+
422
+ else:
423
+ unimplemented(f"Unsupported method: {name}")
424
+
425
+
426
+ @dataclasses.dataclass
427
+ class SavedTensorBox:
428
+ tensors: List[VariableTracker] = dataclasses.field(default_factory=list)
429
+
430
+
431
+ class AutogradFunctionContextVariable(UserDefinedObjectVariable):
432
+ """
433
+ Tracks an autograd.Function() context using mutation tracking in side_effects.py
434
+ """
435
+
436
+ _nonvar_fields = {
437
+ "proxy",
438
+ "inference",
439
+ *UserDefinedObjectVariable._nonvar_fields,
440
+ }
441
+
442
+ def __init__(
443
+ self,
444
+ value,
445
+ value_type=None,
446
+ inference=False,
447
+ proxy=None,
448
+ saved_tensors=None,
449
+ **kwargs,
450
+ ):
451
+ super().__init__(value=value, value_type=value_type, **kwargs)
452
+ self.inference = inference
453
+ self.proxy = proxy
454
+ self.saved_tensors = saved_tensors
455
+
456
+ @staticmethod
457
+ def create(tx):
458
+ proxy = tx.output.create_proxy(
459
+ "call_function", torch.autograd.function.FunctionCtx, tuple(), {}
460
+ )
461
+ out = tx.output.side_effects.track_object_new(
462
+ None,
463
+ torch.autograd.function.FunctionCtx,
464
+ functools.partial(
465
+ AutogradFunctionContextVariable,
466
+ inference=True,
467
+ proxy=proxy,
468
+ saved_tensors=SavedTensorBox(),
469
+ ),
470
+ {},
471
+ )
472
+ proxy.node.meta["example_value"] = out.value
473
+ return out
474
+
475
+ def as_proxy(self):
476
+ if self.proxy is None:
477
+ unimplemented("proxy not set")
478
+ return self.proxy
479
+
480
+ def call_method(
481
+ self,
482
+ tx,
483
+ name,
484
+ args: "List[VariableTracker]",
485
+ kwargs: "Dict[str, VariableTracker]",
486
+ ) -> "VariableTracker":
487
+ if name != "save_for_backward":
488
+ unimplemented(f"autograd.Function context method: {name}")
489
+ if self.saved_tensors is None:
490
+ unimplemented(
491
+ "save_for_backward only supported on a newly constructed FunctionCtx"
492
+ )
493
+
494
+ if not self.inference:
495
+ assert self.source and not kwargs
496
+ tx.output.side_effects.track_save_for_backward(self, args)
497
+
498
+ # In eager mode, multiple calls to .save_for_backward() will overwrite previous calls.
499
+ if len(self.saved_tensors.tensors) > 0:
500
+ self.saved_tensors.tensors = []
501
+ for arg in args:
502
+ self.saved_tensors.tensors.append(arg)
503
+ return variables.ConstantVariable.create(None)
504
+
505
+ def var_getattr(self, tx, name):
506
+ if name == "save_for_backward":
507
+ return LambdaVariable(
508
+ lambda *args, **kwargs: self.call_method(tx, name, args, kwargs)
509
+ )
510
+ if name == "saved_tensors" and self.saved_tensors is not None:
511
+ return variables.TupleVariable(list(self.saved_tensors.tensors))
512
+ return super().var_getattr(tx, name)
513
+
514
+
515
+ class LambdaVariable(VariableTracker):
516
+ def __init__(self, fn, **kwargs):
517
+ super().__init__(**kwargs)
518
+ self.fn = fn
519
+
520
+ def call_function(
521
+ self, tx, args: "List[VariableTracker]", kwargs: "Dict[str, VariableTracker]"
522
+ ) -> "VariableTracker":
523
+ return self.fn(*args, **kwargs)
524
+
525
+
526
+ class GetAttrVariable(VariableTracker):
527
+ def __init__(self, obj, name, **kwargs):
528
+ super().__init__(**kwargs)
529
+ assert isinstance(obj, VariableTracker)
530
+ assert isinstance(name, str)
531
+ self.obj = obj
532
+ self.name = name
533
+
534
+ def __str__(self):
535
+ return f"{self.__class__.__name__}({self.obj}, {self.name})"
536
+
537
+ @staticmethod
538
+ def create_getattr_proxy(base_proxy: torch.fx.Proxy, attr):
539
+ return getattr(base_proxy, attr)
540
+
541
+ def as_proxy(self):
542
+ return GetAttrVariable.create_getattr_proxy(self.obj.as_proxy(), self.name)
543
+
544
+ def const_getattr(self, tx, name):
545
+ if not isinstance(self.obj, variables.NNModuleVariable):
546
+ raise NotImplementedError()
547
+ step1 = tx.output.get_submodule(self.obj.module_key)
548
+ if self.name not in step1.__dict__:
549
+ raise NotImplementedError()
550
+ step2 = inspect.getattr_static(step1, self.name)
551
+ if name not in step2.__dict__:
552
+ raise NotImplementedError()
553
+ return inspect.getattr_static(step2, name)
554
+
555
+ def reconstruct(self, codegen):
556
+ codegen(self.obj)
557
+ codegen.extend_output(codegen.create_load_attrs(self.name))
558
+
559
+ def call_function(
560
+ self, tx, args: "List[VariableTracker]", kwargs: "Dict[str, VariableTracker]"
561
+ ) -> "VariableTracker":
562
+ return self.obj.call_method(tx, self.name, args, kwargs)
563
+
564
+
565
+ class MethodWrapperVariable(VariableTracker):
566
+ def __init__(self, method_wrapper, **kwargs):
567
+ super().__init__(**kwargs)
568
+ self.method_wrapper = method_wrapper
569
+
570
+ def call_function(
571
+ self, tx, args: "List[VariableTracker]", kwargs: "Dict[str, VariableTracker]"
572
+ ) -> "VariableTracker":
573
+ if is_tensor_base_attr_getter(self.method_wrapper) and isinstance(
574
+ args[0], variables.TensorVariable
575
+ ):
576
+ assert len(args) == 1 and len(kwargs) == 0
577
+
578
+ return args[0].var_getattr(tx, self.method_wrapper.__self__.__name__)
579
+
580
+ super().call_function(tx, args, kwargs)
581
+
582
+ def is_python_constant(self):
583
+ return True
584
+
585
+ def as_python_constant(self):
586
+ return self.method_wrapper
587
+
588
+
589
+ class GetSetDescriptorVariable(VariableTracker):
590
+ def __init__(self, desc, **kwargs):
591
+ super().__init__(**kwargs)
592
+ self.desc = desc
593
+
594
+ def var_getattr(self, tx, name):
595
+ if name == "__get__" and self.source:
596
+ from .builder import VariableBuilder
597
+
598
+ return VariableBuilder(tx, AttrSource(self.source, "__get__"))(
599
+ self.desc.__get__
600
+ )
601
+ else:
602
+ return super().var_getattr(tx, name)
603
+
604
+ def is_python_constant(self):
605
+ return True
606
+
607
+ def as_python_constant(self):
608
+ return self.desc
609
+
610
+
611
+ class PythonModuleVariable(VariableTracker):
612
+ def __init__(self, value: types.ModuleType, **kwargs):
613
+ super().__init__(**kwargs)
614
+ self.value = value
615
+ self.is_torch = self.value is torch or self.value.__name__.startswith("torch.")
616
+
617
+ def python_type(self):
618
+ return types.ModuleType
619
+
620
+ def as_python_constant(self):
621
+ return self.value
622
+
623
+ def __repr__(self):
624
+ return f"PythonModuleVariable({self.value})"
625
+
626
+ def call_hasattr(self, tx, name):
627
+ if self.is_torch:
628
+ result = hasattr(self.value, name)
629
+ return variables.ConstantVariable.create(result)
630
+ return super().call_hasattr(tx, name)
631
+
632
+
633
+ class TypingVariable(VariableTracker):
634
+ def __init__(self, value, **kwargs):
635
+ super().__init__(**kwargs)
636
+ self.value = value
637
+
638
+ def call_method(
639
+ self,
640
+ tx,
641
+ name,
642
+ args: "List[VariableTracker]",
643
+ kwargs: "Dict[str, VariableTracker]",
644
+ ) -> "VariableTracker":
645
+ if name == "__getitem__" and len(args) == 1:
646
+ return variables.ConstantVariable.create(
647
+ self.value[args[0].as_python_constant()],
648
+ )
649
+ unimplemented("typing")
650
+
651
+ def python_type(self):
652
+ return type(self.value)
653
+
654
+ def as_python_constant(self):
655
+ return self.value
656
+
657
+
658
+ @functools.lru_cache(maxsize=1)
659
+ def get_np_to_tnp_map():
660
+ from ..utils import NP_TO_TNP_MODULE
661
+
662
+ np_fn_to_tnp_fn = {}
663
+
664
+ for np_mod, tnp_mod in NP_TO_TNP_MODULE.items():
665
+ for fn_name, tnp_fn in tnp_mod.__dict__.items():
666
+ if callable(tnp_fn):
667
+ # some internal details do leak from tnp
668
+ # which are not part of numpy API.
669
+ if np_fn := getattr(np_mod, fn_name, None):
670
+ np_fn_to_tnp_fn[np_fn] = tnp_fn
671
+
672
+ return np_fn_to_tnp_fn
673
+
674
+
675
+ class NumpyVariable(VariableTracker):
676
+ """
677
+ Wrapper around `numpy.*`. Currently, is able to trace a small subset of numpy functions as well as numpy dtypes.
678
+ """
679
+
680
+ constant_fold_functions = (tnp.issubdtype,)
681
+
682
+ def __init__(self, value, **kwargs):
683
+ super().__init__(**kwargs)
684
+ self.value = value
685
+
686
+ @classmethod
687
+ def can_constant_fold_through(cls, fn):
688
+ mod = fn.__module__.split(".")
689
+ assert len(mod) >= 2 and mod[:2] == ["torch", "_numpy"]
690
+ return fn in cls.constant_fold_functions
691
+
692
+ def call_function(
693
+ self, tx, args: "List[VariableTracker]", kwargs: "Dict[str, VariableTracker]"
694
+ ) -> "VariableTracker":
695
+ if not config.trace_numpy:
696
+ unimplemented(f"numpy.{self.value}()")
697
+
698
+ from ..utils import numpy_to_tensor_wrapper
699
+
700
+ from .tensor import NumpyNdarrayVariable
701
+
702
+ # lookup method name in tnp. Things like np.dtype(float) are not supported yet.
703
+ if self.value.__name__ == "dtype":
704
+ unimplemented(
705
+ f"numpy dtype function is not supported yet. Got type {type(self.value)}."
706
+ )
707
+ else: # We are dealing with a callable.
708
+ func = get_np_to_tnp_map().get(self.value)
709
+ if func is None:
710
+ unimplemented(
711
+ f"Can't find numpy function {self.value} in torch._numpy. "
712
+ " Please file an issue to request support for this function."
713
+ )
714
+
715
+ if (
716
+ func.__module__ == "torch._numpy.random"
717
+ and config.use_numpy_random_stream
718
+ ):
719
+ msg = f"delegate '{func.__qualname__}' to NumPy itself via "
720
+ msg += f"confg.use_numpy_random_stream={config.use_numpy_random_stream}"
721
+ unimplemented(msg)
722
+
723
+ args, kwargs = NumpyNdarrayVariable.patch_args(func.__name__, args, kwargs)
724
+
725
+ constant_args = check_constant_args(args, kwargs)
726
+ unspec_python_args = check_unspec_python_args(args, kwargs)
727
+
728
+ if self.can_constant_fold_through(func) and (
729
+ constant_args or unspec_python_args
730
+ ):
731
+ # constant fold
732
+ return variables.ConstantVariable.create(
733
+ self.as_python_constant()(
734
+ *[x.as_python_constant() for x in args],
735
+ **{k: v.as_python_constant() for k, v in kwargs.items()},
736
+ ),
737
+ )
738
+
739
+ # TODO Add all the functions that go from constants to constants to can_constant_fold_through
740
+ proxy = tx.output.create_proxy(
741
+ "call_function",
742
+ numpy_to_tensor_wrapper(func),
743
+ *proxy_args_kwargs(args, kwargs),
744
+ )
745
+ return NumpyNdarrayVariable.create(tx, proxy)
746
+
747
+ def call_method(
748
+ self,
749
+ tx,
750
+ name,
751
+ args: "List[VariableTracker]",
752
+ kwargs: "Dict[str, VariableTracker]",
753
+ ) -> "VariableTracker":
754
+ unimplemented("numpy")
755
+
756
+ def python_type(self):
757
+ return type(self.value)
758
+
759
+ def as_python_constant(self):
760
+ return self.value
761
+
762
+ def as_proxy(self):
763
+ if config.trace_numpy and isinstance(self.value, type):
764
+ # This handles numpy dtype attributes such as np.float32
765
+ # We return a string as we don't want to serialize non-PyTorch objects in the output FX graph
766
+ # In torch/_numpy we normalize strings to their dtypes when the input is a dtype, as NumPy does
767
+ return self.value.__name__
768
+
769
+ return super().as_proxy()
770
+
771
+
772
+ # Used to keep track of NULLs pushed on the stack for Python 3.11 function calls
773
+ class NullVariable(VariableTracker):
774
+ def __init__(self, **kwargs):
775
+ super().__init__(**kwargs)
776
+
777
+ def __str__(self):
778
+ return "NullVariable"
779
+
780
+ def reconstruct(self, codegen):
781
+ if sys.version_info < (3, 11):
782
+ unimplemented("cannot reconstruct NullVariable in < Python 3.11")
783
+ codegen.append_output(create_instruction("PUSH_NULL"))
784
+
785
+
786
+ class DeletedVariable(VariableTracker):
787
+ """Marker used to implement delattr()"""
788
+
789
+
790
+ class StringFormatVariable(VariableTracker):
791
+ """
792
+ Represents a call to str.format(), we delay calling format until after the graph.
793
+ """
794
+
795
+ _nonvar_fields = {"format_string", *VariableTracker._nonvar_fields}
796
+
797
+ @classmethod
798
+ def create(cls, format_string, sym_args, sym_kwargs):
799
+ if all(
800
+ x.is_python_constant()
801
+ for x in itertools.chain(sym_args, sym_kwargs.values())
802
+ ):
803
+ return variables.ConstantVariable.create(
804
+ format_string.format(
805
+ *[v.as_python_constant() for v in sym_args],
806
+ **{k: v.as_python_constant() for k, v in sym_kwargs.items()},
807
+ )
808
+ )
809
+ return cls(format_string, list(sym_args), dict(sym_kwargs))
810
+
811
+ def __init__(self, format_string, sym_args, sym_kwargs, **kwargs):
812
+ super().__init__(**kwargs)
813
+ assert isinstance(format_string, str)
814
+ self.format_string = format_string
815
+ self.sym_args = sym_args
816
+ self.sym_kwargs = sym_kwargs
817
+
818
+ def __repr__(self):
819
+ return f"{self.__class__.__name__}({self.format_string!r}, {self.sym_args!r}, {self.sym_kwargs!r})"
820
+
821
+ def reconstruct(self, codegen):
822
+ if sys.version_info >= (3, 11):
823
+ codegen.append_output(create_instruction("PUSH_NULL"))
824
+ codegen.append_output(codegen.create_load_const(self.format_string))
825
+ codegen.append_output(codegen.create_load_attr("format"))
826
+ codegen(variables.TupleVariable(self.sym_args))
827
+ kwargs = {
828
+ variables.ConstantVariable.create(k): v for k, v in self.sym_kwargs.items()
829
+ }
830
+ codegen(variables.ConstDictVariable(kwargs))
831
+ codegen.append_output(create_instruction("CALL_FUNCTION_EX", arg=1))
832
+
833
+
834
+ class DebuggingVariable(VariableTracker):
835
+ """
836
+ Represents a call to a debugging function like print(), or something
837
+ registered to config.reorderable_logging_functions.
838
+ """
839
+
840
+ def __init__(self, value, **kwargs):
841
+ super().__init__(**kwargs)
842
+ self.value = value
843
+
844
+ @staticmethod
845
+ def is_reorderable_logging_function(obj):
846
+ return (
847
+ callable(obj)
848
+ and isinstance(obj, (types.FunctionType, types.BuiltinFunctionType))
849
+ and obj in torch._dynamo.config.reorderable_logging_functions
850
+ )
851
+
852
+ def call_function(self, tx, args, kwargs):
853
+ if tx.export:
854
+ # For export cases, we can just make debugging functions no-ops
855
+ return
856
+
857
+ if not self.can_reorder_logs(self.value, args, kwargs):
858
+ unimplemented(
859
+ f"Reordering debugging function {self.value} "
860
+ f"with inputs {args} {kwargs} is not yet implemented."
861
+ )
862
+
863
+ tx.debug_locals.append((self, list(args)))
864
+
865
+ def reconstruct(self, codegen):
866
+ return self.source.reconstruct(codegen)
867
+
868
+ @staticmethod
869
+ def can_reorder_logs(fn, args, kwargs) -> True:
870
+ """
871
+ Run some additional checks for what sort of function calls can we
872
+ actually reorder.
873
+ """
874
+
875
+ allowed_input_types = (
876
+ variables.TensorVariable,
877
+ variables.ConstantVariable,
878
+ StringFormatVariable,
879
+ )
880
+
881
+ flat_args = pytree.tree_leaves([args, kwargs])
882
+ for arg in flat_args:
883
+ if not isinstance(arg, allowed_input_types):
884
+ return False
885
+
886
+ return True
shared/package-files/e8/e85cf30a42362172d12af10796925627a8e253724d750d64c379f066e67248bf/blob ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor replication_pad1d(const at::Tensor & self, at::IntArrayRef padding);
21
+ TORCH_API at::Tensor replication_pad1d_symint(const at::Tensor & self, c10::SymIntArrayRef padding);
22
+ TORCH_API at::Tensor & replication_pad1d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef padding);
23
+ TORCH_API at::Tensor & replication_pad1d_outf(const at::Tensor & self, at::IntArrayRef padding, at::Tensor & out);
24
+ TORCH_API at::Tensor & replication_pad1d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef padding);
25
+ TORCH_API at::Tensor & replication_pad1d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef padding, at::Tensor & out);
26
+
27
+ } // namespace meta
28
+ } // namespace at
shared/package-files/e8/e85d6d736adc29a0999a07d5c2c13a39b21efcfbb1db799455803ed83f700857/blob ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from pip._internal.models.direct_url import ArchiveInfo, DirectUrl, DirInfo, VcsInfo
4
+ from pip._internal.models.link import Link
5
+ from pip._internal.utils.urls import path_to_url
6
+ from pip._internal.vcs import vcs
7
+
8
+
9
+ def direct_url_as_pep440_direct_reference(direct_url: DirectUrl, name: str) -> str:
10
+ """Convert a DirectUrl to a pip requirement string."""
11
+ direct_url.validate() # if invalid, this is a pip bug
12
+ requirement = name + " @ "
13
+ fragments = []
14
+ if isinstance(direct_url.info, VcsInfo):
15
+ requirement += "{}+{}@{}".format(
16
+ direct_url.info.vcs, direct_url.url, direct_url.info.commit_id
17
+ )
18
+ elif isinstance(direct_url.info, ArchiveInfo):
19
+ requirement += direct_url.url
20
+ if direct_url.info.hash:
21
+ fragments.append(direct_url.info.hash)
22
+ else:
23
+ assert isinstance(direct_url.info, DirInfo)
24
+ requirement += direct_url.url
25
+ if direct_url.subdirectory:
26
+ fragments.append("subdirectory=" + direct_url.subdirectory)
27
+ if fragments:
28
+ requirement += "#" + "&".join(fragments)
29
+ return requirement
30
+
31
+
32
+ def direct_url_for_editable(source_dir: str) -> DirectUrl:
33
+ return DirectUrl(
34
+ url=path_to_url(source_dir),
35
+ info=DirInfo(editable=True),
36
+ )
37
+
38
+
39
+ def direct_url_from_link(
40
+ link: Link, source_dir: Optional[str] = None, link_is_in_wheel_cache: bool = False
41
+ ) -> DirectUrl:
42
+ if link.is_vcs:
43
+ vcs_backend = vcs.get_backend_for_scheme(link.scheme)
44
+ assert vcs_backend
45
+ url, requested_revision, _ = vcs_backend.get_url_rev_and_auth(
46
+ link.url_without_fragment
47
+ )
48
+ # For VCS links, we need to find out and add commit_id.
49
+ if link_is_in_wheel_cache:
50
+ # If the requested VCS link corresponds to a cached
51
+ # wheel, it means the requested revision was an
52
+ # immutable commit hash, otherwise it would not have
53
+ # been cached. In that case we don't have a source_dir
54
+ # with the VCS checkout.
55
+ assert requested_revision
56
+ commit_id = requested_revision
57
+ else:
58
+ # If the wheel was not in cache, it means we have
59
+ # had to checkout from VCS to build and we have a source_dir
60
+ # which we can inspect to find out the commit id.
61
+ assert source_dir
62
+ commit_id = vcs_backend.get_revision(source_dir)
63
+ return DirectUrl(
64
+ url=url,
65
+ info=VcsInfo(
66
+ vcs=vcs_backend.name,
67
+ commit_id=commit_id,
68
+ requested_revision=requested_revision,
69
+ ),
70
+ subdirectory=link.subdirectory_fragment,
71
+ )
72
+ elif link.is_existing_dir():
73
+ return DirectUrl(
74
+ url=link.url_without_fragment,
75
+ info=DirInfo(),
76
+ subdirectory=link.subdirectory_fragment,
77
+ )
78
+ else:
79
+ hash = None
80
+ hash_name = link.hash_name
81
+ if hash_name:
82
+ hash = f"{hash_name}={link.hash}"
83
+ return DirectUrl(
84
+ url=link.url_without_fragment,
85
+ info=ArchiveInfo(hash=hash),
86
+ subdirectory=link.subdirectory_fragment,
87
+ )
shared/package-files/e8/e85f3d181896a0de17274e65d0f770e8b8c0b029a6abc2bb933d59bb76b6be87/blob ADDED
Binary file (1.2 kB). View file
 
shared/package-files/e8/e8610e5f6cb42b523373df00a23b7ca425d2db551caeee84f93ff7de5454f76b/blob ADDED
@@ -0,0 +1,936 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A directive for including a Matplotlib plot in a Sphinx document
3
+ ================================================================
4
+
5
+ This is a Sphinx extension providing a reStructuredText directive
6
+ ``.. plot::`` for including a plot in a Sphinx document.
7
+
8
+ In HTML output, ``.. plot::`` will include a .png file with a link
9
+ to a high-res .png and .pdf. In LaTeX output, it will include a .pdf.
10
+
11
+ The plot content may be defined in one of three ways:
12
+
13
+ 1. **A path to a source file** as the argument to the directive::
14
+
15
+ .. plot:: path/to/plot.py
16
+
17
+ When a path to a source file is given, the content of the
18
+ directive may optionally contain a caption for the plot::
19
+
20
+ .. plot:: path/to/plot.py
21
+
22
+ The plot caption.
23
+
24
+ Additionally, one may specify the name of a function to call (with
25
+ no arguments) immediately after importing the module::
26
+
27
+ .. plot:: path/to/plot.py plot_function1
28
+
29
+ 2. Included as **inline content** to the directive::
30
+
31
+ .. plot::
32
+
33
+ import matplotlib.pyplot as plt
34
+ plt.plot([1, 2, 3], [4, 5, 6])
35
+ plt.title("A plotting exammple")
36
+
37
+ 3. Using **doctest** syntax::
38
+
39
+ .. plot::
40
+
41
+ A plotting example:
42
+ >>> import matplotlib.pyplot as plt
43
+ >>> plt.plot([1, 2, 3], [4, 5, 6])
44
+
45
+ Options
46
+ -------
47
+
48
+ The ``.. plot::`` directive supports the following options:
49
+
50
+ ``:format:`` : {'python', 'doctest'}
51
+ The format of the input. If unset, the format is auto-detected.
52
+
53
+ ``:include-source:`` : bool
54
+ Whether to display the source code. The default can be changed using
55
+ the ``plot_include_source`` variable in :file:`conf.py` (which itself
56
+ defaults to False).
57
+
58
+ ``:show-source-link:`` : bool
59
+ Whether to show a link to the source in HTML. The default can be
60
+ changed using the ``plot_html_show_source_link`` variable in
61
+ :file:`conf.py` (which itself defaults to True).
62
+
63
+ ``:context:`` : bool or str
64
+ If provided, the code will be run in the context of all previous plot
65
+ directives for which the ``:context:`` option was specified. This only
66
+ applies to inline code plot directives, not those run from files. If
67
+ the ``:context: reset`` option is specified, the context is reset
68
+ for this and future plots, and previous figures are closed prior to
69
+ running the code. ``:context: close-figs`` keeps the context but closes
70
+ previous figures before running the code.
71
+
72
+ ``:nofigs:`` : bool
73
+ If specified, the code block will be run, but no figures will be
74
+ inserted. This is usually useful with the ``:context:`` option.
75
+
76
+ ``:caption:`` : str
77
+ If specified, the option's argument will be used as a caption for the
78
+ figure. This overwrites the caption given in the content, when the plot
79
+ is generated from a file.
80
+
81
+ Additionally, this directive supports all the options of the `image directive
82
+ <https://docutils.sourceforge.io/docs/ref/rst/directives.html#image>`_,
83
+ except for ``:target:`` (since plot will add its own target). These include
84
+ ``:alt:``, ``:height:``, ``:width:``, ``:scale:``, ``:align:`` and ``:class:``.
85
+
86
+ Configuration options
87
+ ---------------------
88
+
89
+ The plot directive has the following configuration options:
90
+
91
+ plot_include_source
92
+ Default value for the include-source option (default: False).
93
+
94
+ plot_html_show_source_link
95
+ Whether to show a link to the source in HTML (default: True).
96
+
97
+ plot_pre_code
98
+ Code that should be executed before each plot. If None (the default),
99
+ it will default to a string containing::
100
+
101
+ import numpy as np
102
+ from matplotlib import pyplot as plt
103
+
104
+ plot_basedir
105
+ Base directory, to which ``plot::`` file names are relative to.
106
+ If None or empty (the default), file names are relative to the
107
+ directory where the file containing the directive is.
108
+
109
+ plot_formats
110
+ File formats to generate (default: ['png', 'hires.png', 'pdf']).
111
+ List of tuples or strings::
112
+
113
+ [(suffix, dpi), suffix, ...]
114
+
115
+ that determine the file format and the DPI. For entries whose
116
+ DPI was omitted, sensible defaults are chosen. When passing from
117
+ the command line through sphinx_build the list should be passed as
118
+ suffix:dpi,suffix:dpi, ...
119
+
120
+ plot_html_show_formats
121
+ Whether to show links to the files in HTML (default: True).
122
+
123
+ plot_rcparams
124
+ A dictionary containing any non-standard rcParams that should
125
+ be applied before each plot (default: {}).
126
+
127
+ plot_apply_rcparams
128
+ By default, rcParams are applied when ``:context:`` option is not used
129
+ in a plot directive. If set, this configuration option overrides this
130
+ behavior and applies rcParams before each plot.
131
+
132
+ plot_working_directory
133
+ By default, the working directory will be changed to the directory of
134
+ the example, so the code can get at its data files, if any. Also its
135
+ path will be added to `sys.path` so it can import any helper modules
136
+ sitting beside it. This configuration option can be used to specify
137
+ a central directory (also added to `sys.path`) where data files and
138
+ helper modules for all code are located.
139
+
140
+ plot_template
141
+ Provide a customized template for preparing restructured text.
142
+
143
+ plot_srcset
144
+ Allow the srcset image option for responsive image resolutions. List of
145
+ strings with the multiplicative factors followed by an "x".
146
+ e.g. ["2.0x", "1.5x"]. "2.0x" will create a png with the default "png"
147
+ resolution from plot_formats, multiplied by 2. If plot_srcset is
148
+ specified, the plot directive uses the
149
+ :doc:`/api/sphinxext_figmpl_directive_api` (instead of the usual figure
150
+ directive) in the intermediary rst file that is generated.
151
+ The plot_srcset option is incompatible with *singlehtml* builds, and an
152
+ error will be raised.
153
+
154
+ Notes on how it works
155
+ ---------------------
156
+
157
+ The plot directive runs the code it is given, either in the source file or the
158
+ code under the directive. The figure created (if any) is saved in the sphinx
159
+ build directory under a subdirectory named ``plot_directive``. It then creates
160
+ an intermediate rst file that calls a ``.. figure:`` directive (or
161
+ ``.. figmpl::`` directive if ``plot_srcset`` is being used) and has links to
162
+ the ``*.png`` files in the ``plot_directive`` directory. These translations can
163
+ be customized by changing the *plot_template*. See the source of
164
+ :doc:`/api/sphinxext_plot_directive_api` for the templates defined in *TEMPLATE*
165
+ and *TEMPLATE_SRCSET*.
166
+ """
167
+
168
+ import contextlib
169
+ import doctest
170
+ from io import StringIO
171
+ import itertools
172
+ import os
173
+ from os.path import relpath
174
+ from pathlib import Path
175
+ import re
176
+ import shutil
177
+ import sys
178
+ import textwrap
179
+ import traceback
180
+
181
+ from docutils.parsers.rst import directives, Directive
182
+ from docutils.parsers.rst.directives.images import Image
183
+ import jinja2 # Sphinx dependency.
184
+
185
+ from sphinx.errors import ExtensionError
186
+
187
+ import matplotlib
188
+ from matplotlib.backend_bases import FigureManagerBase
189
+ import matplotlib.pyplot as plt
190
+ from matplotlib import _pylab_helpers, cbook
191
+
192
+ matplotlib.use("agg")
193
+
194
+ __version__ = 2
195
+
196
+
197
+ # -----------------------------------------------------------------------------
198
+ # Registration hook
199
+ # -----------------------------------------------------------------------------
200
+
201
+
202
+ def _option_boolean(arg):
203
+ if not arg or not arg.strip():
204
+ # no argument given, assume used as a flag
205
+ return True
206
+ elif arg.strip().lower() in ('no', '0', 'false'):
207
+ return False
208
+ elif arg.strip().lower() in ('yes', '1', 'true'):
209
+ return True
210
+ else:
211
+ raise ValueError(f'{arg!r} unknown boolean')
212
+
213
+
214
+ def _option_context(arg):
215
+ if arg in [None, 'reset', 'close-figs']:
216
+ return arg
217
+ raise ValueError("Argument should be None or 'reset' or 'close-figs'")
218
+
219
+
220
+ def _option_format(arg):
221
+ return directives.choice(arg, ('python', 'doctest'))
222
+
223
+
224
+ def mark_plot_labels(app, document):
225
+ """
226
+ To make plots referenceable, we need to move the reference from the
227
+ "htmlonly" (or "latexonly") node to the actual figure node itself.
228
+ """
229
+ for name, explicit in document.nametypes.items():
230
+ if not explicit:
231
+ continue
232
+ labelid = document.nameids[name]
233
+ if labelid is None:
234
+ continue
235
+ node = document.ids[labelid]
236
+ if node.tagname in ('html_only', 'latex_only'):
237
+ for n in node:
238
+ if n.tagname == 'figure':
239
+ sectname = name
240
+ for c in n:
241
+ if c.tagname == 'caption':
242
+ sectname = c.astext()
243
+ break
244
+
245
+ node['ids'].remove(labelid)
246
+ node['names'].remove(name)
247
+ n['ids'].append(labelid)
248
+ n['names'].append(name)
249
+ document.settings.env.labels[name] = \
250
+ document.settings.env.docname, labelid, sectname
251
+ break
252
+
253
+
254
+ class PlotDirective(Directive):
255
+ """The ``.. plot::`` directive, as documented in the module's docstring."""
256
+
257
+ has_content = True
258
+ required_arguments = 0
259
+ optional_arguments = 2
260
+ final_argument_whitespace = False
261
+ option_spec = {
262
+ 'alt': directives.unchanged,
263
+ 'height': directives.length_or_unitless,
264
+ 'width': directives.length_or_percentage_or_unitless,
265
+ 'scale': directives.nonnegative_int,
266
+ 'align': Image.align,
267
+ 'class': directives.class_option,
268
+ 'include-source': _option_boolean,
269
+ 'show-source-link': _option_boolean,
270
+ 'format': _option_format,
271
+ 'context': _option_context,
272
+ 'nofigs': directives.flag,
273
+ 'caption': directives.unchanged,
274
+ }
275
+
276
+ def run(self):
277
+ """Run the plot directive."""
278
+ try:
279
+ return run(self.arguments, self.content, self.options,
280
+ self.state_machine, self.state, self.lineno)
281
+ except Exception as e:
282
+ raise self.error(str(e))
283
+
284
+
285
+ def _copy_css_file(app, exc):
286
+ if exc is None and app.builder.format == 'html':
287
+ src = cbook._get_data_path('plot_directive/plot_directive.css')
288
+ dst = app.outdir / Path('_static')
289
+ dst.mkdir(exist_ok=True)
290
+ # Use copyfile because we do not want to copy src's permissions.
291
+ shutil.copyfile(src, dst / Path('plot_directive.css'))
292
+
293
+
294
+ def setup(app):
295
+ setup.app = app
296
+ setup.config = app.config
297
+ setup.confdir = app.confdir
298
+ app.add_directive('plot', PlotDirective)
299
+ app.add_config_value('plot_pre_code', None, True)
300
+ app.add_config_value('plot_include_source', False, True)
301
+ app.add_config_value('plot_html_show_source_link', True, True)
302
+ app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)
303
+ app.add_config_value('plot_basedir', None, True)
304
+ app.add_config_value('plot_html_show_formats', True, True)
305
+ app.add_config_value('plot_rcparams', {}, True)
306
+ app.add_config_value('plot_apply_rcparams', False, True)
307
+ app.add_config_value('plot_working_directory', None, True)
308
+ app.add_config_value('plot_template', None, True)
309
+ app.add_config_value('plot_srcset', [], True)
310
+ app.connect('doctree-read', mark_plot_labels)
311
+ app.add_css_file('plot_directive.css')
312
+ app.connect('build-finished', _copy_css_file)
313
+ metadata = {'parallel_read_safe': True, 'parallel_write_safe': True,
314
+ 'version': matplotlib.__version__}
315
+ return metadata
316
+
317
+
318
+ # -----------------------------------------------------------------------------
319
+ # Doctest handling
320
+ # -----------------------------------------------------------------------------
321
+
322
+
323
+ def contains_doctest(text):
324
+ try:
325
+ # check if it's valid Python as-is
326
+ compile(text, '<string>', 'exec')
327
+ return False
328
+ except SyntaxError:
329
+ pass
330
+ r = re.compile(r'^\s*>>>', re.M)
331
+ m = r.search(text)
332
+ return bool(m)
333
+
334
+
335
+ def _split_code_at_show(text, function_name):
336
+ """Split code at plt.show()."""
337
+
338
+ is_doctest = contains_doctest(text)
339
+ if function_name is None:
340
+ parts = []
341
+ part = []
342
+ for line in text.split("\n"):
343
+ if ((not is_doctest and line.startswith('plt.show(')) or
344
+ (is_doctest and line.strip() == '>>> plt.show()')):
345
+ part.append(line)
346
+ parts.append("\n".join(part))
347
+ part = []
348
+ else:
349
+ part.append(line)
350
+ if "\n".join(part).strip():
351
+ parts.append("\n".join(part))
352
+ else:
353
+ parts = [text]
354
+ return is_doctest, parts
355
+
356
+
357
+ # -----------------------------------------------------------------------------
358
+ # Template
359
+ # -----------------------------------------------------------------------------
360
+
361
+ _SOURCECODE = """
362
+ {{ source_code }}
363
+
364
+ .. only:: html
365
+
366
+ {% if src_name or (html_show_formats and not multi_image) %}
367
+ (
368
+ {%- if src_name -%}
369
+ :download:`Source code <{{ build_dir }}/{{ src_name }}>`
370
+ {%- endif -%}
371
+ {%- if html_show_formats and not multi_image -%}
372
+ {%- for img in images -%}
373
+ {%- for fmt in img.formats -%}
374
+ {%- if src_name or not loop.first -%}, {% endif -%}
375
+ :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`
376
+ {%- endfor -%}
377
+ {%- endfor -%}
378
+ {%- endif -%}
379
+ )
380
+ {% endif %}
381
+ """
382
+
383
+ TEMPLATE_SRCSET = _SOURCECODE + """
384
+ {% for img in images %}
385
+ .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
386
+ {% for option in options -%}
387
+ {{ option }}
388
+ {% endfor %}
389
+ {%- if caption -%}
390
+ {{ caption }} {# appropriate leading whitespace added beforehand #}
391
+ {% endif -%}
392
+ {%- if srcset -%}
393
+ :srcset: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
394
+ {%- for sr in srcset -%}
395
+ , {{ build_dir }}/{{ img.basename }}.{{ sr }}.{{ default_fmt }} {{sr}}
396
+ {%- endfor -%}
397
+ {% endif %}
398
+
399
+ {% if html_show_formats and multi_image %}
400
+ (
401
+ {%- for fmt in img.formats -%}
402
+ {%- if not loop.first -%}, {% endif -%}
403
+ :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`
404
+ {%- endfor -%}
405
+ )
406
+ {% endif %}
407
+
408
+
409
+ {% endfor %}
410
+
411
+ .. only:: not html
412
+
413
+ {% for img in images %}
414
+ .. figure-mpl:: {{ build_dir }}/{{ img.basename }}.*
415
+ {% for option in options -%}
416
+ {{ option }}
417
+ {% endfor -%}
418
+
419
+ {{ caption }} {# appropriate leading whitespace added beforehand #}
420
+ {% endfor %}
421
+
422
+ """
423
+
424
+ TEMPLATE = _SOURCECODE + """
425
+
426
+ {% for img in images %}
427
+ .. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
428
+ {% for option in options -%}
429
+ {{ option }}
430
+ {% endfor %}
431
+
432
+ {% if html_show_formats and multi_image -%}
433
+ (
434
+ {%- for fmt in img.formats -%}
435
+ {%- if not loop.first -%}, {% endif -%}
436
+ :download:`{{ fmt }} <{{ build_dir }}/{{ img.basename }}.{{ fmt }}>`
437
+ {%- endfor -%}
438
+ )
439
+ {%- endif -%}
440
+
441
+ {{ caption }} {# appropriate leading whitespace added beforehand #}
442
+ {% endfor %}
443
+
444
+ .. only:: not html
445
+
446
+ {% for img in images %}
447
+ .. figure:: {{ build_dir }}/{{ img.basename }}.*
448
+ {% for option in options -%}
449
+ {{ option }}
450
+ {% endfor -%}
451
+
452
+ {{ caption }} {# appropriate leading whitespace added beforehand #}
453
+ {% endfor %}
454
+
455
+ """
456
+
457
+ exception_template = """
458
+ .. only:: html
459
+
460
+ [`source code <%(linkdir)s/%(basename)s.py>`__]
461
+
462
+ Exception occurred rendering plot.
463
+
464
+ """
465
+
466
+ # the context of the plot for all directives specified with the
467
+ # :context: option
468
+ plot_context = dict()
469
+
470
+
471
+ class ImageFile:
472
+ def __init__(self, basename, dirname):
473
+ self.basename = basename
474
+ self.dirname = dirname
475
+ self.formats = []
476
+
477
+ def filename(self, format):
478
+ return os.path.join(self.dirname, f"{self.basename}.{format}")
479
+
480
+ def filenames(self):
481
+ return [self.filename(fmt) for fmt in self.formats]
482
+
483
+
484
+ def out_of_date(original, derived, includes=None):
485
+ """
486
+ Return whether *derived* is out-of-date relative to *original* or any of
487
+ the RST files included in it using the RST include directive (*includes*).
488
+ *derived* and *original* are full paths, and *includes* is optionally a
489
+ list of full paths which may have been included in the *original*.
490
+ """
491
+ if not os.path.exists(derived):
492
+ return True
493
+
494
+ if includes is None:
495
+ includes = []
496
+ files_to_check = [original, *includes]
497
+
498
+ def out_of_date_one(original, derived_mtime):
499
+ return (os.path.exists(original) and
500
+ derived_mtime < os.stat(original).st_mtime)
501
+
502
+ derived_mtime = os.stat(derived).st_mtime
503
+ return any(out_of_date_one(f, derived_mtime) for f in files_to_check)
504
+
505
+
506
+ class PlotError(RuntimeError):
507
+ pass
508
+
509
+
510
+ def _run_code(code, code_path, ns=None, function_name=None):
511
+ """
512
+ Import a Python module from a path, and run the function given by
513
+ name, if function_name is not None.
514
+ """
515
+
516
+ # Change the working directory to the directory of the example, so
517
+ # it can get at its data files, if any. Add its path to sys.path
518
+ # so it can import any helper modules sitting beside it.
519
+ pwd = os.getcwd()
520
+ if setup.config.plot_working_directory is not None:
521
+ try:
522
+ os.chdir(setup.config.plot_working_directory)
523
+ except OSError as err:
524
+ raise OSError(f'{err}\n`plot_working_directory` option in '
525
+ f'Sphinx configuration file must be a valid '
526
+ f'directory path') from err
527
+ except TypeError as err:
528
+ raise TypeError(f'{err}\n`plot_working_directory` option in '
529
+ f'Sphinx configuration file must be a string or '
530
+ f'None') from err
531
+ elif code_path is not None:
532
+ dirname = os.path.abspath(os.path.dirname(code_path))
533
+ os.chdir(dirname)
534
+
535
+ with cbook._setattr_cm(
536
+ sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \
537
+ contextlib.redirect_stdout(StringIO()):
538
+ try:
539
+ if ns is None:
540
+ ns = {}
541
+ if not ns:
542
+ if setup.config.plot_pre_code is None:
543
+ exec('import numpy as np\n'
544
+ 'from matplotlib import pyplot as plt\n', ns)
545
+ else:
546
+ exec(str(setup.config.plot_pre_code), ns)
547
+ if "__main__" in code:
548
+ ns['__name__'] = '__main__'
549
+
550
+ # Patch out non-interactive show() to avoid triggering a warning.
551
+ with cbook._setattr_cm(FigureManagerBase, show=lambda self: None):
552
+ exec(code, ns)
553
+ if function_name is not None:
554
+ exec(function_name + "()", ns)
555
+
556
+ except (Exception, SystemExit) as err:
557
+ raise PlotError(traceback.format_exc()) from err
558
+ finally:
559
+ os.chdir(pwd)
560
+ return ns
561
+
562
+
563
+ def clear_state(plot_rcparams, close=True):
564
+ if close:
565
+ plt.close('all')
566
+ matplotlib.rc_file_defaults()
567
+ matplotlib.rcParams.update(plot_rcparams)
568
+
569
+
570
+ def get_plot_formats(config):
571
+ default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200}
572
+ formats = []
573
+ plot_formats = config.plot_formats
574
+ for fmt in plot_formats:
575
+ if isinstance(fmt, str):
576
+ if ':' in fmt:
577
+ suffix, dpi = fmt.split(':')
578
+ formats.append((str(suffix), int(dpi)))
579
+ else:
580
+ formats.append((fmt, default_dpi.get(fmt, 80)))
581
+ elif isinstance(fmt, (tuple, list)) and len(fmt) == 2:
582
+ formats.append((str(fmt[0]), int(fmt[1])))
583
+ else:
584
+ raise PlotError('invalid image format "%r" in plot_formats' % fmt)
585
+ return formats
586
+
587
+
588
+ def _parse_srcset(entries):
589
+ """
590
+ Parse srcset for multiples...
591
+ """
592
+ srcset = {}
593
+ for entry in entries:
594
+ entry = entry.strip()
595
+ if len(entry) >= 2:
596
+ mult = entry[:-1]
597
+ srcset[float(mult)] = entry
598
+ else:
599
+ raise ExtensionError(f'srcset argument {entry!r} is invalid.')
600
+ return srcset
601
+
602
+
603
+ def render_figures(code, code_path, output_dir, output_base, context,
604
+ function_name, config, context_reset=False,
605
+ close_figs=False,
606
+ code_includes=None):
607
+ """
608
+ Run a pyplot script and save the images in *output_dir*.
609
+
610
+ Save the images under *output_dir* with file names derived from
611
+ *output_base*
612
+ """
613
+
614
+ if function_name is not None:
615
+ output_base = f'{output_base}_{function_name}'
616
+ formats = get_plot_formats(config)
617
+
618
+ # Try to determine if all images already exist
619
+
620
+ is_doctest, code_pieces = _split_code_at_show(code, function_name)
621
+ # Look for single-figure output files first
622
+ img = ImageFile(output_base, output_dir)
623
+ for format, dpi in formats:
624
+ if context or out_of_date(code_path, img.filename(format),
625
+ includes=code_includes):
626
+ all_exists = False
627
+ break
628
+ img.formats.append(format)
629
+ else:
630
+ all_exists = True
631
+
632
+ if all_exists:
633
+ return [(code, [img])]
634
+
635
+ # Then look for multi-figure output files
636
+ results = []
637
+ for i, code_piece in enumerate(code_pieces):
638
+ images = []
639
+ for j in itertools.count():
640
+ if len(code_pieces) > 1:
641
+ img = ImageFile('%s_%02d_%02d' % (output_base, i, j),
642
+ output_dir)
643
+ else:
644
+ img = ImageFile('%s_%02d' % (output_base, j), output_dir)
645
+ for fmt, dpi in formats:
646
+ if context or out_of_date(code_path, img.filename(fmt),
647
+ includes=code_includes):
648
+ all_exists = False
649
+ break
650
+ img.formats.append(fmt)
651
+
652
+ # assume that if we have one, we have them all
653
+ if not all_exists:
654
+ all_exists = (j > 0)
655
+ break
656
+ images.append(img)
657
+ if not all_exists:
658
+ break
659
+ results.append((code_piece, images))
660
+ else:
661
+ all_exists = True
662
+
663
+ if all_exists:
664
+ return results
665
+
666
+ # We didn't find the files, so build them
667
+
668
+ results = []
669
+ ns = plot_context if context else {}
670
+
671
+ if context_reset:
672
+ clear_state(config.plot_rcparams)
673
+ plot_context.clear()
674
+
675
+ close_figs = not context or close_figs
676
+
677
+ for i, code_piece in enumerate(code_pieces):
678
+
679
+ if not context or config.plot_apply_rcparams:
680
+ clear_state(config.plot_rcparams, close_figs)
681
+ elif close_figs:
682
+ plt.close('all')
683
+
684
+ _run_code(doctest.script_from_examples(code_piece) if is_doctest
685
+ else code_piece,
686
+ code_path, ns, function_name)
687
+
688
+ images = []
689
+ fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
690
+ for j, figman in enumerate(fig_managers):
691
+ if len(fig_managers) == 1 and len(code_pieces) == 1:
692
+ img = ImageFile(output_base, output_dir)
693
+ elif len(code_pieces) == 1:
694
+ img = ImageFile("%s_%02d" % (output_base, j), output_dir)
695
+ else:
696
+ img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
697
+ output_dir)
698
+ images.append(img)
699
+
700
+ for fmt, dpi in formats:
701
+ try:
702
+ figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi)
703
+ if fmt == formats[0][0] and config.plot_srcset:
704
+ # save a 2x, 3x etc version of the default...
705
+ srcset = _parse_srcset(config.plot_srcset)
706
+ for mult, suffix in srcset.items():
707
+ fm = f'{suffix}.{fmt}'
708
+ img.formats.append(fm)
709
+ figman.canvas.figure.savefig(img.filename(fm),
710
+ dpi=int(dpi * mult))
711
+ except Exception as err:
712
+ raise PlotError(traceback.format_exc()) from err
713
+ img.formats.append(fmt)
714
+
715
+ results.append((code_piece, images))
716
+
717
+ if not context or config.plot_apply_rcparams:
718
+ clear_state(config.plot_rcparams, close=not context)
719
+
720
+ return results
721
+
722
+
723
+ def run(arguments, content, options, state_machine, state, lineno):
724
+ document = state_machine.document
725
+ config = document.settings.env.config
726
+ nofigs = 'nofigs' in options
727
+
728
+ if config.plot_srcset and setup.app.builder.name == 'singlehtml':
729
+ raise ExtensionError(
730
+ 'plot_srcset option not compatible with single HTML writer')
731
+
732
+ formats = get_plot_formats(config)
733
+ default_fmt = formats[0][0]
734
+
735
+ options.setdefault('include-source', config.plot_include_source)
736
+ options.setdefault('show-source-link', config.plot_html_show_source_link)
737
+
738
+ if 'class' in options:
739
+ # classes are parsed into a list of string, and output by simply
740
+ # printing the list, abusing the fact that RST guarantees to strip
741
+ # non-conforming characters
742
+ options['class'] = ['plot-directive'] + options['class']
743
+ else:
744
+ options.setdefault('class', ['plot-directive'])
745
+ keep_context = 'context' in options
746
+ context_opt = None if not keep_context else options['context']
747
+
748
+ rst_file = document.attributes['source']
749
+ rst_dir = os.path.dirname(rst_file)
750
+
751
+ if len(arguments):
752
+ if not config.plot_basedir:
753
+ source_file_name = os.path.join(setup.app.builder.srcdir,
754
+ directives.uri(arguments[0]))
755
+ else:
756
+ source_file_name = os.path.join(setup.confdir, config.plot_basedir,
757
+ directives.uri(arguments[0]))
758
+ # If there is content, it will be passed as a caption.
759
+ caption = '\n'.join(content)
760
+
761
+ # Enforce unambiguous use of captions.
762
+ if "caption" in options:
763
+ if caption:
764
+ raise ValueError(
765
+ 'Caption specified in both content and options.'
766
+ ' Please remove ambiguity.'
767
+ )
768
+ # Use caption option
769
+ caption = options["caption"]
770
+
771
+ # If the optional function name is provided, use it
772
+ if len(arguments) == 2:
773
+ function_name = arguments[1]
774
+ else:
775
+ function_name = None
776
+
777
+ code = Path(source_file_name).read_text(encoding='utf-8')
778
+ output_base = os.path.basename(source_file_name)
779
+ else:
780
+ source_file_name = rst_file
781
+ code = textwrap.dedent("\n".join(map(str, content)))
782
+ counter = document.attributes.get('_plot_counter', 0) + 1
783
+ document.attributes['_plot_counter'] = counter
784
+ base, ext = os.path.splitext(os.path.basename(source_file_name))
785
+ output_base = '%s-%d.py' % (base, counter)
786
+ function_name = None
787
+ caption = options.get('caption', '')
788
+
789
+ base, source_ext = os.path.splitext(output_base)
790
+ if source_ext in ('.py', '.rst', '.txt'):
791
+ output_base = base
792
+ else:
793
+ source_ext = ''
794
+
795
+ # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
796
+ output_base = output_base.replace('.', '-')
797
+
798
+ # is it in doctest format?
799
+ is_doctest = contains_doctest(code)
800
+ if 'format' in options:
801
+ if options['format'] == 'python':
802
+ is_doctest = False
803
+ else:
804
+ is_doctest = True
805
+
806
+ # determine output directory name fragment
807
+ source_rel_name = relpath(source_file_name, setup.confdir)
808
+ source_rel_dir = os.path.dirname(source_rel_name).lstrip(os.path.sep)
809
+
810
+ # build_dir: where to place output files (temporarily)
811
+ build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
812
+ 'plot_directive',
813
+ source_rel_dir)
814
+ # get rid of .. in paths, also changes pathsep
815
+ # see note in Python docs for warning about symbolic links on Windows.
816
+ # need to compare source and dest paths at end
817
+ build_dir = os.path.normpath(build_dir)
818
+ os.makedirs(build_dir, exist_ok=True)
819
+
820
+ # how to link to files from the RST file
821
+ try:
822
+ build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
823
+ except ValueError:
824
+ # on Windows, relpath raises ValueError when path and start are on
825
+ # different mounts/drives
826
+ build_dir_link = build_dir
827
+
828
+ # get list of included rst files so that the output is updated when any
829
+ # plots in the included files change. These attributes are modified by the
830
+ # include directive (see the docutils.parsers.rst.directives.misc module).
831
+ try:
832
+ source_file_includes = [os.path.join(os.getcwd(), t[0])
833
+ for t in state.document.include_log]
834
+ except AttributeError:
835
+ # the document.include_log attribute only exists in docutils >=0.17,
836
+ # before that we need to inspect the state machine
837
+ possible_sources = {os.path.join(setup.confdir, t[0])
838
+ for t in state_machine.input_lines.items}
839
+ source_file_includes = [f for f in possible_sources
840
+ if os.path.isfile(f)]
841
+ # remove the source file itself from the includes
842
+ try:
843
+ source_file_includes.remove(source_file_name)
844
+ except ValueError:
845
+ pass
846
+
847
+ # save script (if necessary)
848
+ if options['show-source-link']:
849
+ Path(build_dir, output_base + source_ext).write_text(
850
+ doctest.script_from_examples(code)
851
+ if source_file_name == rst_file and is_doctest
852
+ else code,
853
+ encoding='utf-8')
854
+
855
+ # make figures
856
+ try:
857
+ results = render_figures(code=code,
858
+ code_path=source_file_name,
859
+ output_dir=build_dir,
860
+ output_base=output_base,
861
+ context=keep_context,
862
+ function_name=function_name,
863
+ config=config,
864
+ context_reset=context_opt == 'reset',
865
+ close_figs=context_opt == 'close-figs',
866
+ code_includes=source_file_includes)
867
+ errors = []
868
+ except PlotError as err:
869
+ reporter = state.memo.reporter
870
+ sm = reporter.system_message(
871
+ 2, "Exception occurred in plotting {}\n from {}:\n{}".format(
872
+ output_base, source_file_name, err),
873
+ line=lineno)
874
+ results = [(code, [])]
875
+ errors = [sm]
876
+
877
+ # Properly indent the caption
878
+ if caption and config.plot_srcset:
879
+ caption = ':caption: ' + caption.replace('\n', ' ')
880
+ elif caption:
881
+ caption = '\n' + '\n'.join(' ' + line.strip()
882
+ for line in caption.split('\n'))
883
+ # generate output restructuredtext
884
+ total_lines = []
885
+ for j, (code_piece, images) in enumerate(results):
886
+ if options['include-source']:
887
+ if is_doctest:
888
+ lines = ['', *code_piece.splitlines()]
889
+ else:
890
+ lines = ['.. code-block:: python', '',
891
+ *textwrap.indent(code_piece, ' ').splitlines()]
892
+ source_code = "\n".join(lines)
893
+ else:
894
+ source_code = ""
895
+
896
+ if nofigs:
897
+ images = []
898
+
899
+ if 'alt' in options:
900
+ options['alt'] = options['alt'].replace('\n', ' ')
901
+
902
+ opts = [
903
+ f':{key}: {val}' for key, val in options.items()
904
+ if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]
905
+
906
+ # Not-None src_name signals the need for a source download in the
907
+ # generated html
908
+ if j == 0 and options['show-source-link']:
909
+ src_name = output_base + source_ext
910
+ else:
911
+ src_name = None
912
+ if config.plot_srcset:
913
+ srcset = [*_parse_srcset(config.plot_srcset).values()]
914
+ template = TEMPLATE_SRCSET
915
+ else:
916
+ srcset = None
917
+ template = TEMPLATE
918
+
919
+ result = jinja2.Template(config.plot_template or template).render(
920
+ default_fmt=default_fmt,
921
+ build_dir=build_dir_link,
922
+ src_name=src_name,
923
+ multi_image=len(images) > 1,
924
+ options=opts,
925
+ srcset=srcset,
926
+ images=images,
927
+ source_code=source_code,
928
+ html_show_formats=config.plot_html_show_formats and len(images),
929
+ caption=caption)
930
+ total_lines.extend(result.split("\n"))
931
+ total_lines.extend("\n")
932
+
933
+ if total_lines:
934
+ state_machine.insert_input(total_lines, source=source_file_name)
935
+
936
+ return errors
shared/package-files/e8/e86148ee87aff5c65ac861d2989bbc72a23acbddd311af6003b16f5f490ee6b6/blob ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+
3
+ __all__ = [
4
+ "LinearBlockSparsePattern"
5
+ ]
6
+
7
+ def _is_valid_linear_block_sparse_pattern(row_block_size, col_block_size):
8
+ return (row_block_size == 1 and col_block_size == 4) or \
9
+ (row_block_size == 8 and col_block_size == 1)
10
+
11
+ # This is a stop-gap measure as current flow does not allow module
12
+ # specific block sparse pattern.
13
+ # Infact there is no way to convey sparse pattern via module config
14
+ # of quantization flow. Thus using the global context to convey
15
+ # sparsity pattern.
16
+ # Once the flow supports it, this should be removed.
17
+ class LinearBlockSparsePattern:
18
+ rlock = threading.RLock()
19
+ row_block_size = 1
20
+ col_block_size = 4
21
+ prev_row_block_size = 1
22
+ prev_col_block_size = 4
23
+
24
+ def __init__(self, row_block_size=1, col_block_size=4):
25
+ assert _is_valid_linear_block_sparse_pattern(row_block_size, col_block_size)
26
+ LinearBlockSparsePattern.rlock.acquire()
27
+ LinearBlockSparsePattern.prev_row_block_size = LinearBlockSparsePattern.row_block_size
28
+ LinearBlockSparsePattern.prev_col_block_size = LinearBlockSparsePattern.col_block_size
29
+ LinearBlockSparsePattern.row_block_size = row_block_size
30
+ LinearBlockSparsePattern.col_block_size = col_block_size
31
+
32
+ def __enter__(self):
33
+ pass
34
+
35
+ def __exit__(self, exc_type, exc_value, backtrace):
36
+ LinearBlockSparsePattern.row_block_size = LinearBlockSparsePattern.prev_row_block_size
37
+ LinearBlockSparsePattern.col_block_size = LinearBlockSparsePattern.prev_col_block_size
38
+ LinearBlockSparsePattern.rlock.release()
39
+
40
+ @staticmethod
41
+ def block_size():
42
+ return LinearBlockSparsePattern.row_block_size, LinearBlockSparsePattern.col_block_size