s42chen commited on
Commit
c63702b
·
verified ·
1 Parent(s): d91b385

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. shared/package-files/06/06003cce6773f4dc3e5dbbb8fb0dd4001796ca9a8bbe6cbd5732fbe3812662d1/test_rewrite.py +74 -0
  2. shared/package-files/06/060f52bfcb8d3df3376c3b56ac879a8675da71dc864a396221e70fc870aa9937/test_pprint.py +695 -0
  3. shared/package-files/06/061232ee06f86f807af33de374eda5936133334c56c62c9a55ef1210e45700e1/margins.py +303 -0
  4. shared/package-files/06/062d1e165712e78effcbd8e10b8a59ae62e450a7c87083589230eaeef659dab4/qnxw +0 -0
  5. shared/package-files/06/069ed4c1f7c830eee873c527155d75c9819c5d48d26b4361b2e3a041a35132df/test_rv.py +441 -0
  6. shared/package-files/06/069f0d6d4cdf0f03e40bf33b01cac2fc3413cce89a528caef3f9c75f4a22ea76/python_ivalue.h +97 -0
  7. shared/package-files/06/06a0d61aa47624e544ab2f31ae6c858f4ef591cf8fba38a5695276edb13d3ecb/data_missing.dta +0 -0
  8. shared/package-files/06/06bd03cb0ab219a5701da59b81b21664b9d0610ed2a5ad38678794f13ac7cfef/__init__.pyi +309 -0
  9. shared/package-files/06/06d090ae1a5cf3f42e004c937acfa25d9bcd1830a4e0c7218eaf4e0ee7a40025/sparse_csc_tensor_ops.h +39 -0
  10. shared/package-files/06/06e5eecfab0237d4daed4956441ce3c7876d0e96dd748de38cabbcc4ea430f04/kl_div.h +30 -0
  11. shared/package-files/1f/1f012661d626769e2bec85a7a56ac4d20d19d7f1ccdd3ace9a1aebcfb1ad25e0/ansi.sys-old +0 -0
  12. shared/package-files/1f/1f0c7a1de6f606f4d33037d660bdf24685eca8c77dc5dbb5fcb457cf69cccf0b/win32-headers.h +60 -0
  13. shared/package-files/1f/1f0c9cca56cf020455cf89d9be3bf0a8dde642725ba8a03e35131a02f20ff821/_utility_functions.py +37 -0
  14. shared/package-files/1f/1f0ca74ed835cfb97b142562b47e00d3b505f1bff14b8b3b8682aabfe43aac1b/ansi.sys +0 -0
  15. shared/package-files/1f/1f1b0f5dede0263bd81773a78e98af551f36361accb315b618c8ae70a5fe781e/id.msg +47 -0
  16. shared/package-files/1f/1f25c8588b495c12951d4cd67103e2d4c99de992e6664f90851528f4abf65ce2/Omsk +0 -0
  17. shared/package-files/1f/1f3a5a429231389a9f86b10784ac845d11b0cdcfeeefd22eab2fcabaded1562d/six.h +52 -0
  18. shared/package-files/1f/1f3b4f48d844fbb98ef3162a664f704c9437659bb4e9b80a8ddb8f6fc373ca9c/bernoulli_cuda_dispatch.h +26 -0
  19. shared/package-files/1f/1f42bd13d30048a580a164a3b7aa8e67279ef71e4bb7368abc848422c8654da6/norm_except_dim.h +30 -0
  20. shared/package-files/1f/1f4a0d664366c293fc8ba529cac9e40fbc9abded04dd853767c74a1a86d26ce0/test_sdm.py +444 -0
  21. shared/package-files/1f/1f4e17b848b9d5800cfe065a7cf1e576cdfc9cf2c9fd527134095169d52612a6/_nested_get_lengths_ops.h +28 -0
  22. shared/package-files/1f/1f519e110eea3924b0828e79b0d51a896cd56f5bdb02a3abd378677d1f81fa8f/_vector_sentinel.pyx +118 -0
  23. shared/package-files/1f/1f55bdde7a0e8213fab2d4962730fac65163b7476179f1f5b926595c4fcc4d53/rshift_ops.h +83 -0
  24. shared/package-files/1f/1f569ce27cb3145b482bc8bf51cef0b8e9fd1ae8f1e2e7a128061b1ddf93bb0e/scotland_births.html +312 -0
  25. shared/package-files/1f/1f59a95f609804c5eab38ac88282aaed1af4aa19acf7d2c3368da9c5d44e3447/bincount_compositeexplicitautograd_dispatch.h +24 -0
  26. shared/package-files/1f/1f5a6512789fd760f107664a07c1ff9a40b95b15eb3c7a5e1516d32d2c594142/_random.pyx +355 -0
  27. shared/package-files/1f/1f5b81f8d9bec88c2ba738c6a08bba4abc6dc4c6fbb70c3c7c303080eb214cc1/_convert_indices_from_coo_to_csr_native.h +26 -0
  28. shared/package-files/1f/1f666c36d96b5c0a28a42b6200b4cce5a74bde72a327d547e367b2daae2a6abc/nbinom_resids.csv +20 -0
  29. shared/package-files/1f/1f6a89978659a99e1b23e13d3426eed6815fb68d04745c424ca4ee80c3c74478/matfuncs.py +18 -0
  30. shared/package-files/1f/1f6b93fa6477edbf10cfa2880c369f2c16fd53712fcd5de308ecbca5f4237663/dense.py +236 -0
  31. shared/package-files/1f/1f6dfbca13ca6ec97e0a2bf847a12dfcb5f9b815012eb0ea4c3bc14f524c79fe/middleware.pyi +7 -0
  32. shared/package-files/1f/1f6e42785e06337150ab407abb7710a7515918088695b38e86016a9f84480059/_svm_cython_blas_helpers.h +9 -0
  33. shared/package-files/1f/1f726d57e3b9fd25ed45809804e4a07ada87bb4ed41141d1674567b77dc78e43/hp2 +0 -0
  34. shared/package-files/1f/1f726d57e3b9fd25ed45809804e4a07ada87bb4ed41141d1674567b77dc78e43/hpex2 +0 -0
  35. shared/package-files/1f/1f771e18fa4065f1f6fa66eefae63b300ea3b1e93e1c45182c1bd878b4ce3c40/environment.yml +3 -0
  36. shared/package-files/1f/1f795d89c23fae196fd2bdd5169556b542fa5f7d16cb9f7abfbfd81f3dac11d8/langturkishmodel.py +0 -0
  37. shared/package-files/1f/1f7be1029f426e7fbb26e4c6a334be3301a83a511c7757c72a63f4a2ad19d946/_param_validation.py +910 -0
  38. shared/package-files/1f/1f7c72d37dca932cd875eb3c732d17c01de6273fd30f8b38f85e236ed94cd2e3/pprint.py +670 -0
  39. shared/package-files/1f/1f81141da40215c6463fb7f03ac38bd2f5cfd7dfb760881371a194e32c08c489/mps_convolution_backward_ops.h +39 -0
  40. shared/package-files/1f/1f8219810623ae657a2136fb89ec77178ab0052143c8f6ddadbd1ee195db90c6/_dsp.py +433 -0
  41. shared/package-files/1f/1f85cb7a189c3d9da1ec16f7d043911dcb9d728b030fdffbdf045c63251e6a75/news28-a +0 -0
  42. shared/package-files/1f/1f85cb7a189c3d9da1ec16f7d043911dcb9d728b030fdffbdf045c63251e6a75/news29 +0 -0
  43. shared/package-files/1f/1f85f237c2e6c383416779bf50496d1caed3e590037377dba24d8ac0e2804e6f/mergesort.py +126 -0
  44. shared/package-files/1f/1f8619123a353e3e1824e9a27597baaf3b37bf872dd0b130c2d9cb8b1d060858/select_copy_compositeexplicitautogradnonfunctional_dispatch.h +24 -0
  45. shared/package-files/1f/1f8ae7ffab8be339418828bb6a492cec0af74998929c06e12ced655f51383398/special_erfinv_native.h +22 -0
  46. shared/package-files/1f/1f8b43919df95d275faeaa7c1b3ac15f8397e6f8ee8c6e8b3ff5bd031760e4ed/xnuppc+c +0 -0
  47. shared/package-files/1f/1f8c830a711f10c154138388320d452589fd72f8f909b411bf5cdea244dee906/template.pyi +14 -0
  48. shared/package-files/1f/1f924aedebc4c68ebe2b52c946ca31e1f5940451e0f18fee2077c47b4f645a66/tensor_split_compositeimplicitautograd_dispatch.h +27 -0
  49. shared/package-files/1f/1f9398544b699e11b1ead37a04f2481b645857f1d901659a0c17580e3598fa91/DeviceArray.h +28 -0
  50. shared/package-files/1f/1f9aec5b2fb484ec217fb62d337825bba40eae08e6c85fbaaeebdb53e9b58859/replication_pad2d_native.h +26 -0
shared/package-files/06/06003cce6773f4dc3e5dbbb8fb0dd4001796ca9a8bbe6cbd5732fbe3812662d1/test_rewrite.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.unify.rewrite import rewriterule
2
+ from sympy.core.basic import Basic
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import Symbol
5
+ from sympy.functions.elementary.trigonometric import sin
6
+ from sympy.abc import x, y
7
+ from sympy.strategies.rl import rebuild
8
+ from sympy.assumptions import Q
9
+
10
+ p, q = Symbol('p'), Symbol('q')
11
+
12
+ def test_simple():
13
+ rl = rewriterule(Basic(p, S(1)), Basic(p, S(2)), variables=(p,))
14
+ assert list(rl(Basic(S(3), S(1)))) == [Basic(S(3), S(2))]
15
+
16
+ p1 = p**2
17
+ p2 = p**3
18
+ rl = rewriterule(p1, p2, variables=(p,))
19
+
20
+ expr = x**2
21
+ assert list(rl(expr)) == [x**3]
22
+
23
+ def test_simple_variables():
24
+ rl = rewriterule(Basic(x, S(1)), Basic(x, S(2)), variables=(x,))
25
+ assert list(rl(Basic(S(3), S(1)))) == [Basic(S(3), S(2))]
26
+
27
+ rl = rewriterule(x**2, x**3, variables=(x,))
28
+ assert list(rl(y**2)) == [y**3]
29
+
30
+ def test_moderate():
31
+ p1 = p**2 + q**3
32
+ p2 = (p*q)**4
33
+ rl = rewriterule(p1, p2, (p, q))
34
+
35
+ expr = x**2 + y**3
36
+ assert list(rl(expr)) == [(x*y)**4]
37
+
38
+ def test_sincos():
39
+ p1 = sin(p)**2 + sin(p)**2
40
+ p2 = 1
41
+ rl = rewriterule(p1, p2, (p, q))
42
+
43
+ assert list(rl(sin(x)**2 + sin(x)**2)) == [1]
44
+ assert list(rl(sin(y)**2 + sin(y)**2)) == [1]
45
+
46
+ def test_Exprs_ok():
47
+ rl = rewriterule(p+q, q+p, (p, q))
48
+ next(rl(x+y)).is_commutative
49
+ str(next(rl(x+y)))
50
+
51
+ def test_condition_simple():
52
+ rl = rewriterule(x, x+1, [x], lambda x: x < 10)
53
+ assert not list(rl(S(15)))
54
+ assert rebuild(next(rl(S(5)))) == 6
55
+
56
+
57
+ def test_condition_multiple():
58
+ rl = rewriterule(x + y, x**y, [x,y], lambda x, y: x.is_integer)
59
+
60
+ a = Symbol('a')
61
+ b = Symbol('b', integer=True)
62
+ expr = a + b
63
+ assert list(rl(expr)) == [b**a]
64
+
65
+ c = Symbol('c', integer=True)
66
+ d = Symbol('d', integer=True)
67
+ assert set(rl(c + d)) == {c**d, d**c}
68
+
69
+ def test_assumptions():
70
+ rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x))
71
+
72
+ a, b = map(Symbol, 'ab')
73
+ expr = a + b
74
+ assert list(rl(expr, Q.integer(b))) == [b**a]
shared/package-files/06/060f52bfcb8d3df3376c3b56ac879a8675da71dc864a396221e70fc870aa9937/test_pprint.py ADDED
@@ -0,0 +1,695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from pprint import PrettyPrinter
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from sklearn import config_context
8
+ from sklearn.base import BaseEstimator, TransformerMixin
9
+ from sklearn.feature_selection import SelectKBest, chi2
10
+ from sklearn.linear_model import LogisticRegressionCV
11
+ from sklearn.pipeline import make_pipeline
12
+ from sklearn.utils._pprint import _EstimatorPrettyPrinter
13
+
14
+
15
+ # Constructors excerpted to test pprinting
16
+ class LogisticRegression(BaseEstimator):
17
+ def __init__(
18
+ self,
19
+ penalty="l2",
20
+ dual=False,
21
+ tol=1e-4,
22
+ C=1.0,
23
+ fit_intercept=True,
24
+ intercept_scaling=1,
25
+ class_weight=None,
26
+ random_state=None,
27
+ solver="warn",
28
+ max_iter=100,
29
+ multi_class="warn",
30
+ verbose=0,
31
+ warm_start=False,
32
+ n_jobs=None,
33
+ l1_ratio=None,
34
+ ):
35
+ self.penalty = penalty
36
+ self.dual = dual
37
+ self.tol = tol
38
+ self.C = C
39
+ self.fit_intercept = fit_intercept
40
+ self.intercept_scaling = intercept_scaling
41
+ self.class_weight = class_weight
42
+ self.random_state = random_state
43
+ self.solver = solver
44
+ self.max_iter = max_iter
45
+ self.multi_class = multi_class
46
+ self.verbose = verbose
47
+ self.warm_start = warm_start
48
+ self.n_jobs = n_jobs
49
+ self.l1_ratio = l1_ratio
50
+
51
+ def fit(self, X, y):
52
+ return self
53
+
54
+
55
+ class StandardScaler(TransformerMixin, BaseEstimator):
56
+ def __init__(self, copy=True, with_mean=True, with_std=True):
57
+ self.with_mean = with_mean
58
+ self.with_std = with_std
59
+ self.copy = copy
60
+
61
+ def transform(self, X, copy=None):
62
+ return self
63
+
64
+
65
+ class RFE(BaseEstimator):
66
+ def __init__(self, estimator, n_features_to_select=None, step=1, verbose=0):
67
+ self.estimator = estimator
68
+ self.n_features_to_select = n_features_to_select
69
+ self.step = step
70
+ self.verbose = verbose
71
+
72
+
73
+ class GridSearchCV(BaseEstimator):
74
+ def __init__(
75
+ self,
76
+ estimator,
77
+ param_grid,
78
+ scoring=None,
79
+ n_jobs=None,
80
+ iid="warn",
81
+ refit=True,
82
+ cv="warn",
83
+ verbose=0,
84
+ pre_dispatch="2*n_jobs",
85
+ error_score="raise-deprecating",
86
+ return_train_score=False,
87
+ ):
88
+ self.estimator = estimator
89
+ self.param_grid = param_grid
90
+ self.scoring = scoring
91
+ self.n_jobs = n_jobs
92
+ self.iid = iid
93
+ self.refit = refit
94
+ self.cv = cv
95
+ self.verbose = verbose
96
+ self.pre_dispatch = pre_dispatch
97
+ self.error_score = error_score
98
+ self.return_train_score = return_train_score
99
+
100
+
101
+ class CountVectorizer(BaseEstimator):
102
+ def __init__(
103
+ self,
104
+ input="content",
105
+ encoding="utf-8",
106
+ decode_error="strict",
107
+ strip_accents=None,
108
+ lowercase=True,
109
+ preprocessor=None,
110
+ tokenizer=None,
111
+ stop_words=None,
112
+ token_pattern=r"(?u)\b\w\w+\b",
113
+ ngram_range=(1, 1),
114
+ analyzer="word",
115
+ max_df=1.0,
116
+ min_df=1,
117
+ max_features=None,
118
+ vocabulary=None,
119
+ binary=False,
120
+ dtype=np.int64,
121
+ ):
122
+ self.input = input
123
+ self.encoding = encoding
124
+ self.decode_error = decode_error
125
+ self.strip_accents = strip_accents
126
+ self.preprocessor = preprocessor
127
+ self.tokenizer = tokenizer
128
+ self.analyzer = analyzer
129
+ self.lowercase = lowercase
130
+ self.token_pattern = token_pattern
131
+ self.stop_words = stop_words
132
+ self.max_df = max_df
133
+ self.min_df = min_df
134
+ self.max_features = max_features
135
+ self.ngram_range = ngram_range
136
+ self.vocabulary = vocabulary
137
+ self.binary = binary
138
+ self.dtype = dtype
139
+
140
+
141
+ class Pipeline(BaseEstimator):
142
+ def __init__(self, steps, memory=None):
143
+ self.steps = steps
144
+ self.memory = memory
145
+
146
+
147
+ class SVC(BaseEstimator):
148
+ def __init__(
149
+ self,
150
+ C=1.0,
151
+ kernel="rbf",
152
+ degree=3,
153
+ gamma="auto_deprecated",
154
+ coef0=0.0,
155
+ shrinking=True,
156
+ probability=False,
157
+ tol=1e-3,
158
+ cache_size=200,
159
+ class_weight=None,
160
+ verbose=False,
161
+ max_iter=-1,
162
+ decision_function_shape="ovr",
163
+ random_state=None,
164
+ ):
165
+ self.kernel = kernel
166
+ self.degree = degree
167
+ self.gamma = gamma
168
+ self.coef0 = coef0
169
+ self.tol = tol
170
+ self.C = C
171
+ self.shrinking = shrinking
172
+ self.probability = probability
173
+ self.cache_size = cache_size
174
+ self.class_weight = class_weight
175
+ self.verbose = verbose
176
+ self.max_iter = max_iter
177
+ self.decision_function_shape = decision_function_shape
178
+ self.random_state = random_state
179
+
180
+
181
+ class PCA(BaseEstimator):
182
+ def __init__(
183
+ self,
184
+ n_components=None,
185
+ copy=True,
186
+ whiten=False,
187
+ svd_solver="auto",
188
+ tol=0.0,
189
+ iterated_power="auto",
190
+ random_state=None,
191
+ ):
192
+ self.n_components = n_components
193
+ self.copy = copy
194
+ self.whiten = whiten
195
+ self.svd_solver = svd_solver
196
+ self.tol = tol
197
+ self.iterated_power = iterated_power
198
+ self.random_state = random_state
199
+
200
+
201
+ class NMF(BaseEstimator):
202
+ def __init__(
203
+ self,
204
+ n_components=None,
205
+ init=None,
206
+ solver="cd",
207
+ beta_loss="frobenius",
208
+ tol=1e-4,
209
+ max_iter=200,
210
+ random_state=None,
211
+ alpha=0.0,
212
+ l1_ratio=0.0,
213
+ verbose=0,
214
+ shuffle=False,
215
+ ):
216
+ self.n_components = n_components
217
+ self.init = init
218
+ self.solver = solver
219
+ self.beta_loss = beta_loss
220
+ self.tol = tol
221
+ self.max_iter = max_iter
222
+ self.random_state = random_state
223
+ self.alpha = alpha
224
+ self.l1_ratio = l1_ratio
225
+ self.verbose = verbose
226
+ self.shuffle = shuffle
227
+
228
+
229
+ class SimpleImputer(BaseEstimator):
230
+ def __init__(
231
+ self,
232
+ missing_values=np.nan,
233
+ strategy="mean",
234
+ fill_value=None,
235
+ verbose=0,
236
+ copy=True,
237
+ ):
238
+ self.missing_values = missing_values
239
+ self.strategy = strategy
240
+ self.fill_value = fill_value
241
+ self.verbose = verbose
242
+ self.copy = copy
243
+
244
+
245
+ def test_basic(print_changed_only_false):
246
+ # Basic pprint test
247
+ lr = LogisticRegression()
248
+ expected = """
249
+ LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
250
+ intercept_scaling=1, l1_ratio=None, max_iter=100,
251
+ multi_class='warn', n_jobs=None, penalty='l2',
252
+ random_state=None, solver='warn', tol=0.0001, verbose=0,
253
+ warm_start=False)"""
254
+
255
+ expected = expected[1:] # remove first \n
256
+ assert lr.__repr__() == expected
257
+
258
+
259
+ def test_changed_only():
260
+ # Make sure the changed_only param is correctly used when True (default)
261
+ lr = LogisticRegression(C=99)
262
+ expected = """LogisticRegression(C=99)"""
263
+ assert lr.__repr__() == expected
264
+
265
+ # Check with a repr that doesn't fit on a single line
266
+ lr = LogisticRegression(
267
+ C=99, class_weight=0.4, fit_intercept=False, tol=1234, verbose=True
268
+ )
269
+ expected = """
270
+ LogisticRegression(C=99, class_weight=0.4, fit_intercept=False, tol=1234,
271
+ verbose=True)"""
272
+ expected = expected[1:] # remove first \n
273
+ assert lr.__repr__() == expected
274
+
275
+ imputer = SimpleImputer(missing_values=0)
276
+ expected = """SimpleImputer(missing_values=0)"""
277
+ assert imputer.__repr__() == expected
278
+
279
+ # Defaults to np.nan, trying with float('NaN')
280
+ imputer = SimpleImputer(missing_values=float("NaN"))
281
+ expected = """SimpleImputer()"""
282
+ assert imputer.__repr__() == expected
283
+
284
+ # make sure array parameters don't throw error (see #13583)
285
+ repr(LogisticRegressionCV(Cs=np.array([0.1, 1])))
286
+
287
+
288
+ def test_pipeline(print_changed_only_false):
289
+ # Render a pipeline object
290
+ pipeline = make_pipeline(StandardScaler(), LogisticRegression(C=999))
291
+ expected = """
292
+ Pipeline(memory=None,
293
+ steps=[('standardscaler',
294
+ StandardScaler(copy=True, with_mean=True, with_std=True)),
295
+ ('logisticregression',
296
+ LogisticRegression(C=999, class_weight=None, dual=False,
297
+ fit_intercept=True, intercept_scaling=1,
298
+ l1_ratio=None, max_iter=100,
299
+ multi_class='warn', n_jobs=None,
300
+ penalty='l2', random_state=None,
301
+ solver='warn', tol=0.0001, verbose=0,
302
+ warm_start=False))],
303
+ transform_input=None, verbose=False)"""
304
+
305
+ expected = expected[1:] # remove first \n
306
+ assert pipeline.__repr__() == expected
307
+
308
+
309
+ def test_deeply_nested(print_changed_only_false):
310
+ # Render a deeply nested estimator
311
+ rfe = RFE(RFE(RFE(RFE(RFE(RFE(RFE(LogisticRegression())))))))
312
+ expected = """
313
+ RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=RFE(estimator=LogisticRegression(C=1.0,
314
+ class_weight=None,
315
+ dual=False,
316
+ fit_intercept=True,
317
+ intercept_scaling=1,
318
+ l1_ratio=None,
319
+ max_iter=100,
320
+ multi_class='warn',
321
+ n_jobs=None,
322
+ penalty='l2',
323
+ random_state=None,
324
+ solver='warn',
325
+ tol=0.0001,
326
+ verbose=0,
327
+ warm_start=False),
328
+ n_features_to_select=None,
329
+ step=1,
330
+ verbose=0),
331
+ n_features_to_select=None,
332
+ step=1,
333
+ verbose=0),
334
+ n_features_to_select=None,
335
+ step=1, verbose=0),
336
+ n_features_to_select=None, step=1,
337
+ verbose=0),
338
+ n_features_to_select=None, step=1, verbose=0),
339
+ n_features_to_select=None, step=1, verbose=0),
340
+ n_features_to_select=None, step=1, verbose=0)"""
341
+
342
+ expected = expected[1:] # remove first \n
343
+ assert rfe.__repr__() == expected
344
+
345
+
346
+ @pytest.mark.parametrize(
347
+ ("print_changed_only", "expected"),
348
+ [
349
+ (True, "RFE(estimator=RFE(...))"),
350
+ (
351
+ False,
352
+ "RFE(estimator=RFE(...), n_features_to_select=None, step=1, verbose=0)",
353
+ ),
354
+ ],
355
+ )
356
+ def test_print_estimator_max_depth(print_changed_only, expected):
357
+ with config_context(print_changed_only=print_changed_only):
358
+ pp = _EstimatorPrettyPrinter(depth=1)
359
+
360
+ rfe = RFE(RFE(RFE(RFE(RFE(LogisticRegression())))))
361
+ assert pp.pformat(rfe) == expected
362
+
363
+
364
+ def test_gridsearch(print_changed_only_false):
365
+ # render a gridsearch
366
+ param_grid = [
367
+ {"kernel": ["rbf"], "gamma": [1e-3, 1e-4], "C": [1, 10, 100, 1000]},
368
+ {"kernel": ["linear"], "C": [1, 10, 100, 1000]},
369
+ ]
370
+ gs = GridSearchCV(SVC(), param_grid, cv=5)
371
+
372
+ expected = """
373
+ GridSearchCV(cv=5, error_score='raise-deprecating',
374
+ estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
375
+ decision_function_shape='ovr', degree=3,
376
+ gamma='auto_deprecated', kernel='rbf', max_iter=-1,
377
+ probability=False, random_state=None, shrinking=True,
378
+ tol=0.001, verbose=False),
379
+ iid='warn', n_jobs=None,
380
+ param_grid=[{'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001],
381
+ 'kernel': ['rbf']},
382
+ {'C': [1, 10, 100, 1000], 'kernel': ['linear']}],
383
+ pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
384
+ scoring=None, verbose=0)"""
385
+
386
+ expected = expected[1:] # remove first \n
387
+ assert gs.__repr__() == expected
388
+
389
+
390
+ def test_gridsearch_pipeline(print_changed_only_false):
391
+ # render a pipeline inside a gridsearch
392
+ pp = _EstimatorPrettyPrinter(compact=True, indent=1, indent_at_name=True)
393
+
394
+ pipeline = Pipeline([("reduce_dim", PCA()), ("classify", SVC())])
395
+ N_FEATURES_OPTIONS = [2, 4, 8]
396
+ C_OPTIONS = [1, 10, 100, 1000]
397
+ param_grid = [
398
+ {
399
+ "reduce_dim": [PCA(iterated_power=7), NMF()],
400
+ "reduce_dim__n_components": N_FEATURES_OPTIONS,
401
+ "classify__C": C_OPTIONS,
402
+ },
403
+ {
404
+ "reduce_dim": [SelectKBest(chi2)],
405
+ "reduce_dim__k": N_FEATURES_OPTIONS,
406
+ "classify__C": C_OPTIONS,
407
+ },
408
+ ]
409
+ gspipline = GridSearchCV(pipeline, cv=3, n_jobs=1, param_grid=param_grid)
410
+ expected = """
411
+ GridSearchCV(cv=3, error_score='raise-deprecating',
412
+ estimator=Pipeline(memory=None,
413
+ steps=[('reduce_dim',
414
+ PCA(copy=True, iterated_power='auto',
415
+ n_components=None,
416
+ random_state=None,
417
+ svd_solver='auto', tol=0.0,
418
+ whiten=False)),
419
+ ('classify',
420
+ SVC(C=1.0, cache_size=200,
421
+ class_weight=None, coef0=0.0,
422
+ decision_function_shape='ovr',
423
+ degree=3, gamma='auto_deprecated',
424
+ kernel='rbf', max_iter=-1,
425
+ probability=False,
426
+ random_state=None, shrinking=True,
427
+ tol=0.001, verbose=False))]),
428
+ iid='warn', n_jobs=1,
429
+ param_grid=[{'classify__C': [1, 10, 100, 1000],
430
+ 'reduce_dim': [PCA(copy=True, iterated_power=7,
431
+ n_components=None,
432
+ random_state=None,
433
+ svd_solver='auto', tol=0.0,
434
+ whiten=False),
435
+ NMF(alpha=0.0, beta_loss='frobenius',
436
+ init=None, l1_ratio=0.0,
437
+ max_iter=200, n_components=None,
438
+ random_state=None, shuffle=False,
439
+ solver='cd', tol=0.0001,
440
+ verbose=0)],
441
+ 'reduce_dim__n_components': [2, 4, 8]},
442
+ {'classify__C': [1, 10, 100, 1000],
443
+ 'reduce_dim': [SelectKBest(k=10,
444
+ score_func=<function chi2 at some_address>)],
445
+ 'reduce_dim__k': [2, 4, 8]}],
446
+ pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
447
+ scoring=None, verbose=0)""" # noqa: E501
448
+
449
+ expected = expected[1:] # remove first \n
450
+ repr_ = pp.pformat(gspipline)
451
+ # Remove address of '<function chi2 at 0x.....>' for reproducibility
452
+ repr_ = re.sub("function chi2 at 0x.*>", "function chi2 at some_address>", repr_)
453
+ assert repr_ == expected
454
+
455
+
456
+ def test_n_max_elements_to_show(print_changed_only_false):
457
+ n_max_elements_to_show = 30
458
+ pp = _EstimatorPrettyPrinter(
459
+ compact=True,
460
+ indent=1,
461
+ indent_at_name=True,
462
+ n_max_elements_to_show=n_max_elements_to_show,
463
+ )
464
+
465
+ # No ellipsis
466
+ vocabulary = {i: i for i in range(n_max_elements_to_show)}
467
+ vectorizer = CountVectorizer(vocabulary=vocabulary)
468
+
469
+ expected = r"""
470
+ CountVectorizer(analyzer='word', binary=False, decode_error='strict',
471
+ dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
472
+ lowercase=True, max_df=1.0, max_features=None, min_df=1,
473
+ ngram_range=(1, 1), preprocessor=None, stop_words=None,
474
+ strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',
475
+ tokenizer=None,
476
+ vocabulary={0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7,
477
+ 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14,
478
+ 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20,
479
+ 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26,
480
+ 27: 27, 28: 28, 29: 29})"""
481
+
482
+ expected = expected[1:] # remove first \n
483
+ assert pp.pformat(vectorizer) == expected
484
+
485
+ # Now with ellipsis
486
+ vocabulary = {i: i for i in range(n_max_elements_to_show + 1)}
487
+ vectorizer = CountVectorizer(vocabulary=vocabulary)
488
+
489
+ expected = r"""
490
+ CountVectorizer(analyzer='word', binary=False, decode_error='strict',
491
+ dtype=<class 'numpy.int64'>, encoding='utf-8', input='content',
492
+ lowercase=True, max_df=1.0, max_features=None, min_df=1,
493
+ ngram_range=(1, 1), preprocessor=None, stop_words=None,
494
+ strip_accents=None, token_pattern='(?u)\\b\\w\\w+\\b',
495
+ tokenizer=None,
496
+ vocabulary={0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7,
497
+ 8: 8, 9: 9, 10: 10, 11: 11, 12: 12, 13: 13, 14: 14,
498
+ 15: 15, 16: 16, 17: 17, 18: 18, 19: 19, 20: 20,
499
+ 21: 21, 22: 22, 23: 23, 24: 24, 25: 25, 26: 26,
500
+ 27: 27, 28: 28, 29: 29, ...})"""
501
+
502
+ expected = expected[1:] # remove first \n
503
+ assert pp.pformat(vectorizer) == expected
504
+
505
+ # Also test with lists
506
+ param_grid = {"C": list(range(n_max_elements_to_show))}
507
+ gs = GridSearchCV(SVC(), param_grid)
508
+ expected = """
509
+ GridSearchCV(cv='warn', error_score='raise-deprecating',
510
+ estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
511
+ decision_function_shape='ovr', degree=3,
512
+ gamma='auto_deprecated', kernel='rbf', max_iter=-1,
513
+ probability=False, random_state=None, shrinking=True,
514
+ tol=0.001, verbose=False),
515
+ iid='warn', n_jobs=None,
516
+ param_grid={'C': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
517
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
518
+ 27, 28, 29]},
519
+ pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
520
+ scoring=None, verbose=0)"""
521
+
522
+ expected = expected[1:] # remove first \n
523
+ assert pp.pformat(gs) == expected
524
+
525
+ # Now with ellipsis
526
+ param_grid = {"C": list(range(n_max_elements_to_show + 1))}
527
+ gs = GridSearchCV(SVC(), param_grid)
528
+ expected = """
529
+ GridSearchCV(cv='warn', error_score='raise-deprecating',
530
+ estimator=SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
531
+ decision_function_shape='ovr', degree=3,
532
+ gamma='auto_deprecated', kernel='rbf', max_iter=-1,
533
+ probability=False, random_state=None, shrinking=True,
534
+ tol=0.001, verbose=False),
535
+ iid='warn', n_jobs=None,
536
+ param_grid={'C': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
537
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
538
+ 27, 28, 29, ...]},
539
+ pre_dispatch='2*n_jobs', refit=True, return_train_score=False,
540
+ scoring=None, verbose=0)"""
541
+
542
+ expected = expected[1:] # remove first \n
543
+ assert pp.pformat(gs) == expected
544
+
545
+
546
+ def test_bruteforce_ellipsis(print_changed_only_false):
547
+ # Check that the bruteforce ellipsis (used when the number of non-blank
548
+ # characters exceeds N_CHAR_MAX) renders correctly.
549
+
550
+ lr = LogisticRegression()
551
+
552
+ # test when the left and right side of the ellipsis aren't on the same
553
+ # line.
554
+ expected = """
555
+ LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
556
+ in...
557
+ multi_class='warn', n_jobs=None, penalty='l2',
558
+ random_state=None, solver='warn', tol=0.0001, verbose=0,
559
+ warm_start=False)"""
560
+
561
+ expected = expected[1:] # remove first \n
562
+ assert expected == lr.__repr__(N_CHAR_MAX=150)
563
+
564
+ # test with very small N_CHAR_MAX
565
+ # Note that N_CHAR_MAX is not strictly enforced, but it's normal: to avoid
566
+ # weird reprs we still keep the whole line of the right part (after the
567
+ # ellipsis).
568
+ expected = """
569
+ Lo...
570
+ warm_start=False)"""
571
+
572
+ expected = expected[1:] # remove first \n
573
+ assert expected == lr.__repr__(N_CHAR_MAX=4)
574
+
575
+ # test with N_CHAR_MAX == number of non-blank characters: In this case we
576
+ # don't want ellipsis
577
+ full_repr = lr.__repr__(N_CHAR_MAX=float("inf"))
578
+ n_nonblank = len("".join(full_repr.split()))
579
+ assert lr.__repr__(N_CHAR_MAX=n_nonblank) == full_repr
580
+ assert "..." not in full_repr
581
+
582
+ # test with N_CHAR_MAX == number of non-blank characters - 10: the left and
583
+ # right side of the ellispsis are on different lines. In this case we
584
+ # want to expend the whole line of the right side
585
+ expected = """
586
+ LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
587
+ intercept_scaling=1, l1_ratio=None, max_i...
588
+ multi_class='warn', n_jobs=None, penalty='l2',
589
+ random_state=None, solver='warn', tol=0.0001, verbose=0,
590
+ warm_start=False)"""
591
+ expected = expected[1:] # remove first \n
592
+ assert expected == lr.__repr__(N_CHAR_MAX=n_nonblank - 10)
593
+
594
+ # test with N_CHAR_MAX == number of non-blank characters - 10: the left and
595
+ # right side of the ellispsis are on the same line. In this case we don't
596
+ # want to expend the whole line of the right side, just add the ellispsis
597
+ # between the 2 sides.
598
+ expected = """
599
+ LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
600
+ intercept_scaling=1, l1_ratio=None, max_iter...,
601
+ multi_class='warn', n_jobs=None, penalty='l2',
602
+ random_state=None, solver='warn', tol=0.0001, verbose=0,
603
+ warm_start=False)"""
604
+ expected = expected[1:] # remove first \n
605
+ assert expected == lr.__repr__(N_CHAR_MAX=n_nonblank - 4)
606
+
607
+ # test with N_CHAR_MAX == number of non-blank characters - 2: the left and
608
+ # right side of the ellispsis are on the same line, but adding the ellipsis
609
+ # would actually make the repr longer. So we don't add the ellipsis.
610
+ expected = """
611
+ LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
612
+ intercept_scaling=1, l1_ratio=None, max_iter=100,
613
+ multi_class='warn', n_jobs=None, penalty='l2',
614
+ random_state=None, solver='warn', tol=0.0001, verbose=0,
615
+ warm_start=False)"""
616
+ expected = expected[1:] # remove first \n
617
+ assert expected == lr.__repr__(N_CHAR_MAX=n_nonblank - 2)
618
+
619
+
620
+ def test_builtin_prettyprinter():
621
+ # non regression test than ensures we can still use the builtin
622
+ # PrettyPrinter class for estimators (as done e.g. by joblib).
623
+ # Used to be a bug
624
+
625
+ PrettyPrinter().pprint(LogisticRegression())
626
+
627
+
628
+ def test_kwargs_in_init():
629
+ # Make sure the changed_only=True mode is OK when an argument is passed as
630
+ # kwargs.
631
+ # Non-regression test for
632
+ # https://github.com/scikit-learn/scikit-learn/issues/17206
633
+
634
+ class WithKWargs(BaseEstimator):
635
+ # Estimator with a kwargs argument. These need to hack around
636
+ # set_params and get_params. Here we mimic what LightGBM does.
637
+ def __init__(self, a="willchange", b="unchanged", **kwargs):
638
+ self.a = a
639
+ self.b = b
640
+ self._other_params = {}
641
+ self.set_params(**kwargs)
642
+
643
+ def get_params(self, deep=True):
644
+ params = super().get_params(deep=deep)
645
+ params.update(self._other_params)
646
+ return params
647
+
648
+ def set_params(self, **params):
649
+ for key, value in params.items():
650
+ setattr(self, key, value)
651
+ self._other_params[key] = value
652
+ return self
653
+
654
+ est = WithKWargs(a="something", c="abcd", d=None)
655
+
656
+ expected = "WithKWargs(a='something', c='abcd', d=None)"
657
+ assert expected == est.__repr__()
658
+
659
+ with config_context(print_changed_only=False):
660
+ expected = "WithKWargs(a='something', b='unchanged', c='abcd', d=None)"
661
+ assert expected == est.__repr__()
662
+
663
+
664
+ def test_complexity_print_changed_only():
665
+ # Make sure `__repr__` is called the same amount of times
666
+ # whether `print_changed_only` is True or False
667
+ # Non-regression test for
668
+ # https://github.com/scikit-learn/scikit-learn/issues/18490
669
+
670
+ class DummyEstimator(TransformerMixin, BaseEstimator):
671
+ nb_times_repr_called = 0
672
+
673
+ def __init__(self, estimator=None):
674
+ self.estimator = estimator
675
+
676
+ def __repr__(self):
677
+ DummyEstimator.nb_times_repr_called += 1
678
+ return super().__repr__()
679
+
680
+ def transform(self, X, copy=None): # pragma: no cover
681
+ return X
682
+
683
+ estimator = DummyEstimator(
684
+ make_pipeline(DummyEstimator(DummyEstimator()), DummyEstimator(), "passthrough")
685
+ )
686
+ with config_context(print_changed_only=False):
687
+ repr(estimator)
688
+ nb_repr_print_changed_only_false = DummyEstimator.nb_times_repr_called
689
+
690
+ DummyEstimator.nb_times_repr_called = 0
691
+ with config_context(print_changed_only=True):
692
+ repr(estimator)
693
+ nb_repr_print_changed_only_true = DummyEstimator.nb_times_repr_called
694
+
695
+ assert nb_repr_print_changed_only_false == nb_repr_print_changed_only_true
shared/package-files/06/061232ee06f86f807af33de374eda5936133334c56c62c9a55ef1210e45700e1/margins.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Margin implementations for a :class:`~prompt_toolkit.layout.containers.Window`.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ from abc import ABCMeta, abstractmethod
7
+ from typing import TYPE_CHECKING, Callable
8
+
9
+ from prompt_toolkit.filters import FilterOrBool, to_filter
10
+ from prompt_toolkit.formatted_text import (
11
+ StyleAndTextTuples,
12
+ fragment_list_to_text,
13
+ to_formatted_text,
14
+ )
15
+ from prompt_toolkit.utils import get_cwidth
16
+
17
+ from .controls import UIContent
18
+
19
+ if TYPE_CHECKING:
20
+ from .containers import WindowRenderInfo
21
+
22
+ __all__ = [
23
+ "Margin",
24
+ "NumberedMargin",
25
+ "ScrollbarMargin",
26
+ "ConditionalMargin",
27
+ "PromptMargin",
28
+ ]
29
+
30
+
31
+ class Margin(metaclass=ABCMeta):
32
+ """
33
+ Base interface for a margin.
34
+ """
35
+
36
+ @abstractmethod
37
+ def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
38
+ """
39
+ Return the width that this margin is going to consume.
40
+
41
+ :param get_ui_content: Callable that asks the user control to create
42
+ a :class:`.UIContent` instance. This can be used for instance to
43
+ obtain the number of lines.
44
+ """
45
+ return 0
46
+
47
+ @abstractmethod
48
+ def create_margin(
49
+ self, window_render_info: WindowRenderInfo, width: int, height: int
50
+ ) -> StyleAndTextTuples:
51
+ """
52
+ Creates a margin.
53
+ This should return a list of (style_str, text) tuples.
54
+
55
+ :param window_render_info:
56
+ :class:`~prompt_toolkit.layout.containers.WindowRenderInfo`
57
+ instance, generated after rendering and copying the visible part of
58
+ the :class:`~prompt_toolkit.layout.controls.UIControl` into the
59
+ :class:`~prompt_toolkit.layout.containers.Window`.
60
+ :param width: The width that's available for this margin. (As reported
61
+ by :meth:`.get_width`.)
62
+ :param height: The height that's available for this margin. (The height
63
+ of the :class:`~prompt_toolkit.layout.containers.Window`.)
64
+ """
65
+ return []
66
+
67
+
68
+ class NumberedMargin(Margin):
69
+ """
70
+ Margin that displays the line numbers.
71
+
72
+ :param relative: Number relative to the cursor position. Similar to the Vi
73
+ 'relativenumber' option.
74
+ :param display_tildes: Display tildes after the end of the document, just
75
+ like Vi does.
76
+ """
77
+
78
+ def __init__(
79
+ self, relative: FilterOrBool = False, display_tildes: FilterOrBool = False
80
+ ) -> None:
81
+ self.relative = to_filter(relative)
82
+ self.display_tildes = to_filter(display_tildes)
83
+
84
+ def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
85
+ line_count = get_ui_content().line_count
86
+ return max(3, len("%s" % line_count) + 1)
87
+
88
+ def create_margin(
89
+ self, window_render_info: WindowRenderInfo, width: int, height: int
90
+ ) -> StyleAndTextTuples:
91
+ relative = self.relative()
92
+
93
+ style = "class:line-number"
94
+ style_current = "class:line-number.current"
95
+
96
+ # Get current line number.
97
+ current_lineno = window_render_info.ui_content.cursor_position.y
98
+
99
+ # Construct margin.
100
+ result: StyleAndTextTuples = []
101
+ last_lineno = None
102
+
103
+ for y, lineno in enumerate(window_render_info.displayed_lines):
104
+ # Only display line number if this line is not a continuation of the previous line.
105
+ if lineno != last_lineno:
106
+ if lineno is None:
107
+ pass
108
+ elif lineno == current_lineno:
109
+ # Current line.
110
+ if relative:
111
+ # Left align current number in relative mode.
112
+ result.append((style_current, "%i" % (lineno + 1)))
113
+ else:
114
+ result.append(
115
+ (style_current, ("%i " % (lineno + 1)).rjust(width))
116
+ )
117
+ else:
118
+ # Other lines.
119
+ if relative:
120
+ lineno = abs(lineno - current_lineno) - 1
121
+
122
+ result.append((style, ("%i " % (lineno + 1)).rjust(width)))
123
+
124
+ last_lineno = lineno
125
+ result.append(("", "\n"))
126
+
127
+ # Fill with tildes.
128
+ if self.display_tildes():
129
+ while y < window_render_info.window_height:
130
+ result.append(("class:tilde", "~\n"))
131
+ y += 1
132
+
133
+ return result
134
+
135
+
136
+ class ConditionalMargin(Margin):
137
+ """
138
+ Wrapper around other :class:`.Margin` classes to show/hide them.
139
+ """
140
+
141
+ def __init__(self, margin: Margin, filter: FilterOrBool) -> None:
142
+ self.margin = margin
143
+ self.filter = to_filter(filter)
144
+
145
+ def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
146
+ if self.filter():
147
+ return self.margin.get_width(get_ui_content)
148
+ else:
149
+ return 0
150
+
151
+ def create_margin(
152
+ self, window_render_info: WindowRenderInfo, width: int, height: int
153
+ ) -> StyleAndTextTuples:
154
+ if width and self.filter():
155
+ return self.margin.create_margin(window_render_info, width, height)
156
+ else:
157
+ return []
158
+
159
+
160
+ class ScrollbarMargin(Margin):
161
+ """
162
+ Margin displaying a scrollbar.
163
+
164
+ :param display_arrows: Display scroll up/down arrows.
165
+ """
166
+
167
+ def __init__(
168
+ self,
169
+ display_arrows: FilterOrBool = False,
170
+ up_arrow_symbol: str = "^",
171
+ down_arrow_symbol: str = "v",
172
+ ) -> None:
173
+ self.display_arrows = to_filter(display_arrows)
174
+ self.up_arrow_symbol = up_arrow_symbol
175
+ self.down_arrow_symbol = down_arrow_symbol
176
+
177
+ def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
178
+ return 1
179
+
180
+ def create_margin(
181
+ self, window_render_info: WindowRenderInfo, width: int, height: int
182
+ ) -> StyleAndTextTuples:
183
+ content_height = window_render_info.content_height
184
+ window_height = window_render_info.window_height
185
+ display_arrows = self.display_arrows()
186
+
187
+ if display_arrows:
188
+ window_height -= 2
189
+
190
+ try:
191
+ fraction_visible = len(window_render_info.displayed_lines) / float(
192
+ content_height
193
+ )
194
+ fraction_above = window_render_info.vertical_scroll / float(content_height)
195
+
196
+ scrollbar_height = int(
197
+ min(window_height, max(1, window_height * fraction_visible))
198
+ )
199
+ scrollbar_top = int(window_height * fraction_above)
200
+ except ZeroDivisionError:
201
+ return []
202
+ else:
203
+
204
+ def is_scroll_button(row: int) -> bool:
205
+ "True if we should display a button on this row."
206
+ return scrollbar_top <= row <= scrollbar_top + scrollbar_height
207
+
208
+ # Up arrow.
209
+ result: StyleAndTextTuples = []
210
+ if display_arrows:
211
+ result.extend(
212
+ [
213
+ ("class:scrollbar.arrow", self.up_arrow_symbol),
214
+ ("class:scrollbar", "\n"),
215
+ ]
216
+ )
217
+
218
+ # Scrollbar body.
219
+ scrollbar_background = "class:scrollbar.background"
220
+ scrollbar_background_start = "class:scrollbar.background,scrollbar.start"
221
+ scrollbar_button = "class:scrollbar.button"
222
+ scrollbar_button_end = "class:scrollbar.button,scrollbar.end"
223
+
224
+ for i in range(window_height):
225
+ if is_scroll_button(i):
226
+ if not is_scroll_button(i + 1):
227
+ # Give the last cell a different style, because we
228
+ # want to underline this.
229
+ result.append((scrollbar_button_end, " "))
230
+ else:
231
+ result.append((scrollbar_button, " "))
232
+ else:
233
+ if is_scroll_button(i + 1):
234
+ result.append((scrollbar_background_start, " "))
235
+ else:
236
+ result.append((scrollbar_background, " "))
237
+ result.append(("", "\n"))
238
+
239
+ # Down arrow
240
+ if display_arrows:
241
+ result.append(("class:scrollbar.arrow", self.down_arrow_symbol))
242
+
243
+ return result
244
+
245
+
246
+ class PromptMargin(Margin):
247
+ """
248
+ [Deprecated]
249
+
250
+ Create margin that displays a prompt.
251
+ This can display one prompt at the first line, and a continuation prompt
252
+ (e.g, just dots) on all the following lines.
253
+
254
+ This `PromptMargin` implementation has been largely superseded in favor of
255
+ the `get_line_prefix` attribute of `Window`. The reason is that a margin is
256
+ always a fixed width, while `get_line_prefix` can return a variable width
257
+ prefix in front of every line, making it more powerful, especially for line
258
+ continuations.
259
+
260
+ :param get_prompt: Callable returns formatted text or a list of
261
+ `(style_str, type)` tuples to be shown as the prompt at the first line.
262
+ :param get_continuation: Callable that takes three inputs. The width (int),
263
+ line_number (int), and is_soft_wrap (bool). It should return formatted
264
+ text or a list of `(style_str, type)` tuples for the next lines of the
265
+ input.
266
+ """
267
+
268
+ def __init__(
269
+ self,
270
+ get_prompt: Callable[[], StyleAndTextTuples],
271
+ get_continuation: None
272
+ | (Callable[[int, int, bool], StyleAndTextTuples]) = None,
273
+ ) -> None:
274
+ self.get_prompt = get_prompt
275
+ self.get_continuation = get_continuation
276
+
277
+ def get_width(self, get_ui_content: Callable[[], UIContent]) -> int:
278
+ "Width to report to the `Window`."
279
+ # Take the width from the first line.
280
+ text = fragment_list_to_text(self.get_prompt())
281
+ return get_cwidth(text)
282
+
283
+ def create_margin(
284
+ self, window_render_info: WindowRenderInfo, width: int, height: int
285
+ ) -> StyleAndTextTuples:
286
+ get_continuation = self.get_continuation
287
+ result: StyleAndTextTuples = []
288
+
289
+ # First line.
290
+ result.extend(to_formatted_text(self.get_prompt()))
291
+
292
+ # Next lines.
293
+ if get_continuation:
294
+ last_y = None
295
+
296
+ for y in window_render_info.displayed_lines[1:]:
297
+ result.append(("", "\n"))
298
+ result.extend(
299
+ to_formatted_text(get_continuation(width, y, y == last_y))
300
+ )
301
+ last_y = y
302
+
303
+ return result
shared/package-files/06/062d1e165712e78effcbd8e10b8a59ae62e450a7c87083589230eaeef659dab4/qnxw ADDED
Binary file (1.46 kB). View file
 
shared/package-files/06/069ed4c1f7c830eee873c527155d75c9819c5d48d26b4361b2e3a041a35132df/test_rv.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.concrete.summations import Sum
2
+ from sympy.core.basic import Basic
3
+ from sympy.core.containers import Tuple
4
+ from sympy.core.function import Lambda
5
+ from sympy.core.numbers import (Rational, nan, oo, pi)
6
+ from sympy.core.relational import Eq
7
+ from sympy.core.singleton import S
8
+ from sympy.core.symbol import (Symbol, symbols)
9
+ from sympy.functions.combinatorial.factorials import (FallingFactorial, binomial)
10
+ from sympy.functions.elementary.exponential import (exp, log)
11
+ from sympy.functions.elementary.trigonometric import (cos, sin)
12
+ from sympy.functions.special.delta_functions import DiracDelta
13
+ from sympy.integrals.integrals import integrate
14
+ from sympy.logic.boolalg import (And, Or)
15
+ from sympy.matrices.dense import Matrix
16
+ from sympy.sets.sets import Interval
17
+ from sympy.tensor.indexed import Indexed
18
+ from sympy.stats import (Die, Normal, Exponential, FiniteRV, P, E, H, variance,
19
+ density, given, independent, dependent, where, pspace, GaussianUnitaryEnsemble,
20
+ random_symbols, sample, Geometric, factorial_moment, Binomial, Hypergeometric,
21
+ DiscreteUniform, Poisson, characteristic_function, moment_generating_function,
22
+ BernoulliProcess, Variance, Expectation, Probability, Covariance, covariance, cmoment,
23
+ moment, median)
24
+ from sympy.stats.rv import (IndependentProductPSpace, rs_swap, Density, NamedArgsMixin,
25
+ RandomSymbol, sample_iter, PSpace, is_random, RandomIndexedSymbol, RandomMatrixSymbol)
26
+ from sympy.testing.pytest import raises, skip, XFAIL, warns_deprecated_sympy
27
+ from sympy.external import import_module
28
+ from sympy.core.numbers import comp
29
+ from sympy.stats.frv_types import BernoulliDistribution
30
+ from sympy.core.symbol import Dummy
31
+ from sympy.functions.elementary.piecewise import Piecewise
32
+
33
+ def test_where():
34
+ X, Y = Die('X'), Die('Y')
35
+ Z = Normal('Z', 0, 1)
36
+
37
+ assert where(Z**2 <= 1).set == Interval(-1, 1)
38
+ assert where(Z**2 <= 1).as_boolean() == Interval(-1, 1).as_relational(Z.symbol)
39
+ assert where(And(X > Y, Y > 4)).as_boolean() == And(
40
+ Eq(X.symbol, 6), Eq(Y.symbol, 5))
41
+
42
+ assert len(where(X < 3).set) == 2
43
+ assert 1 in where(X < 3).set
44
+
45
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
46
+ assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1)
47
+ XX = given(X, And(X**2 <= 1, X >= 0))
48
+ assert XX.pspace.domain.set == Interval(0, 1)
49
+ assert XX.pspace.domain.as_boolean() == \
50
+ And(0 <= X.symbol, X.symbol**2 <= 1, -oo < X.symbol, X.symbol < oo)
51
+
52
+ with raises(TypeError):
53
+ XX = given(X, X + 3)
54
+
55
+
56
+ def test_random_symbols():
57
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
58
+
59
+ assert set(random_symbols(2*X + 1)) == {X}
60
+ assert set(random_symbols(2*X + Y)) == {X, Y}
61
+ assert set(random_symbols(2*X + Y.symbol)) == {X}
62
+ assert set(random_symbols(2)) == set()
63
+
64
+
65
+ def test_characteristic_function():
66
+ # Imports I from sympy
67
+ from sympy.core.numbers import I
68
+ X = Normal('X',0,1)
69
+ Y = DiscreteUniform('Y', [1,2,7])
70
+ Z = Poisson('Z', 2)
71
+ t = symbols('_t')
72
+ P = Lambda(t, exp(-t**2/2))
73
+ Q = Lambda(t, exp(7*t*I)/3 + exp(2*t*I)/3 + exp(t*I)/3)
74
+ R = Lambda(t, exp(2 * exp(t*I) - 2))
75
+
76
+
77
+ assert characteristic_function(X).dummy_eq(P)
78
+ assert characteristic_function(Y).dummy_eq(Q)
79
+ assert characteristic_function(Z).dummy_eq(R)
80
+
81
+
82
+ def test_moment_generating_function():
83
+
84
+ X = Normal('X',0,1)
85
+ Y = DiscreteUniform('Y', [1,2,7])
86
+ Z = Poisson('Z', 2)
87
+ t = symbols('_t')
88
+ P = Lambda(t, exp(t**2/2))
89
+ Q = Lambda(t, (exp(7*t)/3 + exp(2*t)/3 + exp(t)/3))
90
+ R = Lambda(t, exp(2 * exp(t) - 2))
91
+
92
+
93
+ assert moment_generating_function(X).dummy_eq(P)
94
+ assert moment_generating_function(Y).dummy_eq(Q)
95
+ assert moment_generating_function(Z).dummy_eq(R)
96
+
97
+ def test_sample_iter():
98
+
99
+ X = Normal('X',0,1)
100
+ Y = DiscreteUniform('Y', [1, 2, 7])
101
+ Z = Poisson('Z', 2)
102
+
103
+ scipy = import_module('scipy')
104
+ if not scipy:
105
+ skip('Scipy is not installed. Abort tests')
106
+ expr = X**2 + 3
107
+ iterator = sample_iter(expr)
108
+
109
+ expr2 = Y**2 + 5*Y + 4
110
+ iterator2 = sample_iter(expr2)
111
+
112
+ expr3 = Z**3 + 4
113
+ iterator3 = sample_iter(expr3)
114
+
115
+ def is_iterator(obj):
116
+ if (
117
+ hasattr(obj, '__iter__') and
118
+ (hasattr(obj, 'next') or
119
+ hasattr(obj, '__next__')) and
120
+ callable(obj.__iter__) and
121
+ obj.__iter__() is obj
122
+ ):
123
+ return True
124
+ else:
125
+ return False
126
+ assert is_iterator(iterator)
127
+ assert is_iterator(iterator2)
128
+ assert is_iterator(iterator3)
129
+
130
+ def test_pspace():
131
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
132
+ x = Symbol('x')
133
+
134
+ raises(ValueError, lambda: pspace(5 + 3))
135
+ raises(ValueError, lambda: pspace(x < 1))
136
+ assert pspace(X) == X.pspace
137
+ assert pspace(2*X + 1) == X.pspace
138
+ assert pspace(2*X + Y) == IndependentProductPSpace(Y.pspace, X.pspace)
139
+
140
+ def test_rs_swap():
141
+ X = Normal('x', 0, 1)
142
+ Y = Exponential('y', 1)
143
+
144
+ XX = Normal('x', 0, 2)
145
+ YY = Normal('y', 0, 3)
146
+
147
+ expr = 2*X + Y
148
+ assert expr.subs(rs_swap((X, Y), (YY, XX))) == 2*XX + YY
149
+
150
+
151
+ def test_RandomSymbol():
152
+
153
+ X = Normal('x', 0, 1)
154
+ Y = Normal('x', 0, 2)
155
+ assert X.symbol == Y.symbol
156
+ assert X != Y
157
+
158
+ assert X.name == X.symbol.name
159
+
160
+ X = Normal('lambda', 0, 1) # make sure we can use protected terms
161
+ X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms
162
+
163
+
164
+ def test_RandomSymbol_diff():
165
+ X = Normal('x', 0, 1)
166
+ assert (2*X).diff(X)
167
+
168
+
169
+ def test_random_symbol_no_pspace():
170
+ x = RandomSymbol(Symbol('x'))
171
+ assert x.pspace == PSpace()
172
+
173
+ def test_overlap():
174
+ X = Normal('x', 0, 1)
175
+ Y = Normal('x', 0, 2)
176
+
177
+ raises(ValueError, lambda: P(X > Y))
178
+
179
+
180
+ def test_IndependentProductPSpace():
181
+ X = Normal('X', 0, 1)
182
+ Y = Normal('Y', 0, 1)
183
+ px = X.pspace
184
+ py = Y.pspace
185
+ assert pspace(X + Y) == IndependentProductPSpace(px, py)
186
+ assert pspace(X + Y) == IndependentProductPSpace(py, px)
187
+
188
+
189
+ def test_E():
190
+ assert E(5) == 5
191
+
192
+
193
+ def test_H():
194
+ X = Normal('X', 0, 1)
195
+ D = Die('D', sides = 4)
196
+ G = Geometric('G', 0.5)
197
+ assert H(X, X > 0) == -log(2)/2 + S.Half + log(pi)/2
198
+ assert H(D, D > 2) == log(2)
199
+ assert comp(H(G).evalf().round(2), 1.39)
200
+
201
+
202
+ def test_Sample():
203
+ X = Die('X', 6)
204
+ Y = Normal('Y', 0, 1)
205
+ z = Symbol('z', integer=True)
206
+
207
+ scipy = import_module('scipy')
208
+ if not scipy:
209
+ skip('Scipy is not installed. Abort tests')
210
+ assert sample(X) in [1, 2, 3, 4, 5, 6]
211
+ assert isinstance(sample(X + Y), float)
212
+
213
+ assert P(X + Y > 0, Y < 0, numsamples=10).is_number
214
+ assert E(X + Y, numsamples=10).is_number
215
+ assert E(X**2 + Y, numsamples=10).is_number
216
+ assert E((X + Y)**2, numsamples=10).is_number
217
+ assert variance(X + Y, numsamples=10).is_number
218
+
219
+ raises(TypeError, lambda: P(Y > z, numsamples=5))
220
+
221
+ assert P(sin(Y) <= 1, numsamples=10) == 1.0
222
+ assert P(sin(Y) <= 1, cos(Y) < 1, numsamples=10) == 1.0
223
+
224
+ assert all(i in range(1, 7) for i in density(X, numsamples=10))
225
+ assert all(i in range(4, 7) for i in density(X, X>3, numsamples=10))
226
+
227
+ numpy = import_module('numpy')
228
+ if not numpy:
229
+ skip('Numpy is not installed. Abort tests')
230
+ #Test Issue #21563: Output of sample must be a float or array
231
+ assert isinstance(sample(X), (numpy.int32, numpy.int64))
232
+ assert isinstance(sample(Y), numpy.float64)
233
+ assert isinstance(sample(X, size=2), numpy.ndarray)
234
+
235
+ with warns_deprecated_sympy():
236
+ sample(X, numsamples=2)
237
+
238
+ @XFAIL
239
+ def test_samplingE():
240
+ scipy = import_module('scipy')
241
+ if not scipy:
242
+ skip('Scipy is not installed. Abort tests')
243
+ Y = Normal('Y', 0, 1)
244
+ z = Symbol('z', integer=True)
245
+ assert E(Sum(1/z**Y, (z, 1, oo)), Y > 2, numsamples=3).is_number
246
+
247
+
248
+ def test_given():
249
+ X = Normal('X', 0, 1)
250
+ Y = Normal('Y', 0, 1)
251
+ A = given(X, True)
252
+ B = given(X, Y > 2)
253
+
254
+ assert X == A == B
255
+
256
+
257
+ def test_factorial_moment():
258
+ X = Poisson('X', 2)
259
+ Y = Binomial('Y', 2, S.Half)
260
+ Z = Hypergeometric('Z', 4, 2, 2)
261
+ assert factorial_moment(X, 2) == 4
262
+ assert factorial_moment(Y, 2) == S.Half
263
+ assert factorial_moment(Z, 2) == Rational(1, 3)
264
+
265
+ x, y, z, l = symbols('x y z l')
266
+ Y = Binomial('Y', 2, y)
267
+ Z = Hypergeometric('Z', 10, 2, 3)
268
+ assert factorial_moment(Y, l) == y**2*FallingFactorial(
269
+ 2, l) + 2*y*(1 - y)*FallingFactorial(1, l) + (1 - y)**2*\
270
+ FallingFactorial(0, l)
271
+ assert factorial_moment(Z, l) == 7*FallingFactorial(0, l)/\
272
+ 15 + 7*FallingFactorial(1, l)/15 + FallingFactorial(2, l)/15
273
+
274
+
275
+ def test_dependence():
276
+ X, Y = Die('X'), Die('Y')
277
+ assert independent(X, 2*Y)
278
+ assert not dependent(X, 2*Y)
279
+
280
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
281
+ assert independent(X, Y)
282
+ assert dependent(X, 2*X)
283
+
284
+ # Create a dependency
285
+ XX, YY = given(Tuple(X, Y), Eq(X + Y, 3))
286
+ assert dependent(XX, YY)
287
+
288
+ def test_dependent_finite():
289
+ X, Y = Die('X'), Die('Y')
290
+ # Dependence testing requires symbolic conditions which currently break
291
+ # finite random variables
292
+ assert dependent(X, Y + X)
293
+
294
+ XX, YY = given(Tuple(X, Y), X + Y > 5) # Create a dependency
295
+ assert dependent(XX, YY)
296
+
297
+
298
+ def test_normality():
299
+ X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
300
+ x = Symbol('x', real=True)
301
+ z = Symbol('z', real=True)
302
+ dens = density(X - Y, Eq(X + Y, z))
303
+
304
+ assert integrate(dens(x), (x, -oo, oo)) == 1
305
+
306
+
307
+ def test_Density():
308
+ X = Die('X', 6)
309
+ d = Density(X)
310
+ assert d.doit() == density(X)
311
+
312
+ def test_NamedArgsMixin():
313
+ class Foo(Basic, NamedArgsMixin):
314
+ _argnames = 'foo', 'bar'
315
+
316
+ a = Foo(S(1), S(2))
317
+
318
+ assert a.foo == 1
319
+ assert a.bar == 2
320
+
321
+ raises(AttributeError, lambda: a.baz)
322
+
323
+ class Bar(Basic, NamedArgsMixin):
324
+ pass
325
+
326
+ raises(AttributeError, lambda: Bar(S(1), S(2)).foo)
327
+
328
+ def test_density_constant():
329
+ assert density(3)(2) == 0
330
+ assert density(3)(3) == DiracDelta(0)
331
+
332
+ def test_cmoment_constant():
333
+ assert variance(3) == 0
334
+ assert cmoment(3, 3) == 0
335
+ assert cmoment(3, 4) == 0
336
+ x = Symbol('x')
337
+ assert variance(x) == 0
338
+ assert cmoment(x, 15) == 0
339
+ assert cmoment(x, 0) == 1
340
+
341
+ def test_moment_constant():
342
+ assert moment(3, 0) == 1
343
+ assert moment(3, 1) == 3
344
+ assert moment(3, 2) == 9
345
+ x = Symbol('x')
346
+ assert moment(x, 2) == x**2
347
+
348
+ def test_median_constant():
349
+ assert median(3) == 3
350
+ x = Symbol('x')
351
+ assert median(x) == x
352
+
353
+ def test_real():
354
+ x = Normal('x', 0, 1)
355
+ assert x.is_real
356
+
357
+
358
+ def test_issue_10052():
359
+ X = Exponential('X', 3)
360
+ assert P(X < oo) == 1
361
+ assert P(X > oo) == 0
362
+ assert P(X < 2, X > oo) == 0
363
+ assert P(X < oo, X > oo) == 0
364
+ assert P(X < oo, X > 2) == 1
365
+ assert P(X < 3, X == 2) == 0
366
+ raises(ValueError, lambda: P(1))
367
+ raises(ValueError, lambda: P(X < 1, 2))
368
+
369
+ def test_issue_11934():
370
+ density = {0: .5, 1: .5}
371
+ X = FiniteRV('X', density)
372
+ assert E(X) == 0.5
373
+ assert P( X>= 2) == 0
374
+
375
+ def test_issue_8129():
376
+ X = Exponential('X', 4)
377
+ assert P(X >= X) == 1
378
+ assert P(X > X) == 0
379
+ assert P(X > X+1) == 0
380
+
381
+ def test_issue_12237():
382
+ X = Normal('X', 0, 1)
383
+ Y = Normal('Y', 0, 1)
384
+ U = P(X > 0, X)
385
+ V = P(Y < 0, X)
386
+ W = P(X + Y > 0, X)
387
+ assert W == P(X + Y > 0, X)
388
+ assert U == BernoulliDistribution(S.Half, S.Zero, S.One)
389
+ assert V == S.Half
390
+
391
+ def test_is_random():
392
+ X = Normal('X', 0, 1)
393
+ Y = Normal('Y', 0, 1)
394
+ a, b = symbols('a, b')
395
+ G = GaussianUnitaryEnsemble('U', 2)
396
+ B = BernoulliProcess('B', 0.9)
397
+ assert not is_random(a)
398
+ assert not is_random(a + b)
399
+ assert not is_random(a * b)
400
+ assert not is_random(Matrix([a**2, b**2]))
401
+ assert is_random(X)
402
+ assert is_random(X**2 + Y)
403
+ assert is_random(Y + b**2)
404
+ assert is_random(Y > 5)
405
+ assert is_random(B[3] < 1)
406
+ assert is_random(G)
407
+ assert is_random(X * Y * B[1])
408
+ assert is_random(Matrix([[X, B[2]], [G, Y]]))
409
+ assert is_random(Eq(X, 4))
410
+
411
+ def test_issue_12283():
412
+ x = symbols('x')
413
+ X = RandomSymbol(x)
414
+ Y = RandomSymbol('Y')
415
+ Z = RandomMatrixSymbol('Z', 2, 1)
416
+ W = RandomMatrixSymbol('W', 2, 1)
417
+ RI = RandomIndexedSymbol(Indexed('RI', 3))
418
+ assert pspace(Z) == PSpace()
419
+ assert pspace(RI) == PSpace()
420
+ assert pspace(X) == PSpace()
421
+ assert E(X) == Expectation(X)
422
+ assert P(Y > 3) == Probability(Y > 3)
423
+ assert variance(X) == Variance(X)
424
+ assert variance(RI) == Variance(RI)
425
+ assert covariance(X, Y) == Covariance(X, Y)
426
+ assert covariance(W, Z) == Covariance(W, Z)
427
+
428
+ def test_issue_6810():
429
+ X = Die('X', 6)
430
+ Y = Normal('Y', 0, 1)
431
+ assert P(Eq(X, 2)) == S(1)/6
432
+ assert P(Eq(Y, 0)) == 0
433
+ assert P(Or(X > 2, X < 3)) == 1
434
+ assert P(And(X > 3, X > 2)) == S(1)/2
435
+
436
+ def test_issue_20286():
437
+ n, p = symbols('n p')
438
+ B = Binomial('B', n, p)
439
+ k = Dummy('k', integer = True)
440
+ eq = Sum(Piecewise((-p**k*(1 - p)**(-k + n)*log(p**k*(1 - p)**(-k + n)*binomial(n, k))*binomial(n, k), (k >= 0) & (k <= n)), (nan, True)), (k, 0, n))
441
+ assert eq.dummy_eq(H(B))
shared/package-files/06/069f0d6d4cdf0f03e40bf33b01cac2fc3413cce89a528caef3f9c75f4a22ea76/python_ivalue.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/core/ivalue.h>
3
+ #include <pybind11/pybind11.h>
4
+ #include <torch/csrc/jit/python/pybind_utils.h>
5
+ #include <torch/csrc/python_headers.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ namespace py = pybind11;
9
+
10
+ namespace c10::ivalue {
11
+
12
+ // concrete ivalue Holder that hold a py::object
13
+ struct C10_EXPORT ConcretePyObjectHolder final : PyObjectHolder {
14
+ public:
15
+ static c10::intrusive_ptr<PyObjectHolder> create(py::object py_obj) {
16
+ return c10::make_intrusive<ConcretePyObjectHolder>(std::move(py_obj));
17
+ }
18
+
19
+ static c10::intrusive_ptr<PyObjectHolder> create(const py::handle& handle) {
20
+ py::gil_scoped_acquire ag;
21
+ return c10::make_intrusive<ConcretePyObjectHolder>(
22
+ handle.cast<py::object>());
23
+ }
24
+
25
+ PyObject* getPyObject() override {
26
+ return py_obj_.ptr();
27
+ }
28
+
29
+ InferredType tryToInferType() override {
30
+ pybind11::gil_scoped_acquire ag;
31
+ return torch::jit::tryToInferType(py_obj_);
32
+ }
33
+
34
+ IValue toIValue(const TypePtr& type, c10::optional<int32_t> N = c10::nullopt)
35
+ override {
36
+ pybind11::gil_scoped_acquire ag;
37
+ return torch::jit::toIValue(py_obj_, type, N);
38
+ }
39
+
40
+ std::string toStr() override {
41
+ pybind11::gil_scoped_acquire ag;
42
+ return py::str(py_obj_);
43
+ }
44
+
45
+ std::vector<at::Tensor> extractTensors() override {
46
+ // We could implement this entirely in C++ via pybind11 but it turns out to
47
+ // be substantially slower. Namely, the total time taken by markCompleted on
48
+ // a CUDAFuture is 21.5us with this implementation, but goes up to 58.7us
49
+ // when using C++. The reason is unclear.
50
+ try {
51
+ pybind11::gil_scoped_acquire ag;
52
+ static py::object& extractorFn = *new py::object(
53
+ py::module::import("torch._jit_internal").attr("_extract_tensors"));
54
+ return extractorFn(py_obj_).cast<std::vector<at::Tensor>>();
55
+ } catch (py::error_already_set& e) {
56
+ auto err = std::runtime_error(
57
+ c10::str("Cannot extract tensors from value: ", e.what()));
58
+ {
59
+ pybind11::gil_scoped_acquire ag;
60
+ e.restore();
61
+ PyErr_Clear();
62
+ }
63
+ throw err;
64
+ }
65
+ }
66
+
67
+ // Note [Destructing py::object]
68
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~
69
+ //
70
+ // (1) Why py_obj_ = py::none(); does not work. Because we also need to
71
+ // acquire GIL when destructing py::object of None that de-references None.
72
+ // https://docs.python.org/3/c-api/none.html#c.Py_RETURN_NONE
73
+ //
74
+ // https://stackoverflow.com/questions/15287590/why-should-py-increfpy-none-be-required-before-returning-py-none-in-c
75
+ //
76
+ // (2) Why we need to call dec_ref() explicitly. Because py::object of
77
+ // nullptr, on destruction, effectively does nothing because of it calls
78
+ // Py_XDECREF(NULL) underlying.
79
+ // https://docs.python.org/3/c-api/refcounting.html#c.Py_XDECREF
80
+ ~ConcretePyObjectHolder() override {
81
+ pybind11::gil_scoped_acquire ag;
82
+ py_obj_.dec_ref();
83
+ // explicitly setting PyObject* to nullptr to prevent py::object's dtor to
84
+ // decref on the PyObject again.
85
+ py_obj_.ptr() = nullptr;
86
+ }
87
+
88
+ // explicit construction to avoid errornous implicit conversion and
89
+ // copy-initialization
90
+ explicit ConcretePyObjectHolder(py::object py_obj)
91
+ : py_obj_(std::move(py_obj)) {}
92
+
93
+ private:
94
+ py::object py_obj_;
95
+ };
96
+
97
+ } // namespace c10::ivalue
shared/package-files/06/06a0d61aa47624e544ab2f31ae6c858f4ef591cf8fba38a5695276edb13d3ecb/data_missing.dta ADDED
Binary file (1.13 kB). View file
 
shared/package-files/06/06bd03cb0ab219a5701da59b81b21664b9d0610ed2a5ad38678794f13ac7cfef/__init__.pyi ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from array import array
3
+ from typing import (
4
+ Any,
5
+ Callable,
6
+ ClassVar,
7
+ Generic,
8
+ Iterable,
9
+ Iterator,
10
+ List,
11
+ Mapping,
12
+ Optional,
13
+ Sequence,
14
+ Text,
15
+ Tuple,
16
+ Type,
17
+ TypeVar,
18
+ Union as _UnionT,
19
+ overload,
20
+ )
21
+
22
+ if sys.version_info >= (3, 9):
23
+ from types import GenericAlias
24
+
25
+ _T = TypeVar("_T")
26
+ _DLLT = TypeVar("_DLLT", bound=CDLL)
27
+ _CT = TypeVar("_CT", bound=_CData)
28
+
29
+ RTLD_GLOBAL: int = ...
30
+ RTLD_LOCAL: int = ...
31
+ DEFAULT_MODE: int = ...
32
+
33
+ class CDLL(object):
34
+ _func_flags_: ClassVar[int] = ...
35
+ _func_restype_: ClassVar[_CData] = ...
36
+ _name: str = ...
37
+ _handle: int = ...
38
+ _FuncPtr: Type[_FuncPointer] = ...
39
+ def __init__(
40
+ self,
41
+ name: Optional[str],
42
+ mode: int = ...,
43
+ handle: Optional[int] = ...,
44
+ use_errno: bool = ...,
45
+ use_last_error: bool = ...,
46
+ winmode: Optional[int] = ...,
47
+ ) -> None: ...
48
+ def __getattr__(self, name: str) -> _NamedFuncPointer: ...
49
+ def __getitem__(self, name: str) -> _NamedFuncPointer: ...
50
+
51
+ if sys.platform == "win32":
52
+ class OleDLL(CDLL): ...
53
+ class WinDLL(CDLL): ...
54
+
55
+ class PyDLL(CDLL): ...
56
+
57
+ class LibraryLoader(Generic[_DLLT]):
58
+ def __init__(self, dlltype: Type[_DLLT]) -> None: ...
59
+ def __getattr__(self, name: str) -> _DLLT: ...
60
+ def __getitem__(self, name: str) -> _DLLT: ...
61
+ def LoadLibrary(self, name: str) -> _DLLT: ...
62
+ if sys.version_info >= (3, 9):
63
+ def __class_getitem__(cls, item: Any) -> GenericAlias: ...
64
+
65
+ cdll: LibraryLoader[CDLL] = ...
66
+ if sys.platform == "win32":
67
+ windll: LibraryLoader[WinDLL] = ...
68
+ oledll: LibraryLoader[OleDLL] = ...
69
+ pydll: LibraryLoader[PyDLL] = ...
70
+ pythonapi: PyDLL = ...
71
+
72
+ # Anything that implements the read-write buffer interface.
73
+ # The buffer interface is defined purely on the C level, so we cannot define a normal Protocol
74
+ # for it. Instead we have to list the most common stdlib buffer classes in a Union.
75
+ _WritableBuffer = _UnionT[bytearray, memoryview, array, _CData]
76
+ # Same as _WritableBuffer, but also includes read-only buffer types (like bytes).
77
+ _ReadOnlyBuffer = _UnionT[_WritableBuffer, bytes]
78
+
79
+ class _CDataMeta(type):
80
+ # By default mypy complains about the following two methods, because strictly speaking cls
81
+ # might not be a Type[_CT]. However this can never actually happen, because the only class that
82
+ # uses _CDataMeta as its metaclass is _CData. So it's safe to ignore the errors here.
83
+ def __mul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore
84
+ def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore
85
+
86
+ class _CData(metaclass=_CDataMeta):
87
+ _b_base: int = ...
88
+ _b_needsfree_: bool = ...
89
+ _objects: Optional[Mapping[Any, int]] = ...
90
+ @classmethod
91
+ def from_buffer(cls: Type[_CT], source: _WritableBuffer, offset: int = ...) -> _CT: ...
92
+ @classmethod
93
+ def from_buffer_copy(cls: Type[_CT], source: _ReadOnlyBuffer, offset: int = ...) -> _CT: ...
94
+ @classmethod
95
+ def from_address(cls: Type[_CT], address: int) -> _CT: ...
96
+ @classmethod
97
+ def from_param(cls: Type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ...
98
+ @classmethod
99
+ def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ...
100
+
101
+ class _CanCastTo(_CData): ...
102
+ class _PointerLike(_CanCastTo): ...
103
+
104
+ _ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CData]
105
+ _PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]]
106
+
107
+ class _FuncPointer(_PointerLike, _CData):
108
+ restype: _UnionT[Type[_CData], Callable[[int], None], None] = ...
109
+ argtypes: Sequence[Type[_CData]] = ...
110
+ errcheck: _ECT = ...
111
+ @overload
112
+ def __init__(self, address: int) -> None: ...
113
+ @overload
114
+ def __init__(self, callable: Callable[..., Any]) -> None: ...
115
+ @overload
116
+ def __init__(self, func_spec: Tuple[_UnionT[str, int], CDLL], paramflags: Tuple[_PF, ...] = ...) -> None: ...
117
+ @overload
118
+ def __init__(self, vtlb_index: int, name: str, paramflags: Tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ...
119
+ def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
120
+
121
+ class _NamedFuncPointer(_FuncPointer):
122
+ __name__: str
123
+
124
+ class ArgumentError(Exception): ...
125
+
126
+ def CFUNCTYPE(
127
+ restype: Optional[Type[_CData]], *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ...
128
+ ) -> Type[_FuncPointer]: ...
129
+
130
+ if sys.platform == "win32":
131
+ def WINFUNCTYPE(
132
+ restype: Optional[Type[_CData]], *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ...
133
+ ) -> Type[_FuncPointer]: ...
134
+
135
+ def PYFUNCTYPE(restype: Optional[Type[_CData]], *argtypes: Type[_CData]) -> Type[_FuncPointer]: ...
136
+
137
+ class _CArgObject: ...
138
+
139
+ # Any type that can be implicitly converted to c_void_p when passed as a C function argument.
140
+ # (bytes is not included here, see below.)
141
+ _CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int]
142
+ # Same as above, but including types known to be read-only (i. e. bytes).
143
+ # This distinction is not strictly necessary (ctypes doesn't differentiate between const
144
+ # and non-const pointers), but it catches errors like memmove(b'foo', buf, 4)
145
+ # when memmove(buf, b'foo', 4) was intended.
146
+ _CVoidConstPLike = _UnionT[_CVoidPLike, bytes]
147
+
148
+ def addressof(obj: _CData) -> int: ...
149
+ def alignment(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ...
150
+ def byref(obj: _CData, offset: int = ...) -> _CArgObject: ...
151
+
152
+ _CastT = TypeVar("_CastT", bound=_CanCastTo)
153
+
154
+ def cast(obj: _UnionT[_CData, _CArgObject, int], type: Type[_CastT]) -> _CastT: ...
155
+ def create_string_buffer(init: _UnionT[int, bytes], size: Optional[int] = ...) -> Array[c_char]: ...
156
+
157
+ c_buffer = create_string_buffer
158
+
159
+ def create_unicode_buffer(init: _UnionT[int, Text], size: Optional[int] = ...) -> Array[c_wchar]: ...
160
+
161
+ if sys.platform == "win32":
162
+ def DllCanUnloadNow() -> int: ...
163
+ def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented
164
+ def FormatError(code: int) -> str: ...
165
+ def GetLastError() -> int: ...
166
+
167
+ def get_errno() -> int: ...
168
+
169
+ if sys.platform == "win32":
170
+ def get_last_error() -> int: ...
171
+
172
+ def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> None: ...
173
+ def memset(dst: _CVoidPLike, c: int, count: int) -> None: ...
174
+ def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ...
175
+
176
+ # The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like
177
+ # ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer,
178
+ # it can be instantiated directly (to mimic the behavior of the real pointer function).
179
+ class pointer(Generic[_CT], _PointerLike, _CData):
180
+ _type_: ClassVar[Type[_CT]] = ...
181
+ contents: _CT = ...
182
+ def __init__(self, arg: _CT = ...) -> None: ...
183
+ @overload
184
+ def __getitem__(self, i: int) -> _CT: ...
185
+ @overload
186
+ def __getitem__(self, s: slice) -> List[_CT]: ...
187
+ @overload
188
+ def __setitem__(self, i: int, o: _CT) -> None: ...
189
+ @overload
190
+ def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ...
191
+
192
+ def resize(obj: _CData, size: int) -> None: ...
193
+
194
+ if sys.version_info < (3,):
195
+ def set_conversion_mode(encoding: str, errors: str) -> Tuple[str, str]: ...
196
+
197
+ def set_errno(value: int) -> int: ...
198
+
199
+ if sys.platform == "win32":
200
+ def set_last_error(value: int) -> int: ...
201
+
202
+ def sizeof(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ...
203
+ def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ...
204
+
205
+ if sys.platform == "win32":
206
+ def WinError(code: Optional[int] = ..., descr: Optional[str] = ...) -> OSError: ...
207
+
208
+ def wstring_at(address: _CVoidConstPLike, size: int = ...) -> str: ...
209
+
210
+ class _SimpleCData(Generic[_T], _CData):
211
+ value: _T = ...
212
+ def __init__(self, value: _T = ...) -> None: ...
213
+
214
+ class c_byte(_SimpleCData[int]): ...
215
+
216
+ class c_char(_SimpleCData[bytes]):
217
+ def __init__(self, value: _UnionT[int, bytes] = ...) -> None: ...
218
+
219
+ class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]):
220
+ def __init__(self, value: Optional[_UnionT[int, bytes]] = ...) -> None: ...
221
+
222
+ class c_double(_SimpleCData[float]): ...
223
+ class c_longdouble(_SimpleCData[float]): ...
224
+ class c_float(_SimpleCData[float]): ...
225
+ class c_int(_SimpleCData[int]): ...
226
+ class c_int8(_SimpleCData[int]): ...
227
+ class c_int16(_SimpleCData[int]): ...
228
+ class c_int32(_SimpleCData[int]): ...
229
+ class c_int64(_SimpleCData[int]): ...
230
+ class c_long(_SimpleCData[int]): ...
231
+ class c_longlong(_SimpleCData[int]): ...
232
+ class c_short(_SimpleCData[int]): ...
233
+ class c_size_t(_SimpleCData[int]): ...
234
+ class c_ssize_t(_SimpleCData[int]): ...
235
+ class c_ubyte(_SimpleCData[int]): ...
236
+ class c_uint(_SimpleCData[int]): ...
237
+ class c_uint8(_SimpleCData[int]): ...
238
+ class c_uint16(_SimpleCData[int]): ...
239
+ class c_uint32(_SimpleCData[int]): ...
240
+ class c_uint64(_SimpleCData[int]): ...
241
+ class c_ulong(_SimpleCData[int]): ...
242
+ class c_ulonglong(_SimpleCData[int]): ...
243
+ class c_ushort(_SimpleCData[int]): ...
244
+ class c_void_p(_PointerLike, _SimpleCData[Optional[int]]): ...
245
+ class c_wchar(_SimpleCData[Text]): ...
246
+
247
+ class c_wchar_p(_PointerLike, _SimpleCData[Optional[Text]]):
248
+ def __init__(self, value: Optional[_UnionT[int, Text]] = ...) -> None: ...
249
+
250
+ class c_bool(_SimpleCData[bool]):
251
+ def __init__(self, value: bool = ...) -> None: ...
252
+
253
+ if sys.platform == "win32":
254
+ class HRESULT(_SimpleCData[int]): ... # TODO undocumented
255
+
256
+ class py_object(_CanCastTo, _SimpleCData[_T]): ...
257
+
258
+ class _CField:
259
+ offset: int = ...
260
+ size: int = ...
261
+
262
+ class _StructUnionMeta(_CDataMeta):
263
+ _fields_: Sequence[_UnionT[Tuple[str, Type[_CData]], Tuple[str, Type[_CData], int]]] = ...
264
+ _pack_: int = ...
265
+ _anonymous_: Sequence[str] = ...
266
+ def __getattr__(self, name: str) -> _CField: ...
267
+
268
+ class _StructUnionBase(_CData, metaclass=_StructUnionMeta):
269
+ def __init__(self, *args: Any, **kw: Any) -> None: ...
270
+ def __getattr__(self, name: str) -> Any: ...
271
+ def __setattr__(self, name: str, value: Any) -> None: ...
272
+
273
+ class Union(_StructUnionBase): ...
274
+ class Structure(_StructUnionBase): ...
275
+ class BigEndianStructure(Structure): ...
276
+ class LittleEndianStructure(Structure): ...
277
+
278
+ class Array(Generic[_CT], _CData):
279
+ _length_: ClassVar[int] = ...
280
+ _type_: ClassVar[Type[_CT]] = ...
281
+ raw: bytes = ... # Note: only available if _CT == c_char
282
+ value: Any = ... # Note: bytes if _CT == c_char, Text if _CT == c_wchar, unavailable otherwise
283
+ # TODO These methods cannot be annotated correctly at the moment.
284
+ # All of these "Any"s stand for the array's element type, but it's not possible to use _CT
285
+ # here, because of a special feature of ctypes.
286
+ # By default, when accessing an element of an Array[_CT], the returned object has type _CT.
287
+ # However, when _CT is a "simple type" like c_int, ctypes automatically "unboxes" the object
288
+ # and converts it to the corresponding Python primitive. For example, when accessing an element
289
+ # of an Array[c_int], a Python int object is returned, not a c_int.
290
+ # This behavior does *not* apply to subclasses of "simple types".
291
+ # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns
292
+ # a MyInt, not an int.
293
+ # This special behavior is not easy to model in a stub, so for now all places where
294
+ # the array element type would belong are annotated with Any instead.
295
+ def __init__(self, *args: Any) -> None: ...
296
+ @overload
297
+ def __getitem__(self, i: int) -> Any: ...
298
+ @overload
299
+ def __getitem__(self, s: slice) -> List[Any]: ...
300
+ @overload
301
+ def __setitem__(self, i: int, o: Any) -> None: ...
302
+ @overload
303
+ def __setitem__(self, s: slice, o: Iterable[Any]) -> None: ...
304
+ def __iter__(self) -> Iterator[Any]: ...
305
+ # Can't inherit from Sized because the metaclass conflict between
306
+ # Sized and _CData prevents using _CDataMeta.
307
+ def __len__(self) -> int: ...
308
+ if sys.version_info >= (3, 9):
309
+ def __class_getitem__(cls, item: Any) -> GenericAlias: ...
shared/package-files/06/06d090ae1a5cf3f42e004c937acfa25d9bcd1830a4e0c7218eaf4e0ee7a40025/sparse_csc_tensor_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API sparse_csc_tensor_ccol_row_value_size {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, at::IntArrayRef, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_csc_tensor")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ccol_row_value_size")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_csc_tensor.ccol_row_value_size(Tensor ccol_indices, Tensor row_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, at::IntArrayRef size, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
26
+ };
27
+
28
+ struct TORCH_API sparse_csc_tensor_ccol_row_value {
29
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::optional<at::ScalarType>, c10::optional<at::Layout>, c10::optional<at::Device>, c10::optional<bool>);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::sparse_csc_tensor")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "ccol_row_value")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "sparse_csc_tensor.ccol_row_value(Tensor ccol_indices, Tensor row_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & ccol_indices, const at::Tensor & row_indices, const at::Tensor & values, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/06/06e5eecfab0237d4daed4956441ce3c7876d0e96dd748de38cabbcc4ea430f04/kl_div.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/kl_div_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::kl_div(Tensor self, Tensor target, int reduction=Mean, *, bool log_target=False) -> Tensor
26
+ inline at::Tensor kl_div(const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean, bool log_target=false) {
27
+ return at::_ops::kl_div::call(self, target, reduction, log_target);
28
+ }
29
+
30
+ }
shared/package-files/1f/1f012661d626769e2bec85a7a56ac4d20d19d7f1ccdd3ace9a1aebcfb1ad25e0/ansi.sys-old ADDED
Binary file (1.26 kB). View file
 
shared/package-files/1f/1f0c7a1de6f606f4d33037d660bdf24685eca8c77dc5dbb5fcb457cf69cccf0b/win32-headers.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #ifndef WIN32_LEAN_AND_MEAN
4
+ #define WIN32_LEAN_AND_MEAN
5
+ #endif
6
+ #ifndef NOMINMAX
7
+ #define NOMINMAX
8
+ #endif
9
+ #ifndef NOKERNEL
10
+ #define NOKERNEL
11
+ #endif
12
+ #ifndef NOUSER
13
+ #define NOUSER
14
+ #endif
15
+ #ifndef NOSERVICE
16
+ #define NOSERVICE
17
+ #endif
18
+ #ifndef NOSOUND
19
+ #define NOSOUND
20
+ #endif
21
+ #ifndef NOMCX
22
+ #define NOMCX
23
+ #endif
24
+ #ifndef NOGDI
25
+ #define NOGDI
26
+ #endif
27
+ #ifndef NOMSG
28
+ #define NOMSG
29
+ #endif
30
+ #ifndef NOMB
31
+ #define NOMB
32
+ #endif
33
+ #ifndef NOCLIPBOARD
34
+ #define NOCLIPBOARD
35
+ #endif
36
+
37
+ // dbghelp seems to require windows.h.
38
+ // clang-format off
39
+ #include <windows.h>
40
+ #include <dbghelp.h>
41
+ // clang-format on
42
+
43
+ #undef VOID
44
+ #undef DELETE
45
+ #undef IN
46
+ #undef THIS
47
+ #undef CONST
48
+ #undef NAN
49
+ #undef UNKNOWN
50
+ #undef NONE
51
+ #undef ANY
52
+ #undef IGNORE
53
+ #undef STRICT
54
+ #undef GetObject
55
+ #undef CreateSemaphore
56
+ #undef Yield
57
+ #undef RotateRight32
58
+ #undef RotateLeft32
59
+ #undef RotateRight64
60
+ #undef RotateLeft64
shared/package-files/1f/1f0c9cca56cf020455cf89d9be3bf0a8dde642725ba8a03e35131a02f20ff821/_utility_functions.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ._array_object import Array
4
+
5
+ from typing import Optional, Tuple, Union
6
+
7
+ import numpy as np
8
+
9
+
10
+ def all(
11
+ x: Array,
12
+ /,
13
+ *,
14
+ axis: Optional[Union[int, Tuple[int, ...]]] = None,
15
+ keepdims: bool = False,
16
+ ) -> Array:
17
+ """
18
+ Array API compatible wrapper for :py:func:`np.all <numpy.all>`.
19
+
20
+ See its docstring for more information.
21
+ """
22
+ return Array._new(np.asarray(np.all(x._array, axis=axis, keepdims=keepdims)))
23
+
24
+
25
+ def any(
26
+ x: Array,
27
+ /,
28
+ *,
29
+ axis: Optional[Union[int, Tuple[int, ...]]] = None,
30
+ keepdims: bool = False,
31
+ ) -> Array:
32
+ """
33
+ Array API compatible wrapper for :py:func:`np.any <numpy.any>`.
34
+
35
+ See its docstring for more information.
36
+ """
37
+ return Array._new(np.asarray(np.any(x._array, axis=axis, keepdims=keepdims)))
shared/package-files/1f/1f0ca74ed835cfb97b142562b47e00d3b505f1bff14b8b3b8682aabfe43aac1b/ansi.sys ADDED
Binary file (1.57 kB). View file
 
shared/package-files/1f/1f1b0f5dede0263bd81773a78e98af551f36361accb315b618c8ae70a5fe781e/id.msg ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # created by tools/loadICU.tcl -- do not edit
2
+ namespace eval ::tcl::clock {
3
+ ::msgcat::mcset id DAYS_OF_WEEK_ABBREV [list \
4
+ "Min"\
5
+ "Sen"\
6
+ "Sel"\
7
+ "Rab"\
8
+ "Kam"\
9
+ "Jum"\
10
+ "Sab"]
11
+ ::msgcat::mcset id DAYS_OF_WEEK_FULL [list \
12
+ "Minggu"\
13
+ "Senin"\
14
+ "Selasa"\
15
+ "Rabu"\
16
+ "Kamis"\
17
+ "Jumat"\
18
+ "Sabtu"]
19
+ ::msgcat::mcset id MONTHS_ABBREV [list \
20
+ "Jan"\
21
+ "Peb"\
22
+ "Mar"\
23
+ "Apr"\
24
+ "Mei"\
25
+ "Jun"\
26
+ "Jul"\
27
+ "Agu"\
28
+ "Sep"\
29
+ "Okt"\
30
+ "Nov"\
31
+ "Des"\
32
+ ""]
33
+ ::msgcat::mcset id MONTHS_FULL [list \
34
+ "Januari"\
35
+ "Pebruari"\
36
+ "Maret"\
37
+ "April"\
38
+ "Mei"\
39
+ "Juni"\
40
+ "Juli"\
41
+ "Agustus"\
42
+ "September"\
43
+ "Oktober"\
44
+ "November"\
45
+ "Desember"\
46
+ ""]
47
+ }
shared/package-files/1f/1f25c8588b495c12951d4cd67103e2d4c99de992e6664f90851528f4abf65ce2/Omsk ADDED
Binary file (1.19 kB). View file
 
shared/package-files/1f/1f3a5a429231389a9f86b10784ac845d11b0cdcfeeefd22eab2fcabaded1562d/six.h ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <pybind11/pybind11.h>
4
+ #include <torch/csrc/utils/object_ptr.h>
5
+ #include <torch/csrc/utils/pybind.h>
6
+ #include <torch/csrc/utils/structseq.h>
7
+
8
+ namespace six {
9
+
10
+ // Usually instances of PyStructSequence is also an instance of tuple
11
+ // but in some py2 environment it is not, so we have to manually check
12
+ // the name of the type to determine if it is a namedtupled returned
13
+ // by a pytorch operator.
14
+
15
+ inline bool isStructSeq(pybind11::handle input) {
16
+ return pybind11::cast<std::string>(input.get_type().attr("__module__")) ==
17
+ "torch.return_types";
18
+ }
19
+
20
+ inline bool isStructSeq(PyObject* obj) {
21
+ return isStructSeq(pybind11::handle(obj));
22
+ }
23
+
24
+ inline bool isTuple(pybind11::handle input) {
25
+ if (PyTuple_Check(input.ptr())) {
26
+ return true;
27
+ }
28
+ return false;
29
+ }
30
+
31
+ inline bool isTuple(PyObject* obj) {
32
+ return isTuple(pybind11::handle(obj));
33
+ }
34
+
35
+ // maybeAsTuple: if the input is a structseq, then convert it to a tuple
36
+ //
37
+ // On Python 3, structseq is a subtype of tuple, so these APIs could be used
38
+ // directly. But on Python 2, structseq is not a subtype of tuple, so we need to
39
+ // manually create a new tuple object from structseq.
40
+ inline THPObjectPtr maybeAsTuple(PyStructSequence* obj) {
41
+ Py_INCREF(obj);
42
+ return THPObjectPtr((PyObject*)obj);
43
+ }
44
+
45
+ inline THPObjectPtr maybeAsTuple(PyObject* obj) {
46
+ if (isStructSeq(obj))
47
+ return maybeAsTuple((PyStructSequence*)obj);
48
+ Py_INCREF(obj);
49
+ return THPObjectPtr(obj);
50
+ }
51
+
52
+ } // namespace six
shared/package-files/1f/1f3b4f48d844fbb98ef3162a664f704c9437659bb4e9b80a8ddb8f6fc373ca9c/bernoulli_cuda_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor & bernoulli_out(at::Tensor & out, const at::Tensor & self, c10::optional<at::Generator> generator=c10::nullopt);
21
+ TORCH_API at::Tensor & bernoulli_outf(const at::Tensor & self, c10::optional<at::Generator> generator, at::Tensor & out);
22
+ TORCH_API at::Tensor & bernoulli_(at::Tensor & self, const at::Tensor & p, c10::optional<at::Generator> generator=c10::nullopt);
23
+ TORCH_API at::Tensor & bernoulli_(at::Tensor & self, double p=0.5, c10::optional<at::Generator> generator=c10::nullopt);
24
+
25
+ } // namespace cuda
26
+ } // namespace at
shared/package-files/1f/1f42bd13d30048a580a164a3b7aa8e67279ef71e4bb7368abc848422c8654da6/norm_except_dim.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <c10/util/Optional.h>
17
+
18
+
19
+
20
+ #include <ATen/ops/norm_except_dim_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::norm_except_dim(Tensor v, int pow=2, int dim=0) -> Tensor
26
+ inline at::Tensor norm_except_dim(const at::Tensor & v, int64_t pow=2, int64_t dim=0) {
27
+ return at::_ops::norm_except_dim::call(v, pow, dim);
28
+ }
29
+
30
+ }
shared/package-files/1f/1f4a0d664366c293fc8ba529cac9e40fbc9abded04dd853767c74a1a86d26ce0/test_sdm.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests for the basic functionality of the SDM class.
3
+ """
4
+
5
+ from itertools import product
6
+
7
+ from sympy.core.singleton import S
8
+ from sympy.external.gmpy import HAS_GMPY
9
+ from sympy.testing.pytest import raises
10
+
11
+ from sympy.polys.domains import QQ, ZZ, EXRAW
12
+ from sympy.polys.matrices.sdm import SDM
13
+ from sympy.polys.matrices.ddm import DDM
14
+ from sympy.polys.matrices.exceptions import (DMBadInputError, DMDomainError,
15
+ DMShapeError)
16
+
17
+
18
+ def test_SDM():
19
+ A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
20
+ assert A.domain == ZZ
21
+ assert A.shape == (2, 2)
22
+ assert dict(A) == {0:{0:ZZ(1)}}
23
+
24
+ raises(DMBadInputError, lambda: SDM({5:{1:ZZ(0)}}, (2, 2), ZZ))
25
+ raises(DMBadInputError, lambda: SDM({0:{5:ZZ(0)}}, (2, 2), ZZ))
26
+
27
+
28
+ def test_DDM_str():
29
+ sdm = SDM({0:{0:ZZ(1)}, 1:{1:ZZ(1)}}, (2, 2), ZZ)
30
+ assert str(sdm) == '{0: {0: 1}, 1: {1: 1}}'
31
+ if HAS_GMPY: # pragma: no cover
32
+ assert repr(sdm) == 'SDM({0: {0: mpz(1)}, 1: {1: mpz(1)}}, (2, 2), ZZ)'
33
+ else: # pragma: no cover
34
+ assert repr(sdm) == 'SDM({0: {0: 1}, 1: {1: 1}}, (2, 2), ZZ)'
35
+
36
+
37
+ def test_SDM_new():
38
+ A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
39
+ B = A.new({}, (2, 2), ZZ)
40
+ assert B == SDM({}, (2, 2), ZZ)
41
+
42
+
43
+ def test_SDM_copy():
44
+ A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ)
45
+ B = A.copy()
46
+ assert A == B
47
+ A[0][0] = ZZ(2)
48
+ assert A != B
49
+
50
+
51
+ def test_SDM_from_list():
52
+ A = SDM.from_list([[ZZ(0), ZZ(1)], [ZZ(1), ZZ(0)]], (2, 2), ZZ)
53
+ assert A == SDM({0:{1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
54
+
55
+ raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ))
56
+ raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0), ZZ(1)]], (2, 2), ZZ))
57
+
58
+
59
+ def test_SDM_to_list():
60
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
61
+ assert A.to_list() == [[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]]
62
+
63
+ A = SDM({}, (0, 2), ZZ)
64
+ assert A.to_list() == []
65
+
66
+ A = SDM({}, (2, 0), ZZ)
67
+ assert A.to_list() == [[], []]
68
+
69
+
70
+ def test_SDM_to_list_flat():
71
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
72
+ assert A.to_list_flat() == [ZZ(0), ZZ(1), ZZ(0), ZZ(0)]
73
+
74
+
75
+ def test_SDM_to_dok():
76
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
77
+ assert A.to_dok() == {(0, 1): ZZ(1)}
78
+
79
+
80
+ def test_SDM_from_ddm():
81
+ A = DDM([[ZZ(1), ZZ(0)], [ZZ(1), ZZ(0)]], (2, 2), ZZ)
82
+ B = SDM.from_ddm(A)
83
+ assert B.domain == ZZ
84
+ assert B.shape == (2, 2)
85
+ assert dict(B) == {0:{0:ZZ(1)}, 1:{0:ZZ(1)}}
86
+
87
+
88
+ def test_SDM_to_ddm():
89
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
90
+ B = DDM([[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]], (2, 2), ZZ)
91
+ assert A.to_ddm() == B
92
+
93
+
94
+ def test_SDM_to_sdm():
95
+ A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ)
96
+ assert A.to_sdm() == A
97
+
98
+
99
+ def test_SDM_getitem():
100
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
101
+ assert A.getitem(0, 0) == ZZ.zero
102
+ assert A.getitem(0, 1) == ZZ.one
103
+ assert A.getitem(1, 0) == ZZ.zero
104
+ assert A.getitem(-2, -2) == ZZ.zero
105
+ assert A.getitem(-2, -1) == ZZ.one
106
+ assert A.getitem(-1, -2) == ZZ.zero
107
+ raises(IndexError, lambda: A.getitem(2, 0))
108
+ raises(IndexError, lambda: A.getitem(0, 2))
109
+
110
+
111
+ def test_SDM_setitem():
112
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
113
+ A.setitem(0, 0, ZZ(1))
114
+ assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
115
+ A.setitem(1, 0, ZZ(1))
116
+ assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ)
117
+ A.setitem(1, 0, ZZ(0))
118
+ assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
119
+ # Repeat the above test so that this time the row is empty
120
+ A.setitem(1, 0, ZZ(0))
121
+ assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ)
122
+ A.setitem(0, 0, ZZ(0))
123
+ assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
124
+ # This time the row is there but column is empty
125
+ A.setitem(0, 0, ZZ(0))
126
+ assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
127
+ raises(IndexError, lambda: A.setitem(2, 0, ZZ(1)))
128
+ raises(IndexError, lambda: A.setitem(0, 2, ZZ(1)))
129
+
130
+
131
+ def test_SDM_extract_slice():
132
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
133
+ B = A.extract_slice(slice(1, 2), slice(1, 2))
134
+ assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
135
+
136
+
137
+ def test_SDM_extract():
138
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
139
+ B = A.extract([1], [1])
140
+ assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
141
+ B = A.extract([1, 0], [1, 0])
142
+ assert B == SDM({0:{0:ZZ(4), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(1)}}, (2, 2), ZZ)
143
+ B = A.extract([1, 1], [1, 1])
144
+ assert B == SDM({0:{0:ZZ(4), 1:ZZ(4)}, 1:{0:ZZ(4), 1:ZZ(4)}}, (2, 2), ZZ)
145
+ B = A.extract([-1], [-1])
146
+ assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ)
147
+
148
+ A = SDM({}, (2, 2), ZZ)
149
+ B = A.extract([0, 1, 0], [0, 0])
150
+ assert B == SDM({}, (3, 2), ZZ)
151
+
152
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
153
+ assert A.extract([], []) == SDM.zeros((0, 0), ZZ)
154
+ assert A.extract([1], []) == SDM.zeros((1, 0), ZZ)
155
+ assert A.extract([], [1]) == SDM.zeros((0, 1), ZZ)
156
+
157
+ raises(IndexError, lambda: A.extract([2], [0]))
158
+ raises(IndexError, lambda: A.extract([0], [2]))
159
+ raises(IndexError, lambda: A.extract([-3], [0]))
160
+ raises(IndexError, lambda: A.extract([0], [-3]))
161
+
162
+
163
+ def test_SDM_zeros():
164
+ A = SDM.zeros((2, 2), ZZ)
165
+ assert A.domain == ZZ
166
+ assert A.shape == (2, 2)
167
+ assert dict(A) == {}
168
+
169
+ def test_SDM_ones():
170
+ A = SDM.ones((1, 2), QQ)
171
+ assert A.domain == QQ
172
+ assert A.shape == (1, 2)
173
+ assert dict(A) == {0:{0:QQ(1), 1:QQ(1)}}
174
+
175
+ def test_SDM_eye():
176
+ A = SDM.eye((2, 2), ZZ)
177
+ assert A.domain == ZZ
178
+ assert A.shape == (2, 2)
179
+ assert dict(A) == {0:{0:ZZ(1)}, 1:{1:ZZ(1)}}
180
+
181
+
182
+ def test_SDM_diag():
183
+ A = SDM.diag([ZZ(1), ZZ(2)], ZZ, (2, 3))
184
+ assert A == SDM({0:{0:ZZ(1)}, 1:{1:ZZ(2)}}, (2, 3), ZZ)
185
+
186
+
187
+ def test_SDM_transpose():
188
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
189
+ B = SDM({0:{0:ZZ(1), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(4)}}, (2, 2), ZZ)
190
+ assert A.transpose() == B
191
+
192
+ A = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ)
193
+ B = SDM({1:{0:ZZ(2)}}, (2, 2), ZZ)
194
+ assert A.transpose() == B
195
+
196
+ A = SDM({0:{1:ZZ(2)}}, (1, 2), ZZ)
197
+ B = SDM({1:{0:ZZ(2)}}, (2, 1), ZZ)
198
+ assert A.transpose() == B
199
+
200
+
201
+ def test_SDM_mul():
202
+ A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ)
203
+ B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
204
+ assert A*ZZ(2) == B
205
+ assert ZZ(2)*A == B
206
+
207
+ raises(TypeError, lambda: A*QQ(1, 2))
208
+ raises(TypeError, lambda: QQ(1, 2)*A)
209
+
210
+
211
+ def test_SDM_mul_elementwise():
212
+ A = SDM({0:{0:ZZ(2), 1:ZZ(2)}}, (2, 2), ZZ)
213
+ B = SDM({0:{0:ZZ(4)}, 1:{0:ZZ(3)}}, (2, 2), ZZ)
214
+ C = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ)
215
+ assert A.mul_elementwise(B) == C
216
+ assert B.mul_elementwise(A) == C
217
+
218
+ Aq = A.convert_to(QQ)
219
+ A1 = SDM({0:{0:ZZ(1)}}, (1, 1), ZZ)
220
+
221
+ raises(DMDomainError, lambda: Aq.mul_elementwise(B))
222
+ raises(DMShapeError, lambda: A1.mul_elementwise(B))
223
+
224
+
225
+ def test_SDM_matmul():
226
+ A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ)
227
+ B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
228
+ assert A.matmul(A) == A*A == B
229
+
230
+ C = SDM({0:{0:ZZ(2)}}, (2, 2), QQ)
231
+ raises(DMDomainError, lambda: A.matmul(C))
232
+
233
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
234
+ B = SDM({0:{0:ZZ(7), 1:ZZ(10)}, 1:{0:ZZ(15), 1:ZZ(22)}}, (2, 2), ZZ)
235
+ assert A.matmul(A) == A*A == B
236
+
237
+ A22 = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ)
238
+ A32 = SDM({0:{0:ZZ(2)}}, (3, 2), ZZ)
239
+ A23 = SDM({0:{0:ZZ(4)}}, (2, 3), ZZ)
240
+ A33 = SDM({0:{0:ZZ(8)}}, (3, 3), ZZ)
241
+ A22 = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ)
242
+ assert A32.matmul(A23) == A33
243
+ assert A23.matmul(A32) == A22
244
+ # XXX: @ not supported by SDM...
245
+ #assert A32.matmul(A23) == A32 @ A23 == A33
246
+ #assert A23.matmul(A32) == A23 @ A32 == A22
247
+ #raises(DMShapeError, lambda: A23 @ A22)
248
+ raises(DMShapeError, lambda: A23.matmul(A22))
249
+
250
+ A = SDM({0: {0: ZZ(-1), 1: ZZ(1)}}, (1, 2), ZZ)
251
+ B = SDM({0: {0: ZZ(-1)}, 1: {0: ZZ(-1)}}, (2, 1), ZZ)
252
+ assert A.matmul(B) == A*B == SDM({}, (1, 1), ZZ)
253
+
254
+
255
+ def test_matmul_exraw():
256
+
257
+ def dm(d):
258
+ result = {}
259
+ for i, row in d.items():
260
+ row = {j:val for j, val in row.items() if val}
261
+ if row:
262
+ result[i] = row
263
+ return SDM(result, (2, 2), EXRAW)
264
+
265
+ values = [S.NegativeInfinity, S.NegativeOne, S.Zero, S.One, S.Infinity]
266
+ for a, b, c, d in product(*[values]*4):
267
+ Ad = dm({0: {0:a, 1:b}, 1: {0:c, 1:d}})
268
+ Ad2 = dm({0: {0:a*a + b*c, 1:a*b + b*d}, 1:{0:c*a + d*c, 1: c*b + d*d}})
269
+ assert Ad * Ad == Ad2
270
+
271
+
272
+ def test_SDM_add():
273
+ A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
274
+ B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
275
+ C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{1:ZZ(6)}}, (2, 2), ZZ)
276
+ assert A.add(B) == B.add(A) == A + B == B + A == C
277
+
278
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
279
+ B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
280
+ C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
281
+ assert A.add(B) == B.add(A) == A + B == B + A == C
282
+
283
+ raises(TypeError, lambda: A + [])
284
+
285
+
286
+ def test_SDM_sub():
287
+ A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
288
+ B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ)
289
+ C = SDM({0:{0:ZZ(-1), 1:ZZ(1)}, 1:{0:ZZ(4)}}, (2, 2), ZZ)
290
+ assert A.sub(B) == A - B == C
291
+
292
+ raises(TypeError, lambda: A - [])
293
+
294
+
295
+ def test_SDM_neg():
296
+ A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
297
+ B = SDM({0:{1:ZZ(-1)}, 1:{0:ZZ(-2), 1:ZZ(-3)}}, (2, 2), ZZ)
298
+ assert A.neg() == -A == B
299
+
300
+
301
+ def test_SDM_convert_to():
302
+ A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ)
303
+ B = SDM({0:{1:QQ(1)}, 1:{0:QQ(2), 1:QQ(3)}}, (2, 2), QQ)
304
+ C = A.convert_to(QQ)
305
+ assert C == B
306
+ assert C.domain == QQ
307
+
308
+ D = A.convert_to(ZZ)
309
+ assert D == A
310
+ assert D.domain == ZZ
311
+
312
+
313
+ def test_SDM_hstack():
314
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
315
+ B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ)
316
+ AA = SDM({0:{1:ZZ(1), 3:ZZ(1)}}, (2, 4), ZZ)
317
+ AB = SDM({0:{1:ZZ(1)}, 1:{3:ZZ(1)}}, (2, 4), ZZ)
318
+ assert SDM.hstack(A) == A
319
+ assert SDM.hstack(A, A) == AA
320
+ assert SDM.hstack(A, B) == AB
321
+
322
+
323
+ def test_SDM_vstack():
324
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
325
+ B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ)
326
+ AA = SDM({0:{1:ZZ(1)}, 2:{1:ZZ(1)}}, (4, 2), ZZ)
327
+ AB = SDM({0:{1:ZZ(1)}, 3:{1:ZZ(1)}}, (4, 2), ZZ)
328
+ assert SDM.vstack(A) == A
329
+ assert SDM.vstack(A, A) == AA
330
+ assert SDM.vstack(A, B) == AB
331
+
332
+
333
+ def test_SDM_applyfunc():
334
+ A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ)
335
+ B = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ)
336
+ assert A.applyfunc(lambda x: 2*x, ZZ) == B
337
+
338
+
339
+ def test_SDM_inv():
340
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
341
+ B = SDM({0:{0:QQ(-2), 1:QQ(1)}, 1:{0:QQ(3, 2), 1:QQ(-1, 2)}}, (2, 2), QQ)
342
+ assert A.inv() == B
343
+
344
+
345
+ def test_SDM_det():
346
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
347
+ assert A.det() == QQ(-2)
348
+
349
+
350
+ def test_SDM_lu():
351
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
352
+ L = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(1)}}, (2, 2), QQ)
353
+ #U = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(-2)}}, (2, 2), QQ)
354
+ #swaps = []
355
+ # This doesn't quite work. U has some nonzero elements in the lower part.
356
+ #assert A.lu() == (L, U, swaps)
357
+ assert A.lu()[0] == L
358
+
359
+
360
+ def test_SDM_lu_solve():
361
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
362
+ b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ)
363
+ x = SDM({1:{0:QQ(1, 2)}}, (2, 1), QQ)
364
+ assert A.matmul(x) == b
365
+ assert A.lu_solve(b) == x
366
+
367
+
368
+ def test_SDM_charpoly():
369
+ A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ)
370
+ assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)]
371
+
372
+
373
+ def test_SDM_nullspace():
374
+ A = SDM({0:{0:QQ(1), 1:QQ(1)}}, (2, 2), QQ)
375
+ assert A.nullspace()[0] == SDM({0:{0:QQ(-1), 1:QQ(1)}}, (1, 2), QQ)
376
+
377
+
378
+ def test_SDM_rref():
379
+ eye2 = SDM({0:{0:QQ(1)}, 1:{1:QQ(1)}}, (2, 2), QQ)
380
+
381
+ A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
382
+ assert A.rref() == (eye2, [0, 1])
383
+
384
+ A = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
385
+ assert A.rref() == (eye2, [0, 1])
386
+
387
+ A = SDM({0:{1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ)
388
+ assert A.rref() == (eye2, [0, 1])
389
+
390
+ A = SDM({0:{0:QQ(1), 1:QQ(2), 2:QQ(3)},
391
+ 1:{0:QQ(4), 1:QQ(5), 2:QQ(6)},
392
+ 2:{0:QQ(7), 1:QQ(8), 2:QQ(9)} }, (3, 3), QQ)
393
+ Arref = SDM({0:{0:QQ(1), 2:QQ(-1)}, 1:{1:QQ(1), 2:QQ(2)}}, (3, 3), QQ)
394
+ assert A.rref() == (Arref, [0, 1])
395
+
396
+ A = SDM({0:{0:QQ(1), 1:QQ(2), 3:QQ(1)},
397
+ 1:{0:QQ(1), 1:QQ(1), 2:QQ(9)}}, (2, 4), QQ)
398
+ Arref = SDM({0:{0:QQ(1), 2:QQ(18), 3:QQ(-1)},
399
+ 1:{1:QQ(1), 2:QQ(-9), 3:QQ(1)}}, (2, 4), QQ)
400
+ assert A.rref() == (Arref, [0, 1])
401
+
402
+ A = SDM({0:{0:QQ(1), 1:QQ(1), 2:QQ(1)},
403
+ 1:{0:QQ(1), 1:QQ(2), 2:QQ(2)}}, (2, 3), QQ)
404
+ Arref = SDM(
405
+ {0: {0: QQ(1,1)}, 1: {1: QQ(1,1), 2: QQ(1,1)}},
406
+ (2, 3), QQ)
407
+ assert A.rref() == (Arref, [0, 1])
408
+
409
+
410
+ def test_SDM_particular():
411
+ A = SDM({0:{0:QQ(1)}}, (2, 2), QQ)
412
+ Apart = SDM.zeros((1, 2), QQ)
413
+ assert A.particular() == Apart
414
+
415
+
416
+ def test_SDM_is_zero_matrix():
417
+ A = SDM({0: {0: QQ(1)}}, (2, 2), QQ)
418
+ Azero = SDM.zeros((1, 2), QQ)
419
+ assert A.is_zero_matrix() is False
420
+ assert Azero.is_zero_matrix() is True
421
+
422
+
423
+ def test_SDM_is_upper():
424
+ A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
425
+ 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
426
+ 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ)
427
+ B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
428
+ 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
429
+ 2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ)
430
+ assert A.is_upper() is True
431
+ assert B.is_upper() is False
432
+
433
+
434
+ def test_SDM_is_lower():
435
+ A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
436
+ 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
437
+ 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ
438
+ ).transpose()
439
+ B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)},
440
+ 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)},
441
+ 2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ
442
+ ).transpose()
443
+ assert A.is_lower() is True
444
+ assert B.is_lower() is False
shared/package-files/1f/1f4e17b848b9d5800cfe065a7cf1e576cdfc9cf2c9fd527134095169d52612a6/_nested_get_lengths_ops.h 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 _nested_get_lengths {
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::_nested_get_lengths")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nested_get_lengths(Tensor self) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self);
26
+ };
27
+
28
+ }} // namespace at::_ops
shared/package-files/1f/1f519e110eea3924b0828e79b0d51a896cd56f5bdb02a3abd378677d1f81fa8f/_vector_sentinel.pyx ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from cython.operator cimport dereference as deref
2
+ from cpython.ref cimport Py_INCREF
3
+ cimport numpy as cnp
4
+
5
+ cnp.import_array()
6
+
7
+
8
+ cdef StdVectorSentinel _create_sentinel(vector_typed * vect_ptr):
9
+ if vector_typed is vector[float64_t]:
10
+ return StdVectorSentinelFloat64.create_for(vect_ptr)
11
+ elif vector_typed is vector[int32_t]:
12
+ return StdVectorSentinelInt32.create_for(vect_ptr)
13
+ elif vector_typed is vector[int64_t]:
14
+ return StdVectorSentinelInt64.create_for(vect_ptr)
15
+ else: # intp_t
16
+ return StdVectorSentinelIntP.create_for(vect_ptr)
17
+
18
+
19
+ cdef class StdVectorSentinel:
20
+ """Wraps a reference to a vector which will be deallocated with this object.
21
+
22
+ When created, the StdVectorSentinel swaps the reference of its internal
23
+ vectors with the provided one (vect_ptr), thus making the StdVectorSentinel
24
+ manage the provided one's lifetime.
25
+ """
26
+ cdef void* get_data(self):
27
+ """Return pointer to data."""
28
+
29
+ cdef int get_typenum(self):
30
+ """Get typenum for PyArray_SimpleNewFromData."""
31
+
32
+
33
+ cdef class StdVectorSentinelFloat64(StdVectorSentinel):
34
+ cdef vector[float64_t] vec
35
+
36
+ @staticmethod
37
+ cdef StdVectorSentinel create_for(vector[float64_t] * vect_ptr):
38
+ # This initializes the object directly without calling __init__
39
+ # See: https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#instantiation-from-existing-c-c-pointers # noqa
40
+ cdef StdVectorSentinelFloat64 sentinel = StdVectorSentinelFloat64.__new__(StdVectorSentinelFloat64)
41
+ sentinel.vec.swap(deref(vect_ptr))
42
+ return sentinel
43
+
44
+ cdef void* get_data(self):
45
+ return self.vec.data()
46
+
47
+ cdef int get_typenum(self):
48
+ return cnp.NPY_FLOAT64
49
+
50
+
51
+ cdef class StdVectorSentinelIntP(StdVectorSentinel):
52
+ cdef vector[intp_t] vec
53
+
54
+ @staticmethod
55
+ cdef StdVectorSentinel create_for(vector[intp_t] * vect_ptr):
56
+ # This initializes the object directly without calling __init__
57
+ # See: https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#instantiation-from-existing-c-c-pointers # noqa
58
+ cdef StdVectorSentinelIntP sentinel = StdVectorSentinelIntP.__new__(StdVectorSentinelIntP)
59
+ sentinel.vec.swap(deref(vect_ptr))
60
+ return sentinel
61
+
62
+ cdef void* get_data(self):
63
+ return self.vec.data()
64
+
65
+ cdef int get_typenum(self):
66
+ return cnp.NPY_INTP
67
+
68
+
69
+ cdef class StdVectorSentinelInt32(StdVectorSentinel):
70
+ cdef vector[int32_t] vec
71
+
72
+ @staticmethod
73
+ cdef StdVectorSentinel create_for(vector[int32_t] * vect_ptr):
74
+ # This initializes the object directly without calling __init__
75
+ # See: https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#instantiation-from-existing-c-c-pointers # noqa
76
+ cdef StdVectorSentinelInt32 sentinel = StdVectorSentinelInt32.__new__(StdVectorSentinelInt32)
77
+ sentinel.vec.swap(deref(vect_ptr))
78
+ return sentinel
79
+
80
+ cdef void* get_data(self):
81
+ return self.vec.data()
82
+
83
+ cdef int get_typenum(self):
84
+ return cnp.NPY_INT32
85
+
86
+
87
+ cdef class StdVectorSentinelInt64(StdVectorSentinel):
88
+ cdef vector[int64_t] vec
89
+
90
+ @staticmethod
91
+ cdef StdVectorSentinel create_for(vector[int64_t] * vect_ptr):
92
+ # This initializes the object directly without calling __init__
93
+ # See: https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#instantiation-from-existing-c-c-pointers # noqa
94
+ cdef StdVectorSentinelInt64 sentinel = StdVectorSentinelInt64.__new__(StdVectorSentinelInt64)
95
+ sentinel.vec.swap(deref(vect_ptr))
96
+ return sentinel
97
+
98
+ cdef void* get_data(self):
99
+ return self.vec.data()
100
+
101
+ cdef int get_typenum(self):
102
+ return cnp.NPY_INT64
103
+
104
+
105
+ cdef cnp.ndarray vector_to_nd_array(vector_typed * vect_ptr):
106
+ cdef:
107
+ cnp.npy_intp size = deref(vect_ptr).size()
108
+ StdVectorSentinel sentinel = _create_sentinel(vect_ptr)
109
+ cnp.ndarray arr = cnp.PyArray_SimpleNewFromData(
110
+ 1, &size, sentinel.get_typenum(), sentinel.get_data())
111
+
112
+ # Makes the numpy array responsible of the life-cycle of its buffer.
113
+ # A reference to the StdVectorSentinel will be stolen by the call to
114
+ # `PyArray_SetBaseObject` below, so we increase its reference counter.
115
+ # See: https://docs.python.org/3/c-api/intro.html#reference-count-details
116
+ Py_INCREF(sentinel)
117
+ cnp.PyArray_SetBaseObject(arr, sentinel)
118
+ return arr
shared/package-files/1f/1f55bdde7a0e8213fab2d4962730fac65163b7476179f1f5b926595c4fcc4d53/rshift_ops.h ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 __rshift___Scalar {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Scalar &);
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::__rshift__")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__rshift__.Scalar(Tensor self, Scalar other) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Scalar & other);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other);
26
+ };
27
+
28
+ struct TORCH_API __rshift___Tensor {
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::__rshift__")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__rshift__.Tensor(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 __irshift___Scalar {
40
+ using schema = at::Tensor & (at::Tensor &, const at::Scalar &);
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::__irshift__")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__irshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)")
46
+ static at::Tensor & call(at::Tensor & self, const at::Scalar & other);
47
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other);
48
+ };
49
+
50
+ struct TORCH_API __irshift___Tensor {
51
+ using schema = at::Tensor & (at::Tensor &, const at::Tensor &);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__irshift__")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__irshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)")
57
+ static at::Tensor & call(at::Tensor & self, const at::Tensor & other);
58
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other);
59
+ };
60
+
61
+ struct TORCH_API __rshift___Scalar_out {
62
+ using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &);
63
+ using ptr_schema = schema*;
64
+ // See Note [static constexpr char* members for windows NVCC]
65
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__rshift__")
66
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out")
67
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__rshift__.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)")
68
+ static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out);
69
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out);
70
+ };
71
+
72
+ struct TORCH_API __rshift___Tensor_out {
73
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &);
74
+ using ptr_schema = schema*;
75
+ // See Note [static constexpr char* members for windows NVCC]
76
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__rshift__")
77
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out")
78
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__rshift__.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)")
79
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
80
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
81
+ };
82
+
83
+ }} // namespace at::_ops
shared/package-files/1f/1f569ce27cb3145b482bc8bf51cef0b8e9fd1ae8f1e2e7a128061b1ddf93bb0e/scotland_births.html ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ <HTML>
3
+ <HEAD>
4
+ <META NAME="GENERATOR" Content="Microsoft Visual InterDev 1.0">
5
+ <META HTTP-EQUIV="Content-Type" content="text/html; charset=iso-8859-1">
6
+ <TITLE>Cross-sectional dataset viewer v1.1</TITLE>
7
+ </HEAD>
8
+ <BODY bgcolor='#ffffff' leftmargin="5" topmargin="0" >
9
+ <table RULES="columns" border="1" frame = "void" bgcolor='#000000' width="640" cellpadding="0" cellspacing="0">
10
+ <tr >
11
+ <td>
12
+ <a href= "mainmenu.asp"><img alt="Home" border="noborder" src= "images/home.gif" height="12" width="48" valign="center"></a>
13
+ </td>
14
+ <td>
15
+ <a href= "ss.asp"><img alt="StatSearch" border="noborder" src= "images/ssrch.gif" height="12" width="84" align= 'left' valign="center"></a>
16
+ </td>
17
+ <td>
18
+ <a href= "search.asp"><img alt="Text Search" border="noborder" src= "images/textsrch.gif" height="12" align= 'left' width="94" valign="center"></a>
19
+ </td>
20
+ <td>
21
+ <a href= "datasets2.asp"><img alt="StatStore" border="noborder" src= "images/sstore.gif" height="12" width="84" align= 'left' valign="center"></a>
22
+ </td>
23
+ <td>
24
+ <a href= "faq.asp"><img alt="FAQ" border="noborder" src= "images/faq.gif" height="12" width="84" align= 'left' valign="center"></a>
25
+ </td>
26
+
27
+
28
+ <td width="210">
29
+ &nbsp;
30
+ </td>
31
+ </tr>
32
+ </table>
33
+
34
+ <table rules='none' border='0' bordercolordark="EEEEEE" bordercolorlight="#FFFFFF" border="0" width="640">
35
+ <tr>
36
+ <td valign='top' bgcolor='#ffffff' colspan= '2'><font face= "arial" color="#339900" size="5"><strong>Dataset Display - Cross-Sectional</strong></font></td>
37
+ </tr>
38
+ <tr>
39
+ <td colspan= '2'><hr></td>
40
+ </tr>
41
+ <tr>
42
+ <td width='200' valign='top' align='left' bgcolor='#ffffff'><b>Dataset Name:</b></td>
43
+ <td valign='top' align='left' bgcolor='#ffffff'>
44
+ RT331602
45
+ </td>
46
+ </tr>
47
+ <tr>
48
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Title:</b></td>
49
+ <td valign='top' align='left' bgcolor='#ffffff'>
50
+
51
+ Vital and social statistics: Scotland
52
+ </td>
53
+ </tr>
54
+
55
+
56
+
57
+ <tr>
58
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Description:</b></td>
59
+
60
+ <td valign='top' align='left' bgcolor='#ffffff'>Vital and social statistics: Scotland<br><br>This dataset has been compiled from data published in Regional Trends 33, 1998 edition published on 25 June 1998.<br><br></td>
61
+ </tr>
62
+ <tr>
63
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Source:</b></td>
64
+ <td valign='top' align='left' bgcolor='#ffffff'>
65
+ Office for National Statistics; General Register Office for Scotland
66
+ </td>
67
+ </tr>
68
+ <tr>
69
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Time Frame:</b></td>
70
+ <td>
71
+ 1996
72
+ </td>
73
+ </tr>
74
+
75
+
76
+ <tr>
77
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Geographic Coverage:</b></td>
78
+ <td>
79
+ United Kingdom
80
+
81
+ </td>
82
+
83
+ </tr>
84
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Universe:</b></td>
85
+ <td>
86
+ UK live births
87
+ </td>
88
+ </tr>
89
+ <tr>
90
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Measure:</b></td>
91
+ <td>
92
+ various
93
+ </td>
94
+ </tr>
95
+
96
+
97
+
98
+ <tr>
99
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Units:</b></td>
100
+ <td>
101
+ See table
102
+ </td>
103
+ </tr>
104
+ <tr>
105
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Scalar:</b></td>
106
+ <td>
107
+ various
108
+ </td>
109
+ </tr>
110
+ <tr>
111
+ <td valign='top' align='left' bgcolor='#ffffff'><b>Formula:</b></td>
112
+ <td>
113
+ none
114
+ </td>
115
+
116
+ </tr>
117
+
118
+ </table>
119
+
120
+
121
+
122
+ <hr align='left' width='640'>
123
+
124
+ <table rules="box" border='0' width='640'>
125
+ <tr>
126
+ <td colspan="2" align="center" valign="center"bgcolor="#ffffff"><strong>Table Dimensions</strong></td>
127
+ </tr>
128
+ <tr><td colspan="2" width valign="top" bgcolor="#ffffff">Please select at least one item from each list and "Display Selection" or choose "Display All" </td></tr>
129
+ <tr><td colspan="2" width valign="top" bgcolor="#ffffff">To select list items either hold down 'Ctrl' key and click each item required, or click the first item and hold down the mouse button whilst scrolling down the list.</td></tr>
130
+
131
+ <tr>
132
+
133
+
134
+ <td width valign="top" bgcolor="#ffffff">
135
+ <b>Region</b>
136
+
137
+ <SUP>4</SUP>
138
+ </td>
139
+
140
+
141
+ <td width valign="top" bgcolor="#ffffff">
142
+ <b>Measure</b>
143
+
144
+
145
+ </td>
146
+
147
+ </tr>
148
+
149
+
150
+
151
+ <form TARGET="_self" ACTION="xsdataset.asp">
152
+ <tr>
153
+
154
+ <td>
155
+ <select multiple size="6" name="list1">
156
+
157
+ <option value="1" SELECTED>
158
+ United Kingdom
159
+ <option value="2" SELECTED>
160
+ Scotland
161
+ <option value="3" SELECTED>
162
+ Aberdeen City
163
+ <option value="4" SELECTED>
164
+ Aberdeenshire
165
+ <option value="5" SELECTED>
166
+ Angus
167
+ <option value="6" SELECTED>
168
+ Argyll and Bute
169
+ <option value="7" SELECTED>
170
+ Clackmannanshire
171
+ <option value="8" SELECTED>
172
+ Dumfries and Galloway
173
+ <option value="9" SELECTED>
174
+ Dundee City
175
+ <option value="10" SELECTED>
176
+ East Ayrshire
177
+ <option value="11" SELECTED>
178
+ East Dunbartonshire
179
+ <option value="12" SELECTED>
180
+ East Lothian
181
+ <option value="13" SELECTED>
182
+ East Renfrewshire
183
+ <option value="14" SELECTED>
184
+ Edinburgh, City of
185
+ <option value="15" SELECTED>
186
+ Eilean Siar (Western Isles)
187
+ <option value="16" SELECTED>
188
+ Falkirk
189
+ <option value="17" SELECTED>
190
+ Fife
191
+ <option value="18" SELECTED>
192
+ Glasgow City
193
+ <option value="19" SELECTED>
194
+ Highland
195
+ <option value="20" SELECTED>
196
+ Inverclyde
197
+ <option value="21" SELECTED>
198
+ Midlothian
199
+ <option value="22" SELECTED>
200
+ Moray
201
+ <option value="23" SELECTED>
202
+ North Ayrshire
203
+ <option value="24" SELECTED>
204
+ North Lanarkshire
205
+ <option value="25" SELECTED>
206
+ Orkney Islands
207
+ <option value="26" SELECTED>
208
+ Perth and Kinross
209
+ <option value="27" SELECTED>
210
+ Renfrewshire
211
+ <option value="28" SELECTED>
212
+ Scottish Borders, The
213
+ <option value="29" SELECTED>
214
+ Shetland Islands
215
+ <option value="30" SELECTED>
216
+ South Ayrshire
217
+ <option value="31" SELECTED>
218
+ South Lanarkshire
219
+ <option value="32" SELECTED>
220
+ Stirling
221
+ <option value="33" SELECTED>
222
+ West Dunbartonshire
223
+ <option value="34" SELECTED>
224
+ West Lothian
225
+ </select>
226
+ </td>
227
+
228
+ <td>
229
+ <select multiple size="6" name="list2">
230
+
231
+ <option value="1" SELECTED>
232
+ Live births per 1,000 population 1996
233
+ <option value="2" SELECTED>
234
+ Deaths per 1,000 population 1996
235
+ <option value="3" SELECTED>
236
+ Perinatal mortality rate, 3 year average, 1994-1996
237
+ <option value="4" SELECTED>
238
+ Infant mortality rate, 3 year average, 1994-1996
239
+ <option value="5" SELECTED>
240
+ Percentage of live births outside marriage 1996
241
+ </select>
242
+ </td>
243
+
244
+
245
+ </tr>
246
+ <tr>
247
+ <td><input type="submit" value="Display All" name="B2"></td>
248
+ <td><input type="submit" value="Display Selection" name="B1"></td>
249
+ <td>&nbsp;</td>
250
+
251
+ </tr>
252
+
253
+
254
+ <tr>
255
+ <tr><td colspan="2" width valign="top" bgcolor="#000000" align="center"><font color="#ffffff">To change your selection, click in the appropriate box</font></td></tr>
256
+ <tr>
257
+
258
+
259
+ </form>
260
+ </table>
261
+
262
+
263
+
264
+ <hr align='left' width='640'>
265
+
266
+
267
+
268
+ <table
269
+
270
+ border="1"
271
+
272
+ frame = "border"
273
+
274
+ rules="all"
275
+
276
+ cellpadding="0" width="640" bgcolor="#FFFFFF"
277
+
278
+ bordercolordark= "#999999"
279
+
280
+ bordercolorlight= "#EEEEEE"
281
+
282
+ width="640"
283
+
284
+
285
+ >
286
+
287
+ <THEAD>
288
+ <tr>
289
+ <th
290
+ colspan="3"
291
+ >
292
+
293
+ <font size="3"
294
+
295
+ >
296
+ <strong>Table</strong></font>
297
+
298
+
299
+
300
+
301
+ </th>
302
+ </tr>
303
+ </THEAD>
304
+ <TBODY><TR><TD></TD><TD ALIGN='center'>Live births per 1,000 population 1996<SUP>1</SUP></TD><TD ALIGN='center'>Deaths per 1,000 population 1996<SUP>1</SUP></TD><TD ALIGN='center'>Perinatal mortality rate, 3 year average, 1994-1996<SUP>2</SUP></TD><TD ALIGN='center'>Infant mortality rate, 3 year average, 1994-1996<SUP>3</SUP></TD><TD ALIGN='center'>Percentage of live births outside marriage 1996</TD><TR><TD ALIGN='left'>United Kingdom</TD><TD ALIGN='right'>12.5</TD><TD ALIGN='right'>10.9</TD><TD ALIGN='right'>8.8</TD><TD ALIGN='right'>6.1</TD><TD ALIGN='right'>36.0</TD><TR><TD ALIGN='left'>Scotland</TD><TD ALIGN='right'>11.6</TD><TD ALIGN='right'>11.8</TD><TD ALIGN='right'>9.3</TD><TD ALIGN='right'>6.2</TD><TD ALIGN='right'>36.0</TD><TR><TD ALIGN='left'>Aberdeen City</TD><TD ALIGN='right'>11.0</TD><TD ALIGN='right'>10.4</TD><TD ALIGN='right'>7.7</TD><TD ALIGN='right'>5.7</TD><TD ALIGN='right'>35.0</TD><TR><TD ALIGN='left'>Aberdeenshire</TD><TD ALIGN='right'>11.3</TD><TD ALIGN='right'>9.0</TD><TD ALIGN='right'>9.0</TD><TD ALIGN='right'>3.8</TD><TD ALIGN='right'>24.0</TD><TR><TD ALIGN='left'>Angus<SUP>3</SUP></TD><TD ALIGN='right'>11.0</TD><TD ALIGN='right'>13.2</TD><TD ALIGN='right'>5.6</TD><TD ALIGN='right'>3.2</TD><TD ALIGN='right'>33.0</TD><TR><TD ALIGN='left'>Argyll and Bute</TD><TD ALIGN='right'>10.5</TD><TD ALIGN='right'>13.8</TD><TD ALIGN='right'>8.6</TD><TD ALIGN='right'>7.0</TD><TD ALIGN='right'>33.0</TD><TR><TD ALIGN='left'>Clackmannanshire</TD><TD ALIGN='right'>12.3</TD><TD ALIGN='right'>11.3</TD><TD ALIGN='right'>10.4</TD><TD ALIGN='right'>6.3</TD><TD ALIGN='right'>40.0</TD><TR><TD ALIGN='left'>Dumfries and Galloway</TD><TD ALIGN='right'>10.9</TD><TD ALIGN='right'>12.8</TD><TD ALIGN='right'>8.8</TD><TD ALIGN='right'>7.8</TD><TD ALIGN='right'>34.0</TD><TR><TD ALIGN='left'>Dundee City</TD><TD ALIGN='right'>11.5</TD><TD ALIGN='right'>13.1</TD><TD ALIGN='right'>8.6</TD><TD ALIGN='right'>6.8</TD><TD ALIGN='right'>51.0</TD><TR><TD ALIGN='left'>East Ayrshire<SUP>3</SUP></TD><TD ALIGN='right'>11.4</TD><TD ALIGN='right'>11.6</TD><TD ALIGN='right'>12.3</TD><TD ALIGN='right'>6.5</TD><TD ALIGN='right'>40.0</TD><TR><TD ALIGN='left'>East Dunbartonshire</TD><TD ALIGN='right'>10.5</TD><TD ALIGN='right'>9.2</TD><TD ALIGN='right'>8.1</TD><TD ALIGN='right'>7.2</TD><TD ALIGN='right'>19.0</TD><TR><TD ALIGN='left'>East Lothian</TD><TD ALIGN='right'>12.3</TD><TD ALIGN='right'>12.6</TD><TD ALIGN='right'>7.6</TD><TD ALIGN='right'>5.2</TD><TD ALIGN='right'>29.0</TD><TR><TD ALIGN='left'>East Renfrewshire</TD><TD ALIGN='right'>11.5</TD><TD ALIGN='right'>9.5</TD><TD ALIGN='right'>7.4</TD><TD ALIGN='right'>6.2</TD><TD ALIGN='right'>19.0</TD><TR><TD ALIGN='left'>Edinburgh, City of</TD><TD ALIGN='right'>11.4</TD><TD ALIGN='right'>11.7</TD><TD ALIGN='right'>8.1</TD><TD ALIGN='right'>6.4</TD><TD ALIGN='right'>33.0</TD><TR><TD ALIGN='left'>Eilean Siar (Western Isles)<SUP>23</SUP></TD><TD ALIGN='right'>9.7</TD><TD ALIGN='right'>14.9</TD><TD ALIGN='right'>11.2</TD><TD ALIGN='right'>5.7</TD><TD ALIGN='right'>19.0</TD><TR><TD ALIGN='left'>Falkirk</TD><TD ALIGN='right'>11.7</TD><TD ALIGN='right'>11.7</TD><TD ALIGN='right'>7.9</TD><TD ALIGN='right'>4.8</TD><TD ALIGN='right'>34.0</TD><TR><TD ALIGN='left'>Fife</TD><TD ALIGN='right'>11.0</TD><TD ALIGN='right'>11.4</TD><TD ALIGN='right'>8.7</TD><TD ALIGN='right'>7.1</TD><TD ALIGN='right'>37.0</TD><TR><TD ALIGN='left'>Glasgow City</TD><TD ALIGN='right'>12.5</TD><TD ALIGN='right'>14.0</TD><TD ALIGN='right'>11.1</TD><TD ALIGN='right'>6.9</TD><TD ALIGN='right'>49.0</TD><TR><TD ALIGN='left'>Highland</TD><TD ALIGN='right'>11.4</TD><TD ALIGN='right'>11.4</TD><TD ALIGN='right'>8.3</TD><TD ALIGN='right'>6.5</TD><TD ALIGN='right'>34.0</TD><TR><TD ALIGN='left'>Inverclyde</TD><TD ALIGN='right'>11.7</TD><TD ALIGN='right'>14.5</TD><TD ALIGN='right'>11.5</TD><TD ALIGN='right'>8.0</TD><TD ALIGN='right'>45.0</TD><TR><TD ALIGN='left'>Midlothian</TD><TD ALIGN='right'>11.2</TD><TD ALIGN='right'>10.7</TD><TD ALIGN='right'>10.8</TD><TD ALIGN='right'>6.0</TD><TD ALIGN='right'>35.0</TD><TR><TD ALIGN='left'>Moray</TD><TD ALIGN='right'>12.4</TD><TD ALIGN='right'>11.0</TD><TD ALIGN='right'>9.8</TD><TD ALIGN='right'>7.4</TD><TD ALIGN='right'>26.0</TD><TR><TD ALIGN='left'>North Ayrshire<SUP>23</SUP></TD><TD ALIGN='right'>11.3</TD><TD ALIGN='right'>11.8</TD><TD ALIGN='right'>11.6</TD><TD ALIGN='right'>6.9</TD><TD ALIGN='right'>42.0</TD><TR><TD ALIGN='left'>North Lanarkshire</TD><TD ALIGN='right'>12.5</TD><TD ALIGN='right'>11.1</TD><TD ALIGN='right'>11.6</TD><TD ALIGN='right'>8.5</TD><TD ALIGN='right'>38.0</TD><TR><TD ALIGN='left'>Orkney Islands</TD><TD ALIGN='right'>10.9</TD><TD ALIGN='right'>11.6</TD><TD ALIGN='right'>7.5</TD><TD ALIGN='right'>1.4</TD><TD ALIGN='right'>30.0</TD><TR><TD ALIGN='left'>Perth and Kinross<SUP>3</SUP></TD><TD ALIGN='right'>10.5</TD><TD ALIGN='right'>12.6</TD><TD ALIGN='right'>9.8</TD><TD ALIGN='right'>5.9</TD><TD ALIGN='right'>29.0</TD><TR><TD ALIGN='left'>Renfrewshire<SUP>3</SUP></TD><TD ALIGN='right'>11.9</TD><TD ALIGN='right'>11.6</TD><TD ALIGN='right'>8.0</TD><TD ALIGN='right'>4.5</TD><TD ALIGN='right'>39.0</TD><TR><TD ALIGN='left'>Scottish Borders, The<SUP>3</SUP></TD><TD ALIGN='right'>10.7</TD><TD ALIGN='right'>12.8</TD><TD ALIGN='right'>8.0</TD><TD ALIGN='right'>4.9</TD><TD ALIGN='right'>28.0</TD><TR><TD ALIGN='left'>Shetland Islands<SUP>23</SUP></TD><TD ALIGN='right'>11.7</TD><TD ALIGN='right'>10.9</TD><TD ALIGN='right'>9.9</TD><TD ALIGN='right'>6.5</TD><TD ALIGN='right'>28.0</TD><TR><TD ALIGN='left'>South Ayrshire</TD><TD ALIGN='right'>10.1</TD><TD ALIGN='right'>12.7</TD><TD ALIGN='right'>6.2</TD><TD ALIGN='right'>4.3</TD><TD ALIGN='right'>33.0</TD><TR><TD ALIGN='left'>South Lanarkshire</TD><TD ALIGN='right'>11.5</TD><TD ALIGN='right'>11.3</TD><TD ALIGN='right'>9.2</TD><TD ALIGN='right'>5.1</TD><TD ALIGN='right'>33.0</TD><TR><TD ALIGN='left'>Stirling</TD><TD ALIGN='right'>11.1</TD><TD ALIGN='right'>11.8</TD><TD ALIGN='right'>7.7</TD><TD ALIGN='right'>4.9</TD><TD ALIGN='right'>33.0</TD><TR><TD ALIGN='left'>West Dunbartonshire</TD><TD ALIGN='right'>12.5</TD><TD ALIGN='right'>12.7</TD><TD ALIGN='right'>11.7</TD><TD ALIGN='right'>8.7</TD><TD ALIGN='right'>42.0</TD><TR><TD ALIGN='left'>West Lothian</TD><TD ALIGN='right'>13.1</TD><TD ALIGN='right'>9.5</TD><TD ALIGN='right'>8.7</TD><TD ALIGN='right'>4.6</TD><TD ALIGN='right'>33.0</TD></TABLE>
305
+ <HR align='left' width='640'>
306
+
307
+ <table border='0' width='640'>
308
+ <tr><td colspan='2' valign='top' align='center' ><strong>Footnotes</strong></td></tr>
309
+ <tr><td valign='top' width='20'>1 -</td><td>Births are on the basis of year of occurrence in England and Wales and year of registration in Scotland and Northern Ireland. Deaths relate to year of registration.<BR></td></tr><tr><td valign='top' width='20'>2 -</td><td>Still births and deaths of infants under 1 week of age per 1,000 live and still births. Figures for some Council areas should be treated with caution as the perinatal mortality rate was based on fewer than 20 deaths.<BR></td></tr><tr><td valign='top' width='20'>3 -</td><td>Deaths of infants under 1 year of age per 1,000 live births. Figures for some Council areas should be treated with caution as the infant mortality rate was based on fewer than 20 deaths.<BR></td></tr><tr><td valign='top' width='20'>4 -</td><td>New Councils for Scotland<BR></td></tr>
310
+ </table>
311
+ <hr align='left' width='640'>
312
+
shared/package-files/1f/1f59a95f609804c5eab38ac88282aaed1af4aa19acf7d2c3368da9c5d44e3447/bincount_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & bincount_out(at::Tensor & out, const at::Tensor & self, const c10::optional<at::Tensor> & weights={}, int64_t minlength=0);
21
+ TORCH_API at::Tensor & bincount_outf(const at::Tensor & self, const c10::optional<at::Tensor> & weights, int64_t minlength, at::Tensor & out);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
shared/package-files/1f/1f5a6512789fd760f107664a07c1ff9a40b95b15eb3c7a5e1516d32d2c594142/_random.pyx ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: The scikit-learn developers
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ """
5
+ Random utility function
6
+ =======================
7
+ This module complements missing features of ``numpy.random``.
8
+
9
+ The module contains:
10
+ * Several algorithms to sample integers without replacement.
11
+ * Fast rand_r alternative based on xor shifts
12
+ """
13
+ import numpy as np
14
+ from . import check_random_state
15
+
16
+ from ._typedefs cimport intp_t
17
+
18
+
19
+ cdef uint32_t DEFAULT_SEED = 1
20
+
21
+
22
+ # Compatibility type to always accept the default int type used by NumPy, both
23
+ # before and after NumPy 2. On Windows, `long` does not always match `inp_t`.
24
+ # See the comments in the `sample_without_replacement` Python function for more
25
+ # details.
26
+ ctypedef fused default_int:
27
+ intp_t
28
+ long
29
+
30
+
31
+ cpdef _sample_without_replacement_check_input(default_int n_population,
32
+ default_int n_samples):
33
+ """ Check that input are consistent for sample_without_replacement"""
34
+ if n_population < 0:
35
+ raise ValueError('n_population should be greater than 0, got %s.'
36
+ % n_population)
37
+
38
+ if n_samples > n_population:
39
+ raise ValueError('n_population should be greater or equal than '
40
+ 'n_samples, got n_samples > n_population (%s > %s)'
41
+ % (n_samples, n_population))
42
+
43
+
44
+ cpdef _sample_without_replacement_with_tracking_selection(
45
+ default_int n_population,
46
+ default_int n_samples,
47
+ random_state=None):
48
+ r"""Sample integers without replacement.
49
+
50
+ Select n_samples integers from the set [0, n_population) without
51
+ replacement.
52
+
53
+ Time complexity:
54
+ - Worst-case: unbounded
55
+ - Average-case:
56
+ O(O(np.random.randint) * \sum_{i=1}^n_samples 1 /
57
+ (1 - i / n_population)))
58
+ <= O(O(np.random.randint) *
59
+ n_population * ln((n_population - 2)
60
+ /(n_population - 1 - n_samples)))
61
+ <= O(O(np.random.randint) *
62
+ n_population * 1 / (1 - n_samples / n_population))
63
+
64
+ Space complexity of O(n_samples) in a python set.
65
+
66
+
67
+ Parameters
68
+ ----------
69
+ n_population : int
70
+ The size of the set to sample from.
71
+
72
+ n_samples : int
73
+ The number of integer to sample.
74
+
75
+ random_state : int, RandomState instance or None, default=None
76
+ If int, random_state is the seed used by the random number generator;
77
+ If RandomState instance, random_state is the random number generator;
78
+ If None, the random number generator is the RandomState instance used
79
+ by `np.random`.
80
+
81
+ Returns
82
+ -------
83
+ out : ndarray of shape (n_samples,)
84
+ The sampled subsets of integer.
85
+ """
86
+ _sample_without_replacement_check_input(n_population, n_samples)
87
+
88
+ cdef default_int i
89
+ cdef default_int j
90
+ cdef default_int[::1] out = np.empty((n_samples, ), dtype=int)
91
+
92
+ rng = check_random_state(random_state)
93
+ rng_randint = rng.randint
94
+
95
+ # The following line of code are heavily inspired from python core,
96
+ # more precisely of random.sample.
97
+ cdef set selected = set()
98
+
99
+ for i in range(n_samples):
100
+ j = rng_randint(n_population)
101
+ while j in selected:
102
+ j = rng_randint(n_population)
103
+ selected.add(j)
104
+ out[i] = j
105
+
106
+ return np.asarray(out)
107
+
108
+
109
+ cpdef _sample_without_replacement_with_pool(default_int n_population,
110
+ default_int n_samples,
111
+ random_state=None):
112
+ """Sample integers without replacement.
113
+
114
+ Select n_samples integers from the set [0, n_population) without
115
+ replacement.
116
+
117
+ Time complexity: O(n_population + O(np.random.randint) * n_samples)
118
+
119
+ Space complexity of O(n_population + n_samples).
120
+
121
+
122
+ Parameters
123
+ ----------
124
+ n_population : int
125
+ The size of the set to sample from.
126
+
127
+ n_samples : int
128
+ The number of integer to sample.
129
+
130
+ random_state : int, RandomState instance or None, default=None
131
+ If int, random_state is the seed used by the random number generator;
132
+ If RandomState instance, random_state is the random number generator;
133
+ If None, the random number generator is the RandomState instance used
134
+ by `np.random`.
135
+
136
+ Returns
137
+ -------
138
+ out : ndarray of shape (n_samples,)
139
+ The sampled subsets of integer.
140
+ """
141
+ _sample_without_replacement_check_input(n_population, n_samples)
142
+
143
+ cdef default_int i
144
+ cdef default_int j
145
+ cdef default_int[::1] out = np.empty((n_samples,), dtype=int)
146
+ cdef default_int[::1] pool = np.empty((n_population,), dtype=int)
147
+
148
+ rng = check_random_state(random_state)
149
+ rng_randint = rng.randint
150
+
151
+ # Initialize the pool
152
+ for i in range(n_population):
153
+ pool[i] = i
154
+
155
+ # The following line of code are heavily inspired from python core,
156
+ # more precisely of random.sample.
157
+ for i in range(n_samples):
158
+ j = rng_randint(n_population - i) # invariant: non-selected at [0,n-i)
159
+ out[i] = pool[j]
160
+ pool[j] = pool[n_population - i - 1] # move non-selected item into vacancy
161
+
162
+ return np.asarray(out)
163
+
164
+
165
+ cpdef _sample_without_replacement_with_reservoir_sampling(
166
+ default_int n_population,
167
+ default_int n_samples,
168
+ random_state=None
169
+ ):
170
+ """Sample integers without replacement.
171
+
172
+ Select n_samples integers from the set [0, n_population) without
173
+ replacement.
174
+
175
+ Time complexity of
176
+ O((n_population - n_samples) * O(np.random.randint) + n_samples)
177
+ Space complexity of O(n_samples)
178
+
179
+
180
+ Parameters
181
+ ----------
182
+ n_population : int
183
+ The size of the set to sample from.
184
+
185
+ n_samples : int
186
+ The number of integer to sample.
187
+
188
+ random_state : int, RandomState instance or None, default=None
189
+ If int, random_state is the seed used by the random number generator;
190
+ If RandomState instance, random_state is the random number generator;
191
+ If None, the random number generator is the RandomState instance used
192
+ by `np.random`.
193
+
194
+ Returns
195
+ -------
196
+ out : ndarray of shape (n_samples,)
197
+ The sampled subsets of integer. The order of the items is not
198
+ necessarily random. Use a random permutation of the array if the order
199
+ of the items has to be randomized.
200
+ """
201
+ _sample_without_replacement_check_input(n_population, n_samples)
202
+
203
+ cdef default_int i
204
+ cdef default_int j
205
+ cdef default_int[::1] out = np.empty((n_samples, ), dtype=int)
206
+
207
+ rng = check_random_state(random_state)
208
+ rng_randint = rng.randint
209
+
210
+ # This cython implementation is based on the one of Robert Kern:
211
+ # http://mail.scipy.org/pipermail/numpy-discussion/2010-December/
212
+ # 054289.html
213
+ #
214
+ for i in range(n_samples):
215
+ out[i] = i
216
+
217
+ for i from n_samples <= i < n_population:
218
+ j = rng_randint(0, i + 1)
219
+ if j < n_samples:
220
+ out[j] = i
221
+
222
+ return np.asarray(out)
223
+
224
+
225
+ cdef _sample_without_replacement(default_int n_population,
226
+ default_int n_samples,
227
+ method="auto",
228
+ random_state=None):
229
+ """Sample integers without replacement.
230
+
231
+ Private function for the implementation, see sample_without_replacement
232
+ documentation for more details.
233
+ """
234
+ _sample_without_replacement_check_input(n_population, n_samples)
235
+
236
+ all_methods = ("auto", "tracking_selection", "reservoir_sampling", "pool")
237
+
238
+ ratio = <double> n_samples / n_population if n_population != 0.0 else 1.0
239
+
240
+ # Check ratio and use permutation unless ratio < 0.01 or ratio > 0.99
241
+ if method == "auto" and ratio > 0.01 and ratio < 0.99:
242
+ rng = check_random_state(random_state)
243
+ return rng.permutation(n_population)[:n_samples]
244
+
245
+ if method == "auto" or method == "tracking_selection":
246
+ # TODO the pool based method can also be used.
247
+ # however, it requires special benchmark to take into account
248
+ # the memory requirement of the array vs the set.
249
+
250
+ # The value 0.2 has been determined through benchmarking.
251
+ if ratio < 0.2:
252
+ return _sample_without_replacement_with_tracking_selection(
253
+ n_population, n_samples, random_state)
254
+ else:
255
+ return _sample_without_replacement_with_reservoir_sampling(
256
+ n_population, n_samples, random_state)
257
+
258
+ elif method == "reservoir_sampling":
259
+ return _sample_without_replacement_with_reservoir_sampling(
260
+ n_population, n_samples, random_state)
261
+
262
+ elif method == "pool":
263
+ return _sample_without_replacement_with_pool(n_population, n_samples,
264
+ random_state)
265
+ else:
266
+ raise ValueError('Expected a method name in %s, got %s. '
267
+ % (all_methods, method))
268
+
269
+
270
+ def sample_without_replacement(
271
+ object n_population, object n_samples, method="auto", random_state=None):
272
+ """Sample integers without replacement.
273
+
274
+ Select n_samples integers from the set [0, n_population) without
275
+ replacement.
276
+
277
+
278
+ Parameters
279
+ ----------
280
+ n_population : int
281
+ The size of the set to sample from.
282
+
283
+ n_samples : int
284
+ The number of integer to sample.
285
+
286
+ random_state : int, RandomState instance or None, default=None
287
+ If int, random_state is the seed used by the random number generator;
288
+ If RandomState instance, random_state is the random number generator;
289
+ If None, the random number generator is the RandomState instance used
290
+ by `np.random`.
291
+
292
+ method : {"auto", "tracking_selection", "reservoir_sampling", "pool"}, \
293
+ default='auto'
294
+ If method == "auto", the ratio of n_samples / n_population is used
295
+ to determine which algorithm to use:
296
+ If ratio is between 0 and 0.01, tracking selection is used.
297
+ If ratio is between 0.01 and 0.99, numpy.random.permutation is used.
298
+ If ratio is greater than 0.99, reservoir sampling is used.
299
+ The order of the selected integers is undefined. If a random order is
300
+ desired, the selected subset should be shuffled.
301
+
302
+ If method =="tracking_selection", a set based implementation is used
303
+ which is suitable for `n_samples` <<< `n_population`.
304
+
305
+ If method == "reservoir_sampling", a reservoir sampling algorithm is
306
+ used which is suitable for high memory constraint or when
307
+ O(`n_samples`) ~ O(`n_population`).
308
+ The order of the selected integers is undefined. If a random order is
309
+ desired, the selected subset should be shuffled.
310
+
311
+ If method == "pool", a pool based algorithm is particularly fast, even
312
+ faster than the tracking selection method. However, a vector containing
313
+ the entire population has to be initialized.
314
+ If n_samples ~ n_population, the reservoir sampling method is faster.
315
+
316
+ Returns
317
+ -------
318
+ out : ndarray of shape (n_samples,)
319
+ The sampled subsets of integer. The subset of selected integer might
320
+ not be randomized, see the method argument.
321
+
322
+ Examples
323
+ --------
324
+ >>> from sklearn.utils.random import sample_without_replacement
325
+ >>> sample_without_replacement(10, 5, random_state=42)
326
+ array([8, 1, 5, 0, 7])
327
+ """
328
+ cdef:
329
+ intp_t n_pop_intp, n_samples_intp
330
+ long n_pop_long, n_samples_long
331
+
332
+ # On most platforms `np.int_ is np.intp`. However, before NumPy 2 the
333
+ # default integer `np.int_` was a long which is 32bit on 64bit windows
334
+ # while `intp` is 64bit on 64bit platforms and 32bit on 32bit ones.
335
+ if np.int_ is np.intp:
336
+ # Branch always taken on NumPy >=2 (or when not on 64bit windows).
337
+ # Cython has different rules for conversion of values to integers.
338
+ # For NumPy <1.26.2 AND Cython 3, this first branch requires `int()`
339
+ # called explicitly to allow e.g. floats.
340
+ n_pop_intp = int(n_population)
341
+ n_samples_intp = int(n_samples)
342
+ return _sample_without_replacement(
343
+ n_pop_intp, n_samples_intp, method, random_state)
344
+ else:
345
+ # Branch taken on 64bit windows with Numpy<2.0 where `long` is 32bit
346
+ n_pop_long = n_population
347
+ n_samples_long = n_samples
348
+ return _sample_without_replacement(
349
+ n_pop_long, n_samples_long, method, random_state)
350
+
351
+
352
+ def _our_rand_r_py(seed):
353
+ """Python utils to test the our_rand_r function"""
354
+ cdef uint32_t my_seed = seed
355
+ return our_rand_r(&my_seed)
shared/package-files/1f/1f5b81f8d9bec88c2ba738c6a08bba4abc6dc4c6fbb70c3c7c303080eb214cc1/_convert_indices_from_coo_to_csr_native.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+ #include <ATen/ops/_convert_indices_from_coo_to_csr_meta.h>
16
+
17
+ namespace at {
18
+ namespace native {
19
+ struct TORCH_API structured__convert_indices_from_coo_to_csr_structured_cpu : public at::meta::structured__convert_indices_from_coo_to_csr {
20
+ void impl(const at::Tensor & self, int64_t size, bool out_int32, const at::Tensor & out);
21
+ };
22
+ struct TORCH_API structured__convert_indices_from_coo_to_csr_structured_cuda : public at::meta::structured__convert_indices_from_coo_to_csr {
23
+ void impl(const at::Tensor & self, int64_t size, bool out_int32, const at::Tensor & out);
24
+ };
25
+ } // namespace native
26
+ } // namespace at
shared/package-files/1f/1f666c36d96b5c0a28a42b6200b4cce5a74bde72a327d547e367b2daae2a6abc/nbinom_resids.csv ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -.5049508,-.6297218,-83.54991,-1.306285,-6.620286
2
+ -.2341522,-.2554235,-216.8307,-.758866,-7.183702
3
+ 1.024237,.7987758,483.7363,2.503515,22.51353
4
+ -.2850617,-.3177966,-70411.51,-2.379918,-141.7456
5
+ .2099025,.1967877,2247.514,.9519455,21.77242
6
+ -.4034835,-.4757415,-19563.36,-2.635026,-88.94614
7
+ -.1644134,-.1744011,-17331.03,-1.162355,-53.42135
8
+ -.4296077,-.5134667,-5300.37,-2.244962,-47.82603
9
+ .323713,.2941846,4110.794,1.486844,36.55984
10
+ .1503672,.1434294,7285.321,.8855429,33.1355
11
+ .4212886,.373428,1373.157,1.521332,24.15702
12
+ .4506587,.3965867,1701.469,1.661779,27.80326
13
+ .2435375,.226174,3184.023,1.136562,27.90734
14
+ 1.051829,.8162054,6001.352,3.890797,79.71313
15
+ -.5544503,-.712749,-2094.852,-2.454965,-34.21899
16
+ -.6057506,-.8064111,-274.7382,-1.907744,-13.05105
17
+ -.3412157,-.3902446,-631.138,-1.270229,-14.76001
18
+ .2218985,.2073287,691.1358,.8168764,12.43929
19
+ .2455925,.2266392,.1992506,.2579483,.2747237
20
+ -.7589526,-1.153008,-256.739,-2.407166,-14.14742
shared/package-files/1f/1f6a89978659a99e1b23e13d3426eed6815fb68d04745c424ca4ee80c3c74478/matfuncs.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.sparse.linalg` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = ["expm", "inv", "spsolve", "LinearOperator"] # noqa: F822
9
+
10
+
11
+ def __dir__():
12
+ return __all__
13
+
14
+
15
+ def __getattr__(name):
16
+ return _sub_module_deprecation(sub_package="sparse.linalg", module="matfuncs",
17
+ private_modules=["_matfuncs"], all=__all__,
18
+ attribute=name)
shared/package-files/1f/1f6b93fa6477edbf10cfa2880c369f2c16fd53712fcd5de308ecbca5f4237663/dense.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Floyd-Warshall algorithm for shortest paths.
2
+ """
3
+ import networkx as nx
4
+
5
+ __all__ = [
6
+ "floyd_warshall",
7
+ "floyd_warshall_predecessor_and_distance",
8
+ "reconstruct_path",
9
+ "floyd_warshall_numpy",
10
+ ]
11
+
12
+
13
+ @nx._dispatch
14
+ def floyd_warshall_numpy(G, nodelist=None, weight="weight"):
15
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
16
+
17
+ This algorithm for finding shortest paths takes advantage of
18
+ matrix representations of a graph and works well for dense
19
+ graphs where all-pairs shortest path lengths are desired.
20
+ The results are returned as a NumPy array, distance[i, j],
21
+ where i and j are the indexes of two nodes in nodelist.
22
+ The entry distance[i, j] is the distance along a shortest
23
+ path from i to j. If no path exists the distance is Inf.
24
+
25
+ Parameters
26
+ ----------
27
+ G : NetworkX graph
28
+
29
+ nodelist : list, optional (default=G.nodes)
30
+ The rows and columns are ordered by the nodes in nodelist.
31
+ If nodelist is None then the ordering is produced by G.nodes.
32
+ Nodelist should include all nodes in G.
33
+
34
+ weight: string, optional (default='weight')
35
+ Edge data key corresponding to the edge weight.
36
+
37
+ Returns
38
+ -------
39
+ distance : 2D numpy.ndarray
40
+ A numpy array of shortest path distances between nodes.
41
+ If there is no path between two nodes the value is Inf.
42
+
43
+ Notes
44
+ -----
45
+ Floyd's algorithm is appropriate for finding shortest paths in
46
+ dense graphs or graphs with negative weights when Dijkstra's
47
+ algorithm fails. This algorithm can still fail if there are negative
48
+ cycles. It has running time $O(n^3)$ with running space of $O(n^2)$.
49
+
50
+ Raises
51
+ ------
52
+ NetworkXError
53
+ If nodelist is not a list of the nodes in G.
54
+ """
55
+ import numpy as np
56
+
57
+ if nodelist is not None:
58
+ if not (len(nodelist) == len(G) == len(set(nodelist))):
59
+ raise nx.NetworkXError(
60
+ "nodelist must contain every node in G with no repeats."
61
+ "If you wanted a subgraph of G use G.subgraph(nodelist)"
62
+ )
63
+
64
+ # To handle cases when an edge has weight=0, we must make sure that
65
+ # nonedges are not given the value 0 as well.
66
+ A = nx.to_numpy_array(
67
+ G, nodelist, multigraph_weight=min, weight=weight, nonedge=np.inf
68
+ )
69
+ n, m = A.shape
70
+ np.fill_diagonal(A, 0) # diagonal elements should be zero
71
+ for i in range(n):
72
+ # The second term has the same shape as A due to broadcasting
73
+ A = np.minimum(A, A[i, :][np.newaxis, :] + A[:, i][:, np.newaxis])
74
+ return A
75
+
76
+
77
+ @nx._dispatch
78
+ def floyd_warshall_predecessor_and_distance(G, weight="weight"):
79
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
80
+
81
+ Parameters
82
+ ----------
83
+ G : NetworkX graph
84
+
85
+ weight: string, optional (default= 'weight')
86
+ Edge data key corresponding to the edge weight.
87
+
88
+ Returns
89
+ -------
90
+ predecessor,distance : dictionaries
91
+ Dictionaries, keyed by source and target, of predecessors and distances
92
+ in the shortest path.
93
+
94
+ Examples
95
+ --------
96
+ >>> G = nx.DiGraph()
97
+ >>> G.add_weighted_edges_from(
98
+ ... [
99
+ ... ("s", "u", 10),
100
+ ... ("s", "x", 5),
101
+ ... ("u", "v", 1),
102
+ ... ("u", "x", 2),
103
+ ... ("v", "y", 1),
104
+ ... ("x", "u", 3),
105
+ ... ("x", "v", 5),
106
+ ... ("x", "y", 2),
107
+ ... ("y", "s", 7),
108
+ ... ("y", "v", 6),
109
+ ... ]
110
+ ... )
111
+ >>> predecessors, _ = nx.floyd_warshall_predecessor_and_distance(G)
112
+ >>> print(nx.reconstruct_path("s", "v", predecessors))
113
+ ['s', 'x', 'u', 'v']
114
+
115
+ Notes
116
+ -----
117
+ Floyd's algorithm is appropriate for finding shortest paths
118
+ in dense graphs or graphs with negative weights when Dijkstra's algorithm
119
+ fails. This algorithm can still fail if there are negative cycles.
120
+ It has running time $O(n^3)$ with running space of $O(n^2)$.
121
+
122
+ See Also
123
+ --------
124
+ floyd_warshall
125
+ floyd_warshall_numpy
126
+ all_pairs_shortest_path
127
+ all_pairs_shortest_path_length
128
+ """
129
+ from collections import defaultdict
130
+
131
+ # dictionary-of-dictionaries representation for dist and pred
132
+ # use some defaultdict magick here
133
+ # for dist the default is the floating point inf value
134
+ dist = defaultdict(lambda: defaultdict(lambda: float("inf")))
135
+ for u in G:
136
+ dist[u][u] = 0
137
+ pred = defaultdict(dict)
138
+ # initialize path distance dictionary to be the adjacency matrix
139
+ # also set the distance to self to 0 (zero diagonal)
140
+ undirected = not G.is_directed()
141
+ for u, v, d in G.edges(data=True):
142
+ e_weight = d.get(weight, 1.0)
143
+ dist[u][v] = min(e_weight, dist[u][v])
144
+ pred[u][v] = u
145
+ if undirected:
146
+ dist[v][u] = min(e_weight, dist[v][u])
147
+ pred[v][u] = v
148
+ for w in G:
149
+ dist_w = dist[w] # save recomputation
150
+ for u in G:
151
+ dist_u = dist[u] # save recomputation
152
+ for v in G:
153
+ d = dist_u[w] + dist_w[v]
154
+ if dist_u[v] > d:
155
+ dist_u[v] = d
156
+ pred[u][v] = pred[w][v]
157
+ return dict(pred), dict(dist)
158
+
159
+
160
+ def reconstruct_path(source, target, predecessors):
161
+ """Reconstruct a path from source to target using the predecessors
162
+ dict as returned by floyd_warshall_predecessor_and_distance
163
+
164
+ Parameters
165
+ ----------
166
+ source : node
167
+ Starting node for path
168
+
169
+ target : node
170
+ Ending node for path
171
+
172
+ predecessors: dictionary
173
+ Dictionary, keyed by source and target, of predecessors in the
174
+ shortest path, as returned by floyd_warshall_predecessor_and_distance
175
+
176
+ Returns
177
+ -------
178
+ path : list
179
+ A list of nodes containing the shortest path from source to target
180
+
181
+ If source and target are the same, an empty list is returned
182
+
183
+ Notes
184
+ -----
185
+ This function is meant to give more applicability to the
186
+ floyd_warshall_predecessor_and_distance function
187
+
188
+ See Also
189
+ --------
190
+ floyd_warshall_predecessor_and_distance
191
+ """
192
+ if source == target:
193
+ return []
194
+ prev = predecessors[source]
195
+ curr = prev[target]
196
+ path = [target, curr]
197
+ while curr != source:
198
+ curr = prev[curr]
199
+ path.append(curr)
200
+ return list(reversed(path))
201
+
202
+
203
+ @nx._dispatch
204
+ def floyd_warshall(G, weight="weight"):
205
+ """Find all-pairs shortest path lengths using Floyd's algorithm.
206
+
207
+ Parameters
208
+ ----------
209
+ G : NetworkX graph
210
+
211
+ weight: string, optional (default= 'weight')
212
+ Edge data key corresponding to the edge weight.
213
+
214
+
215
+ Returns
216
+ -------
217
+ distance : dict
218
+ A dictionary, keyed by source and target, of shortest paths distances
219
+ between nodes.
220
+
221
+ Notes
222
+ -----
223
+ Floyd's algorithm is appropriate for finding shortest paths
224
+ in dense graphs or graphs with negative weights when Dijkstra's algorithm
225
+ fails. This algorithm can still fail if there are negative cycles.
226
+ It has running time $O(n^3)$ with running space of $O(n^2)$.
227
+
228
+ See Also
229
+ --------
230
+ floyd_warshall_predecessor_and_distance
231
+ floyd_warshall_numpy
232
+ all_pairs_shortest_path
233
+ all_pairs_shortest_path_length
234
+ """
235
+ # could make this its own function to reduce memory costs
236
+ return floyd_warshall_predecessor_and_distance(G, weight=weight)[1]
shared/package-files/1f/1f6dfbca13ca6ec97e0a2bf847a12dfcb5f9b815012eb0ea4c3bc14f524c79fe/middleware.pyi ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from django.http.request import HttpRequest
2
+ from django.http.response import HttpResponse
3
+ from django.utils.deprecation import MiddlewareMixin
4
+
5
+ class MessageMiddleware(MiddlewareMixin):
6
+ def process_request(self, request: HttpRequest) -> None: ...
7
+ def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: ...
shared/package-files/1f/1f6e42785e06337150ab407abb7710a7515918088695b38e86016a9f84480059/_svm_cython_blas_helpers.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef _SVM_CYTHON_BLAS_HELPERS_H
2
+ #define _SVM_CYTHON_BLAS_HELPERS_H
3
+
4
+ typedef double (*dot_func)(int, const double*, int, const double*, int);
5
+ typedef struct BlasFunctions{
6
+ dot_func dot;
7
+ } BlasFunctions;
8
+
9
+ #endif
shared/package-files/1f/1f726d57e3b9fd25ed45809804e4a07ada87bb4ed41141d1674567b77dc78e43/hp2 ADDED
Binary file (1.37 kB). View file
 
shared/package-files/1f/1f726d57e3b9fd25ed45809804e4a07ada87bb4ed41141d1674567b77dc78e43/hpex2 ADDED
Binary file (1.37 kB). View file
 
shared/package-files/1f/1f771e18fa4065f1f6fa66eefae63b300ea3b1e93e1c45182c1bd878b4ce3c40/environment.yml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ name: to-save
2
+ dependencies:
3
+ - python
shared/package-files/1f/1f795d89c23fae196fd2bdd5169556b542fa5f7d16cb9f7abfbfd81f3dac11d8/langturkishmodel.py ADDED
The diff for this file is too large to render. See raw diff
 
shared/package-files/1f/1f7be1029f426e7fbb26e4c6a334be3301a83a511c7757c72a63f4a2ad19d946/_param_validation.py ADDED
@@ -0,0 +1,910 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: The scikit-learn developers
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ import functools
5
+ import math
6
+ import operator
7
+ import re
8
+ from abc import ABC, abstractmethod
9
+ from collections.abc import Iterable
10
+ from inspect import signature
11
+ from numbers import Integral, Real
12
+
13
+ import numpy as np
14
+ from scipy.sparse import csr_matrix, issparse
15
+
16
+ from .._config import config_context, get_config
17
+ from .validation import _is_arraylike_not_scalar
18
+
19
+
20
+ class InvalidParameterError(ValueError, TypeError):
21
+ """Custom exception to be raised when the parameter of a class/method/function
22
+ does not have a valid type or value.
23
+ """
24
+
25
+ # Inherits from ValueError and TypeError to keep backward compatibility.
26
+
27
+
28
+ def validate_parameter_constraints(parameter_constraints, params, caller_name):
29
+ """Validate types and values of given parameters.
30
+
31
+ Parameters
32
+ ----------
33
+ parameter_constraints : dict or {"no_validation"}
34
+ If "no_validation", validation is skipped for this parameter.
35
+
36
+ If a dict, it must be a dictionary `param_name: list of constraints`.
37
+ A parameter is valid if it satisfies one of the constraints from the list.
38
+ Constraints can be:
39
+ - an Interval object, representing a continuous or discrete range of numbers
40
+ - the string "array-like"
41
+ - the string "sparse matrix"
42
+ - the string "random_state"
43
+ - callable
44
+ - None, meaning that None is a valid value for the parameter
45
+ - any type, meaning that any instance of this type is valid
46
+ - an Options object, representing a set of elements of a given type
47
+ - a StrOptions object, representing a set of strings
48
+ - the string "boolean"
49
+ - the string "verbose"
50
+ - the string "cv_object"
51
+ - the string "nan"
52
+ - a MissingValues object representing markers for missing values
53
+ - a HasMethods object, representing method(s) an object must have
54
+ - a Hidden object, representing a constraint not meant to be exposed to the user
55
+
56
+ params : dict
57
+ A dictionary `param_name: param_value`. The parameters to validate against the
58
+ constraints.
59
+
60
+ caller_name : str
61
+ The name of the estimator or function or method that called this function.
62
+ """
63
+ for param_name, param_val in params.items():
64
+ # We allow parameters to not have a constraint so that third party estimators
65
+ # can inherit from sklearn estimators without having to necessarily use the
66
+ # validation tools.
67
+ if param_name not in parameter_constraints:
68
+ continue
69
+
70
+ constraints = parameter_constraints[param_name]
71
+
72
+ if constraints == "no_validation":
73
+ continue
74
+
75
+ constraints = [make_constraint(constraint) for constraint in constraints]
76
+
77
+ for constraint in constraints:
78
+ if constraint.is_satisfied_by(param_val):
79
+ # this constraint is satisfied, no need to check further.
80
+ break
81
+ else:
82
+ # No constraint is satisfied, raise with an informative message.
83
+
84
+ # Ignore constraints that we don't want to expose in the error message,
85
+ # i.e. options that are for internal purpose or not officially supported.
86
+ constraints = [
87
+ constraint for constraint in constraints if not constraint.hidden
88
+ ]
89
+
90
+ if len(constraints) == 1:
91
+ constraints_str = f"{constraints[0]}"
92
+ else:
93
+ constraints_str = (
94
+ f"{', '.join([str(c) for c in constraints[:-1]])} or"
95
+ f" {constraints[-1]}"
96
+ )
97
+
98
+ raise InvalidParameterError(
99
+ f"The {param_name!r} parameter of {caller_name} must be"
100
+ f" {constraints_str}. Got {param_val!r} instead."
101
+ )
102
+
103
+
104
+ def make_constraint(constraint):
105
+ """Convert the constraint into the appropriate Constraint object.
106
+
107
+ Parameters
108
+ ----------
109
+ constraint : object
110
+ The constraint to convert.
111
+
112
+ Returns
113
+ -------
114
+ constraint : instance of _Constraint
115
+ The converted constraint.
116
+ """
117
+ if isinstance(constraint, str) and constraint == "array-like":
118
+ return _ArrayLikes()
119
+ if isinstance(constraint, str) and constraint == "sparse matrix":
120
+ return _SparseMatrices()
121
+ if isinstance(constraint, str) and constraint == "random_state":
122
+ return _RandomStates()
123
+ if constraint is callable:
124
+ return _Callables()
125
+ if constraint is None:
126
+ return _NoneConstraint()
127
+ if isinstance(constraint, type):
128
+ return _InstancesOf(constraint)
129
+ if isinstance(
130
+ constraint, (Interval, StrOptions, Options, HasMethods, MissingValues)
131
+ ):
132
+ return constraint
133
+ if isinstance(constraint, str) and constraint == "boolean":
134
+ return _Booleans()
135
+ if isinstance(constraint, str) and constraint == "verbose":
136
+ return _VerboseHelper()
137
+ if isinstance(constraint, str) and constraint == "cv_object":
138
+ return _CVObjects()
139
+ if isinstance(constraint, Hidden):
140
+ constraint = make_constraint(constraint.constraint)
141
+ constraint.hidden = True
142
+ return constraint
143
+ if (isinstance(constraint, str) and constraint == "nan") or (
144
+ isinstance(constraint, float) and np.isnan(constraint)
145
+ ):
146
+ return _NanConstraint()
147
+ raise ValueError(f"Unknown constraint type: {constraint}")
148
+
149
+
150
+ def validate_params(parameter_constraints, *, prefer_skip_nested_validation):
151
+ """Decorator to validate types and values of functions and methods.
152
+
153
+ Parameters
154
+ ----------
155
+ parameter_constraints : dict
156
+ A dictionary `param_name: list of constraints`. See the docstring of
157
+ `validate_parameter_constraints` for a description of the accepted constraints.
158
+
159
+ Note that the *args and **kwargs parameters are not validated and must not be
160
+ present in the parameter_constraints dictionary.
161
+
162
+ prefer_skip_nested_validation : bool
163
+ If True, the validation of parameters of inner estimators or functions
164
+ called by the decorated function will be skipped.
165
+
166
+ This is useful to avoid validating many times the parameters passed by the
167
+ user from the public facing API. It's also useful to avoid validating
168
+ parameters that we pass internally to inner functions that are guaranteed to
169
+ be valid by the test suite.
170
+
171
+ It should be set to True for most functions, except for those that receive
172
+ non-validated objects as parameters or that are just wrappers around classes
173
+ because they only perform a partial validation.
174
+
175
+ Returns
176
+ -------
177
+ decorated_function : function or method
178
+ The decorated function.
179
+ """
180
+
181
+ def decorator(func):
182
+ # The dict of parameter constraints is set as an attribute of the function
183
+ # to make it possible to dynamically introspect the constraints for
184
+ # automatic testing.
185
+ setattr(func, "_skl_parameter_constraints", parameter_constraints)
186
+
187
+ @functools.wraps(func)
188
+ def wrapper(*args, **kwargs):
189
+ global_skip_validation = get_config()["skip_parameter_validation"]
190
+ if global_skip_validation:
191
+ return func(*args, **kwargs)
192
+
193
+ func_sig = signature(func)
194
+
195
+ # Map *args/**kwargs to the function signature
196
+ params = func_sig.bind(*args, **kwargs)
197
+ params.apply_defaults()
198
+
199
+ # ignore self/cls and positional/keyword markers
200
+ to_ignore = [
201
+ p.name
202
+ for p in func_sig.parameters.values()
203
+ if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
204
+ ]
205
+ to_ignore += ["self", "cls"]
206
+ params = {k: v for k, v in params.arguments.items() if k not in to_ignore}
207
+
208
+ validate_parameter_constraints(
209
+ parameter_constraints, params, caller_name=func.__qualname__
210
+ )
211
+
212
+ try:
213
+ with config_context(
214
+ skip_parameter_validation=(
215
+ prefer_skip_nested_validation or global_skip_validation
216
+ )
217
+ ):
218
+ return func(*args, **kwargs)
219
+ except InvalidParameterError as e:
220
+ # When the function is just a wrapper around an estimator, we allow
221
+ # the function to delegate validation to the estimator, but we replace
222
+ # the name of the estimator by the name of the function in the error
223
+ # message to avoid confusion.
224
+ msg = re.sub(
225
+ r"parameter of \w+ must be",
226
+ f"parameter of {func.__qualname__} must be",
227
+ str(e),
228
+ )
229
+ raise InvalidParameterError(msg) from e
230
+
231
+ return wrapper
232
+
233
+ return decorator
234
+
235
+
236
+ class RealNotInt(Real):
237
+ """A type that represents reals that are not instances of int.
238
+
239
+ Behaves like float, but also works with values extracted from numpy arrays.
240
+ isintance(1, RealNotInt) -> False
241
+ isinstance(1.0, RealNotInt) -> True
242
+ """
243
+
244
+
245
+ RealNotInt.register(float)
246
+
247
+
248
+ def _type_name(t):
249
+ """Convert type into human readable string."""
250
+ module = t.__module__
251
+ qualname = t.__qualname__
252
+ if module == "builtins":
253
+ return qualname
254
+ elif t == Real:
255
+ return "float"
256
+ elif t == Integral:
257
+ return "int"
258
+ return f"{module}.{qualname}"
259
+
260
+
261
+ class _Constraint(ABC):
262
+ """Base class for the constraint objects."""
263
+
264
+ def __init__(self):
265
+ self.hidden = False
266
+
267
+ @abstractmethod
268
+ def is_satisfied_by(self, val):
269
+ """Whether or not a value satisfies the constraint.
270
+
271
+ Parameters
272
+ ----------
273
+ val : object
274
+ The value to check.
275
+
276
+ Returns
277
+ -------
278
+ is_satisfied : bool
279
+ Whether or not the constraint is satisfied by this value.
280
+ """
281
+
282
+ @abstractmethod
283
+ def __str__(self):
284
+ """A human readable representational string of the constraint."""
285
+
286
+
287
+ class _InstancesOf(_Constraint):
288
+ """Constraint representing instances of a given type.
289
+
290
+ Parameters
291
+ ----------
292
+ type : type
293
+ The valid type.
294
+ """
295
+
296
+ def __init__(self, type):
297
+ super().__init__()
298
+ self.type = type
299
+
300
+ def is_satisfied_by(self, val):
301
+ return isinstance(val, self.type)
302
+
303
+ def __str__(self):
304
+ return f"an instance of {_type_name(self.type)!r}"
305
+
306
+
307
+ class _NoneConstraint(_Constraint):
308
+ """Constraint representing the None singleton."""
309
+
310
+ def is_satisfied_by(self, val):
311
+ return val is None
312
+
313
+ def __str__(self):
314
+ return "None"
315
+
316
+
317
+ class _NanConstraint(_Constraint):
318
+ """Constraint representing the indicator `np.nan`."""
319
+
320
+ def is_satisfied_by(self, val):
321
+ return (
322
+ not isinstance(val, Integral) and isinstance(val, Real) and math.isnan(val)
323
+ )
324
+
325
+ def __str__(self):
326
+ return "numpy.nan"
327
+
328
+
329
+ class _PandasNAConstraint(_Constraint):
330
+ """Constraint representing the indicator `pd.NA`."""
331
+
332
+ def is_satisfied_by(self, val):
333
+ try:
334
+ import pandas as pd
335
+
336
+ return isinstance(val, type(pd.NA)) and pd.isna(val)
337
+ except ImportError:
338
+ return False
339
+
340
+ def __str__(self):
341
+ return "pandas.NA"
342
+
343
+
344
+ class Options(_Constraint):
345
+ """Constraint representing a finite set of instances of a given type.
346
+
347
+ Parameters
348
+ ----------
349
+ type : type
350
+
351
+ options : set
352
+ The set of valid scalars.
353
+
354
+ deprecated : set or None, default=None
355
+ A subset of the `options` to mark as deprecated in the string
356
+ representation of the constraint.
357
+ """
358
+
359
+ def __init__(self, type, options, *, deprecated=None):
360
+ super().__init__()
361
+ self.type = type
362
+ self.options = options
363
+ self.deprecated = deprecated or set()
364
+
365
+ if self.deprecated - self.options:
366
+ raise ValueError("The deprecated options must be a subset of the options.")
367
+
368
+ def is_satisfied_by(self, val):
369
+ return isinstance(val, self.type) and val in self.options
370
+
371
+ def _mark_if_deprecated(self, option):
372
+ """Add a deprecated mark to an option if needed."""
373
+ option_str = f"{option!r}"
374
+ if option in self.deprecated:
375
+ option_str = f"{option_str} (deprecated)"
376
+ return option_str
377
+
378
+ def __str__(self):
379
+ options_str = (
380
+ f"{', '.join([self._mark_if_deprecated(o) for o in self.options])}"
381
+ )
382
+ return f"a {_type_name(self.type)} among {{{options_str}}}"
383
+
384
+
385
+ class StrOptions(Options):
386
+ """Constraint representing a finite set of strings.
387
+
388
+ Parameters
389
+ ----------
390
+ options : set of str
391
+ The set of valid strings.
392
+
393
+ deprecated : set of str or None, default=None
394
+ A subset of the `options` to mark as deprecated in the string
395
+ representation of the constraint.
396
+ """
397
+
398
+ def __init__(self, options, *, deprecated=None):
399
+ super().__init__(type=str, options=options, deprecated=deprecated)
400
+
401
+
402
+ class Interval(_Constraint):
403
+ """Constraint representing a typed interval.
404
+
405
+ Parameters
406
+ ----------
407
+ type : {numbers.Integral, numbers.Real, RealNotInt}
408
+ The set of numbers in which to set the interval.
409
+
410
+ If RealNotInt, only reals that don't have the integer type
411
+ are allowed. For example 1.0 is allowed but 1 is not.
412
+
413
+ left : float or int or None
414
+ The left bound of the interval. None means left bound is -∞.
415
+
416
+ right : float, int or None
417
+ The right bound of the interval. None means right bound is +∞.
418
+
419
+ closed : {"left", "right", "both", "neither"}
420
+ Whether the interval is open or closed. Possible choices are:
421
+
422
+ - `"left"`: the interval is closed on the left and open on the right.
423
+ It is equivalent to the interval `[ left, right )`.
424
+ - `"right"`: the interval is closed on the right and open on the left.
425
+ It is equivalent to the interval `( left, right ]`.
426
+ - `"both"`: the interval is closed.
427
+ It is equivalent to the interval `[ left, right ]`.
428
+ - `"neither"`: the interval is open.
429
+ It is equivalent to the interval `( left, right )`.
430
+
431
+ Notes
432
+ -----
433
+ Setting a bound to `None` and setting the interval closed is valid. For instance,
434
+ strictly speaking, `Interval(Real, 0, None, closed="both")` corresponds to
435
+ `[0, +∞) U {+∞}`.
436
+ """
437
+
438
+ def __init__(self, type, left, right, *, closed):
439
+ super().__init__()
440
+ self.type = type
441
+ self.left = left
442
+ self.right = right
443
+ self.closed = closed
444
+
445
+ self._check_params()
446
+
447
+ def _check_params(self):
448
+ if self.type not in (Integral, Real, RealNotInt):
449
+ raise ValueError(
450
+ "type must be either numbers.Integral, numbers.Real or RealNotInt."
451
+ f" Got {self.type} instead."
452
+ )
453
+
454
+ if self.closed not in ("left", "right", "both", "neither"):
455
+ raise ValueError(
456
+ "closed must be either 'left', 'right', 'both' or 'neither'. "
457
+ f"Got {self.closed} instead."
458
+ )
459
+
460
+ if self.type is Integral:
461
+ suffix = "for an interval over the integers."
462
+ if self.left is not None and not isinstance(self.left, Integral):
463
+ raise TypeError(f"Expecting left to be an int {suffix}")
464
+ if self.right is not None and not isinstance(self.right, Integral):
465
+ raise TypeError(f"Expecting right to be an int {suffix}")
466
+ if self.left is None and self.closed in ("left", "both"):
467
+ raise ValueError(
468
+ f"left can't be None when closed == {self.closed} {suffix}"
469
+ )
470
+ if self.right is None and self.closed in ("right", "both"):
471
+ raise ValueError(
472
+ f"right can't be None when closed == {self.closed} {suffix}"
473
+ )
474
+ else:
475
+ if self.left is not None and not isinstance(self.left, Real):
476
+ raise TypeError("Expecting left to be a real number.")
477
+ if self.right is not None and not isinstance(self.right, Real):
478
+ raise TypeError("Expecting right to be a real number.")
479
+
480
+ if self.right is not None and self.left is not None and self.right <= self.left:
481
+ raise ValueError(
482
+ f"right can't be less than left. Got left={self.left} and "
483
+ f"right={self.right}"
484
+ )
485
+
486
+ def __contains__(self, val):
487
+ if not isinstance(val, Integral) and np.isnan(val):
488
+ return False
489
+
490
+ left_cmp = operator.lt if self.closed in ("left", "both") else operator.le
491
+ right_cmp = operator.gt if self.closed in ("right", "both") else operator.ge
492
+
493
+ left = -np.inf if self.left is None else self.left
494
+ right = np.inf if self.right is None else self.right
495
+
496
+ if left_cmp(val, left):
497
+ return False
498
+ if right_cmp(val, right):
499
+ return False
500
+ return True
501
+
502
+ def is_satisfied_by(self, val):
503
+ if not isinstance(val, self.type):
504
+ return False
505
+
506
+ return val in self
507
+
508
+ def __str__(self):
509
+ type_str = "an int" if self.type is Integral else "a float"
510
+ left_bracket = "[" if self.closed in ("left", "both") else "("
511
+ left_bound = "-inf" if self.left is None else self.left
512
+ right_bound = "inf" if self.right is None else self.right
513
+ right_bracket = "]" if self.closed in ("right", "both") else ")"
514
+
515
+ # better repr if the bounds were given as integers
516
+ if not self.type == Integral and isinstance(self.left, Real):
517
+ left_bound = float(left_bound)
518
+ if not self.type == Integral and isinstance(self.right, Real):
519
+ right_bound = float(right_bound)
520
+
521
+ return (
522
+ f"{type_str} in the range "
523
+ f"{left_bracket}{left_bound}, {right_bound}{right_bracket}"
524
+ )
525
+
526
+
527
+ class _ArrayLikes(_Constraint):
528
+ """Constraint representing array-likes"""
529
+
530
+ def is_satisfied_by(self, val):
531
+ return _is_arraylike_not_scalar(val)
532
+
533
+ def __str__(self):
534
+ return "an array-like"
535
+
536
+
537
+ class _SparseMatrices(_Constraint):
538
+ """Constraint representing sparse matrices."""
539
+
540
+ def is_satisfied_by(self, val):
541
+ return issparse(val)
542
+
543
+ def __str__(self):
544
+ return "a sparse matrix"
545
+
546
+
547
+ class _Callables(_Constraint):
548
+ """Constraint representing callables."""
549
+
550
+ def is_satisfied_by(self, val):
551
+ return callable(val)
552
+
553
+ def __str__(self):
554
+ return "a callable"
555
+
556
+
557
+ class _RandomStates(_Constraint):
558
+ """Constraint representing random states.
559
+
560
+ Convenience class for
561
+ [Interval(Integral, 0, 2**32 - 1, closed="both"), np.random.RandomState, None]
562
+ """
563
+
564
+ def __init__(self):
565
+ super().__init__()
566
+ self._constraints = [
567
+ Interval(Integral, 0, 2**32 - 1, closed="both"),
568
+ _InstancesOf(np.random.RandomState),
569
+ _NoneConstraint(),
570
+ ]
571
+
572
+ def is_satisfied_by(self, val):
573
+ return any(c.is_satisfied_by(val) for c in self._constraints)
574
+
575
+ def __str__(self):
576
+ return (
577
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
578
+ f" {self._constraints[-1]}"
579
+ )
580
+
581
+
582
+ class _Booleans(_Constraint):
583
+ """Constraint representing boolean likes.
584
+
585
+ Convenience class for
586
+ [bool, np.bool_]
587
+ """
588
+
589
+ def __init__(self):
590
+ super().__init__()
591
+ self._constraints = [
592
+ _InstancesOf(bool),
593
+ _InstancesOf(np.bool_),
594
+ ]
595
+
596
+ def is_satisfied_by(self, val):
597
+ return any(c.is_satisfied_by(val) for c in self._constraints)
598
+
599
+ def __str__(self):
600
+ return (
601
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
602
+ f" {self._constraints[-1]}"
603
+ )
604
+
605
+
606
+ class _VerboseHelper(_Constraint):
607
+ """Helper constraint for the verbose parameter.
608
+
609
+ Convenience class for
610
+ [Interval(Integral, 0, None, closed="left"), bool, numpy.bool_]
611
+ """
612
+
613
+ def __init__(self):
614
+ super().__init__()
615
+ self._constraints = [
616
+ Interval(Integral, 0, None, closed="left"),
617
+ _InstancesOf(bool),
618
+ _InstancesOf(np.bool_),
619
+ ]
620
+
621
+ def is_satisfied_by(self, val):
622
+ return any(c.is_satisfied_by(val) for c in self._constraints)
623
+
624
+ def __str__(self):
625
+ return (
626
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
627
+ f" {self._constraints[-1]}"
628
+ )
629
+
630
+
631
+ class MissingValues(_Constraint):
632
+ """Helper constraint for the `missing_values` parameters.
633
+
634
+ Convenience for
635
+ [
636
+ Integral,
637
+ Interval(Real, None, None, closed="both"),
638
+ str, # when numeric_only is False
639
+ None, # when numeric_only is False
640
+ _NanConstraint(),
641
+ _PandasNAConstraint(),
642
+ ]
643
+
644
+ Parameters
645
+ ----------
646
+ numeric_only : bool, default=False
647
+ Whether to consider only numeric missing value markers.
648
+
649
+ """
650
+
651
+ def __init__(self, numeric_only=False):
652
+ super().__init__()
653
+
654
+ self.numeric_only = numeric_only
655
+
656
+ self._constraints = [
657
+ _InstancesOf(Integral),
658
+ # we use an interval of Real to ignore np.nan that has its own constraint
659
+ Interval(Real, None, None, closed="both"),
660
+ _NanConstraint(),
661
+ _PandasNAConstraint(),
662
+ ]
663
+ if not self.numeric_only:
664
+ self._constraints.extend([_InstancesOf(str), _NoneConstraint()])
665
+
666
+ def is_satisfied_by(self, val):
667
+ return any(c.is_satisfied_by(val) for c in self._constraints)
668
+
669
+ def __str__(self):
670
+ return (
671
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
672
+ f" {self._constraints[-1]}"
673
+ )
674
+
675
+
676
+ class HasMethods(_Constraint):
677
+ """Constraint representing objects that expose specific methods.
678
+
679
+ It is useful for parameters following a protocol and where we don't want to impose
680
+ an affiliation to a specific module or class.
681
+
682
+ Parameters
683
+ ----------
684
+ methods : str or list of str
685
+ The method(s) that the object is expected to expose.
686
+ """
687
+
688
+ @validate_params(
689
+ {"methods": [str, list]},
690
+ prefer_skip_nested_validation=True,
691
+ )
692
+ def __init__(self, methods):
693
+ super().__init__()
694
+ if isinstance(methods, str):
695
+ methods = [methods]
696
+ self.methods = methods
697
+
698
+ def is_satisfied_by(self, val):
699
+ return all(callable(getattr(val, method, None)) for method in self.methods)
700
+
701
+ def __str__(self):
702
+ if len(self.methods) == 1:
703
+ methods = f"{self.methods[0]!r}"
704
+ else:
705
+ methods = (
706
+ f"{', '.join([repr(m) for m in self.methods[:-1]])} and"
707
+ f" {self.methods[-1]!r}"
708
+ )
709
+ return f"an object implementing {methods}"
710
+
711
+
712
+ class _IterablesNotString(_Constraint):
713
+ """Constraint representing iterables that are not strings."""
714
+
715
+ def is_satisfied_by(self, val):
716
+ return isinstance(val, Iterable) and not isinstance(val, str)
717
+
718
+ def __str__(self):
719
+ return "an iterable"
720
+
721
+
722
+ class _CVObjects(_Constraint):
723
+ """Constraint representing cv objects.
724
+
725
+ Convenient class for
726
+ [
727
+ Interval(Integral, 2, None, closed="left"),
728
+ HasMethods(["split", "get_n_splits"]),
729
+ _IterablesNotString(),
730
+ None,
731
+ ]
732
+ """
733
+
734
+ def __init__(self):
735
+ super().__init__()
736
+ self._constraints = [
737
+ Interval(Integral, 2, None, closed="left"),
738
+ HasMethods(["split", "get_n_splits"]),
739
+ _IterablesNotString(),
740
+ _NoneConstraint(),
741
+ ]
742
+
743
+ def is_satisfied_by(self, val):
744
+ return any(c.is_satisfied_by(val) for c in self._constraints)
745
+
746
+ def __str__(self):
747
+ return (
748
+ f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
749
+ f" {self._constraints[-1]}"
750
+ )
751
+
752
+
753
+ class Hidden:
754
+ """Class encapsulating a constraint not meant to be exposed to the user.
755
+
756
+ Parameters
757
+ ----------
758
+ constraint : str or _Constraint instance
759
+ The constraint to be used internally.
760
+ """
761
+
762
+ def __init__(self, constraint):
763
+ self.constraint = constraint
764
+
765
+
766
+ def generate_invalid_param_val(constraint):
767
+ """Return a value that does not satisfy the constraint.
768
+
769
+ Raises a NotImplementedError if there exists no invalid value for this constraint.
770
+
771
+ This is only useful for testing purpose.
772
+
773
+ Parameters
774
+ ----------
775
+ constraint : _Constraint instance
776
+ The constraint to generate a value for.
777
+
778
+ Returns
779
+ -------
780
+ val : object
781
+ A value that does not satisfy the constraint.
782
+ """
783
+ if isinstance(constraint, StrOptions):
784
+ return f"not {' or '.join(constraint.options)}"
785
+
786
+ if isinstance(constraint, MissingValues):
787
+ return np.array([1, 2, 3])
788
+
789
+ if isinstance(constraint, _VerboseHelper):
790
+ return -1
791
+
792
+ if isinstance(constraint, HasMethods):
793
+ return type("HasNotMethods", (), {})()
794
+
795
+ if isinstance(constraint, _IterablesNotString):
796
+ return "a string"
797
+
798
+ if isinstance(constraint, _CVObjects):
799
+ return "not a cv object"
800
+
801
+ if isinstance(constraint, Interval) and constraint.type is Integral:
802
+ if constraint.left is not None:
803
+ return constraint.left - 1
804
+ if constraint.right is not None:
805
+ return constraint.right + 1
806
+
807
+ # There's no integer outside (-inf, +inf)
808
+ raise NotImplementedError
809
+
810
+ if isinstance(constraint, Interval) and constraint.type in (Real, RealNotInt):
811
+ if constraint.left is not None:
812
+ return constraint.left - 1e-6
813
+ if constraint.right is not None:
814
+ return constraint.right + 1e-6
815
+
816
+ # bounds are -inf, +inf
817
+ if constraint.closed in ("right", "neither"):
818
+ return -np.inf
819
+ if constraint.closed in ("left", "neither"):
820
+ return np.inf
821
+
822
+ # interval is [-inf, +inf]
823
+ return np.nan
824
+
825
+ raise NotImplementedError
826
+
827
+
828
+ def generate_valid_param(constraint):
829
+ """Return a value that does satisfy a constraint.
830
+
831
+ This is only useful for testing purpose.
832
+
833
+ Parameters
834
+ ----------
835
+ constraint : Constraint instance
836
+ The constraint to generate a value for.
837
+
838
+ Returns
839
+ -------
840
+ val : object
841
+ A value that does satisfy the constraint.
842
+ """
843
+ if isinstance(constraint, _ArrayLikes):
844
+ return np.array([1, 2, 3])
845
+
846
+ if isinstance(constraint, _SparseMatrices):
847
+ return csr_matrix([[0, 1], [1, 0]])
848
+
849
+ if isinstance(constraint, _RandomStates):
850
+ return np.random.RandomState(42)
851
+
852
+ if isinstance(constraint, _Callables):
853
+ return lambda x: x
854
+
855
+ if isinstance(constraint, _NoneConstraint):
856
+ return None
857
+
858
+ if isinstance(constraint, _InstancesOf):
859
+ if constraint.type is np.ndarray:
860
+ # special case for ndarray since it can't be instantiated without arguments
861
+ return np.array([1, 2, 3])
862
+
863
+ if constraint.type in (Integral, Real):
864
+ # special case for Integral and Real since they are abstract classes
865
+ return 1
866
+
867
+ return constraint.type()
868
+
869
+ if isinstance(constraint, _Booleans):
870
+ return True
871
+
872
+ if isinstance(constraint, _VerboseHelper):
873
+ return 1
874
+
875
+ if isinstance(constraint, MissingValues) and constraint.numeric_only:
876
+ return np.nan
877
+
878
+ if isinstance(constraint, MissingValues) and not constraint.numeric_only:
879
+ return "missing"
880
+
881
+ if isinstance(constraint, HasMethods):
882
+ return type(
883
+ "ValidHasMethods", (), {m: lambda self: None for m in constraint.methods}
884
+ )()
885
+
886
+ if isinstance(constraint, _IterablesNotString):
887
+ return [1, 2, 3]
888
+
889
+ if isinstance(constraint, _CVObjects):
890
+ return 5
891
+
892
+ if isinstance(constraint, Options): # includes StrOptions
893
+ for option in constraint.options:
894
+ return option
895
+
896
+ if isinstance(constraint, Interval):
897
+ interval = constraint
898
+ if interval.left is None and interval.right is None:
899
+ return 0
900
+ elif interval.left is None:
901
+ return interval.right - 1
902
+ elif interval.right is None:
903
+ return interval.left + 1
904
+ else:
905
+ if interval.type is Real:
906
+ return (interval.left + interval.right) / 2
907
+ else:
908
+ return interval.left + 1
909
+
910
+ raise ValueError(f"Unknown constraint type: {constraint}")
shared/package-files/1f/1f7c72d37dca932cd875eb3c732d17c01de6273fd30f8b38f85e236ed94cd2e3/pprint.py ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Author: Fred L. Drake, Jr.
2
+ # fdrake@acm.org
3
+ #
4
+ # This is a simple little module I wrote to make life easier. I didn't
5
+ # see anything quite like it in the library, though I may have overlooked
6
+ # something. I wrote this when I was trying to read some heavily nested
7
+ # tuples with fairly non-descriptive content. This is modeled very much
8
+ # after Lisp/Scheme - style pretty-printing of lists. If you find it
9
+ # useful, thank small children who sleep at night.
10
+
11
+ """Support to pretty-print lists, tuples, & dictionaries recursively.
12
+
13
+ Very simple, but useful, especially in debugging data structures.
14
+
15
+ Classes
16
+ -------
17
+
18
+ PrettyPrinter()
19
+ Handle pretty-printing operations onto a stream using a configured
20
+ set of formatting parameters.
21
+
22
+ Functions
23
+ ---------
24
+
25
+ pformat()
26
+ Format a Python object into a pretty-printed representation.
27
+
28
+ pprint()
29
+ Pretty-print a Python object to a stream [default is sys.stdout].
30
+
31
+ saferepr()
32
+ Generate a 'standard' repr()-like value, but protect against recursive
33
+ data structures.
34
+
35
+ """
36
+
37
+ import collections as _collections
38
+ import dataclasses as _dataclasses
39
+ import re
40
+ import sys as _sys
41
+ import types as _types
42
+ from io import StringIO as _StringIO
43
+
44
+ __all__ = ["pprint","pformat","isreadable","isrecursive","saferepr",
45
+ "PrettyPrinter", "pp"]
46
+
47
+
48
+ def pprint(object, stream=None, indent=1, width=80, depth=None, *,
49
+ compact=False, sort_dicts=True, underscore_numbers=False):
50
+ """Pretty-print a Python object to a stream [default is sys.stdout]."""
51
+ printer = PrettyPrinter(
52
+ stream=stream, indent=indent, width=width, depth=depth,
53
+ compact=compact, sort_dicts=sort_dicts,
54
+ underscore_numbers=underscore_numbers)
55
+ printer.pprint(object)
56
+
57
+ def pformat(object, indent=1, width=80, depth=None, *,
58
+ compact=False, sort_dicts=True, underscore_numbers=False):
59
+ """Format a Python object into a pretty-printed representation."""
60
+ return PrettyPrinter(indent=indent, width=width, depth=depth,
61
+ compact=compact, sort_dicts=sort_dicts,
62
+ underscore_numbers=underscore_numbers).pformat(object)
63
+
64
+ def pp(object, *args, sort_dicts=False, **kwargs):
65
+ """Pretty-print a Python object"""
66
+ pprint(object, *args, sort_dicts=sort_dicts, **kwargs)
67
+
68
+ def saferepr(object):
69
+ """Version of repr() which can handle recursive data structures."""
70
+ return PrettyPrinter()._safe_repr(object, {}, None, 0)[0]
71
+
72
+ def isreadable(object):
73
+ """Determine if saferepr(object) is readable by eval()."""
74
+ return PrettyPrinter()._safe_repr(object, {}, None, 0)[1]
75
+
76
+ def isrecursive(object):
77
+ """Determine if object requires a recursive representation."""
78
+ return PrettyPrinter()._safe_repr(object, {}, None, 0)[2]
79
+
80
+ class _safe_key:
81
+ """Helper function for key functions when sorting unorderable objects.
82
+
83
+ The wrapped-object will fallback to a Py2.x style comparison for
84
+ unorderable types (sorting first comparing the type name and then by
85
+ the obj ids). Does not work recursively, so dict.items() must have
86
+ _safe_key applied to both the key and the value.
87
+
88
+ """
89
+
90
+ __slots__ = ['obj']
91
+
92
+ def __init__(self, obj):
93
+ self.obj = obj
94
+
95
+ def __lt__(self, other):
96
+ try:
97
+ return self.obj < other.obj
98
+ except TypeError:
99
+ return ((str(type(self.obj)), id(self.obj)) < \
100
+ (str(type(other.obj)), id(other.obj)))
101
+
102
+ def _safe_tuple(t):
103
+ "Helper function for comparing 2-tuples"
104
+ return _safe_key(t[0]), _safe_key(t[1])
105
+
106
+ class PrettyPrinter:
107
+ def __init__(self, indent=1, width=80, depth=None, stream=None, *,
108
+ compact=False, sort_dicts=True, underscore_numbers=False):
109
+ """Handle pretty printing operations onto a stream using a set of
110
+ configured parameters.
111
+
112
+ indent
113
+ Number of spaces to indent for each level of nesting.
114
+
115
+ width
116
+ Attempted maximum number of columns in the output.
117
+
118
+ depth
119
+ The maximum depth to print out nested structures.
120
+
121
+ stream
122
+ The desired output stream. If omitted (or false), the standard
123
+ output stream available at construction will be used.
124
+
125
+ compact
126
+ If true, several items will be combined in one line.
127
+
128
+ sort_dicts
129
+ If true, dict keys are sorted.
130
+
131
+ """
132
+ indent = int(indent)
133
+ width = int(width)
134
+ if indent < 0:
135
+ raise ValueError('indent must be >= 0')
136
+ if depth is not None and depth <= 0:
137
+ raise ValueError('depth must be > 0')
138
+ if not width:
139
+ raise ValueError('width must be != 0')
140
+ self._depth = depth
141
+ self._indent_per_level = indent
142
+ self._width = width
143
+ if stream is not None:
144
+ self._stream = stream
145
+ else:
146
+ self._stream = _sys.stdout
147
+ self._compact = bool(compact)
148
+ self._sort_dicts = sort_dicts
149
+ self._underscore_numbers = underscore_numbers
150
+
151
+ def pprint(self, object):
152
+ self._format(object, self._stream, 0, 0, {}, 0)
153
+ self._stream.write("\n")
154
+
155
+ def pformat(self, object):
156
+ sio = _StringIO()
157
+ self._format(object, sio, 0, 0, {}, 0)
158
+ return sio.getvalue()
159
+
160
+ def isrecursive(self, object):
161
+ return self.format(object, {}, 0, 0)[2]
162
+
163
+ def isreadable(self, object):
164
+ s, readable, recursive = self.format(object, {}, 0, 0)
165
+ return readable and not recursive
166
+
167
+ def _format(self, object, stream, indent, allowance, context, level):
168
+ objid = id(object)
169
+ if objid in context:
170
+ stream.write(_recursion(object))
171
+ self._recursive = True
172
+ self._readable = False
173
+ return
174
+ rep = self._repr(object, context, level)
175
+ max_width = self._width - indent - allowance
176
+ if len(rep) > max_width:
177
+ p = self._dispatch.get(type(object).__repr__, None)
178
+ if p is not None:
179
+ context[objid] = 1
180
+ p(self, object, stream, indent, allowance, context, level + 1)
181
+ del context[objid]
182
+ return
183
+ elif (_dataclasses.is_dataclass(object) and
184
+ not isinstance(object, type) and
185
+ object.__dataclass_params__.repr and
186
+ # Check dataclass has generated repr method.
187
+ hasattr(object.__repr__, "__wrapped__") and
188
+ "__create_fn__" in object.__repr__.__wrapped__.__qualname__):
189
+ context[objid] = 1
190
+ self._pprint_dataclass(object, stream, indent, allowance, context, level + 1)
191
+ del context[objid]
192
+ return
193
+ stream.write(rep)
194
+
195
+ def _pprint_dataclass(self, object, stream, indent, allowance, context, level):
196
+ cls_name = object.__class__.__name__
197
+ indent += len(cls_name) + 1
198
+ items = [(f.name, getattr(object, f.name)) for f in _dataclasses.fields(object) if f.repr]
199
+ stream.write(cls_name + '(')
200
+ self._format_namespace_items(items, stream, indent, allowance, context, level)
201
+ stream.write(')')
202
+
203
+ _dispatch = {}
204
+
205
+ def _pprint_dict(self, object, stream, indent, allowance, context, level):
206
+ write = stream.write
207
+ write('{')
208
+ if self._indent_per_level > 1:
209
+ write((self._indent_per_level - 1) * ' ')
210
+ length = len(object)
211
+ if length:
212
+ if self._sort_dicts:
213
+ items = sorted(object.items(), key=_safe_tuple)
214
+ else:
215
+ items = object.items()
216
+ self._format_dict_items(items, stream, indent, allowance + 1,
217
+ context, level)
218
+ write('}')
219
+
220
+ _dispatch[dict.__repr__] = _pprint_dict
221
+
222
+ def _pprint_ordered_dict(self, object, stream, indent, allowance, context, level):
223
+ if not len(object):
224
+ stream.write(repr(object))
225
+ return
226
+ cls = object.__class__
227
+ stream.write(cls.__name__ + '(')
228
+ self._format(list(object.items()), stream,
229
+ indent + len(cls.__name__) + 1, allowance + 1,
230
+ context, level)
231
+ stream.write(')')
232
+
233
+ _dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict
234
+
235
+ def _pprint_list(self, object, stream, indent, allowance, context, level):
236
+ stream.write('[')
237
+ self._format_items(object, stream, indent, allowance + 1,
238
+ context, level)
239
+ stream.write(']')
240
+
241
+ _dispatch[list.__repr__] = _pprint_list
242
+
243
+ def _pprint_tuple(self, object, stream, indent, allowance, context, level):
244
+ stream.write('(')
245
+ endchar = ',)' if len(object) == 1 else ')'
246
+ self._format_items(object, stream, indent, allowance + len(endchar),
247
+ context, level)
248
+ stream.write(endchar)
249
+
250
+ _dispatch[tuple.__repr__] = _pprint_tuple
251
+
252
+ def _pprint_set(self, object, stream, indent, allowance, context, level):
253
+ if not len(object):
254
+ stream.write(repr(object))
255
+ return
256
+ typ = object.__class__
257
+ if typ is set:
258
+ stream.write('{')
259
+ endchar = '}'
260
+ else:
261
+ stream.write(typ.__name__ + '({')
262
+ endchar = '})'
263
+ indent += len(typ.__name__) + 1
264
+ object = sorted(object, key=_safe_key)
265
+ self._format_items(object, stream, indent, allowance + len(endchar),
266
+ context, level)
267
+ stream.write(endchar)
268
+
269
+ _dispatch[set.__repr__] = _pprint_set
270
+ _dispatch[frozenset.__repr__] = _pprint_set
271
+
272
+ def _pprint_str(self, object, stream, indent, allowance, context, level):
273
+ write = stream.write
274
+ if not len(object):
275
+ write(repr(object))
276
+ return
277
+ chunks = []
278
+ lines = object.splitlines(True)
279
+ if level == 1:
280
+ indent += 1
281
+ allowance += 1
282
+ max_width1 = max_width = self._width - indent
283
+ for i, line in enumerate(lines):
284
+ rep = repr(line)
285
+ if i == len(lines) - 1:
286
+ max_width1 -= allowance
287
+ if len(rep) <= max_width1:
288
+ chunks.append(rep)
289
+ else:
290
+ # A list of alternating (non-space, space) strings
291
+ parts = re.findall(r'\S*\s*', line)
292
+ assert parts
293
+ assert not parts[-1]
294
+ parts.pop() # drop empty last part
295
+ max_width2 = max_width
296
+ current = ''
297
+ for j, part in enumerate(parts):
298
+ candidate = current + part
299
+ if j == len(parts) - 1 and i == len(lines) - 1:
300
+ max_width2 -= allowance
301
+ if len(repr(candidate)) > max_width2:
302
+ if current:
303
+ chunks.append(repr(current))
304
+ current = part
305
+ else:
306
+ current = candidate
307
+ if current:
308
+ chunks.append(repr(current))
309
+ if len(chunks) == 1:
310
+ write(rep)
311
+ return
312
+ if level == 1:
313
+ write('(')
314
+ for i, rep in enumerate(chunks):
315
+ if i > 0:
316
+ write('\n' + ' '*indent)
317
+ write(rep)
318
+ if level == 1:
319
+ write(')')
320
+
321
+ _dispatch[str.__repr__] = _pprint_str
322
+
323
+ def _pprint_bytes(self, object, stream, indent, allowance, context, level):
324
+ write = stream.write
325
+ if len(object) <= 4:
326
+ write(repr(object))
327
+ return
328
+ parens = level == 1
329
+ if parens:
330
+ indent += 1
331
+ allowance += 1
332
+ write('(')
333
+ delim = ''
334
+ for rep in _wrap_bytes_repr(object, self._width - indent, allowance):
335
+ write(delim)
336
+ write(rep)
337
+ if not delim:
338
+ delim = '\n' + ' '*indent
339
+ if parens:
340
+ write(')')
341
+
342
+ _dispatch[bytes.__repr__] = _pprint_bytes
343
+
344
+ def _pprint_bytearray(self, object, stream, indent, allowance, context, level):
345
+ write = stream.write
346
+ write('bytearray(')
347
+ self._pprint_bytes(bytes(object), stream, indent + 10,
348
+ allowance + 1, context, level + 1)
349
+ write(')')
350
+
351
+ _dispatch[bytearray.__repr__] = _pprint_bytearray
352
+
353
+ def _pprint_mappingproxy(self, object, stream, indent, allowance, context, level):
354
+ stream.write('mappingproxy(')
355
+ self._format(object.copy(), stream, indent + 13, allowance + 1,
356
+ context, level)
357
+ stream.write(')')
358
+
359
+ _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
360
+
361
+ def _pprint_simplenamespace(self, object, stream, indent, allowance, context, level):
362
+ if type(object) is _types.SimpleNamespace:
363
+ # The SimpleNamespace repr is "namespace" instead of the class
364
+ # name, so we do the same here. For subclasses; use the class name.
365
+ cls_name = 'namespace'
366
+ else:
367
+ cls_name = object.__class__.__name__
368
+ indent += len(cls_name) + 1
369
+ items = object.__dict__.items()
370
+ stream.write(cls_name + '(')
371
+ self._format_namespace_items(items, stream, indent, allowance, context, level)
372
+ stream.write(')')
373
+
374
+ _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace
375
+
376
+ def _format_dict_items(self, items, stream, indent, allowance, context,
377
+ level):
378
+ write = stream.write
379
+ indent += self._indent_per_level
380
+ delimnl = ',\n' + ' ' * indent
381
+ last_index = len(items) - 1
382
+ for i, (key, ent) in enumerate(items):
383
+ last = i == last_index
384
+ rep = self._repr(key, context, level)
385
+ write(rep)
386
+ write(': ')
387
+ self._format(ent, stream, indent + len(rep) + 2,
388
+ allowance if last else 1,
389
+ context, level)
390
+ if not last:
391
+ write(delimnl)
392
+
393
+ def _format_namespace_items(self, items, stream, indent, allowance, context, level):
394
+ write = stream.write
395
+ delimnl = ',\n' + ' ' * indent
396
+ last_index = len(items) - 1
397
+ for i, (key, ent) in enumerate(items):
398
+ last = i == last_index
399
+ write(key)
400
+ write('=')
401
+ if id(ent) in context:
402
+ # Special-case representation of recursion to match standard
403
+ # recursive dataclass repr.
404
+ write("...")
405
+ else:
406
+ self._format(ent, stream, indent + len(key) + 1,
407
+ allowance if last else 1,
408
+ context, level)
409
+ if not last:
410
+ write(delimnl)
411
+
412
+ def _format_items(self, items, stream, indent, allowance, context, level):
413
+ write = stream.write
414
+ indent += self._indent_per_level
415
+ if self._indent_per_level > 1:
416
+ write((self._indent_per_level - 1) * ' ')
417
+ delimnl = ',\n' + ' ' * indent
418
+ delim = ''
419
+ width = max_width = self._width - indent + 1
420
+ it = iter(items)
421
+ try:
422
+ next_ent = next(it)
423
+ except StopIteration:
424
+ return
425
+ last = False
426
+ while not last:
427
+ ent = next_ent
428
+ try:
429
+ next_ent = next(it)
430
+ except StopIteration:
431
+ last = True
432
+ max_width -= allowance
433
+ width -= allowance
434
+ if self._compact:
435
+ rep = self._repr(ent, context, level)
436
+ w = len(rep) + 2
437
+ if width < w:
438
+ width = max_width
439
+ if delim:
440
+ delim = delimnl
441
+ if width >= w:
442
+ width -= w
443
+ write(delim)
444
+ delim = ', '
445
+ write(rep)
446
+ continue
447
+ write(delim)
448
+ delim = delimnl
449
+ self._format(ent, stream, indent,
450
+ allowance if last else 1,
451
+ context, level)
452
+
453
+ def _repr(self, object, context, level):
454
+ repr, readable, recursive = self.format(object, context.copy(),
455
+ self._depth, level)
456
+ if not readable:
457
+ self._readable = False
458
+ if recursive:
459
+ self._recursive = True
460
+ return repr
461
+
462
+ def format(self, object, context, maxlevels, level):
463
+ """Format object for a specific context, returning a string
464
+ and flags indicating whether the representation is 'readable'
465
+ and whether the object represents a recursive construct.
466
+ """
467
+ return self._safe_repr(object, context, maxlevels, level)
468
+
469
+ def _pprint_default_dict(self, object, stream, indent, allowance, context, level):
470
+ if not len(object):
471
+ stream.write(repr(object))
472
+ return
473
+ rdf = self._repr(object.default_factory, context, level)
474
+ cls = object.__class__
475
+ indent += len(cls.__name__) + 1
476
+ stream.write('%s(%s,\n%s' % (cls.__name__, rdf, ' ' * indent))
477
+ self._pprint_dict(object, stream, indent, allowance + 1, context, level)
478
+ stream.write(')')
479
+
480
+ _dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict
481
+
482
+ def _pprint_counter(self, object, stream, indent, allowance, context, level):
483
+ if not len(object):
484
+ stream.write(repr(object))
485
+ return
486
+ cls = object.__class__
487
+ stream.write(cls.__name__ + '({')
488
+ if self._indent_per_level > 1:
489
+ stream.write((self._indent_per_level - 1) * ' ')
490
+ items = object.most_common()
491
+ self._format_dict_items(items, stream,
492
+ indent + len(cls.__name__) + 1, allowance + 2,
493
+ context, level)
494
+ stream.write('})')
495
+
496
+ _dispatch[_collections.Counter.__repr__] = _pprint_counter
497
+
498
+ def _pprint_chain_map(self, object, stream, indent, allowance, context, level):
499
+ if not len(object.maps):
500
+ stream.write(repr(object))
501
+ return
502
+ cls = object.__class__
503
+ stream.write(cls.__name__ + '(')
504
+ indent += len(cls.__name__) + 1
505
+ for i, m in enumerate(object.maps):
506
+ if i == len(object.maps) - 1:
507
+ self._format(m, stream, indent, allowance + 1, context, level)
508
+ stream.write(')')
509
+ else:
510
+ self._format(m, stream, indent, 1, context, level)
511
+ stream.write(',\n' + ' ' * indent)
512
+
513
+ _dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map
514
+
515
+ def _pprint_deque(self, object, stream, indent, allowance, context, level):
516
+ if not len(object):
517
+ stream.write(repr(object))
518
+ return
519
+ cls = object.__class__
520
+ stream.write(cls.__name__ + '(')
521
+ indent += len(cls.__name__) + 1
522
+ stream.write('[')
523
+ if object.maxlen is None:
524
+ self._format_items(object, stream, indent, allowance + 2,
525
+ context, level)
526
+ stream.write('])')
527
+ else:
528
+ self._format_items(object, stream, indent, 2,
529
+ context, level)
530
+ rml = self._repr(object.maxlen, context, level)
531
+ stream.write('],\n%smaxlen=%s)' % (' ' * indent, rml))
532
+
533
+ _dispatch[_collections.deque.__repr__] = _pprint_deque
534
+
535
+ def _pprint_user_dict(self, object, stream, indent, allowance, context, level):
536
+ self._format(object.data, stream, indent, allowance, context, level - 1)
537
+
538
+ _dispatch[_collections.UserDict.__repr__] = _pprint_user_dict
539
+
540
+ def _pprint_user_list(self, object, stream, indent, allowance, context, level):
541
+ self._format(object.data, stream, indent, allowance, context, level - 1)
542
+
543
+ _dispatch[_collections.UserList.__repr__] = _pprint_user_list
544
+
545
+ def _pprint_user_string(self, object, stream, indent, allowance, context, level):
546
+ self._format(object.data, stream, indent, allowance, context, level - 1)
547
+
548
+ _dispatch[_collections.UserString.__repr__] = _pprint_user_string
549
+
550
+ def _safe_repr(self, object, context, maxlevels, level):
551
+ # Return triple (repr_string, isreadable, isrecursive).
552
+ typ = type(object)
553
+ if typ in _builtin_scalars:
554
+ return repr(object), True, False
555
+
556
+ r = getattr(typ, "__repr__", None)
557
+
558
+ if issubclass(typ, int) and r is int.__repr__:
559
+ if self._underscore_numbers:
560
+ return f"{object:_d}", True, False
561
+ else:
562
+ return repr(object), True, False
563
+
564
+ if issubclass(typ, dict) and r is dict.__repr__:
565
+ if not object:
566
+ return "{}", True, False
567
+ objid = id(object)
568
+ if maxlevels and level >= maxlevels:
569
+ return "{...}", False, objid in context
570
+ if objid in context:
571
+ return _recursion(object), False, True
572
+ context[objid] = 1
573
+ readable = True
574
+ recursive = False
575
+ components = []
576
+ append = components.append
577
+ level += 1
578
+ if self._sort_dicts:
579
+ items = sorted(object.items(), key=_safe_tuple)
580
+ else:
581
+ items = object.items()
582
+ for k, v in items:
583
+ krepr, kreadable, krecur = self.format(
584
+ k, context, maxlevels, level)
585
+ vrepr, vreadable, vrecur = self.format(
586
+ v, context, maxlevels, level)
587
+ append("%s: %s" % (krepr, vrepr))
588
+ readable = readable and kreadable and vreadable
589
+ if krecur or vrecur:
590
+ recursive = True
591
+ del context[objid]
592
+ return "{%s}" % ", ".join(components), readable, recursive
593
+
594
+ if (issubclass(typ, list) and r is list.__repr__) or \
595
+ (issubclass(typ, tuple) and r is tuple.__repr__):
596
+ if issubclass(typ, list):
597
+ if not object:
598
+ return "[]", True, False
599
+ format = "[%s]"
600
+ elif len(object) == 1:
601
+ format = "(%s,)"
602
+ else:
603
+ if not object:
604
+ return "()", True, False
605
+ format = "(%s)"
606
+ objid = id(object)
607
+ if maxlevels and level >= maxlevels:
608
+ return format % "...", False, objid in context
609
+ if objid in context:
610
+ return _recursion(object), False, True
611
+ context[objid] = 1
612
+ readable = True
613
+ recursive = False
614
+ components = []
615
+ append = components.append
616
+ level += 1
617
+ for o in object:
618
+ orepr, oreadable, orecur = self.format(
619
+ o, context, maxlevels, level)
620
+ append(orepr)
621
+ if not oreadable:
622
+ readable = False
623
+ if orecur:
624
+ recursive = True
625
+ del context[objid]
626
+ return format % ", ".join(components), readable, recursive
627
+
628
+ rep = repr(object)
629
+ return rep, (rep and not rep.startswith('<')), False
630
+
631
+ _builtin_scalars = frozenset({str, bytes, bytearray, float, complex,
632
+ bool, type(None)})
633
+
634
+ def _recursion(object):
635
+ return ("<Recursion on %s with id=%s>"
636
+ % (type(object).__name__, id(object)))
637
+
638
+
639
+ def _perfcheck(object=None):
640
+ import time
641
+ if object is None:
642
+ object = [("string", (1, 2), [3, 4], {5: 6, 7: 8})] * 100000
643
+ p = PrettyPrinter()
644
+ t1 = time.perf_counter()
645
+ p._safe_repr(object, {}, None, 0, True)
646
+ t2 = time.perf_counter()
647
+ p.pformat(object)
648
+ t3 = time.perf_counter()
649
+ print("_safe_repr:", t2 - t1)
650
+ print("pformat:", t3 - t2)
651
+
652
+ def _wrap_bytes_repr(object, width, allowance):
653
+ current = b''
654
+ last = len(object) // 4 * 4
655
+ for i in range(0, len(object), 4):
656
+ part = object[i: i+4]
657
+ candidate = current + part
658
+ if i == last:
659
+ width -= allowance
660
+ if len(repr(candidate)) > width:
661
+ if current:
662
+ yield repr(current)
663
+ current = part
664
+ else:
665
+ current = candidate
666
+ if current:
667
+ yield repr(current)
668
+
669
+ if __name__ == "__main__":
670
+ _perfcheck()
shared/package-files/1f/1f81141da40215c6463fb7f03ac38bd2f5cfd7dfb760881371a194e32c08c489/mps_convolution_backward_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API mps_convolution_backward {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt, ::std::array<bool,3>);
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::mps_convolution_backward")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mps_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)")
24
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & self, const at::Tensor & grad_output, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, ::std::array<bool,3> output_mask);
25
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & grad_output, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, ::std::array<bool,3> output_mask);
26
+ };
27
+
28
+ struct TORCH_API mps_convolution_backward_out {
29
+ using schema = ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> (const at::Tensor &, const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt, ::std::array<bool,3>, at::Tensor &, at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::mps_convolution_backward")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "mps_convolution_backward.out(Tensor self, Tensor grad_output, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool[3] output_mask, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2) -> (Tensor(a!), Tensor(b!), Tensor(c!))")
35
+ static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> call(const at::Tensor & self, const at::Tensor & grad_output, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
36
+ static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & grad_output, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, ::std::array<bool,3> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2);
37
+ };
38
+
39
+ }} // namespace at::_ops
shared/package-files/1f/1f8219810623ae657a2136fb89ec77178ab0052143c8f6ddadbd1ee195db90c6/_dsp.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from typing import List, Optional, Union
3
+
4
+ import torch
5
+
6
+ from torchaudio.functional import fftconvolve
7
+
8
+
9
+ def oscillator_bank(
10
+ frequencies: torch.Tensor,
11
+ amplitudes: torch.Tensor,
12
+ sample_rate: float,
13
+ reduction: str = "sum",
14
+ dtype: Optional[torch.dtype] = torch.float64,
15
+ ) -> torch.Tensor:
16
+ """Synthesize waveform from the given instantaneous frequencies and amplitudes.
17
+
18
+ .. devices:: CPU CUDA
19
+
20
+ .. properties:: Autograd TorchScript
21
+
22
+ Note:
23
+ The phase information of the output waveform is found by taking the cumulative sum
24
+ of the given instantaneous frequencies (``frequencies``).
25
+ This incurs roundoff error when the data type does not have enough precision.
26
+ Using ``torch.float64`` can work around this.
27
+
28
+ The following figure shows the difference between ``torch.float32`` and
29
+ ``torch.float64`` when generating a sin wave of constant frequency and amplitude
30
+ with sample rate 8000 [Hz].
31
+ Notice that ``torch.float32`` version shows artifacts that are not seen in
32
+ ``torch.float64`` version.
33
+
34
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/oscillator_precision.png
35
+
36
+ Args:
37
+ frequencies (Tensor): Sample-wise oscillator frequencies (Hz). Shape `(..., time, N)`.
38
+ amplitudes (Tensor): Sample-wise oscillator amplitude. Shape: `(..., time, N)`.
39
+ sample_rate (float): Sample rate
40
+ reduction (str): Reduction to perform.
41
+ Valid values are ``"sum"``, ``"mean"`` or ``"none"``. Default: ``"sum"``
42
+ dtype (torch.dtype or None, optional): The data type on which cumulative sum operation is performed.
43
+ Default: ``torch.float64``. Pass ``None`` to disable the casting.
44
+
45
+ Returns:
46
+ Tensor:
47
+ The resulting waveform.
48
+
49
+ If ``reduction`` is ``"none"``, then the shape is
50
+ `(..., time, N)`, otherwise the shape is `(..., time)`.
51
+ """
52
+ if frequencies.shape != amplitudes.shape:
53
+ raise ValueError(
54
+ "The shapes of `frequencies` and `amplitudes` must match. "
55
+ f"Found: {frequencies.shape} and {amplitudes.shape} respectively."
56
+ )
57
+ reductions = ["sum", "mean", "none"]
58
+ if reduction not in reductions:
59
+ raise ValueError(f"The value of reduction must be either {reductions}. Found: {reduction}")
60
+
61
+ invalid = torch.abs(frequencies) >= sample_rate / 2
62
+ if torch.any(invalid):
63
+ warnings.warn(
64
+ "Some frequencies are above nyquist frequency. "
65
+ "Setting the corresponding amplitude to zero. "
66
+ "This might cause numerically unstable gradient."
67
+ )
68
+ amplitudes = torch.where(invalid, 0.0, amplitudes)
69
+
70
+ pi2 = 2.0 * torch.pi
71
+ freqs = frequencies * pi2 / sample_rate % pi2
72
+ phases = torch.cumsum(freqs, dim=-2, dtype=dtype)
73
+ if dtype is not None and freqs.dtype != dtype:
74
+ phases = phases.to(freqs.dtype)
75
+
76
+ waveform = amplitudes * torch.sin(phases)
77
+ if reduction == "sum":
78
+ return waveform.sum(-1)
79
+ if reduction == "mean":
80
+ return waveform.mean(-1)
81
+ return waveform
82
+
83
+
84
+ def adsr_envelope(
85
+ num_frames: int,
86
+ *,
87
+ attack: float = 0.0,
88
+ hold: float = 0.0,
89
+ decay: float = 0.0,
90
+ sustain: float = 1.0,
91
+ release: float = 0.0,
92
+ n_decay: int = 2,
93
+ dtype: Optional[torch.dtype] = None,
94
+ device: Optional[torch.device] = None,
95
+ ):
96
+ """Generate ADSR Envelope
97
+
98
+ .. devices:: CPU CUDA
99
+
100
+ Args:
101
+ num_frames (int): The number of output frames.
102
+ attack (float, optional):
103
+ The relative *time* it takes to reach the maximum level from
104
+ the start. (Default: ``0.0``)
105
+ hold (float, optional):
106
+ The relative *time* the maximum level is held before
107
+ it starts to decay. (Default: ``0.0``)
108
+ decay (float, optional):
109
+ The relative *time* it takes to sustain from
110
+ the maximum level. (Default: ``0.0``)
111
+ sustain (float, optional): The relative *level* at which
112
+ the sound should sustain. (Default: ``1.0``)
113
+
114
+ .. Note::
115
+ The duration of sustain is derived as `1.0 - (The sum of attack, hold, decay and release)`.
116
+
117
+ release (float, optional): The relative *time* it takes for the sound level to
118
+ reach zero after the sustain. (Default: ``0.0``)
119
+ n_decay (int, optional): The degree of polynomial decay. Default: ``2``.
120
+ dtype (torch.dtype, optional): the desired data type of returned tensor.
121
+ Default: if ``None``, uses a global default
122
+ (see :py:func:`torch.set_default_tensor_type`).
123
+ device (torch.device, optional): the desired device of returned tensor.
124
+ Default: if ``None``, uses the current device for the default tensor type
125
+ (see :py:func:`torch.set_default_tensor_type`).
126
+ device will be the CPU for CPU tensor types and the current CUDA
127
+ device for CUDA tensor types.
128
+
129
+ Returns:
130
+ Tensor: ADSR Envelope. Shape: `(num_frames, )`
131
+
132
+ Example
133
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/adsr_examples.png
134
+
135
+ """
136
+ if not 0 <= attack <= 1:
137
+ raise ValueError(f"The value of `attack` must be within [0, 1]. Found: {attack}")
138
+ if not 0 <= decay <= 1:
139
+ raise ValueError(f"The value of `decay` must be within [0, 1]. Found: {decay}")
140
+ if not 0 <= sustain <= 1:
141
+ raise ValueError(f"The value of `sustain` must be within [0, 1]. Found: {sustain}")
142
+ if not 0 <= hold <= 1:
143
+ raise ValueError(f"The value of `hold` must be within [0, 1]. Found: {hold}")
144
+ if not 0 <= release <= 1:
145
+ raise ValueError(f"The value of `release` must be within [0, 1]. Found: {release}")
146
+ if attack + decay + release + hold > 1:
147
+ raise ValueError("The sum of `attack`, `hold`, `decay` and `release` must not exceed 1.")
148
+
149
+ nframes = num_frames - 1
150
+ num_a = int(nframes * attack)
151
+ num_h = int(nframes * hold)
152
+ num_d = int(nframes * decay)
153
+ num_r = int(nframes * release)
154
+
155
+ # Initialize with sustain
156
+ out = torch.full((num_frames,), float(sustain), device=device, dtype=dtype)
157
+
158
+ # attack
159
+ if num_a > 0:
160
+ torch.linspace(0.0, 1.0, num_a + 1, out=out[: num_a + 1])
161
+
162
+ # hold
163
+ if num_h > 0:
164
+ out[num_a : num_a + num_h + 1] = 1.0
165
+
166
+ # decay
167
+ if num_d > 0:
168
+ # Compute: sustain + (1.0 - sustain) * (linspace[1, 0] ** n_decay)
169
+ i = num_a + num_h
170
+ decay = out[i : i + num_d + 1]
171
+ torch.linspace(1.0, 0.0, num_d + 1, out=decay)
172
+ decay **= n_decay
173
+ decay *= 1.0 - sustain
174
+ decay += sustain
175
+
176
+ # sustain is handled by initialization
177
+
178
+ # release
179
+ if num_r > 0:
180
+ torch.linspace(sustain, 0, num_r + 1, out=out[-num_r - 1 :])
181
+
182
+ return out
183
+
184
+
185
+ def extend_pitch(
186
+ base: torch.Tensor,
187
+ pattern: Union[int, List[float], torch.Tensor],
188
+ ):
189
+ """Extend the given time series values with multipliers of them.
190
+
191
+ .. devices:: CPU CUDA
192
+
193
+ .. properties:: Autograd TorchScript
194
+
195
+ Given a series of fundamental frequencies (pitch), this function appends
196
+ its harmonic overtones or inharmonic partials.
197
+
198
+ Args:
199
+ base (torch.Tensor):
200
+ Base time series, like fundamental frequencies (Hz). Shape: `(..., time, 1)`.
201
+ pattern (int, list of floats or torch.Tensor):
202
+ If ``int``, the number of pitch series after the operation.
203
+ `pattern - 1` tones are added, so that the resulting Tensor contains
204
+ up to `pattern`-th overtones of the given series.
205
+
206
+ If list of float or ``torch.Tensor``, it must be one dimensional,
207
+ representing the custom multiplier of the fundamental frequency.
208
+
209
+ Returns:
210
+ Tensor: Oscillator frequencies (Hz). Shape: `(..., time, num_tones)`.
211
+
212
+ Example
213
+ >>> # fundamental frequency
214
+ >>> f0 = torch.linspace(1, 5, 5).unsqueeze(-1)
215
+ >>> f0
216
+ tensor([[1.],
217
+ [2.],
218
+ [3.],
219
+ [4.],
220
+ [5.]])
221
+ >>> # Add harmonic overtones, up to 3rd.
222
+ >>> f = extend_pitch(f0, 3)
223
+ >>> f.shape
224
+ torch.Size([5, 3])
225
+ >>> f
226
+ tensor([[ 1., 2., 3.],
227
+ [ 2., 4., 6.],
228
+ [ 3., 6., 9.],
229
+ [ 4., 8., 12.],
230
+ [ 5., 10., 15.]])
231
+ >>> # Add custom (inharmonic) partials.
232
+ >>> f = extend_pitch(f0, torch.tensor([1, 2.1, 3.3, 4.5]))
233
+ >>> f.shape
234
+ torch.Size([5, 4])
235
+ >>> f
236
+ tensor([[ 1.0000, 2.1000, 3.3000, 4.5000],
237
+ [ 2.0000, 4.2000, 6.6000, 9.0000],
238
+ [ 3.0000, 6.3000, 9.9000, 13.5000],
239
+ [ 4.0000, 8.4000, 13.2000, 18.0000],
240
+ [ 5.0000, 10.5000, 16.5000, 22.5000]])
241
+ """
242
+ if isinstance(pattern, torch.Tensor):
243
+ mult = pattern
244
+ elif isinstance(pattern, int):
245
+ mult = torch.linspace(1.0, float(pattern), pattern, device=base.device, dtype=base.dtype)
246
+ else:
247
+ mult = torch.tensor(pattern, dtype=base.dtype, device=base.device)
248
+ h_freq = base @ mult.unsqueeze(0)
249
+ return h_freq
250
+
251
+
252
+ def sinc_impulse_response(cutoff: torch.Tensor, window_size: int = 513, high_pass: bool = False):
253
+ """Create windowed-sinc impulse response for given cutoff frequencies.
254
+
255
+ .. devices:: CPU CUDA
256
+
257
+ .. properties:: Autograd TorchScript
258
+
259
+ Args:
260
+ cutoff (Tensor): Cutoff frequencies for low-pass sinc filter.
261
+
262
+ window_size (int, optional): Size of the Hamming window to apply. Must be odd.
263
+ (Default: 513)
264
+
265
+ high_pass (bool, optional):
266
+ If ``True``, convert the resulting filter to high-pass.
267
+ Otherwise low-pass filter is returned. Default: ``False``.
268
+
269
+ Returns:
270
+ Tensor: A series of impulse responses. Shape: `(..., window_size)`.
271
+ """
272
+ if window_size % 2 == 0:
273
+ raise ValueError(f"`window_size` must be odd. Given: {window_size}")
274
+
275
+ half = window_size // 2
276
+ device, dtype = cutoff.device, cutoff.dtype
277
+ idx = torch.linspace(-half, half, window_size, device=device, dtype=dtype)
278
+
279
+ filt = torch.special.sinc(cutoff.unsqueeze(-1) * idx.unsqueeze(0))
280
+ filt = filt * torch.hamming_window(window_size, device=device, dtype=dtype, periodic=False).unsqueeze(0)
281
+ filt = filt / filt.sum(dim=-1, keepdim=True).abs()
282
+
283
+ # High pass IR is obtained by subtracting low_pass IR from delta function.
284
+ # https://courses.engr.illinois.edu/ece401/fa2020/slides/lec10.pdf
285
+ if high_pass:
286
+ filt = -filt
287
+ filt[..., half] = 1.0 + filt[..., half]
288
+ return filt
289
+
290
+
291
+ def frequency_impulse_response(magnitudes):
292
+ """Create filter from desired frequency response
293
+
294
+ Args:
295
+ magnitudes: The desired frequency responses. Shape: `(..., num_fft_bins)`
296
+
297
+ Returns:
298
+ Tensor: Impulse response. Shape `(..., 2 * (num_fft_bins - 1))`
299
+ """
300
+ if magnitudes.min() < 0.0:
301
+ # Negative magnitude does not make sense but allowing so that autograd works
302
+ # around 0.
303
+ # Should we raise error?
304
+ warnings.warn("The input frequency response should not contain negative values.")
305
+ ir = torch.fft.fftshift(torch.fft.irfft(magnitudes), dim=-1)
306
+ device, dtype = magnitudes.device, magnitudes.dtype
307
+ window = torch.hann_window(ir.size(-1), periodic=False, device=device, dtype=dtype).expand_as(ir)
308
+ return ir * window
309
+
310
+
311
+ def _overlap_and_add(waveform, stride):
312
+ num_frames, frame_size = waveform.shape[-2:]
313
+ numel = (num_frames - 1) * stride + frame_size
314
+ buffer = torch.zeros(waveform.shape[:-2] + (numel,), device=waveform.device, dtype=waveform.dtype)
315
+ for i in range(num_frames):
316
+ start = i * stride
317
+ end = start + frame_size
318
+ buffer[..., start:end] += waveform[..., i, :]
319
+ return buffer
320
+
321
+
322
+ def filter_waveform(waveform: torch.Tensor, kernels: torch.Tensor, delay_compensation: int = -1):
323
+ """Applies filters along time axis of the given waveform.
324
+
325
+ This function applies the given filters along time axis in the following manner:
326
+
327
+ 1. Split the given waveform into chunks. The number of chunks is equal to the number of given filters.
328
+ 2. Filter each chunk with corresponding filter.
329
+ 3. Place the filtered chunks at the original indices while adding up the overlapping parts.
330
+ 4. Crop the resulting waveform so that delay introduced by the filter is removed and its length
331
+ matches that of the input waveform.
332
+
333
+ The following figure illustrates this.
334
+
335
+ .. image:: https://download.pytorch.org/torchaudio/doc-assets/filter_waveform.png
336
+
337
+ .. note::
338
+
339
+ If the number of filters is one, then the operation becomes stationary.
340
+ i.e. the same filtering is applied across the time axis.
341
+
342
+ Args:
343
+ waveform (Tensor): Shape `(..., time)`.
344
+ kernels (Tensor): Impulse responses.
345
+ Valid inputs are 2D tensor with shape `(num_filters, filter_length)` or
346
+ `(N+1)`-D tensor with shape `(..., num_filters, filter_length)`, where `N` is
347
+ the dimension of waveform.
348
+
349
+ In case of 2D input, the same set of filters is used across channels and batches.
350
+ Otherwise, different sets of filters are applied. In this case, the shape of
351
+ the first `N-1` dimensions of filters must match (or be broadcastable to) that of waveform.
352
+
353
+ delay_compensation (int): Control how the waveform is cropped after full convolution.
354
+ If the value is zero or positive, it is interpreted as the length of crop at the
355
+ beginning of the waveform. The value cannot be larger than the size of filter kernel.
356
+ Otherwise the initial crop is ``filter_size // 2``.
357
+ When cropping happens, the waveform is also cropped from the end so that the
358
+ length of the resulting waveform matches the input waveform.
359
+
360
+ Returns:
361
+ Tensor: `(..., time)`.
362
+ """
363
+ if kernels.ndim not in [2, waveform.ndim + 1]:
364
+ raise ValueError(
365
+ "`kernels` must be 2 or N+1 dimension where "
366
+ f"N is the dimension of waveform. Found: {kernels.ndim} (N={waveform.ndim})"
367
+ )
368
+
369
+ num_filters, filter_size = kernels.shape[-2:]
370
+ num_frames = waveform.size(-1)
371
+
372
+ if delay_compensation > filter_size:
373
+ raise ValueError(
374
+ "When `delay_compenstation` is provided, it cannot be larger than the size of filters."
375
+ f"Found: delay_compensation={delay_compensation}, filter_size={filter_size}"
376
+ )
377
+
378
+ # Transform waveform's time axis into (num_filters x chunk_length) with optional padding
379
+ chunk_length = num_frames // num_filters
380
+ if num_frames % num_filters > 0:
381
+ chunk_length += 1
382
+ num_pad = chunk_length * num_filters - num_frames
383
+ waveform = torch.nn.functional.pad(waveform, [0, num_pad], "constant", 0)
384
+ chunked = waveform.unfold(-1, chunk_length, chunk_length)
385
+ assert chunked.numel() >= waveform.numel()
386
+
387
+ # Broadcast kernels
388
+ if waveform.ndim + 1 > kernels.ndim:
389
+ expand_shape = waveform.shape[:-1] + kernels.shape
390
+ kernels = kernels.expand(expand_shape)
391
+
392
+ convolved = fftconvolve(chunked, kernels)
393
+ restored = _overlap_and_add(convolved, chunk_length)
394
+
395
+ # Trim in a way that the number of samples are same as input,
396
+ # and the filter delay is compensated
397
+ if delay_compensation >= 0:
398
+ start = delay_compensation
399
+ else:
400
+ start = filter_size // 2
401
+ num_crops = restored.size(-1) - num_frames
402
+ end = num_crops - start
403
+ result = restored[..., start:-end]
404
+ return result
405
+
406
+
407
+ def exp_sigmoid(
408
+ input: torch.Tensor, exponent: float = 10.0, max_value: float = 2.0, threshold: float = 1e-7
409
+ ) -> torch.Tensor:
410
+ """Exponential Sigmoid pointwise nonlinearity.
411
+ Implements the equation:
412
+ ``max_value`` * sigmoid(``input``) ** (log(``exponent``)) + ``threshold``
413
+
414
+ The output has a range of [``threshold``, ``max_value``].
415
+ ``exponent`` controls the slope of the output.
416
+
417
+ .. devices:: CPU CUDA
418
+
419
+ Args:
420
+ input (Tensor): Input Tensor
421
+ exponent (float, optional): Exponent. Controls the slope of the output
422
+ max_value (float, optional): Maximum value of the output
423
+ threshold (float, optional): Minimum value of the output
424
+
425
+ Returns:
426
+ Tensor: Exponential Sigmoid output. Shape: same as input
427
+
428
+ """
429
+
430
+ return max_value * torch.pow(
431
+ torch.nn.functional.sigmoid(input),
432
+ torch.log(torch.tensor(exponent, device=input.device, dtype=input.dtype)),
433
+ ) + torch.tensor(threshold, device=input.device, dtype=input.dtype)
shared/package-files/1f/1f85cb7a189c3d9da1ec16f7d043911dcb9d728b030fdffbdf045c63251e6a75/news28-a ADDED
Binary file (1.43 kB). View file
 
shared/package-files/1f/1f85cb7a189c3d9da1ec16f7d043911dcb9d728b030fdffbdf045c63251e6a75/news29 ADDED
Binary file (1.43 kB). View file
 
shared/package-files/1f/1f85f237c2e6c383416779bf50496d1caed3e590037377dba24d8ac0e2804e6f/mergesort.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The same algorithm as translated from numpy.
3
+ See numpy/core/src/npysort/mergesort.c.src.
4
+ The high-level numba code is adding a little overhead comparing to
5
+ the pure-C implementation in numpy.
6
+ """
7
+ import numpy as np
8
+ from collections import namedtuple
9
+
10
+ # Array size smaller than this will be sorted by insertion sort
11
+ SMALL_MERGESORT = 20
12
+
13
+
14
+ MergesortImplementation = namedtuple('MergesortImplementation', [
15
+ 'run_mergesort',
16
+ ])
17
+
18
+
19
+ def make_mergesort_impl(wrap, lt=None, is_argsort=False):
20
+ kwargs_lite = dict(no_cpython_wrapper=True, _nrt=False)
21
+
22
+ # The less than
23
+ if lt is None:
24
+ @wrap(**kwargs_lite)
25
+ def lt(a, b):
26
+ return a < b
27
+ else:
28
+ lt = wrap(**kwargs_lite)(lt)
29
+
30
+ if is_argsort:
31
+ @wrap(**kwargs_lite)
32
+ def lessthan(a, b, vals):
33
+ return lt(vals[a], vals[b])
34
+ else:
35
+ @wrap(**kwargs_lite)
36
+ def lessthan(a, b, vals):
37
+ return lt(a, b)
38
+
39
+ @wrap(**kwargs_lite)
40
+ def argmergesort_inner(arr, vals, ws):
41
+ """The actual mergesort function
42
+
43
+ Parameters
44
+ ----------
45
+ arr : array [read+write]
46
+ The values being sorted inplace. For argsort, this is the
47
+ indices.
48
+ vals : array [readonly]
49
+ ``None`` for normal sort. In argsort, this is the actual array values.
50
+ ws : array [write]
51
+ The workspace. Must be of size ``arr.size // 2``
52
+ """
53
+ if arr.size > SMALL_MERGESORT:
54
+ # Merge sort
55
+ mid = arr.size // 2
56
+
57
+ argmergesort_inner(arr[:mid], vals, ws)
58
+ argmergesort_inner(arr[mid:], vals, ws)
59
+
60
+ # Copy left half into workspace so we don't overwrite it
61
+ for i in range(mid):
62
+ ws[i] = arr[i]
63
+
64
+ # Merge
65
+ left = ws[:mid]
66
+ right = arr[mid:]
67
+ out = arr
68
+
69
+ i = j = k = 0
70
+ while i < left.size and j < right.size:
71
+ if not lessthan(right[j], left[i], vals):
72
+ out[k] = left[i]
73
+ i += 1
74
+ else:
75
+ out[k] = right[j]
76
+ j += 1
77
+ k += 1
78
+
79
+ # Leftovers
80
+ while i < left.size:
81
+ out[k] = left[i]
82
+ i += 1
83
+ k += 1
84
+
85
+ while j < right.size:
86
+ out[k] = right[j]
87
+ j += 1
88
+ k += 1
89
+ else:
90
+ # Insertion sort
91
+ i = 1
92
+ while i < arr.size:
93
+ j = i
94
+ while j > 0 and lessthan(arr[j], arr[j - 1], vals):
95
+ arr[j - 1], arr[j] = arr[j], arr[j - 1]
96
+ j -= 1
97
+ i += 1
98
+
99
+ # The top-level entry points
100
+
101
+ @wrap(no_cpython_wrapper=True)
102
+ def mergesort(arr):
103
+ "Inplace"
104
+ ws = np.empty(arr.size // 2, dtype=arr.dtype)
105
+ argmergesort_inner(arr, None, ws)
106
+ return arr
107
+
108
+
109
+ @wrap(no_cpython_wrapper=True)
110
+ def argmergesort(arr):
111
+ "Out-of-place"
112
+ idxs = np.arange(arr.size)
113
+ ws = np.empty(arr.size // 2, dtype=idxs.dtype)
114
+ argmergesort_inner(idxs, arr, ws)
115
+ return idxs
116
+
117
+ return MergesortImplementation(
118
+ run_mergesort=(argmergesort if is_argsort else mergesort)
119
+ )
120
+
121
+
122
+ def make_jit_mergesort(*args, **kwargs):
123
+ from numba import njit
124
+ # NOTE: wrap with njit to allow recursion
125
+ # because @register_jitable => @overload doesn't support recursion
126
+ return make_mergesort_impl(njit, *args, **kwargs)
shared/package-files/1f/1f8619123a353e3e1824e9a27597baaf3b37bf872dd0b130c2d9cb8b1d060858/select_copy_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor select_copy(const at::Tensor & self, int64_t dim, int64_t index);
21
+ TORCH_API at::Tensor select_copy_symint(const at::Tensor & self, int64_t dim, c10::SymInt index);
22
+
23
+ } // namespace compositeexplicitautogradnonfunctional
24
+ } // namespace at
shared/package-files/1f/1f8ae7ffab8be339418828bb6a492cec0af74998929c06e12ced655f51383398/special_erfinv_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor special_erfinv(const at::Tensor & self);
20
+ TORCH_API at::Tensor & special_erfinv_out(const at::Tensor & self, at::Tensor & out);
21
+ } // namespace native
22
+ } // namespace at
shared/package-files/1f/1f8b43919df95d275faeaa7c1b3ac15f8397e6f8ee8c6e8b3ff5bd031760e4ed/xnuppc+c ADDED
Binary file (847 Bytes). View file
 
shared/package-files/1f/1f8c830a711f10c154138388320d452589fd72f8f909b411bf5cdea244dee906/template.pyi ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ dot_re: Any
4
+
5
+ def blankout(src: str, char: str) -> str: ...
6
+
7
+ context_re: Any
8
+ inline_re: Any
9
+ block_re: Any
10
+ endblock_re: Any
11
+ plural_re: Any
12
+ constant_re: Any
13
+
14
+ def templatize(src: str, origin: str = ...) -> str: ...
shared/package-files/1f/1f924aedebc4c68ebe2b52c946ca31e1f5940451e0f18fee2077c47b4f645a66/tensor_split_compositeimplicitautograd_dispatch.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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::vector<at::Tensor> tensor_split(const at::Tensor & self, int64_t sections, int64_t dim=0);
21
+ TORCH_API ::std::vector<at::Tensor> tensor_split_symint(const at::Tensor & self, c10::SymInt sections, int64_t dim=0);
22
+ TORCH_API ::std::vector<at::Tensor> tensor_split(const at::Tensor & self, at::IntArrayRef indices, int64_t dim=0);
23
+ TORCH_API ::std::vector<at::Tensor> tensor_split_symint(const at::Tensor & self, c10::SymIntArrayRef indices, int64_t dim=0);
24
+ TORCH_API ::std::vector<at::Tensor> tensor_split(const at::Tensor & self, const at::Tensor & tensor_indices_or_sections, int64_t dim=0);
25
+
26
+ } // namespace compositeimplicitautograd
27
+ } // namespace at
shared/package-files/1f/1f9398544b699e11b1ead37a04f2481b645857f1d901659a0c17580e3598fa91/DeviceArray.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <c10/core/Allocator.h>
2
+ #include <c10/util/Exception.h>
3
+ #include <cstddef>
4
+ #include <cstdint>
5
+ #include <type_traits>
6
+
7
+ namespace c10 {
8
+
9
+ template <typename T>
10
+ class DeviceArray {
11
+ public:
12
+ DeviceArray(c10::Allocator& allocator, size_t size)
13
+ : data_ptr_(allocator.allocate(size * sizeof(T))) {
14
+ static_assert(std::is_trivial<T>::value, "T must be a trivial type");
15
+ TORCH_INTERNAL_ASSERT(
16
+ 0 == (reinterpret_cast<intptr_t>(data_ptr_.get()) % alignof(T)),
17
+ "c10::DeviceArray: Allocated memory is not aligned for this data type");
18
+ }
19
+
20
+ T* get() {
21
+ return static_cast<T*>(data_ptr_.get());
22
+ }
23
+
24
+ private:
25
+ c10::DataPtr data_ptr_;
26
+ };
27
+
28
+ } // namespace c10
shared/package-files/1f/1f9aec5b2fb484ec217fb62d337825bba40eae08e6c85fbaaeebdb53e9b58859/replication_pad2d_native.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <c10/util/Optional.h>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+ #include <ATen/ops/replication_pad2d_meta.h>
16
+
17
+ namespace at {
18
+ namespace native {
19
+ struct TORCH_API structured_replication_pad2d_out_cpu : public at::meta::structured_replication_pad2d {
20
+ void impl(const at::Tensor & self, at::ArrayRef<int64_t> padding, const at::Tensor & out);
21
+ };
22
+ struct TORCH_API structured_replication_pad2d_out_cuda : public at::meta::structured_replication_pad2d {
23
+ void impl(const at::Tensor & self, at::ArrayRef<int64_t> padding, const at::Tensor & out);
24
+ };
25
+ } // namespace native
26
+ } // namespace at