Publish 11 evaluated Astra histories with reproducible checkpoint artifacts (part 21)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +28 -0
- shared/package-files/41/41afc530ff9989deed3854cd88d8e756b622ed890ae212ad70626202ff3ce01c/blob +372 -0
- shared/package-files/41/41b0189d71536ce4b79f53a7b5a096235c775c86d65fdea8470cb203d039bd9c/blob +17 -0
- shared/package-files/41/41b0c932922029d59dd6b99c62e4a11c41827599ee5a29a217cbffb77a77793b/blob +108 -0
- shared/package-files/41/41b37281c4f21f309f4a934aef0159409d9d109d5ddae2142546232e5b2f9011/blob +112 -0
- shared/package-files/41/41b5052fe85ce699fef7db72e3cec88ff2434b925f5883da732441b95fa1a437/blob +23 -0
- shared/package-files/41/41b64e0aa22f9da2b45ce1f791a49705efa6ff5fd16f7de9b2af04f963120535/blob +0 -0
- shared/package-files/41/41b65e49401b21d55f0d478d672cb2fa5f01a9b2b2f0bf947936bcf0073444dc/blob +27 -0
- shared/package-files/41/41b8ab7ebbcab1e626accda42e31c784d18d80ee83b07252d6772e1f93e73d3e/blob +2387 -0
- shared/package-files/41/41bb9b06cff1425bcac1e027bab8721e320ae238bbec68781bebac5ee97a5d53/blob +0 -0
- shared/package-files/41/41bd0efdfefcabe0ad1da6ef1d2ed54499a771b92eaa8c164c5dff76b98c8312/blob +3360 -0
- shared/package-files/41/41bd50e0d1c86d224e72c67cbd406a68f4feb3a956a63f980f5908f4323a5dfa/blob +11 -0
- shared/package-files/41/41c0462a4a7dfe05203ce3065dc7ee1aca9e0bb893d40006aeae590d7fa710aa/blob +51 -0
- shared/package-files/41/41c129c561275c7070edae8385a717253020bcf3700c79b35c5a44fc87315082/blob +1893 -0
- shared/package-files/41/41c6e13b296e71c76e86fa20b1e5a184c2a99c931e77f95fb3486f73a06f00d7/blob +3 -0
- shared/package-files/41/41c708c5adba6e097513ab8ccb9f1d7865a2fb469e22491a9e01dcc64da459fc/blob +4 -0
- shared/package-files/41/41cac51c9f92ffe7a4bbf83041bf6f9317b714ece180b65187a5edb1884d1c29/blob +3 -0
- shared/package-files/41/41cb1a37427106bf40af0427ce198dd3a1bc74c4e9a88b886daa49bd65abf084/blob +1 -0
- shared/package-files/41/41cb48d69deaa9089aa8ba4625d2f0bc8bc40910f3e6d697151d44945641d71d/blob +15 -0
- shared/package-files/41/41cda824ec237bee2e7054f570046990150bbe4157308c8ec42b70382c68960c/blob +0 -0
- shared/package-files/41/41d26fc8ad8dd77f1b8833e18b1c7f67dc5b27b47e692c73e668524af87e1d18/blob +101 -0
- shared/package-files/41/41d4d08956f385ba5968965511255f4ba72050c2448ca6916896bddcde3dc346/blob +3 -0
- shared/package-files/41/41d7179c2340c29b395554cda3a8ec766112e87e8aeb3aa9c9467121999f29ad/blob +9 -0
- shared/package-files/41/41d7748bb1f870d8400017c53993eea65862ffd482aae1693be84d93245c303f/blob +108 -0
- shared/package-files/41/41d7b70281a913330914c46e645ae09630e80da35258e8929e82e69ae2df7140/blob +881 -0
- shared/package-files/41/41d7bbdf2f62da80eefc257751f2636c3d3eba990c25b9489ff46f708ce2f83e/blob +5 -0
- shared/package-files/41/41da0e7eaac03dd6f0b6d2ebcdf01ee7968423665cc787d0850a7a853fe57c5b/blob +0 -0
- shared/package-files/41/41da76f5afb7ce062d248f762463a92f7ca47e4e0f905b224ba6afeef91ded0f/blob +58 -0
- shared/package-files/41/41dc9d81c4a6464bff41eb29c21b84fefad74914be7e77d578a78876c6d392e6/blob +25 -0
- shared/package-files/41/41df4cdb9a30165dd83ae009fcbafe8408759bb6d1c7314412c3960ece8aebc6/blob +198 -0
- shared/package-files/41/41df97defedabb250b1589cebc2e20b405d409a95d561e4c42b33117d90305aa/blob +348 -0
- shared/package-files/41/41e02cb261410cf082e5546839b029e1491e6f01133f7a92efe9dae1a72cb563/blob +33 -0
- shared/package-files/41/41e0e8878e2d4bfff2f4b2bb2f050101cf920f9452fa984f03879858f979c888/blob +64 -0
- shared/package-files/41/41e2ffde1a6743801c20aeb7422a454429dd72113c64a1aa8d0afc43d9d1c019/blob +33 -0
- shared/package-files/41/41e3234dcdb4fc865e552865c4465042cbf6b2e1403eaa6f0fce93047112ca4b/blob +1486 -0
- shared/package-files/41/41e42466b686bd3739838b6fd503ec1d514c93bbcdef23b6b1b4e869fe86369e/blob +47 -0
- shared/package-files/41/41e51412e3668739e9b8a34f2fe0742153a431d302bbca095fad8e0b4569cee8/blob +137 -0
- shared/package-files/41/41e80dd275b5a4e2c432a9991e82a1bb3ca028535ae5d187bb51dc36c0d0e660/blob +155 -0
- shared/package-files/41/41eb014e1136d816b5ede51d1b6d6558da8f46f061caea4b9cfb17b9e2dacc7c/blob +11 -0
- shared/package-files/41/41ec04f5a5a1b98ec51fbab9a72051194552aab6396188ab188a5740a791630b/blob +21 -0
- shared/package-files/41/41ee0a110d3f5eca6ac054c050864febdd930ac6112750f7189cded34bf19256/blob +26 -0
- shared/package-files/41/41ee96f160ccca37ebf3ed10fa95b98e0803be54b448083ef92c6ac8cf6f6312/blob +3 -0
- shared/package-files/41/41f089ebe7eaba30a1d7ad9a45bf40fea356942d24fbae6b57834033470517da/blob +563 -0
- shared/package-files/41/41f0e2a823a0cd2c8273e38146fd1ddfcdccc8b5b5c4a4575ef365256681017a/blob +0 -0
- shared/package-files/41/41f62f4991e9fa89ec25bc78a82a65e4f6773e67ba8b900be61d360035c38188/blob +61 -0
- shared/package-files/41/41f694531f93d0588a0490416f76c3965b7c3bc79313b3298a0abbc2f0dea517/blob +955 -0
- shared/package-files/41/41f87914952ff5959dfcfe73c64bd860892faac3e9b60683b8a91e5ff17cbf20/blob +20 -0
- shared/package-files/41/41f9e80776a2884bd4ce7f15057874d73a651d08246dd33cb70e9dcb4c7aec17/blob +490 -0
- shared/package-files/41/41fb194beb1554d13af237fbe930c0a82455b9f315f08c1a049622f4533beb55/blob +258 -0
- shared/package-files/41/41fcaa0ad1ff3099c890a5b99bef7c1990f6323b4f60bb4f4c38bbf697081a1b/blob +37 -0
.gitattributes
CHANGED
|
@@ -352,3 +352,31 @@ shared/package-files/40/40da9341758e7d778e7c5310207d327b76aa8836101f4ea7e94e9067
|
|
| 352 |
shared/package-files/41/4141415c8a105e52fdfd45e0c3c9d0cd9a4adc4c9eb69b7426eb268e53a196b5/blob filter=lfs diff=lfs merge=lfs -text
|
| 353 |
shared/package-files/41/4175c7f0363ada56cf3dbce13f6b8afc3dea3b08bba96c648e7912f87511b6fe/blob filter=lfs diff=lfs merge=lfs -text
|
| 354 |
shared/package-files/41/417f32ec19ff77404494c4aa49d4e4477ac8904c23661e6df70620ce6e26ab11/blob filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
shared/package-files/41/4141415c8a105e52fdfd45e0c3c9d0cd9a4adc4c9eb69b7426eb268e53a196b5/blob filter=lfs diff=lfs merge=lfs -text
|
| 353 |
shared/package-files/41/4175c7f0363ada56cf3dbce13f6b8afc3dea3b08bba96c648e7912f87511b6fe/blob filter=lfs diff=lfs merge=lfs -text
|
| 354 |
shared/package-files/41/417f32ec19ff77404494c4aa49d4e4477ac8904c23661e6df70620ce6e26ab11/blob filter=lfs diff=lfs merge=lfs -text
|
| 355 |
+
shared/package-files/41/41c6e13b296e71c76e86fa20b1e5a184c2a99c931e77f95fb3486f73a06f00d7/blob filter=lfs diff=lfs merge=lfs -text
|
| 356 |
+
shared/package-files/41/41cac51c9f92ffe7a4bbf83041bf6f9317b714ece180b65187a5edb1884d1c29/blob filter=lfs diff=lfs merge=lfs -text
|
| 357 |
+
shared/package-files/41/41d4d08956f385ba5968965511255f4ba72050c2448ca6916896bddcde3dc346/blob filter=lfs diff=lfs merge=lfs -text
|
| 358 |
+
shared/package-files/41/41ee96f160ccca37ebf3ed10fa95b98e0803be54b448083ef92c6ac8cf6f6312/blob filter=lfs diff=lfs merge=lfs -text
|
| 359 |
+
shared/package-files/42/4210969f70fd62d78c425c5faec9ce171bbcad9d8e851023bf698ba81fdb88c0/blob filter=lfs diff=lfs merge=lfs -text
|
| 360 |
+
shared/package-files/42/4239de96773a37e2874fd38becafee81909702e58f06eb9c932a683d47a6946a/blob filter=lfs diff=lfs merge=lfs -text
|
| 361 |
+
shared/package-files/42/42444a4411d59e501e080a8876abe6cb9d9d94c5df6f4f289b468679accdc07f/blob filter=lfs diff=lfs merge=lfs -text
|
| 362 |
+
shared/package-files/42/42864efe330a0d47c29afc480949e810cc082ac3417d30d43702c2dc5548be69/blob filter=lfs diff=lfs merge=lfs -text
|
| 363 |
+
shared/package-files/42/42c5c2abcc858ac5d3bc6f1f8304158a313ee39db243aa30493a5f3ce3366795/blob filter=lfs diff=lfs merge=lfs -text
|
| 364 |
+
shared/package-files/42/42cf224dd64557e7d427094be7ae18395c17df0bbb849c9bf7ab8f238d7628ff/blob filter=lfs diff=lfs merge=lfs -text
|
| 365 |
+
shared/package-files/43/43100d30c34d2eb13e03cb4a808748d14681b69c6fdc2f2e7ae97bf23513609a/blob filter=lfs diff=lfs merge=lfs -text
|
| 366 |
+
shared/package-files/43/4333610e3354704d33815f7b3767626d93f46ff8bd6c69f417d90b9d5734e4d2/blob filter=lfs diff=lfs merge=lfs -text
|
| 367 |
+
shared/package-files/43/433df3699d3ca5610697eeea3d2fcbadd6b70ccc6f2309e65bffc9e33b97aa56/blob filter=lfs diff=lfs merge=lfs -text
|
| 368 |
+
shared/package-files/43/434278a2390e651df0f7a19061ca835b9f2817a57529b85dcd1324963abe4a85/blob filter=lfs diff=lfs merge=lfs -text
|
| 369 |
+
shared/package-files/43/4358374c599427b08746241c6294a33661daf0fc5c421a6cafb69d0c4b7b3354/blob filter=lfs diff=lfs merge=lfs -text
|
| 370 |
+
shared/package-files/43/436381bdecd5b99ce2b56bfab79ef225058735c09ef10350b7a6e08a008e8bb1/blob filter=lfs diff=lfs merge=lfs -text
|
| 371 |
+
shared/package-files/43/437ffecdb57c1d8357a8d275df3e54bd4c96a9a58e6671dfe0b25fbc51b26ef1/blob filter=lfs diff=lfs merge=lfs -text
|
| 372 |
+
shared/package-files/43/43a7e71d6a2aefd310629e7cd71f9979702cc406eb2b0e12586fb6f56eebec3f/blob filter=lfs diff=lfs merge=lfs -text
|
| 373 |
+
shared/package-files/44/441a5d7750bc07db39b7bc0372bf3f38e7b7e2a11c5b8e6bd3e83534ee5a5eea/blob filter=lfs diff=lfs merge=lfs -text
|
| 374 |
+
shared/package-files/44/449ac6908a5ffa64670b1bdd0c1742729d396eb69323440a537605a0f1a394ef/blob filter=lfs diff=lfs merge=lfs -text
|
| 375 |
+
shared/package-files/44/449b4b5a9343bc4bc1f97aaf7fd3c0864ed43cca1048cc823cd0b5b4679f3934/blob filter=lfs diff=lfs merge=lfs -text
|
| 376 |
+
shared/package-files/44/44df135283655f5881633bfdcadb42f9e2e211463aa1484992c9156529d200ec/blob filter=lfs diff=lfs merge=lfs -text
|
| 377 |
+
shared/package-files/44/44feebba310d24561afa6f498beef670d38e4fa91eb3da58ef919b170a6839b3/blob filter=lfs diff=lfs merge=lfs -text
|
| 378 |
+
shared/package-files/45/453349bb31bd4758057336ad43d3952dc870c6fd837280d7870b47cbfe67de24/blob filter=lfs diff=lfs merge=lfs -text
|
| 379 |
+
shared/package-files/45/456fe124e1b71c1475a9e79a2994a4479bb135308d992d06200d53a0ad7d941e/blob filter=lfs diff=lfs merge=lfs -text
|
| 380 |
+
shared/package-files/45/45888f066fa3f2d823c10d1635eb9cb1a82d54ce95589b5b425d0bdfd23fb18c/blob filter=lfs diff=lfs merge=lfs -text
|
| 381 |
+
shared/package-files/45/458bb348a5bed943199eaf3618b9ed541e65fad61c438af1a6cb72250ff567e8/blob filter=lfs diff=lfs merge=lfs -text
|
| 382 |
+
shared/package-files/45/45f810caf95292f82800ffc82c958c18bf17436116a063d82a472189b9880a27/blob fil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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Module for reading and writing matlab (TM) .mat files
|
| 3 |
+
"""
|
| 4 |
+
# Authors: Travis Oliphant, Matthew Brett
|
| 5 |
+
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
|
| 8 |
+
from ._miobase import _get_matfile_version, docfiller
|
| 9 |
+
from ._mio4 import MatFile4Reader, MatFile4Writer
|
| 10 |
+
from ._mio5 import MatFile5Reader, MatFile5Writer
|
| 11 |
+
|
| 12 |
+
__all__ = ['loadmat', 'savemat', 'whosmat']
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@contextmanager
|
| 16 |
+
def _open_file_context(file_like, appendmat, mode='rb'):
|
| 17 |
+
f, opened = _open_file(file_like, appendmat, mode)
|
| 18 |
+
try:
|
| 19 |
+
yield f
|
| 20 |
+
finally:
|
| 21 |
+
if opened:
|
| 22 |
+
f.close()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _open_file(file_like, appendmat, mode='rb'):
|
| 26 |
+
"""
|
| 27 |
+
Open `file_like` and return as file-like object. First, check if object is
|
| 28 |
+
already file-like; if so, return it as-is. Otherwise, try to pass it
|
| 29 |
+
to open(). If that fails, and `file_like` is a string, and `appendmat` is true,
|
| 30 |
+
append '.mat' and try again.
|
| 31 |
+
"""
|
| 32 |
+
reqs = {'read'} if set(mode) & set('r+') else set()
|
| 33 |
+
if set(mode) & set('wax+'):
|
| 34 |
+
reqs.add('write')
|
| 35 |
+
if reqs.issubset(dir(file_like)):
|
| 36 |
+
return file_like, False
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
return open(file_like, mode), True
|
| 40 |
+
except OSError as e:
|
| 41 |
+
# Probably "not found"
|
| 42 |
+
if isinstance(file_like, str):
|
| 43 |
+
if appendmat and not file_like.endswith('.mat'):
|
| 44 |
+
file_like += '.mat'
|
| 45 |
+
return open(file_like, mode), True
|
| 46 |
+
else:
|
| 47 |
+
raise OSError(
|
| 48 |
+
'Reader needs file name or open file-like object'
|
| 49 |
+
) from e
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@docfiller
|
| 53 |
+
def mat_reader_factory(file_name, appendmat=True, **kwargs):
|
| 54 |
+
"""
|
| 55 |
+
Create reader for matlab .mat format files.
|
| 56 |
+
|
| 57 |
+
Parameters
|
| 58 |
+
----------
|
| 59 |
+
%(file_arg)s
|
| 60 |
+
%(append_arg)s
|
| 61 |
+
%(load_args)s
|
| 62 |
+
%(struct_arg)s
|
| 63 |
+
|
| 64 |
+
Returns
|
| 65 |
+
-------
|
| 66 |
+
matreader : MatFileReader object
|
| 67 |
+
Initialized instance of MatFileReader class matching the mat file
|
| 68 |
+
type detected in `filename`.
|
| 69 |
+
file_opened : bool
|
| 70 |
+
Whether the file was opened by this routine.
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
byte_stream, file_opened = _open_file(file_name, appendmat)
|
| 74 |
+
mjv, mnv = _get_matfile_version(byte_stream)
|
| 75 |
+
if mjv == 0:
|
| 76 |
+
return MatFile4Reader(byte_stream, **kwargs), file_opened
|
| 77 |
+
elif mjv == 1:
|
| 78 |
+
return MatFile5Reader(byte_stream, **kwargs), file_opened
|
| 79 |
+
elif mjv == 2:
|
| 80 |
+
raise NotImplementedError('Please use HDF reader for matlab v7.3 '
|
| 81 |
+
'files, e.g. h5py')
|
| 82 |
+
else:
|
| 83 |
+
raise TypeError(f'Did not recognize version {mjv}')
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@docfiller
|
| 87 |
+
def loadmat(file_name, mdict=None, appendmat=True, *, spmatrix=True, **kwargs):
|
| 88 |
+
"""
|
| 89 |
+
Load MATLAB file.
|
| 90 |
+
|
| 91 |
+
Parameters
|
| 92 |
+
----------
|
| 93 |
+
file_name : str
|
| 94 |
+
Name of the mat file (do not need .mat extension if
|
| 95 |
+
appendmat==True). Can also pass open file-like object.
|
| 96 |
+
mdict : dict, optional
|
| 97 |
+
Dictionary in which to insert matfile variables.
|
| 98 |
+
appendmat : bool, optional
|
| 99 |
+
True to append the .mat extension to the end of the given
|
| 100 |
+
filename, if not already present. Default is True.
|
| 101 |
+
spmatrix : bool, optional (default: True)
|
| 102 |
+
If ``True``, return sparse ``coo_matrix``. Otherwise return ``coo_array``.
|
| 103 |
+
Only relevant for sparse variables.
|
| 104 |
+
byte_order : str or None, optional
|
| 105 |
+
None by default, implying byte order guessed from mat
|
| 106 |
+
file. Otherwise can be one of ('native', '=', 'little', '<',
|
| 107 |
+
'BIG', '>').
|
| 108 |
+
mat_dtype : bool, optional
|
| 109 |
+
If True, return arrays in same dtype as would be loaded into
|
| 110 |
+
MATLAB (instead of the dtype with which they are saved).
|
| 111 |
+
squeeze_me : bool, optional
|
| 112 |
+
Whether to squeeze unit matrix dimensions or not.
|
| 113 |
+
chars_as_strings : bool, optional
|
| 114 |
+
Whether to convert char arrays to string arrays.
|
| 115 |
+
matlab_compatible : bool, optional
|
| 116 |
+
Returns matrices as would be loaded by MATLAB (implies
|
| 117 |
+
squeeze_me=False, chars_as_strings=False, mat_dtype=True,
|
| 118 |
+
struct_as_record=True).
|
| 119 |
+
struct_as_record : bool, optional
|
| 120 |
+
Whether to load MATLAB structs as NumPy record arrays, or as
|
| 121 |
+
old-style NumPy arrays with dtype=object. Setting this flag to
|
| 122 |
+
False replicates the behavior of scipy version 0.7.x (returning
|
| 123 |
+
NumPy object arrays). The default setting is True, because it
|
| 124 |
+
allows easier round-trip load and save of MATLAB files.
|
| 125 |
+
verify_compressed_data_integrity : bool, optional
|
| 126 |
+
Whether the length of compressed sequences in the MATLAB file
|
| 127 |
+
should be checked, to ensure that they are not longer than we expect.
|
| 128 |
+
It is advisable to enable this (the default) because overlong
|
| 129 |
+
compressed sequences in MATLAB files generally indicate that the
|
| 130 |
+
files have experienced some sort of corruption.
|
| 131 |
+
variable_names : None or sequence
|
| 132 |
+
If None (the default) - read all variables in file. Otherwise,
|
| 133 |
+
`variable_names` should be a sequence of strings, giving names of the
|
| 134 |
+
MATLAB variables to read from the file. The reader will skip any
|
| 135 |
+
variable with a name not in this sequence, possibly saving some read
|
| 136 |
+
processing.
|
| 137 |
+
simplify_cells : False, optional
|
| 138 |
+
If True, return a simplified dict structure (which is useful if the mat
|
| 139 |
+
file contains cell arrays). Note that this only affects the structure
|
| 140 |
+
of the result and not its contents (which is identical for both output
|
| 141 |
+
structures). If True, this automatically sets `struct_as_record` to
|
| 142 |
+
False and `squeeze_me` to True, which is required to simplify cells.
|
| 143 |
+
uint16_codec : str, optional
|
| 144 |
+
The codec to use for decoding characters, which are stored as uint16
|
| 145 |
+
values. The default uses the system encoding, but this can be manually
|
| 146 |
+
set to other values such as 'ascii', 'latin1', and 'utf-8'. This
|
| 147 |
+
parameter is relevant only for files stored as v6 and above, and not
|
| 148 |
+
for files stored as v4.
|
| 149 |
+
|
| 150 |
+
Returns
|
| 151 |
+
-------
|
| 152 |
+
mat_dict : dict
|
| 153 |
+
dictionary with variable names as keys, and loaded matrices as values.
|
| 154 |
+
|
| 155 |
+
Notes
|
| 156 |
+
-----
|
| 157 |
+
v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.
|
| 158 |
+
|
| 159 |
+
You will need an HDF5 Python library to read MATLAB 7.3 format mat
|
| 160 |
+
files. Because SciPy does not supply one, we do not implement the
|
| 161 |
+
HDF5 / 7.3 interface here.
|
| 162 |
+
|
| 163 |
+
Examples
|
| 164 |
+
--------
|
| 165 |
+
>>> from os.path import dirname, join as pjoin
|
| 166 |
+
>>> import scipy.io as sio
|
| 167 |
+
|
| 168 |
+
Get the filename for an example .mat file from the tests/data directory.
|
| 169 |
+
|
| 170 |
+
>>> data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data')
|
| 171 |
+
>>> mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat')
|
| 172 |
+
|
| 173 |
+
Load the .mat file contents.
|
| 174 |
+
|
| 175 |
+
>>> mat_contents = sio.loadmat(mat_fname, spmatrix=False)
|
| 176 |
+
|
| 177 |
+
The result is a dictionary, one key/value pair for each variable:
|
| 178 |
+
|
| 179 |
+
>>> sorted(mat_contents.keys())
|
| 180 |
+
['__globals__', '__header__', '__version__', 'testdouble']
|
| 181 |
+
>>> mat_contents['testdouble']
|
| 182 |
+
array([[0. , 0.78539816, 1.57079633, 2.35619449, 3.14159265,
|
| 183 |
+
3.92699082, 4.71238898, 5.49778714, 6.28318531]])
|
| 184 |
+
|
| 185 |
+
By default SciPy reads MATLAB structs as structured NumPy arrays where the
|
| 186 |
+
dtype fields are of type `object` and the names correspond to the MATLAB
|
| 187 |
+
struct field names. This can be disabled by setting the optional argument
|
| 188 |
+
`struct_as_record=False`.
|
| 189 |
+
|
| 190 |
+
Get the filename for an example .mat file that contains a MATLAB struct
|
| 191 |
+
called `teststruct` and load the contents.
|
| 192 |
+
|
| 193 |
+
>>> matstruct_fname = pjoin(data_dir, 'teststruct_7.4_GLNX86.mat')
|
| 194 |
+
>>> matstruct_contents = sio.loadmat(matstruct_fname)
|
| 195 |
+
>>> teststruct = matstruct_contents['teststruct']
|
| 196 |
+
>>> teststruct.dtype
|
| 197 |
+
dtype([('stringfield', 'O'), ('doublefield', 'O'), ('complexfield', 'O')])
|
| 198 |
+
|
| 199 |
+
The size of the structured array is the size of the MATLAB struct, not the
|
| 200 |
+
number of elements in any particular field. The shape defaults to 2-D
|
| 201 |
+
unless the optional argument `squeeze_me=True`, in which case all length 1
|
| 202 |
+
dimensions are removed.
|
| 203 |
+
|
| 204 |
+
>>> teststruct.size
|
| 205 |
+
1
|
| 206 |
+
>>> teststruct.shape
|
| 207 |
+
(1, 1)
|
| 208 |
+
|
| 209 |
+
Get the 'stringfield' of the first element in the MATLAB struct.
|
| 210 |
+
|
| 211 |
+
>>> teststruct[0, 0]['stringfield']
|
| 212 |
+
array(['Rats live on no evil star.'],
|
| 213 |
+
dtype='<U26')
|
| 214 |
+
|
| 215 |
+
Get the first element of the 'doublefield'.
|
| 216 |
+
|
| 217 |
+
>>> teststruct['doublefield'][0, 0]
|
| 218 |
+
array([[ 1.41421356, 2.71828183, 3.14159265]])
|
| 219 |
+
|
| 220 |
+
Load the MATLAB struct, squeezing out length 1 dimensions, and get the item
|
| 221 |
+
from the 'complexfield'.
|
| 222 |
+
|
| 223 |
+
>>> matstruct_squeezed = sio.loadmat(matstruct_fname, squeeze_me=True)
|
| 224 |
+
>>> matstruct_squeezed['teststruct'].shape
|
| 225 |
+
()
|
| 226 |
+
>>> matstruct_squeezed['teststruct']['complexfield'].shape
|
| 227 |
+
()
|
| 228 |
+
>>> matstruct_squeezed['teststruct']['complexfield'].item()
|
| 229 |
+
array([ 1.41421356+1.41421356j, 2.71828183+2.71828183j,
|
| 230 |
+
3.14159265+3.14159265j])
|
| 231 |
+
"""
|
| 232 |
+
variable_names = kwargs.pop('variable_names', None)
|
| 233 |
+
with _open_file_context(file_name, appendmat) as f:
|
| 234 |
+
MR, _ = mat_reader_factory(f, **kwargs)
|
| 235 |
+
matfile_dict = MR.get_variables(variable_names)
|
| 236 |
+
if spmatrix:
|
| 237 |
+
from scipy.sparse import issparse, coo_matrix
|
| 238 |
+
for name, var in list(matfile_dict.items()):
|
| 239 |
+
if issparse(var):
|
| 240 |
+
matfile_dict[name] = coo_matrix(var)
|
| 241 |
+
|
| 242 |
+
if mdict is not None:
|
| 243 |
+
mdict.update(matfile_dict)
|
| 244 |
+
else:
|
| 245 |
+
mdict = matfile_dict
|
| 246 |
+
|
| 247 |
+
return mdict
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@docfiller
|
| 251 |
+
def savemat(file_name, mdict,
|
| 252 |
+
appendmat=True,
|
| 253 |
+
format='5',
|
| 254 |
+
long_field_names=False,
|
| 255 |
+
do_compression=False,
|
| 256 |
+
oned_as='row'):
|
| 257 |
+
"""
|
| 258 |
+
Save a dictionary of names and arrays into a MATLAB-style .mat file.
|
| 259 |
+
|
| 260 |
+
This saves the array objects in the given dictionary to a MATLAB-
|
| 261 |
+
style .mat file.
|
| 262 |
+
|
| 263 |
+
Parameters
|
| 264 |
+
----------
|
| 265 |
+
file_name : str or file-like object
|
| 266 |
+
Name of the .mat file (.mat extension not needed if ``appendmat ==
|
| 267 |
+
True``).
|
| 268 |
+
Can also pass open file_like object.
|
| 269 |
+
mdict : dict
|
| 270 |
+
Dictionary from which to save matfile variables.
|
| 271 |
+
appendmat : bool, optional
|
| 272 |
+
True (the default) to append the .mat extension to the end of the
|
| 273 |
+
given filename, if not already present.
|
| 274 |
+
format : {'5', '4'}, string, optional
|
| 275 |
+
'5' (the default) for MATLAB 5 and up (to 7.2),
|
| 276 |
+
'4' for MATLAB 4 .mat files.
|
| 277 |
+
long_field_names : bool, optional
|
| 278 |
+
False (the default) - maximum field name length in a structure is
|
| 279 |
+
31 characters which is the documented maximum length.
|
| 280 |
+
True - maximum field name length in a structure is 63 characters
|
| 281 |
+
which works for MATLAB 7.6+.
|
| 282 |
+
do_compression : bool, optional
|
| 283 |
+
Whether or not to compress matrices on write. Default is False.
|
| 284 |
+
oned_as : {'row', 'column'}, optional
|
| 285 |
+
If 'column', write 1-D NumPy arrays as column vectors.
|
| 286 |
+
If 'row', write 1-D NumPy arrays as row vectors.
|
| 287 |
+
|
| 288 |
+
Examples
|
| 289 |
+
--------
|
| 290 |
+
>>> from scipy.io import savemat
|
| 291 |
+
>>> import numpy as np
|
| 292 |
+
>>> a = np.arange(20)
|
| 293 |
+
>>> mdic = {"a": a, "label": "experiment"}
|
| 294 |
+
>>> mdic
|
| 295 |
+
{'a': array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
|
| 296 |
+
17, 18, 19]),
|
| 297 |
+
'label': 'experiment'}
|
| 298 |
+
>>> savemat("matlab_matrix.mat", mdic)
|
| 299 |
+
"""
|
| 300 |
+
with _open_file_context(file_name, appendmat, 'wb') as file_stream:
|
| 301 |
+
if format == '4':
|
| 302 |
+
if long_field_names:
|
| 303 |
+
message = "Long field names are not available for version 4 files"
|
| 304 |
+
raise ValueError(message)
|
| 305 |
+
MW = MatFile4Writer(file_stream, oned_as)
|
| 306 |
+
elif format == '5':
|
| 307 |
+
MW = MatFile5Writer(file_stream,
|
| 308 |
+
do_compression=do_compression,
|
| 309 |
+
unicode_strings=True,
|
| 310 |
+
long_field_names=long_field_names,
|
| 311 |
+
oned_as=oned_as)
|
| 312 |
+
else:
|
| 313 |
+
raise ValueError("Format should be '4' or '5'")
|
| 314 |
+
MW.put_variables(mdict)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@docfiller
|
| 318 |
+
def whosmat(file_name, appendmat=True, **kwargs):
|
| 319 |
+
"""
|
| 320 |
+
List variables inside a MATLAB file.
|
| 321 |
+
|
| 322 |
+
Parameters
|
| 323 |
+
----------
|
| 324 |
+
%(file_arg)s
|
| 325 |
+
%(append_arg)s
|
| 326 |
+
%(load_args)s
|
| 327 |
+
%(struct_arg)s
|
| 328 |
+
|
| 329 |
+
Returns
|
| 330 |
+
-------
|
| 331 |
+
variables : list of tuples
|
| 332 |
+
A list of tuples, where each tuple holds the matrix name (a string),
|
| 333 |
+
its shape (tuple of ints), and its data class (a string).
|
| 334 |
+
Possible data classes are: int8, uint8, int16, uint16, int32, uint32,
|
| 335 |
+
int64, uint64, single, double, cell, struct, object, char, sparse,
|
| 336 |
+
function, opaque, logical, unknown.
|
| 337 |
+
|
| 338 |
+
Notes
|
| 339 |
+
-----
|
| 340 |
+
v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported.
|
| 341 |
+
|
| 342 |
+
You will need an HDF5 python library to read matlab 7.3 format mat
|
| 343 |
+
files (e.g. h5py). Because SciPy does not supply one, we do not implement the
|
| 344 |
+
HDF5 / 7.3 interface here.
|
| 345 |
+
|
| 346 |
+
.. versionadded:: 0.12.0
|
| 347 |
+
|
| 348 |
+
Examples
|
| 349 |
+
--------
|
| 350 |
+
>>> from io import BytesIO
|
| 351 |
+
>>> import numpy as np
|
| 352 |
+
>>> from scipy.io import savemat, whosmat
|
| 353 |
+
|
| 354 |
+
Create some arrays, and use `savemat` to write them to a ``BytesIO``
|
| 355 |
+
instance.
|
| 356 |
+
|
| 357 |
+
>>> a = np.array([[10, 20, 30], [11, 21, 31]], dtype=np.int32)
|
| 358 |
+
>>> b = np.geomspace(1, 10, 5)
|
| 359 |
+
>>> f = BytesIO()
|
| 360 |
+
>>> savemat(f, {'a': a, 'b': b})
|
| 361 |
+
|
| 362 |
+
Use `whosmat` to inspect ``f``. Each tuple in the output list gives
|
| 363 |
+
the name, shape and data type of the array in ``f``.
|
| 364 |
+
|
| 365 |
+
>>> whosmat(f)
|
| 366 |
+
[('a', (2, 3), 'int32'), ('b', (1, 5), 'double')]
|
| 367 |
+
|
| 368 |
+
"""
|
| 369 |
+
with _open_file_context(file_name, appendmat) as f:
|
| 370 |
+
ML, file_opened = mat_reader_factory(f, **kwargs)
|
| 371 |
+
variables = ML.list_variables()
|
| 372 |
+
return variables
|
shared/package-files/41/41b0189d71536ce4b79f53a7b5a096235c775c86d65fdea8470cb203d039bd9c/blob
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Tuple
|
| 2 |
+
|
| 3 |
+
from . import _LangModelType
|
| 4 |
+
|
| 5 |
+
KOI8R_char_to_order_map: Tuple[int, ...]
|
| 6 |
+
win1251_char_to_order_map: Tuple[int, ...]
|
| 7 |
+
latin5_char_to_order_map: Tuple[int, ...]
|
| 8 |
+
macCyrillic_char_to_order_map: Tuple[int, ...]
|
| 9 |
+
IBM855_char_to_order_map: Tuple[int, ...]
|
| 10 |
+
IBM866_char_to_order_map: Tuple[int, ...]
|
| 11 |
+
RussianLangModel: Tuple[int, ...]
|
| 12 |
+
Koi8rModel: _LangModelType
|
| 13 |
+
Win1251CyrillicModel: _LangModelType
|
| 14 |
+
Latin5CyrillicModel: _LangModelType
|
| 15 |
+
MacCyrillicModel: _LangModelType
|
| 16 |
+
Ibm866Model: _LangModelType
|
| 17 |
+
Ibm855Model: _LangModelType
|
shared/package-files/41/41b0c932922029d59dd6b99c62e4a11c41827599ee5a29a217cbffb77a77793b/blob
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates
|
| 2 |
+
from typing import Dict, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.distributed._tensor.random as random
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from torch.distributed._tensor import (
|
| 8 |
+
DeviceMesh,
|
| 9 |
+
)
|
| 10 |
+
from torch.distributed._tensor.random import (
|
| 11 |
+
is_rng_supported_mesh,
|
| 12 |
+
TensorParallelRNGTracker,
|
| 13 |
+
)
|
| 14 |
+
from torch.distributed.tensor.parallel._utils import _validate_tp_mesh_dim
|
| 15 |
+
from torch.distributed.tensor.parallel.style import (
|
| 16 |
+
ParallelStyle,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
"parallelize_module",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def parallelize_module( # type: ignore[return]
|
| 26 |
+
module: nn.Module,
|
| 27 |
+
device_mesh: DeviceMesh,
|
| 28 |
+
parallelize_plan: Union[ParallelStyle, Dict[str, ParallelStyle]],
|
| 29 |
+
) -> nn.Module:
|
| 30 |
+
"""
|
| 31 |
+
Apply Tensor Parallelism in PyTorch by parallelizing modules or sub-modules based on a user-specified plan.
|
| 32 |
+
|
| 33 |
+
We parallelize module or sub_modules based on a parallelize_plan. The parallelize_plan contains
|
| 34 |
+
:class:`ParallelStyle`, which indicates how user wants the module or sub_module
|
| 35 |
+
to be parallelized.
|
| 36 |
+
|
| 37 |
+
User can also specify different parallel style per module fully qualified name (FQN).
|
| 38 |
+
|
| 39 |
+
Note that ``parallelize_module`` only accepts a 1-D :class:`DeviceMesh`, if you have a 2-D or N-D :class:`DeviceMesh`,
|
| 40 |
+
slice the DeviceMesh to a 1-D sub DeviceMesh first then pass to this API(i.e. ``device_mesh[\"tp\"]``)
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
module (:class:`nn.Module`):
|
| 44 |
+
Module to be parallelized.
|
| 45 |
+
device_mesh (:class:`DeviceMesh`):
|
| 46 |
+
Object which describes the mesh topology
|
| 47 |
+
of devices for the DTensor.
|
| 48 |
+
parallelize_plan (Union[:class:`ParallelStyle`, Dict[str, :class:`ParallelStyle`]]):
|
| 49 |
+
The plan used to parallelize the module. It can be either a
|
| 50 |
+
:class:`ParallelStyle` object which contains how
|
| 51 |
+
we prepare input/output for Tensor Parallelism or it can be a
|
| 52 |
+
dict of module FQN and its corresponding :class:`ParallelStyle` object.
|
| 53 |
+
Return:
|
| 54 |
+
A :class:`nn.Module` object parallelized.
|
| 55 |
+
|
| 56 |
+
Example::
|
| 57 |
+
>>> # xdoctest: +SKIP("distributed")
|
| 58 |
+
>>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel
|
| 59 |
+
>>> from torch.distributed.device_mesh import init_device_mesh
|
| 60 |
+
>>>
|
| 61 |
+
>>> # Define the module.
|
| 62 |
+
>>> m = Model(...)
|
| 63 |
+
>>> tp_mesh = init_device_mesh("cuda", (8,))
|
| 64 |
+
>>> m = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel(), "w2": RowwiseParallel()})
|
| 65 |
+
>>>
|
| 66 |
+
|
| 67 |
+
.. note:: For complex module architecture like Attention, MLP layers, we recommend composing
|
| 68 |
+
different ParallelStyles together (i.e. ``ColwiseParallel`` and ``RowwiseParallel``) and pass
|
| 69 |
+
as a parallelize_plan, to achieves the desired sharding computation.
|
| 70 |
+
"""
|
| 71 |
+
torch._C._log_api_usage_once("torch.distributed.tensor.parallel.parallelize_module")
|
| 72 |
+
|
| 73 |
+
_validate_tp_mesh_dim(device_mesh)
|
| 74 |
+
|
| 75 |
+
# instantiate a TP RNG state tracker if it's not there
|
| 76 |
+
if is_rng_supported_mesh(device_mesh) and not isinstance(
|
| 77 |
+
random._rng_tracker, TensorParallelRNGTracker
|
| 78 |
+
):
|
| 79 |
+
random._rng_tracker = TensorParallelRNGTracker(device_mesh.device_type)
|
| 80 |
+
# TODO: we should allow user to pass in the default seed from a config
|
| 81 |
+
random._rng_tracker._manual_seed(device_mesh, base_seed=1234)
|
| 82 |
+
# By default we execute random ops in non-tensor-parallel region. If users want
|
| 83 |
+
# to execute in tensor-parallel region, they can manually set this field to True
|
| 84 |
+
# after parallelizing the model.
|
| 85 |
+
random._rng_tracker.distribute_region_enabled = False
|
| 86 |
+
|
| 87 |
+
if isinstance(parallelize_plan, ParallelStyle):
|
| 88 |
+
return parallelize_plan._apply(module, device_mesh)
|
| 89 |
+
elif isinstance(parallelize_plan, dict):
|
| 90 |
+
for module_path, parallelize_style in parallelize_plan.items():
|
| 91 |
+
sub_module = module.get_submodule(module_path)
|
| 92 |
+
parent_module = module
|
| 93 |
+
if "." in module_path:
|
| 94 |
+
parent_module_path = ".".join(module_path.split(".")[:-1])
|
| 95 |
+
parent_module = module.get_submodule(parent_module_path)
|
| 96 |
+
module_path = module_path.split(".")[-1]
|
| 97 |
+
parent_module.register_module( # type: ignore[call-arg] # pyre-ignore[20]
|
| 98 |
+
module_path,
|
| 99 |
+
parallelize_module( # type: ignore[arg-type]
|
| 100 |
+
sub_module, device_mesh, parallelize_style # type: ignore[arg-type] # pyre-ignore[6]
|
| 101 |
+
),
|
| 102 |
+
)
|
| 103 |
+
return module
|
| 104 |
+
else:
|
| 105 |
+
raise RuntimeError( # pyre-ignore[7]
|
| 106 |
+
"Expect Union[ParallelStyle, Dict[str, ParallelStyle]] for"
|
| 107 |
+
f" parallelize_plan, {type(parallelize_plan)} found!"
|
| 108 |
+
)
|
shared/package-files/41/41b37281c4f21f309f4a934aef0159409d9d109d5ddae2142546232e5b2f9011/blob
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# The Python Imaging Library.
|
| 3 |
+
# $Id$
|
| 4 |
+
#
|
| 5 |
+
# transform wrappers
|
| 6 |
+
#
|
| 7 |
+
# History:
|
| 8 |
+
# 2002-04-08 fl Created
|
| 9 |
+
#
|
| 10 |
+
# Copyright (c) 2002 by Secret Labs AB
|
| 11 |
+
# Copyright (c) 2002 by Fredrik Lundh
|
| 12 |
+
#
|
| 13 |
+
# See the README file for information on usage and redistribution.
|
| 14 |
+
#
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from typing import Sequence
|
| 18 |
+
|
| 19 |
+
from . import Image
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Transform(Image.ImageTransformHandler):
|
| 23 |
+
method: Image.Transform
|
| 24 |
+
|
| 25 |
+
def __init__(self, data: Sequence[int]) -> None:
|
| 26 |
+
self.data = data
|
| 27 |
+
|
| 28 |
+
def getdata(self) -> tuple[int, Sequence[int]]:
|
| 29 |
+
return self.method, self.data
|
| 30 |
+
|
| 31 |
+
def transform(
|
| 32 |
+
self,
|
| 33 |
+
size: tuple[int, int],
|
| 34 |
+
image: Image.Image,
|
| 35 |
+
**options: dict[str, str | int | tuple[int, ...] | list[int]],
|
| 36 |
+
) -> Image.Image:
|
| 37 |
+
# can be overridden
|
| 38 |
+
method, data = self.getdata()
|
| 39 |
+
return image.transform(size, method, data, **options)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class AffineTransform(Transform):
|
| 43 |
+
"""
|
| 44 |
+
Define an affine image transform.
|
| 45 |
+
|
| 46 |
+
This function takes a 6-tuple (a, b, c, d, e, f) which contain the first
|
| 47 |
+
two rows from an affine transform matrix. For each pixel (x, y) in the
|
| 48 |
+
output image, the new value is taken from a position (a x + b y + c,
|
| 49 |
+
d x + e y + f) in the input image, rounded to nearest pixel.
|
| 50 |
+
|
| 51 |
+
This function can be used to scale, translate, rotate, and shear the
|
| 52 |
+
original image.
|
| 53 |
+
|
| 54 |
+
See :py:meth:`~PIL.Image.Image.transform`
|
| 55 |
+
|
| 56 |
+
:param matrix: A 6-tuple (a, b, c, d, e, f) containing the first two rows
|
| 57 |
+
from an affine transform matrix.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
method = Image.Transform.AFFINE
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class ExtentTransform(Transform):
|
| 64 |
+
"""
|
| 65 |
+
Define a transform to extract a subregion from an image.
|
| 66 |
+
|
| 67 |
+
Maps a rectangle (defined by two corners) from the image to a rectangle of
|
| 68 |
+
the given size. The resulting image will contain data sampled from between
|
| 69 |
+
the corners, such that (x0, y0) in the input image will end up at (0,0) in
|
| 70 |
+
the output image, and (x1, y1) at size.
|
| 71 |
+
|
| 72 |
+
This method can be used to crop, stretch, shrink, or mirror an arbitrary
|
| 73 |
+
rectangle in the current image. It is slightly slower than crop, but about
|
| 74 |
+
as fast as a corresponding resize operation.
|
| 75 |
+
|
| 76 |
+
See :py:meth:`~PIL.Image.Image.transform`
|
| 77 |
+
|
| 78 |
+
:param bbox: A 4-tuple (x0, y0, x1, y1) which specifies two points in the
|
| 79 |
+
input image's coordinate system. See :ref:`coordinate-system`.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
method = Image.Transform.EXTENT
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class QuadTransform(Transform):
|
| 86 |
+
"""
|
| 87 |
+
Define a quad image transform.
|
| 88 |
+
|
| 89 |
+
Maps a quadrilateral (a region defined by four corners) from the image to a
|
| 90 |
+
rectangle of the given size.
|
| 91 |
+
|
| 92 |
+
See :py:meth:`~PIL.Image.Image.transform`
|
| 93 |
+
|
| 94 |
+
:param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the
|
| 95 |
+
upper left, lower left, lower right, and upper right corner of the
|
| 96 |
+
source quadrilateral.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
method = Image.Transform.QUAD
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class MeshTransform(Transform):
|
| 103 |
+
"""
|
| 104 |
+
Define a mesh image transform. A mesh transform consists of one or more
|
| 105 |
+
individual quad transforms.
|
| 106 |
+
|
| 107 |
+
See :py:meth:`~PIL.Image.Image.transform`
|
| 108 |
+
|
| 109 |
+
:param data: A list of (bbox, quad) tuples.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
method = Image.Transform.MESH
|
shared/package-files/41/41b5052fe85ce699fef7db72e3cec88ff2434b925f5883da732441b95fa1a437/blob
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API int64_t _fused_sdp_choice_cpp(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional<at::Tensor> & attn_mask={}, double dropout_p=0.0, bool is_causal=false, c10::optional<double> scale=c10::nullopt);
|
| 20 |
+
TORCH_API int64_t _fused_sdp_choice_cuda(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional<at::Tensor> & attn_mask={}, double dropout_p=0.0, bool is_causal=false, c10::optional<double> scale=c10::nullopt);
|
| 21 |
+
TORCH_API int64_t _fused_sdp_choice_meta(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional<at::Tensor> & attn_mask={}, double dropout_p=0.0, bool is_causal=false, c10::optional<double> scale=c10::nullopt);
|
| 22 |
+
} // namespace native
|
| 23 |
+
} // namespace at
|
shared/package-files/41/41b64e0aa22f9da2b45ce1f791a49705efa6ff5fd16f7de9b2af04f963120535/blob
ADDED
|
Binary file (229 Bytes). View file
|
|
|
shared/package-files/41/41b65e49401b21d55f0d478d672cb2fa5f01a9b2b2f0bf947936bcf0073444dc/blob
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
class Sharder(abc.ABC):
|
| 5 |
+
"""
|
| 6 |
+
This is an interface which allows user to create more advanced
|
| 7 |
+
sharding strategies that are not easily be composed by the
|
| 8 |
+
`ShardingSpec`.
|
| 9 |
+
|
| 10 |
+
:class:`torch.distributed._shard.sharding_plan.ShardingPlan` could
|
| 11 |
+
take an object of the `Sharder` and call `shard` to shard the module,
|
| 12 |
+
then replace the original module with sharded module returned.
|
| 13 |
+
"""
|
| 14 |
+
@abc.abstractmethod
|
| 15 |
+
def shard(self, module: nn.Module) -> nn.Module:
|
| 16 |
+
"""
|
| 17 |
+
Shard a module base on the implementation of this method, and
|
| 18 |
+
return the sharded version of the module.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
module (:class:`torch.nn.Module`):
|
| 22 |
+
The module to apply sharding to.
|
| 23 |
+
Returns:
|
| 24 |
+
A :class:`torch.nn.Module` object that represents a module
|
| 25 |
+
that's already been sharded.
|
| 26 |
+
"""
|
| 27 |
+
pass
|
shared/package-files/41/41b8ab7ebbcab1e626accda42e31c784d18d80ee83b07252d6772e1f93e73d3e/blob
ADDED
|
@@ -0,0 +1,2387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This is our testing framework.
|
| 3 |
+
|
| 4 |
+
Goals:
|
| 5 |
+
|
| 6 |
+
* it should be compatible with py.test and operate very similarly
|
| 7 |
+
(or identically)
|
| 8 |
+
* does not require any external dependencies
|
| 9 |
+
* preferably all the functionality should be in this file only
|
| 10 |
+
* no magic, just import the test file and execute the test functions, that's it
|
| 11 |
+
* portable
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import platform
|
| 18 |
+
import inspect
|
| 19 |
+
import traceback
|
| 20 |
+
import pdb
|
| 21 |
+
import re
|
| 22 |
+
import linecache
|
| 23 |
+
import time
|
| 24 |
+
from fnmatch import fnmatch
|
| 25 |
+
from timeit import default_timer as clock
|
| 26 |
+
import doctest as pdoctest # avoid clashing with our doctest() function
|
| 27 |
+
from doctest import DocTestFinder, DocTestRunner
|
| 28 |
+
import random
|
| 29 |
+
import subprocess
|
| 30 |
+
import shutil
|
| 31 |
+
import signal
|
| 32 |
+
import stat
|
| 33 |
+
import tempfile
|
| 34 |
+
import warnings
|
| 35 |
+
from contextlib import contextmanager
|
| 36 |
+
from inspect import unwrap
|
| 37 |
+
|
| 38 |
+
from sympy.core.cache import clear_cache
|
| 39 |
+
from sympy.external import import_module
|
| 40 |
+
from sympy.external.gmpy import GROUND_TYPES, HAS_GMPY
|
| 41 |
+
|
| 42 |
+
IS_WINDOWS = (os.name == 'nt')
|
| 43 |
+
ON_CI = os.getenv('CI', None)
|
| 44 |
+
|
| 45 |
+
# empirically generated list of the proportion of time spent running
|
| 46 |
+
# an even split of tests. This should periodically be regenerated.
|
| 47 |
+
# A list of [.6, .1, .3] would mean that if the tests are evenly split
|
| 48 |
+
# into '1/3', '2/3', '3/3', the first split would take 60% of the time,
|
| 49 |
+
# the second 10% and the third 30%. These lists are normalized to sum
|
| 50 |
+
# to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3].
|
| 51 |
+
#
|
| 52 |
+
# This list can be generated with the code:
|
| 53 |
+
# from time import time
|
| 54 |
+
# import sympy
|
| 55 |
+
# import os
|
| 56 |
+
# os.environ["CI"] = 'true' # Mock CI to get more correct densities
|
| 57 |
+
# delays, num_splits = [], 30
|
| 58 |
+
# for i in range(1, num_splits + 1):
|
| 59 |
+
# tic = time()
|
| 60 |
+
# sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests
|
| 61 |
+
# delays.append(time() - tic)
|
| 62 |
+
# tot = sum(delays)
|
| 63 |
+
# print([round(x / tot, 4) for x in delays])
|
| 64 |
+
SPLIT_DENSITY = [
|
| 65 |
+
0.0059, 0.0027, 0.0068, 0.0011, 0.0006,
|
| 66 |
+
0.0058, 0.0047, 0.0046, 0.004, 0.0257,
|
| 67 |
+
0.0017, 0.0026, 0.004, 0.0032, 0.0016,
|
| 68 |
+
0.0015, 0.0004, 0.0011, 0.0016, 0.0014,
|
| 69 |
+
0.0077, 0.0137, 0.0217, 0.0074, 0.0043,
|
| 70 |
+
0.0067, 0.0236, 0.0004, 0.1189, 0.0142,
|
| 71 |
+
0.0234, 0.0003, 0.0003, 0.0047, 0.0006,
|
| 72 |
+
0.0013, 0.0004, 0.0008, 0.0007, 0.0006,
|
| 73 |
+
0.0139, 0.0013, 0.0007, 0.0051, 0.002,
|
| 74 |
+
0.0004, 0.0005, 0.0213, 0.0048, 0.0016,
|
| 75 |
+
0.0012, 0.0014, 0.0024, 0.0015, 0.0004,
|
| 76 |
+
0.0005, 0.0007, 0.011, 0.0062, 0.0015,
|
| 77 |
+
0.0021, 0.0049, 0.0006, 0.0006, 0.0011,
|
| 78 |
+
0.0006, 0.0019, 0.003, 0.0044, 0.0054,
|
| 79 |
+
0.0057, 0.0049, 0.0016, 0.0006, 0.0009,
|
| 80 |
+
0.0006, 0.0012, 0.0006, 0.0149, 0.0532,
|
| 81 |
+
0.0076, 0.0041, 0.0024, 0.0135, 0.0081,
|
| 82 |
+
0.2209, 0.0459, 0.0438, 0.0488, 0.0137,
|
| 83 |
+
0.002, 0.0003, 0.0008, 0.0039, 0.0024,
|
| 84 |
+
0.0005, 0.0004, 0.003, 0.056, 0.0026]
|
| 85 |
+
SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483]
|
| 86 |
+
|
| 87 |
+
class Skipped(Exception):
|
| 88 |
+
pass
|
| 89 |
+
|
| 90 |
+
class TimeOutError(Exception):
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
class DependencyError(Exception):
|
| 94 |
+
pass
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _indent(s, indent=4):
|
| 98 |
+
"""
|
| 99 |
+
Add the given number of space characters to the beginning of
|
| 100 |
+
every non-blank line in ``s``, and return the result.
|
| 101 |
+
If the string ``s`` is Unicode, it is encoded using the stdout
|
| 102 |
+
encoding and the ``backslashreplace`` error handler.
|
| 103 |
+
"""
|
| 104 |
+
# This regexp matches the start of non-blank lines:
|
| 105 |
+
return re.sub('(?m)^(?!$)', indent*' ', s)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
pdoctest._indent = _indent # type: ignore
|
| 109 |
+
|
| 110 |
+
# override reporter to maintain windows and python3
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _report_failure(self, out, test, example, got):
|
| 114 |
+
"""
|
| 115 |
+
Report that the given example failed.
|
| 116 |
+
"""
|
| 117 |
+
s = self._checker.output_difference(example, got, self.optionflags)
|
| 118 |
+
s = s.encode('raw_unicode_escape').decode('utf8', 'ignore')
|
| 119 |
+
out(self._failure_header(test, example) + s)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if IS_WINDOWS:
|
| 123 |
+
DocTestRunner.report_failure = _report_failure # type: ignore
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def convert_to_native_paths(lst):
|
| 127 |
+
"""
|
| 128 |
+
Converts a list of '/' separated paths into a list of
|
| 129 |
+
native (os.sep separated) paths and converts to lowercase
|
| 130 |
+
if the system is case insensitive.
|
| 131 |
+
"""
|
| 132 |
+
newlst = []
|
| 133 |
+
for i, rv in enumerate(lst):
|
| 134 |
+
rv = os.path.join(*rv.split("/"))
|
| 135 |
+
# on windows the slash after the colon is dropped
|
| 136 |
+
if sys.platform == "win32":
|
| 137 |
+
pos = rv.find(':')
|
| 138 |
+
if pos != -1:
|
| 139 |
+
if rv[pos + 1] != '\\':
|
| 140 |
+
rv = rv[:pos + 1] + '\\' + rv[pos + 1:]
|
| 141 |
+
newlst.append(os.path.normcase(rv))
|
| 142 |
+
return newlst
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def get_sympy_dir():
|
| 146 |
+
"""
|
| 147 |
+
Returns the root SymPy directory and set the global value
|
| 148 |
+
indicating whether the system is case sensitive or not.
|
| 149 |
+
"""
|
| 150 |
+
this_file = os.path.abspath(__file__)
|
| 151 |
+
sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..")
|
| 152 |
+
sympy_dir = os.path.normpath(sympy_dir)
|
| 153 |
+
return os.path.normcase(sympy_dir)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def setup_pprint():
|
| 157 |
+
from sympy.interactive.printing import init_printing
|
| 158 |
+
from sympy.printing.pretty.pretty import pprint_use_unicode
|
| 159 |
+
import sympy.interactive.printing as interactive_printing
|
| 160 |
+
|
| 161 |
+
# force pprint to be in ascii mode in doctests
|
| 162 |
+
use_unicode_prev = pprint_use_unicode(False)
|
| 163 |
+
|
| 164 |
+
# hook our nice, hash-stable strprinter
|
| 165 |
+
init_printing(pretty_print=False)
|
| 166 |
+
|
| 167 |
+
# Prevent init_printing() in doctests from affecting other doctests
|
| 168 |
+
interactive_printing.NO_GLOBAL = True
|
| 169 |
+
return use_unicode_prev
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@contextmanager
|
| 173 |
+
def raise_on_deprecated():
|
| 174 |
+
"""Context manager to make DeprecationWarning raise an error
|
| 175 |
+
|
| 176 |
+
This is to catch SymPyDeprecationWarning from library code while running
|
| 177 |
+
tests and doctests. It is important to use this context manager around
|
| 178 |
+
each individual test/doctest in case some tests modify the warning
|
| 179 |
+
filters.
|
| 180 |
+
"""
|
| 181 |
+
with warnings.catch_warnings():
|
| 182 |
+
warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*')
|
| 183 |
+
yield
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def run_in_subprocess_with_hash_randomization(
|
| 187 |
+
function, function_args=(),
|
| 188 |
+
function_kwargs=None, command=sys.executable,
|
| 189 |
+
module='sympy.testing.runtests', force=False):
|
| 190 |
+
"""
|
| 191 |
+
Run a function in a Python subprocess with hash randomization enabled.
|
| 192 |
+
|
| 193 |
+
If hash randomization is not supported by the version of Python given, it
|
| 194 |
+
returns False. Otherwise, it returns the exit value of the command. The
|
| 195 |
+
function is passed to sys.exit(), so the return value of the function will
|
| 196 |
+
be the return value.
|
| 197 |
+
|
| 198 |
+
The environment variable PYTHONHASHSEED is used to seed Python's hash
|
| 199 |
+
randomization. If it is set, this function will return False, because
|
| 200 |
+
starting a new subprocess is unnecessary in that case. If it is not set,
|
| 201 |
+
one is set at random, and the tests are run. Note that if this
|
| 202 |
+
environment variable is set when Python starts, hash randomization is
|
| 203 |
+
automatically enabled. To force a subprocess to be created even if
|
| 204 |
+
PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a
|
| 205 |
+
subprocess in Python versions that do not support hash randomization (see
|
| 206 |
+
below), because those versions of Python do not support the ``-R`` flag.
|
| 207 |
+
|
| 208 |
+
``function`` should be a string name of a function that is importable from
|
| 209 |
+
the module ``module``, like "_test". The default for ``module`` is
|
| 210 |
+
"sympy.testing.runtests". ``function_args`` and ``function_kwargs``
|
| 211 |
+
should be a repr-able tuple and dict, respectively. The default Python
|
| 212 |
+
command is sys.executable, which is the currently running Python command.
|
| 213 |
+
|
| 214 |
+
This function is necessary because the seed for hash randomization must be
|
| 215 |
+
set by the environment variable before Python starts. Hence, in order to
|
| 216 |
+
use a predetermined seed for tests, we must start Python in a separate
|
| 217 |
+
subprocess.
|
| 218 |
+
|
| 219 |
+
Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
|
| 220 |
+
3.1.5, and 3.2.3, and is enabled by default in all Python versions after
|
| 221 |
+
and including 3.3.0.
|
| 222 |
+
|
| 223 |
+
Examples
|
| 224 |
+
========
|
| 225 |
+
|
| 226 |
+
>>> from sympy.testing.runtests import (
|
| 227 |
+
... run_in_subprocess_with_hash_randomization)
|
| 228 |
+
>>> # run the core tests in verbose mode
|
| 229 |
+
>>> run_in_subprocess_with_hash_randomization("_test",
|
| 230 |
+
... function_args=("core",),
|
| 231 |
+
... function_kwargs={'verbose': True}) # doctest: +SKIP
|
| 232 |
+
# Will return 0 if sys.executable supports hash randomization and tests
|
| 233 |
+
# pass, 1 if they fail, and False if it does not support hash
|
| 234 |
+
# randomization.
|
| 235 |
+
|
| 236 |
+
"""
|
| 237 |
+
cwd = get_sympy_dir()
|
| 238 |
+
# Note, we must return False everywhere, not None, as subprocess.call will
|
| 239 |
+
# sometimes return None.
|
| 240 |
+
|
| 241 |
+
# First check if the Python version supports hash randomization
|
| 242 |
+
# If it does not have this support, it won't recognize the -R flag
|
| 243 |
+
p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE,
|
| 244 |
+
stderr=subprocess.STDOUT, cwd=cwd)
|
| 245 |
+
p.communicate()
|
| 246 |
+
if p.returncode != 0:
|
| 247 |
+
return False
|
| 248 |
+
|
| 249 |
+
hash_seed = os.getenv("PYTHONHASHSEED")
|
| 250 |
+
if not hash_seed:
|
| 251 |
+
os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32))
|
| 252 |
+
else:
|
| 253 |
+
if not force:
|
| 254 |
+
return False
|
| 255 |
+
|
| 256 |
+
function_kwargs = function_kwargs or {}
|
| 257 |
+
|
| 258 |
+
# Now run the command
|
| 259 |
+
commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" %
|
| 260 |
+
(module, function, function, repr(function_args),
|
| 261 |
+
repr(function_kwargs)))
|
| 262 |
+
|
| 263 |
+
try:
|
| 264 |
+
p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd)
|
| 265 |
+
p.communicate()
|
| 266 |
+
except KeyboardInterrupt:
|
| 267 |
+
p.wait()
|
| 268 |
+
finally:
|
| 269 |
+
# Put the environment variable back, so that it reads correctly for
|
| 270 |
+
# the current Python process.
|
| 271 |
+
if hash_seed is None:
|
| 272 |
+
del os.environ["PYTHONHASHSEED"]
|
| 273 |
+
else:
|
| 274 |
+
os.environ["PYTHONHASHSEED"] = hash_seed
|
| 275 |
+
return p.returncode
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def run_all_tests(test_args=(), test_kwargs=None,
|
| 279 |
+
doctest_args=(), doctest_kwargs=None,
|
| 280 |
+
examples_args=(), examples_kwargs=None):
|
| 281 |
+
"""
|
| 282 |
+
Run all tests.
|
| 283 |
+
|
| 284 |
+
Right now, this runs the regular tests (bin/test), the doctests
|
| 285 |
+
(bin/doctest), and the examples (examples/all.py).
|
| 286 |
+
|
| 287 |
+
This is what ``setup.py test`` uses.
|
| 288 |
+
|
| 289 |
+
You can pass arguments and keyword arguments to the test functions that
|
| 290 |
+
support them (for now, test, doctest, and the examples). See the
|
| 291 |
+
docstrings of those functions for a description of the available options.
|
| 292 |
+
|
| 293 |
+
For example, to run the solvers tests with colors turned off:
|
| 294 |
+
|
| 295 |
+
>>> from sympy.testing.runtests import run_all_tests
|
| 296 |
+
>>> run_all_tests(test_args=("solvers",),
|
| 297 |
+
... test_kwargs={"colors:False"}) # doctest: +SKIP
|
| 298 |
+
|
| 299 |
+
"""
|
| 300 |
+
tests_successful = True
|
| 301 |
+
|
| 302 |
+
test_kwargs = test_kwargs or {}
|
| 303 |
+
doctest_kwargs = doctest_kwargs or {}
|
| 304 |
+
examples_kwargs = examples_kwargs or {'quiet': True}
|
| 305 |
+
|
| 306 |
+
try:
|
| 307 |
+
# Regular tests
|
| 308 |
+
if not test(*test_args, **test_kwargs):
|
| 309 |
+
# some regular test fails, so set the tests_successful
|
| 310 |
+
# flag to false and continue running the doctests
|
| 311 |
+
tests_successful = False
|
| 312 |
+
|
| 313 |
+
# Doctests
|
| 314 |
+
print()
|
| 315 |
+
if not doctest(*doctest_args, **doctest_kwargs):
|
| 316 |
+
tests_successful = False
|
| 317 |
+
|
| 318 |
+
# Examples
|
| 319 |
+
print()
|
| 320 |
+
sys.path.append("examples") # examples/all.py
|
| 321 |
+
from all import run_examples # type: ignore
|
| 322 |
+
if not run_examples(*examples_args, **examples_kwargs):
|
| 323 |
+
tests_successful = False
|
| 324 |
+
|
| 325 |
+
if tests_successful:
|
| 326 |
+
return
|
| 327 |
+
else:
|
| 328 |
+
# Return nonzero exit code
|
| 329 |
+
sys.exit(1)
|
| 330 |
+
except KeyboardInterrupt:
|
| 331 |
+
print()
|
| 332 |
+
print("DO *NOT* COMMIT!")
|
| 333 |
+
sys.exit(1)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def test(*paths, subprocess=True, rerun=0, **kwargs):
|
| 337 |
+
"""
|
| 338 |
+
Run tests in the specified test_*.py files.
|
| 339 |
+
|
| 340 |
+
Tests in a particular test_*.py file are run if any of the given strings
|
| 341 |
+
in ``paths`` matches a part of the test file's path. If ``paths=[]``,
|
| 342 |
+
tests in all test_*.py files are run.
|
| 343 |
+
|
| 344 |
+
Notes:
|
| 345 |
+
|
| 346 |
+
- If sort=False, tests are run in random order (not default).
|
| 347 |
+
- Paths can be entered in native system format or in unix,
|
| 348 |
+
forward-slash format.
|
| 349 |
+
- Files that are on the blacklist can be tested by providing
|
| 350 |
+
their path; they are only excluded if no paths are given.
|
| 351 |
+
|
| 352 |
+
**Explanation of test results**
|
| 353 |
+
|
| 354 |
+
====== ===============================================================
|
| 355 |
+
Output Meaning
|
| 356 |
+
====== ===============================================================
|
| 357 |
+
. passed
|
| 358 |
+
F failed
|
| 359 |
+
X XPassed (expected to fail but passed)
|
| 360 |
+
f XFAILed (expected to fail and indeed failed)
|
| 361 |
+
s skipped
|
| 362 |
+
w slow
|
| 363 |
+
T timeout (e.g., when ``--timeout`` is used)
|
| 364 |
+
K KeyboardInterrupt (when running the slow tests with ``--slow``,
|
| 365 |
+
you can interrupt one of them without killing the test runner)
|
| 366 |
+
====== ===============================================================
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
Colors have no additional meaning and are used just to facilitate
|
| 370 |
+
interpreting the output.
|
| 371 |
+
|
| 372 |
+
Examples
|
| 373 |
+
========
|
| 374 |
+
|
| 375 |
+
>>> import sympy
|
| 376 |
+
|
| 377 |
+
Run all tests:
|
| 378 |
+
|
| 379 |
+
>>> sympy.test() # doctest: +SKIP
|
| 380 |
+
|
| 381 |
+
Run one file:
|
| 382 |
+
|
| 383 |
+
>>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP
|
| 384 |
+
>>> sympy.test("_basic") # doctest: +SKIP
|
| 385 |
+
|
| 386 |
+
Run all tests in sympy/functions/ and some particular file:
|
| 387 |
+
|
| 388 |
+
>>> sympy.test("sympy/core/tests/test_basic.py",
|
| 389 |
+
... "sympy/functions") # doctest: +SKIP
|
| 390 |
+
|
| 391 |
+
Run all tests in sympy/core and sympy/utilities:
|
| 392 |
+
|
| 393 |
+
>>> sympy.test("/core", "/util") # doctest: +SKIP
|
| 394 |
+
|
| 395 |
+
Run specific test from a file:
|
| 396 |
+
|
| 397 |
+
>>> sympy.test("sympy/core/tests/test_basic.py",
|
| 398 |
+
... kw="test_equality") # doctest: +SKIP
|
| 399 |
+
|
| 400 |
+
Run specific test from any file:
|
| 401 |
+
|
| 402 |
+
>>> sympy.test(kw="subs") # doctest: +SKIP
|
| 403 |
+
|
| 404 |
+
Run the tests with verbose mode on:
|
| 405 |
+
|
| 406 |
+
>>> sympy.test(verbose=True) # doctest: +SKIP
|
| 407 |
+
|
| 408 |
+
Do not sort the test output:
|
| 409 |
+
|
| 410 |
+
>>> sympy.test(sort=False) # doctest: +SKIP
|
| 411 |
+
|
| 412 |
+
Turn on post-mortem pdb:
|
| 413 |
+
|
| 414 |
+
>>> sympy.test(pdb=True) # doctest: +SKIP
|
| 415 |
+
|
| 416 |
+
Turn off colors:
|
| 417 |
+
|
| 418 |
+
>>> sympy.test(colors=False) # doctest: +SKIP
|
| 419 |
+
|
| 420 |
+
Force colors, even when the output is not to a terminal (this is useful,
|
| 421 |
+
e.g., if you are piping to ``less -r`` and you still want colors)
|
| 422 |
+
|
| 423 |
+
>>> sympy.test(force_colors=False) # doctest: +SKIP
|
| 424 |
+
|
| 425 |
+
The traceback verboseness can be set to "short" or "no" (default is
|
| 426 |
+
"short")
|
| 427 |
+
|
| 428 |
+
>>> sympy.test(tb='no') # doctest: +SKIP
|
| 429 |
+
|
| 430 |
+
The ``split`` option can be passed to split the test run into parts. The
|
| 431 |
+
split currently only splits the test files, though this may change in the
|
| 432 |
+
future. ``split`` should be a string of the form 'a/b', which will run
|
| 433 |
+
part ``a`` of ``b``. For instance, to run the first half of the test suite:
|
| 434 |
+
|
| 435 |
+
>>> sympy.test(split='1/2') # doctest: +SKIP
|
| 436 |
+
|
| 437 |
+
The ``time_balance`` option can be passed in conjunction with ``split``.
|
| 438 |
+
If ``time_balance=True`` (the default for ``sympy.test``), SymPy will attempt
|
| 439 |
+
to split the tests such that each split takes equal time. This heuristic
|
| 440 |
+
for balancing is based on pre-recorded test data.
|
| 441 |
+
|
| 442 |
+
>>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP
|
| 443 |
+
|
| 444 |
+
You can disable running the tests in a separate subprocess using
|
| 445 |
+
``subprocess=False``. This is done to support seeding hash randomization,
|
| 446 |
+
which is enabled by default in the Python versions where it is supported.
|
| 447 |
+
If subprocess=False, hash randomization is enabled/disabled according to
|
| 448 |
+
whether it has been enabled or not in the calling Python process.
|
| 449 |
+
However, even if it is enabled, the seed cannot be printed unless it is
|
| 450 |
+
called from a new Python process.
|
| 451 |
+
|
| 452 |
+
Hash randomization was added in the minor Python versions 2.6.8, 2.7.3,
|
| 453 |
+
3.1.5, and 3.2.3, and is enabled by default in all Python versions after
|
| 454 |
+
and including 3.3.0.
|
| 455 |
+
|
| 456 |
+
If hash randomization is not supported ``subprocess=False`` is used
|
| 457 |
+
automatically.
|
| 458 |
+
|
| 459 |
+
>>> sympy.test(subprocess=False) # doctest: +SKIP
|
| 460 |
+
|
| 461 |
+
To set the hash randomization seed, set the environment variable
|
| 462 |
+
``PYTHONHASHSEED`` before running the tests. This can be done from within
|
| 463 |
+
Python using
|
| 464 |
+
|
| 465 |
+
>>> import os
|
| 466 |
+
>>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP
|
| 467 |
+
|
| 468 |
+
Or from the command line using
|
| 469 |
+
|
| 470 |
+
$ PYTHONHASHSEED=42 ./bin/test
|
| 471 |
+
|
| 472 |
+
If the seed is not set, a random seed will be chosen.
|
| 473 |
+
|
| 474 |
+
Note that to reproduce the same hash values, you must use both the same seed
|
| 475 |
+
as well as the same architecture (32-bit vs. 64-bit).
|
| 476 |
+
|
| 477 |
+
"""
|
| 478 |
+
# count up from 0, do not print 0
|
| 479 |
+
print_counter = lambda i : (print("rerun %d" % (rerun-i))
|
| 480 |
+
if rerun-i else None)
|
| 481 |
+
|
| 482 |
+
if subprocess:
|
| 483 |
+
# loop backwards so last i is 0
|
| 484 |
+
for i in range(rerun, -1, -1):
|
| 485 |
+
print_counter(i)
|
| 486 |
+
ret = run_in_subprocess_with_hash_randomization("_test",
|
| 487 |
+
function_args=paths, function_kwargs=kwargs)
|
| 488 |
+
if ret is False:
|
| 489 |
+
break
|
| 490 |
+
val = not bool(ret)
|
| 491 |
+
# exit on the first failure or if done
|
| 492 |
+
if not val or i == 0:
|
| 493 |
+
return val
|
| 494 |
+
|
| 495 |
+
# rerun even if hash randomization is not supported
|
| 496 |
+
for i in range(rerun, -1, -1):
|
| 497 |
+
print_counter(i)
|
| 498 |
+
val = not bool(_test(*paths, **kwargs))
|
| 499 |
+
if not val or i == 0:
|
| 500 |
+
return val
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def _test(*paths,
|
| 504 |
+
verbose=False, tb="short", kw=None, pdb=False, colors=True,
|
| 505 |
+
force_colors=False, sort=True, seed=None, timeout=False,
|
| 506 |
+
fail_on_timeout=False, slow=False, enhance_asserts=False, split=None,
|
| 507 |
+
time_balance=True, blacklist=(),
|
| 508 |
+
fast_threshold=None, slow_threshold=None):
|
| 509 |
+
"""
|
| 510 |
+
Internal function that actually runs the tests.
|
| 511 |
+
|
| 512 |
+
All keyword arguments from ``test()`` are passed to this function except for
|
| 513 |
+
``subprocess``.
|
| 514 |
+
|
| 515 |
+
Returns 0 if tests passed and 1 if they failed. See the docstring of
|
| 516 |
+
``test()`` for more information.
|
| 517 |
+
"""
|
| 518 |
+
kw = kw or ()
|
| 519 |
+
# ensure that kw is a tuple
|
| 520 |
+
if isinstance(kw, str):
|
| 521 |
+
kw = (kw,)
|
| 522 |
+
post_mortem = pdb
|
| 523 |
+
if seed is None:
|
| 524 |
+
seed = random.randrange(100000000)
|
| 525 |
+
if ON_CI and timeout is False:
|
| 526 |
+
timeout = 595
|
| 527 |
+
fail_on_timeout = True
|
| 528 |
+
if ON_CI:
|
| 529 |
+
blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests']
|
| 530 |
+
blacklist = convert_to_native_paths(blacklist)
|
| 531 |
+
r = PyTestReporter(verbose=verbose, tb=tb, colors=colors,
|
| 532 |
+
force_colors=force_colors, split=split)
|
| 533 |
+
t = SymPyTests(r, kw, post_mortem, seed,
|
| 534 |
+
fast_threshold=fast_threshold,
|
| 535 |
+
slow_threshold=slow_threshold)
|
| 536 |
+
|
| 537 |
+
test_files = t.get_test_files('sympy')
|
| 538 |
+
|
| 539 |
+
not_blacklisted = [f for f in test_files
|
| 540 |
+
if not any(b in f for b in blacklist)]
|
| 541 |
+
|
| 542 |
+
if len(paths) == 0:
|
| 543 |
+
matched = not_blacklisted
|
| 544 |
+
else:
|
| 545 |
+
paths = convert_to_native_paths(paths)
|
| 546 |
+
matched = []
|
| 547 |
+
for f in not_blacklisted:
|
| 548 |
+
basename = os.path.basename(f)
|
| 549 |
+
for p in paths:
|
| 550 |
+
if p in f or fnmatch(basename, p):
|
| 551 |
+
matched.append(f)
|
| 552 |
+
break
|
| 553 |
+
|
| 554 |
+
density = None
|
| 555 |
+
if time_balance:
|
| 556 |
+
if slow:
|
| 557 |
+
density = SPLIT_DENSITY_SLOW
|
| 558 |
+
else:
|
| 559 |
+
density = SPLIT_DENSITY
|
| 560 |
+
|
| 561 |
+
if split:
|
| 562 |
+
matched = split_list(matched, split, density=density)
|
| 563 |
+
|
| 564 |
+
t._testfiles.extend(matched)
|
| 565 |
+
|
| 566 |
+
return int(not t.test(sort=sort, timeout=timeout, slow=slow,
|
| 567 |
+
enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout))
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def doctest(*paths, subprocess=True, rerun=0, **kwargs):
|
| 571 |
+
r"""
|
| 572 |
+
Runs doctests in all \*.py files in the SymPy directory which match
|
| 573 |
+
any of the given strings in ``paths`` or all tests if paths=[].
|
| 574 |
+
|
| 575 |
+
Notes:
|
| 576 |
+
|
| 577 |
+
- Paths can be entered in native system format or in unix,
|
| 578 |
+
forward-slash format.
|
| 579 |
+
- Files that are on the blacklist can be tested by providing
|
| 580 |
+
their path; they are only excluded if no paths are given.
|
| 581 |
+
|
| 582 |
+
Examples
|
| 583 |
+
========
|
| 584 |
+
|
| 585 |
+
>>> import sympy
|
| 586 |
+
|
| 587 |
+
Run all tests:
|
| 588 |
+
|
| 589 |
+
>>> sympy.doctest() # doctest: +SKIP
|
| 590 |
+
|
| 591 |
+
Run one file:
|
| 592 |
+
|
| 593 |
+
>>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP
|
| 594 |
+
>>> sympy.doctest("polynomial.rst") # doctest: +SKIP
|
| 595 |
+
|
| 596 |
+
Run all tests in sympy/functions/ and some particular file:
|
| 597 |
+
|
| 598 |
+
>>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP
|
| 599 |
+
|
| 600 |
+
Run any file having polynomial in its name, doc/src/modules/polynomial.rst,
|
| 601 |
+
sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py:
|
| 602 |
+
|
| 603 |
+
>>> sympy.doctest("polynomial") # doctest: +SKIP
|
| 604 |
+
|
| 605 |
+
The ``split`` option can be passed to split the test run into parts. The
|
| 606 |
+
split currently only splits the test files, though this may change in the
|
| 607 |
+
future. ``split`` should be a string of the form 'a/b', which will run
|
| 608 |
+
part ``a`` of ``b``. Note that the regular doctests and the Sphinx
|
| 609 |
+
doctests are split independently. For instance, to run the first half of
|
| 610 |
+
the test suite:
|
| 611 |
+
|
| 612 |
+
>>> sympy.doctest(split='1/2') # doctest: +SKIP
|
| 613 |
+
|
| 614 |
+
The ``subprocess`` and ``verbose`` options are the same as with the function
|
| 615 |
+
``test()`` (see the docstring of that function for more information) except
|
| 616 |
+
that ``verbose`` may also be set equal to ``2`` in order to print
|
| 617 |
+
individual doctest lines, as they are being tested.
|
| 618 |
+
"""
|
| 619 |
+
# count up from 0, do not print 0
|
| 620 |
+
print_counter = lambda i : (print("rerun %d" % (rerun-i))
|
| 621 |
+
if rerun-i else None)
|
| 622 |
+
|
| 623 |
+
if subprocess:
|
| 624 |
+
# loop backwards so last i is 0
|
| 625 |
+
for i in range(rerun, -1, -1):
|
| 626 |
+
print_counter(i)
|
| 627 |
+
ret = run_in_subprocess_with_hash_randomization("_doctest",
|
| 628 |
+
function_args=paths, function_kwargs=kwargs)
|
| 629 |
+
if ret is False:
|
| 630 |
+
break
|
| 631 |
+
val = not bool(ret)
|
| 632 |
+
# exit on the first failure or if done
|
| 633 |
+
if not val or i == 0:
|
| 634 |
+
return val
|
| 635 |
+
|
| 636 |
+
# rerun even if hash randomization is not supported
|
| 637 |
+
for i in range(rerun, -1, -1):
|
| 638 |
+
print_counter(i)
|
| 639 |
+
val = not bool(_doctest(*paths, **kwargs))
|
| 640 |
+
if not val or i == 0:
|
| 641 |
+
return val
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def _get_doctest_blacklist():
|
| 645 |
+
'''Get the default blacklist for the doctests'''
|
| 646 |
+
blacklist = []
|
| 647 |
+
|
| 648 |
+
blacklist.extend([
|
| 649 |
+
"doc/src/modules/plotting.rst", # generates live plots
|
| 650 |
+
"doc/src/modules/physics/mechanics/autolev_parser.rst",
|
| 651 |
+
"sympy/codegen/array_utils.py", # raises deprecation warning
|
| 652 |
+
"sympy/core/compatibility.py", # backwards compatibility shim, importing it triggers a deprecation warning
|
| 653 |
+
"sympy/core/trace.py", # backwards compatibility shim, importing it triggers a deprecation warning
|
| 654 |
+
"sympy/galgebra.py", # no longer part of SymPy
|
| 655 |
+
"sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code
|
| 656 |
+
"sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code
|
| 657 |
+
"sympy/parsing/autolev/_antlr/autolevparser.py", # generated code
|
| 658 |
+
"sympy/parsing/latex/_antlr/latexlexer.py", # generated code
|
| 659 |
+
"sympy/parsing/latex/_antlr/latexparser.py", # generated code
|
| 660 |
+
"sympy/plotting/pygletplot/__init__.py", # crashes on some systems
|
| 661 |
+
"sympy/plotting/pygletplot/plot.py", # crashes on some systems
|
| 662 |
+
"sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests
|
| 663 |
+
"sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
|
| 664 |
+
"sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests
|
| 665 |
+
"sympy/testing/randtest.py", # backwards compatibility shim, importing it triggers a deprecation warning
|
| 666 |
+
"sympy/this.py", # prints text
|
| 667 |
+
])
|
| 668 |
+
# autolev parser tests
|
| 669 |
+
num = 12
|
| 670 |
+
for i in range (1, num+1):
|
| 671 |
+
blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py")
|
| 672 |
+
blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py",
|
| 673 |
+
"sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py",
|
| 674 |
+
"sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py",
|
| 675 |
+
"sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"])
|
| 676 |
+
|
| 677 |
+
if import_module('numpy') is None:
|
| 678 |
+
blacklist.extend([
|
| 679 |
+
"sympy/plotting/experimental_lambdify.py",
|
| 680 |
+
"sympy/plotting/plot_implicit.py",
|
| 681 |
+
"examples/advanced/autowrap_integrators.py",
|
| 682 |
+
"examples/advanced/autowrap_ufuncify.py",
|
| 683 |
+
"examples/intermediate/sample.py",
|
| 684 |
+
"examples/intermediate/mplot2d.py",
|
| 685 |
+
"examples/intermediate/mplot3d.py",
|
| 686 |
+
"doc/src/modules/numeric-computation.rst"
|
| 687 |
+
])
|
| 688 |
+
else:
|
| 689 |
+
if import_module('matplotlib') is None:
|
| 690 |
+
blacklist.extend([
|
| 691 |
+
"examples/intermediate/mplot2d.py",
|
| 692 |
+
"examples/intermediate/mplot3d.py"
|
| 693 |
+
])
|
| 694 |
+
else:
|
| 695 |
+
# Use a non-windowed backend, so that the tests work on CI
|
| 696 |
+
import matplotlib
|
| 697 |
+
matplotlib.use('Agg')
|
| 698 |
+
|
| 699 |
+
if ON_CI or import_module('pyglet') is None:
|
| 700 |
+
blacklist.extend(["sympy/plotting/pygletplot"])
|
| 701 |
+
|
| 702 |
+
if import_module('aesara') is None:
|
| 703 |
+
blacklist.extend([
|
| 704 |
+
"sympy/printing/aesaracode.py",
|
| 705 |
+
"doc/src/modules/numeric-computation.rst",
|
| 706 |
+
])
|
| 707 |
+
|
| 708 |
+
if import_module('cupy') is None:
|
| 709 |
+
blacklist.extend([
|
| 710 |
+
"doc/src/modules/numeric-computation.rst",
|
| 711 |
+
])
|
| 712 |
+
|
| 713 |
+
if import_module('jax') is None:
|
| 714 |
+
blacklist.extend([
|
| 715 |
+
"doc/src/modules/numeric-computation.rst",
|
| 716 |
+
])
|
| 717 |
+
|
| 718 |
+
if import_module('antlr4') is None:
|
| 719 |
+
blacklist.extend([
|
| 720 |
+
"sympy/parsing/autolev/__init__.py",
|
| 721 |
+
"sympy/parsing/latex/_parse_latex_antlr.py",
|
| 722 |
+
])
|
| 723 |
+
|
| 724 |
+
if import_module('lfortran') is None:
|
| 725 |
+
#throws ImportError when lfortran not installed
|
| 726 |
+
blacklist.extend([
|
| 727 |
+
"sympy/parsing/sym_expr.py",
|
| 728 |
+
])
|
| 729 |
+
|
| 730 |
+
if import_module("scipy") is None:
|
| 731 |
+
# throws ModuleNotFoundError when scipy not installed
|
| 732 |
+
blacklist.extend([
|
| 733 |
+
"doc/src/guides/solving/solve-numerically.md",
|
| 734 |
+
"doc/src/guides/solving/solve-ode.md",
|
| 735 |
+
])
|
| 736 |
+
|
| 737 |
+
if import_module("numpy") is None:
|
| 738 |
+
# throws ModuleNotFoundError when numpy not installed
|
| 739 |
+
blacklist.extend([
|
| 740 |
+
"doc/src/guides/solving/solve-ode.md",
|
| 741 |
+
"doc/src/guides/solving/solve-numerically.md",
|
| 742 |
+
])
|
| 743 |
+
|
| 744 |
+
# disabled because of doctest failures in asmeurer's bot
|
| 745 |
+
blacklist.extend([
|
| 746 |
+
"sympy/utilities/autowrap.py",
|
| 747 |
+
"examples/advanced/autowrap_integrators.py",
|
| 748 |
+
"examples/advanced/autowrap_ufuncify.py"
|
| 749 |
+
])
|
| 750 |
+
|
| 751 |
+
blacklist.extend([
|
| 752 |
+
"sympy/conftest.py", # Depends on pytest
|
| 753 |
+
])
|
| 754 |
+
|
| 755 |
+
# These are deprecated stubs to be removed:
|
| 756 |
+
blacklist.extend([
|
| 757 |
+
"sympy/utilities/tmpfiles.py",
|
| 758 |
+
"sympy/utilities/pytest.py",
|
| 759 |
+
"sympy/utilities/runtests.py",
|
| 760 |
+
"sympy/utilities/quality_unicode.py",
|
| 761 |
+
"sympy/utilities/randtest.py",
|
| 762 |
+
])
|
| 763 |
+
|
| 764 |
+
blacklist = convert_to_native_paths(blacklist)
|
| 765 |
+
return blacklist
|
| 766 |
+
|
| 767 |
+
|
| 768 |
+
def _doctest(*paths, **kwargs):
|
| 769 |
+
"""
|
| 770 |
+
Internal function that actually runs the doctests.
|
| 771 |
+
|
| 772 |
+
All keyword arguments from ``doctest()`` are passed to this function
|
| 773 |
+
except for ``subprocess``.
|
| 774 |
+
|
| 775 |
+
Returns 0 if tests passed and 1 if they failed. See the docstrings of
|
| 776 |
+
``doctest()`` and ``test()`` for more information.
|
| 777 |
+
"""
|
| 778 |
+
from sympy.printing.pretty.pretty import pprint_use_unicode
|
| 779 |
+
|
| 780 |
+
normal = kwargs.get("normal", False)
|
| 781 |
+
verbose = kwargs.get("verbose", False)
|
| 782 |
+
colors = kwargs.get("colors", True)
|
| 783 |
+
force_colors = kwargs.get("force_colors", False)
|
| 784 |
+
blacklist = kwargs.get("blacklist", [])
|
| 785 |
+
split = kwargs.get('split', None)
|
| 786 |
+
|
| 787 |
+
blacklist.extend(_get_doctest_blacklist())
|
| 788 |
+
|
| 789 |
+
# Use a non-windowed backend, so that the tests work on CI
|
| 790 |
+
if import_module('matplotlib') is not None:
|
| 791 |
+
import matplotlib
|
| 792 |
+
matplotlib.use('Agg')
|
| 793 |
+
|
| 794 |
+
# Disable warnings for external modules
|
| 795 |
+
import sympy.external
|
| 796 |
+
sympy.external.importtools.WARN_OLD_VERSION = False
|
| 797 |
+
sympy.external.importtools.WARN_NOT_INSTALLED = False
|
| 798 |
+
|
| 799 |
+
# Disable showing up of plots
|
| 800 |
+
from sympy.plotting.plot import unset_show
|
| 801 |
+
unset_show()
|
| 802 |
+
|
| 803 |
+
r = PyTestReporter(verbose, split=split, colors=colors,\
|
| 804 |
+
force_colors=force_colors)
|
| 805 |
+
t = SymPyDocTests(r, normal)
|
| 806 |
+
|
| 807 |
+
test_files = t.get_test_files('sympy')
|
| 808 |
+
test_files.extend(t.get_test_files('examples', init_only=False))
|
| 809 |
+
|
| 810 |
+
not_blacklisted = [f for f in test_files
|
| 811 |
+
if not any(b in f for b in blacklist)]
|
| 812 |
+
if len(paths) == 0:
|
| 813 |
+
matched = not_blacklisted
|
| 814 |
+
else:
|
| 815 |
+
# take only what was requested...but not blacklisted items
|
| 816 |
+
# and allow for partial match anywhere or fnmatch of name
|
| 817 |
+
paths = convert_to_native_paths(paths)
|
| 818 |
+
matched = []
|
| 819 |
+
for f in not_blacklisted:
|
| 820 |
+
basename = os.path.basename(f)
|
| 821 |
+
for p in paths:
|
| 822 |
+
if p in f or fnmatch(basename, p):
|
| 823 |
+
matched.append(f)
|
| 824 |
+
break
|
| 825 |
+
|
| 826 |
+
matched.sort()
|
| 827 |
+
|
| 828 |
+
if split:
|
| 829 |
+
matched = split_list(matched, split)
|
| 830 |
+
|
| 831 |
+
t._testfiles.extend(matched)
|
| 832 |
+
|
| 833 |
+
# run the tests and record the result for this *py portion of the tests
|
| 834 |
+
if t._testfiles:
|
| 835 |
+
failed = not t.test()
|
| 836 |
+
else:
|
| 837 |
+
failed = False
|
| 838 |
+
|
| 839 |
+
# N.B.
|
| 840 |
+
# --------------------------------------------------------------------
|
| 841 |
+
# Here we test *.rst and *.md files at or below doc/src. Code from these
|
| 842 |
+
# must be self supporting in terms of imports since there is no importing
|
| 843 |
+
# of necessary modules by doctest.testfile. If you try to pass *.py files
|
| 844 |
+
# through this they might fail because they will lack the needed imports
|
| 845 |
+
# and smarter parsing that can be done with source code.
|
| 846 |
+
#
|
| 847 |
+
test_files_rst = t.get_test_files('doc/src', '*.rst', init_only=False)
|
| 848 |
+
test_files_md = t.get_test_files('doc/src', '*.md', init_only=False)
|
| 849 |
+
test_files = test_files_rst + test_files_md
|
| 850 |
+
test_files.sort()
|
| 851 |
+
|
| 852 |
+
not_blacklisted = [f for f in test_files
|
| 853 |
+
if not any(b in f for b in blacklist)]
|
| 854 |
+
|
| 855 |
+
if len(paths) == 0:
|
| 856 |
+
matched = not_blacklisted
|
| 857 |
+
else:
|
| 858 |
+
# Take only what was requested as long as it's not on the blacklist.
|
| 859 |
+
# Paths were already made native in *py tests so don't repeat here.
|
| 860 |
+
# There's no chance of having a *py file slip through since we
|
| 861 |
+
# only have *rst files in test_files.
|
| 862 |
+
matched = []
|
| 863 |
+
for f in not_blacklisted:
|
| 864 |
+
basename = os.path.basename(f)
|
| 865 |
+
for p in paths:
|
| 866 |
+
if p in f or fnmatch(basename, p):
|
| 867 |
+
matched.append(f)
|
| 868 |
+
break
|
| 869 |
+
|
| 870 |
+
if split:
|
| 871 |
+
matched = split_list(matched, split)
|
| 872 |
+
|
| 873 |
+
first_report = True
|
| 874 |
+
for rst_file in matched:
|
| 875 |
+
if not os.path.isfile(rst_file):
|
| 876 |
+
continue
|
| 877 |
+
old_displayhook = sys.displayhook
|
| 878 |
+
try:
|
| 879 |
+
use_unicode_prev = setup_pprint()
|
| 880 |
+
out = sympytestfile(
|
| 881 |
+
rst_file, module_relative=False, encoding='utf-8',
|
| 882 |
+
optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE |
|
| 883 |
+
pdoctest.IGNORE_EXCEPTION_DETAIL)
|
| 884 |
+
finally:
|
| 885 |
+
# make sure we return to the original displayhook in case some
|
| 886 |
+
# doctest has changed that
|
| 887 |
+
sys.displayhook = old_displayhook
|
| 888 |
+
# The NO_GLOBAL flag overrides the no_global flag to init_printing
|
| 889 |
+
# if True
|
| 890 |
+
import sympy.interactive.printing as interactive_printing
|
| 891 |
+
interactive_printing.NO_GLOBAL = False
|
| 892 |
+
pprint_use_unicode(use_unicode_prev)
|
| 893 |
+
|
| 894 |
+
rstfailed, tested = out
|
| 895 |
+
if tested:
|
| 896 |
+
failed = rstfailed or failed
|
| 897 |
+
if first_report:
|
| 898 |
+
first_report = False
|
| 899 |
+
msg = 'rst/md doctests start'
|
| 900 |
+
if not t._testfiles:
|
| 901 |
+
r.start(msg=msg)
|
| 902 |
+
else:
|
| 903 |
+
r.write_center(msg)
|
| 904 |
+
print()
|
| 905 |
+
# use as the id, everything past the first 'sympy'
|
| 906 |
+
file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:]
|
| 907 |
+
print(file_id, end=" ")
|
| 908 |
+
# get at least the name out so it is know who is being tested
|
| 909 |
+
wid = r.terminal_width - len(file_id) - 1 # update width
|
| 910 |
+
test_file = '[%s]' % (tested)
|
| 911 |
+
report = '[%s]' % (rstfailed or 'OK')
|
| 912 |
+
print(''.join(
|
| 913 |
+
[test_file, ' '*(wid - len(test_file) - len(report)), report])
|
| 914 |
+
)
|
| 915 |
+
|
| 916 |
+
# the doctests for *py will have printed this message already if there was
|
| 917 |
+
# a failure, so now only print it if there was intervening reporting by
|
| 918 |
+
# testing the *rst as evidenced by first_report no longer being True.
|
| 919 |
+
if not first_report and failed:
|
| 920 |
+
print()
|
| 921 |
+
print("DO *NOT* COMMIT!")
|
| 922 |
+
|
| 923 |
+
return int(failed)
|
| 924 |
+
|
| 925 |
+
sp = re.compile(r'([0-9]+)/([1-9][0-9]*)')
|
| 926 |
+
|
| 927 |
+
def split_list(l, split, density=None):
|
| 928 |
+
"""
|
| 929 |
+
Splits a list into part a of b
|
| 930 |
+
|
| 931 |
+
split should be a string of the form 'a/b'. For instance, '1/3' would give
|
| 932 |
+
the split one of three.
|
| 933 |
+
|
| 934 |
+
If the length of the list is not divisible by the number of splits, the
|
| 935 |
+
last split will have more items.
|
| 936 |
+
|
| 937 |
+
`density` may be specified as a list. If specified,
|
| 938 |
+
tests will be balanced so that each split has as equal-as-possible
|
| 939 |
+
amount of mass according to `density`.
|
| 940 |
+
|
| 941 |
+
>>> from sympy.testing.runtests import split_list
|
| 942 |
+
>>> a = list(range(10))
|
| 943 |
+
>>> split_list(a, '1/3')
|
| 944 |
+
[0, 1, 2]
|
| 945 |
+
>>> split_list(a, '2/3')
|
| 946 |
+
[3, 4, 5]
|
| 947 |
+
>>> split_list(a, '3/3')
|
| 948 |
+
[6, 7, 8, 9]
|
| 949 |
+
"""
|
| 950 |
+
m = sp.match(split)
|
| 951 |
+
if not m:
|
| 952 |
+
raise ValueError("split must be a string of the form a/b where a and b are ints")
|
| 953 |
+
i, t = map(int, m.groups())
|
| 954 |
+
|
| 955 |
+
if not density:
|
| 956 |
+
return l[(i - 1)*len(l)//t : i*len(l)//t]
|
| 957 |
+
|
| 958 |
+
# normalize density
|
| 959 |
+
tot = sum(density)
|
| 960 |
+
density = [x / tot for x in density]
|
| 961 |
+
|
| 962 |
+
def density_inv(x):
|
| 963 |
+
"""Interpolate the inverse to the cumulative
|
| 964 |
+
distribution function given by density"""
|
| 965 |
+
if x <= 0:
|
| 966 |
+
return 0
|
| 967 |
+
if x >= sum(density):
|
| 968 |
+
return 1
|
| 969 |
+
|
| 970 |
+
# find the first time the cumulative sum surpasses x
|
| 971 |
+
# and linearly interpolate
|
| 972 |
+
cumm = 0
|
| 973 |
+
for i, d in enumerate(density):
|
| 974 |
+
cumm += d
|
| 975 |
+
if cumm >= x:
|
| 976 |
+
break
|
| 977 |
+
frac = (d - (cumm - x)) / d
|
| 978 |
+
return (i + frac) / len(density)
|
| 979 |
+
|
| 980 |
+
lower_frac = density_inv((i - 1) / t)
|
| 981 |
+
higher_frac = density_inv(i / t)
|
| 982 |
+
return l[int(lower_frac*len(l)) : int(higher_frac*len(l))]
|
| 983 |
+
|
| 984 |
+
from collections import namedtuple
|
| 985 |
+
SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted')
|
| 986 |
+
|
| 987 |
+
def sympytestfile(filename, module_relative=True, name=None, package=None,
|
| 988 |
+
globs=None, verbose=None, report=True, optionflags=0,
|
| 989 |
+
extraglobs=None, raise_on_error=False,
|
| 990 |
+
parser=pdoctest.DocTestParser(), encoding=None):
|
| 991 |
+
|
| 992 |
+
"""
|
| 993 |
+
Test examples in the given file. Return (#failures, #tests).
|
| 994 |
+
|
| 995 |
+
Optional keyword arg ``module_relative`` specifies how filenames
|
| 996 |
+
should be interpreted:
|
| 997 |
+
|
| 998 |
+
- If ``module_relative`` is True (the default), then ``filename``
|
| 999 |
+
specifies a module-relative path. By default, this path is
|
| 1000 |
+
relative to the calling module's directory; but if the
|
| 1001 |
+
``package`` argument is specified, then it is relative to that
|
| 1002 |
+
package. To ensure os-independence, ``filename`` should use
|
| 1003 |
+
"/" characters to separate path segments, and should not
|
| 1004 |
+
be an absolute path (i.e., it may not begin with "/").
|
| 1005 |
+
|
| 1006 |
+
- If ``module_relative`` is False, then ``filename`` specifies an
|
| 1007 |
+
os-specific path. The path may be absolute or relative (to
|
| 1008 |
+
the current working directory).
|
| 1009 |
+
|
| 1010 |
+
Optional keyword arg ``name`` gives the name of the test; by default
|
| 1011 |
+
use the file's basename.
|
| 1012 |
+
|
| 1013 |
+
Optional keyword argument ``package`` is a Python package or the
|
| 1014 |
+
name of a Python package whose directory should be used as the
|
| 1015 |
+
base directory for a module relative filename. If no package is
|
| 1016 |
+
specified, then the calling module's directory is used as the base
|
| 1017 |
+
directory for module relative filenames. It is an error to
|
| 1018 |
+
specify ``package`` if ``module_relative`` is False.
|
| 1019 |
+
|
| 1020 |
+
Optional keyword arg ``globs`` gives a dict to be used as the globals
|
| 1021 |
+
when executing examples; by default, use {}. A copy of this dict
|
| 1022 |
+
is actually used for each docstring, so that each docstring's
|
| 1023 |
+
examples start with a clean slate.
|
| 1024 |
+
|
| 1025 |
+
Optional keyword arg ``extraglobs`` gives a dictionary that should be
|
| 1026 |
+
merged into the globals that are used to execute examples. By
|
| 1027 |
+
default, no extra globals are used.
|
| 1028 |
+
|
| 1029 |
+
Optional keyword arg ``verbose`` prints lots of stuff if true, prints
|
| 1030 |
+
only failures if false; by default, it's true iff "-v" is in sys.argv.
|
| 1031 |
+
|
| 1032 |
+
Optional keyword arg ``report`` prints a summary at the end when true,
|
| 1033 |
+
else prints nothing at the end. In verbose mode, the summary is
|
| 1034 |
+
detailed, else very brief (in fact, empty if all tests passed).
|
| 1035 |
+
|
| 1036 |
+
Optional keyword arg ``optionflags`` or's together module constants,
|
| 1037 |
+
and defaults to 0. Possible values (see the docs for details):
|
| 1038 |
+
|
| 1039 |
+
- DONT_ACCEPT_TRUE_FOR_1
|
| 1040 |
+
- DONT_ACCEPT_BLANKLINE
|
| 1041 |
+
- NORMALIZE_WHITESPACE
|
| 1042 |
+
- ELLIPSIS
|
| 1043 |
+
- SKIP
|
| 1044 |
+
- IGNORE_EXCEPTION_DETAIL
|
| 1045 |
+
- REPORT_UDIFF
|
| 1046 |
+
- REPORT_CDIFF
|
| 1047 |
+
- REPORT_NDIFF
|
| 1048 |
+
- REPORT_ONLY_FIRST_FAILURE
|
| 1049 |
+
|
| 1050 |
+
Optional keyword arg ``raise_on_error`` raises an exception on the
|
| 1051 |
+
first unexpected exception or failure. This allows failures to be
|
| 1052 |
+
post-mortem debugged.
|
| 1053 |
+
|
| 1054 |
+
Optional keyword arg ``parser`` specifies a DocTestParser (or
|
| 1055 |
+
subclass) that should be used to extract tests from the files.
|
| 1056 |
+
|
| 1057 |
+
Optional keyword arg ``encoding`` specifies an encoding that should
|
| 1058 |
+
be used to convert the file to unicode.
|
| 1059 |
+
|
| 1060 |
+
Advanced tomfoolery: testmod runs methods of a local instance of
|
| 1061 |
+
class doctest.Tester, then merges the results into (or creates)
|
| 1062 |
+
global Tester instance doctest.master. Methods of doctest.master
|
| 1063 |
+
can be called directly too, if you want to do something unusual.
|
| 1064 |
+
Passing report=0 to testmod is especially useful then, to delay
|
| 1065 |
+
displaying a summary. Invoke doctest.master.summarize(verbose)
|
| 1066 |
+
when you're done fiddling.
|
| 1067 |
+
"""
|
| 1068 |
+
if package and not module_relative:
|
| 1069 |
+
raise ValueError("Package may only be specified for module-"
|
| 1070 |
+
"relative paths.")
|
| 1071 |
+
|
| 1072 |
+
# Relativize the path
|
| 1073 |
+
text, filename = pdoctest._load_testfile(
|
| 1074 |
+
filename, package, module_relative, encoding)
|
| 1075 |
+
|
| 1076 |
+
# If no name was given, then use the file's name.
|
| 1077 |
+
if name is None:
|
| 1078 |
+
name = os.path.basename(filename)
|
| 1079 |
+
|
| 1080 |
+
# Assemble the globals.
|
| 1081 |
+
if globs is None:
|
| 1082 |
+
globs = {}
|
| 1083 |
+
else:
|
| 1084 |
+
globs = globs.copy()
|
| 1085 |
+
if extraglobs is not None:
|
| 1086 |
+
globs.update(extraglobs)
|
| 1087 |
+
if '__name__' not in globs:
|
| 1088 |
+
globs['__name__'] = '__main__'
|
| 1089 |
+
|
| 1090 |
+
if raise_on_error:
|
| 1091 |
+
runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags)
|
| 1092 |
+
else:
|
| 1093 |
+
runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags)
|
| 1094 |
+
runner._checker = SymPyOutputChecker()
|
| 1095 |
+
|
| 1096 |
+
# Read the file, convert it to a test, and run it.
|
| 1097 |
+
test = parser.get_doctest(text, globs, name, filename, 0)
|
| 1098 |
+
runner.run(test)
|
| 1099 |
+
|
| 1100 |
+
if report:
|
| 1101 |
+
runner.summarize()
|
| 1102 |
+
|
| 1103 |
+
if pdoctest.master is None:
|
| 1104 |
+
pdoctest.master = runner
|
| 1105 |
+
else:
|
| 1106 |
+
pdoctest.master.merge(runner)
|
| 1107 |
+
|
| 1108 |
+
return SymPyTestResults(runner.failures, runner.tries)
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
class SymPyTests:
|
| 1112 |
+
|
| 1113 |
+
def __init__(self, reporter, kw="", post_mortem=False,
|
| 1114 |
+
seed=None, fast_threshold=None, slow_threshold=None):
|
| 1115 |
+
self._post_mortem = post_mortem
|
| 1116 |
+
self._kw = kw
|
| 1117 |
+
self._count = 0
|
| 1118 |
+
self._root_dir = get_sympy_dir()
|
| 1119 |
+
self._reporter = reporter
|
| 1120 |
+
self._reporter.root_dir(self._root_dir)
|
| 1121 |
+
self._testfiles = []
|
| 1122 |
+
self._seed = seed if seed is not None else random.random()
|
| 1123 |
+
|
| 1124 |
+
# Defaults in seconds, from human / UX design limits
|
| 1125 |
+
# http://www.nngroup.com/articles/response-times-3-important-limits/
|
| 1126 |
+
#
|
| 1127 |
+
# These defaults are *NOT* set in stone as we are measuring different
|
| 1128 |
+
# things, so others feel free to come up with a better yardstick :)
|
| 1129 |
+
if fast_threshold:
|
| 1130 |
+
self._fast_threshold = float(fast_threshold)
|
| 1131 |
+
else:
|
| 1132 |
+
self._fast_threshold = 8
|
| 1133 |
+
if slow_threshold:
|
| 1134 |
+
self._slow_threshold = float(slow_threshold)
|
| 1135 |
+
else:
|
| 1136 |
+
self._slow_threshold = 10
|
| 1137 |
+
|
| 1138 |
+
def test(self, sort=False, timeout=False, slow=False,
|
| 1139 |
+
enhance_asserts=False, fail_on_timeout=False):
|
| 1140 |
+
"""
|
| 1141 |
+
Runs the tests returning True if all tests pass, otherwise False.
|
| 1142 |
+
|
| 1143 |
+
If sort=False run tests in random order.
|
| 1144 |
+
"""
|
| 1145 |
+
if sort:
|
| 1146 |
+
self._testfiles.sort()
|
| 1147 |
+
elif slow:
|
| 1148 |
+
pass
|
| 1149 |
+
else:
|
| 1150 |
+
random.seed(self._seed)
|
| 1151 |
+
random.shuffle(self._testfiles)
|
| 1152 |
+
self._reporter.start(self._seed)
|
| 1153 |
+
for f in self._testfiles:
|
| 1154 |
+
try:
|
| 1155 |
+
self.test_file(f, sort, timeout, slow,
|
| 1156 |
+
enhance_asserts, fail_on_timeout)
|
| 1157 |
+
except KeyboardInterrupt:
|
| 1158 |
+
print(" interrupted by user")
|
| 1159 |
+
self._reporter.finish()
|
| 1160 |
+
raise
|
| 1161 |
+
return self._reporter.finish()
|
| 1162 |
+
|
| 1163 |
+
def _enhance_asserts(self, source):
|
| 1164 |
+
from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple,
|
| 1165 |
+
Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations)
|
| 1166 |
+
|
| 1167 |
+
ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=',
|
| 1168 |
+
"Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not',
|
| 1169 |
+
"In": 'in', "NotIn": 'not in'}
|
| 1170 |
+
|
| 1171 |
+
class Transform(NodeTransformer):
|
| 1172 |
+
def visit_Assert(self, stmt):
|
| 1173 |
+
if isinstance(stmt.test, Compare):
|
| 1174 |
+
compare = stmt.test
|
| 1175 |
+
values = [compare.left] + compare.comparators
|
| 1176 |
+
names = [ "_%s" % i for i, _ in enumerate(values) ]
|
| 1177 |
+
names_store = [ Name(n, Store()) for n in names ]
|
| 1178 |
+
names_load = [ Name(n, Load()) for n in names ]
|
| 1179 |
+
target = Tuple(names_store, Store())
|
| 1180 |
+
value = Tuple(values, Load())
|
| 1181 |
+
assign = Assign([target], value)
|
| 1182 |
+
new_compare = Compare(names_load[0], compare.ops, names_load[1:])
|
| 1183 |
+
msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s"
|
| 1184 |
+
msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load()))
|
| 1185 |
+
test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset)
|
| 1186 |
+
return [assign, test]
|
| 1187 |
+
else:
|
| 1188 |
+
return stmt
|
| 1189 |
+
|
| 1190 |
+
tree = parse(source)
|
| 1191 |
+
new_tree = Transform().visit(tree)
|
| 1192 |
+
return fix_missing_locations(new_tree)
|
| 1193 |
+
|
| 1194 |
+
def test_file(self, filename, sort=True, timeout=False, slow=False,
|
| 1195 |
+
enhance_asserts=False, fail_on_timeout=False):
|
| 1196 |
+
reporter = self._reporter
|
| 1197 |
+
funcs = []
|
| 1198 |
+
try:
|
| 1199 |
+
gl = {'__file__': filename}
|
| 1200 |
+
try:
|
| 1201 |
+
open_file = lambda: open(filename, encoding="utf8")
|
| 1202 |
+
|
| 1203 |
+
with open_file() as f:
|
| 1204 |
+
source = f.read()
|
| 1205 |
+
if self._kw:
|
| 1206 |
+
for l in source.splitlines():
|
| 1207 |
+
if l.lstrip().startswith('def '):
|
| 1208 |
+
if any(l.lower().find(k.lower()) != -1 for k in self._kw):
|
| 1209 |
+
break
|
| 1210 |
+
else:
|
| 1211 |
+
return
|
| 1212 |
+
|
| 1213 |
+
if enhance_asserts:
|
| 1214 |
+
try:
|
| 1215 |
+
source = self._enhance_asserts(source)
|
| 1216 |
+
except ImportError:
|
| 1217 |
+
pass
|
| 1218 |
+
|
| 1219 |
+
code = compile(source, filename, "exec", flags=0, dont_inherit=True)
|
| 1220 |
+
exec(code, gl)
|
| 1221 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1222 |
+
raise
|
| 1223 |
+
except ImportError:
|
| 1224 |
+
reporter.import_error(filename, sys.exc_info())
|
| 1225 |
+
return
|
| 1226 |
+
except Exception:
|
| 1227 |
+
reporter.test_exception(sys.exc_info())
|
| 1228 |
+
|
| 1229 |
+
clear_cache()
|
| 1230 |
+
self._count += 1
|
| 1231 |
+
random.seed(self._seed)
|
| 1232 |
+
disabled = gl.get("disabled", False)
|
| 1233 |
+
if not disabled:
|
| 1234 |
+
# we need to filter only those functions that begin with 'test_'
|
| 1235 |
+
# We have to be careful about decorated functions. As long as
|
| 1236 |
+
# the decorator uses functools.wraps, we can detect it.
|
| 1237 |
+
funcs = []
|
| 1238 |
+
for f in gl:
|
| 1239 |
+
if (f.startswith("test_") and (inspect.isfunction(gl[f])
|
| 1240 |
+
or inspect.ismethod(gl[f]))):
|
| 1241 |
+
func = gl[f]
|
| 1242 |
+
# Handle multiple decorators
|
| 1243 |
+
while hasattr(func, '__wrapped__'):
|
| 1244 |
+
func = func.__wrapped__
|
| 1245 |
+
|
| 1246 |
+
if inspect.getsourcefile(func) == filename:
|
| 1247 |
+
funcs.append(gl[f])
|
| 1248 |
+
if slow:
|
| 1249 |
+
funcs = [f for f in funcs if getattr(f, '_slow', False)]
|
| 1250 |
+
# Sorting of XFAILed functions isn't fixed yet :-(
|
| 1251 |
+
funcs.sort(key=lambda x: inspect.getsourcelines(x)[1])
|
| 1252 |
+
i = 0
|
| 1253 |
+
while i < len(funcs):
|
| 1254 |
+
if inspect.isgeneratorfunction(funcs[i]):
|
| 1255 |
+
# some tests can be generators, that return the actual
|
| 1256 |
+
# test functions. We unpack it below:
|
| 1257 |
+
f = funcs.pop(i)
|
| 1258 |
+
for fg in f():
|
| 1259 |
+
func = fg[0]
|
| 1260 |
+
args = fg[1:]
|
| 1261 |
+
fgw = lambda: func(*args)
|
| 1262 |
+
funcs.insert(i, fgw)
|
| 1263 |
+
i += 1
|
| 1264 |
+
else:
|
| 1265 |
+
i += 1
|
| 1266 |
+
# drop functions that are not selected with the keyword expression:
|
| 1267 |
+
funcs = [x for x in funcs if self.matches(x)]
|
| 1268 |
+
|
| 1269 |
+
if not funcs:
|
| 1270 |
+
return
|
| 1271 |
+
except Exception:
|
| 1272 |
+
reporter.entering_filename(filename, len(funcs))
|
| 1273 |
+
raise
|
| 1274 |
+
|
| 1275 |
+
reporter.entering_filename(filename, len(funcs))
|
| 1276 |
+
if not sort:
|
| 1277 |
+
random.shuffle(funcs)
|
| 1278 |
+
|
| 1279 |
+
for f in funcs:
|
| 1280 |
+
start = time.time()
|
| 1281 |
+
reporter.entering_test(f)
|
| 1282 |
+
try:
|
| 1283 |
+
if getattr(f, '_slow', False) and not slow:
|
| 1284 |
+
raise Skipped("Slow")
|
| 1285 |
+
with raise_on_deprecated():
|
| 1286 |
+
if timeout:
|
| 1287 |
+
self._timeout(f, timeout, fail_on_timeout)
|
| 1288 |
+
else:
|
| 1289 |
+
random.seed(self._seed)
|
| 1290 |
+
f()
|
| 1291 |
+
except KeyboardInterrupt:
|
| 1292 |
+
if getattr(f, '_slow', False):
|
| 1293 |
+
reporter.test_skip("KeyboardInterrupt")
|
| 1294 |
+
else:
|
| 1295 |
+
raise
|
| 1296 |
+
except Exception:
|
| 1297 |
+
if timeout:
|
| 1298 |
+
signal.alarm(0) # Disable the alarm. It could not be handled before.
|
| 1299 |
+
t, v, tr = sys.exc_info()
|
| 1300 |
+
if t is AssertionError:
|
| 1301 |
+
reporter.test_fail((t, v, tr))
|
| 1302 |
+
if self._post_mortem:
|
| 1303 |
+
pdb.post_mortem(tr)
|
| 1304 |
+
elif t.__name__ == "Skipped":
|
| 1305 |
+
reporter.test_skip(v)
|
| 1306 |
+
elif t.__name__ == "XFail":
|
| 1307 |
+
reporter.test_xfail()
|
| 1308 |
+
elif t.__name__ == "XPass":
|
| 1309 |
+
reporter.test_xpass(v)
|
| 1310 |
+
else:
|
| 1311 |
+
reporter.test_exception((t, v, tr))
|
| 1312 |
+
if self._post_mortem:
|
| 1313 |
+
pdb.post_mortem(tr)
|
| 1314 |
+
else:
|
| 1315 |
+
reporter.test_pass()
|
| 1316 |
+
taken = time.time() - start
|
| 1317 |
+
if taken > self._slow_threshold:
|
| 1318 |
+
filename = os.path.relpath(filename, reporter._root_dir)
|
| 1319 |
+
reporter.slow_test_functions.append(
|
| 1320 |
+
(filename + "::" + f.__name__, taken))
|
| 1321 |
+
if getattr(f, '_slow', False) and slow:
|
| 1322 |
+
if taken < self._fast_threshold:
|
| 1323 |
+
filename = os.path.relpath(filename, reporter._root_dir)
|
| 1324 |
+
reporter.fast_test_functions.append(
|
| 1325 |
+
(filename + "::" + f.__name__, taken))
|
| 1326 |
+
reporter.leaving_filename()
|
| 1327 |
+
|
| 1328 |
+
def _timeout(self, function, timeout, fail_on_timeout):
|
| 1329 |
+
def callback(x, y):
|
| 1330 |
+
signal.alarm(0)
|
| 1331 |
+
if fail_on_timeout:
|
| 1332 |
+
raise TimeOutError("Timed out after %d seconds" % timeout)
|
| 1333 |
+
else:
|
| 1334 |
+
raise Skipped("Timeout")
|
| 1335 |
+
signal.signal(signal.SIGALRM, callback)
|
| 1336 |
+
signal.alarm(timeout) # Set an alarm with a given timeout
|
| 1337 |
+
function()
|
| 1338 |
+
signal.alarm(0) # Disable the alarm
|
| 1339 |
+
|
| 1340 |
+
def matches(self, x):
|
| 1341 |
+
"""
|
| 1342 |
+
Does the keyword expression self._kw match "x"? Returns True/False.
|
| 1343 |
+
|
| 1344 |
+
Always returns True if self._kw is "".
|
| 1345 |
+
"""
|
| 1346 |
+
if not self._kw:
|
| 1347 |
+
return True
|
| 1348 |
+
for kw in self._kw:
|
| 1349 |
+
if x.__name__.lower().find(kw.lower()) != -1:
|
| 1350 |
+
return True
|
| 1351 |
+
return False
|
| 1352 |
+
|
| 1353 |
+
def get_test_files(self, dir, pat='test_*.py'):
|
| 1354 |
+
"""
|
| 1355 |
+
Returns the list of test_*.py (default) files at or below directory
|
| 1356 |
+
``dir`` relative to the SymPy home directory.
|
| 1357 |
+
"""
|
| 1358 |
+
dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
|
| 1359 |
+
|
| 1360 |
+
g = []
|
| 1361 |
+
for path, folders, files in os.walk(dir):
|
| 1362 |
+
g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)])
|
| 1363 |
+
|
| 1364 |
+
return sorted([os.path.normcase(gi) for gi in g])
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
class SymPyDocTests:
|
| 1368 |
+
|
| 1369 |
+
def __init__(self, reporter, normal):
|
| 1370 |
+
self._count = 0
|
| 1371 |
+
self._root_dir = get_sympy_dir()
|
| 1372 |
+
self._reporter = reporter
|
| 1373 |
+
self._reporter.root_dir(self._root_dir)
|
| 1374 |
+
self._normal = normal
|
| 1375 |
+
|
| 1376 |
+
self._testfiles = []
|
| 1377 |
+
|
| 1378 |
+
def test(self):
|
| 1379 |
+
"""
|
| 1380 |
+
Runs the tests and returns True if all tests pass, otherwise False.
|
| 1381 |
+
"""
|
| 1382 |
+
self._reporter.start()
|
| 1383 |
+
for f in self._testfiles:
|
| 1384 |
+
try:
|
| 1385 |
+
self.test_file(f)
|
| 1386 |
+
except KeyboardInterrupt:
|
| 1387 |
+
print(" interrupted by user")
|
| 1388 |
+
self._reporter.finish()
|
| 1389 |
+
raise
|
| 1390 |
+
return self._reporter.finish()
|
| 1391 |
+
|
| 1392 |
+
def test_file(self, filename):
|
| 1393 |
+
clear_cache()
|
| 1394 |
+
|
| 1395 |
+
from io import StringIO
|
| 1396 |
+
import sympy.interactive.printing as interactive_printing
|
| 1397 |
+
from sympy.printing.pretty.pretty import pprint_use_unicode
|
| 1398 |
+
|
| 1399 |
+
rel_name = filename[len(self._root_dir) + 1:]
|
| 1400 |
+
dirname, file = os.path.split(filename)
|
| 1401 |
+
module = rel_name.replace(os.sep, '.')[:-3]
|
| 1402 |
+
|
| 1403 |
+
if rel_name.startswith("examples"):
|
| 1404 |
+
# Examples files do not have __init__.py files,
|
| 1405 |
+
# So we have to temporarily extend sys.path to import them
|
| 1406 |
+
sys.path.insert(0, dirname)
|
| 1407 |
+
module = file[:-3] # remove ".py"
|
| 1408 |
+
try:
|
| 1409 |
+
module = pdoctest._normalize_module(module)
|
| 1410 |
+
tests = SymPyDocTestFinder().find(module)
|
| 1411 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1412 |
+
raise
|
| 1413 |
+
except ImportError:
|
| 1414 |
+
self._reporter.import_error(filename, sys.exc_info())
|
| 1415 |
+
return
|
| 1416 |
+
finally:
|
| 1417 |
+
if rel_name.startswith("examples"):
|
| 1418 |
+
del sys.path[0]
|
| 1419 |
+
|
| 1420 |
+
tests = [test for test in tests if len(test.examples) > 0]
|
| 1421 |
+
# By default tests are sorted by alphabetical order by function name.
|
| 1422 |
+
# We sort by line number so one can edit the file sequentially from
|
| 1423 |
+
# bottom to top. However, if there are decorated functions, their line
|
| 1424 |
+
# numbers will be too large and for now one must just search for these
|
| 1425 |
+
# by text and function name.
|
| 1426 |
+
tests.sort(key=lambda x: -x.lineno)
|
| 1427 |
+
|
| 1428 |
+
if not tests:
|
| 1429 |
+
return
|
| 1430 |
+
self._reporter.entering_filename(filename, len(tests))
|
| 1431 |
+
for test in tests:
|
| 1432 |
+
assert len(test.examples) != 0
|
| 1433 |
+
|
| 1434 |
+
if self._reporter._verbose:
|
| 1435 |
+
self._reporter.write("\n{} ".format(test.name))
|
| 1436 |
+
|
| 1437 |
+
# check if there are external dependencies which need to be met
|
| 1438 |
+
if '_doctest_depends_on' in test.globs:
|
| 1439 |
+
try:
|
| 1440 |
+
self._check_dependencies(**test.globs['_doctest_depends_on'])
|
| 1441 |
+
except DependencyError as e:
|
| 1442 |
+
self._reporter.test_skip(v=str(e))
|
| 1443 |
+
continue
|
| 1444 |
+
|
| 1445 |
+
runner = SymPyDocTestRunner(verbose=self._reporter._verbose==2,
|
| 1446 |
+
optionflags=pdoctest.ELLIPSIS |
|
| 1447 |
+
pdoctest.NORMALIZE_WHITESPACE |
|
| 1448 |
+
pdoctest.IGNORE_EXCEPTION_DETAIL)
|
| 1449 |
+
runner._checker = SymPyOutputChecker()
|
| 1450 |
+
old = sys.stdout
|
| 1451 |
+
new = old if self._reporter._verbose==2 else StringIO()
|
| 1452 |
+
sys.stdout = new
|
| 1453 |
+
# If the testing is normal, the doctests get importing magic to
|
| 1454 |
+
# provide the global namespace. If not normal (the default) then
|
| 1455 |
+
# then must run on their own; all imports must be explicit within
|
| 1456 |
+
# a function's docstring. Once imported that import will be
|
| 1457 |
+
# available to the rest of the tests in a given function's
|
| 1458 |
+
# docstring (unless clear_globs=True below).
|
| 1459 |
+
if not self._normal:
|
| 1460 |
+
test.globs = {}
|
| 1461 |
+
# if this is uncommented then all the test would get is what
|
| 1462 |
+
# comes by default with a "from sympy import *"
|
| 1463 |
+
#exec('from sympy import *') in test.globs
|
| 1464 |
+
old_displayhook = sys.displayhook
|
| 1465 |
+
use_unicode_prev = setup_pprint()
|
| 1466 |
+
|
| 1467 |
+
try:
|
| 1468 |
+
f, t = runner.run(test,
|
| 1469 |
+
out=new.write, clear_globs=False)
|
| 1470 |
+
except KeyboardInterrupt:
|
| 1471 |
+
raise
|
| 1472 |
+
finally:
|
| 1473 |
+
sys.stdout = old
|
| 1474 |
+
if f > 0:
|
| 1475 |
+
self._reporter.doctest_fail(test.name, new.getvalue())
|
| 1476 |
+
else:
|
| 1477 |
+
self._reporter.test_pass()
|
| 1478 |
+
sys.displayhook = old_displayhook
|
| 1479 |
+
interactive_printing.NO_GLOBAL = False
|
| 1480 |
+
pprint_use_unicode(use_unicode_prev)
|
| 1481 |
+
|
| 1482 |
+
self._reporter.leaving_filename()
|
| 1483 |
+
|
| 1484 |
+
def get_test_files(self, dir, pat='*.py', init_only=True):
|
| 1485 |
+
r"""
|
| 1486 |
+
Returns the list of \*.py files (default) from which docstrings
|
| 1487 |
+
will be tested which are at or below directory ``dir``. By default,
|
| 1488 |
+
only those that have an __init__.py in their parent directory
|
| 1489 |
+
and do not start with ``test_`` will be included.
|
| 1490 |
+
"""
|
| 1491 |
+
def importable(x):
|
| 1492 |
+
"""
|
| 1493 |
+
Checks if given pathname x is an importable module by checking for
|
| 1494 |
+
__init__.py file.
|
| 1495 |
+
|
| 1496 |
+
Returns True/False.
|
| 1497 |
+
|
| 1498 |
+
Currently we only test if the __init__.py file exists in the
|
| 1499 |
+
directory with the file "x" (in theory we should also test all the
|
| 1500 |
+
parent dirs).
|
| 1501 |
+
"""
|
| 1502 |
+
init_py = os.path.join(os.path.dirname(x), "__init__.py")
|
| 1503 |
+
return os.path.exists(init_py)
|
| 1504 |
+
|
| 1505 |
+
dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0])
|
| 1506 |
+
|
| 1507 |
+
g = []
|
| 1508 |
+
for path, folders, files in os.walk(dir):
|
| 1509 |
+
g.extend([os.path.join(path, f) for f in files
|
| 1510 |
+
if not f.startswith('test_') and fnmatch(f, pat)])
|
| 1511 |
+
if init_only:
|
| 1512 |
+
# skip files that are not importable (i.e. missing __init__.py)
|
| 1513 |
+
g = [x for x in g if importable(x)]
|
| 1514 |
+
|
| 1515 |
+
return [os.path.normcase(gi) for gi in g]
|
| 1516 |
+
|
| 1517 |
+
def _check_dependencies(self,
|
| 1518 |
+
executables=(),
|
| 1519 |
+
modules=(),
|
| 1520 |
+
disable_viewers=(),
|
| 1521 |
+
python_version=(3, 5)):
|
| 1522 |
+
"""
|
| 1523 |
+
Checks if the dependencies for the test are installed.
|
| 1524 |
+
|
| 1525 |
+
Raises ``DependencyError`` it at least one dependency is not installed.
|
| 1526 |
+
"""
|
| 1527 |
+
|
| 1528 |
+
for executable in executables:
|
| 1529 |
+
if not shutil.which(executable):
|
| 1530 |
+
raise DependencyError("Could not find %s" % executable)
|
| 1531 |
+
|
| 1532 |
+
for module in modules:
|
| 1533 |
+
if module == 'matplotlib':
|
| 1534 |
+
matplotlib = import_module(
|
| 1535 |
+
'matplotlib',
|
| 1536 |
+
import_kwargs={'fromlist':
|
| 1537 |
+
['pyplot', 'cm', 'collections']},
|
| 1538 |
+
min_module_version='1.0.0', catch=(RuntimeError,))
|
| 1539 |
+
if matplotlib is None:
|
| 1540 |
+
raise DependencyError("Could not import matplotlib")
|
| 1541 |
+
else:
|
| 1542 |
+
if not import_module(module):
|
| 1543 |
+
raise DependencyError("Could not import %s" % module)
|
| 1544 |
+
|
| 1545 |
+
if disable_viewers:
|
| 1546 |
+
tempdir = tempfile.mkdtemp()
|
| 1547 |
+
os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH'])
|
| 1548 |
+
|
| 1549 |
+
vw = ('#!/usr/bin/env python3\n'
|
| 1550 |
+
'import sys\n'
|
| 1551 |
+
'if len(sys.argv) <= 1:\n'
|
| 1552 |
+
' exit("wrong number of args")\n')
|
| 1553 |
+
|
| 1554 |
+
for viewer in disable_viewers:
|
| 1555 |
+
with open(os.path.join(tempdir, viewer), 'w') as fh:
|
| 1556 |
+
fh.write(vw)
|
| 1557 |
+
|
| 1558 |
+
# make the file executable
|
| 1559 |
+
os.chmod(os.path.join(tempdir, viewer),
|
| 1560 |
+
stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR)
|
| 1561 |
+
|
| 1562 |
+
if python_version:
|
| 1563 |
+
if sys.version_info < python_version:
|
| 1564 |
+
raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version)))
|
| 1565 |
+
|
| 1566 |
+
if 'pyglet' in modules:
|
| 1567 |
+
# monkey-patch pyglet s.t. it does not open a window during
|
| 1568 |
+
# doctesting
|
| 1569 |
+
import pyglet
|
| 1570 |
+
class DummyWindow:
|
| 1571 |
+
def __init__(self, *args, **kwargs):
|
| 1572 |
+
self.has_exit = True
|
| 1573 |
+
self.width = 600
|
| 1574 |
+
self.height = 400
|
| 1575 |
+
|
| 1576 |
+
def set_vsync(self, x):
|
| 1577 |
+
pass
|
| 1578 |
+
|
| 1579 |
+
def switch_to(self):
|
| 1580 |
+
pass
|
| 1581 |
+
|
| 1582 |
+
def push_handlers(self, x):
|
| 1583 |
+
pass
|
| 1584 |
+
|
| 1585 |
+
def close(self):
|
| 1586 |
+
pass
|
| 1587 |
+
|
| 1588 |
+
pyglet.window.Window = DummyWindow
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
class SymPyDocTestFinder(DocTestFinder):
|
| 1592 |
+
"""
|
| 1593 |
+
A class used to extract the DocTests that are relevant to a given
|
| 1594 |
+
object, from its docstring and the docstrings of its contained
|
| 1595 |
+
objects. Doctests can currently be extracted from the following
|
| 1596 |
+
object types: modules, functions, classes, methods, staticmethods,
|
| 1597 |
+
classmethods, and properties.
|
| 1598 |
+
|
| 1599 |
+
Modified from doctest's version to look harder for code that
|
| 1600 |
+
appears comes from a different module. For example, the @vectorize
|
| 1601 |
+
decorator makes it look like functions come from multidimensional.py
|
| 1602 |
+
even though their code exists elsewhere.
|
| 1603 |
+
"""
|
| 1604 |
+
|
| 1605 |
+
def _find(self, tests, obj, name, module, source_lines, globs, seen):
|
| 1606 |
+
"""
|
| 1607 |
+
Find tests for the given object and any contained objects, and
|
| 1608 |
+
add them to ``tests``.
|
| 1609 |
+
"""
|
| 1610 |
+
if self._verbose:
|
| 1611 |
+
print('Finding tests in %s' % name)
|
| 1612 |
+
|
| 1613 |
+
# If we've already processed this object, then ignore it.
|
| 1614 |
+
if id(obj) in seen:
|
| 1615 |
+
return
|
| 1616 |
+
seen[id(obj)] = 1
|
| 1617 |
+
|
| 1618 |
+
# Make sure we don't run doctests for classes outside of sympy, such
|
| 1619 |
+
# as in numpy or scipy.
|
| 1620 |
+
if inspect.isclass(obj):
|
| 1621 |
+
if obj.__module__.split('.')[0] != 'sympy':
|
| 1622 |
+
return
|
| 1623 |
+
|
| 1624 |
+
# Find a test for this object, and add it to the list of tests.
|
| 1625 |
+
test = self._get_test(obj, name, module, globs, source_lines)
|
| 1626 |
+
if test is not None:
|
| 1627 |
+
tests.append(test)
|
| 1628 |
+
|
| 1629 |
+
if not self._recurse:
|
| 1630 |
+
return
|
| 1631 |
+
|
| 1632 |
+
# Look for tests in a module's contained objects.
|
| 1633 |
+
if inspect.ismodule(obj):
|
| 1634 |
+
for rawname, val in obj.__dict__.items():
|
| 1635 |
+
# Recurse to functions & classes.
|
| 1636 |
+
if inspect.isfunction(val) or inspect.isclass(val):
|
| 1637 |
+
# Make sure we don't run doctests functions or classes
|
| 1638 |
+
# from different modules
|
| 1639 |
+
if val.__module__ != module.__name__:
|
| 1640 |
+
continue
|
| 1641 |
+
|
| 1642 |
+
assert self._from_module(module, val), \
|
| 1643 |
+
"%s is not in module %s (rawname %s)" % (val, module, rawname)
|
| 1644 |
+
|
| 1645 |
+
try:
|
| 1646 |
+
valname = '%s.%s' % (name, rawname)
|
| 1647 |
+
self._find(tests, val, valname, module,
|
| 1648 |
+
source_lines, globs, seen)
|
| 1649 |
+
except KeyboardInterrupt:
|
| 1650 |
+
raise
|
| 1651 |
+
|
| 1652 |
+
# Look for tests in a module's __test__ dictionary.
|
| 1653 |
+
for valname, val in getattr(obj, '__test__', {}).items():
|
| 1654 |
+
if not isinstance(valname, str):
|
| 1655 |
+
raise ValueError("SymPyDocTestFinder.find: __test__ keys "
|
| 1656 |
+
"must be strings: %r" %
|
| 1657 |
+
(type(valname),))
|
| 1658 |
+
if not (inspect.isfunction(val) or inspect.isclass(val) or
|
| 1659 |
+
inspect.ismethod(val) or inspect.ismodule(val) or
|
| 1660 |
+
isinstance(val, str)):
|
| 1661 |
+
raise ValueError("SymPyDocTestFinder.find: __test__ values "
|
| 1662 |
+
"must be strings, functions, methods, "
|
| 1663 |
+
"classes, or modules: %r" %
|
| 1664 |
+
(type(val),))
|
| 1665 |
+
valname = '%s.__test__.%s' % (name, valname)
|
| 1666 |
+
self._find(tests, val, valname, module, source_lines,
|
| 1667 |
+
globs, seen)
|
| 1668 |
+
|
| 1669 |
+
|
| 1670 |
+
# Look for tests in a class's contained objects.
|
| 1671 |
+
if inspect.isclass(obj):
|
| 1672 |
+
for valname, val in obj.__dict__.items():
|
| 1673 |
+
# Special handling for staticmethod/classmethod.
|
| 1674 |
+
if isinstance(val, staticmethod):
|
| 1675 |
+
val = getattr(obj, valname)
|
| 1676 |
+
if isinstance(val, classmethod):
|
| 1677 |
+
val = getattr(obj, valname).__func__
|
| 1678 |
+
|
| 1679 |
+
|
| 1680 |
+
# Recurse to methods, properties, and nested classes.
|
| 1681 |
+
if ((inspect.isfunction(unwrap(val)) or
|
| 1682 |
+
inspect.isclass(val) or
|
| 1683 |
+
isinstance(val, property)) and
|
| 1684 |
+
self._from_module(module, val)):
|
| 1685 |
+
# Make sure we don't run doctests functions or classes
|
| 1686 |
+
# from different modules
|
| 1687 |
+
if isinstance(val, property):
|
| 1688 |
+
if hasattr(val.fget, '__module__'):
|
| 1689 |
+
if val.fget.__module__ != module.__name__:
|
| 1690 |
+
continue
|
| 1691 |
+
else:
|
| 1692 |
+
if val.__module__ != module.__name__:
|
| 1693 |
+
continue
|
| 1694 |
+
|
| 1695 |
+
assert self._from_module(module, val), \
|
| 1696 |
+
"%s is not in module %s (valname %s)" % (
|
| 1697 |
+
val, module, valname)
|
| 1698 |
+
|
| 1699 |
+
valname = '%s.%s' % (name, valname)
|
| 1700 |
+
self._find(tests, val, valname, module, source_lines,
|
| 1701 |
+
globs, seen)
|
| 1702 |
+
|
| 1703 |
+
def _get_test(self, obj, name, module, globs, source_lines):
|
| 1704 |
+
"""
|
| 1705 |
+
Return a DocTest for the given object, if it defines a docstring;
|
| 1706 |
+
otherwise, return None.
|
| 1707 |
+
"""
|
| 1708 |
+
|
| 1709 |
+
lineno = None
|
| 1710 |
+
|
| 1711 |
+
# Extract the object's docstring. If it does not have one,
|
| 1712 |
+
# then return None (no test for this object).
|
| 1713 |
+
if isinstance(obj, str):
|
| 1714 |
+
# obj is a string in the case for objects in the polys package.
|
| 1715 |
+
# Note that source_lines is a binary string (compiled polys
|
| 1716 |
+
# modules), which can't be handled by _find_lineno so determine
|
| 1717 |
+
# the line number here.
|
| 1718 |
+
|
| 1719 |
+
docstring = obj
|
| 1720 |
+
|
| 1721 |
+
matches = re.findall(r"line \d+", name)
|
| 1722 |
+
assert len(matches) == 1, \
|
| 1723 |
+
"string '%s' does not contain lineno " % name
|
| 1724 |
+
|
| 1725 |
+
# NOTE: this is not the exact linenumber but its better than no
|
| 1726 |
+
# lineno ;)
|
| 1727 |
+
lineno = int(matches[0][5:])
|
| 1728 |
+
|
| 1729 |
+
else:
|
| 1730 |
+
try:
|
| 1731 |
+
if obj.__doc__ is None:
|
| 1732 |
+
docstring = ''
|
| 1733 |
+
else:
|
| 1734 |
+
docstring = obj.__doc__
|
| 1735 |
+
if not isinstance(docstring, str):
|
| 1736 |
+
docstring = str(docstring)
|
| 1737 |
+
except (TypeError, AttributeError):
|
| 1738 |
+
docstring = ''
|
| 1739 |
+
|
| 1740 |
+
# Don't bother if the docstring is empty.
|
| 1741 |
+
if self._exclude_empty and not docstring:
|
| 1742 |
+
return None
|
| 1743 |
+
|
| 1744 |
+
# check that properties have a docstring because _find_lineno
|
| 1745 |
+
# assumes it
|
| 1746 |
+
if isinstance(obj, property):
|
| 1747 |
+
if obj.fget.__doc__ is None:
|
| 1748 |
+
return None
|
| 1749 |
+
|
| 1750 |
+
# Find the docstring's location in the file.
|
| 1751 |
+
if lineno is None:
|
| 1752 |
+
obj = unwrap(obj)
|
| 1753 |
+
# handling of properties is not implemented in _find_lineno so do
|
| 1754 |
+
# it here
|
| 1755 |
+
if hasattr(obj, 'func_closure') and obj.func_closure is not None:
|
| 1756 |
+
tobj = obj.func_closure[0].cell_contents
|
| 1757 |
+
elif isinstance(obj, property):
|
| 1758 |
+
tobj = obj.fget
|
| 1759 |
+
else:
|
| 1760 |
+
tobj = obj
|
| 1761 |
+
lineno = self._find_lineno(tobj, source_lines)
|
| 1762 |
+
|
| 1763 |
+
if lineno is None:
|
| 1764 |
+
return None
|
| 1765 |
+
|
| 1766 |
+
# Return a DocTest for this object.
|
| 1767 |
+
if module is None:
|
| 1768 |
+
filename = None
|
| 1769 |
+
else:
|
| 1770 |
+
filename = getattr(module, '__file__', module.__name__)
|
| 1771 |
+
if filename[-4:] in (".pyc", ".pyo"):
|
| 1772 |
+
filename = filename[:-1]
|
| 1773 |
+
|
| 1774 |
+
globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {})
|
| 1775 |
+
|
| 1776 |
+
return self._parser.get_doctest(docstring, globs, name,
|
| 1777 |
+
filename, lineno)
|
| 1778 |
+
|
| 1779 |
+
|
| 1780 |
+
class SymPyDocTestRunner(DocTestRunner):
|
| 1781 |
+
"""
|
| 1782 |
+
A class used to run DocTest test cases, and accumulate statistics.
|
| 1783 |
+
The ``run`` method is used to process a single DocTest case. It
|
| 1784 |
+
returns a tuple ``(f, t)``, where ``t`` is the number of test cases
|
| 1785 |
+
tried, and ``f`` is the number of test cases that failed.
|
| 1786 |
+
|
| 1787 |
+
Modified from the doctest version to not reset the sys.displayhook (see
|
| 1788 |
+
issue 5140).
|
| 1789 |
+
|
| 1790 |
+
See the docstring of the original DocTestRunner for more information.
|
| 1791 |
+
"""
|
| 1792 |
+
|
| 1793 |
+
def run(self, test, compileflags=None, out=None, clear_globs=True):
|
| 1794 |
+
"""
|
| 1795 |
+
Run the examples in ``test``, and display the results using the
|
| 1796 |
+
writer function ``out``.
|
| 1797 |
+
|
| 1798 |
+
The examples are run in the namespace ``test.globs``. If
|
| 1799 |
+
``clear_globs`` is true (the default), then this namespace will
|
| 1800 |
+
be cleared after the test runs, to help with garbage
|
| 1801 |
+
collection. If you would like to examine the namespace after
|
| 1802 |
+
the test completes, then use ``clear_globs=False``.
|
| 1803 |
+
|
| 1804 |
+
``compileflags`` gives the set of flags that should be used by
|
| 1805 |
+
the Python compiler when running the examples. If not
|
| 1806 |
+
specified, then it will default to the set of future-import
|
| 1807 |
+
flags that apply to ``globs``.
|
| 1808 |
+
|
| 1809 |
+
The output of each example is checked using
|
| 1810 |
+
``SymPyDocTestRunner.check_output``, and the results are
|
| 1811 |
+
formatted by the ``SymPyDocTestRunner.report_*`` methods.
|
| 1812 |
+
"""
|
| 1813 |
+
self.test = test
|
| 1814 |
+
|
| 1815 |
+
# Remove ``` from the end of example, which may appear in Markdown
|
| 1816 |
+
# files
|
| 1817 |
+
for example in test.examples:
|
| 1818 |
+
example.want = example.want.replace('```\n', '')
|
| 1819 |
+
example.exc_msg = example.exc_msg and example.exc_msg.replace('```\n', '')
|
| 1820 |
+
|
| 1821 |
+
|
| 1822 |
+
if compileflags is None:
|
| 1823 |
+
compileflags = pdoctest._extract_future_flags(test.globs)
|
| 1824 |
+
|
| 1825 |
+
save_stdout = sys.stdout
|
| 1826 |
+
if out is None:
|
| 1827 |
+
out = save_stdout.write
|
| 1828 |
+
sys.stdout = self._fakeout
|
| 1829 |
+
|
| 1830 |
+
# Patch pdb.set_trace to restore sys.stdout during interactive
|
| 1831 |
+
# debugging (so it's not still redirected to self._fakeout).
|
| 1832 |
+
# Note that the interactive output will go to *our*
|
| 1833 |
+
# save_stdout, even if that's not the real sys.stdout; this
|
| 1834 |
+
# allows us to write test cases for the set_trace behavior.
|
| 1835 |
+
save_set_trace = pdb.set_trace
|
| 1836 |
+
self.debugger = pdoctest._OutputRedirectingPdb(save_stdout)
|
| 1837 |
+
self.debugger.reset()
|
| 1838 |
+
pdb.set_trace = self.debugger.set_trace
|
| 1839 |
+
|
| 1840 |
+
# Patch linecache.getlines, so we can see the example's source
|
| 1841 |
+
# when we're inside the debugger.
|
| 1842 |
+
self.save_linecache_getlines = pdoctest.linecache.getlines
|
| 1843 |
+
linecache.getlines = self.__patched_linecache_getlines
|
| 1844 |
+
|
| 1845 |
+
# Fail for deprecation warnings
|
| 1846 |
+
with raise_on_deprecated():
|
| 1847 |
+
try:
|
| 1848 |
+
return self.__run(test, compileflags, out)
|
| 1849 |
+
finally:
|
| 1850 |
+
sys.stdout = save_stdout
|
| 1851 |
+
pdb.set_trace = save_set_trace
|
| 1852 |
+
linecache.getlines = self.save_linecache_getlines
|
| 1853 |
+
if clear_globs:
|
| 1854 |
+
test.globs.clear()
|
| 1855 |
+
|
| 1856 |
+
|
| 1857 |
+
# We have to override the name mangled methods.
|
| 1858 |
+
monkeypatched_methods = [
|
| 1859 |
+
'patched_linecache_getlines',
|
| 1860 |
+
'run',
|
| 1861 |
+
'record_outcome'
|
| 1862 |
+
]
|
| 1863 |
+
for method in monkeypatched_methods:
|
| 1864 |
+
oldname = '_DocTestRunner__' + method
|
| 1865 |
+
newname = '_SymPyDocTestRunner__' + method
|
| 1866 |
+
setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname))
|
| 1867 |
+
|
| 1868 |
+
|
| 1869 |
+
class SymPyOutputChecker(pdoctest.OutputChecker):
|
| 1870 |
+
"""
|
| 1871 |
+
Compared to the OutputChecker from the stdlib our OutputChecker class
|
| 1872 |
+
supports numerical comparison of floats occurring in the output of the
|
| 1873 |
+
doctest examples
|
| 1874 |
+
"""
|
| 1875 |
+
|
| 1876 |
+
def __init__(self):
|
| 1877 |
+
# NOTE OutputChecker is an old-style class with no __init__ method,
|
| 1878 |
+
# so we can't call the base class version of __init__ here
|
| 1879 |
+
|
| 1880 |
+
got_floats = r'(\d+\.\d*|\.\d+)'
|
| 1881 |
+
|
| 1882 |
+
# floats in the 'want' string may contain ellipses
|
| 1883 |
+
want_floats = got_floats + r'(\.{3})?'
|
| 1884 |
+
|
| 1885 |
+
front_sep = r'\s|\+|\-|\*|,'
|
| 1886 |
+
back_sep = front_sep + r'|j|e'
|
| 1887 |
+
|
| 1888 |
+
fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep)
|
| 1889 |
+
fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep)
|
| 1890 |
+
self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
|
| 1891 |
+
|
| 1892 |
+
fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep)
|
| 1893 |
+
fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep)
|
| 1894 |
+
self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend))
|
| 1895 |
+
|
| 1896 |
+
def check_output(self, want, got, optionflags):
|
| 1897 |
+
"""
|
| 1898 |
+
Return True iff the actual output from an example (`got`)
|
| 1899 |
+
matches the expected output (`want`). These strings are
|
| 1900 |
+
always considered to match if they are identical; but
|
| 1901 |
+
depending on what option flags the test runner is using,
|
| 1902 |
+
several non-exact match types are also possible. See the
|
| 1903 |
+
documentation for `TestRunner` for more information about
|
| 1904 |
+
option flags.
|
| 1905 |
+
"""
|
| 1906 |
+
# Handle the common case first, for efficiency:
|
| 1907 |
+
# if they're string-identical, always return true.
|
| 1908 |
+
if got == want:
|
| 1909 |
+
return True
|
| 1910 |
+
|
| 1911 |
+
# TODO parse integers as well ?
|
| 1912 |
+
# Parse floats and compare them. If some of the parsed floats contain
|
| 1913 |
+
# ellipses, skip the comparison.
|
| 1914 |
+
matches = self.num_got_rgx.finditer(got)
|
| 1915 |
+
numbers_got = [match.group(1) for match in matches] # list of strs
|
| 1916 |
+
matches = self.num_want_rgx.finditer(want)
|
| 1917 |
+
numbers_want = [match.group(1) for match in matches] # list of strs
|
| 1918 |
+
if len(numbers_got) != len(numbers_want):
|
| 1919 |
+
return False
|
| 1920 |
+
|
| 1921 |
+
if len(numbers_got) > 0:
|
| 1922 |
+
nw_ = []
|
| 1923 |
+
for ng, nw in zip(numbers_got, numbers_want):
|
| 1924 |
+
if '...' in nw:
|
| 1925 |
+
nw_.append(ng)
|
| 1926 |
+
continue
|
| 1927 |
+
else:
|
| 1928 |
+
nw_.append(nw)
|
| 1929 |
+
|
| 1930 |
+
if abs(float(ng)-float(nw)) > 1e-5:
|
| 1931 |
+
return False
|
| 1932 |
+
|
| 1933 |
+
got = self.num_got_rgx.sub(r'%s', got)
|
| 1934 |
+
got = got % tuple(nw_)
|
| 1935 |
+
|
| 1936 |
+
# <BLANKLINE> can be used as a special sequence to signify a
|
| 1937 |
+
# blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
|
| 1938 |
+
if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE):
|
| 1939 |
+
# Replace <BLANKLINE> in want with a blank line.
|
| 1940 |
+
want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER),
|
| 1941 |
+
'', want)
|
| 1942 |
+
# If a line in got contains only spaces, then remove the
|
| 1943 |
+
# spaces.
|
| 1944 |
+
got = re.sub(r'(?m)^\s*?$', '', got)
|
| 1945 |
+
if got == want:
|
| 1946 |
+
return True
|
| 1947 |
+
|
| 1948 |
+
# This flag causes doctest to ignore any differences in the
|
| 1949 |
+
# contents of whitespace strings. Note that this can be used
|
| 1950 |
+
# in conjunction with the ELLIPSIS flag.
|
| 1951 |
+
if optionflags & pdoctest.NORMALIZE_WHITESPACE:
|
| 1952 |
+
got = ' '.join(got.split())
|
| 1953 |
+
want = ' '.join(want.split())
|
| 1954 |
+
if got == want:
|
| 1955 |
+
return True
|
| 1956 |
+
|
| 1957 |
+
# The ELLIPSIS flag says to let the sequence "..." in `want`
|
| 1958 |
+
# match any substring in `got`.
|
| 1959 |
+
if optionflags & pdoctest.ELLIPSIS:
|
| 1960 |
+
if pdoctest._ellipsis_match(want, got):
|
| 1961 |
+
return True
|
| 1962 |
+
|
| 1963 |
+
# We didn't find any match; return false.
|
| 1964 |
+
return False
|
| 1965 |
+
|
| 1966 |
+
|
| 1967 |
+
class Reporter:
|
| 1968 |
+
"""
|
| 1969 |
+
Parent class for all reporters.
|
| 1970 |
+
"""
|
| 1971 |
+
pass
|
| 1972 |
+
|
| 1973 |
+
|
| 1974 |
+
class PyTestReporter(Reporter):
|
| 1975 |
+
"""
|
| 1976 |
+
Py.test like reporter. Should produce output identical to py.test.
|
| 1977 |
+
"""
|
| 1978 |
+
|
| 1979 |
+
def __init__(self, verbose=False, tb="short", colors=True,
|
| 1980 |
+
force_colors=False, split=None):
|
| 1981 |
+
self._verbose = verbose
|
| 1982 |
+
self._tb_style = tb
|
| 1983 |
+
self._colors = colors
|
| 1984 |
+
self._force_colors = force_colors
|
| 1985 |
+
self._xfailed = 0
|
| 1986 |
+
self._xpassed = []
|
| 1987 |
+
self._failed = []
|
| 1988 |
+
self._failed_doctest = []
|
| 1989 |
+
self._passed = 0
|
| 1990 |
+
self._skipped = 0
|
| 1991 |
+
self._exceptions = []
|
| 1992 |
+
self._terminal_width = None
|
| 1993 |
+
self._default_width = 80
|
| 1994 |
+
self._split = split
|
| 1995 |
+
self._active_file = ''
|
| 1996 |
+
self._active_f = None
|
| 1997 |
+
|
| 1998 |
+
# TODO: Should these be protected?
|
| 1999 |
+
self.slow_test_functions = []
|
| 2000 |
+
self.fast_test_functions = []
|
| 2001 |
+
|
| 2002 |
+
# this tracks the x-position of the cursor (useful for positioning
|
| 2003 |
+
# things on the screen), without the need for any readline library:
|
| 2004 |
+
self._write_pos = 0
|
| 2005 |
+
self._line_wrap = False
|
| 2006 |
+
|
| 2007 |
+
def root_dir(self, dir):
|
| 2008 |
+
self._root_dir = dir
|
| 2009 |
+
|
| 2010 |
+
@property
|
| 2011 |
+
def terminal_width(self):
|
| 2012 |
+
if self._terminal_width is not None:
|
| 2013 |
+
return self._terminal_width
|
| 2014 |
+
|
| 2015 |
+
def findout_terminal_width():
|
| 2016 |
+
if sys.platform == "win32":
|
| 2017 |
+
# Windows support is based on:
|
| 2018 |
+
#
|
| 2019 |
+
# http://code.activestate.com/recipes/
|
| 2020 |
+
# 440694-determine-size-of-console-window-on-windows/
|
| 2021 |
+
|
| 2022 |
+
from ctypes import windll, create_string_buffer
|
| 2023 |
+
|
| 2024 |
+
h = windll.kernel32.GetStdHandle(-12)
|
| 2025 |
+
csbi = create_string_buffer(22)
|
| 2026 |
+
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
|
| 2027 |
+
|
| 2028 |
+
if res:
|
| 2029 |
+
import struct
|
| 2030 |
+
(_, _, _, _, _, left, _, right, _, _, _) = \
|
| 2031 |
+
struct.unpack("hhhhHhhhhhh", csbi.raw)
|
| 2032 |
+
return right - left
|
| 2033 |
+
else:
|
| 2034 |
+
return self._default_width
|
| 2035 |
+
|
| 2036 |
+
if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty():
|
| 2037 |
+
return self._default_width # leave PIPEs alone
|
| 2038 |
+
|
| 2039 |
+
try:
|
| 2040 |
+
process = subprocess.Popen(['stty', '-a'],
|
| 2041 |
+
stdout=subprocess.PIPE,
|
| 2042 |
+
stderr=subprocess.PIPE)
|
| 2043 |
+
stdout, stderr = process.communicate()
|
| 2044 |
+
stdout = stdout.decode("utf-8")
|
| 2045 |
+
except OSError:
|
| 2046 |
+
pass
|
| 2047 |
+
else:
|
| 2048 |
+
# We support the following output formats from stty:
|
| 2049 |
+
#
|
| 2050 |
+
# 1) Linux -> columns 80
|
| 2051 |
+
# 2) OS X -> 80 columns
|
| 2052 |
+
# 3) Solaris -> columns = 80
|
| 2053 |
+
|
| 2054 |
+
re_linux = r"columns\s+(?P<columns>\d+);"
|
| 2055 |
+
re_osx = r"(?P<columns>\d+)\s*columns;"
|
| 2056 |
+
re_solaris = r"columns\s+=\s+(?P<columns>\d+);"
|
| 2057 |
+
|
| 2058 |
+
for regex in (re_linux, re_osx, re_solaris):
|
| 2059 |
+
match = re.search(regex, stdout)
|
| 2060 |
+
|
| 2061 |
+
if match is not None:
|
| 2062 |
+
columns = match.group('columns')
|
| 2063 |
+
|
| 2064 |
+
try:
|
| 2065 |
+
width = int(columns)
|
| 2066 |
+
except ValueError:
|
| 2067 |
+
pass
|
| 2068 |
+
if width != 0:
|
| 2069 |
+
return width
|
| 2070 |
+
|
| 2071 |
+
return self._default_width
|
| 2072 |
+
|
| 2073 |
+
width = findout_terminal_width()
|
| 2074 |
+
self._terminal_width = width
|
| 2075 |
+
|
| 2076 |
+
return width
|
| 2077 |
+
|
| 2078 |
+
def write(self, text, color="", align="left", width=None,
|
| 2079 |
+
force_colors=False):
|
| 2080 |
+
"""
|
| 2081 |
+
Prints a text on the screen.
|
| 2082 |
+
|
| 2083 |
+
It uses sys.stdout.write(), so no readline library is necessary.
|
| 2084 |
+
|
| 2085 |
+
Parameters
|
| 2086 |
+
==========
|
| 2087 |
+
|
| 2088 |
+
color : choose from the colors below, "" means default color
|
| 2089 |
+
align : "left"/"right", "left" is a normal print, "right" is aligned on
|
| 2090 |
+
the right-hand side of the screen, filled with spaces if
|
| 2091 |
+
necessary
|
| 2092 |
+
width : the screen width
|
| 2093 |
+
|
| 2094 |
+
"""
|
| 2095 |
+
color_templates = (
|
| 2096 |
+
("Black", "0;30"),
|
| 2097 |
+
("Red", "0;31"),
|
| 2098 |
+
("Green", "0;32"),
|
| 2099 |
+
("Brown", "0;33"),
|
| 2100 |
+
("Blue", "0;34"),
|
| 2101 |
+
("Purple", "0;35"),
|
| 2102 |
+
("Cyan", "0;36"),
|
| 2103 |
+
("LightGray", "0;37"),
|
| 2104 |
+
("DarkGray", "1;30"),
|
| 2105 |
+
("LightRed", "1;31"),
|
| 2106 |
+
("LightGreen", "1;32"),
|
| 2107 |
+
("Yellow", "1;33"),
|
| 2108 |
+
("LightBlue", "1;34"),
|
| 2109 |
+
("LightPurple", "1;35"),
|
| 2110 |
+
("LightCyan", "1;36"),
|
| 2111 |
+
("White", "1;37"),
|
| 2112 |
+
)
|
| 2113 |
+
|
| 2114 |
+
colors = {}
|
| 2115 |
+
|
| 2116 |
+
for name, value in color_templates:
|
| 2117 |
+
colors[name] = value
|
| 2118 |
+
c_normal = '\033[0m'
|
| 2119 |
+
c_color = '\033[%sm'
|
| 2120 |
+
|
| 2121 |
+
if width is None:
|
| 2122 |
+
width = self.terminal_width
|
| 2123 |
+
|
| 2124 |
+
if align == "right":
|
| 2125 |
+
if self._write_pos + len(text) > width:
|
| 2126 |
+
# we don't fit on the current line, create a new line
|
| 2127 |
+
self.write("\n")
|
| 2128 |
+
self.write(" "*(width - self._write_pos - len(text)))
|
| 2129 |
+
|
| 2130 |
+
if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \
|
| 2131 |
+
sys.stdout.isatty():
|
| 2132 |
+
# the stdout is not a terminal, this for example happens if the
|
| 2133 |
+
# output is piped to less, e.g. "bin/test | less". In this case,
|
| 2134 |
+
# the terminal control sequences would be printed verbatim, so
|
| 2135 |
+
# don't use any colors.
|
| 2136 |
+
color = ""
|
| 2137 |
+
elif sys.platform == "win32":
|
| 2138 |
+
# Windows consoles don't support ANSI escape sequences
|
| 2139 |
+
color = ""
|
| 2140 |
+
elif not self._colors:
|
| 2141 |
+
color = ""
|
| 2142 |
+
|
| 2143 |
+
if self._line_wrap:
|
| 2144 |
+
if text[0] != "\n":
|
| 2145 |
+
sys.stdout.write("\n")
|
| 2146 |
+
|
| 2147 |
+
# Avoid UnicodeEncodeError when printing out test failures
|
| 2148 |
+
if IS_WINDOWS:
|
| 2149 |
+
text = text.encode('raw_unicode_escape').decode('utf8', 'ignore')
|
| 2150 |
+
elif not sys.stdout.encoding.lower().startswith('utf'):
|
| 2151 |
+
text = text.encode(sys.stdout.encoding, 'backslashreplace'
|
| 2152 |
+
).decode(sys.stdout.encoding)
|
| 2153 |
+
|
| 2154 |
+
if color == "":
|
| 2155 |
+
sys.stdout.write(text)
|
| 2156 |
+
else:
|
| 2157 |
+
sys.stdout.write("%s%s%s" %
|
| 2158 |
+
(c_color % colors[color], text, c_normal))
|
| 2159 |
+
sys.stdout.flush()
|
| 2160 |
+
l = text.rfind("\n")
|
| 2161 |
+
if l == -1:
|
| 2162 |
+
self._write_pos += len(text)
|
| 2163 |
+
else:
|
| 2164 |
+
self._write_pos = len(text) - l - 1
|
| 2165 |
+
self._line_wrap = self._write_pos >= width
|
| 2166 |
+
self._write_pos %= width
|
| 2167 |
+
|
| 2168 |
+
def write_center(self, text, delim="="):
|
| 2169 |
+
width = self.terminal_width
|
| 2170 |
+
if text != "":
|
| 2171 |
+
text = " %s " % text
|
| 2172 |
+
idx = (width - len(text)) // 2
|
| 2173 |
+
t = delim*idx + text + delim*(width - idx - len(text))
|
| 2174 |
+
self.write(t + "\n")
|
| 2175 |
+
|
| 2176 |
+
def write_exception(self, e, val, tb):
|
| 2177 |
+
# remove the first item, as that is always runtests.py
|
| 2178 |
+
tb = tb.tb_next
|
| 2179 |
+
t = traceback.format_exception(e, val, tb)
|
| 2180 |
+
self.write("".join(t))
|
| 2181 |
+
|
| 2182 |
+
def start(self, seed=None, msg="test process starts"):
|
| 2183 |
+
self.write_center(msg)
|
| 2184 |
+
executable = sys.executable
|
| 2185 |
+
v = tuple(sys.version_info)
|
| 2186 |
+
python_version = "%s.%s.%s-%s-%s" % v
|
| 2187 |
+
implementation = platform.python_implementation()
|
| 2188 |
+
if implementation == 'PyPy':
|
| 2189 |
+
implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info
|
| 2190 |
+
self.write("executable: %s (%s) [%s]\n" %
|
| 2191 |
+
(executable, python_version, implementation))
|
| 2192 |
+
from sympy.utilities.misc import ARCH
|
| 2193 |
+
self.write("architecture: %s\n" % ARCH)
|
| 2194 |
+
from sympy.core.cache import USE_CACHE
|
| 2195 |
+
self.write("cache: %s\n" % USE_CACHE)
|
| 2196 |
+
version = ''
|
| 2197 |
+
if GROUND_TYPES =='gmpy':
|
| 2198 |
+
if HAS_GMPY == 1:
|
| 2199 |
+
import gmpy
|
| 2200 |
+
elif HAS_GMPY == 2:
|
| 2201 |
+
import gmpy2 as gmpy
|
| 2202 |
+
version = gmpy.version()
|
| 2203 |
+
self.write("ground types: %s %s\n" % (GROUND_TYPES, version))
|
| 2204 |
+
numpy = import_module('numpy')
|
| 2205 |
+
self.write("numpy: %s\n" % (None if not numpy else numpy.__version__))
|
| 2206 |
+
if seed is not None:
|
| 2207 |
+
self.write("random seed: %d\n" % seed)
|
| 2208 |
+
from sympy.utilities.misc import HASH_RANDOMIZATION
|
| 2209 |
+
self.write("hash randomization: ")
|
| 2210 |
+
hash_seed = os.getenv("PYTHONHASHSEED") or '0'
|
| 2211 |
+
if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)):
|
| 2212 |
+
self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed)
|
| 2213 |
+
else:
|
| 2214 |
+
self.write("off\n")
|
| 2215 |
+
if self._split:
|
| 2216 |
+
self.write("split: %s\n" % self._split)
|
| 2217 |
+
self.write('\n')
|
| 2218 |
+
self._t_start = clock()
|
| 2219 |
+
|
| 2220 |
+
def finish(self):
|
| 2221 |
+
self._t_end = clock()
|
| 2222 |
+
self.write("\n")
|
| 2223 |
+
global text, linelen
|
| 2224 |
+
text = "tests finished: %d passed, " % self._passed
|
| 2225 |
+
linelen = len(text)
|
| 2226 |
+
|
| 2227 |
+
def add_text(mytext):
|
| 2228 |
+
global text, linelen
|
| 2229 |
+
"""Break new text if too long."""
|
| 2230 |
+
if linelen + len(mytext) > self.terminal_width:
|
| 2231 |
+
text += '\n'
|
| 2232 |
+
linelen = 0
|
| 2233 |
+
text += mytext
|
| 2234 |
+
linelen += len(mytext)
|
| 2235 |
+
|
| 2236 |
+
if len(self._failed) > 0:
|
| 2237 |
+
add_text("%d failed, " % len(self._failed))
|
| 2238 |
+
if len(self._failed_doctest) > 0:
|
| 2239 |
+
add_text("%d failed, " % len(self._failed_doctest))
|
| 2240 |
+
if self._skipped > 0:
|
| 2241 |
+
add_text("%d skipped, " % self._skipped)
|
| 2242 |
+
if self._xfailed > 0:
|
| 2243 |
+
add_text("%d expected to fail, " % self._xfailed)
|
| 2244 |
+
if len(self._xpassed) > 0:
|
| 2245 |
+
add_text("%d expected to fail but passed, " % len(self._xpassed))
|
| 2246 |
+
if len(self._exceptions) > 0:
|
| 2247 |
+
add_text("%d exceptions, " % len(self._exceptions))
|
| 2248 |
+
add_text("in %.2f seconds" % (self._t_end - self._t_start))
|
| 2249 |
+
|
| 2250 |
+
if self.slow_test_functions:
|
| 2251 |
+
self.write_center('slowest tests', '_')
|
| 2252 |
+
sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1])
|
| 2253 |
+
for slow_func_name, taken in sorted_slow:
|
| 2254 |
+
print('%s - Took %.3f seconds' % (slow_func_name, taken))
|
| 2255 |
+
|
| 2256 |
+
if self.fast_test_functions:
|
| 2257 |
+
self.write_center('unexpectedly fast tests', '_')
|
| 2258 |
+
sorted_fast = sorted(self.fast_test_functions,
|
| 2259 |
+
key=lambda r: r[1])
|
| 2260 |
+
for fast_func_name, taken in sorted_fast:
|
| 2261 |
+
print('%s - Took %.3f seconds' % (fast_func_name, taken))
|
| 2262 |
+
|
| 2263 |
+
if len(self._xpassed) > 0:
|
| 2264 |
+
self.write_center("xpassed tests", "_")
|
| 2265 |
+
for e in self._xpassed:
|
| 2266 |
+
self.write("%s: %s\n" % (e[0], e[1]))
|
| 2267 |
+
self.write("\n")
|
| 2268 |
+
|
| 2269 |
+
if self._tb_style != "no" and len(self._exceptions) > 0:
|
| 2270 |
+
for e in self._exceptions:
|
| 2271 |
+
filename, f, (t, val, tb) = e
|
| 2272 |
+
self.write_center("", "_")
|
| 2273 |
+
if f is None:
|
| 2274 |
+
s = "%s" % filename
|
| 2275 |
+
else:
|
| 2276 |
+
s = "%s:%s" % (filename, f.__name__)
|
| 2277 |
+
self.write_center(s, "_")
|
| 2278 |
+
self.write_exception(t, val, tb)
|
| 2279 |
+
self.write("\n")
|
| 2280 |
+
|
| 2281 |
+
if self._tb_style != "no" and len(self._failed) > 0:
|
| 2282 |
+
for e in self._failed:
|
| 2283 |
+
filename, f, (t, val, tb) = e
|
| 2284 |
+
self.write_center("", "_")
|
| 2285 |
+
self.write_center("%s:%s" % (filename, f.__name__), "_")
|
| 2286 |
+
self.write_exception(t, val, tb)
|
| 2287 |
+
self.write("\n")
|
| 2288 |
+
|
| 2289 |
+
if self._tb_style != "no" and len(self._failed_doctest) > 0:
|
| 2290 |
+
for e in self._failed_doctest:
|
| 2291 |
+
filename, msg = e
|
| 2292 |
+
self.write_center("", "_")
|
| 2293 |
+
self.write_center("%s" % filename, "_")
|
| 2294 |
+
self.write(msg)
|
| 2295 |
+
self.write("\n")
|
| 2296 |
+
|
| 2297 |
+
self.write_center(text)
|
| 2298 |
+
ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \
|
| 2299 |
+
len(self._failed_doctest) == 0
|
| 2300 |
+
if not ok:
|
| 2301 |
+
self.write("DO *NOT* COMMIT!\n")
|
| 2302 |
+
return ok
|
| 2303 |
+
|
| 2304 |
+
def entering_filename(self, filename, n):
|
| 2305 |
+
rel_name = filename[len(self._root_dir) + 1:]
|
| 2306 |
+
self._active_file = rel_name
|
| 2307 |
+
self._active_file_error = False
|
| 2308 |
+
self.write(rel_name)
|
| 2309 |
+
self.write("[%d] " % n)
|
| 2310 |
+
|
| 2311 |
+
def leaving_filename(self):
|
| 2312 |
+
self.write(" ")
|
| 2313 |
+
if self._active_file_error:
|
| 2314 |
+
self.write("[FAIL]", "Red", align="right")
|
| 2315 |
+
else:
|
| 2316 |
+
self.write("[OK]", "Green", align="right")
|
| 2317 |
+
self.write("\n")
|
| 2318 |
+
if self._verbose:
|
| 2319 |
+
self.write("\n")
|
| 2320 |
+
|
| 2321 |
+
def entering_test(self, f):
|
| 2322 |
+
self._active_f = f
|
| 2323 |
+
if self._verbose:
|
| 2324 |
+
self.write("\n" + f.__name__ + " ")
|
| 2325 |
+
|
| 2326 |
+
def test_xfail(self):
|
| 2327 |
+
self._xfailed += 1
|
| 2328 |
+
self.write("f", "Green")
|
| 2329 |
+
|
| 2330 |
+
def test_xpass(self, v):
|
| 2331 |
+
message = str(v)
|
| 2332 |
+
self._xpassed.append((self._active_file, message))
|
| 2333 |
+
self.write("X", "Green")
|
| 2334 |
+
|
| 2335 |
+
def test_fail(self, exc_info):
|
| 2336 |
+
self._failed.append((self._active_file, self._active_f, exc_info))
|
| 2337 |
+
self.write("F", "Red")
|
| 2338 |
+
self._active_file_error = True
|
| 2339 |
+
|
| 2340 |
+
def doctest_fail(self, name, error_msg):
|
| 2341 |
+
# the first line contains "******", remove it:
|
| 2342 |
+
error_msg = "\n".join(error_msg.split("\n")[1:])
|
| 2343 |
+
self._failed_doctest.append((name, error_msg))
|
| 2344 |
+
self.write("F", "Red")
|
| 2345 |
+
self._active_file_error = True
|
| 2346 |
+
|
| 2347 |
+
def test_pass(self, char="."):
|
| 2348 |
+
self._passed += 1
|
| 2349 |
+
if self._verbose:
|
| 2350 |
+
self.write("ok", "Green")
|
| 2351 |
+
else:
|
| 2352 |
+
self.write(char, "Green")
|
| 2353 |
+
|
| 2354 |
+
def test_skip(self, v=None):
|
| 2355 |
+
char = "s"
|
| 2356 |
+
self._skipped += 1
|
| 2357 |
+
if v is not None:
|
| 2358 |
+
message = str(v)
|
| 2359 |
+
if message == "KeyboardInterrupt":
|
| 2360 |
+
char = "K"
|
| 2361 |
+
elif message == "Timeout":
|
| 2362 |
+
char = "T"
|
| 2363 |
+
elif message == "Slow":
|
| 2364 |
+
char = "w"
|
| 2365 |
+
if self._verbose:
|
| 2366 |
+
if v is not None:
|
| 2367 |
+
self.write(message + ' ', "Blue")
|
| 2368 |
+
else:
|
| 2369 |
+
self.write(" - ", "Blue")
|
| 2370 |
+
self.write(char, "Blue")
|
| 2371 |
+
|
| 2372 |
+
def test_exception(self, exc_info):
|
| 2373 |
+
self._exceptions.append((self._active_file, self._active_f, exc_info))
|
| 2374 |
+
if exc_info[0] is TimeOutError:
|
| 2375 |
+
self.write("T", "Red")
|
| 2376 |
+
else:
|
| 2377 |
+
self.write("E", "Red")
|
| 2378 |
+
self._active_file_error = True
|
| 2379 |
+
|
| 2380 |
+
def import_error(self, filename, exc_info):
|
| 2381 |
+
self._exceptions.append((filename, None, exc_info))
|
| 2382 |
+
rel_name = filename[len(self._root_dir) + 1:]
|
| 2383 |
+
self.write(rel_name)
|
| 2384 |
+
self.write("[?] Failed to import", "Red")
|
| 2385 |
+
self.write(" ")
|
| 2386 |
+
self.write("[FAIL]", "Red", align="right")
|
| 2387 |
+
self.write("\n")
|
shared/package-files/41/41bb9b06cff1425bcac1e027bab8721e320ae238bbec68781bebac5ee97a5d53/blob
ADDED
|
Binary file (2.22 kB). View file
|
|
|
shared/package-files/41/41bd0efdfefcabe0ad1da6ef1d2ed54499a771b92eaa8c164c5dff76b98c8312/blob
ADDED
|
@@ -0,0 +1,3360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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4 |
+
and the Diffie-Hellman key exchange.
|
| 5 |
+
|
| 6 |
+
.. warning::
|
| 7 |
+
|
| 8 |
+
This module is intended for educational purposes only. Do not use the
|
| 9 |
+
functions in this module for real cryptographic applications. If you wish
|
| 10 |
+
to encrypt real data, we recommend using something like the `cryptography
|
| 11 |
+
<https://cryptography.io/en/latest/>`_ module.
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from string import whitespace, ascii_uppercase as uppercase, printable
|
| 16 |
+
from functools import reduce
|
| 17 |
+
import warnings
|
| 18 |
+
|
| 19 |
+
from itertools import cycle
|
| 20 |
+
|
| 21 |
+
from sympy.core import Symbol
|
| 22 |
+
from sympy.core.numbers import igcdex, mod_inverse, igcd, Rational
|
| 23 |
+
from sympy.core.random import _randrange, _randint
|
| 24 |
+
from sympy.matrices import Matrix
|
| 25 |
+
from sympy.ntheory import isprime, primitive_root, factorint
|
| 26 |
+
from sympy.ntheory import totient as _euler
|
| 27 |
+
from sympy.ntheory import reduced_totient as _carmichael
|
| 28 |
+
from sympy.ntheory.generate import nextprime
|
| 29 |
+
from sympy.ntheory.modular import crt
|
| 30 |
+
from sympy.polys.domains import FF
|
| 31 |
+
from sympy.polys.polytools import gcd, Poly
|
| 32 |
+
from sympy.utilities.misc import as_int, filldedent, translate
|
| 33 |
+
from sympy.utilities.iterables import uniq, multiset
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class NonInvertibleCipherWarning(RuntimeWarning):
|
| 37 |
+
"""A warning raised if the cipher is not invertible."""
|
| 38 |
+
def __init__(self, msg):
|
| 39 |
+
self.fullMessage = msg
|
| 40 |
+
|
| 41 |
+
def __str__(self):
|
| 42 |
+
return '\n\t' + self.fullMessage
|
| 43 |
+
|
| 44 |
+
def warn(self, stacklevel=3):
|
| 45 |
+
warnings.warn(self, stacklevel=stacklevel)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def AZ(s=None):
|
| 49 |
+
"""Return the letters of ``s`` in uppercase. In case more than
|
| 50 |
+
one string is passed, each of them will be processed and a list
|
| 51 |
+
of upper case strings will be returned.
|
| 52 |
+
|
| 53 |
+
Examples
|
| 54 |
+
========
|
| 55 |
+
|
| 56 |
+
>>> from sympy.crypto.crypto import AZ
|
| 57 |
+
>>> AZ('Hello, world!')
|
| 58 |
+
'HELLOWORLD'
|
| 59 |
+
>>> AZ('Hello, world!'.split())
|
| 60 |
+
['HELLO', 'WORLD']
|
| 61 |
+
|
| 62 |
+
See Also
|
| 63 |
+
========
|
| 64 |
+
|
| 65 |
+
check_and_join
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
if not s:
|
| 69 |
+
return uppercase
|
| 70 |
+
t = isinstance(s, str)
|
| 71 |
+
if t:
|
| 72 |
+
s = [s]
|
| 73 |
+
rv = [check_and_join(i.upper().split(), uppercase, filter=True)
|
| 74 |
+
for i in s]
|
| 75 |
+
if t:
|
| 76 |
+
return rv[0]
|
| 77 |
+
return rv
|
| 78 |
+
|
| 79 |
+
bifid5 = AZ().replace('J', '')
|
| 80 |
+
bifid6 = AZ() + '0123456789'
|
| 81 |
+
bifid10 = printable
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def padded_key(key, symbols):
|
| 85 |
+
"""Return a string of the distinct characters of ``symbols`` with
|
| 86 |
+
those of ``key`` appearing first. A ValueError is raised if
|
| 87 |
+
a) there are duplicate characters in ``symbols`` or
|
| 88 |
+
b) there are characters in ``key`` that are not in ``symbols``.
|
| 89 |
+
|
| 90 |
+
Examples
|
| 91 |
+
========
|
| 92 |
+
|
| 93 |
+
>>> from sympy.crypto.crypto import padded_key
|
| 94 |
+
>>> padded_key('PUPPY', 'OPQRSTUVWXY')
|
| 95 |
+
'PUYOQRSTVWX'
|
| 96 |
+
>>> padded_key('RSA', 'ARTIST')
|
| 97 |
+
Traceback (most recent call last):
|
| 98 |
+
...
|
| 99 |
+
ValueError: duplicate characters in symbols: T
|
| 100 |
+
|
| 101 |
+
"""
|
| 102 |
+
syms = list(uniq(symbols))
|
| 103 |
+
if len(syms) != len(symbols):
|
| 104 |
+
extra = ''.join(sorted({
|
| 105 |
+
i for i in symbols if symbols.count(i) > 1}))
|
| 106 |
+
raise ValueError('duplicate characters in symbols: %s' % extra)
|
| 107 |
+
extra = set(key) - set(syms)
|
| 108 |
+
if extra:
|
| 109 |
+
raise ValueError(
|
| 110 |
+
'characters in key but not symbols: %s' % ''.join(
|
| 111 |
+
sorted(extra)))
|
| 112 |
+
key0 = ''.join(list(uniq(key)))
|
| 113 |
+
# remove from syms characters in key0
|
| 114 |
+
return key0 + translate(''.join(syms), None, key0)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def check_and_join(phrase, symbols=None, filter=None):
|
| 118 |
+
"""
|
| 119 |
+
Joins characters of ``phrase`` and if ``symbols`` is given, raises
|
| 120 |
+
an error if any character in ``phrase`` is not in ``symbols``.
|
| 121 |
+
|
| 122 |
+
Parameters
|
| 123 |
+
==========
|
| 124 |
+
|
| 125 |
+
phrase
|
| 126 |
+
String or list of strings to be returned as a string.
|
| 127 |
+
|
| 128 |
+
symbols
|
| 129 |
+
Iterable of characters allowed in ``phrase``.
|
| 130 |
+
|
| 131 |
+
If ``symbols`` is ``None``, no checking is performed.
|
| 132 |
+
|
| 133 |
+
Examples
|
| 134 |
+
========
|
| 135 |
+
|
| 136 |
+
>>> from sympy.crypto.crypto import check_and_join
|
| 137 |
+
>>> check_and_join('a phrase')
|
| 138 |
+
'a phrase'
|
| 139 |
+
>>> check_and_join('a phrase'.upper().split())
|
| 140 |
+
'APHRASE'
|
| 141 |
+
>>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True)
|
| 142 |
+
'ARAE'
|
| 143 |
+
>>> check_and_join('a phrase!'.upper().split(), 'ARE')
|
| 144 |
+
Traceback (most recent call last):
|
| 145 |
+
...
|
| 146 |
+
ValueError: characters in phrase but not symbols: "!HPS"
|
| 147 |
+
|
| 148 |
+
"""
|
| 149 |
+
rv = ''.join(''.join(phrase))
|
| 150 |
+
if symbols is not None:
|
| 151 |
+
symbols = check_and_join(symbols)
|
| 152 |
+
missing = ''.join(sorted(set(rv) - set(symbols)))
|
| 153 |
+
if missing:
|
| 154 |
+
if not filter:
|
| 155 |
+
raise ValueError(
|
| 156 |
+
'characters in phrase but not symbols: "%s"' % missing)
|
| 157 |
+
rv = translate(rv, None, missing)
|
| 158 |
+
return rv
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _prep(msg, key, alp, default=None):
|
| 162 |
+
if not alp:
|
| 163 |
+
if not default:
|
| 164 |
+
alp = AZ()
|
| 165 |
+
msg = AZ(msg)
|
| 166 |
+
key = AZ(key)
|
| 167 |
+
else:
|
| 168 |
+
alp = default
|
| 169 |
+
else:
|
| 170 |
+
alp = ''.join(alp)
|
| 171 |
+
key = check_and_join(key, alp, filter=True)
|
| 172 |
+
msg = check_and_join(msg, alp, filter=True)
|
| 173 |
+
return msg, key, alp
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def cycle_list(k, n):
|
| 177 |
+
"""
|
| 178 |
+
Returns the elements of the list ``range(n)`` shifted to the
|
| 179 |
+
left by ``k`` (so the list starts with ``k`` (mod ``n``)).
|
| 180 |
+
|
| 181 |
+
Examples
|
| 182 |
+
========
|
| 183 |
+
|
| 184 |
+
>>> from sympy.crypto.crypto import cycle_list
|
| 185 |
+
>>> cycle_list(3, 10)
|
| 186 |
+
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
|
| 187 |
+
|
| 188 |
+
"""
|
| 189 |
+
k = k % n
|
| 190 |
+
return list(range(k, n)) + list(range(k))
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
######## shift cipher examples ############
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def encipher_shift(msg, key, symbols=None):
|
| 197 |
+
"""
|
| 198 |
+
Performs shift cipher encryption on plaintext msg, and returns the
|
| 199 |
+
ciphertext.
|
| 200 |
+
|
| 201 |
+
Parameters
|
| 202 |
+
==========
|
| 203 |
+
|
| 204 |
+
key : int
|
| 205 |
+
The secret key.
|
| 206 |
+
|
| 207 |
+
msg : str
|
| 208 |
+
Plaintext of upper-case letters.
|
| 209 |
+
|
| 210 |
+
Returns
|
| 211 |
+
=======
|
| 212 |
+
|
| 213 |
+
str
|
| 214 |
+
Ciphertext of upper-case letters.
|
| 215 |
+
|
| 216 |
+
Examples
|
| 217 |
+
========
|
| 218 |
+
|
| 219 |
+
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift
|
| 220 |
+
>>> msg = "GONAVYBEATARMY"
|
| 221 |
+
>>> ct = encipher_shift(msg, 1); ct
|
| 222 |
+
'HPOBWZCFBUBSNZ'
|
| 223 |
+
|
| 224 |
+
To decipher the shifted text, change the sign of the key:
|
| 225 |
+
|
| 226 |
+
>>> encipher_shift(ct, -1)
|
| 227 |
+
'GONAVYBEATARMY'
|
| 228 |
+
|
| 229 |
+
There is also a convenience function that does this with the
|
| 230 |
+
original key:
|
| 231 |
+
|
| 232 |
+
>>> decipher_shift(ct, 1)
|
| 233 |
+
'GONAVYBEATARMY'
|
| 234 |
+
|
| 235 |
+
Notes
|
| 236 |
+
=====
|
| 237 |
+
|
| 238 |
+
ALGORITHM:
|
| 239 |
+
|
| 240 |
+
STEPS:
|
| 241 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 242 |
+
1. Compute from the string ``msg`` a list ``L1`` of
|
| 243 |
+
corresponding integers.
|
| 244 |
+
2. Compute from the list ``L1`` a new list ``L2``, given by
|
| 245 |
+
adding ``(k mod 26)`` to each element in ``L1``.
|
| 246 |
+
3. Compute from the list ``L2`` a string ``ct`` of
|
| 247 |
+
corresponding letters.
|
| 248 |
+
|
| 249 |
+
The shift cipher is also called the Caesar cipher, after
|
| 250 |
+
Julius Caesar, who, according to Suetonius, used it with a
|
| 251 |
+
shift of three to protect messages of military significance.
|
| 252 |
+
Caesar's nephew Augustus reportedly used a similar cipher, but
|
| 253 |
+
with a right shift of 1.
|
| 254 |
+
|
| 255 |
+
References
|
| 256 |
+
==========
|
| 257 |
+
|
| 258 |
+
.. [1] https://en.wikipedia.org/wiki/Caesar_cipher
|
| 259 |
+
.. [2] https://mathworld.wolfram.com/CaesarsMethod.html
|
| 260 |
+
|
| 261 |
+
See Also
|
| 262 |
+
========
|
| 263 |
+
|
| 264 |
+
decipher_shift
|
| 265 |
+
|
| 266 |
+
"""
|
| 267 |
+
msg, _, A = _prep(msg, '', symbols)
|
| 268 |
+
shift = len(A) - key % len(A)
|
| 269 |
+
key = A[shift:] + A[:shift]
|
| 270 |
+
return translate(msg, key, A)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def decipher_shift(msg, key, symbols=None):
|
| 274 |
+
"""
|
| 275 |
+
Return the text by shifting the characters of ``msg`` to the
|
| 276 |
+
left by the amount given by ``key``.
|
| 277 |
+
|
| 278 |
+
Examples
|
| 279 |
+
========
|
| 280 |
+
|
| 281 |
+
>>> from sympy.crypto.crypto import encipher_shift, decipher_shift
|
| 282 |
+
>>> msg = "GONAVYBEATARMY"
|
| 283 |
+
>>> ct = encipher_shift(msg, 1); ct
|
| 284 |
+
'HPOBWZCFBUBSNZ'
|
| 285 |
+
|
| 286 |
+
To decipher the shifted text, change the sign of the key:
|
| 287 |
+
|
| 288 |
+
>>> encipher_shift(ct, -1)
|
| 289 |
+
'GONAVYBEATARMY'
|
| 290 |
+
|
| 291 |
+
Or use this function with the original key:
|
| 292 |
+
|
| 293 |
+
>>> decipher_shift(ct, 1)
|
| 294 |
+
'GONAVYBEATARMY'
|
| 295 |
+
|
| 296 |
+
"""
|
| 297 |
+
return encipher_shift(msg, -key, symbols)
|
| 298 |
+
|
| 299 |
+
def encipher_rot13(msg, symbols=None):
|
| 300 |
+
"""
|
| 301 |
+
Performs the ROT13 encryption on a given plaintext ``msg``.
|
| 302 |
+
|
| 303 |
+
Explanation
|
| 304 |
+
===========
|
| 305 |
+
|
| 306 |
+
ROT13 is a substitution cipher which substitutes each letter
|
| 307 |
+
in the plaintext message for the letter furthest away from it
|
| 308 |
+
in the English alphabet.
|
| 309 |
+
|
| 310 |
+
Equivalently, it is just a Caeser (shift) cipher with a shift
|
| 311 |
+
key of 13 (midway point of the alphabet).
|
| 312 |
+
|
| 313 |
+
References
|
| 314 |
+
==========
|
| 315 |
+
|
| 316 |
+
.. [1] https://en.wikipedia.org/wiki/ROT13
|
| 317 |
+
|
| 318 |
+
See Also
|
| 319 |
+
========
|
| 320 |
+
|
| 321 |
+
decipher_rot13
|
| 322 |
+
encipher_shift
|
| 323 |
+
|
| 324 |
+
"""
|
| 325 |
+
return encipher_shift(msg, 13, symbols)
|
| 326 |
+
|
| 327 |
+
def decipher_rot13(msg, symbols=None):
|
| 328 |
+
"""
|
| 329 |
+
Performs the ROT13 decryption on a given plaintext ``msg``.
|
| 330 |
+
|
| 331 |
+
Explanation
|
| 332 |
+
============
|
| 333 |
+
|
| 334 |
+
``decipher_rot13`` is equivalent to ``encipher_rot13`` as both
|
| 335 |
+
``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a
|
| 336 |
+
key of 13 will return the same results. Nonetheless,
|
| 337 |
+
``decipher_rot13`` has nonetheless been explicitly defined here for
|
| 338 |
+
consistency.
|
| 339 |
+
|
| 340 |
+
Examples
|
| 341 |
+
========
|
| 342 |
+
|
| 343 |
+
>>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13
|
| 344 |
+
>>> msg = 'GONAVYBEATARMY'
|
| 345 |
+
>>> ciphertext = encipher_rot13(msg);ciphertext
|
| 346 |
+
'TBANILORNGNEZL'
|
| 347 |
+
>>> decipher_rot13(ciphertext)
|
| 348 |
+
'GONAVYBEATARMY'
|
| 349 |
+
>>> encipher_rot13(msg) == decipher_rot13(msg)
|
| 350 |
+
True
|
| 351 |
+
>>> msg == decipher_rot13(ciphertext)
|
| 352 |
+
True
|
| 353 |
+
|
| 354 |
+
"""
|
| 355 |
+
return decipher_shift(msg, 13, symbols)
|
| 356 |
+
|
| 357 |
+
######## affine cipher examples ############
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def encipher_affine(msg, key, symbols=None, _inverse=False):
|
| 361 |
+
r"""
|
| 362 |
+
Performs the affine cipher encryption on plaintext ``msg``, and
|
| 363 |
+
returns the ciphertext.
|
| 364 |
+
|
| 365 |
+
Explanation
|
| 366 |
+
===========
|
| 367 |
+
|
| 368 |
+
Encryption is based on the map `x \rightarrow ax+b` (mod `N`)
|
| 369 |
+
where ``N`` is the number of characters in the alphabet.
|
| 370 |
+
Decryption is based on the map `x \rightarrow cx+d` (mod `N`),
|
| 371 |
+
where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
|
| 372 |
+
In particular, for the map to be invertible, we need
|
| 373 |
+
`\mathrm{gcd}(a, N) = 1` and an error will be raised if this is
|
| 374 |
+
not true.
|
| 375 |
+
|
| 376 |
+
Parameters
|
| 377 |
+
==========
|
| 378 |
+
|
| 379 |
+
msg : str
|
| 380 |
+
Characters that appear in ``symbols``.
|
| 381 |
+
|
| 382 |
+
a, b : int, int
|
| 383 |
+
A pair integers, with ``gcd(a, N) = 1`` (the secret key).
|
| 384 |
+
|
| 385 |
+
symbols
|
| 386 |
+
String of characters (default = uppercase letters).
|
| 387 |
+
|
| 388 |
+
When no symbols are given, ``msg`` is converted to upper case
|
| 389 |
+
letters and all other characters are ignored.
|
| 390 |
+
|
| 391 |
+
Returns
|
| 392 |
+
=======
|
| 393 |
+
|
| 394 |
+
ct
|
| 395 |
+
String of characters (the ciphertext message)
|
| 396 |
+
|
| 397 |
+
Notes
|
| 398 |
+
=====
|
| 399 |
+
|
| 400 |
+
ALGORITHM:
|
| 401 |
+
|
| 402 |
+
STEPS:
|
| 403 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 404 |
+
1. Compute from the string ``msg`` a list ``L1`` of
|
| 405 |
+
corresponding integers.
|
| 406 |
+
2. Compute from the list ``L1`` a new list ``L2``, given by
|
| 407 |
+
replacing ``x`` by ``a*x + b (mod N)``, for each element
|
| 408 |
+
``x`` in ``L1``.
|
| 409 |
+
3. Compute from the list ``L2`` a string ``ct`` of
|
| 410 |
+
corresponding letters.
|
| 411 |
+
|
| 412 |
+
This is a straightforward generalization of the shift cipher with
|
| 413 |
+
the added complexity of requiring 2 characters to be deciphered in
|
| 414 |
+
order to recover the key.
|
| 415 |
+
|
| 416 |
+
References
|
| 417 |
+
==========
|
| 418 |
+
|
| 419 |
+
.. [1] https://en.wikipedia.org/wiki/Affine_cipher
|
| 420 |
+
|
| 421 |
+
See Also
|
| 422 |
+
========
|
| 423 |
+
|
| 424 |
+
decipher_affine
|
| 425 |
+
|
| 426 |
+
"""
|
| 427 |
+
msg, _, A = _prep(msg, '', symbols)
|
| 428 |
+
N = len(A)
|
| 429 |
+
a, b = key
|
| 430 |
+
assert gcd(a, N) == 1
|
| 431 |
+
if _inverse:
|
| 432 |
+
c = mod_inverse(a, N)
|
| 433 |
+
d = -b*c
|
| 434 |
+
a, b = c, d
|
| 435 |
+
B = ''.join([A[(a*i + b) % N] for i in range(N)])
|
| 436 |
+
return translate(msg, A, B)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def decipher_affine(msg, key, symbols=None):
|
| 440 |
+
r"""
|
| 441 |
+
Return the deciphered text that was made from the mapping,
|
| 442 |
+
`x \rightarrow ax+b` (mod `N`), where ``N`` is the
|
| 443 |
+
number of characters in the alphabet. Deciphering is done by
|
| 444 |
+
reciphering with a new key: `x \rightarrow cx+d` (mod `N`),
|
| 445 |
+
where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`).
|
| 446 |
+
|
| 447 |
+
Examples
|
| 448 |
+
========
|
| 449 |
+
|
| 450 |
+
>>> from sympy.crypto.crypto import encipher_affine, decipher_affine
|
| 451 |
+
>>> msg = "GO NAVY BEAT ARMY"
|
| 452 |
+
>>> key = (3, 1)
|
| 453 |
+
>>> encipher_affine(msg, key)
|
| 454 |
+
'TROBMVENBGBALV'
|
| 455 |
+
>>> decipher_affine(_, key)
|
| 456 |
+
'GONAVYBEATARMY'
|
| 457 |
+
|
| 458 |
+
See Also
|
| 459 |
+
========
|
| 460 |
+
|
| 461 |
+
encipher_affine
|
| 462 |
+
|
| 463 |
+
"""
|
| 464 |
+
return encipher_affine(msg, key, symbols, _inverse=True)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def encipher_atbash(msg, symbols=None):
|
| 468 |
+
r"""
|
| 469 |
+
Enciphers a given ``msg`` into its Atbash ciphertext and returns it.
|
| 470 |
+
|
| 471 |
+
Explanation
|
| 472 |
+
===========
|
| 473 |
+
|
| 474 |
+
Atbash is a substitution cipher originally used to encrypt the Hebrew
|
| 475 |
+
alphabet. Atbash works on the principle of mapping each alphabet to its
|
| 476 |
+
reverse / counterpart (i.e. a would map to z, b to y etc.)
|
| 477 |
+
|
| 478 |
+
Atbash is functionally equivalent to the affine cipher with ``a = 25``
|
| 479 |
+
and ``b = 25``
|
| 480 |
+
|
| 481 |
+
See Also
|
| 482 |
+
========
|
| 483 |
+
|
| 484 |
+
decipher_atbash
|
| 485 |
+
|
| 486 |
+
"""
|
| 487 |
+
return encipher_affine(msg, (25, 25), symbols)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def decipher_atbash(msg, symbols=None):
|
| 491 |
+
r"""
|
| 492 |
+
Deciphers a given ``msg`` using Atbash cipher and returns it.
|
| 493 |
+
|
| 494 |
+
Explanation
|
| 495 |
+
===========
|
| 496 |
+
|
| 497 |
+
``decipher_atbash`` is functionally equivalent to ``encipher_atbash``.
|
| 498 |
+
However, it has still been added as a separate function to maintain
|
| 499 |
+
consistency.
|
| 500 |
+
|
| 501 |
+
Examples
|
| 502 |
+
========
|
| 503 |
+
|
| 504 |
+
>>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash
|
| 505 |
+
>>> msg = 'GONAVYBEATARMY'
|
| 506 |
+
>>> encipher_atbash(msg)
|
| 507 |
+
'TLMZEBYVZGZINB'
|
| 508 |
+
>>> decipher_atbash(msg)
|
| 509 |
+
'TLMZEBYVZGZINB'
|
| 510 |
+
>>> encipher_atbash(msg) == decipher_atbash(msg)
|
| 511 |
+
True
|
| 512 |
+
>>> msg == encipher_atbash(encipher_atbash(msg))
|
| 513 |
+
True
|
| 514 |
+
|
| 515 |
+
References
|
| 516 |
+
==========
|
| 517 |
+
|
| 518 |
+
.. [1] https://en.wikipedia.org/wiki/Atbash
|
| 519 |
+
|
| 520 |
+
See Also
|
| 521 |
+
========
|
| 522 |
+
|
| 523 |
+
encipher_atbash
|
| 524 |
+
|
| 525 |
+
"""
|
| 526 |
+
return decipher_affine(msg, (25, 25), symbols)
|
| 527 |
+
|
| 528 |
+
#################### substitution cipher ###########################
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def encipher_substitution(msg, old, new=None):
|
| 532 |
+
r"""
|
| 533 |
+
Returns the ciphertext obtained by replacing each character that
|
| 534 |
+
appears in ``old`` with the corresponding character in ``new``.
|
| 535 |
+
If ``old`` is a mapping, then new is ignored and the replacements
|
| 536 |
+
defined by ``old`` are used.
|
| 537 |
+
|
| 538 |
+
Explanation
|
| 539 |
+
===========
|
| 540 |
+
|
| 541 |
+
This is a more general than the affine cipher in that the key can
|
| 542 |
+
only be recovered by determining the mapping for each symbol.
|
| 543 |
+
Though in practice, once a few symbols are recognized the mappings
|
| 544 |
+
for other characters can be quickly guessed.
|
| 545 |
+
|
| 546 |
+
Examples
|
| 547 |
+
========
|
| 548 |
+
|
| 549 |
+
>>> from sympy.crypto.crypto import encipher_substitution, AZ
|
| 550 |
+
>>> old = 'OEYAG'
|
| 551 |
+
>>> new = '034^6'
|
| 552 |
+
>>> msg = AZ("go navy! beat army!")
|
| 553 |
+
>>> ct = encipher_substitution(msg, old, new); ct
|
| 554 |
+
'60N^V4B3^T^RM4'
|
| 555 |
+
|
| 556 |
+
To decrypt a substitution, reverse the last two arguments:
|
| 557 |
+
|
| 558 |
+
>>> encipher_substitution(ct, new, old)
|
| 559 |
+
'GONAVYBEATARMY'
|
| 560 |
+
|
| 561 |
+
In the special case where ``old`` and ``new`` are a permutation of
|
| 562 |
+
order 2 (representing a transposition of characters) their order
|
| 563 |
+
is immaterial:
|
| 564 |
+
|
| 565 |
+
>>> old = 'NAVY'
|
| 566 |
+
>>> new = 'ANYV'
|
| 567 |
+
>>> encipher = lambda x: encipher_substitution(x, old, new)
|
| 568 |
+
>>> encipher('NAVY')
|
| 569 |
+
'ANYV'
|
| 570 |
+
>>> encipher(_)
|
| 571 |
+
'NAVY'
|
| 572 |
+
|
| 573 |
+
The substitution cipher, in general, is a method
|
| 574 |
+
whereby "units" (not necessarily single characters) of plaintext
|
| 575 |
+
are replaced with ciphertext according to a regular system.
|
| 576 |
+
|
| 577 |
+
>>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc']))
|
| 578 |
+
>>> print(encipher_substitution('abc', ords))
|
| 579 |
+
\97\98\99
|
| 580 |
+
|
| 581 |
+
References
|
| 582 |
+
==========
|
| 583 |
+
|
| 584 |
+
.. [1] https://en.wikipedia.org/wiki/Substitution_cipher
|
| 585 |
+
|
| 586 |
+
"""
|
| 587 |
+
return translate(msg, old, new)
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
######################################################################
|
| 591 |
+
#################### Vigenere cipher examples ########################
|
| 592 |
+
######################################################################
|
| 593 |
+
|
| 594 |
+
def encipher_vigenere(msg, key, symbols=None):
|
| 595 |
+
"""
|
| 596 |
+
Performs the Vigenere cipher encryption on plaintext ``msg``, and
|
| 597 |
+
returns the ciphertext.
|
| 598 |
+
|
| 599 |
+
Examples
|
| 600 |
+
========
|
| 601 |
+
|
| 602 |
+
>>> from sympy.crypto.crypto import encipher_vigenere, AZ
|
| 603 |
+
>>> key = "encrypt"
|
| 604 |
+
>>> msg = "meet me on monday"
|
| 605 |
+
>>> encipher_vigenere(msg, key)
|
| 606 |
+
'QRGKKTHRZQEBPR'
|
| 607 |
+
|
| 608 |
+
Section 1 of the Kryptos sculpture at the CIA headquarters
|
| 609 |
+
uses this cipher and also changes the order of the
|
| 610 |
+
alphabet [2]_. Here is the first line of that section of
|
| 611 |
+
the sculpture:
|
| 612 |
+
|
| 613 |
+
>>> from sympy.crypto.crypto import decipher_vigenere, padded_key
|
| 614 |
+
>>> alp = padded_key('KRYPTOS', AZ())
|
| 615 |
+
>>> key = 'PALIMPSEST'
|
| 616 |
+
>>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ'
|
| 617 |
+
>>> decipher_vigenere(msg, key, alp)
|
| 618 |
+
'BETWEENSUBTLESHADINGANDTHEABSENC'
|
| 619 |
+
|
| 620 |
+
Explanation
|
| 621 |
+
===========
|
| 622 |
+
|
| 623 |
+
The Vigenere cipher is named after Blaise de Vigenere, a sixteenth
|
| 624 |
+
century diplomat and cryptographer, by a historical accident.
|
| 625 |
+
Vigenere actually invented a different and more complicated cipher.
|
| 626 |
+
The so-called *Vigenere cipher* was actually invented
|
| 627 |
+
by Giovan Batista Belaso in 1553.
|
| 628 |
+
|
| 629 |
+
This cipher was used in the 1800's, for example, during the American
|
| 630 |
+
Civil War. The Confederacy used a brass cipher disk to implement the
|
| 631 |
+
Vigenere cipher (now on display in the NSA Museum in Fort
|
| 632 |
+
Meade) [1]_.
|
| 633 |
+
|
| 634 |
+
The Vigenere cipher is a generalization of the shift cipher.
|
| 635 |
+
Whereas the shift cipher shifts each letter by the same amount
|
| 636 |
+
(that amount being the key of the shift cipher) the Vigenere
|
| 637 |
+
cipher shifts a letter by an amount determined by the key (which is
|
| 638 |
+
a word or phrase known only to the sender and receiver).
|
| 639 |
+
|
| 640 |
+
For example, if the key was a single letter, such as "C", then the
|
| 641 |
+
so-called Vigenere cipher is actually a shift cipher with a
|
| 642 |
+
shift of `2` (since "C" is the 2nd letter of the alphabet, if
|
| 643 |
+
you start counting at `0`). If the key was a word with two
|
| 644 |
+
letters, such as "CA", then the so-called Vigenere cipher will
|
| 645 |
+
shift letters in even positions by `2` and letters in odd positions
|
| 646 |
+
are left alone (shifted by `0`, since "A" is the 0th letter, if
|
| 647 |
+
you start counting at `0`).
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
ALGORITHM:
|
| 651 |
+
|
| 652 |
+
INPUT:
|
| 653 |
+
|
| 654 |
+
``msg``: string of characters that appear in ``symbols``
|
| 655 |
+
(the plaintext)
|
| 656 |
+
|
| 657 |
+
``key``: a string of characters that appear in ``symbols``
|
| 658 |
+
(the secret key)
|
| 659 |
+
|
| 660 |
+
``symbols``: a string of letters defining the alphabet
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
OUTPUT:
|
| 664 |
+
|
| 665 |
+
``ct``: string of characters (the ciphertext message)
|
| 666 |
+
|
| 667 |
+
STEPS:
|
| 668 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 669 |
+
1. Compute from the string ``key`` a list ``L1`` of
|
| 670 |
+
corresponding integers. Let ``n1 = len(L1)``.
|
| 671 |
+
2. Compute from the string ``msg`` a list ``L2`` of
|
| 672 |
+
corresponding integers. Let ``n2 = len(L2)``.
|
| 673 |
+
3. Break ``L2`` up sequentially into sublists of size
|
| 674 |
+
``n1``; the last sublist may be smaller than ``n1``
|
| 675 |
+
4. For each of these sublists ``L`` of ``L2``, compute a
|
| 676 |
+
new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)``
|
| 677 |
+
to the ``i``-th element in the sublist, for each ``i``.
|
| 678 |
+
5. Assemble these lists ``C`` by concatenation into a new
|
| 679 |
+
list of length ``n2``.
|
| 680 |
+
6. Compute from the new list a string ``ct`` of
|
| 681 |
+
corresponding letters.
|
| 682 |
+
|
| 683 |
+
Once it is known that the key is, say, `n` characters long,
|
| 684 |
+
frequency analysis can be applied to every `n`-th letter of
|
| 685 |
+
the ciphertext to determine the plaintext. This method is
|
| 686 |
+
called *Kasiski examination* (although it was first discovered
|
| 687 |
+
by Babbage). If they key is as long as the message and is
|
| 688 |
+
comprised of randomly selected characters -- a one-time pad -- the
|
| 689 |
+
message is theoretically unbreakable.
|
| 690 |
+
|
| 691 |
+
The cipher Vigenere actually discovered is an "auto-key" cipher
|
| 692 |
+
described as follows.
|
| 693 |
+
|
| 694 |
+
ALGORITHM:
|
| 695 |
+
|
| 696 |
+
INPUT:
|
| 697 |
+
|
| 698 |
+
``key``: a string of letters (the secret key)
|
| 699 |
+
|
| 700 |
+
``msg``: string of letters (the plaintext message)
|
| 701 |
+
|
| 702 |
+
OUTPUT:
|
| 703 |
+
|
| 704 |
+
``ct``: string of upper-case letters (the ciphertext message)
|
| 705 |
+
|
| 706 |
+
STEPS:
|
| 707 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 708 |
+
1. Compute from the string ``msg`` a list ``L2`` of
|
| 709 |
+
corresponding integers. Let ``n2 = len(L2)``.
|
| 710 |
+
2. Let ``n1`` be the length of the key. Append to the
|
| 711 |
+
string ``key`` the first ``n2 - n1`` characters of
|
| 712 |
+
the plaintext message. Compute from this string (also of
|
| 713 |
+
length ``n2``) a list ``L1`` of integers corresponding
|
| 714 |
+
to the letter numbers in the first step.
|
| 715 |
+
3. Compute a new list ``C`` given by
|
| 716 |
+
``C[i] = L1[i] + L2[i] (mod N)``.
|
| 717 |
+
4. Compute from the new list a string ``ct`` of letters
|
| 718 |
+
corresponding to the new integers.
|
| 719 |
+
|
| 720 |
+
To decipher the auto-key ciphertext, the key is used to decipher
|
| 721 |
+
the first ``n1`` characters and then those characters become the
|
| 722 |
+
key to decipher the next ``n1`` characters, etc...:
|
| 723 |
+
|
| 724 |
+
>>> m = AZ('go navy, beat army! yes you can'); m
|
| 725 |
+
'GONAVYBEATARMYYESYOUCAN'
|
| 726 |
+
>>> key = AZ('gold bug'); n1 = len(key); n2 = len(m)
|
| 727 |
+
>>> auto_key = key + m[:n2 - n1]; auto_key
|
| 728 |
+
'GOLDBUGGONAVYBEATARMYYE'
|
| 729 |
+
>>> ct = encipher_vigenere(m, auto_key); ct
|
| 730 |
+
'MCYDWSHKOGAMKZCELYFGAYR'
|
| 731 |
+
>>> n1 = len(key)
|
| 732 |
+
>>> pt = []
|
| 733 |
+
>>> while ct:
|
| 734 |
+
... part, ct = ct[:n1], ct[n1:]
|
| 735 |
+
... pt.append(decipher_vigenere(part, key))
|
| 736 |
+
... key = pt[-1]
|
| 737 |
+
...
|
| 738 |
+
>>> ''.join(pt) == m
|
| 739 |
+
True
|
| 740 |
+
|
| 741 |
+
References
|
| 742 |
+
==========
|
| 743 |
+
|
| 744 |
+
.. [1] https://en.wikipedia.org/wiki/Vigenere_cipher
|
| 745 |
+
.. [2] https://web.archive.org/web/20071116100808/https://filebox.vt.edu/users/batman/kryptos.html
|
| 746 |
+
(short URL: https://goo.gl/ijr22d)
|
| 747 |
+
|
| 748 |
+
"""
|
| 749 |
+
msg, key, A = _prep(msg, key, symbols)
|
| 750 |
+
map = {c: i for i, c in enumerate(A)}
|
| 751 |
+
key = [map[c] for c in key]
|
| 752 |
+
N = len(map)
|
| 753 |
+
k = len(key)
|
| 754 |
+
rv = []
|
| 755 |
+
for i, m in enumerate(msg):
|
| 756 |
+
rv.append(A[(map[m] + key[i % k]) % N])
|
| 757 |
+
rv = ''.join(rv)
|
| 758 |
+
return rv
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
def decipher_vigenere(msg, key, symbols=None):
|
| 762 |
+
"""
|
| 763 |
+
Decode using the Vigenere cipher.
|
| 764 |
+
|
| 765 |
+
Examples
|
| 766 |
+
========
|
| 767 |
+
|
| 768 |
+
>>> from sympy.crypto.crypto import decipher_vigenere
|
| 769 |
+
>>> key = "encrypt"
|
| 770 |
+
>>> ct = "QRGK kt HRZQE BPR"
|
| 771 |
+
>>> decipher_vigenere(ct, key)
|
| 772 |
+
'MEETMEONMONDAY'
|
| 773 |
+
|
| 774 |
+
"""
|
| 775 |
+
msg, key, A = _prep(msg, key, symbols)
|
| 776 |
+
map = {c: i for i, c in enumerate(A)}
|
| 777 |
+
N = len(A) # normally, 26
|
| 778 |
+
K = [map[c] for c in key]
|
| 779 |
+
n = len(K)
|
| 780 |
+
C = [map[c] for c in msg]
|
| 781 |
+
rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)])
|
| 782 |
+
return rv
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
#################### Hill cipher ########################
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
def encipher_hill(msg, key, symbols=None, pad="Q"):
|
| 789 |
+
r"""
|
| 790 |
+
Return the Hill cipher encryption of ``msg``.
|
| 791 |
+
|
| 792 |
+
Explanation
|
| 793 |
+
===========
|
| 794 |
+
|
| 795 |
+
The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_,
|
| 796 |
+
was the first polygraphic cipher in which it was practical
|
| 797 |
+
(though barely) to operate on more than three symbols at once.
|
| 798 |
+
The following discussion assumes an elementary knowledge of
|
| 799 |
+
matrices.
|
| 800 |
+
|
| 801 |
+
First, each letter is first encoded as a number starting with 0.
|
| 802 |
+
Suppose your message `msg` consists of `n` capital letters, with no
|
| 803 |
+
spaces. This may be regarded an `n`-tuple M of elements of
|
| 804 |
+
`Z_{26}` (if the letters are those of the English alphabet). A key
|
| 805 |
+
in the Hill cipher is a `k x k` matrix `K`, all of whose entries
|
| 806 |
+
are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the
|
| 807 |
+
linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k`
|
| 808 |
+
is one-to-one).
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
Parameters
|
| 812 |
+
==========
|
| 813 |
+
|
| 814 |
+
msg
|
| 815 |
+
Plaintext message of `n` upper-case letters.
|
| 816 |
+
|
| 817 |
+
key
|
| 818 |
+
A `k \times k` invertible matrix `K`, all of whose entries are
|
| 819 |
+
in `Z_{26}` (or whatever number of symbols are being used).
|
| 820 |
+
|
| 821 |
+
pad
|
| 822 |
+
Character (default "Q") to use to make length of text be a
|
| 823 |
+
multiple of ``k``.
|
| 824 |
+
|
| 825 |
+
Returns
|
| 826 |
+
=======
|
| 827 |
+
|
| 828 |
+
ct
|
| 829 |
+
Ciphertext of upper-case letters.
|
| 830 |
+
|
| 831 |
+
Notes
|
| 832 |
+
=====
|
| 833 |
+
|
| 834 |
+
ALGORITHM:
|
| 835 |
+
|
| 836 |
+
STEPS:
|
| 837 |
+
0. Number the letters of the alphabet from 0, ..., N
|
| 838 |
+
1. Compute from the string ``msg`` a list ``L`` of
|
| 839 |
+
corresponding integers. Let ``n = len(L)``.
|
| 840 |
+
2. Break the list ``L`` up into ``t = ceiling(n/k)``
|
| 841 |
+
sublists ``L_1``, ..., ``L_t`` of size ``k`` (with
|
| 842 |
+
the last list "padded" to ensure its size is
|
| 843 |
+
``k``).
|
| 844 |
+
3. Compute new list ``C_1``, ..., ``C_t`` given by
|
| 845 |
+
``C[i] = K*L_i`` (arithmetic is done mod N), for each
|
| 846 |
+
``i``.
|
| 847 |
+
4. Concatenate these into a list ``C = C_1 + ... + C_t``.
|
| 848 |
+
5. Compute from ``C`` a string ``ct`` of corresponding
|
| 849 |
+
letters. This has length ``k*t``.
|
| 850 |
+
|
| 851 |
+
References
|
| 852 |
+
==========
|
| 853 |
+
|
| 854 |
+
.. [1] https://en.wikipedia.org/wiki/Hill_cipher
|
| 855 |
+
.. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet,
|
| 856 |
+
The American Mathematical Monthly Vol.36, June-July 1929,
|
| 857 |
+
pp.306-312.
|
| 858 |
+
|
| 859 |
+
See Also
|
| 860 |
+
========
|
| 861 |
+
|
| 862 |
+
decipher_hill
|
| 863 |
+
|
| 864 |
+
"""
|
| 865 |
+
assert key.is_square
|
| 866 |
+
assert len(pad) == 1
|
| 867 |
+
msg, pad, A = _prep(msg, pad, symbols)
|
| 868 |
+
map = {c: i for i, c in enumerate(A)}
|
| 869 |
+
P = [map[c] for c in msg]
|
| 870 |
+
N = len(A)
|
| 871 |
+
k = key.cols
|
| 872 |
+
n = len(P)
|
| 873 |
+
m, r = divmod(n, k)
|
| 874 |
+
if r:
|
| 875 |
+
P = P + [map[pad]]*(k - r)
|
| 876 |
+
m += 1
|
| 877 |
+
rv = ''.join([A[c % N] for j in range(m) for c in
|
| 878 |
+
list(key*Matrix(k, 1, [P[i]
|
| 879 |
+
for i in range(k*j, k*(j + 1))]))])
|
| 880 |
+
return rv
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def decipher_hill(msg, key, symbols=None):
|
| 884 |
+
"""
|
| 885 |
+
Deciphering is the same as enciphering but using the inverse of the
|
| 886 |
+
key matrix.
|
| 887 |
+
|
| 888 |
+
Examples
|
| 889 |
+
========
|
| 890 |
+
|
| 891 |
+
>>> from sympy.crypto.crypto import encipher_hill, decipher_hill
|
| 892 |
+
>>> from sympy import Matrix
|
| 893 |
+
|
| 894 |
+
>>> key = Matrix([[1, 2], [3, 5]])
|
| 895 |
+
>>> encipher_hill("meet me on monday", key)
|
| 896 |
+
'UEQDUEODOCTCWQ'
|
| 897 |
+
>>> decipher_hill(_, key)
|
| 898 |
+
'MEETMEONMONDAY'
|
| 899 |
+
|
| 900 |
+
When the length of the plaintext (stripped of invalid characters)
|
| 901 |
+
is not a multiple of the key dimension, extra characters will
|
| 902 |
+
appear at the end of the enciphered and deciphered text. In order to
|
| 903 |
+
decipher the text, those characters must be included in the text to
|
| 904 |
+
be deciphered. In the following, the key has a dimension of 4 but
|
| 905 |
+
the text is 2 short of being a multiple of 4 so two characters will
|
| 906 |
+
be added.
|
| 907 |
+
|
| 908 |
+
>>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0],
|
| 909 |
+
... [2, 2, 3, 4], [1, 1, 0, 1]])
|
| 910 |
+
>>> msg = "ST"
|
| 911 |
+
>>> encipher_hill(msg, key)
|
| 912 |
+
'HJEB'
|
| 913 |
+
>>> decipher_hill(_, key)
|
| 914 |
+
'STQQ'
|
| 915 |
+
>>> encipher_hill(msg, key, pad="Z")
|
| 916 |
+
'ISPK'
|
| 917 |
+
>>> decipher_hill(_, key)
|
| 918 |
+
'STZZ'
|
| 919 |
+
|
| 920 |
+
If the last two characters of the ciphertext were ignored in
|
| 921 |
+
either case, the wrong plaintext would be recovered:
|
| 922 |
+
|
| 923 |
+
>>> decipher_hill("HD", key)
|
| 924 |
+
'ORMV'
|
| 925 |
+
>>> decipher_hill("IS", key)
|
| 926 |
+
'UIKY'
|
| 927 |
+
|
| 928 |
+
See Also
|
| 929 |
+
========
|
| 930 |
+
|
| 931 |
+
encipher_hill
|
| 932 |
+
|
| 933 |
+
"""
|
| 934 |
+
assert key.is_square
|
| 935 |
+
msg, _, A = _prep(msg, '', symbols)
|
| 936 |
+
map = {c: i for i, c in enumerate(A)}
|
| 937 |
+
C = [map[c] for c in msg]
|
| 938 |
+
N = len(A)
|
| 939 |
+
k = key.cols
|
| 940 |
+
n = len(C)
|
| 941 |
+
m, r = divmod(n, k)
|
| 942 |
+
if r:
|
| 943 |
+
C = C + [0]*(k - r)
|
| 944 |
+
m += 1
|
| 945 |
+
key_inv = key.inv_mod(N)
|
| 946 |
+
rv = ''.join([A[p % N] for j in range(m) for p in
|
| 947 |
+
list(key_inv*Matrix(
|
| 948 |
+
k, 1, [C[i] for i in range(k*j, k*(j + 1))]))])
|
| 949 |
+
return rv
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
#################### Bifid cipher ########################
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
def encipher_bifid(msg, key, symbols=None):
|
| 956 |
+
r"""
|
| 957 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
| 958 |
+
returns the ciphertext.
|
| 959 |
+
|
| 960 |
+
This is the version of the Bifid cipher that uses an `n \times n`
|
| 961 |
+
Polybius square.
|
| 962 |
+
|
| 963 |
+
Parameters
|
| 964 |
+
==========
|
| 965 |
+
|
| 966 |
+
msg
|
| 967 |
+
Plaintext string.
|
| 968 |
+
|
| 969 |
+
key
|
| 970 |
+
Short string for key.
|
| 971 |
+
|
| 972 |
+
Duplicate characters are ignored and then it is padded with the
|
| 973 |
+
characters in ``symbols`` that were not in the short key.
|
| 974 |
+
|
| 975 |
+
symbols
|
| 976 |
+
`n \times n` characters defining the alphabet.
|
| 977 |
+
|
| 978 |
+
(default is string.printable)
|
| 979 |
+
|
| 980 |
+
Returns
|
| 981 |
+
=======
|
| 982 |
+
|
| 983 |
+
ciphertext
|
| 984 |
+
Ciphertext using Bifid5 cipher without spaces.
|
| 985 |
+
|
| 986 |
+
See Also
|
| 987 |
+
========
|
| 988 |
+
|
| 989 |
+
decipher_bifid, encipher_bifid5, encipher_bifid6
|
| 990 |
+
|
| 991 |
+
References
|
| 992 |
+
==========
|
| 993 |
+
|
| 994 |
+
.. [1] https://en.wikipedia.org/wiki/Bifid_cipher
|
| 995 |
+
|
| 996 |
+
"""
|
| 997 |
+
msg, key, A = _prep(msg, key, symbols, bifid10)
|
| 998 |
+
long_key = ''.join(uniq(key)) or A
|
| 999 |
+
|
| 1000 |
+
n = len(A)**.5
|
| 1001 |
+
if n != int(n):
|
| 1002 |
+
raise ValueError(
|
| 1003 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
| 1004 |
+
N = int(n)
|
| 1005 |
+
if len(long_key) < N**2:
|
| 1006 |
+
long_key = list(long_key) + [x for x in A if x not in long_key]
|
| 1007 |
+
|
| 1008 |
+
# the fractionalization
|
| 1009 |
+
row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)}
|
| 1010 |
+
r, c = zip(*[row_col[x] for x in msg])
|
| 1011 |
+
rc = r + c
|
| 1012 |
+
ch = {i: ch for ch, i in row_col.items()}
|
| 1013 |
+
rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2]))
|
| 1014 |
+
return rv
|
| 1015 |
+
|
| 1016 |
+
|
| 1017 |
+
def decipher_bifid(msg, key, symbols=None):
|
| 1018 |
+
r"""
|
| 1019 |
+
Performs the Bifid cipher decryption on ciphertext ``msg``, and
|
| 1020 |
+
returns the plaintext.
|
| 1021 |
+
|
| 1022 |
+
This is the version of the Bifid cipher that uses the `n \times n`
|
| 1023 |
+
Polybius square.
|
| 1024 |
+
|
| 1025 |
+
Parameters
|
| 1026 |
+
==========
|
| 1027 |
+
|
| 1028 |
+
msg
|
| 1029 |
+
Ciphertext string.
|
| 1030 |
+
|
| 1031 |
+
key
|
| 1032 |
+
Short string for key.
|
| 1033 |
+
|
| 1034 |
+
Duplicate characters are ignored and then it is padded with the
|
| 1035 |
+
characters in symbols that were not in the short key.
|
| 1036 |
+
|
| 1037 |
+
symbols
|
| 1038 |
+
`n \times n` characters defining the alphabet.
|
| 1039 |
+
|
| 1040 |
+
(default=string.printable, a `10 \times 10` matrix)
|
| 1041 |
+
|
| 1042 |
+
Returns
|
| 1043 |
+
=======
|
| 1044 |
+
|
| 1045 |
+
deciphered
|
| 1046 |
+
Deciphered text.
|
| 1047 |
+
|
| 1048 |
+
Examples
|
| 1049 |
+
========
|
| 1050 |
+
|
| 1051 |
+
>>> from sympy.crypto.crypto import (
|
| 1052 |
+
... encipher_bifid, decipher_bifid, AZ)
|
| 1053 |
+
|
| 1054 |
+
Do an encryption using the bifid5 alphabet:
|
| 1055 |
+
|
| 1056 |
+
>>> alp = AZ().replace('J', '')
|
| 1057 |
+
>>> ct = AZ("meet me on monday!")
|
| 1058 |
+
>>> key = AZ("gold bug")
|
| 1059 |
+
>>> encipher_bifid(ct, key, alp)
|
| 1060 |
+
'IEILHHFSTSFQYE'
|
| 1061 |
+
|
| 1062 |
+
When entering the text or ciphertext, spaces are ignored so it
|
| 1063 |
+
can be formatted as desired. Re-entering the ciphertext from the
|
| 1064 |
+
preceding, putting 4 characters per line and padding with an extra
|
| 1065 |
+
J, does not cause problems for the deciphering:
|
| 1066 |
+
|
| 1067 |
+
>>> decipher_bifid('''
|
| 1068 |
+
... IEILH
|
| 1069 |
+
... HFSTS
|
| 1070 |
+
... FQYEJ''', key, alp)
|
| 1071 |
+
'MEETMEONMONDAY'
|
| 1072 |
+
|
| 1073 |
+
When no alphabet is given, all 100 printable characters will be
|
| 1074 |
+
used:
|
| 1075 |
+
|
| 1076 |
+
>>> key = ''
|
| 1077 |
+
>>> encipher_bifid('hello world!', key)
|
| 1078 |
+
'bmtwmg-bIo*w'
|
| 1079 |
+
>>> decipher_bifid(_, key)
|
| 1080 |
+
'hello world!'
|
| 1081 |
+
|
| 1082 |
+
If the key is changed, a different encryption is obtained:
|
| 1083 |
+
|
| 1084 |
+
>>> key = 'gold bug'
|
| 1085 |
+
>>> encipher_bifid('hello world!', 'gold_bug')
|
| 1086 |
+
'hg2sfuei7t}w'
|
| 1087 |
+
|
| 1088 |
+
And if the key used to decrypt the message is not exact, the
|
| 1089 |
+
original text will not be perfectly obtained:
|
| 1090 |
+
|
| 1091 |
+
>>> decipher_bifid(_, 'gold pug')
|
| 1092 |
+
'heldo~wor6d!'
|
| 1093 |
+
|
| 1094 |
+
"""
|
| 1095 |
+
msg, _, A = _prep(msg, '', symbols, bifid10)
|
| 1096 |
+
long_key = ''.join(uniq(key)) or A
|
| 1097 |
+
|
| 1098 |
+
n = len(A)**.5
|
| 1099 |
+
if n != int(n):
|
| 1100 |
+
raise ValueError(
|
| 1101 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
| 1102 |
+
N = int(n)
|
| 1103 |
+
if len(long_key) < N**2:
|
| 1104 |
+
long_key = list(long_key) + [x for x in A if x not in long_key]
|
| 1105 |
+
|
| 1106 |
+
# the reverse fractionalization
|
| 1107 |
+
row_col = {
|
| 1108 |
+
ch: divmod(i, N) for i, ch in enumerate(long_key)}
|
| 1109 |
+
rc = [i for c in msg for i in row_col[c]]
|
| 1110 |
+
n = len(msg)
|
| 1111 |
+
rc = zip(*(rc[:n], rc[n:]))
|
| 1112 |
+
ch = {i: ch for ch, i in row_col.items()}
|
| 1113 |
+
rv = ''.join(ch[i] for i in rc)
|
| 1114 |
+
return rv
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
def bifid_square(key):
|
| 1118 |
+
"""Return characters of ``key`` arranged in a square.
|
| 1119 |
+
|
| 1120 |
+
Examples
|
| 1121 |
+
========
|
| 1122 |
+
|
| 1123 |
+
>>> from sympy.crypto.crypto import (
|
| 1124 |
+
... bifid_square, AZ, padded_key, bifid5)
|
| 1125 |
+
>>> bifid_square(AZ().replace('J', ''))
|
| 1126 |
+
Matrix([
|
| 1127 |
+
[A, B, C, D, E],
|
| 1128 |
+
[F, G, H, I, K],
|
| 1129 |
+
[L, M, N, O, P],
|
| 1130 |
+
[Q, R, S, T, U],
|
| 1131 |
+
[V, W, X, Y, Z]])
|
| 1132 |
+
|
| 1133 |
+
>>> bifid_square(padded_key(AZ('gold bug!'), bifid5))
|
| 1134 |
+
Matrix([
|
| 1135 |
+
[G, O, L, D, B],
|
| 1136 |
+
[U, A, C, E, F],
|
| 1137 |
+
[H, I, K, M, N],
|
| 1138 |
+
[P, Q, R, S, T],
|
| 1139 |
+
[V, W, X, Y, Z]])
|
| 1140 |
+
|
| 1141 |
+
See Also
|
| 1142 |
+
========
|
| 1143 |
+
|
| 1144 |
+
padded_key
|
| 1145 |
+
|
| 1146 |
+
"""
|
| 1147 |
+
A = ''.join(uniq(''.join(key)))
|
| 1148 |
+
n = len(A)**.5
|
| 1149 |
+
if n != int(n):
|
| 1150 |
+
raise ValueError(
|
| 1151 |
+
'Length of alphabet (%s) is not a square number.' % len(A))
|
| 1152 |
+
n = int(n)
|
| 1153 |
+
f = lambda i, j: Symbol(A[n*i + j])
|
| 1154 |
+
rv = Matrix(n, n, f)
|
| 1155 |
+
return rv
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
def encipher_bifid5(msg, key):
|
| 1159 |
+
r"""
|
| 1160 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
| 1161 |
+
returns the ciphertext.
|
| 1162 |
+
|
| 1163 |
+
Explanation
|
| 1164 |
+
===========
|
| 1165 |
+
|
| 1166 |
+
This is the version of the Bifid cipher that uses the `5 \times 5`
|
| 1167 |
+
Polybius square. The letter "J" is ignored so it must be replaced
|
| 1168 |
+
with something else (traditionally an "I") before encryption.
|
| 1169 |
+
|
| 1170 |
+
ALGORITHM: (5x5 case)
|
| 1171 |
+
|
| 1172 |
+
STEPS:
|
| 1173 |
+
0. Create the `5 \times 5` Polybius square ``S`` associated
|
| 1174 |
+
to ``key`` as follows:
|
| 1175 |
+
|
| 1176 |
+
a) moving from left-to-right, top-to-bottom,
|
| 1177 |
+
place the letters of the key into a `5 \times 5`
|
| 1178 |
+
matrix,
|
| 1179 |
+
b) if the key has less than 25 letters, add the
|
| 1180 |
+
letters of the alphabet not in the key until the
|
| 1181 |
+
`5 \times 5` square is filled.
|
| 1182 |
+
|
| 1183 |
+
1. Create a list ``P`` of pairs of numbers which are the
|
| 1184 |
+
coordinates in the Polybius square of the letters in
|
| 1185 |
+
``msg``.
|
| 1186 |
+
2. Let ``L1`` be the list of all first coordinates of ``P``
|
| 1187 |
+
(length of ``L1 = n``), let ``L2`` be the list of all
|
| 1188 |
+
second coordinates of ``P`` (so the length of ``L2``
|
| 1189 |
+
is also ``n``).
|
| 1190 |
+
3. Let ``L`` be the concatenation of ``L1`` and ``L2``
|
| 1191 |
+
(length ``L = 2*n``), except that consecutive numbers
|
| 1192 |
+
are paired ``(L[2*i], L[2*i + 1])``. You can regard
|
| 1193 |
+
``L`` as a list of pairs of length ``n``.
|
| 1194 |
+
4. Let ``C`` be the list of all letters which are of the
|
| 1195 |
+
form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a
|
| 1196 |
+
string, this is the ciphertext of ``msg``.
|
| 1197 |
+
|
| 1198 |
+
Parameters
|
| 1199 |
+
==========
|
| 1200 |
+
|
| 1201 |
+
msg : str
|
| 1202 |
+
Plaintext string.
|
| 1203 |
+
|
| 1204 |
+
Converted to upper case and filtered of anything but all letters
|
| 1205 |
+
except J.
|
| 1206 |
+
|
| 1207 |
+
key
|
| 1208 |
+
Short string for key; non-alphabetic letters, J and duplicated
|
| 1209 |
+
characters are ignored and then, if the length is less than 25
|
| 1210 |
+
characters, it is padded with other letters of the alphabet
|
| 1211 |
+
(in alphabetical order).
|
| 1212 |
+
|
| 1213 |
+
Returns
|
| 1214 |
+
=======
|
| 1215 |
+
|
| 1216 |
+
ct
|
| 1217 |
+
Ciphertext (all caps, no spaces).
|
| 1218 |
+
|
| 1219 |
+
Examples
|
| 1220 |
+
========
|
| 1221 |
+
|
| 1222 |
+
>>> from sympy.crypto.crypto import (
|
| 1223 |
+
... encipher_bifid5, decipher_bifid5)
|
| 1224 |
+
|
| 1225 |
+
"J" will be omitted unless it is replaced with something else:
|
| 1226 |
+
|
| 1227 |
+
>>> round_trip = lambda m, k: \
|
| 1228 |
+
... decipher_bifid5(encipher_bifid5(m, k), k)
|
| 1229 |
+
>>> key = 'a'
|
| 1230 |
+
>>> msg = "JOSIE"
|
| 1231 |
+
>>> round_trip(msg, key)
|
| 1232 |
+
'OSIE'
|
| 1233 |
+
>>> round_trip(msg.replace("J", "I"), key)
|
| 1234 |
+
'IOSIE'
|
| 1235 |
+
>>> j = "QIQ"
|
| 1236 |
+
>>> round_trip(msg.replace("J", j), key).replace(j, "J")
|
| 1237 |
+
'JOSIE'
|
| 1238 |
+
|
| 1239 |
+
|
| 1240 |
+
Notes
|
| 1241 |
+
=====
|
| 1242 |
+
|
| 1243 |
+
The Bifid cipher was invented around 1901 by Felix Delastelle.
|
| 1244 |
+
It is a *fractional substitution* cipher, where letters are
|
| 1245 |
+
replaced by pairs of symbols from a smaller alphabet. The
|
| 1246 |
+
cipher uses a `5 \times 5` square filled with some ordering of the
|
| 1247 |
+
alphabet, except that "J" is replaced with "I" (this is a so-called
|
| 1248 |
+
Polybius square; there is a `6 \times 6` analog if you add back in
|
| 1249 |
+
"J" and also append onto the usual 26 letter alphabet, the digits
|
| 1250 |
+
0, 1, ..., 9).
|
| 1251 |
+
According to Helen Gaines' book *Cryptanalysis*, this type of cipher
|
| 1252 |
+
was used in the field by the German Army during World War I.
|
| 1253 |
+
|
| 1254 |
+
See Also
|
| 1255 |
+
========
|
| 1256 |
+
|
| 1257 |
+
decipher_bifid5, encipher_bifid
|
| 1258 |
+
|
| 1259 |
+
"""
|
| 1260 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
|
| 1261 |
+
key = padded_key(key, bifid5)
|
| 1262 |
+
return encipher_bifid(msg, '', key)
|
| 1263 |
+
|
| 1264 |
+
|
| 1265 |
+
def decipher_bifid5(msg, key):
|
| 1266 |
+
r"""
|
| 1267 |
+
Return the Bifid cipher decryption of ``msg``.
|
| 1268 |
+
|
| 1269 |
+
Explanation
|
| 1270 |
+
===========
|
| 1271 |
+
|
| 1272 |
+
This is the version of the Bifid cipher that uses the `5 \times 5`
|
| 1273 |
+
Polybius square; the letter "J" is ignored unless a ``key`` of
|
| 1274 |
+
length 25 is used.
|
| 1275 |
+
|
| 1276 |
+
Parameters
|
| 1277 |
+
==========
|
| 1278 |
+
|
| 1279 |
+
msg
|
| 1280 |
+
Ciphertext string.
|
| 1281 |
+
|
| 1282 |
+
key
|
| 1283 |
+
Short string for key; duplicated characters are ignored and if
|
| 1284 |
+
the length is less then 25 characters, it will be padded with
|
| 1285 |
+
other letters from the alphabet omitting "J".
|
| 1286 |
+
Non-alphabetic characters are ignored.
|
| 1287 |
+
|
| 1288 |
+
Returns
|
| 1289 |
+
=======
|
| 1290 |
+
|
| 1291 |
+
plaintext
|
| 1292 |
+
Plaintext from Bifid5 cipher (all caps, no spaces).
|
| 1293 |
+
|
| 1294 |
+
Examples
|
| 1295 |
+
========
|
| 1296 |
+
|
| 1297 |
+
>>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5
|
| 1298 |
+
>>> key = "gold bug"
|
| 1299 |
+
>>> encipher_bifid5('meet me on friday', key)
|
| 1300 |
+
'IEILEHFSTSFXEE'
|
| 1301 |
+
>>> encipher_bifid5('meet me on monday', key)
|
| 1302 |
+
'IEILHHFSTSFQYE'
|
| 1303 |
+
>>> decipher_bifid5(_, key)
|
| 1304 |
+
'MEETMEONMONDAY'
|
| 1305 |
+
|
| 1306 |
+
"""
|
| 1307 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5)
|
| 1308 |
+
key = padded_key(key, bifid5)
|
| 1309 |
+
return decipher_bifid(msg, '', key)
|
| 1310 |
+
|
| 1311 |
+
|
| 1312 |
+
def bifid5_square(key=None):
|
| 1313 |
+
r"""
|
| 1314 |
+
5x5 Polybius square.
|
| 1315 |
+
|
| 1316 |
+
Produce the Polybius square for the `5 \times 5` Bifid cipher.
|
| 1317 |
+
|
| 1318 |
+
Examples
|
| 1319 |
+
========
|
| 1320 |
+
|
| 1321 |
+
>>> from sympy.crypto.crypto import bifid5_square
|
| 1322 |
+
>>> bifid5_square("gold bug")
|
| 1323 |
+
Matrix([
|
| 1324 |
+
[G, O, L, D, B],
|
| 1325 |
+
[U, A, C, E, F],
|
| 1326 |
+
[H, I, K, M, N],
|
| 1327 |
+
[P, Q, R, S, T],
|
| 1328 |
+
[V, W, X, Y, Z]])
|
| 1329 |
+
|
| 1330 |
+
"""
|
| 1331 |
+
if not key:
|
| 1332 |
+
key = bifid5
|
| 1333 |
+
else:
|
| 1334 |
+
_, key, _ = _prep('', key.upper(), None, bifid5)
|
| 1335 |
+
key = padded_key(key, bifid5)
|
| 1336 |
+
return bifid_square(key)
|
| 1337 |
+
|
| 1338 |
+
|
| 1339 |
+
def encipher_bifid6(msg, key):
|
| 1340 |
+
r"""
|
| 1341 |
+
Performs the Bifid cipher encryption on plaintext ``msg``, and
|
| 1342 |
+
returns the ciphertext.
|
| 1343 |
+
|
| 1344 |
+
This is the version of the Bifid cipher that uses the `6 \times 6`
|
| 1345 |
+
Polybius square.
|
| 1346 |
+
|
| 1347 |
+
Parameters
|
| 1348 |
+
==========
|
| 1349 |
+
|
| 1350 |
+
msg
|
| 1351 |
+
Plaintext string (digits okay).
|
| 1352 |
+
|
| 1353 |
+
key
|
| 1354 |
+
Short string for key (digits okay).
|
| 1355 |
+
|
| 1356 |
+
If ``key`` is less than 36 characters long, the square will be
|
| 1357 |
+
filled with letters A through Z and digits 0 through 9.
|
| 1358 |
+
|
| 1359 |
+
Returns
|
| 1360 |
+
=======
|
| 1361 |
+
|
| 1362 |
+
ciphertext
|
| 1363 |
+
Ciphertext from Bifid cipher (all caps, no spaces).
|
| 1364 |
+
|
| 1365 |
+
See Also
|
| 1366 |
+
========
|
| 1367 |
+
|
| 1368 |
+
decipher_bifid6, encipher_bifid
|
| 1369 |
+
|
| 1370 |
+
"""
|
| 1371 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
|
| 1372 |
+
key = padded_key(key, bifid6)
|
| 1373 |
+
return encipher_bifid(msg, '', key)
|
| 1374 |
+
|
| 1375 |
+
|
| 1376 |
+
def decipher_bifid6(msg, key):
|
| 1377 |
+
r"""
|
| 1378 |
+
Performs the Bifid cipher decryption on ciphertext ``msg``, and
|
| 1379 |
+
returns the plaintext.
|
| 1380 |
+
|
| 1381 |
+
This is the version of the Bifid cipher that uses the `6 \times 6`
|
| 1382 |
+
Polybius square.
|
| 1383 |
+
|
| 1384 |
+
Parameters
|
| 1385 |
+
==========
|
| 1386 |
+
|
| 1387 |
+
msg
|
| 1388 |
+
Ciphertext string (digits okay); converted to upper case
|
| 1389 |
+
|
| 1390 |
+
key
|
| 1391 |
+
Short string for key (digits okay).
|
| 1392 |
+
|
| 1393 |
+
If ``key`` is less than 36 characters long, the square will be
|
| 1394 |
+
filled with letters A through Z and digits 0 through 9.
|
| 1395 |
+
All letters are converted to uppercase.
|
| 1396 |
+
|
| 1397 |
+
Returns
|
| 1398 |
+
=======
|
| 1399 |
+
|
| 1400 |
+
plaintext
|
| 1401 |
+
Plaintext from Bifid cipher (all caps, no spaces).
|
| 1402 |
+
|
| 1403 |
+
Examples
|
| 1404 |
+
========
|
| 1405 |
+
|
| 1406 |
+
>>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
|
| 1407 |
+
>>> key = "gold bug"
|
| 1408 |
+
>>> encipher_bifid6('meet me on monday at 8am', key)
|
| 1409 |
+
'KFKLJJHF5MMMKTFRGPL'
|
| 1410 |
+
>>> decipher_bifid6(_, key)
|
| 1411 |
+
'MEETMEONMONDAYAT8AM'
|
| 1412 |
+
|
| 1413 |
+
"""
|
| 1414 |
+
msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6)
|
| 1415 |
+
key = padded_key(key, bifid6)
|
| 1416 |
+
return decipher_bifid(msg, '', key)
|
| 1417 |
+
|
| 1418 |
+
|
| 1419 |
+
def bifid6_square(key=None):
|
| 1420 |
+
r"""
|
| 1421 |
+
6x6 Polybius square.
|
| 1422 |
+
|
| 1423 |
+
Produces the Polybius square for the `6 \times 6` Bifid cipher.
|
| 1424 |
+
Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9".
|
| 1425 |
+
|
| 1426 |
+
Examples
|
| 1427 |
+
========
|
| 1428 |
+
|
| 1429 |
+
>>> from sympy.crypto.crypto import bifid6_square
|
| 1430 |
+
>>> key = "gold bug"
|
| 1431 |
+
>>> bifid6_square(key)
|
| 1432 |
+
Matrix([
|
| 1433 |
+
[G, O, L, D, B, U],
|
| 1434 |
+
[A, C, E, F, H, I],
|
| 1435 |
+
[J, K, M, N, P, Q],
|
| 1436 |
+
[R, S, T, V, W, X],
|
| 1437 |
+
[Y, Z, 0, 1, 2, 3],
|
| 1438 |
+
[4, 5, 6, 7, 8, 9]])
|
| 1439 |
+
|
| 1440 |
+
"""
|
| 1441 |
+
if not key:
|
| 1442 |
+
key = bifid6
|
| 1443 |
+
else:
|
| 1444 |
+
_, key, _ = _prep('', key.upper(), None, bifid6)
|
| 1445 |
+
key = padded_key(key, bifid6)
|
| 1446 |
+
return bifid_square(key)
|
| 1447 |
+
|
| 1448 |
+
|
| 1449 |
+
#################### RSA #############################
|
| 1450 |
+
|
| 1451 |
+
def _decipher_rsa_crt(i, d, factors):
|
| 1452 |
+
"""Decipher RSA using chinese remainder theorem from the information
|
| 1453 |
+
of the relatively-prime factors of the modulus.
|
| 1454 |
+
|
| 1455 |
+
Parameters
|
| 1456 |
+
==========
|
| 1457 |
+
|
| 1458 |
+
i : integer
|
| 1459 |
+
Ciphertext
|
| 1460 |
+
|
| 1461 |
+
d : integer
|
| 1462 |
+
The exponent component.
|
| 1463 |
+
|
| 1464 |
+
factors : list of relatively-prime integers
|
| 1465 |
+
The integers given must be coprime and the product must equal
|
| 1466 |
+
the modulus component of the original RSA key.
|
| 1467 |
+
|
| 1468 |
+
Examples
|
| 1469 |
+
========
|
| 1470 |
+
|
| 1471 |
+
How to decrypt RSA with CRT:
|
| 1472 |
+
|
| 1473 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
| 1474 |
+
>>> primes = [61, 53]
|
| 1475 |
+
>>> e = 17
|
| 1476 |
+
>>> args = primes + [e]
|
| 1477 |
+
>>> puk = rsa_public_key(*args)
|
| 1478 |
+
>>> prk = rsa_private_key(*args)
|
| 1479 |
+
|
| 1480 |
+
>>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt
|
| 1481 |
+
>>> msg = 65
|
| 1482 |
+
>>> crt_primes = primes
|
| 1483 |
+
>>> encrypted = encipher_rsa(msg, puk)
|
| 1484 |
+
>>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes)
|
| 1485 |
+
>>> decrypted
|
| 1486 |
+
65
|
| 1487 |
+
"""
|
| 1488 |
+
moduluses = [pow(i, d, p) for p in factors]
|
| 1489 |
+
|
| 1490 |
+
result = crt(factors, moduluses)
|
| 1491 |
+
if not result:
|
| 1492 |
+
raise ValueError("CRT failed")
|
| 1493 |
+
return result[0]
|
| 1494 |
+
|
| 1495 |
+
|
| 1496 |
+
def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None):
|
| 1497 |
+
r"""A private subroutine to generate RSA key
|
| 1498 |
+
|
| 1499 |
+
Parameters
|
| 1500 |
+
==========
|
| 1501 |
+
|
| 1502 |
+
public, private : bool, optional
|
| 1503 |
+
Flag to generate either a public key, a private key.
|
| 1504 |
+
|
| 1505 |
+
totient : 'Euler' or 'Carmichael'
|
| 1506 |
+
Different notation used for totient.
|
| 1507 |
+
|
| 1508 |
+
multipower : bool, optional
|
| 1509 |
+
Flag to bypass warning for multipower RSA.
|
| 1510 |
+
"""
|
| 1511 |
+
|
| 1512 |
+
if len(args) < 2:
|
| 1513 |
+
return False
|
| 1514 |
+
|
| 1515 |
+
if totient not in ('Euler', 'Carmichael'):
|
| 1516 |
+
raise ValueError(
|
| 1517 |
+
"The argument totient={} should either be " \
|
| 1518 |
+
"'Euler', 'Carmichalel'." \
|
| 1519 |
+
.format(totient))
|
| 1520 |
+
|
| 1521 |
+
if totient == 'Euler':
|
| 1522 |
+
_totient = _euler
|
| 1523 |
+
else:
|
| 1524 |
+
_totient = _carmichael
|
| 1525 |
+
|
| 1526 |
+
if index is not None:
|
| 1527 |
+
index = as_int(index)
|
| 1528 |
+
if totient != 'Carmichael':
|
| 1529 |
+
raise ValueError(
|
| 1530 |
+
"Setting the 'index' keyword argument requires totient"
|
| 1531 |
+
"notation to be specified as 'Carmichael'.")
|
| 1532 |
+
|
| 1533 |
+
primes, e = args[:-1], args[-1]
|
| 1534 |
+
|
| 1535 |
+
if not all(isprime(p) for p in primes):
|
| 1536 |
+
new_primes = []
|
| 1537 |
+
for i in primes:
|
| 1538 |
+
new_primes.extend(factorint(i, multiple=True))
|
| 1539 |
+
primes = new_primes
|
| 1540 |
+
|
| 1541 |
+
n = reduce(lambda i, j: i*j, primes)
|
| 1542 |
+
|
| 1543 |
+
tally = multiset(primes)
|
| 1544 |
+
if all(v == 1 for v in tally.values()):
|
| 1545 |
+
multiple = list(tally.keys())
|
| 1546 |
+
phi = _totient._from_distinct_primes(*multiple)
|
| 1547 |
+
|
| 1548 |
+
else:
|
| 1549 |
+
if not multipower:
|
| 1550 |
+
NonInvertibleCipherWarning(
|
| 1551 |
+
'Non-distinctive primes found in the factors {}. '
|
| 1552 |
+
'The cipher may not be decryptable for some numbers '
|
| 1553 |
+
'in the complete residue system Z[{}], but the cipher '
|
| 1554 |
+
'can still be valid if you restrict the domain to be '
|
| 1555 |
+
'the reduced residue system Z*[{}]. You can pass '
|
| 1556 |
+
'the flag multipower=True if you want to suppress this '
|
| 1557 |
+
'warning.'
|
| 1558 |
+
.format(primes, n, n)
|
| 1559 |
+
# stacklevel=4 because most users will call a function that
|
| 1560 |
+
# calls this function
|
| 1561 |
+
).warn(stacklevel=4)
|
| 1562 |
+
phi = _totient._from_factors(tally)
|
| 1563 |
+
|
| 1564 |
+
if igcd(e, phi) == 1:
|
| 1565 |
+
if public and not private:
|
| 1566 |
+
if isinstance(index, int):
|
| 1567 |
+
e = e % phi
|
| 1568 |
+
e += index * phi
|
| 1569 |
+
return n, e
|
| 1570 |
+
|
| 1571 |
+
if private and not public:
|
| 1572 |
+
d = mod_inverse(e, phi)
|
| 1573 |
+
if isinstance(index, int):
|
| 1574 |
+
d += index * phi
|
| 1575 |
+
return n, d
|
| 1576 |
+
|
| 1577 |
+
return False
|
| 1578 |
+
|
| 1579 |
+
|
| 1580 |
+
def rsa_public_key(*args, **kwargs):
|
| 1581 |
+
r"""Return the RSA *public key* pair, `(n, e)`
|
| 1582 |
+
|
| 1583 |
+
Parameters
|
| 1584 |
+
==========
|
| 1585 |
+
|
| 1586 |
+
args : naturals
|
| 1587 |
+
If specified as `p, q, e` where `p` and `q` are distinct primes
|
| 1588 |
+
and `e` is a desired public exponent of the RSA, `n = p q` and
|
| 1589 |
+
`e` will be verified against the totient
|
| 1590 |
+
`\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient)
|
| 1591 |
+
to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`.
|
| 1592 |
+
|
| 1593 |
+
If specified as `p_1, p_2, \dots, p_n, e` where
|
| 1594 |
+
`p_1, p_2, \dots, p_n` are specified as primes,
|
| 1595 |
+
and `e` is specified as a desired public exponent of the RSA,
|
| 1596 |
+
it will be able to form a multi-prime RSA, which is a more
|
| 1597 |
+
generalized form of the popular 2-prime RSA.
|
| 1598 |
+
|
| 1599 |
+
It can also be possible to form a single-prime RSA by specifying
|
| 1600 |
+
the argument as `p, e`, which can be considered a trivial case
|
| 1601 |
+
of a multiprime RSA.
|
| 1602 |
+
|
| 1603 |
+
Furthermore, it can be possible to form a multi-power RSA by
|
| 1604 |
+
specifying two or more pairs of the primes to be same.
|
| 1605 |
+
However, unlike the two-distinct prime RSA or multi-prime
|
| 1606 |
+
RSA, not every numbers in the complete residue system
|
| 1607 |
+
(`\mathbb{Z}_n`) will be decryptable since the mapping
|
| 1608 |
+
`\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}`
|
| 1609 |
+
will not be bijective.
|
| 1610 |
+
(Only except for the trivial case when
|
| 1611 |
+
`e = 1`
|
| 1612 |
+
or more generally,
|
| 1613 |
+
|
| 1614 |
+
.. math::
|
| 1615 |
+
e \in \left \{ 1 + k \lambda(n)
|
| 1616 |
+
\mid k \in \mathbb{Z} \land k \geq 0 \right \}
|
| 1617 |
+
|
| 1618 |
+
when RSA reduces to the identity.)
|
| 1619 |
+
However, the RSA can still be decryptable for the numbers in the
|
| 1620 |
+
reduced residue system (`\mathbb{Z}_n^{\times}`), since the
|
| 1621 |
+
mapping
|
| 1622 |
+
`\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}`
|
| 1623 |
+
can still be bijective.
|
| 1624 |
+
|
| 1625 |
+
If you pass a non-prime integer to the arguments
|
| 1626 |
+
`p_1, p_2, \dots, p_n`, the particular number will be
|
| 1627 |
+
prime-factored and it will become either a multi-prime RSA or a
|
| 1628 |
+
multi-power RSA in its canonical form, depending on whether the
|
| 1629 |
+
product equals its radical or not.
|
| 1630 |
+
`p_1 p_2 \dots p_n = \text{rad}(p_1 p_2 \dots p_n)`
|
| 1631 |
+
|
| 1632 |
+
totient : bool, optional
|
| 1633 |
+
If ``'Euler'``, it uses Euler's totient `\phi(n)` which is
|
| 1634 |
+
:meth:`sympy.ntheory.factor_.totient` in SymPy.
|
| 1635 |
+
|
| 1636 |
+
If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)`
|
| 1637 |
+
which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
|
| 1638 |
+
|
| 1639 |
+
Unlike private key generation, this is a trivial keyword for
|
| 1640 |
+
public key generation because
|
| 1641 |
+
`\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`.
|
| 1642 |
+
|
| 1643 |
+
index : nonnegative integer, optional
|
| 1644 |
+
Returns an arbitrary solution of a RSA public key at the index
|
| 1645 |
+
specified at `0, 1, 2, \dots`. This parameter needs to be
|
| 1646 |
+
specified along with ``totient='Carmichael'``.
|
| 1647 |
+
|
| 1648 |
+
Similarly to the non-uniquenss of a RSA private key as described
|
| 1649 |
+
in the ``index`` parameter documentation in
|
| 1650 |
+
:meth:`rsa_private_key`, RSA public key is also not unique and
|
| 1651 |
+
there is an infinite number of RSA public exponents which
|
| 1652 |
+
can behave in the same manner.
|
| 1653 |
+
|
| 1654 |
+
From any given RSA public exponent `e`, there are can be an
|
| 1655 |
+
another RSA public exponent `e + k \lambda(n)` where `k` is an
|
| 1656 |
+
integer, `\lambda` is a Carmichael's totient function.
|
| 1657 |
+
|
| 1658 |
+
However, considering only the positive cases, there can be
|
| 1659 |
+
a principal solution of a RSA public exponent `e_0` in
|
| 1660 |
+
`0 < e_0 < \lambda(n)`, and all the other solutions
|
| 1661 |
+
can be canonicalzed in a form of `e_0 + k \lambda(n)`.
|
| 1662 |
+
|
| 1663 |
+
``index`` specifies the `k` notation to yield any possible value
|
| 1664 |
+
an RSA public key can have.
|
| 1665 |
+
|
| 1666 |
+
An example of computing any arbitrary RSA public key:
|
| 1667 |
+
|
| 1668 |
+
>>> from sympy.crypto.crypto import rsa_public_key
|
| 1669 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0)
|
| 1670 |
+
(3233, 17)
|
| 1671 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1)
|
| 1672 |
+
(3233, 797)
|
| 1673 |
+
>>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2)
|
| 1674 |
+
(3233, 1577)
|
| 1675 |
+
|
| 1676 |
+
multipower : bool, optional
|
| 1677 |
+
Any pair of non-distinct primes found in the RSA specification
|
| 1678 |
+
will restrict the domain of the cryptosystem, as noted in the
|
| 1679 |
+
explanation of the parameter ``args``.
|
| 1680 |
+
|
| 1681 |
+
SymPy RSA key generator may give a warning before dispatching it
|
| 1682 |
+
as a multi-power RSA, however, you can disable the warning if
|
| 1683 |
+
you pass ``True`` to this keyword.
|
| 1684 |
+
|
| 1685 |
+
Returns
|
| 1686 |
+
=======
|
| 1687 |
+
|
| 1688 |
+
(n, e) : int, int
|
| 1689 |
+
`n` is a product of any arbitrary number of primes given as
|
| 1690 |
+
the argument.
|
| 1691 |
+
|
| 1692 |
+
`e` is relatively prime (coprime) to the Euler totient
|
| 1693 |
+
`\phi(n)`.
|
| 1694 |
+
|
| 1695 |
+
False
|
| 1696 |
+
Returned if less than two arguments are given, or `e` is
|
| 1697 |
+
not relatively prime to the modulus.
|
| 1698 |
+
|
| 1699 |
+
Examples
|
| 1700 |
+
========
|
| 1701 |
+
|
| 1702 |
+
>>> from sympy.crypto.crypto import rsa_public_key
|
| 1703 |
+
|
| 1704 |
+
A public key of a two-prime RSA:
|
| 1705 |
+
|
| 1706 |
+
>>> p, q, e = 3, 5, 7
|
| 1707 |
+
>>> rsa_public_key(p, q, e)
|
| 1708 |
+
(15, 7)
|
| 1709 |
+
>>> rsa_public_key(p, q, 30)
|
| 1710 |
+
False
|
| 1711 |
+
|
| 1712 |
+
A public key of a multiprime RSA:
|
| 1713 |
+
|
| 1714 |
+
>>> primes = [2, 3, 5, 7, 11, 13]
|
| 1715 |
+
>>> e = 7
|
| 1716 |
+
>>> args = primes + [e]
|
| 1717 |
+
>>> rsa_public_key(*args)
|
| 1718 |
+
(30030, 7)
|
| 1719 |
+
|
| 1720 |
+
Notes
|
| 1721 |
+
=====
|
| 1722 |
+
|
| 1723 |
+
Although the RSA can be generalized over any modulus `n`, using
|
| 1724 |
+
two large primes had became the most popular specification because a
|
| 1725 |
+
product of two large primes is usually the hardest to factor
|
| 1726 |
+
relatively to the digits of `n` can have.
|
| 1727 |
+
|
| 1728 |
+
However, it may need further understanding of the time complexities
|
| 1729 |
+
of each prime-factoring algorithms to verify the claim.
|
| 1730 |
+
|
| 1731 |
+
See Also
|
| 1732 |
+
========
|
| 1733 |
+
|
| 1734 |
+
rsa_private_key
|
| 1735 |
+
encipher_rsa
|
| 1736 |
+
decipher_rsa
|
| 1737 |
+
|
| 1738 |
+
References
|
| 1739 |
+
==========
|
| 1740 |
+
|
| 1741 |
+
.. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
|
| 1742 |
+
|
| 1743 |
+
.. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
|
| 1744 |
+
|
| 1745 |
+
.. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
|
| 1746 |
+
|
| 1747 |
+
.. [4] https://www.itiis.org/digital-library/manuscript/1381
|
| 1748 |
+
"""
|
| 1749 |
+
return _rsa_key(*args, public=True, private=False, **kwargs)
|
| 1750 |
+
|
| 1751 |
+
|
| 1752 |
+
def rsa_private_key(*args, **kwargs):
|
| 1753 |
+
r"""Return the RSA *private key* pair, `(n, d)`
|
| 1754 |
+
|
| 1755 |
+
Parameters
|
| 1756 |
+
==========
|
| 1757 |
+
|
| 1758 |
+
args : naturals
|
| 1759 |
+
The keyword is identical to the ``args`` in
|
| 1760 |
+
:meth:`rsa_public_key`.
|
| 1761 |
+
|
| 1762 |
+
totient : bool, optional
|
| 1763 |
+
If ``'Euler'``, it uses Euler's totient convention `\phi(n)`
|
| 1764 |
+
which is :meth:`sympy.ntheory.factor_.totient` in SymPy.
|
| 1765 |
+
|
| 1766 |
+
If ``'Carmichael'``, it uses Carmichael's totient convention
|
| 1767 |
+
`\lambda(n)` which is
|
| 1768 |
+
:meth:`sympy.ntheory.factor_.reduced_totient` in SymPy.
|
| 1769 |
+
|
| 1770 |
+
There can be some output differences for private key generation
|
| 1771 |
+
as examples below.
|
| 1772 |
+
|
| 1773 |
+
Example using Euler's totient:
|
| 1774 |
+
|
| 1775 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
| 1776 |
+
>>> rsa_private_key(61, 53, 17, totient='Euler')
|
| 1777 |
+
(3233, 2753)
|
| 1778 |
+
|
| 1779 |
+
Example using Carmichael's totient:
|
| 1780 |
+
|
| 1781 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
| 1782 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael')
|
| 1783 |
+
(3233, 413)
|
| 1784 |
+
|
| 1785 |
+
index : nonnegative integer, optional
|
| 1786 |
+
Returns an arbitrary solution of a RSA private key at the index
|
| 1787 |
+
specified at `0, 1, 2, \dots`. This parameter needs to be
|
| 1788 |
+
specified along with ``totient='Carmichael'``.
|
| 1789 |
+
|
| 1790 |
+
RSA private exponent is a non-unique solution of
|
| 1791 |
+
`e d \mod \lambda(n) = 1` and it is possible in any form of
|
| 1792 |
+
`d + k \lambda(n)`, where `d` is an another
|
| 1793 |
+
already-computed private exponent, and `\lambda` is a
|
| 1794 |
+
Carmichael's totient function, and `k` is any integer.
|
| 1795 |
+
|
| 1796 |
+
However, considering only the positive cases, there can be
|
| 1797 |
+
a principal solution of a RSA private exponent `d_0` in
|
| 1798 |
+
`0 < d_0 < \lambda(n)`, and all the other solutions
|
| 1799 |
+
can be canonicalzed in a form of `d_0 + k \lambda(n)`.
|
| 1800 |
+
|
| 1801 |
+
``index`` specifies the `k` notation to yield any possible value
|
| 1802 |
+
an RSA private key can have.
|
| 1803 |
+
|
| 1804 |
+
An example of computing any arbitrary RSA private key:
|
| 1805 |
+
|
| 1806 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
| 1807 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0)
|
| 1808 |
+
(3233, 413)
|
| 1809 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1)
|
| 1810 |
+
(3233, 1193)
|
| 1811 |
+
>>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2)
|
| 1812 |
+
(3233, 1973)
|
| 1813 |
+
|
| 1814 |
+
multipower : bool, optional
|
| 1815 |
+
The keyword is identical to the ``multipower`` in
|
| 1816 |
+
:meth:`rsa_public_key`.
|
| 1817 |
+
|
| 1818 |
+
Returns
|
| 1819 |
+
=======
|
| 1820 |
+
|
| 1821 |
+
(n, d) : int, int
|
| 1822 |
+
`n` is a product of any arbitrary number of primes given as
|
| 1823 |
+
the argument.
|
| 1824 |
+
|
| 1825 |
+
`d` is the inverse of `e` (mod `\phi(n)`) where `e` is the
|
| 1826 |
+
exponent given, and `\phi` is a Euler totient.
|
| 1827 |
+
|
| 1828 |
+
False
|
| 1829 |
+
Returned if less than two arguments are given, or `e` is
|
| 1830 |
+
not relatively prime to the totient of the modulus.
|
| 1831 |
+
|
| 1832 |
+
Examples
|
| 1833 |
+
========
|
| 1834 |
+
|
| 1835 |
+
>>> from sympy.crypto.crypto import rsa_private_key
|
| 1836 |
+
|
| 1837 |
+
A private key of a two-prime RSA:
|
| 1838 |
+
|
| 1839 |
+
>>> p, q, e = 3, 5, 7
|
| 1840 |
+
>>> rsa_private_key(p, q, e)
|
| 1841 |
+
(15, 7)
|
| 1842 |
+
>>> rsa_private_key(p, q, 30)
|
| 1843 |
+
False
|
| 1844 |
+
|
| 1845 |
+
A private key of a multiprime RSA:
|
| 1846 |
+
|
| 1847 |
+
>>> primes = [2, 3, 5, 7, 11, 13]
|
| 1848 |
+
>>> e = 7
|
| 1849 |
+
>>> args = primes + [e]
|
| 1850 |
+
>>> rsa_private_key(*args)
|
| 1851 |
+
(30030, 823)
|
| 1852 |
+
|
| 1853 |
+
See Also
|
| 1854 |
+
========
|
| 1855 |
+
|
| 1856 |
+
rsa_public_key
|
| 1857 |
+
encipher_rsa
|
| 1858 |
+
decipher_rsa
|
| 1859 |
+
|
| 1860 |
+
References
|
| 1861 |
+
==========
|
| 1862 |
+
|
| 1863 |
+
.. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29
|
| 1864 |
+
|
| 1865 |
+
.. [2] https://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
|
| 1866 |
+
|
| 1867 |
+
.. [3] https://link.springer.com/content/pdf/10.1007/BFb0055738.pdf
|
| 1868 |
+
|
| 1869 |
+
.. [4] https://www.itiis.org/digital-library/manuscript/1381
|
| 1870 |
+
"""
|
| 1871 |
+
return _rsa_key(*args, public=False, private=True, **kwargs)
|
| 1872 |
+
|
| 1873 |
+
|
| 1874 |
+
def _encipher_decipher_rsa(i, key, factors=None):
|
| 1875 |
+
n, d = key
|
| 1876 |
+
if not factors:
|
| 1877 |
+
return pow(i, d, n)
|
| 1878 |
+
|
| 1879 |
+
def _is_coprime_set(l):
|
| 1880 |
+
is_coprime_set = True
|
| 1881 |
+
for i in range(len(l)):
|
| 1882 |
+
for j in range(i+1, len(l)):
|
| 1883 |
+
if igcd(l[i], l[j]) != 1:
|
| 1884 |
+
is_coprime_set = False
|
| 1885 |
+
break
|
| 1886 |
+
return is_coprime_set
|
| 1887 |
+
|
| 1888 |
+
prod = reduce(lambda i, j: i*j, factors)
|
| 1889 |
+
if prod == n and _is_coprime_set(factors):
|
| 1890 |
+
return _decipher_rsa_crt(i, d, factors)
|
| 1891 |
+
return _encipher_decipher_rsa(i, key, factors=None)
|
| 1892 |
+
|
| 1893 |
+
|
| 1894 |
+
def encipher_rsa(i, key, factors=None):
|
| 1895 |
+
r"""Encrypt the plaintext with RSA.
|
| 1896 |
+
|
| 1897 |
+
Parameters
|
| 1898 |
+
==========
|
| 1899 |
+
|
| 1900 |
+
i : integer
|
| 1901 |
+
The plaintext to be encrypted for.
|
| 1902 |
+
|
| 1903 |
+
key : (n, e) where n, e are integers
|
| 1904 |
+
`n` is the modulus of the key and `e` is the exponent of the
|
| 1905 |
+
key. The encryption is computed by `i^e \bmod n`.
|
| 1906 |
+
|
| 1907 |
+
The key can either be a public key or a private key, however,
|
| 1908 |
+
the message encrypted by a public key can only be decrypted by
|
| 1909 |
+
a private key, and vice versa, as RSA is an asymmetric
|
| 1910 |
+
cryptography system.
|
| 1911 |
+
|
| 1912 |
+
factors : list of coprime integers
|
| 1913 |
+
This is identical to the keyword ``factors`` in
|
| 1914 |
+
:meth:`decipher_rsa`.
|
| 1915 |
+
|
| 1916 |
+
Notes
|
| 1917 |
+
=====
|
| 1918 |
+
|
| 1919 |
+
Some specifications may make the RSA not cryptographically
|
| 1920 |
+
meaningful.
|
| 1921 |
+
|
| 1922 |
+
For example, `0`, `1` will remain always same after taking any
|
| 1923 |
+
number of exponentiation, thus, should be avoided.
|
| 1924 |
+
|
| 1925 |
+
Furthermore, if `i^e < n`, `i` may easily be figured out by taking
|
| 1926 |
+
`e` th root.
|
| 1927 |
+
|
| 1928 |
+
And also, specifying the exponent as `1` or in more generalized form
|
| 1929 |
+
as `1 + k \lambda(n)` where `k` is an nonnegative integer,
|
| 1930 |
+
`\lambda` is a carmichael totient, the RSA becomes an identity
|
| 1931 |
+
mapping.
|
| 1932 |
+
|
| 1933 |
+
Examples
|
| 1934 |
+
========
|
| 1935 |
+
|
| 1936 |
+
>>> from sympy.crypto.crypto import encipher_rsa
|
| 1937 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
| 1938 |
+
|
| 1939 |
+
Public Key Encryption:
|
| 1940 |
+
|
| 1941 |
+
>>> p, q, e = 3, 5, 7
|
| 1942 |
+
>>> puk = rsa_public_key(p, q, e)
|
| 1943 |
+
>>> msg = 12
|
| 1944 |
+
>>> encipher_rsa(msg, puk)
|
| 1945 |
+
3
|
| 1946 |
+
|
| 1947 |
+
Private Key Encryption:
|
| 1948 |
+
|
| 1949 |
+
>>> p, q, e = 3, 5, 7
|
| 1950 |
+
>>> prk = rsa_private_key(p, q, e)
|
| 1951 |
+
>>> msg = 12
|
| 1952 |
+
>>> encipher_rsa(msg, prk)
|
| 1953 |
+
3
|
| 1954 |
+
|
| 1955 |
+
Encryption using chinese remainder theorem:
|
| 1956 |
+
|
| 1957 |
+
>>> encipher_rsa(msg, prk, factors=[p, q])
|
| 1958 |
+
3
|
| 1959 |
+
"""
|
| 1960 |
+
return _encipher_decipher_rsa(i, key, factors=factors)
|
| 1961 |
+
|
| 1962 |
+
|
| 1963 |
+
def decipher_rsa(i, key, factors=None):
|
| 1964 |
+
r"""Decrypt the ciphertext with RSA.
|
| 1965 |
+
|
| 1966 |
+
Parameters
|
| 1967 |
+
==========
|
| 1968 |
+
|
| 1969 |
+
i : integer
|
| 1970 |
+
The ciphertext to be decrypted for.
|
| 1971 |
+
|
| 1972 |
+
key : (n, d) where n, d are integers
|
| 1973 |
+
`n` is the modulus of the key and `d` is the exponent of the
|
| 1974 |
+
key. The decryption is computed by `i^d \bmod n`.
|
| 1975 |
+
|
| 1976 |
+
The key can either be a public key or a private key, however,
|
| 1977 |
+
the message encrypted by a public key can only be decrypted by
|
| 1978 |
+
a private key, and vice versa, as RSA is an asymmetric
|
| 1979 |
+
cryptography system.
|
| 1980 |
+
|
| 1981 |
+
factors : list of coprime integers
|
| 1982 |
+
As the modulus `n` created from RSA key generation is composed
|
| 1983 |
+
of arbitrary prime factors
|
| 1984 |
+
`n = {p_1}^{k_1}{p_2}^{k_2}\dots{p_n}^{k_n}` where
|
| 1985 |
+
`p_1, p_2, \dots, p_n` are distinct primes and
|
| 1986 |
+
`k_1, k_2, \dots, k_n` are positive integers, chinese remainder
|
| 1987 |
+
theorem can be used to compute `i^d \bmod n` from the
|
| 1988 |
+
fragmented modulo operations like
|
| 1989 |
+
|
| 1990 |
+
.. math::
|
| 1991 |
+
i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, \dots,
|
| 1992 |
+
i^d \bmod {p_n}^{k_n}
|
| 1993 |
+
|
| 1994 |
+
or like
|
| 1995 |
+
|
| 1996 |
+
.. math::
|
| 1997 |
+
i^d \bmod {p_1}^{k_1}{p_2}^{k_2},
|
| 1998 |
+
i^d \bmod {p_3}^{k_3}, \dots ,
|
| 1999 |
+
i^d \bmod {p_n}^{k_n}
|
| 2000 |
+
|
| 2001 |
+
as long as every moduli does not share any common divisor each
|
| 2002 |
+
other.
|
| 2003 |
+
|
| 2004 |
+
The raw primes used in generating the RSA key pair can be a good
|
| 2005 |
+
option.
|
| 2006 |
+
|
| 2007 |
+
Note that the speed advantage of using this is only viable for
|
| 2008 |
+
very large cases (Like 2048-bit RSA keys) since the
|
| 2009 |
+
overhead of using pure Python implementation of
|
| 2010 |
+
:meth:`sympy.ntheory.modular.crt` may overcompensate the
|
| 2011 |
+
theoretical speed advantage.
|
| 2012 |
+
|
| 2013 |
+
Notes
|
| 2014 |
+
=====
|
| 2015 |
+
|
| 2016 |
+
See the ``Notes`` section in the documentation of
|
| 2017 |
+
:meth:`encipher_rsa`
|
| 2018 |
+
|
| 2019 |
+
Examples
|
| 2020 |
+
========
|
| 2021 |
+
|
| 2022 |
+
>>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa
|
| 2023 |
+
>>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key
|
| 2024 |
+
|
| 2025 |
+
Public Key Encryption and Decryption:
|
| 2026 |
+
|
| 2027 |
+
>>> p, q, e = 3, 5, 7
|
| 2028 |
+
>>> prk = rsa_private_key(p, q, e)
|
| 2029 |
+
>>> puk = rsa_public_key(p, q, e)
|
| 2030 |
+
>>> msg = 12
|
| 2031 |
+
>>> new_msg = encipher_rsa(msg, prk)
|
| 2032 |
+
>>> new_msg
|
| 2033 |
+
3
|
| 2034 |
+
>>> decipher_rsa(new_msg, puk)
|
| 2035 |
+
12
|
| 2036 |
+
|
| 2037 |
+
Private Key Encryption and Decryption:
|
| 2038 |
+
|
| 2039 |
+
>>> p, q, e = 3, 5, 7
|
| 2040 |
+
>>> prk = rsa_private_key(p, q, e)
|
| 2041 |
+
>>> puk = rsa_public_key(p, q, e)
|
| 2042 |
+
>>> msg = 12
|
| 2043 |
+
>>> new_msg = encipher_rsa(msg, puk)
|
| 2044 |
+
>>> new_msg
|
| 2045 |
+
3
|
| 2046 |
+
>>> decipher_rsa(new_msg, prk)
|
| 2047 |
+
12
|
| 2048 |
+
|
| 2049 |
+
Decryption using chinese remainder theorem:
|
| 2050 |
+
|
| 2051 |
+
>>> decipher_rsa(new_msg, prk, factors=[p, q])
|
| 2052 |
+
12
|
| 2053 |
+
|
| 2054 |
+
See Also
|
| 2055 |
+
========
|
| 2056 |
+
|
| 2057 |
+
encipher_rsa
|
| 2058 |
+
"""
|
| 2059 |
+
return _encipher_decipher_rsa(i, key, factors=factors)
|
| 2060 |
+
|
| 2061 |
+
|
| 2062 |
+
#################### kid krypto (kid RSA) #############################
|
| 2063 |
+
|
| 2064 |
+
|
| 2065 |
+
def kid_rsa_public_key(a, b, A, B):
|
| 2066 |
+
r"""
|
| 2067 |
+
Kid RSA is a version of RSA useful to teach grade school children
|
| 2068 |
+
since it does not involve exponentiation.
|
| 2069 |
+
|
| 2070 |
+
Explanation
|
| 2071 |
+
===========
|
| 2072 |
+
|
| 2073 |
+
Alice wants to talk to Bob. Bob generates keys as follows.
|
| 2074 |
+
Key generation:
|
| 2075 |
+
|
| 2076 |
+
* Select positive integers `a, b, A, B` at random.
|
| 2077 |
+
* Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
|
| 2078 |
+
`n = (e d - 1)//M`.
|
| 2079 |
+
* The *public key* is `(n, e)`. Bob sends these to Alice.
|
| 2080 |
+
* The *private key* is `(n, d)`, which Bob keeps secret.
|
| 2081 |
+
|
| 2082 |
+
Encryption: If `p` is the plaintext message then the
|
| 2083 |
+
ciphertext is `c = p e \pmod n`.
|
| 2084 |
+
|
| 2085 |
+
Decryption: If `c` is the ciphertext message then the
|
| 2086 |
+
plaintext is `p = c d \pmod n`.
|
| 2087 |
+
|
| 2088 |
+
Examples
|
| 2089 |
+
========
|
| 2090 |
+
|
| 2091 |
+
>>> from sympy.crypto.crypto import kid_rsa_public_key
|
| 2092 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
| 2093 |
+
>>> kid_rsa_public_key(a, b, A, B)
|
| 2094 |
+
(369, 58)
|
| 2095 |
+
|
| 2096 |
+
"""
|
| 2097 |
+
M = a*b - 1
|
| 2098 |
+
e = A*M + a
|
| 2099 |
+
d = B*M + b
|
| 2100 |
+
n = (e*d - 1)//M
|
| 2101 |
+
return n, e
|
| 2102 |
+
|
| 2103 |
+
|
| 2104 |
+
def kid_rsa_private_key(a, b, A, B):
|
| 2105 |
+
"""
|
| 2106 |
+
Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`,
|
| 2107 |
+
`n = (e d - 1) / M`. The *private key* is `d`, which Bob
|
| 2108 |
+
keeps secret.
|
| 2109 |
+
|
| 2110 |
+
Examples
|
| 2111 |
+
========
|
| 2112 |
+
|
| 2113 |
+
>>> from sympy.crypto.crypto import kid_rsa_private_key
|
| 2114 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
| 2115 |
+
>>> kid_rsa_private_key(a, b, A, B)
|
| 2116 |
+
(369, 70)
|
| 2117 |
+
|
| 2118 |
+
"""
|
| 2119 |
+
M = a*b - 1
|
| 2120 |
+
e = A*M + a
|
| 2121 |
+
d = B*M + b
|
| 2122 |
+
n = (e*d - 1)//M
|
| 2123 |
+
return n, d
|
| 2124 |
+
|
| 2125 |
+
|
| 2126 |
+
def encipher_kid_rsa(msg, key):
|
| 2127 |
+
"""
|
| 2128 |
+
Here ``msg`` is the plaintext and ``key`` is the public key.
|
| 2129 |
+
|
| 2130 |
+
Examples
|
| 2131 |
+
========
|
| 2132 |
+
|
| 2133 |
+
>>> from sympy.crypto.crypto import (
|
| 2134 |
+
... encipher_kid_rsa, kid_rsa_public_key)
|
| 2135 |
+
>>> msg = 200
|
| 2136 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
| 2137 |
+
>>> key = kid_rsa_public_key(a, b, A, B)
|
| 2138 |
+
>>> encipher_kid_rsa(msg, key)
|
| 2139 |
+
161
|
| 2140 |
+
|
| 2141 |
+
"""
|
| 2142 |
+
n, e = key
|
| 2143 |
+
return (msg*e) % n
|
| 2144 |
+
|
| 2145 |
+
|
| 2146 |
+
def decipher_kid_rsa(msg, key):
|
| 2147 |
+
"""
|
| 2148 |
+
Here ``msg`` is the plaintext and ``key`` is the private key.
|
| 2149 |
+
|
| 2150 |
+
Examples
|
| 2151 |
+
========
|
| 2152 |
+
|
| 2153 |
+
>>> from sympy.crypto.crypto import (
|
| 2154 |
+
... kid_rsa_public_key, kid_rsa_private_key,
|
| 2155 |
+
... decipher_kid_rsa, encipher_kid_rsa)
|
| 2156 |
+
>>> a, b, A, B = 3, 4, 5, 6
|
| 2157 |
+
>>> d = kid_rsa_private_key(a, b, A, B)
|
| 2158 |
+
>>> msg = 200
|
| 2159 |
+
>>> pub = kid_rsa_public_key(a, b, A, B)
|
| 2160 |
+
>>> pri = kid_rsa_private_key(a, b, A, B)
|
| 2161 |
+
>>> ct = encipher_kid_rsa(msg, pub)
|
| 2162 |
+
>>> decipher_kid_rsa(ct, pri)
|
| 2163 |
+
200
|
| 2164 |
+
|
| 2165 |
+
"""
|
| 2166 |
+
n, d = key
|
| 2167 |
+
return (msg*d) % n
|
| 2168 |
+
|
| 2169 |
+
|
| 2170 |
+
#################### Morse Code ######################################
|
| 2171 |
+
|
| 2172 |
+
morse_char = {
|
| 2173 |
+
".-": "A", "-...": "B",
|
| 2174 |
+
"-.-.": "C", "-..": "D",
|
| 2175 |
+
".": "E", "..-.": "F",
|
| 2176 |
+
"--.": "G", "....": "H",
|
| 2177 |
+
"..": "I", ".---": "J",
|
| 2178 |
+
"-.-": "K", ".-..": "L",
|
| 2179 |
+
"--": "M", "-.": "N",
|
| 2180 |
+
"---": "O", ".--.": "P",
|
| 2181 |
+
"--.-": "Q", ".-.": "R",
|
| 2182 |
+
"...": "S", "-": "T",
|
| 2183 |
+
"..-": "U", "...-": "V",
|
| 2184 |
+
".--": "W", "-..-": "X",
|
| 2185 |
+
"-.--": "Y", "--..": "Z",
|
| 2186 |
+
"-----": "0", ".----": "1",
|
| 2187 |
+
"..---": "2", "...--": "3",
|
| 2188 |
+
"....-": "4", ".....": "5",
|
| 2189 |
+
"-....": "6", "--...": "7",
|
| 2190 |
+
"---..": "8", "----.": "9",
|
| 2191 |
+
".-.-.-": ".", "--..--": ",",
|
| 2192 |
+
"---...": ":", "-.-.-.": ";",
|
| 2193 |
+
"..--..": "?", "-....-": "-",
|
| 2194 |
+
"..--.-": "_", "-.--.": "(",
|
| 2195 |
+
"-.--.-": ")", ".----.": "'",
|
| 2196 |
+
"-...-": "=", ".-.-.": "+",
|
| 2197 |
+
"-..-.": "/", ".--.-.": "@",
|
| 2198 |
+
"...-..-": "$", "-.-.--": "!"}
|
| 2199 |
+
char_morse = {v: k for k, v in morse_char.items()}
|
| 2200 |
+
|
| 2201 |
+
|
| 2202 |
+
def encode_morse(msg, sep='|', mapping=None):
|
| 2203 |
+
"""
|
| 2204 |
+
Encodes a plaintext into popular Morse Code with letters
|
| 2205 |
+
separated by ``sep`` and words by a double ``sep``.
|
| 2206 |
+
|
| 2207 |
+
Examples
|
| 2208 |
+
========
|
| 2209 |
+
|
| 2210 |
+
>>> from sympy.crypto.crypto import encode_morse
|
| 2211 |
+
>>> msg = 'ATTACK RIGHT FLANK'
|
| 2212 |
+
>>> encode_morse(msg)
|
| 2213 |
+
'.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-'
|
| 2214 |
+
|
| 2215 |
+
References
|
| 2216 |
+
==========
|
| 2217 |
+
|
| 2218 |
+
.. [1] https://en.wikipedia.org/wiki/Morse_code
|
| 2219 |
+
|
| 2220 |
+
"""
|
| 2221 |
+
|
| 2222 |
+
mapping = mapping or char_morse
|
| 2223 |
+
assert sep not in mapping
|
| 2224 |
+
word_sep = 2*sep
|
| 2225 |
+
mapping[" "] = word_sep
|
| 2226 |
+
suffix = msg and msg[-1] in whitespace
|
| 2227 |
+
|
| 2228 |
+
# normalize whitespace
|
| 2229 |
+
msg = (' ' if word_sep else '').join(msg.split())
|
| 2230 |
+
# omit unmapped chars
|
| 2231 |
+
chars = set(''.join(msg.split()))
|
| 2232 |
+
ok = set(mapping.keys())
|
| 2233 |
+
msg = translate(msg, None, ''.join(chars - ok))
|
| 2234 |
+
|
| 2235 |
+
morsestring = []
|
| 2236 |
+
words = msg.split()
|
| 2237 |
+
for word in words:
|
| 2238 |
+
morseword = []
|
| 2239 |
+
for letter in word:
|
| 2240 |
+
morseletter = mapping[letter]
|
| 2241 |
+
morseword.append(morseletter)
|
| 2242 |
+
|
| 2243 |
+
word = sep.join(morseword)
|
| 2244 |
+
morsestring.append(word)
|
| 2245 |
+
|
| 2246 |
+
return word_sep.join(morsestring) + (word_sep if suffix else '')
|
| 2247 |
+
|
| 2248 |
+
|
| 2249 |
+
def decode_morse(msg, sep='|', mapping=None):
|
| 2250 |
+
"""
|
| 2251 |
+
Decodes a Morse Code with letters separated by ``sep``
|
| 2252 |
+
(default is '|') and words by `word_sep` (default is '||)
|
| 2253 |
+
into plaintext.
|
| 2254 |
+
|
| 2255 |
+
Examples
|
| 2256 |
+
========
|
| 2257 |
+
|
| 2258 |
+
>>> from sympy.crypto.crypto import decode_morse
|
| 2259 |
+
>>> mc = '--|---|...-|.||.|.-|...|-'
|
| 2260 |
+
>>> decode_morse(mc)
|
| 2261 |
+
'MOVE EAST'
|
| 2262 |
+
|
| 2263 |
+
References
|
| 2264 |
+
==========
|
| 2265 |
+
|
| 2266 |
+
.. [1] https://en.wikipedia.org/wiki/Morse_code
|
| 2267 |
+
|
| 2268 |
+
"""
|
| 2269 |
+
|
| 2270 |
+
mapping = mapping or morse_char
|
| 2271 |
+
word_sep = 2*sep
|
| 2272 |
+
characterstring = []
|
| 2273 |
+
words = msg.strip(word_sep).split(word_sep)
|
| 2274 |
+
for word in words:
|
| 2275 |
+
letters = word.split(sep)
|
| 2276 |
+
chars = [mapping[c] for c in letters]
|
| 2277 |
+
word = ''.join(chars)
|
| 2278 |
+
characterstring.append(word)
|
| 2279 |
+
rv = " ".join(characterstring)
|
| 2280 |
+
return rv
|
| 2281 |
+
|
| 2282 |
+
|
| 2283 |
+
#################### LFSRs ##########################################
|
| 2284 |
+
|
| 2285 |
+
|
| 2286 |
+
def lfsr_sequence(key, fill, n):
|
| 2287 |
+
r"""
|
| 2288 |
+
This function creates an LFSR sequence.
|
| 2289 |
+
|
| 2290 |
+
Parameters
|
| 2291 |
+
==========
|
| 2292 |
+
|
| 2293 |
+
key : list
|
| 2294 |
+
A list of finite field elements, `[c_0, c_1, \ldots, c_k].`
|
| 2295 |
+
|
| 2296 |
+
fill : list
|
| 2297 |
+
The list of the initial terms of the LFSR sequence,
|
| 2298 |
+
`[x_0, x_1, \ldots, x_k].`
|
| 2299 |
+
|
| 2300 |
+
n
|
| 2301 |
+
Number of terms of the sequence that the function returns.
|
| 2302 |
+
|
| 2303 |
+
Returns
|
| 2304 |
+
=======
|
| 2305 |
+
|
| 2306 |
+
L
|
| 2307 |
+
The LFSR sequence defined by
|
| 2308 |
+
`x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for
|
| 2309 |
+
`n \leq k`.
|
| 2310 |
+
|
| 2311 |
+
Notes
|
| 2312 |
+
=====
|
| 2313 |
+
|
| 2314 |
+
S. Golomb [G]_ gives a list of three statistical properties a
|
| 2315 |
+
sequence of numbers `a = \{a_n\}_{n=1}^\infty`,
|
| 2316 |
+
`a_n \in \{0,1\}`, should display to be considered
|
| 2317 |
+
"random". Define the autocorrelation of `a` to be
|
| 2318 |
+
|
| 2319 |
+
.. math::
|
| 2320 |
+
|
| 2321 |
+
C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}.
|
| 2322 |
+
|
| 2323 |
+
In the case where `a` is periodic with period
|
| 2324 |
+
`P` then this reduces to
|
| 2325 |
+
|
| 2326 |
+
.. math::
|
| 2327 |
+
|
| 2328 |
+
C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}.
|
| 2329 |
+
|
| 2330 |
+
Assume `a` is periodic with period `P`.
|
| 2331 |
+
|
| 2332 |
+
- balance:
|
| 2333 |
+
|
| 2334 |
+
.. math::
|
| 2335 |
+
|
| 2336 |
+
\left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1.
|
| 2337 |
+
|
| 2338 |
+
- low autocorrelation:
|
| 2339 |
+
|
| 2340 |
+
.. math::
|
| 2341 |
+
|
| 2342 |
+
C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right.
|
| 2343 |
+
|
| 2344 |
+
(For sequences satisfying these first two properties, it is known
|
| 2345 |
+
that `\epsilon = -1/P` must hold.)
|
| 2346 |
+
|
| 2347 |
+
- proportional runs property: In each period, half the runs have
|
| 2348 |
+
length `1`, one-fourth have length `2`, etc.
|
| 2349 |
+
Moreover, there are as many runs of `1`'s as there are of
|
| 2350 |
+
`0`'s.
|
| 2351 |
+
|
| 2352 |
+
Examples
|
| 2353 |
+
========
|
| 2354 |
+
|
| 2355 |
+
>>> from sympy.crypto.crypto import lfsr_sequence
|
| 2356 |
+
>>> from sympy.polys.domains import FF
|
| 2357 |
+
>>> F = FF(2)
|
| 2358 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
| 2359 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
| 2360 |
+
>>> lfsr_sequence(key, fill, 10)
|
| 2361 |
+
[1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2,
|
| 2362 |
+
1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2]
|
| 2363 |
+
|
| 2364 |
+
References
|
| 2365 |
+
==========
|
| 2366 |
+
|
| 2367 |
+
.. [G] Solomon Golomb, Shift register sequences, Aegean Park Press,
|
| 2368 |
+
Laguna Hills, Ca, 1967
|
| 2369 |
+
|
| 2370 |
+
"""
|
| 2371 |
+
if not isinstance(key, list):
|
| 2372 |
+
raise TypeError("key must be a list")
|
| 2373 |
+
if not isinstance(fill, list):
|
| 2374 |
+
raise TypeError("fill must be a list")
|
| 2375 |
+
p = key[0].mod
|
| 2376 |
+
F = FF(p)
|
| 2377 |
+
s = fill
|
| 2378 |
+
k = len(fill)
|
| 2379 |
+
L = []
|
| 2380 |
+
for i in range(n):
|
| 2381 |
+
s0 = s[:]
|
| 2382 |
+
L.append(s[0])
|
| 2383 |
+
s = s[1:k]
|
| 2384 |
+
x = sum([int(key[i]*s0[i]) for i in range(k)])
|
| 2385 |
+
s.append(F(x))
|
| 2386 |
+
return L # use [x.to_int() for x in L] for int version
|
| 2387 |
+
|
| 2388 |
+
|
| 2389 |
+
def lfsr_autocorrelation(L, P, k):
|
| 2390 |
+
"""
|
| 2391 |
+
This function computes the LFSR autocorrelation function.
|
| 2392 |
+
|
| 2393 |
+
Parameters
|
| 2394 |
+
==========
|
| 2395 |
+
|
| 2396 |
+
L
|
| 2397 |
+
A periodic sequence of elements of `GF(2)`.
|
| 2398 |
+
L must have length larger than P.
|
| 2399 |
+
|
| 2400 |
+
P
|
| 2401 |
+
The period of L.
|
| 2402 |
+
|
| 2403 |
+
k : int
|
| 2404 |
+
An integer `k` (`0 < k < P`).
|
| 2405 |
+
|
| 2406 |
+
Returns
|
| 2407 |
+
=======
|
| 2408 |
+
|
| 2409 |
+
autocorrelation
|
| 2410 |
+
The k-th value of the autocorrelation of the LFSR L.
|
| 2411 |
+
|
| 2412 |
+
Examples
|
| 2413 |
+
========
|
| 2414 |
+
|
| 2415 |
+
>>> from sympy.crypto.crypto import (
|
| 2416 |
+
... lfsr_sequence, lfsr_autocorrelation)
|
| 2417 |
+
>>> from sympy.polys.domains import FF
|
| 2418 |
+
>>> F = FF(2)
|
| 2419 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
| 2420 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
| 2421 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2422 |
+
>>> lfsr_autocorrelation(s, 15, 7)
|
| 2423 |
+
-1/15
|
| 2424 |
+
>>> lfsr_autocorrelation(s, 15, 0)
|
| 2425 |
+
1
|
| 2426 |
+
|
| 2427 |
+
"""
|
| 2428 |
+
if not isinstance(L, list):
|
| 2429 |
+
raise TypeError("L (=%s) must be a list" % L)
|
| 2430 |
+
P = int(P)
|
| 2431 |
+
k = int(k)
|
| 2432 |
+
L0 = L[:P] # slices makes a copy
|
| 2433 |
+
L1 = L0 + L0[:k]
|
| 2434 |
+
L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)]
|
| 2435 |
+
tot = sum(L2)
|
| 2436 |
+
return Rational(tot, P)
|
| 2437 |
+
|
| 2438 |
+
|
| 2439 |
+
def lfsr_connection_polynomial(s):
|
| 2440 |
+
"""
|
| 2441 |
+
This function computes the LFSR connection polynomial.
|
| 2442 |
+
|
| 2443 |
+
Parameters
|
| 2444 |
+
==========
|
| 2445 |
+
|
| 2446 |
+
s
|
| 2447 |
+
A sequence of elements of even length, with entries in a finite
|
| 2448 |
+
field.
|
| 2449 |
+
|
| 2450 |
+
Returns
|
| 2451 |
+
=======
|
| 2452 |
+
|
| 2453 |
+
C(x)
|
| 2454 |
+
The connection polynomial of a minimal LFSR yielding s.
|
| 2455 |
+
|
| 2456 |
+
This implements the algorithm in section 3 of J. L. Massey's
|
| 2457 |
+
article [M]_.
|
| 2458 |
+
|
| 2459 |
+
Examples
|
| 2460 |
+
========
|
| 2461 |
+
|
| 2462 |
+
>>> from sympy.crypto.crypto import (
|
| 2463 |
+
... lfsr_sequence, lfsr_connection_polynomial)
|
| 2464 |
+
>>> from sympy.polys.domains import FF
|
| 2465 |
+
>>> F = FF(2)
|
| 2466 |
+
>>> fill = [F(1), F(1), F(0), F(1)]
|
| 2467 |
+
>>> key = [F(1), F(0), F(0), F(1)]
|
| 2468 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2469 |
+
>>> lfsr_connection_polynomial(s)
|
| 2470 |
+
x**4 + x + 1
|
| 2471 |
+
>>> fill = [F(1), F(0), F(0), F(1)]
|
| 2472 |
+
>>> key = [F(1), F(1), F(0), F(1)]
|
| 2473 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2474 |
+
>>> lfsr_connection_polynomial(s)
|
| 2475 |
+
x**3 + 1
|
| 2476 |
+
>>> fill = [F(1), F(0), F(1)]
|
| 2477 |
+
>>> key = [F(1), F(1), F(0)]
|
| 2478 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2479 |
+
>>> lfsr_connection_polynomial(s)
|
| 2480 |
+
x**3 + x**2 + 1
|
| 2481 |
+
>>> fill = [F(1), F(0), F(1)]
|
| 2482 |
+
>>> key = [F(1), F(0), F(1)]
|
| 2483 |
+
>>> s = lfsr_sequence(key, fill, 20)
|
| 2484 |
+
>>> lfsr_connection_polynomial(s)
|
| 2485 |
+
x**3 + x + 1
|
| 2486 |
+
|
| 2487 |
+
References
|
| 2488 |
+
==========
|
| 2489 |
+
|
| 2490 |
+
.. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding."
|
| 2491 |
+
IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127,
|
| 2492 |
+
Jan 1969.
|
| 2493 |
+
|
| 2494 |
+
"""
|
| 2495 |
+
# Initialization:
|
| 2496 |
+
p = s[0].mod
|
| 2497 |
+
x = Symbol("x")
|
| 2498 |
+
C = 1*x**0
|
| 2499 |
+
B = 1*x**0
|
| 2500 |
+
m = 1
|
| 2501 |
+
b = 1*x**0
|
| 2502 |
+
L = 0
|
| 2503 |
+
N = 0
|
| 2504 |
+
while N < len(s):
|
| 2505 |
+
if L > 0:
|
| 2506 |
+
dC = Poly(C).degree()
|
| 2507 |
+
r = min(L + 1, dC + 1)
|
| 2508 |
+
coeffsC = [C.subs(x, 0)] + [C.coeff(x**i)
|
| 2509 |
+
for i in range(1, dC + 1)]
|
| 2510 |
+
d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int()
|
| 2511 |
+
for i in range(1, r)])) % p
|
| 2512 |
+
if L == 0:
|
| 2513 |
+
d = s[N].to_int()*x**0
|
| 2514 |
+
if d == 0:
|
| 2515 |
+
m += 1
|
| 2516 |
+
N += 1
|
| 2517 |
+
if d > 0:
|
| 2518 |
+
if 2*L > N:
|
| 2519 |
+
C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
|
| 2520 |
+
m += 1
|
| 2521 |
+
N += 1
|
| 2522 |
+
else:
|
| 2523 |
+
T = C
|
| 2524 |
+
C = (C - d*((b**(p - 2)) % p)*x**m*B).expand()
|
| 2525 |
+
L = N + 1 - L
|
| 2526 |
+
m = 1
|
| 2527 |
+
b = d
|
| 2528 |
+
B = T
|
| 2529 |
+
N += 1
|
| 2530 |
+
dC = Poly(C).degree()
|
| 2531 |
+
coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)]
|
| 2532 |
+
return sum([coeffsC[i] % p*x**i for i in range(dC + 1)
|
| 2533 |
+
if coeffsC[i] is not None])
|
| 2534 |
+
|
| 2535 |
+
|
| 2536 |
+
#################### ElGamal #############################
|
| 2537 |
+
|
| 2538 |
+
|
| 2539 |
+
def elgamal_private_key(digit=10, seed=None):
|
| 2540 |
+
r"""
|
| 2541 |
+
Return three number tuple as private key.
|
| 2542 |
+
|
| 2543 |
+
Explanation
|
| 2544 |
+
===========
|
| 2545 |
+
|
| 2546 |
+
Elgamal encryption is based on the mathematical problem
|
| 2547 |
+
called the Discrete Logarithm Problem (DLP). For example,
|
| 2548 |
+
|
| 2549 |
+
`a^{b} \equiv c \pmod p`
|
| 2550 |
+
|
| 2551 |
+
In general, if ``a`` and ``b`` are known, ``ct`` is easily
|
| 2552 |
+
calculated. If ``b`` is unknown, it is hard to use
|
| 2553 |
+
``a`` and ``ct`` to get ``b``.
|
| 2554 |
+
|
| 2555 |
+
Parameters
|
| 2556 |
+
==========
|
| 2557 |
+
|
| 2558 |
+
digit : int
|
| 2559 |
+
Minimum number of binary digits for key.
|
| 2560 |
+
|
| 2561 |
+
Returns
|
| 2562 |
+
=======
|
| 2563 |
+
|
| 2564 |
+
tuple : (p, r, d)
|
| 2565 |
+
p = prime number.
|
| 2566 |
+
|
| 2567 |
+
r = primitive root.
|
| 2568 |
+
|
| 2569 |
+
d = random number.
|
| 2570 |
+
|
| 2571 |
+
Notes
|
| 2572 |
+
=====
|
| 2573 |
+
|
| 2574 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
| 2575 |
+
the output of this routine. See sympy.core.random._randrange.
|
| 2576 |
+
|
| 2577 |
+
Examples
|
| 2578 |
+
========
|
| 2579 |
+
|
| 2580 |
+
>>> from sympy.crypto.crypto import elgamal_private_key
|
| 2581 |
+
>>> from sympy.ntheory import is_primitive_root, isprime
|
| 2582 |
+
>>> a, b, _ = elgamal_private_key()
|
| 2583 |
+
>>> isprime(a)
|
| 2584 |
+
True
|
| 2585 |
+
>>> is_primitive_root(b, a)
|
| 2586 |
+
True
|
| 2587 |
+
|
| 2588 |
+
"""
|
| 2589 |
+
randrange = _randrange(seed)
|
| 2590 |
+
p = nextprime(2**digit)
|
| 2591 |
+
return p, primitive_root(p), randrange(2, p)
|
| 2592 |
+
|
| 2593 |
+
|
| 2594 |
+
def elgamal_public_key(key):
|
| 2595 |
+
r"""
|
| 2596 |
+
Return three number tuple as public key.
|
| 2597 |
+
|
| 2598 |
+
Parameters
|
| 2599 |
+
==========
|
| 2600 |
+
|
| 2601 |
+
key : (p, r, e)
|
| 2602 |
+
Tuple generated by ``elgamal_private_key``.
|
| 2603 |
+
|
| 2604 |
+
Returns
|
| 2605 |
+
=======
|
| 2606 |
+
|
| 2607 |
+
tuple : (p, r, e)
|
| 2608 |
+
`e = r**d \bmod p`
|
| 2609 |
+
|
| 2610 |
+
`d` is a random number in private key.
|
| 2611 |
+
|
| 2612 |
+
Examples
|
| 2613 |
+
========
|
| 2614 |
+
|
| 2615 |
+
>>> from sympy.crypto.crypto import elgamal_public_key
|
| 2616 |
+
>>> elgamal_public_key((1031, 14, 636))
|
| 2617 |
+
(1031, 14, 212)
|
| 2618 |
+
|
| 2619 |
+
"""
|
| 2620 |
+
p, r, e = key
|
| 2621 |
+
return p, r, pow(r, e, p)
|
| 2622 |
+
|
| 2623 |
+
|
| 2624 |
+
def encipher_elgamal(i, key, seed=None):
|
| 2625 |
+
r"""
|
| 2626 |
+
Encrypt message with public key.
|
| 2627 |
+
|
| 2628 |
+
Explanation
|
| 2629 |
+
===========
|
| 2630 |
+
|
| 2631 |
+
``i`` is a plaintext message expressed as an integer.
|
| 2632 |
+
``key`` is public key (p, r, e). In order to encrypt
|
| 2633 |
+
a message, a random number ``a`` in ``range(2, p)``
|
| 2634 |
+
is generated and the encryped message is returned as
|
| 2635 |
+
`c_{1}` and `c_{2}` where:
|
| 2636 |
+
|
| 2637 |
+
`c_{1} \equiv r^{a} \pmod p`
|
| 2638 |
+
|
| 2639 |
+
`c_{2} \equiv m e^{a} \pmod p`
|
| 2640 |
+
|
| 2641 |
+
Parameters
|
| 2642 |
+
==========
|
| 2643 |
+
|
| 2644 |
+
msg
|
| 2645 |
+
int of encoded message.
|
| 2646 |
+
|
| 2647 |
+
key
|
| 2648 |
+
Public key.
|
| 2649 |
+
|
| 2650 |
+
Returns
|
| 2651 |
+
=======
|
| 2652 |
+
|
| 2653 |
+
tuple : (c1, c2)
|
| 2654 |
+
Encipher into two number.
|
| 2655 |
+
|
| 2656 |
+
Notes
|
| 2657 |
+
=====
|
| 2658 |
+
|
| 2659 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
| 2660 |
+
the output of this routine. See sympy.core.random._randrange.
|
| 2661 |
+
|
| 2662 |
+
Examples
|
| 2663 |
+
========
|
| 2664 |
+
|
| 2665 |
+
>>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key
|
| 2666 |
+
>>> pri = elgamal_private_key(5, seed=[3]); pri
|
| 2667 |
+
(37, 2, 3)
|
| 2668 |
+
>>> pub = elgamal_public_key(pri); pub
|
| 2669 |
+
(37, 2, 8)
|
| 2670 |
+
>>> msg = 36
|
| 2671 |
+
>>> encipher_elgamal(msg, pub, seed=[3])
|
| 2672 |
+
(8, 6)
|
| 2673 |
+
|
| 2674 |
+
"""
|
| 2675 |
+
p, r, e = key
|
| 2676 |
+
if i < 0 or i >= p:
|
| 2677 |
+
raise ValueError(
|
| 2678 |
+
'Message (%s) should be in range(%s)' % (i, p))
|
| 2679 |
+
randrange = _randrange(seed)
|
| 2680 |
+
a = randrange(2, p)
|
| 2681 |
+
return pow(r, a, p), i*pow(e, a, p) % p
|
| 2682 |
+
|
| 2683 |
+
|
| 2684 |
+
def decipher_elgamal(msg, key):
|
| 2685 |
+
r"""
|
| 2686 |
+
Decrypt message with private key.
|
| 2687 |
+
|
| 2688 |
+
`msg = (c_{1}, c_{2})`
|
| 2689 |
+
|
| 2690 |
+
`key = (p, r, d)`
|
| 2691 |
+
|
| 2692 |
+
According to extended Eucliden theorem,
|
| 2693 |
+
`u c_{1}^{d} + p n = 1`
|
| 2694 |
+
|
| 2695 |
+
`u \equiv 1/{{c_{1}}^d} \pmod p`
|
| 2696 |
+
|
| 2697 |
+
`u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p`
|
| 2698 |
+
|
| 2699 |
+
`\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p`
|
| 2700 |
+
|
| 2701 |
+
Examples
|
| 2702 |
+
========
|
| 2703 |
+
|
| 2704 |
+
>>> from sympy.crypto.crypto import decipher_elgamal
|
| 2705 |
+
>>> from sympy.crypto.crypto import encipher_elgamal
|
| 2706 |
+
>>> from sympy.crypto.crypto import elgamal_private_key
|
| 2707 |
+
>>> from sympy.crypto.crypto import elgamal_public_key
|
| 2708 |
+
|
| 2709 |
+
>>> pri = elgamal_private_key(5, seed=[3])
|
| 2710 |
+
>>> pub = elgamal_public_key(pri); pub
|
| 2711 |
+
(37, 2, 8)
|
| 2712 |
+
>>> msg = 17
|
| 2713 |
+
>>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg
|
| 2714 |
+
True
|
| 2715 |
+
|
| 2716 |
+
"""
|
| 2717 |
+
p, _, d = key
|
| 2718 |
+
c1, c2 = msg
|
| 2719 |
+
u = igcdex(c1**d, p)[0]
|
| 2720 |
+
return u * c2 % p
|
| 2721 |
+
|
| 2722 |
+
|
| 2723 |
+
################ Diffie-Hellman Key Exchange #########################
|
| 2724 |
+
|
| 2725 |
+
def dh_private_key(digit=10, seed=None):
|
| 2726 |
+
r"""
|
| 2727 |
+
Return three integer tuple as private key.
|
| 2728 |
+
|
| 2729 |
+
Explanation
|
| 2730 |
+
===========
|
| 2731 |
+
|
| 2732 |
+
Diffie-Hellman key exchange is based on the mathematical problem
|
| 2733 |
+
called the Discrete Logarithm Problem (see ElGamal).
|
| 2734 |
+
|
| 2735 |
+
Diffie-Hellman key exchange is divided into the following steps:
|
| 2736 |
+
|
| 2737 |
+
* Alice and Bob agree on a base that consist of a prime ``p``
|
| 2738 |
+
and a primitive root of ``p`` called ``g``
|
| 2739 |
+
* Alice choses a number ``a`` and Bob choses a number ``b`` where
|
| 2740 |
+
``a`` and ``b`` are random numbers in range `[2, p)`. These are
|
| 2741 |
+
their private keys.
|
| 2742 |
+
* Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends
|
| 2743 |
+
Alice `g^{b} \pmod p`
|
| 2744 |
+
* They both raise the received value to their secretly chosen
|
| 2745 |
+
number (``a`` or ``b``) and now have both as their shared key
|
| 2746 |
+
`g^{ab} \pmod p`
|
| 2747 |
+
|
| 2748 |
+
Parameters
|
| 2749 |
+
==========
|
| 2750 |
+
|
| 2751 |
+
digit
|
| 2752 |
+
Minimum number of binary digits required in key.
|
| 2753 |
+
|
| 2754 |
+
Returns
|
| 2755 |
+
=======
|
| 2756 |
+
|
| 2757 |
+
tuple : (p, g, a)
|
| 2758 |
+
p = prime number.
|
| 2759 |
+
|
| 2760 |
+
g = primitive root of p.
|
| 2761 |
+
|
| 2762 |
+
a = random number from 2 through p - 1.
|
| 2763 |
+
|
| 2764 |
+
Notes
|
| 2765 |
+
=====
|
| 2766 |
+
|
| 2767 |
+
For testing purposes, the ``seed`` parameter may be set to control
|
| 2768 |
+
the output of this routine. See sympy.core.random._randrange.
|
| 2769 |
+
|
| 2770 |
+
Examples
|
| 2771 |
+
========
|
| 2772 |
+
|
| 2773 |
+
>>> from sympy.crypto.crypto import dh_private_key
|
| 2774 |
+
>>> from sympy.ntheory import isprime, is_primitive_root
|
| 2775 |
+
>>> p, g, _ = dh_private_key()
|
| 2776 |
+
>>> isprime(p)
|
| 2777 |
+
True
|
| 2778 |
+
>>> is_primitive_root(g, p)
|
| 2779 |
+
True
|
| 2780 |
+
>>> p, g, _ = dh_private_key(5)
|
| 2781 |
+
>>> isprime(p)
|
| 2782 |
+
True
|
| 2783 |
+
>>> is_primitive_root(g, p)
|
| 2784 |
+
True
|
| 2785 |
+
|
| 2786 |
+
"""
|
| 2787 |
+
p = nextprime(2**digit)
|
| 2788 |
+
g = primitive_root(p)
|
| 2789 |
+
randrange = _randrange(seed)
|
| 2790 |
+
a = randrange(2, p)
|
| 2791 |
+
return p, g, a
|
| 2792 |
+
|
| 2793 |
+
|
| 2794 |
+
def dh_public_key(key):
|
| 2795 |
+
r"""
|
| 2796 |
+
Return three number tuple as public key.
|
| 2797 |
+
|
| 2798 |
+
This is the tuple that Alice sends to Bob.
|
| 2799 |
+
|
| 2800 |
+
Parameters
|
| 2801 |
+
==========
|
| 2802 |
+
|
| 2803 |
+
key : (p, g, a)
|
| 2804 |
+
A tuple generated by ``dh_private_key``.
|
| 2805 |
+
|
| 2806 |
+
Returns
|
| 2807 |
+
=======
|
| 2808 |
+
|
| 2809 |
+
tuple : int, int, int
|
| 2810 |
+
A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as
|
| 2811 |
+
parameters.s
|
| 2812 |
+
|
| 2813 |
+
Examples
|
| 2814 |
+
========
|
| 2815 |
+
|
| 2816 |
+
>>> from sympy.crypto.crypto import dh_private_key, dh_public_key
|
| 2817 |
+
>>> p, g, a = dh_private_key();
|
| 2818 |
+
>>> _p, _g, x = dh_public_key((p, g, a))
|
| 2819 |
+
>>> p == _p and g == _g
|
| 2820 |
+
True
|
| 2821 |
+
>>> x == pow(g, a, p)
|
| 2822 |
+
True
|
| 2823 |
+
|
| 2824 |
+
"""
|
| 2825 |
+
p, g, a = key
|
| 2826 |
+
return p, g, pow(g, a, p)
|
| 2827 |
+
|
| 2828 |
+
|
| 2829 |
+
def dh_shared_key(key, b):
|
| 2830 |
+
"""
|
| 2831 |
+
Return an integer that is the shared key.
|
| 2832 |
+
|
| 2833 |
+
This is what Bob and Alice can both calculate using the public
|
| 2834 |
+
keys they received from each other and their private keys.
|
| 2835 |
+
|
| 2836 |
+
Parameters
|
| 2837 |
+
==========
|
| 2838 |
+
|
| 2839 |
+
key : (p, g, x)
|
| 2840 |
+
Tuple `(p, g, x)` generated by ``dh_public_key``.
|
| 2841 |
+
|
| 2842 |
+
b
|
| 2843 |
+
Random number in the range of `2` to `p - 1`
|
| 2844 |
+
(Chosen by second key exchange member (Bob)).
|
| 2845 |
+
|
| 2846 |
+
Returns
|
| 2847 |
+
=======
|
| 2848 |
+
|
| 2849 |
+
int
|
| 2850 |
+
A shared key.
|
| 2851 |
+
|
| 2852 |
+
Examples
|
| 2853 |
+
========
|
| 2854 |
+
|
| 2855 |
+
>>> from sympy.crypto.crypto import (
|
| 2856 |
+
... dh_private_key, dh_public_key, dh_shared_key)
|
| 2857 |
+
>>> prk = dh_private_key();
|
| 2858 |
+
>>> p, g, x = dh_public_key(prk);
|
| 2859 |
+
>>> sk = dh_shared_key((p, g, x), 1000)
|
| 2860 |
+
>>> sk == pow(x, 1000, p)
|
| 2861 |
+
True
|
| 2862 |
+
|
| 2863 |
+
"""
|
| 2864 |
+
p, _, x = key
|
| 2865 |
+
if 1 >= b or b >= p:
|
| 2866 |
+
raise ValueError(filldedent('''
|
| 2867 |
+
Value of b should be greater 1 and less
|
| 2868 |
+
than prime %s.''' % p))
|
| 2869 |
+
|
| 2870 |
+
return pow(x, b, p)
|
| 2871 |
+
|
| 2872 |
+
|
| 2873 |
+
################ Goldwasser-Micali Encryption #########################
|
| 2874 |
+
|
| 2875 |
+
|
| 2876 |
+
def _legendre(a, p):
|
| 2877 |
+
"""
|
| 2878 |
+
Returns the legendre symbol of a and p
|
| 2879 |
+
assuming that p is a prime.
|
| 2880 |
+
|
| 2881 |
+
i.e. 1 if a is a quadratic residue mod p
|
| 2882 |
+
-1 if a is not a quadratic residue mod p
|
| 2883 |
+
0 if a is divisible by p
|
| 2884 |
+
|
| 2885 |
+
Parameters
|
| 2886 |
+
==========
|
| 2887 |
+
|
| 2888 |
+
a : int
|
| 2889 |
+
The number to test.
|
| 2890 |
+
|
| 2891 |
+
p : prime
|
| 2892 |
+
The prime to test ``a`` against.
|
| 2893 |
+
|
| 2894 |
+
Returns
|
| 2895 |
+
=======
|
| 2896 |
+
|
| 2897 |
+
int
|
| 2898 |
+
Legendre symbol (a / p).
|
| 2899 |
+
|
| 2900 |
+
"""
|
| 2901 |
+
sig = pow(a, (p - 1)//2, p)
|
| 2902 |
+
if sig == 1:
|
| 2903 |
+
return 1
|
| 2904 |
+
elif sig == 0:
|
| 2905 |
+
return 0
|
| 2906 |
+
else:
|
| 2907 |
+
return -1
|
| 2908 |
+
|
| 2909 |
+
|
| 2910 |
+
def _random_coprime_stream(n, seed=None):
|
| 2911 |
+
randrange = _randrange(seed)
|
| 2912 |
+
while True:
|
| 2913 |
+
y = randrange(n)
|
| 2914 |
+
if gcd(y, n) == 1:
|
| 2915 |
+
yield y
|
| 2916 |
+
|
| 2917 |
+
|
| 2918 |
+
def gm_private_key(p, q, a=None):
|
| 2919 |
+
r"""
|
| 2920 |
+
Check if ``p`` and ``q`` can be used as private keys for
|
| 2921 |
+
the Goldwasser-Micali encryption. The method works
|
| 2922 |
+
roughly as follows.
|
| 2923 |
+
|
| 2924 |
+
Explanation
|
| 2925 |
+
===========
|
| 2926 |
+
|
| 2927 |
+
#. Pick two large primes $p$ and $q$.
|
| 2928 |
+
#. Call their product $N$.
|
| 2929 |
+
#. Given a message as an integer $i$, write $i$ in its bit representation $b_0, \dots, b_n$.
|
| 2930 |
+
#. For each $k$,
|
| 2931 |
+
|
| 2932 |
+
if $b_k = 0$:
|
| 2933 |
+
let $a_k$ be a random square
|
| 2934 |
+
(quadratic residue) modulo $p q$
|
| 2935 |
+
such that ``jacobi_symbol(a, p*q) = 1``
|
| 2936 |
+
if $b_k = 1$:
|
| 2937 |
+
let $a_k$ be a random non-square
|
| 2938 |
+
(non-quadratic residue) modulo $p q$
|
| 2939 |
+
such that ``jacobi_symbol(a, p*q) = 1``
|
| 2940 |
+
|
| 2941 |
+
returns $\left[a_1, a_2, \dots\right]$
|
| 2942 |
+
|
| 2943 |
+
$b_k$ can be recovered by checking whether or not
|
| 2944 |
+
$a_k$ is a residue. And from the $b_k$'s, the message
|
| 2945 |
+
can be reconstructed.
|
| 2946 |
+
|
| 2947 |
+
The idea is that, while ``jacobi_symbol(a, p*q)``
|
| 2948 |
+
can be easily computed (and when it is equal to $-1$ will
|
| 2949 |
+
tell you that $a$ is not a square mod $p q$), quadratic
|
| 2950 |
+
residuosity modulo a composite number is hard to compute
|
| 2951 |
+
without knowing its factorization.
|
| 2952 |
+
|
| 2953 |
+
Moreover, approximately half the numbers coprime to $p q$ have
|
| 2954 |
+
:func:`~.jacobi_symbol` equal to $1$ . And among those, approximately half
|
| 2955 |
+
are residues and approximately half are not. This maximizes the
|
| 2956 |
+
entropy of the code.
|
| 2957 |
+
|
| 2958 |
+
Parameters
|
| 2959 |
+
==========
|
| 2960 |
+
|
| 2961 |
+
p, q, a
|
| 2962 |
+
Initialization variables.
|
| 2963 |
+
|
| 2964 |
+
Returns
|
| 2965 |
+
=======
|
| 2966 |
+
|
| 2967 |
+
tuple : (p, q)
|
| 2968 |
+
The input value ``p`` and ``q``.
|
| 2969 |
+
|
| 2970 |
+
Raises
|
| 2971 |
+
======
|
| 2972 |
+
|
| 2973 |
+
ValueError
|
| 2974 |
+
If ``p`` and ``q`` are not distinct odd primes.
|
| 2975 |
+
|
| 2976 |
+
"""
|
| 2977 |
+
if p == q:
|
| 2978 |
+
raise ValueError("expected distinct primes, "
|
| 2979 |
+
"got two copies of %i" % p)
|
| 2980 |
+
elif not isprime(p) or not isprime(q):
|
| 2981 |
+
raise ValueError("first two arguments must be prime, "
|
| 2982 |
+
"got %i of %i" % (p, q))
|
| 2983 |
+
elif p == 2 or q == 2:
|
| 2984 |
+
raise ValueError("first two arguments must not be even, "
|
| 2985 |
+
"got %i of %i" % (p, q))
|
| 2986 |
+
return p, q
|
| 2987 |
+
|
| 2988 |
+
|
| 2989 |
+
def gm_public_key(p, q, a=None, seed=None):
|
| 2990 |
+
"""
|
| 2991 |
+
Compute public keys for ``p`` and ``q``.
|
| 2992 |
+
Note that in Goldwasser-Micali Encryption,
|
| 2993 |
+
public keys are randomly selected.
|
| 2994 |
+
|
| 2995 |
+
Parameters
|
| 2996 |
+
==========
|
| 2997 |
+
|
| 2998 |
+
p, q, a : int, int, int
|
| 2999 |
+
Initialization variables.
|
| 3000 |
+
|
| 3001 |
+
Returns
|
| 3002 |
+
=======
|
| 3003 |
+
|
| 3004 |
+
tuple : (a, N)
|
| 3005 |
+
``a`` is the input ``a`` if it is not ``None`` otherwise
|
| 3006 |
+
some random integer coprime to ``p`` and ``q``.
|
| 3007 |
+
|
| 3008 |
+
``N`` is the product of ``p`` and ``q``.
|
| 3009 |
+
|
| 3010 |
+
"""
|
| 3011 |
+
|
| 3012 |
+
p, q = gm_private_key(p, q)
|
| 3013 |
+
N = p * q
|
| 3014 |
+
|
| 3015 |
+
if a is None:
|
| 3016 |
+
randrange = _randrange(seed)
|
| 3017 |
+
while True:
|
| 3018 |
+
a = randrange(N)
|
| 3019 |
+
if _legendre(a, p) == _legendre(a, q) == -1:
|
| 3020 |
+
break
|
| 3021 |
+
else:
|
| 3022 |
+
if _legendre(a, p) != -1 or _legendre(a, q) != -1:
|
| 3023 |
+
return False
|
| 3024 |
+
return (a, N)
|
| 3025 |
+
|
| 3026 |
+
|
| 3027 |
+
def encipher_gm(i, key, seed=None):
|
| 3028 |
+
"""
|
| 3029 |
+
Encrypt integer 'i' using public_key 'key'
|
| 3030 |
+
Note that gm uses random encryption.
|
| 3031 |
+
|
| 3032 |
+
Parameters
|
| 3033 |
+
==========
|
| 3034 |
+
|
| 3035 |
+
i : int
|
| 3036 |
+
The message to encrypt.
|
| 3037 |
+
|
| 3038 |
+
key : (a, N)
|
| 3039 |
+
The public key.
|
| 3040 |
+
|
| 3041 |
+
Returns
|
| 3042 |
+
=======
|
| 3043 |
+
|
| 3044 |
+
list : list of int
|
| 3045 |
+
The randomized encrypted message.
|
| 3046 |
+
|
| 3047 |
+
"""
|
| 3048 |
+
if i < 0:
|
| 3049 |
+
raise ValueError(
|
| 3050 |
+
"message must be a non-negative "
|
| 3051 |
+
"integer: got %d instead" % i)
|
| 3052 |
+
a, N = key
|
| 3053 |
+
bits = []
|
| 3054 |
+
while i > 0:
|
| 3055 |
+
bits.append(i % 2)
|
| 3056 |
+
i //= 2
|
| 3057 |
+
|
| 3058 |
+
gen = _random_coprime_stream(N, seed)
|
| 3059 |
+
rev = reversed(bits)
|
| 3060 |
+
encode = lambda b: next(gen)**2*pow(a, b) % N
|
| 3061 |
+
return [ encode(b) for b in rev ]
|
| 3062 |
+
|
| 3063 |
+
|
| 3064 |
+
|
| 3065 |
+
def decipher_gm(message, key):
|
| 3066 |
+
"""
|
| 3067 |
+
Decrypt message 'message' using public_key 'key'.
|
| 3068 |
+
|
| 3069 |
+
Parameters
|
| 3070 |
+
==========
|
| 3071 |
+
|
| 3072 |
+
message : list of int
|
| 3073 |
+
The randomized encrypted message.
|
| 3074 |
+
|
| 3075 |
+
key : (p, q)
|
| 3076 |
+
The private key.
|
| 3077 |
+
|
| 3078 |
+
Returns
|
| 3079 |
+
=======
|
| 3080 |
+
|
| 3081 |
+
int
|
| 3082 |
+
The encrypted message.
|
| 3083 |
+
|
| 3084 |
+
"""
|
| 3085 |
+
p, q = key
|
| 3086 |
+
res = lambda m, p: _legendre(m, p) > 0
|
| 3087 |
+
bits = [res(m, p) * res(m, q) for m in message]
|
| 3088 |
+
m = 0
|
| 3089 |
+
for b in bits:
|
| 3090 |
+
m <<= 1
|
| 3091 |
+
m += not b
|
| 3092 |
+
return m
|
| 3093 |
+
|
| 3094 |
+
|
| 3095 |
+
|
| 3096 |
+
########### RailFence Cipher #############
|
| 3097 |
+
|
| 3098 |
+
def encipher_railfence(message,rails):
|
| 3099 |
+
"""
|
| 3100 |
+
Performs Railfence Encryption on plaintext and returns ciphertext
|
| 3101 |
+
|
| 3102 |
+
Examples
|
| 3103 |
+
========
|
| 3104 |
+
|
| 3105 |
+
>>> from sympy.crypto.crypto import encipher_railfence
|
| 3106 |
+
>>> message = "hello world"
|
| 3107 |
+
>>> encipher_railfence(message,3)
|
| 3108 |
+
'horel ollwd'
|
| 3109 |
+
|
| 3110 |
+
Parameters
|
| 3111 |
+
==========
|
| 3112 |
+
|
| 3113 |
+
message : string, the message to encrypt.
|
| 3114 |
+
rails : int, the number of rails.
|
| 3115 |
+
|
| 3116 |
+
Returns
|
| 3117 |
+
=======
|
| 3118 |
+
|
| 3119 |
+
The Encrypted string message.
|
| 3120 |
+
|
| 3121 |
+
References
|
| 3122 |
+
==========
|
| 3123 |
+
.. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher
|
| 3124 |
+
|
| 3125 |
+
"""
|
| 3126 |
+
r = list(range(rails))
|
| 3127 |
+
p = cycle(r + r[-2:0:-1])
|
| 3128 |
+
return ''.join(sorted(message, key=lambda i: next(p)))
|
| 3129 |
+
|
| 3130 |
+
|
| 3131 |
+
def decipher_railfence(ciphertext,rails):
|
| 3132 |
+
"""
|
| 3133 |
+
Decrypt the message using the given rails
|
| 3134 |
+
|
| 3135 |
+
Examples
|
| 3136 |
+
========
|
| 3137 |
+
|
| 3138 |
+
>>> from sympy.crypto.crypto import decipher_railfence
|
| 3139 |
+
>>> decipher_railfence("horel ollwd",3)
|
| 3140 |
+
'hello world'
|
| 3141 |
+
|
| 3142 |
+
Parameters
|
| 3143 |
+
==========
|
| 3144 |
+
|
| 3145 |
+
message : string, the message to encrypt.
|
| 3146 |
+
rails : int, the number of rails.
|
| 3147 |
+
|
| 3148 |
+
Returns
|
| 3149 |
+
=======
|
| 3150 |
+
|
| 3151 |
+
The Decrypted string message.
|
| 3152 |
+
|
| 3153 |
+
"""
|
| 3154 |
+
r = list(range(rails))
|
| 3155 |
+
p = cycle(r + r[-2:0:-1])
|
| 3156 |
+
|
| 3157 |
+
idx = sorted(range(len(ciphertext)), key=lambda i: next(p))
|
| 3158 |
+
res = [''] * len(ciphertext)
|
| 3159 |
+
for i, c in zip(idx, ciphertext):
|
| 3160 |
+
res[i] = c
|
| 3161 |
+
return ''.join(res)
|
| 3162 |
+
|
| 3163 |
+
|
| 3164 |
+
################ Blum-Goldwasser cryptosystem #########################
|
| 3165 |
+
|
| 3166 |
+
def bg_private_key(p, q):
|
| 3167 |
+
"""
|
| 3168 |
+
Check if p and q can be used as private keys for
|
| 3169 |
+
the Blum-Goldwasser cryptosystem.
|
| 3170 |
+
|
| 3171 |
+
Explanation
|
| 3172 |
+
===========
|
| 3173 |
+
|
| 3174 |
+
The three necessary checks for p and q to pass
|
| 3175 |
+
so that they can be used as private keys:
|
| 3176 |
+
|
| 3177 |
+
1. p and q must both be prime
|
| 3178 |
+
2. p and q must be distinct
|
| 3179 |
+
3. p and q must be congruent to 3 mod 4
|
| 3180 |
+
|
| 3181 |
+
Parameters
|
| 3182 |
+
==========
|
| 3183 |
+
|
| 3184 |
+
p, q
|
| 3185 |
+
The keys to be checked.
|
| 3186 |
+
|
| 3187 |
+
Returns
|
| 3188 |
+
=======
|
| 3189 |
+
|
| 3190 |
+
p, q
|
| 3191 |
+
Input values.
|
| 3192 |
+
|
| 3193 |
+
Raises
|
| 3194 |
+
======
|
| 3195 |
+
|
| 3196 |
+
ValueError
|
| 3197 |
+
If p and q do not pass the above conditions.
|
| 3198 |
+
|
| 3199 |
+
"""
|
| 3200 |
+
|
| 3201 |
+
if not isprime(p) or not isprime(q):
|
| 3202 |
+
raise ValueError("the two arguments must be prime, "
|
| 3203 |
+
"got %i and %i" %(p, q))
|
| 3204 |
+
elif p == q:
|
| 3205 |
+
raise ValueError("the two arguments must be distinct, "
|
| 3206 |
+
"got two copies of %i. " %p)
|
| 3207 |
+
elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0:
|
| 3208 |
+
raise ValueError("the two arguments must be congruent to 3 mod 4, "
|
| 3209 |
+
"got %i and %i" %(p, q))
|
| 3210 |
+
return p, q
|
| 3211 |
+
|
| 3212 |
+
def bg_public_key(p, q):
|
| 3213 |
+
"""
|
| 3214 |
+
Calculates public keys from private keys.
|
| 3215 |
+
|
| 3216 |
+
Explanation
|
| 3217 |
+
===========
|
| 3218 |
+
|
| 3219 |
+
The function first checks the validity of
|
| 3220 |
+
private keys passed as arguments and
|
| 3221 |
+
then returns their product.
|
| 3222 |
+
|
| 3223 |
+
Parameters
|
| 3224 |
+
==========
|
| 3225 |
+
|
| 3226 |
+
p, q
|
| 3227 |
+
The private keys.
|
| 3228 |
+
|
| 3229 |
+
Returns
|
| 3230 |
+
=======
|
| 3231 |
+
|
| 3232 |
+
N
|
| 3233 |
+
The public key.
|
| 3234 |
+
|
| 3235 |
+
"""
|
| 3236 |
+
p, q = bg_private_key(p, q)
|
| 3237 |
+
N = p * q
|
| 3238 |
+
return N
|
| 3239 |
+
|
| 3240 |
+
def encipher_bg(i, key, seed=None):
|
| 3241 |
+
"""
|
| 3242 |
+
Encrypts the message using public key and seed.
|
| 3243 |
+
|
| 3244 |
+
Explanation
|
| 3245 |
+
===========
|
| 3246 |
+
|
| 3247 |
+
ALGORITHM:
|
| 3248 |
+
1. Encodes i as a string of L bits, m.
|
| 3249 |
+
2. Select a random element r, where 1 < r < key, and computes
|
| 3250 |
+
x = r^2 mod key.
|
| 3251 |
+
3. Use BBS pseudo-random number generator to generate L random bits, b,
|
| 3252 |
+
using the initial seed as x.
|
| 3253 |
+
4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L.
|
| 3254 |
+
5. x_L = x^(2^L) mod key.
|
| 3255 |
+
6. Return (c, x_L)
|
| 3256 |
+
|
| 3257 |
+
Parameters
|
| 3258 |
+
==========
|
| 3259 |
+
|
| 3260 |
+
i
|
| 3261 |
+
Message, a non-negative integer
|
| 3262 |
+
|
| 3263 |
+
key
|
| 3264 |
+
The public key
|
| 3265 |
+
|
| 3266 |
+
Returns
|
| 3267 |
+
=======
|
| 3268 |
+
|
| 3269 |
+
Tuple
|
| 3270 |
+
(encrypted_message, x_L)
|
| 3271 |
+
|
| 3272 |
+
Raises
|
| 3273 |
+
======
|
| 3274 |
+
|
| 3275 |
+
ValueError
|
| 3276 |
+
If i is negative.
|
| 3277 |
+
|
| 3278 |
+
"""
|
| 3279 |
+
|
| 3280 |
+
if i < 0:
|
| 3281 |
+
raise ValueError(
|
| 3282 |
+
"message must be a non-negative "
|
| 3283 |
+
"integer: got %d instead" % i)
|
| 3284 |
+
|
| 3285 |
+
enc_msg = []
|
| 3286 |
+
while i > 0:
|
| 3287 |
+
enc_msg.append(i % 2)
|
| 3288 |
+
i //= 2
|
| 3289 |
+
enc_msg.reverse()
|
| 3290 |
+
L = len(enc_msg)
|
| 3291 |
+
|
| 3292 |
+
r = _randint(seed)(2, key - 1)
|
| 3293 |
+
x = r**2 % key
|
| 3294 |
+
x_L = pow(int(x), int(2**L), int(key))
|
| 3295 |
+
|
| 3296 |
+
rand_bits = []
|
| 3297 |
+
for _ in range(L):
|
| 3298 |
+
rand_bits.append(x % 2)
|
| 3299 |
+
x = x**2 % key
|
| 3300 |
+
|
| 3301 |
+
encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)]
|
| 3302 |
+
|
| 3303 |
+
return (encrypt_msg, x_L)
|
| 3304 |
+
|
| 3305 |
+
def decipher_bg(message, key):
|
| 3306 |
+
"""
|
| 3307 |
+
Decrypts the message using private keys.
|
| 3308 |
+
|
| 3309 |
+
Explanation
|
| 3310 |
+
===========
|
| 3311 |
+
|
| 3312 |
+
ALGORITHM:
|
| 3313 |
+
1. Let, c be the encrypted message, y the second number received,
|
| 3314 |
+
and p and q be the private keys.
|
| 3315 |
+
2. Compute, r_p = y^((p+1)/4 ^ L) mod p and
|
| 3316 |
+
r_q = y^((q+1)/4 ^ L) mod q.
|
| 3317 |
+
3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N.
|
| 3318 |
+
4. From, recompute the bits using the BBS generator, as in the
|
| 3319 |
+
encryption algorithm.
|
| 3320 |
+
5. Compute original message by XORing c and b.
|
| 3321 |
+
|
| 3322 |
+
Parameters
|
| 3323 |
+
==========
|
| 3324 |
+
|
| 3325 |
+
message
|
| 3326 |
+
Tuple of encrypted message and a non-negative integer.
|
| 3327 |
+
|
| 3328 |
+
key
|
| 3329 |
+
Tuple of private keys.
|
| 3330 |
+
|
| 3331 |
+
Returns
|
| 3332 |
+
=======
|
| 3333 |
+
|
| 3334 |
+
orig_msg
|
| 3335 |
+
The original message
|
| 3336 |
+
|
| 3337 |
+
"""
|
| 3338 |
+
|
| 3339 |
+
p, q = key
|
| 3340 |
+
encrypt_msg, y = message
|
| 3341 |
+
public_key = p * q
|
| 3342 |
+
L = len(encrypt_msg)
|
| 3343 |
+
p_t = ((p + 1)/4)**L
|
| 3344 |
+
q_t = ((q + 1)/4)**L
|
| 3345 |
+
r_p = pow(int(y), int(p_t), int(p))
|
| 3346 |
+
r_q = pow(int(y), int(q_t), int(q))
|
| 3347 |
+
|
| 3348 |
+
x = (q * mod_inverse(q, p) * r_p + p * mod_inverse(p, q) * r_q) % public_key
|
| 3349 |
+
|
| 3350 |
+
orig_bits = []
|
| 3351 |
+
for _ in range(L):
|
| 3352 |
+
orig_bits.append(x % 2)
|
| 3353 |
+
x = x**2 % public_key
|
| 3354 |
+
|
| 3355 |
+
orig_msg = 0
|
| 3356 |
+
for (m, b) in zip(encrypt_msg, orig_bits):
|
| 3357 |
+
orig_msg = orig_msg * 2
|
| 3358 |
+
orig_msg += (m ^ b)
|
| 3359 |
+
|
| 3360 |
+
return orig_msg
|
shared/package-files/41/41bd50e0d1c86d224e72c67cbd406a68f4feb3a956a63f980f5908f4323a5dfa/blob
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def base64_len(s: bytes) -> int: ...
|
| 2 |
+
def header_encode(header, charset=..., keep_eols=..., maxlinelen=..., eol=...): ...
|
| 3 |
+
def encode(s, binary=..., maxlinelen=..., eol=...): ...
|
| 4 |
+
|
| 5 |
+
body_encode = encode
|
| 6 |
+
encodestring = encode
|
| 7 |
+
|
| 8 |
+
def decode(s, convert_eols=...): ...
|
| 9 |
+
|
| 10 |
+
body_decode = decode
|
| 11 |
+
decodestring = decode
|
shared/package-files/41/41c0462a4a7dfe05203ce3065dc7ee1aca9e0bb893d40006aeae590d7fa710aa/blob
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any, Generic
|
| 4 |
+
|
| 5 |
+
from narwhals._compliant import LazyExprNamespace
|
| 6 |
+
from narwhals._compliant.any_namespace import DateTimeNamespace
|
| 7 |
+
from narwhals._sql.typing import SQLExprT
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from narwhals._compliant.expr import NativeExpr
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SQLExprDateTimeNamesSpace(
|
| 14 |
+
LazyExprNamespace[SQLExprT], DateTimeNamespace[SQLExprT], Generic[SQLExprT]
|
| 15 |
+
):
|
| 16 |
+
def _function(self, name: str, *args: Any) -> NativeExpr:
|
| 17 |
+
return self.compliant._function(name, *args) # type: ignore[no-any-return]
|
| 18 |
+
|
| 19 |
+
def year(self) -> SQLExprT:
|
| 20 |
+
return self.compliant._with_elementwise(lambda expr: self._function("year", expr))
|
| 21 |
+
|
| 22 |
+
def month(self) -> SQLExprT:
|
| 23 |
+
return self.compliant._with_elementwise(
|
| 24 |
+
lambda expr: self._function("month", expr)
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def day(self) -> SQLExprT:
|
| 28 |
+
return self.compliant._with_elementwise(lambda expr: self._function("day", expr))
|
| 29 |
+
|
| 30 |
+
def hour(self) -> SQLExprT:
|
| 31 |
+
return self.compliant._with_elementwise(lambda expr: self._function("hour", expr))
|
| 32 |
+
|
| 33 |
+
def minute(self) -> SQLExprT:
|
| 34 |
+
return self.compliant._with_elementwise(
|
| 35 |
+
lambda expr: self._function("minute", expr)
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
def second(self) -> SQLExprT:
|
| 39 |
+
return self.compliant._with_elementwise(
|
| 40 |
+
lambda expr: self._function("second", expr)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
def ordinal_day(self) -> SQLExprT:
|
| 44 |
+
return self.compliant._with_elementwise(
|
| 45 |
+
lambda expr: self._function("dayofyear", expr)
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
def date(self) -> SQLExprT:
|
| 49 |
+
return self.compliant._with_elementwise(
|
| 50 |
+
lambda expr: self._function("to_date", expr)
|
| 51 |
+
)
|
shared/package-files/41/41c129c561275c7070edae8385a717253020bcf3700c79b35c5a44fc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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pylint: disable-msg=W0142
|
| 2 |
+
"""
|
| 3 |
+
Statistical power, solving for nobs, ... - trial version
|
| 4 |
+
|
| 5 |
+
Created on Sat Jan 12 21:48:06 2013
|
| 6 |
+
|
| 7 |
+
Author: Josef Perktold
|
| 8 |
+
|
| 9 |
+
Examples
|
| 10 |
+
--------
|
| 11 |
+
roundtrip - root with respect to all variables
|
| 12 |
+
|
| 13 |
+
calculated, desired
|
| 14 |
+
nobs 33.367204205 33.367204205
|
| 15 |
+
effect 0.5 0.5
|
| 16 |
+
alpha 0.05 0.05
|
| 17 |
+
power 0.8 0.8
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
TODO:
|
| 21 |
+
refactoring
|
| 22 |
+
- rename beta -> power, beta (type 2 error is beta = 1-power) DONE
|
| 23 |
+
- I think the current implementation can handle any kinds of extra keywords
|
| 24 |
+
(except for maybe raising meaningful exceptions
|
| 25 |
+
- streamline code, I think internally classes can be merged
|
| 26 |
+
how to extend to k-sample tests?
|
| 27 |
+
user interface for different tests that map to the same (internal) test class
|
| 28 |
+
- sequence of arguments might be inconsistent,
|
| 29 |
+
arg and/or kwds so python checks what's required and what can be None.
|
| 30 |
+
- templating for docstrings ?
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import warnings
|
| 36 |
+
|
| 37 |
+
import numpy as np
|
| 38 |
+
from scipy import optimize, special, stats
|
| 39 |
+
|
| 40 |
+
from statsmodels.graphics.utils import _import_mpl
|
| 41 |
+
from statsmodels.tools.rootfinding import brentq_expanding
|
| 42 |
+
from statsmodels.tools.validation import string_like
|
| 43 |
+
|
| 44 |
+
# Undocumented short form accepted for backwards compatibility by
|
| 45 |
+
# ttest_power, normal_power and normal_power_het. Deprecated in favor of
|
| 46 |
+
# the documented spelling.
|
| 47 |
+
_ALTERNATIVE_ALIASES = {"2s": "two-sided"}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def nct_cdf(x, df, nc):
|
| 51 |
+
return special.nctdtr(df, nc, x)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def nct_sf(x, df, nc):
|
| 55 |
+
return 1 - special.nctdtr(df, nc, x)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def ncf_cdf(x, dfn, dfd, nc):
|
| 59 |
+
return special.ncfdtr(dfn, dfd, nc, x)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def ncf_sf(x, dfn, dfd, nc):
|
| 63 |
+
return 1 - special.ncfdtr(dfn, dfd, nc, x)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def ncf_ppf(q, dfn, dfd, nc):
|
| 67 |
+
return special.ncfdtri(dfn, dfd, nc, q)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def ttest_power(effect_size, nobs, alpha, df=None, alternative="two-sided"):
|
| 71 |
+
"""
|
| 72 |
+
Calculate power of a ttest
|
| 73 |
+
|
| 74 |
+
Parameters
|
| 75 |
+
----------
|
| 76 |
+
effect_size : float
|
| 77 |
+
Standardized effect size, mean divided by the standard deviation.
|
| 78 |
+
nobs : int or float
|
| 79 |
+
Sample size, number of observations.
|
| 80 |
+
alpha : float in interval (0,1)
|
| 81 |
+
Significance level, e.g., 0.05, is the probability of a type I
|
| 82 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 83 |
+
df : int or float, optional
|
| 84 |
+
Degrees of freedom. By default this is None, and ``df = nobs - 1``
|
| 85 |
+
is used.
|
| 86 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 87 |
+
Extra argument to choose whether the power is calculated for a
|
| 88 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 89 |
+
either 'larger', 'smaller'.
|
| 90 |
+
|
| 91 |
+
Returns
|
| 92 |
+
-------
|
| 93 |
+
power : float
|
| 94 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 95 |
+
type II error. Power is the probability that the test correctly
|
| 96 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 97 |
+
"""
|
| 98 |
+
d = effect_size
|
| 99 |
+
if df is None:
|
| 100 |
+
df = nobs - 1
|
| 101 |
+
|
| 102 |
+
alternative = string_like(
|
| 103 |
+
alternative,
|
| 104 |
+
"alternative",
|
| 105 |
+
options=("two-sided", "larger", "smaller"),
|
| 106 |
+
lower=False,
|
| 107 |
+
deprecated=_ALTERNATIVE_ALIASES,
|
| 108 |
+
removed_after="0.16",
|
| 109 |
+
)
|
| 110 |
+
if alternative == "two-sided":
|
| 111 |
+
alpha_ = alpha / 2.0 # no inplace changes, does not work
|
| 112 |
+
else:
|
| 113 |
+
alpha_ = alpha
|
| 114 |
+
|
| 115 |
+
pow_ = 0
|
| 116 |
+
if alternative in ["two-sided", "larger"]:
|
| 117 |
+
crit_upp = stats.t.isf(alpha_, df)
|
| 118 |
+
# print crit_upp, df, d*np.sqrt(nobs)
|
| 119 |
+
# use private methods, generic methods return nan with negative d
|
| 120 |
+
if np.any(np.isnan(crit_upp)):
|
| 121 |
+
# avoid endless loop, https://github.com/scipy/scipy/issues/2667
|
| 122 |
+
pow_ = np.nan
|
| 123 |
+
else:
|
| 124 |
+
# pow_ = stats.nct._sf(crit_upp, df, d*np.sqrt(nobs))
|
| 125 |
+
# use scipy.special
|
| 126 |
+
pow_ = nct_sf(crit_upp, df, d * np.sqrt(nobs))
|
| 127 |
+
if alternative in ["two-sided", "smaller"]:
|
| 128 |
+
crit_low = stats.t.ppf(alpha_, df)
|
| 129 |
+
# print crit_low, df, d*np.sqrt(nobs)
|
| 130 |
+
if np.any(np.isnan(crit_low)):
|
| 131 |
+
pow_ = np.nan
|
| 132 |
+
else:
|
| 133 |
+
# pow_ += stats.nct._cdf(crit_low, df, d*np.sqrt(nobs))
|
| 134 |
+
pow_ += nct_cdf(crit_low, df, d * np.sqrt(nobs))
|
| 135 |
+
return pow_
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def normal_power(effect_size, nobs, alpha, alternative="two-sided", sigma=1.0):
|
| 139 |
+
"""
|
| 140 |
+
Calculate power of a normal distributed test statistic
|
| 141 |
+
|
| 142 |
+
Parameters
|
| 143 |
+
----------
|
| 144 |
+
effect_size : float
|
| 145 |
+
difference in the estimated means or statistics under the alternative
|
| 146 |
+
normalized by the standard deviation (without division by sqrt(nobs).
|
| 147 |
+
nobs : float or int
|
| 148 |
+
number of observations
|
| 149 |
+
alpha : float in interval (0,1)
|
| 150 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 151 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 152 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 153 |
+
extra argument to choose whether the power is calculated for a
|
| 154 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 155 |
+
either 'larger', 'smaller'.
|
| 156 |
+
sigma : float, optional
|
| 157 |
+
The standard deviation used to standardize the effect size.
|
| 158 |
+
|
| 159 |
+
Returns
|
| 160 |
+
-------
|
| 161 |
+
power : float
|
| 162 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 163 |
+
type II error. Power is the probability that the test correctly
|
| 164 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
d = effect_size
|
| 168 |
+
|
| 169 |
+
alternative = string_like(
|
| 170 |
+
alternative,
|
| 171 |
+
"alternative",
|
| 172 |
+
options=("two-sided", "larger", "smaller"),
|
| 173 |
+
lower=False,
|
| 174 |
+
deprecated=_ALTERNATIVE_ALIASES,
|
| 175 |
+
removed_after="0.16",
|
| 176 |
+
)
|
| 177 |
+
if alternative == "two-sided":
|
| 178 |
+
alpha_ = alpha / 2.0 # no inplace changes, does not work
|
| 179 |
+
else:
|
| 180 |
+
alpha_ = alpha
|
| 181 |
+
|
| 182 |
+
pow_ = 0
|
| 183 |
+
if alternative in ["two-sided", "larger"]:
|
| 184 |
+
crit = stats.norm.isf(alpha_)
|
| 185 |
+
pow_ = stats.norm.sf(crit - d * np.sqrt(nobs) / sigma)
|
| 186 |
+
if alternative in ["two-sided", "smaller"]:
|
| 187 |
+
crit = stats.norm.ppf(alpha_)
|
| 188 |
+
pow_ += stats.norm.cdf(crit - d * np.sqrt(nobs) / sigma)
|
| 189 |
+
return pow_
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def normal_power_het(
|
| 193 |
+
diff, nobs, alpha, std_null=1.0, std_alternative=None, alternative="two-sided"
|
| 194 |
+
):
|
| 195 |
+
"""
|
| 196 |
+
Calculate power of a normal distributed test statistic
|
| 197 |
+
|
| 198 |
+
This is a generalization of `normal_power` when variance under Null and
|
| 199 |
+
Alternative differ.
|
| 200 |
+
|
| 201 |
+
Parameters
|
| 202 |
+
----------
|
| 203 |
+
diff : float
|
| 204 |
+
difference in the estimated means or statistics under the alternative.
|
| 205 |
+
nobs : float or int
|
| 206 |
+
number of observations
|
| 207 |
+
alpha : float in interval (0,1)
|
| 208 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 209 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 210 |
+
std_null : float, optional
|
| 211 |
+
standard deviation under the Null hypothesis without division by
|
| 212 |
+
sqrt(nobs)
|
| 213 |
+
std_alternative : float, optional
|
| 214 |
+
standard deviation under the Alternative hypothesis without division
|
| 215 |
+
by sqrt(nobs). If None, ``std_alternative`` is set to the value of
|
| 216 |
+
``std_null``.
|
| 217 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 218 |
+
extra argument to choose whether the power is calculated for a
|
| 219 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 220 |
+
either 'larger', 'smaller'.
|
| 221 |
+
|
| 222 |
+
Returns
|
| 223 |
+
-------
|
| 224 |
+
power : float
|
| 225 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 226 |
+
type II error. Power is the probability that the test correctly
|
| 227 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
d = diff
|
| 231 |
+
if std_alternative is None:
|
| 232 |
+
std_alternative = std_null
|
| 233 |
+
|
| 234 |
+
alternative = string_like(
|
| 235 |
+
alternative,
|
| 236 |
+
"alternative",
|
| 237 |
+
options=("two-sided", "larger", "smaller"),
|
| 238 |
+
lower=False,
|
| 239 |
+
deprecated=_ALTERNATIVE_ALIASES,
|
| 240 |
+
removed_after="0.16",
|
| 241 |
+
)
|
| 242 |
+
if alternative == "two-sided":
|
| 243 |
+
alpha_ = alpha / 2.0 # no inplace changes, does not work
|
| 244 |
+
else:
|
| 245 |
+
alpha_ = alpha
|
| 246 |
+
|
| 247 |
+
std_ratio = std_null / std_alternative
|
| 248 |
+
pow_ = 0
|
| 249 |
+
if alternative in ["two-sided", "larger"]:
|
| 250 |
+
crit = stats.norm.isf(alpha_)
|
| 251 |
+
pow_ = stats.norm.sf(crit * std_ratio - d * np.sqrt(nobs) / std_alternative)
|
| 252 |
+
if alternative in ["two-sided", "smaller"]:
|
| 253 |
+
crit = stats.norm.ppf(alpha_)
|
| 254 |
+
pow_ += stats.norm.cdf(crit * std_ratio - d * np.sqrt(nobs) / std_alternative)
|
| 255 |
+
return pow_
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def normal_sample_size_one_tail(diff, power, alpha, std_null=1.0, std_alternative=None):
|
| 259 |
+
"""
|
| 260 |
+
Explicit sample size computation if only one tail is relevant
|
| 261 |
+
|
| 262 |
+
The sample size is based on the power in one tail assuming that the
|
| 263 |
+
alternative is in the tail where the test has power that increases
|
| 264 |
+
with sample size.
|
| 265 |
+
Use alpha/2 to compute the one tail approximation to the two-sided
|
| 266 |
+
test, i.e., consider only one tail of two-sided test.
|
| 267 |
+
|
| 268 |
+
Parameters
|
| 269 |
+
----------
|
| 270 |
+
diff : float
|
| 271 |
+
difference in the estimated means or statistics under the alternative.
|
| 272 |
+
power : float in interval (0,1)
|
| 273 |
+
power of the test, e.g., 0.8, is one minus the probability of a type II
|
| 274 |
+
error. Power is the probability that the test correctly rejects the
|
| 275 |
+
Null Hypothesis if the Alternative Hypothesis is true.
|
| 276 |
+
alpha : float in interval (0,1)
|
| 277 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 278 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 279 |
+
Note: alpha is used for one tail. Use alpha/2 for two-sided
|
| 280 |
+
alternative.
|
| 281 |
+
std_null : float, optional
|
| 282 |
+
standard deviation under the Null hypothesis without division by
|
| 283 |
+
sqrt(nobs)
|
| 284 |
+
std_alternative : float, optional
|
| 285 |
+
standard deviation under the Alternative hypothesis without division
|
| 286 |
+
by sqrt(nobs). Defaults to None. If None, ``std_alternative`` is set
|
| 287 |
+
to the value of ``std_null``.
|
| 288 |
+
|
| 289 |
+
Returns
|
| 290 |
+
-------
|
| 291 |
+
nobs : float
|
| 292 |
+
Sample size to achieve (at least) the desired power.
|
| 293 |
+
If the minimum power is satisfied for all positive sample sizes, then
|
| 294 |
+
``nobs`` will be zero. This will be the case when power <= alpha if
|
| 295 |
+
std_alternative is equal to std_null.
|
| 296 |
+
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
if std_alternative is None:
|
| 300 |
+
std_alternative = std_null
|
| 301 |
+
|
| 302 |
+
crit_power = stats.norm.isf(power)
|
| 303 |
+
crit = stats.norm.isf(alpha)
|
| 304 |
+
n1 = (np.maximum(crit * std_null - crit_power * std_alternative, 0) / diff) ** 2
|
| 305 |
+
return n1
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def ftest_anova_power(effect_size, nobs, alpha, k_groups=2, df=None):
|
| 309 |
+
"""
|
| 310 |
+
Power for ftest for one way anova with k equal sized groups
|
| 311 |
+
|
| 312 |
+
nobs total sample size, sum over all groups
|
| 313 |
+
|
| 314 |
+
should be general nobs observations, k_groups restrictions ???
|
| 315 |
+
|
| 316 |
+
Parameters
|
| 317 |
+
----------
|
| 318 |
+
effect_size : float
|
| 319 |
+
Standardized effect size, according to Cohen's f definition.
|
| 320 |
+
nobs : int or float
|
| 321 |
+
Total sample size, sum over all groups.
|
| 322 |
+
alpha : float in interval (0,1)
|
| 323 |
+
Significance level, e.g., 0.05, is the probability of a type I
|
| 324 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 325 |
+
k_groups : int, optional
|
| 326 |
+
Number of groups in the one-way ANOVA. Default is 2.
|
| 327 |
+
df : None
|
| 328 |
+
Unused. Included for compatibility; degrees of freedom are
|
| 329 |
+
computed internally from ``nobs`` and ``k_groups``.
|
| 330 |
+
|
| 331 |
+
Returns
|
| 332 |
+
-------
|
| 333 |
+
power : float
|
| 334 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 335 |
+
type II error. Power is the probability that the test correctly
|
| 336 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 337 |
+
"""
|
| 338 |
+
df_num = k_groups - 1
|
| 339 |
+
df_denom = nobs - k_groups
|
| 340 |
+
crit = stats.f.isf(alpha, df_num, df_denom)
|
| 341 |
+
pow_ = ncf_sf(crit, df_num, df_denom, effect_size**2 * nobs)
|
| 342 |
+
return pow_
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def ftest_power(effect_size, df2, df1, alpha, ncc=1):
|
| 346 |
+
"""
|
| 347 |
+
Calculate the power of a F-test
|
| 348 |
+
|
| 349 |
+
Parameters
|
| 350 |
+
----------
|
| 351 |
+
effect_size : float
|
| 352 |
+
The effect size is here Cohen's ``f``, the square root of ``f2``.
|
| 353 |
+
df2 : int or float
|
| 354 |
+
Denominator degrees of freedom.
|
| 355 |
+
This corresponds to the df_resid in Wald tests.
|
| 356 |
+
df1 : int or float
|
| 357 |
+
Numerator degrees of freedom.
|
| 358 |
+
This corresponds to the number of constraints in Wald tests.
|
| 359 |
+
alpha : float in interval (0,1)
|
| 360 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 361 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 362 |
+
ncc : int, optional
|
| 363 |
+
degrees of freedom correction for non-centrality parameter.
|
| 364 |
+
see Notes
|
| 365 |
+
|
| 366 |
+
Returns
|
| 367 |
+
-------
|
| 368 |
+
power : float
|
| 369 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 370 |
+
type II error. Power is the probability that the test correctly
|
| 371 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 372 |
+
|
| 373 |
+
Notes
|
| 374 |
+
-----
|
| 375 |
+
changed in 0.14: use df2, df1 instead of df_num, df_denom as arg names.
|
| 376 |
+
The latter had reversed meaning.
|
| 377 |
+
|
| 378 |
+
The sample size is given implicitly by ``df2`` with fixed number of
|
| 379 |
+
constraints given by numerator degrees of freedom ``df1``:
|
| 380 |
+
|
| 381 |
+
nobs = df2 + df1 + ncc
|
| 382 |
+
|
| 383 |
+
Set ncc=0 to match t-test, or f-test in LikelihoodModelResults.
|
| 384 |
+
ncc=1 matches the non-centrality parameter in R::pwr::pwr.f2.test
|
| 385 |
+
|
| 386 |
+
ftest_power with ncc=0 should also be correct for f_test in regression
|
| 387 |
+
models, with df_num (df1) as number of constraints and d_denom (df2) as
|
| 388 |
+
df_resid.
|
| 389 |
+
"""
|
| 390 |
+
df_num, df_denom = df1, df2
|
| 391 |
+
nc = effect_size**2 * (df_denom + df_num + ncc)
|
| 392 |
+
crit = stats.f.isf(alpha, df_num, df_denom)
|
| 393 |
+
# pow_ = stats.ncf.sf(crit, df_num, df_denom, nc)
|
| 394 |
+
# use scipy.special for ncf
|
| 395 |
+
pow_ = ncf_sf(crit, df_num, df_denom, nc)
|
| 396 |
+
return pow_ # , crit, nc
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def ftest_power_f2(effect_size, df_num, df_denom, alpha, ncc=1):
|
| 400 |
+
"""
|
| 401 |
+
Calculate the power of a F-test
|
| 402 |
+
|
| 403 |
+
Based on Cohen's `f^2` effect size.
|
| 404 |
+
|
| 405 |
+
This assumes
|
| 406 |
+
|
| 407 |
+
df_num : numerator degrees of freedom, (number of constraints)
|
| 408 |
+
df_denom : denominator degrees of freedom (df_resid in regression)
|
| 409 |
+
nobs = df_denom + df_num + ncc
|
| 410 |
+
nc = effect_size * nobs (noncentrality index)
|
| 411 |
+
|
| 412 |
+
Power is computed one-sided in the upper tail.
|
| 413 |
+
|
| 414 |
+
Parameters
|
| 415 |
+
----------
|
| 416 |
+
effect_size : float
|
| 417 |
+
Cohen's f2 effect size or noncentrality divided by nobs.
|
| 418 |
+
df_num : int or float
|
| 419 |
+
Numerator degrees of freedom.
|
| 420 |
+
This corresponds to the number of constraints in Wald tests.
|
| 421 |
+
df_denom : int or float
|
| 422 |
+
Denominator degrees of freedom.
|
| 423 |
+
This corresponds to the df_resid in Wald tests.
|
| 424 |
+
alpha : float in interval (0,1)
|
| 425 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 426 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 427 |
+
ncc : int, optional
|
| 428 |
+
degrees of freedom correction for non-centrality parameter.
|
| 429 |
+
see Notes
|
| 430 |
+
|
| 431 |
+
Returns
|
| 432 |
+
-------
|
| 433 |
+
power : float
|
| 434 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 435 |
+
type II error. Power is the probability that the test correctly
|
| 436 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 437 |
+
|
| 438 |
+
Notes
|
| 439 |
+
-----
|
| 440 |
+
The sample size is given implicitly by ``df_denom`` with fixed number of
|
| 441 |
+
constraints given by numerator degrees of freedom ``df_num``:
|
| 442 |
+
|
| 443 |
+
nobs = df_denom + df_num + ncc
|
| 444 |
+
|
| 445 |
+
Set ncc=0 to match t-test, or f-test in LikelihoodModelResults.
|
| 446 |
+
ncc=1 matches the non-centrality parameter in R::pwr::pwr.f2.test
|
| 447 |
+
|
| 448 |
+
ftest_power with ncc=0 should also be correct for f_test in regression
|
| 449 |
+
models, with df_num (df1) as number of constraints and d_denom (df2) as
|
| 450 |
+
df_resid.
|
| 451 |
+
"""
|
| 452 |
+
|
| 453 |
+
nc = effect_size * (df_denom + df_num + ncc)
|
| 454 |
+
crit = stats.f.isf(alpha, df_num, df_denom)
|
| 455 |
+
# pow_ = stats.ncf.sf(crit, df_num, df_denom, nc)
|
| 456 |
+
# use scipy.special for ncf
|
| 457 |
+
pow_ = ncf_sf(crit, df_num, df_denom, nc)
|
| 458 |
+
return pow_
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
# class based implementation
|
| 462 |
+
# --------------------------
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
class Power:
|
| 466 |
+
"""
|
| 467 |
+
Statistical Power calculations, Base Class
|
| 468 |
+
|
| 469 |
+
so far this could all be class methods
|
| 470 |
+
"""
|
| 471 |
+
|
| 472 |
+
def __init__(self):
|
| 473 |
+
# Populated by `solve_power`; declared here so they exist (as
|
| 474 |
+
# None) even before `solve_power` has been called.
|
| 475 |
+
self._counter = None
|
| 476 |
+
self.cache_fit_res = None
|
| 477 |
+
|
| 478 |
+
# used only for instance level start values
|
| 479 |
+
self.start_ttp = {
|
| 480 |
+
"effect_size": 0.01,
|
| 481 |
+
"nobs": 10.0,
|
| 482 |
+
"alpha": 0.15,
|
| 483 |
+
"power": 0.6,
|
| 484 |
+
"nobs1": 10.0,
|
| 485 |
+
"ratio": 1,
|
| 486 |
+
"df_num": 10,
|
| 487 |
+
"df_denom": 3, # for FTestPower
|
| 488 |
+
}
|
| 489 |
+
# TODO: nobs1 and ratio are for ttest_ind,
|
| 490 |
+
# need start_ttp for each test/class separately,
|
| 491 |
+
# possible rootfinding problem for effect_size, starting small seems to
|
| 492 |
+
# work
|
| 493 |
+
from collections import defaultdict
|
| 494 |
+
|
| 495 |
+
self.start_bqexp = defaultdict(dict)
|
| 496 |
+
for key in ["nobs", "nobs1", "df_num", "df_denom"]:
|
| 497 |
+
self.start_bqexp[key] = {"low": 2.0, "start_upp": 50.0}
|
| 498 |
+
for key in ["df_denom"]:
|
| 499 |
+
self.start_bqexp[key] = {"low": 1.0, "start_upp": 50.0}
|
| 500 |
+
for key in ["ratio"]:
|
| 501 |
+
self.start_bqexp[key] = {"low": 1e-8, "start_upp": 2}
|
| 502 |
+
for key in ["alpha"]:
|
| 503 |
+
self.start_bqexp[key] = {"low": 1e-12, "upp": 1 - 1e-12}
|
| 504 |
+
|
| 505 |
+
def power(self, *args, **kwds):
|
| 506 |
+
raise NotImplementedError
|
| 507 |
+
|
| 508 |
+
def _power_identity(self, *args, **kwds):
|
| 509 |
+
power_ = kwds.pop("power")
|
| 510 |
+
return self.power(*args, **kwds) - power_
|
| 511 |
+
|
| 512 |
+
def solve_power(self, **kwds):
|
| 513 |
+
"""
|
| 514 |
+
Solve for any one of the parameters of a t-test
|
| 515 |
+
|
| 516 |
+
for t-test the keywords are:
|
| 517 |
+
effect_size, nobs, alpha, power
|
| 518 |
+
|
| 519 |
+
exactly one needs to be ``None``, all others need numeric values
|
| 520 |
+
|
| 521 |
+
Parameters
|
| 522 |
+
----------
|
| 523 |
+
**kwds
|
| 524 |
+
The keyword arguments of the power function for the specific
|
| 525 |
+
test, exactly one of which must be ``None``; the others must
|
| 526 |
+
be given numeric values.
|
| 527 |
+
|
| 528 |
+
Returns
|
| 529 |
+
-------
|
| 530 |
+
value : float
|
| 531 |
+
The value of the parameter that was set to None in the call.
|
| 532 |
+
The value solves the power equation given the remaining
|
| 533 |
+
parameters.
|
| 534 |
+
|
| 535 |
+
Notes
|
| 536 |
+
-----
|
| 537 |
+
This method attaches the following to the instance:
|
| 538 |
+
|
| 539 |
+
cache_fit_res : list
|
| 540 |
+
Cache of the result of the root finding procedure for the latest
|
| 541 |
+
call to ``solve_power``, mainly for debugging purposes.
|
| 542 |
+
The first element is the success indicator, one if successful.
|
| 543 |
+
The remaining elements contain the return information of the up to
|
| 544 |
+
three solvers that have been tried.
|
| 545 |
+
|
| 546 |
+
"""
|
| 547 |
+
# TODO: maybe use explicit kwds,
|
| 548 |
+
# nicer but requires inspect? and not generic across tests
|
| 549 |
+
# I'm duplicating this in the subclass to get informative docstring
|
| 550 |
+
key = [k for k, v in kwds.items() if v is None]
|
| 551 |
+
# print kwds, key
|
| 552 |
+
if len(key) != 1:
|
| 553 |
+
raise ValueError("need exactly one keyword that is None")
|
| 554 |
+
key = key[0]
|
| 555 |
+
|
| 556 |
+
if key == "power":
|
| 557 |
+
del kwds["power"]
|
| 558 |
+
return self.power(**kwds)
|
| 559 |
+
|
| 560 |
+
if kwds["effect_size"] == 0:
|
| 561 |
+
import warnings
|
| 562 |
+
|
| 563 |
+
from statsmodels.tools.sm_exceptions import HypothesisTestWarning
|
| 564 |
+
|
| 565 |
+
warnings.warn(
|
| 566 |
+
"Warning: Effect size of 0 detected",
|
| 567 |
+
HypothesisTestWarning,
|
| 568 |
+
stacklevel=2,
|
| 569 |
+
)
|
| 570 |
+
if key == "power":
|
| 571 |
+
return kwds["alpha"]
|
| 572 |
+
if key == "alpha":
|
| 573 |
+
return kwds["power"]
|
| 574 |
+
else:
|
| 575 |
+
raise ValueError(
|
| 576 |
+
"Cannot detect an effect-size of 0. Try changing your effect-size."
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
# GH#9378 intercept impossible one-sided cases before root finding:
|
| 580 |
+
# if the effect size points into the tail opposite to the
|
| 581 |
+
# alternative, the attained power is smaller than alpha for any
|
| 582 |
+
# sample size, so no solution exists unless the requested power is
|
| 583 |
+
# also smaller than alpha.
|
| 584 |
+
alternative = kwds.get("alternative")
|
| 585 |
+
if key in ("nobs", "nobs1", "ratio") and alternative in (
|
| 586 |
+
"larger",
|
| 587 |
+
"smaller",
|
| 588 |
+
):
|
| 589 |
+
effect_size = kwds["effect_size"]
|
| 590 |
+
wrong_sign = (
|
| 591 |
+
effect_size < 0
|
| 592 |
+
if alternative == "larger"
|
| 593 |
+
else effect_size > 0
|
| 594 |
+
)
|
| 595 |
+
if wrong_sign and kwds["power"] >= kwds["alpha"]:
|
| 596 |
+
raise ValueError(
|
| 597 |
+
f"No solution exists for {key}: with alternative="
|
| 598 |
+
f"{alternative!r} the attained power is smaller than "
|
| 599 |
+
f"alpha for any {key} because effect_size is "
|
| 600 |
+
f"{'negative' if effect_size < 0 else 'positive'}. A "
|
| 601 |
+
"one-sided alternative requires an effect size with "
|
| 602 |
+
"matching sign: positive for 'larger', negative for "
|
| 603 |
+
"'smaller'."
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
self._counter = 0
|
| 607 |
+
|
| 608 |
+
def func(x):
|
| 609 |
+
kwds[key] = x
|
| 610 |
+
fval = self._power_identity(**kwds)
|
| 611 |
+
self._counter += 1
|
| 612 |
+
# print self._counter,
|
| 613 |
+
if self._counter > 500:
|
| 614 |
+
raise RuntimeError("possible endless loop (500 NaNs)")
|
| 615 |
+
if np.isnan(fval):
|
| 616 |
+
return np.inf
|
| 617 |
+
else:
|
| 618 |
+
return fval
|
| 619 |
+
|
| 620 |
+
# TODO: I'm using the following so I get a warning when start_ttp is not defined
|
| 621 |
+
try:
|
| 622 |
+
start_value = self.start_ttp[key]
|
| 623 |
+
except KeyError:
|
| 624 |
+
start_value = 0.9
|
| 625 |
+
import warnings
|
| 626 |
+
|
| 627 |
+
from statsmodels.tools.sm_exceptions import ValueWarning
|
| 628 |
+
|
| 629 |
+
warnings.warn(
|
| 630 |
+
f"Warning: using default start_value for {key}",
|
| 631 |
+
ValueWarning,
|
| 632 |
+
stacklevel=2,
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
fit_kwds = self.start_bqexp[key]
|
| 636 |
+
fit_res = []
|
| 637 |
+
# print vars()
|
| 638 |
+
# ensure ``val`` is bound for the warning below even if the first
|
| 639 |
+
# solver raises before assigning it and no backup solver runs
|
| 640 |
+
val = np.nan
|
| 641 |
+
try:
|
| 642 |
+
val, res = brentq_expanding(func, full_output=True, **fit_kwds)
|
| 643 |
+
failed = False
|
| 644 |
+
fit_res.append(res)
|
| 645 |
+
except ValueError:
|
| 646 |
+
failed = True
|
| 647 |
+
fit_res.append(None)
|
| 648 |
+
|
| 649 |
+
success = None
|
| 650 |
+
if (not failed) and res.converged:
|
| 651 |
+
success = 1
|
| 652 |
+
else:
|
| 653 |
+
# try backup
|
| 654 |
+
# TODO: check more cases to make this robust
|
| 655 |
+
if not np.isnan(start_value):
|
| 656 |
+
val, infodict, ier, msg = optimize.fsolve(
|
| 657 |
+
func, start_value, full_output=True
|
| 658 |
+
) # scalar
|
| 659 |
+
# val = optimize.newton(func, start_value) # scalar
|
| 660 |
+
fval = infodict["fvec"]
|
| 661 |
+
fit_res.append(infodict)
|
| 662 |
+
else:
|
| 663 |
+
ier = -1
|
| 664 |
+
fval = 1
|
| 665 |
+
fit_res.append([None])
|
| 666 |
+
|
| 667 |
+
if ier == 1 and np.abs(fval) < 1e-4:
|
| 668 |
+
success = 1
|
| 669 |
+
# print infodict
|
| 670 |
+
elif key in ["alpha", "power", "effect_size"]:
|
| 671 |
+
val, r = optimize.brentq(
|
| 672 |
+
func, 1e-8, 1 - 1e-8, full_output=True
|
| 673 |
+
) # scalar
|
| 674 |
+
success = 1 if r.converged else 0
|
| 675 |
+
fit_res.append(r)
|
| 676 |
+
else:
|
| 677 |
+
success = 0
|
| 678 |
+
|
| 679 |
+
if not success == 1:
|
| 680 |
+
import warnings
|
| 681 |
+
|
| 682 |
+
from statsmodels.tools.sm_exceptions import (
|
| 683 |
+
ConvergenceWarning,
|
| 684 |
+
convergence_doc,
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
# the root finder did not converge, so ``val`` is not a solution
|
| 688 |
+
# (it is the last point the solver evaluated, e.g., a bracket
|
| 689 |
+
# bound). Report it in the warning for diagnostics, but return
|
| 690 |
+
# nan instead so it cannot masquerade as a valid answer.
|
| 691 |
+
warnings.warn(
|
| 692 |
+
convergence_doc
|
| 693 |
+
+ f"The last value evaluated by the root finder was {val}; "
|
| 694 |
+
"returning nan instead. Solver details are stored in the "
|
| 695 |
+
"``cache_fit_res`` attribute.",
|
| 696 |
+
ConvergenceWarning,
|
| 697 |
+
stacklevel=2,
|
| 698 |
+
)
|
| 699 |
+
val = np.nan
|
| 700 |
+
|
| 701 |
+
# attach fit_res, for reading only, should be needed only for debugging
|
| 702 |
+
fit_res.insert(0, success)
|
| 703 |
+
self.cache_fit_res = fit_res
|
| 704 |
+
return val
|
| 705 |
+
|
| 706 |
+
def plot_power(
|
| 707 |
+
self,
|
| 708 |
+
dep_var="nobs",
|
| 709 |
+
nobs=None,
|
| 710 |
+
effect_size=None,
|
| 711 |
+
alpha=0.05,
|
| 712 |
+
ax=None,
|
| 713 |
+
title=None,
|
| 714 |
+
plt_kwds=None,
|
| 715 |
+
**kwds,
|
| 716 |
+
):
|
| 717 |
+
"""
|
| 718 |
+
Plot power with number of observations or effect size on x-axis
|
| 719 |
+
|
| 720 |
+
Parameters
|
| 721 |
+
----------
|
| 722 |
+
dep_var : {'nobs', 'effect_size', 'alpha'}, optional
|
| 723 |
+
This specifies which variable is used for the horizontal axis.
|
| 724 |
+
If dep_var='nobs' (default), then one curve is created for each
|
| 725 |
+
value of ``effect_size``. If dep_var='effect_size' or alpha, then
|
| 726 |
+
one curve is created for each value of ``nobs``.
|
| 727 |
+
nobs : array_like, optional
|
| 728 |
+
specifies the values of the number of observations in the plot
|
| 729 |
+
effect_size : array_like, optional
|
| 730 |
+
specifies the values of the effect_size in the plot
|
| 731 |
+
alpha : float or array_like, optional
|
| 732 |
+
The significance level (type I error) used in the power
|
| 733 |
+
calculation. Can only be more than a scalar, if ``dep_var='alpha'``
|
| 734 |
+
ax : AxesSubplot, optional
|
| 735 |
+
If ax is None, than a matplotlib figure is created. If ax is a
|
| 736 |
+
matplotlib axis instance, then it is reused, and the plot elements
|
| 737 |
+
are created with it.
|
| 738 |
+
title : str, optional
|
| 739 |
+
Title for the axis. Use an empty string, ``''``, to avoid a
|
| 740 |
+
title. If not given, the default title "Power of Test" is used.
|
| 741 |
+
plt_kwds : dict, optional
|
| 742 |
+
Not used yet.
|
| 743 |
+
**kwds
|
| 744 |
+
These remaining keyword arguments are used as arguments to the
|
| 745 |
+
power function. Many power functions support ``alternative`` as
|
| 746 |
+
a keyword argument, two-sample tests support ``ratio``.
|
| 747 |
+
|
| 748 |
+
Returns
|
| 749 |
+
-------
|
| 750 |
+
Figure
|
| 751 |
+
If `ax` is None, the created figure. Otherwise the figure to which
|
| 752 |
+
`ax` is connected.
|
| 753 |
+
|
| 754 |
+
Notes
|
| 755 |
+
-----
|
| 756 |
+
This works only for classes where the ``power`` method has
|
| 757 |
+
``effect_size``, ``nobs`` and ``alpha`` as the first three arguments.
|
| 758 |
+
If the second argument is ``nobs1``, then the number of observations
|
| 759 |
+
in the plot are those for the first sample.
|
| 760 |
+
TODO: fix this for FTestPower and GofChisquarePower
|
| 761 |
+
|
| 762 |
+
TODO: maybe add line variable, if we want more than nobs and effectsize
|
| 763 |
+
"""
|
| 764 |
+
# if pwr_kwds is None:
|
| 765 |
+
# pwr_kwds = {}
|
| 766 |
+
from statsmodels.graphics import utils
|
| 767 |
+
from statsmodels.graphics.plottools import rainbow
|
| 768 |
+
|
| 769 |
+
plt = _import_mpl()
|
| 770 |
+
fig, ax = utils.create_mpl_ax(ax)
|
| 771 |
+
|
| 772 |
+
colormap = plt.cm.Dark2 # pylint: disable-msg=E1101
|
| 773 |
+
plt_alpha = 1 # 0.75
|
| 774 |
+
lw = 2
|
| 775 |
+
if dep_var == "nobs":
|
| 776 |
+
colors = rainbow(len(effect_size))
|
| 777 |
+
colors = [colormap(i) for i in np.linspace(0, 0.9, len(effect_size))]
|
| 778 |
+
for ii, es in enumerate(effect_size):
|
| 779 |
+
power = self.power(es, nobs, alpha, **kwds)
|
| 780 |
+
ax.plot(
|
| 781 |
+
nobs,
|
| 782 |
+
power,
|
| 783 |
+
lw=lw,
|
| 784 |
+
alpha=plt_alpha,
|
| 785 |
+
color=colors[ii],
|
| 786 |
+
label=f"es={es:4.2F}",
|
| 787 |
+
)
|
| 788 |
+
xlabel = "Number of Observations"
|
| 789 |
+
elif dep_var in ["effect size", "effect_size", "es"]:
|
| 790 |
+
colors = rainbow(len(nobs))
|
| 791 |
+
colors = [colormap(i) for i in np.linspace(0, 0.9, len(nobs))]
|
| 792 |
+
for ii, n in enumerate(nobs):
|
| 793 |
+
power = self.power(effect_size, n, alpha, **kwds)
|
| 794 |
+
ax.plot(
|
| 795 |
+
effect_size,
|
| 796 |
+
power,
|
| 797 |
+
lw=lw,
|
| 798 |
+
alpha=plt_alpha,
|
| 799 |
+
color=colors[ii],
|
| 800 |
+
label=f"N={n:4.2F}",
|
| 801 |
+
)
|
| 802 |
+
xlabel = "Effect Size"
|
| 803 |
+
elif dep_var == "alpha":
|
| 804 |
+
# experimental nobs as defining separate lines
|
| 805 |
+
colors = rainbow(len(nobs))
|
| 806 |
+
|
| 807 |
+
for ii, n in enumerate(nobs):
|
| 808 |
+
power = self.power(effect_size, n, alpha, **kwds)
|
| 809 |
+
ax.plot(
|
| 810 |
+
alpha,
|
| 811 |
+
power,
|
| 812 |
+
lw=lw,
|
| 813 |
+
alpha=plt_alpha,
|
| 814 |
+
color=colors[ii],
|
| 815 |
+
label=f"N={n:4.2F}",
|
| 816 |
+
)
|
| 817 |
+
xlabel = "alpha"
|
| 818 |
+
else:
|
| 819 |
+
raise ValueError("depvar not implemented")
|
| 820 |
+
|
| 821 |
+
if title is None:
|
| 822 |
+
title = "Power of Test"
|
| 823 |
+
ax.set_xlabel(xlabel)
|
| 824 |
+
ax.set_title(title)
|
| 825 |
+
ax.legend(loc="lower right")
|
| 826 |
+
return fig
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
class TTestPower(Power):
|
| 830 |
+
"""Statistical Power calculations for one sample or paired sample t-test"""
|
| 831 |
+
|
| 832 |
+
def power(self, effect_size, nobs, alpha, df=None, alternative="two-sided"):
|
| 833 |
+
"""
|
| 834 |
+
Calculate the power of a t-test for one sample or paired samples
|
| 835 |
+
|
| 836 |
+
Parameters
|
| 837 |
+
----------
|
| 838 |
+
effect_size : float
|
| 839 |
+
standardized effect size, mean divided by the standard deviation.
|
| 840 |
+
effect size has to be positive.
|
| 841 |
+
nobs : int or float
|
| 842 |
+
sample size, number of observations.
|
| 843 |
+
alpha : float in interval (0,1)
|
| 844 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 845 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 846 |
+
df : int or float, optional
|
| 847 |
+
degrees of freedom. By default this is None, and the df from the
|
| 848 |
+
one sample or paired ttest is used, ``df = nobs1 - 1``
|
| 849 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 850 |
+
extra argument to choose whether the power is calculated for a
|
| 851 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 852 |
+
either 'larger', 'smaller'.
|
| 853 |
+
|
| 854 |
+
Returns
|
| 855 |
+
-------
|
| 856 |
+
power : float
|
| 857 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 858 |
+
type II error. Power is the probability that the test correctly
|
| 859 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 860 |
+
|
| 861 |
+
"""
|
| 862 |
+
# for debugging
|
| 863 |
+
# print 'calling ttest power with', (effect_size, nobs, alpha, df, alternative)
|
| 864 |
+
return ttest_power(effect_size, nobs, alpha, df=df, alternative=alternative)
|
| 865 |
+
|
| 866 |
+
# method is only added to have explicit keywords and docstring
|
| 867 |
+
def solve_power(
|
| 868 |
+
self,
|
| 869 |
+
effect_size=None,
|
| 870 |
+
nobs=None,
|
| 871 |
+
alpha=None,
|
| 872 |
+
power=None,
|
| 873 |
+
alternative="two-sided",
|
| 874 |
+
):
|
| 875 |
+
"""
|
| 876 |
+
Solve for any one parameter of the power of a one sample t-test
|
| 877 |
+
|
| 878 |
+
for the one sample t-test the keywords are:
|
| 879 |
+
effect_size, nobs, alpha, power
|
| 880 |
+
|
| 881 |
+
Exactly one needs to be ``None``, all others need numeric values.
|
| 882 |
+
|
| 883 |
+
This test can also be used for a paired t-test, where effect size is
|
| 884 |
+
defined in terms of the mean difference, and nobs is the number of
|
| 885 |
+
pairs.
|
| 886 |
+
|
| 887 |
+
Parameters
|
| 888 |
+
----------
|
| 889 |
+
effect_size : None or float
|
| 890 |
+
Standardized effect size, mean divided by the standard
|
| 891 |
+
deviation.
|
| 892 |
+
nobs : None or int or float
|
| 893 |
+
sample size, number of observations.
|
| 894 |
+
alpha : None or float in interval (0,1)
|
| 895 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 896 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 897 |
+
power : None or float in interval (0,1)
|
| 898 |
+
power of the test, e.g., 0.8, is one minus the probability of a
|
| 899 |
+
type II error. Power is the probability that the test correctly
|
| 900 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 901 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 902 |
+
extra argument to choose whether the power is calculated for a
|
| 903 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 904 |
+
either 'larger', 'smaller'.
|
| 905 |
+
|
| 906 |
+
Returns
|
| 907 |
+
-------
|
| 908 |
+
value : float
|
| 909 |
+
The value of the parameter that was set to None in the call. The
|
| 910 |
+
value solves the power equation given the remaining parameters.
|
| 911 |
+
|
| 912 |
+
Notes
|
| 913 |
+
-----
|
| 914 |
+
This method attaches the following to the instance:
|
| 915 |
+
|
| 916 |
+
cache_fit_res : list
|
| 917 |
+
Cache of the result of the root finding procedure for the latest
|
| 918 |
+
call to ``solve_power``, mainly for debugging purposes.
|
| 919 |
+
The first element is the success indicator, one if successful.
|
| 920 |
+
The remaining elements contain the return information of the up to
|
| 921 |
+
three solvers that have been tried.
|
| 922 |
+
|
| 923 |
+
The function uses scipy.optimize for finding the value that satisfies
|
| 924 |
+
the power equation. It first uses ``brentq`` with a prior search for
|
| 925 |
+
bounds. If this fails to find a root, ``fsolve`` is used. If ``fsolve``
|
| 926 |
+
also fails, then, for ``alpha``, ``power`` and ``effect_size``,
|
| 927 |
+
``brentq`` with fixed bounds is used. However, there can still be cases
|
| 928 |
+
where this fails.
|
| 929 |
+
|
| 930 |
+
"""
|
| 931 |
+
# for debugging
|
| 932 |
+
# print 'calling ttest solve with', (effect_size, nobs, alpha, power, alternative)
|
| 933 |
+
return super().solve_power(
|
| 934 |
+
effect_size=effect_size,
|
| 935 |
+
nobs=nobs,
|
| 936 |
+
alpha=alpha,
|
| 937 |
+
power=power,
|
| 938 |
+
alternative=alternative,
|
| 939 |
+
)
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
class TTestIndPower(Power):
|
| 943 |
+
"""
|
| 944 |
+
Statistical Power calculations for t-test for two independent sample
|
| 945 |
+
|
| 946 |
+
currently only uses pooled variance
|
| 947 |
+
|
| 948 |
+
"""
|
| 949 |
+
|
| 950 |
+
def power(
|
| 951 |
+
self, effect_size, nobs1, alpha, ratio=1, df=None, alternative="two-sided"
|
| 952 |
+
):
|
| 953 |
+
"""
|
| 954 |
+
Calculate the power of a t-test for two independent sample
|
| 955 |
+
|
| 956 |
+
Parameters
|
| 957 |
+
----------
|
| 958 |
+
effect_size : float
|
| 959 |
+
standardized effect size, difference between the two means divided
|
| 960 |
+
by the standard deviation. `effect_size` has to be positive.
|
| 961 |
+
nobs1 : int or float
|
| 962 |
+
number of observations of sample 1. The number of observations of
|
| 963 |
+
sample two is ratio times the size of sample 1,
|
| 964 |
+
i.e., ``nobs2 = nobs1 * ratio``
|
| 965 |
+
alpha : float in interval (0,1)
|
| 966 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 967 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 968 |
+
ratio : float, optional
|
| 969 |
+
ratio of the number of observations in sample 2 relative to
|
| 970 |
+
sample 1. see description of nobs1
|
| 971 |
+
df : int or float, optional
|
| 972 |
+
degrees of freedom. By default this is None, and the df from the
|
| 973 |
+
ttest with pooled variance is used, ``df = (nobs1 - 1 + nobs2 - 1)``
|
| 974 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 975 |
+
extra argument to choose whether the power is calculated for a
|
| 976 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 977 |
+
either 'larger', 'smaller'.
|
| 978 |
+
|
| 979 |
+
Returns
|
| 980 |
+
-------
|
| 981 |
+
power : float
|
| 982 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 983 |
+
type II error. Power is the probability that the test correctly
|
| 984 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 985 |
+
|
| 986 |
+
"""
|
| 987 |
+
|
| 988 |
+
nobs2 = nobs1 * ratio
|
| 989 |
+
# pooled variance
|
| 990 |
+
if df is None:
|
| 991 |
+
df = nobs1 - 1 + nobs2 - 1
|
| 992 |
+
|
| 993 |
+
nobs = 1.0 / (1.0 / nobs1 + 1.0 / nobs2)
|
| 994 |
+
# print 'calling ttest power with', (effect_size, nobs, alpha, df, alternative)
|
| 995 |
+
return ttest_power(effect_size, nobs, alpha, df=df, alternative=alternative)
|
| 996 |
+
|
| 997 |
+
# method is only added to have explicit keywords and docstring
|
| 998 |
+
def solve_power(
|
| 999 |
+
self,
|
| 1000 |
+
effect_size=None,
|
| 1001 |
+
nobs1=None,
|
| 1002 |
+
alpha=None,
|
| 1003 |
+
power=None,
|
| 1004 |
+
ratio=1.0,
|
| 1005 |
+
alternative="two-sided",
|
| 1006 |
+
):
|
| 1007 |
+
"""
|
| 1008 |
+
Solve for any one parameter of the power of a two sample t-test
|
| 1009 |
+
|
| 1010 |
+
for t-test the keywords are:
|
| 1011 |
+
effect_size, nobs1, alpha, power, ratio
|
| 1012 |
+
|
| 1013 |
+
exactly one needs to be ``None``, all others need numeric values
|
| 1014 |
+
|
| 1015 |
+
Parameters
|
| 1016 |
+
----------
|
| 1017 |
+
effect_size : None or float
|
| 1018 |
+
standardized effect size, difference between the two means divided
|
| 1019 |
+
by the standard deviation. `effect_size` has to be positive.
|
| 1020 |
+
nobs1 : None or int or float
|
| 1021 |
+
number of observations of sample 1. The number of observations of
|
| 1022 |
+
sample two is ratio times the size of sample 1,
|
| 1023 |
+
i.e., ``nobs2 = nobs1 * ratio``
|
| 1024 |
+
alpha : None or float in interval (0,1)
|
| 1025 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1026 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1027 |
+
power : None or float in interval (0,1)
|
| 1028 |
+
power of the test, e.g., 0.8, is one minus the probability of a
|
| 1029 |
+
type II error. Power is the probability that the test correctly
|
| 1030 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1031 |
+
ratio : None or float, optional
|
| 1032 |
+
ratio of the number of observations in sample 2 relative to
|
| 1033 |
+
sample 1. see description of nobs1
|
| 1034 |
+
The default for ratio is 1; to solve for ratio given the other
|
| 1035 |
+
arguments it has to be explicitly set to None.
|
| 1036 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 1037 |
+
extra argument to choose whether the power is calculated for a
|
| 1038 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 1039 |
+
either 'larger', 'smaller'.
|
| 1040 |
+
|
| 1041 |
+
Returns
|
| 1042 |
+
-------
|
| 1043 |
+
value : float
|
| 1044 |
+
The value of the parameter that was set to None in the call. The
|
| 1045 |
+
value solves the power equation given the remaining parameters.
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
Notes
|
| 1049 |
+
-----
|
| 1050 |
+
The function uses scipy.optimize for finding the value that satisfies
|
| 1051 |
+
the power equation. It first uses ``brentq`` with a prior search for
|
| 1052 |
+
bounds. If this fails to find a root, ``fsolve`` is used. If ``fsolve``
|
| 1053 |
+
also fails, then, for ``alpha``, ``power`` and ``effect_size``,
|
| 1054 |
+
``brentq`` with fixed bounds is used. However, there can still be cases
|
| 1055 |
+
where this fails.
|
| 1056 |
+
|
| 1057 |
+
"""
|
| 1058 |
+
return super().solve_power(
|
| 1059 |
+
effect_size=effect_size,
|
| 1060 |
+
nobs1=nobs1,
|
| 1061 |
+
alpha=alpha,
|
| 1062 |
+
power=power,
|
| 1063 |
+
ratio=ratio,
|
| 1064 |
+
alternative=alternative,
|
| 1065 |
+
)
|
| 1066 |
+
|
| 1067 |
+
|
| 1068 |
+
class NormalIndPower(Power):
|
| 1069 |
+
"""
|
| 1070 |
+
Statistical Power calculations for z-test for two independent samples
|
| 1071 |
+
|
| 1072 |
+
currently only uses pooled variance
|
| 1073 |
+
|
| 1074 |
+
Parameters
|
| 1075 |
+
----------
|
| 1076 |
+
ddof : int, optional
|
| 1077 |
+
Degrees of freedom correction for the standard deviation used in
|
| 1078 |
+
computing the effective sample size. Used, e.g., for a correlation
|
| 1079 |
+
coefficient where ddof=3.
|
| 1080 |
+
**kwds
|
| 1081 |
+
Additional keyword arguments passed to the ``Power`` base class.
|
| 1082 |
+
|
| 1083 |
+
"""
|
| 1084 |
+
|
| 1085 |
+
def __init__(self, ddof=0, **kwds):
|
| 1086 |
+
self.ddof = ddof
|
| 1087 |
+
super().__init__(**kwds)
|
| 1088 |
+
|
| 1089 |
+
def power(self, effect_size, nobs1, alpha, ratio=1, alternative="two-sided"):
|
| 1090 |
+
"""
|
| 1091 |
+
Calculate the power of a z-test for two independent sample
|
| 1092 |
+
|
| 1093 |
+
Parameters
|
| 1094 |
+
----------
|
| 1095 |
+
effect_size : float
|
| 1096 |
+
standardized effect size, difference between the two means divided
|
| 1097 |
+
by the standard deviation. effect size has to be positive.
|
| 1098 |
+
nobs1 : int or float
|
| 1099 |
+
number of observations of sample 1. The number of observations of
|
| 1100 |
+
sample two is ratio times the size of sample 1,
|
| 1101 |
+
i.e., ``nobs2 = nobs1 * ratio``
|
| 1102 |
+
``ratio`` can be set to zero in order to get the power for a
|
| 1103 |
+
one sample test.
|
| 1104 |
+
alpha : float in interval (0,1)
|
| 1105 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1106 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1107 |
+
ratio : float, optional
|
| 1108 |
+
ratio of the number of observations in sample 2 relative to
|
| 1109 |
+
sample 1. see description of nobs1
|
| 1110 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 1111 |
+
extra argument to choose whether the power is calculated for a
|
| 1112 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 1113 |
+
either 'larger', 'smaller'.
|
| 1114 |
+
|
| 1115 |
+
Returns
|
| 1116 |
+
-------
|
| 1117 |
+
power : float
|
| 1118 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 1119 |
+
type II error. Power is the probability that the test correctly
|
| 1120 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1121 |
+
|
| 1122 |
+
"""
|
| 1123 |
+
|
| 1124 |
+
ddof = self.ddof # for correlation, ddof=3
|
| 1125 |
+
|
| 1126 |
+
# get effective nobs, factor for std of test statistic
|
| 1127 |
+
if ratio > 0:
|
| 1128 |
+
nobs2 = nobs1 * ratio
|
| 1129 |
+
# equivalent to nobs = n1*n2/(n1+n2)=n1*ratio/(1+ratio)
|
| 1130 |
+
nobs = 1.0 / (1.0 / (nobs1 - ddof) + 1.0 / (nobs2 - ddof))
|
| 1131 |
+
else:
|
| 1132 |
+
nobs = nobs1 - ddof
|
| 1133 |
+
return normal_power(effect_size, nobs, alpha, alternative=alternative)
|
| 1134 |
+
|
| 1135 |
+
# method is only added to have explicit keywords and docstring
|
| 1136 |
+
def solve_power(
|
| 1137 |
+
self,
|
| 1138 |
+
effect_size=None,
|
| 1139 |
+
nobs1=None,
|
| 1140 |
+
alpha=None,
|
| 1141 |
+
power=None,
|
| 1142 |
+
ratio=1.0,
|
| 1143 |
+
alternative="two-sided",
|
| 1144 |
+
):
|
| 1145 |
+
"""
|
| 1146 |
+
Solve for any one parameter of the power of a two sample z-test
|
| 1147 |
+
|
| 1148 |
+
for z-test the keywords are:
|
| 1149 |
+
effect_size, nobs1, alpha, power, ratio
|
| 1150 |
+
|
| 1151 |
+
exactly one needs to be ``None``, all others need numeric values
|
| 1152 |
+
|
| 1153 |
+
Parameters
|
| 1154 |
+
----------
|
| 1155 |
+
effect_size : None or float
|
| 1156 |
+
standardized effect size, difference between the two means divided
|
| 1157 |
+
by the standard deviation.
|
| 1158 |
+
If ratio=0, then this is the standardized mean in the one sample
|
| 1159 |
+
test.
|
| 1160 |
+
nobs1 : None or int or float
|
| 1161 |
+
number of observations of sample 1. The number of observations of
|
| 1162 |
+
sample two is ratio times the size of sample 1,
|
| 1163 |
+
i.e., ``nobs2 = nobs1 * ratio``
|
| 1164 |
+
``ratio`` can be set to zero in order to get the power for a
|
| 1165 |
+
one sample test.
|
| 1166 |
+
alpha : None or float in interval (0,1)
|
| 1167 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1168 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1169 |
+
power : None or float in interval (0,1)
|
| 1170 |
+
power of the test, e.g., 0.8, is one minus the probability of a
|
| 1171 |
+
type II error. Power is the probability that the test correctly
|
| 1172 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1173 |
+
ratio : None or float, optional
|
| 1174 |
+
ratio of the number of observations in sample 2 relative to
|
| 1175 |
+
sample 1. see description of nobs1
|
| 1176 |
+
The default for ratio is 1; to solve for ratio given the other
|
| 1177 |
+
arguments it has to be explicitly set to None.
|
| 1178 |
+
alternative : {'two-sided', 'larger', 'smaller'}, optional
|
| 1179 |
+
extra argument to choose whether the power is calculated for a
|
| 1180 |
+
two-sided (default) or one sided test. The one-sided test can be
|
| 1181 |
+
either 'larger', 'smaller'.
|
| 1182 |
+
|
| 1183 |
+
Returns
|
| 1184 |
+
-------
|
| 1185 |
+
value : float
|
| 1186 |
+
The value of the parameter that was set to None in the call. The
|
| 1187 |
+
value solves the power equation given the remaining parameters.
|
| 1188 |
+
|
| 1189 |
+
|
| 1190 |
+
Notes
|
| 1191 |
+
-----
|
| 1192 |
+
The function uses scipy.optimize for finding the value that satisfies
|
| 1193 |
+
the power equation. It first uses ``brentq`` with a prior search for
|
| 1194 |
+
bounds. If this fails to find a root, ``fsolve`` is used. If ``fsolve``
|
| 1195 |
+
also fails, then, for ``alpha``, ``power`` and ``effect_size``,
|
| 1196 |
+
``brentq`` with fixed bounds is used. However, there can still be cases
|
| 1197 |
+
where this fails.
|
| 1198 |
+
|
| 1199 |
+
"""
|
| 1200 |
+
return super().solve_power(
|
| 1201 |
+
effect_size=effect_size,
|
| 1202 |
+
nobs1=nobs1,
|
| 1203 |
+
alpha=alpha,
|
| 1204 |
+
power=power,
|
| 1205 |
+
ratio=ratio,
|
| 1206 |
+
alternative=alternative,
|
| 1207 |
+
)
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
class FTestPower(Power):
|
| 1211 |
+
"""
|
| 1212 |
+
Statistical Power calculations for generic F-test of a constraint
|
| 1213 |
+
|
| 1214 |
+
This class is not recommended, use `FTestPowerF2` with corrected interface.
|
| 1215 |
+
|
| 1216 |
+
This is based on Cohen's f as effect size measure.
|
| 1217 |
+
|
| 1218 |
+
Warning: Methods in this class have the names df_num and df_denom reversed.
|
| 1219 |
+
|
| 1220 |
+
See Also
|
| 1221 |
+
--------
|
| 1222 |
+
FTestPowerF2 :
|
| 1223 |
+
Class with Cohen's f-squared as effect size, corrected keyword names.
|
| 1224 |
+
|
| 1225 |
+
Examples
|
| 1226 |
+
--------
|
| 1227 |
+
Sample size and power for multiple regression base on R-squared
|
| 1228 |
+
|
| 1229 |
+
Compute effect size from R-squared
|
| 1230 |
+
|
| 1231 |
+
>>> r2 = 0.1
|
| 1232 |
+
>>> f2 = r2 / (1 - r2)
|
| 1233 |
+
>>> f = np.sqrt(f2)
|
| 1234 |
+
>>> r2, f2, f
|
| 1235 |
+
(0.1, 0.11111111111111112, 0.33333333333333337)
|
| 1236 |
+
|
| 1237 |
+
Find sample size by solving for denominator df, wrongly named ``df_num``
|
| 1238 |
+
|
| 1239 |
+
>>> df1 = 1 # number of constraints in hypothesis test
|
| 1240 |
+
>>> df2 = FTestPower().solve_power(effect_size=f, alpha=0.1, power=0.9,
|
| 1241 |
+
... df_denom=df1)
|
| 1242 |
+
>>> ncc = 1 # default
|
| 1243 |
+
>>> nobs = df2 + df1 + ncc
|
| 1244 |
+
>>> df2, nobs
|
| 1245 |
+
(76.46459758305376, 78.46459758305376)
|
| 1246 |
+
|
| 1247 |
+
verify power at df2
|
| 1248 |
+
|
| 1249 |
+
>>> FTestPower().power(effect_size=f, alpha=0.1, df_denom=df1, df_num=df2)
|
| 1250 |
+
0.8999999972109698
|
| 1251 |
+
|
| 1252 |
+
"""
|
| 1253 |
+
|
| 1254 |
+
def power(self, effect_size, df_num, df_denom, alpha, ncc=1):
|
| 1255 |
+
"""
|
| 1256 |
+
Calculate the power of a F-test
|
| 1257 |
+
|
| 1258 |
+
The effect size is Cohen's ``f``, square root of ``f2``.
|
| 1259 |
+
|
| 1260 |
+
The sample size is given by ``nobs = df_denom + df_num + ncc``
|
| 1261 |
+
|
| 1262 |
+
Warning: The meaning of df_num and df_denom is reversed.
|
| 1263 |
+
|
| 1264 |
+
Parameters
|
| 1265 |
+
----------
|
| 1266 |
+
effect_size : float
|
| 1267 |
+
Standardized effect size. The effect size is here Cohen's ``f``,
|
| 1268 |
+
square root of ``f2``.
|
| 1269 |
+
df_num : int or float
|
| 1270 |
+
Warning incorrect name
|
| 1271 |
+
denominator degrees of freedom,
|
| 1272 |
+
This corresponds to the number of constraints in Wald tests.
|
| 1273 |
+
df_denom : int or float
|
| 1274 |
+
Warning incorrect name
|
| 1275 |
+
numerator degrees of freedom.
|
| 1276 |
+
This corresponds to the df_resid in Wald tests.
|
| 1277 |
+
alpha : float in interval (0,1)
|
| 1278 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1279 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1280 |
+
ncc : int, optional
|
| 1281 |
+
degrees of freedom correction for non-centrality parameter.
|
| 1282 |
+
see Notes
|
| 1283 |
+
|
| 1284 |
+
Returns
|
| 1285 |
+
-------
|
| 1286 |
+
power : float
|
| 1287 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 1288 |
+
type II error. Power is the probability that the test correctly
|
| 1289 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1290 |
+
|
| 1291 |
+
Notes
|
| 1292 |
+
-----
|
| 1293 |
+
|
| 1294 |
+
sample size is given implicitly by df_num
|
| 1295 |
+
|
| 1296 |
+
set ncc=0 to match t-test, or f-test in LikelihoodModelResults.
|
| 1297 |
+
ncc=1 matches the non-centrality parameter in R::pwr::pwr.f2.test
|
| 1298 |
+
|
| 1299 |
+
ftest_power with ncc=0 should also be correct for f_test in regression
|
| 1300 |
+
models, with df_num and d_denom as defined there. (not verified yet)
|
| 1301 |
+
"""
|
| 1302 |
+
|
| 1303 |
+
pow_ = ftest_power(effect_size, df_num, df_denom, alpha, ncc=ncc)
|
| 1304 |
+
# print effect_size, df_num, df_denom, alpha, pow_
|
| 1305 |
+
return pow_
|
| 1306 |
+
|
| 1307 |
+
# method is only added to have explicit keywords and docstring
|
| 1308 |
+
def solve_power(
|
| 1309 |
+
self,
|
| 1310 |
+
effect_size=None,
|
| 1311 |
+
df_num=None,
|
| 1312 |
+
df_denom=None,
|
| 1313 |
+
alpha=None,
|
| 1314 |
+
power=None,
|
| 1315 |
+
ncc=1,
|
| 1316 |
+
**kwargs,
|
| 1317 |
+
):
|
| 1318 |
+
"""
|
| 1319 |
+
Solve for any one parameter of the power of a F-test
|
| 1320 |
+
|
| 1321 |
+
for the one sample F-test the keywords are:
|
| 1322 |
+
effect_size, df_num, df_denom, alpha, power
|
| 1323 |
+
|
| 1324 |
+
Exactly one needs to be ``None``, all others need numeric values.
|
| 1325 |
+
|
| 1326 |
+
The effect size is Cohen's ``f``, square root of ``f2``.
|
| 1327 |
+
|
| 1328 |
+
The sample size is given by ``nobs = df_denom + df_num + ncc``.
|
| 1329 |
+
|
| 1330 |
+
Warning: The meaning of df_num and df_denom is reversed.
|
| 1331 |
+
|
| 1332 |
+
Parameters
|
| 1333 |
+
----------
|
| 1334 |
+
effect_size : None or float
|
| 1335 |
+
Standardized effect size. The effect size is here Cohen's ``f``,
|
| 1336 |
+
square root of ``f2``.
|
| 1337 |
+
df_num : None or int or float
|
| 1338 |
+
Warning incorrect name
|
| 1339 |
+
denominator degrees of freedom,
|
| 1340 |
+
This corresponds to the number of constraints in Wald tests.
|
| 1341 |
+
Sample size is given by ``nobs = df_denom + df_num + ncc``
|
| 1342 |
+
df_denom : None or int or float
|
| 1343 |
+
Warning incorrect name
|
| 1344 |
+
numerator degrees of freedom.
|
| 1345 |
+
This corresponds to the df_resid in Wald tests.
|
| 1346 |
+
alpha : None or float in interval (0,1)
|
| 1347 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1348 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1349 |
+
power : None or float in interval (0,1)
|
| 1350 |
+
power of the test, e.g., 0.8, is one minus the probability of a
|
| 1351 |
+
type II error. Power is the probability that the test correctly
|
| 1352 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1353 |
+
ncc : int, optional
|
| 1354 |
+
degrees of freedom correction for non-centrality parameter.
|
| 1355 |
+
see Notes
|
| 1356 |
+
**kwargs
|
| 1357 |
+
``kwargs`` are not used and included for backwards compatibility.
|
| 1358 |
+
If ``nobs`` is used as keyword, then a warning is issued. All
|
| 1359 |
+
other keywords in ``kwargs`` raise a ValueError.
|
| 1360 |
+
|
| 1361 |
+
Returns
|
| 1362 |
+
-------
|
| 1363 |
+
value : float
|
| 1364 |
+
The value of the parameter that was set to None in the call. The
|
| 1365 |
+
value solves the power equation given the remaining parameters.
|
| 1366 |
+
|
| 1367 |
+
|
| 1368 |
+
Notes
|
| 1369 |
+
-----
|
| 1370 |
+
The method uses scipy.optimize for finding the value that satisfies
|
| 1371 |
+
the power equation. It first uses ``brentq`` with a prior search for
|
| 1372 |
+
bounds. If this fails to find a root, ``fsolve`` is used. If ``fsolve``
|
| 1373 |
+
also fails, then, for ``alpha``, ``power`` and ``effect_size``,
|
| 1374 |
+
``brentq`` with fixed bounds is used. However, there can still be cases
|
| 1375 |
+
where this fails.
|
| 1376 |
+
|
| 1377 |
+
"""
|
| 1378 |
+
if kwargs:
|
| 1379 |
+
if "nobs" in kwargs:
|
| 1380 |
+
warnings.warn("nobs is not used", stacklevel=2)
|
| 1381 |
+
else:
|
| 1382 |
+
raise ValueError(f"incorrect keyword(s) {kwargs}")
|
| 1383 |
+
return super().solve_power(
|
| 1384 |
+
effect_size=effect_size,
|
| 1385 |
+
df_num=df_num,
|
| 1386 |
+
df_denom=df_denom,
|
| 1387 |
+
alpha=alpha,
|
| 1388 |
+
power=power,
|
| 1389 |
+
ncc=ncc,
|
| 1390 |
+
)
|
| 1391 |
+
|
| 1392 |
+
|
| 1393 |
+
class FTestPowerF2(Power):
|
| 1394 |
+
"""
|
| 1395 |
+
Statistical Power calculations for generic F-test of a constraint
|
| 1396 |
+
|
| 1397 |
+
This is based on Cohen's f^2 as effect size measure.
|
| 1398 |
+
|
| 1399 |
+
Examples
|
| 1400 |
+
--------
|
| 1401 |
+
Sample size and power for multiple regression base on R-squared
|
| 1402 |
+
|
| 1403 |
+
Compute effect size from R-squared
|
| 1404 |
+
|
| 1405 |
+
>>> r2 = 0.1
|
| 1406 |
+
>>> f2 = r2 / (1 - r2)
|
| 1407 |
+
>>> f = np.sqrt(f2)
|
| 1408 |
+
>>> r2, f2, f
|
| 1409 |
+
(0.1, 0.11111111111111112, 0.33333333333333337)
|
| 1410 |
+
|
| 1411 |
+
Find sample size by solving for denominator degrees of freedom.
|
| 1412 |
+
|
| 1413 |
+
>>> df1 = 1 # number of constraints in hypothesis test
|
| 1414 |
+
>>> df2 = FTestPowerF2().solve_power(effect_size=f2, alpha=0.1, power=0.9,
|
| 1415 |
+
... df_num=df1)
|
| 1416 |
+
>>> ncc = 1 # default
|
| 1417 |
+
>>> nobs = df2 + df1 + ncc
|
| 1418 |
+
>>> df2, nobs
|
| 1419 |
+
(76.46459758305376, 78.46459758305376)
|
| 1420 |
+
|
| 1421 |
+
verify power at df2
|
| 1422 |
+
|
| 1423 |
+
>>> FTestPowerF2().power(effect_size=f, alpha=0.1, df_num=df1, df_denom=df2)
|
| 1424 |
+
0.8999999972109698
|
| 1425 |
+
|
| 1426 |
+
"""
|
| 1427 |
+
|
| 1428 |
+
def power(self, effect_size, df_num, df_denom, alpha, ncc=1):
|
| 1429 |
+
"""
|
| 1430 |
+
Calculate the power of a F-test
|
| 1431 |
+
|
| 1432 |
+
The effect size is Cohen's ``f^2``.
|
| 1433 |
+
|
| 1434 |
+
The sample size is given by ``nobs = df_denom + df_num + ncc``
|
| 1435 |
+
|
| 1436 |
+
Parameters
|
| 1437 |
+
----------
|
| 1438 |
+
effect_size : float
|
| 1439 |
+
The effect size is here Cohen's ``f2``. This is equal to
|
| 1440 |
+
the noncentrality of an F-test divided by nobs.
|
| 1441 |
+
df_num : int or float
|
| 1442 |
+
Numerator degrees of freedom,
|
| 1443 |
+
This corresponds to the number of constraints in Wald tests.
|
| 1444 |
+
df_denom : int or float
|
| 1445 |
+
Denominator degrees of freedom.
|
| 1446 |
+
This corresponds to the df_resid in Wald tests.
|
| 1447 |
+
alpha : float in interval (0,1)
|
| 1448 |
+
Significance level, e.g., 0.05, is the probability of a type I
|
| 1449 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1450 |
+
ncc : int, optional
|
| 1451 |
+
Degrees of freedom correction for non-centrality parameter.
|
| 1452 |
+
see Notes
|
| 1453 |
+
|
| 1454 |
+
Returns
|
| 1455 |
+
-------
|
| 1456 |
+
power : float
|
| 1457 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 1458 |
+
type II error. Power is the probability that the test correctly
|
| 1459 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1460 |
+
|
| 1461 |
+
Notes
|
| 1462 |
+
-----
|
| 1463 |
+
The sample size is given implicitly by df_denom
|
| 1464 |
+
|
| 1465 |
+
set ncc=0 to match t-test, or f-test in LikelihoodModelResults.
|
| 1466 |
+
ncc=1 matches the non-centrality parameter in R::pwr::pwr.f2.test
|
| 1467 |
+
|
| 1468 |
+
ftest_power with ncc=0 should also be correct for f_test in regression
|
| 1469 |
+
models, with df_num and d_denom as defined there. (not verified yet)
|
| 1470 |
+
"""
|
| 1471 |
+
|
| 1472 |
+
pow_ = ftest_power_f2(effect_size, df_num, df_denom, alpha, ncc=ncc)
|
| 1473 |
+
return pow_
|
| 1474 |
+
|
| 1475 |
+
# method is only added to have explicit keywords and docstring
|
| 1476 |
+
def solve_power(
|
| 1477 |
+
self,
|
| 1478 |
+
effect_size=None,
|
| 1479 |
+
df_num=None,
|
| 1480 |
+
df_denom=None,
|
| 1481 |
+
alpha=None,
|
| 1482 |
+
power=None,
|
| 1483 |
+
ncc=1,
|
| 1484 |
+
):
|
| 1485 |
+
"""
|
| 1486 |
+
Solve for any one parameter of the power of a F-test
|
| 1487 |
+
|
| 1488 |
+
for the one sample F-test the keywords are:
|
| 1489 |
+
effect_size, df_num, df_denom, alpha, power
|
| 1490 |
+
|
| 1491 |
+
Exactly one needs to be ``None``, all others need numeric values.
|
| 1492 |
+
|
| 1493 |
+
The effect size is Cohen's ``f2``.
|
| 1494 |
+
|
| 1495 |
+
The sample size is given by ``nobs = df_denom + df_num + ncc``, and
|
| 1496 |
+
can be found by solving for df_denom.
|
| 1497 |
+
|
| 1498 |
+
Parameters
|
| 1499 |
+
----------
|
| 1500 |
+
effect_size : None or float
|
| 1501 |
+
The effect size is here Cohen's ``f2``. This is equal to
|
| 1502 |
+
the noncentrality of an F-test divided by nobs.
|
| 1503 |
+
df_num : None or int or float
|
| 1504 |
+
Numerator degrees of freedom,
|
| 1505 |
+
This corresponds to the number of constraints in Wald tests.
|
| 1506 |
+
df_denom : None or int or float
|
| 1507 |
+
Denominator degrees of freedom.
|
| 1508 |
+
This corresponds to the df_resid in Wald tests.
|
| 1509 |
+
alpha : None or float in interval (0,1)
|
| 1510 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1511 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1512 |
+
power : None or float in interval (0,1)
|
| 1513 |
+
power of the test, e.g., 0.8, is one minus the probability of a
|
| 1514 |
+
type II error. Power is the probability that the test correctly
|
| 1515 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1516 |
+
ncc : int, optional
|
| 1517 |
+
degrees of freedom correction for non-centrality parameter.
|
| 1518 |
+
see Notes
|
| 1519 |
+
|
| 1520 |
+
Returns
|
| 1521 |
+
-------
|
| 1522 |
+
value : float
|
| 1523 |
+
The value of the parameter that was set to None in the call. The
|
| 1524 |
+
value solves the power equation given the remaining parameters.
|
| 1525 |
+
|
| 1526 |
+
|
| 1527 |
+
Notes
|
| 1528 |
+
-----
|
| 1529 |
+
The function uses scipy.optimize for finding the value that satisfies
|
| 1530 |
+
the power equation. It first uses ``brentq`` with a prior search for
|
| 1531 |
+
bounds. If this fails to find a root, ``fsolve`` is used. If ``fsolve``
|
| 1532 |
+
also fails, then, for ``alpha``, ``power`` and ``effect_size``,
|
| 1533 |
+
``brentq`` with fixed bounds is used. However, there can still be cases
|
| 1534 |
+
where this fails.
|
| 1535 |
+
|
| 1536 |
+
"""
|
| 1537 |
+
|
| 1538 |
+
return super().solve_power(
|
| 1539 |
+
effect_size=effect_size,
|
| 1540 |
+
df_num=df_num,
|
| 1541 |
+
df_denom=df_denom,
|
| 1542 |
+
alpha=alpha,
|
| 1543 |
+
power=power,
|
| 1544 |
+
ncc=ncc,
|
| 1545 |
+
)
|
| 1546 |
+
|
| 1547 |
+
|
| 1548 |
+
class FTestAnovaPower(Power):
|
| 1549 |
+
"""
|
| 1550 |
+
Statistical Power calculations F-test for one factor balanced ANOVA
|
| 1551 |
+
|
| 1552 |
+
This is based on Cohen's f as effect size measure.
|
| 1553 |
+
|
| 1554 |
+
See Also
|
| 1555 |
+
--------
|
| 1556 |
+
statsmodels.stats.oneway.effectsize_oneway
|
| 1557 |
+
|
| 1558 |
+
"""
|
| 1559 |
+
|
| 1560 |
+
def power(self, effect_size, nobs, alpha, k_groups=2):
|
| 1561 |
+
"""
|
| 1562 |
+
Calculate the power of a F-test for one factor ANOVA
|
| 1563 |
+
|
| 1564 |
+
Parameters
|
| 1565 |
+
----------
|
| 1566 |
+
effect_size : float
|
| 1567 |
+
standardized effect size. The effect size is here Cohen's f, square
|
| 1568 |
+
root of "f2".
|
| 1569 |
+
nobs : int or float
|
| 1570 |
+
sample size, number of observations.
|
| 1571 |
+
alpha : float in interval (0,1)
|
| 1572 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1573 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1574 |
+
k_groups : int or float
|
| 1575 |
+
number of groups in the ANOVA or k-sample comparison. Default is 2.
|
| 1576 |
+
|
| 1577 |
+
Returns
|
| 1578 |
+
-------
|
| 1579 |
+
power : float
|
| 1580 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 1581 |
+
type II error. Power is the probability that the test correctly
|
| 1582 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1583 |
+
|
| 1584 |
+
"""
|
| 1585 |
+
return ftest_anova_power(effect_size, nobs, alpha, k_groups=k_groups)
|
| 1586 |
+
|
| 1587 |
+
# method is only added to have explicit keywords and docstring
|
| 1588 |
+
def solve_power(
|
| 1589 |
+
self, effect_size=None, nobs=None, alpha=None, power=None, k_groups=2
|
| 1590 |
+
):
|
| 1591 |
+
"""
|
| 1592 |
+
Solve for any one parameter of the power of a F-test
|
| 1593 |
+
|
| 1594 |
+
for the one sample F-test the keywords are:
|
| 1595 |
+
effect_size, nobs, alpha, power
|
| 1596 |
+
|
| 1597 |
+
Exactly one needs to be ``None``, all others need numeric values.
|
| 1598 |
+
|
| 1599 |
+
|
| 1600 |
+
Parameters
|
| 1601 |
+
----------
|
| 1602 |
+
effect_size : None or float
|
| 1603 |
+
standardized effect size, mean divided by the standard deviation.
|
| 1604 |
+
effect size has to be positive.
|
| 1605 |
+
nobs : None or int or float
|
| 1606 |
+
sample size, number of observations.
|
| 1607 |
+
alpha : None or float in interval (0,1)
|
| 1608 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1609 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1610 |
+
power : None or float in interval (0,1)
|
| 1611 |
+
power of the test, e.g., 0.8, is one minus the probability of a
|
| 1612 |
+
type II error. Power is the probability that the test correctly
|
| 1613 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1614 |
+
k_groups : int or float, optional
|
| 1615 |
+
number of groups in the ANOVA or k-sample comparison. Default is 2.
|
| 1616 |
+
|
| 1617 |
+
Returns
|
| 1618 |
+
-------
|
| 1619 |
+
value : float
|
| 1620 |
+
The value of the parameter that was set to None in the call. The
|
| 1621 |
+
value solves the power equation given the remaining parameters.
|
| 1622 |
+
|
| 1623 |
+
|
| 1624 |
+
Notes
|
| 1625 |
+
-----
|
| 1626 |
+
The function uses scipy.optimize for finding the value that satisfies
|
| 1627 |
+
the power equation. It first uses ``brentq`` with a prior search for
|
| 1628 |
+
bounds. If this fails to find a root, ``fsolve`` is used. If ``fsolve``
|
| 1629 |
+
also fails, then, for ``alpha``, ``power`` and ``effect_size``,
|
| 1630 |
+
``brentq`` with fixed bounds is used. However, there can still be cases
|
| 1631 |
+
where this fails.
|
| 1632 |
+
|
| 1633 |
+
"""
|
| 1634 |
+
# update start values for root finding
|
| 1635 |
+
if k_groups is not None:
|
| 1636 |
+
self.start_ttp["nobs"] = k_groups * 10
|
| 1637 |
+
self.start_bqexp["nobs"] = {"low": k_groups * 2, "start_upp": k_groups * 10}
|
| 1638 |
+
# first attempt at special casing
|
| 1639 |
+
if effect_size is None:
|
| 1640 |
+
return self._solve_effect_size(
|
| 1641 |
+
effect_size=effect_size,
|
| 1642 |
+
nobs=nobs,
|
| 1643 |
+
alpha=alpha,
|
| 1644 |
+
k_groups=k_groups,
|
| 1645 |
+
power=power,
|
| 1646 |
+
)
|
| 1647 |
+
|
| 1648 |
+
return super().solve_power(
|
| 1649 |
+
effect_size=effect_size,
|
| 1650 |
+
nobs=nobs,
|
| 1651 |
+
alpha=alpha,
|
| 1652 |
+
k_groups=k_groups,
|
| 1653 |
+
power=power,
|
| 1654 |
+
)
|
| 1655 |
+
|
| 1656 |
+
def _solve_effect_size(
|
| 1657 |
+
self, effect_size=None, nobs=None, alpha=None, power=None, k_groups=2
|
| 1658 |
+
):
|
| 1659 |
+
"""experimental, test failure in solve_power for effect_size"""
|
| 1660 |
+
|
| 1661 |
+
def func(x):
|
| 1662 |
+
effect_size = x
|
| 1663 |
+
return self._power_identity(
|
| 1664 |
+
effect_size=effect_size,
|
| 1665 |
+
nobs=nobs,
|
| 1666 |
+
alpha=alpha,
|
| 1667 |
+
k_groups=k_groups,
|
| 1668 |
+
power=power,
|
| 1669 |
+
)
|
| 1670 |
+
|
| 1671 |
+
val, r = optimize.brentq(func, 1e-8, 1 - 1e-8, full_output=True)
|
| 1672 |
+
if not r.converged:
|
| 1673 |
+
print(r)
|
| 1674 |
+
return val
|
| 1675 |
+
|
| 1676 |
+
|
| 1677 |
+
class GofChisquarePower(Power):
|
| 1678 |
+
"""Statistical Power calculations for one sample chisquare test"""
|
| 1679 |
+
|
| 1680 |
+
def power(
|
| 1681 |
+
self, effect_size, nobs, alpha, n_bins, ddof=0
|
| 1682 |
+
): # alternative='two-sided'):
|
| 1683 |
+
"""
|
| 1684 |
+
Calculate the power of a chisquare test for one sample
|
| 1685 |
+
|
| 1686 |
+
Only two-sided alternative is implemented
|
| 1687 |
+
|
| 1688 |
+
Parameters
|
| 1689 |
+
----------
|
| 1690 |
+
effect_size : float
|
| 1691 |
+
standardized effect size, according to Cohen's definition.
|
| 1692 |
+
see :func:`statsmodels.stats.gof.chisquare_effectsize`
|
| 1693 |
+
nobs : int or float
|
| 1694 |
+
sample size, number of observations.
|
| 1695 |
+
alpha : float in interval (0,1)
|
| 1696 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1697 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1698 |
+
n_bins : int
|
| 1699 |
+
number of bins or cells in the distribution.
|
| 1700 |
+
ddof : int, optional
|
| 1701 |
+
Degrees of freedom correction for the chisquare distribution.
|
| 1702 |
+
|
| 1703 |
+
Returns
|
| 1704 |
+
-------
|
| 1705 |
+
power : float
|
| 1706 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 1707 |
+
type II error. Power is the probability that the test correctly
|
| 1708 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1709 |
+
|
| 1710 |
+
"""
|
| 1711 |
+
from statsmodels.stats.gof import chisquare_power
|
| 1712 |
+
|
| 1713 |
+
return chisquare_power(effect_size, nobs, n_bins, alpha, ddof=ddof)
|
| 1714 |
+
|
| 1715 |
+
# method is only added to have explicit keywords and docstring
|
| 1716 |
+
def solve_power(
|
| 1717 |
+
self, effect_size=None, nobs=None, alpha=None, power=None, n_bins=2
|
| 1718 |
+
):
|
| 1719 |
+
"""
|
| 1720 |
+
Solve for any one parameter of the power of a one sample chisquare-test
|
| 1721 |
+
|
| 1722 |
+
for the one sample chisquare-test the keywords are:
|
| 1723 |
+
effect_size, nobs, alpha, power
|
| 1724 |
+
|
| 1725 |
+
Exactly one needs to be ``None``, all others need numeric values.
|
| 1726 |
+
|
| 1727 |
+
n_bins needs to be defined, a default=2 is used.
|
| 1728 |
+
|
| 1729 |
+
|
| 1730 |
+
Parameters
|
| 1731 |
+
----------
|
| 1732 |
+
effect_size : None or float
|
| 1733 |
+
standardized effect size, according to Cohen's definition.
|
| 1734 |
+
see :func:`statsmodels.stats.gof.chisquare_effectsize`
|
| 1735 |
+
nobs : None or int or float
|
| 1736 |
+
sample size, number of observations.
|
| 1737 |
+
alpha : None or float in interval (0,1)
|
| 1738 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1739 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1740 |
+
power : None or float in interval (0,1)
|
| 1741 |
+
power of the test, e.g., 0.8, is one minus the probability of a
|
| 1742 |
+
type II error. Power is the probability that the test correctly
|
| 1743 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1744 |
+
n_bins : int, optional
|
| 1745 |
+
number of bins or cells in the distribution
|
| 1746 |
+
|
| 1747 |
+
Returns
|
| 1748 |
+
-------
|
| 1749 |
+
value : float
|
| 1750 |
+
The value of the parameter that was set to None in the call. The
|
| 1751 |
+
value solves the power equation given the remaining parameters.
|
| 1752 |
+
|
| 1753 |
+
|
| 1754 |
+
Notes
|
| 1755 |
+
-----
|
| 1756 |
+
The function uses scipy.optimize for finding the value that satisfies
|
| 1757 |
+
the power equation. It first uses ``brentq`` with a prior search for
|
| 1758 |
+
bounds. If this fails to find a root, ``fsolve`` is used. If ``fsolve``
|
| 1759 |
+
also fails, then, for ``alpha``, ``power`` and ``effect_size``,
|
| 1760 |
+
``brentq`` with fixed bounds is used. However, there can still be cases
|
| 1761 |
+
where this fails.
|
| 1762 |
+
|
| 1763 |
+
"""
|
| 1764 |
+
return super().solve_power(
|
| 1765 |
+
effect_size=effect_size, nobs=nobs, n_bins=n_bins, alpha=alpha, power=power
|
| 1766 |
+
)
|
| 1767 |
+
|
| 1768 |
+
|
| 1769 |
+
class _GofChisquareIndPower(Power):
|
| 1770 |
+
"""
|
| 1771 |
+
Statistical Power calculations for chisquare goodness-of-fit test
|
| 1772 |
+
|
| 1773 |
+
TODO: this is not working yet
|
| 1774 |
+
for 2sample case need two nobs in function
|
| 1775 |
+
no one-sided chisquare test, is there one? use normal distribution?
|
| 1776 |
+
-> drop one-sided options?
|
| 1777 |
+
"""
|
| 1778 |
+
|
| 1779 |
+
def power(self, effect_size, nobs1, alpha, ratio=1, alternative="two-sided"):
|
| 1780 |
+
"""
|
| 1781 |
+
Calculate the power of a chisquare for two independent sample
|
| 1782 |
+
|
| 1783 |
+
Parameters
|
| 1784 |
+
----------
|
| 1785 |
+
effect_size : float
|
| 1786 |
+
standardized effect size, difference between the two means divided
|
| 1787 |
+
by the standard deviation. effect size has to be positive.
|
| 1788 |
+
nobs1 : int or float
|
| 1789 |
+
number of observations of sample 1. The number of observations of
|
| 1790 |
+
sample two is ratio times the size of sample 1,
|
| 1791 |
+
i.e., ``nobs2 = nobs1 * ratio``
|
| 1792 |
+
alpha : float in interval (0,1)
|
| 1793 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1794 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1795 |
+
ratio : float, optional
|
| 1796 |
+
ratio of the number of observations in sample 2 relative to
|
| 1797 |
+
sample 1. see description of nobs1
|
| 1798 |
+
alternative : {'two-sided', 'one-sided'}, optional
|
| 1799 |
+
extra argument to choose whether the power is calculated for a
|
| 1800 |
+
two-sided (default) or one sided test.
|
| 1801 |
+
'one-sided' assumes we are in the relevant tail.
|
| 1802 |
+
|
| 1803 |
+
Returns
|
| 1804 |
+
-------
|
| 1805 |
+
power : float
|
| 1806 |
+
Power of the test, e.g., 0.8, is one minus the probability of a
|
| 1807 |
+
type II error. Power is the probability that the test correctly
|
| 1808 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1809 |
+
|
| 1810 |
+
"""
|
| 1811 |
+
|
| 1812 |
+
from statsmodels.stats.gof import chisquare_power
|
| 1813 |
+
|
| 1814 |
+
nobs2 = nobs1 * ratio
|
| 1815 |
+
# equivalent to nobs = n1*n2/(n1+n2)=n1*ratio/(1+ratio)
|
| 1816 |
+
nobs = 1.0 / (1.0 / nobs1 + 1.0 / nobs2)
|
| 1817 |
+
return chisquare_power(effect_size, nobs, alpha)
|
| 1818 |
+
|
| 1819 |
+
# method is only added to have explicit keywords and docstring
|
| 1820 |
+
def solve_power(
|
| 1821 |
+
self,
|
| 1822 |
+
effect_size=None,
|
| 1823 |
+
nobs1=None,
|
| 1824 |
+
alpha=None,
|
| 1825 |
+
power=None,
|
| 1826 |
+
ratio=1.0,
|
| 1827 |
+
alternative="two-sided",
|
| 1828 |
+
):
|
| 1829 |
+
"""
|
| 1830 |
+
Solve for any one parameter of the power of a two sample chisquare-test
|
| 1831 |
+
|
| 1832 |
+
for the chisquare-test the keywords are:
|
| 1833 |
+
effect_size, nobs1, alpha, power, ratio
|
| 1834 |
+
|
| 1835 |
+
exactly one needs to be ``None``, all others need numeric values
|
| 1836 |
+
|
| 1837 |
+
Parameters
|
| 1838 |
+
----------
|
| 1839 |
+
effect_size : None or float
|
| 1840 |
+
standardized effect size, difference between the two means divided
|
| 1841 |
+
by the standard deviation.
|
| 1842 |
+
nobs1 : None or int or float
|
| 1843 |
+
number of observations of sample 1. The number of observations of
|
| 1844 |
+
sample two is ratio times the size of sample 1,
|
| 1845 |
+
i.e., ``nobs2 = nobs1 * ratio``
|
| 1846 |
+
alpha : None or float in interval (0,1)
|
| 1847 |
+
significance level, e.g., 0.05, is the probability of a type I
|
| 1848 |
+
error, that is wrong rejections if the Null Hypothesis is true.
|
| 1849 |
+
power : None or float in interval (0,1)
|
| 1850 |
+
power of the test, e.g., 0.8, is one minus the probability of a
|
| 1851 |
+
type II error. Power is the probability that the test correctly
|
| 1852 |
+
rejects the Null Hypothesis if the Alternative Hypothesis is true.
|
| 1853 |
+
ratio : None or float, optional
|
| 1854 |
+
ratio of the number of observations in sample 2 relative to
|
| 1855 |
+
sample 1. see description of nobs1
|
| 1856 |
+
The default for ratio is 1; to solve for ratio given the other
|
| 1857 |
+
arguments it has to be explicitly set to None.
|
| 1858 |
+
alternative : {'two-sided', 'one-sided'}, optional
|
| 1859 |
+
extra argument to choose whether the power is calculated for a
|
| 1860 |
+
two-sided (default) or one sided test.
|
| 1861 |
+
'one-sided' assumes we are in the relevant tail.
|
| 1862 |
+
|
| 1863 |
+
Returns
|
| 1864 |
+
-------
|
| 1865 |
+
value : float
|
| 1866 |
+
The value of the parameter that was set to None in the call. The
|
| 1867 |
+
value solves the power equation given the remaining parameters.
|
| 1868 |
+
|
| 1869 |
+
|
| 1870 |
+
Notes
|
| 1871 |
+
-----
|
| 1872 |
+
The function uses scipy.optimize for finding the value that satisfies
|
| 1873 |
+
the power equation. It first uses ``brentq`` with a prior search for
|
| 1874 |
+
bounds. If this fails to find a root, ``fsolve`` is used. If ``fsolve``
|
| 1875 |
+
also fails, then, for ``alpha``, ``power`` and ``effect_size``,
|
| 1876 |
+
``brentq`` with fixed bounds is used. However, there can still be cases
|
| 1877 |
+
where this fails.
|
| 1878 |
+
|
| 1879 |
+
"""
|
| 1880 |
+
return super().solve_power(
|
| 1881 |
+
effect_size=effect_size,
|
| 1882 |
+
nobs1=nobs1,
|
| 1883 |
+
alpha=alpha,
|
| 1884 |
+
power=power,
|
| 1885 |
+
ratio=ratio,
|
| 1886 |
+
alternative=alternative,
|
| 1887 |
+
)
|
| 1888 |
+
|
| 1889 |
+
|
| 1890 |
+
# shortcut functions
|
| 1891 |
+
tt_solve_power = TTestPower().solve_power
|
| 1892 |
+
tt_ind_solve_power = TTestIndPower().solve_power
|
| 1893 |
+
zt_ind_solve_power = NormalIndPower().solve_power
|
shared/package-files/41/41c6e13b296e71c76e86fa20b1e5a184c2a99c931e77f95fb3486f73a06f00d7/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41c6e13b296e71c76e86fa20b1e5a184c2a99c931e77f95fb3486f73a06f00d7
|
| 3 |
+
size 2701899968
|
shared/package-files/41/41c708c5adba6e097513ab8ccb9f1d7865a2fb469e22491a9e01dcc64da459fc/blob
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.29.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
shared/package-files/41/41cac51c9f92ffe7a4bbf83041bf6f9317b714ece180b65187a5edb1884d1c29/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41cac51c9f92ffe7a4bbf83041bf6f9317b714ece180b65187a5edb1884d1c29
|
| 3 |
+
size 6981992
|
shared/package-files/41/41cb1a37427106bf40af0427ce198dd3a1bc74c4e9a88b886daa49bd65abf084/blob
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from _dummy_thread import *
|
shared/package-files/41/41cb48d69deaa9089aa8ba4625d2f0bc8bc40910f3e6d697151d44945641d71d/blob
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
from typing import Any, Dict, Iterator, List, Optional
|
| 3 |
+
|
| 4 |
+
from django.core.serializers.base import DeserializedObject
|
| 5 |
+
from django.db.models.base import Model
|
| 6 |
+
|
| 7 |
+
from django.core.serializers import base
|
| 8 |
+
|
| 9 |
+
class Serializer(base.Serializer):
|
| 10 |
+
objects: List[Any] = ...
|
| 11 |
+
def get_dump_object(self, obj: Model) -> OrderedDict: ...
|
| 12 |
+
|
| 13 |
+
def Deserializer(
|
| 14 |
+
object_list: List[Dict[str, Any]], *, using: Optional[str] = ..., ignorenonexistent: bool = ..., **options: Any
|
| 15 |
+
) -> Iterator[DeserializedObject]: ...
|
shared/package-files/41/41cda824ec237bee2e7054f570046990150bbe4157308c8ec42b70382c68960c/blob
ADDED
|
Binary file (2.41 kB). View file
|
|
|
shared/package-files/41/41d26fc8ad8dd77f1b8833e18b1c7f67dc5b27b47e692c73e668524af87e1d18/blob
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
from sklearn.metrics import euclidean_distances
|
| 5 |
+
from sklearn.neighbors import KNeighborsTransformer, RadiusNeighborsTransformer
|
| 6 |
+
from sklearn.neighbors._base import _is_sorted_by_data
|
| 7 |
+
from sklearn.utils._testing import assert_array_equal
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_transformer_result():
|
| 11 |
+
# Test the number of neighbors returned
|
| 12 |
+
n_neighbors = 5
|
| 13 |
+
n_samples_fit = 20
|
| 14 |
+
n_queries = 18
|
| 15 |
+
n_features = 10
|
| 16 |
+
|
| 17 |
+
rng = np.random.RandomState(42)
|
| 18 |
+
X = rng.randn(n_samples_fit, n_features)
|
| 19 |
+
X2 = rng.randn(n_queries, n_features)
|
| 20 |
+
radius = np.percentile(euclidean_distances(X), 10)
|
| 21 |
+
|
| 22 |
+
# with n_neighbors
|
| 23 |
+
for mode in ["distance", "connectivity"]:
|
| 24 |
+
add_one = mode == "distance"
|
| 25 |
+
nnt = KNeighborsTransformer(n_neighbors=n_neighbors, mode=mode)
|
| 26 |
+
Xt = nnt.fit_transform(X)
|
| 27 |
+
assert Xt.shape == (n_samples_fit, n_samples_fit)
|
| 28 |
+
assert Xt.data.shape == (n_samples_fit * (n_neighbors + add_one),)
|
| 29 |
+
assert Xt.format == "csr"
|
| 30 |
+
assert _is_sorted_by_data(Xt)
|
| 31 |
+
|
| 32 |
+
X2t = nnt.transform(X2)
|
| 33 |
+
assert X2t.shape == (n_queries, n_samples_fit)
|
| 34 |
+
assert X2t.data.shape == (n_queries * (n_neighbors + add_one),)
|
| 35 |
+
assert X2t.format == "csr"
|
| 36 |
+
assert _is_sorted_by_data(X2t)
|
| 37 |
+
|
| 38 |
+
# with radius
|
| 39 |
+
for mode in ["distance", "connectivity"]:
|
| 40 |
+
add_one = mode == "distance"
|
| 41 |
+
nnt = RadiusNeighborsTransformer(radius=radius, mode=mode)
|
| 42 |
+
Xt = nnt.fit_transform(X)
|
| 43 |
+
assert Xt.shape == (n_samples_fit, n_samples_fit)
|
| 44 |
+
assert not Xt.data.shape == (n_samples_fit * (n_neighbors + add_one),)
|
| 45 |
+
assert Xt.format == "csr"
|
| 46 |
+
assert _is_sorted_by_data(Xt)
|
| 47 |
+
|
| 48 |
+
X2t = nnt.transform(X2)
|
| 49 |
+
assert X2t.shape == (n_queries, n_samples_fit)
|
| 50 |
+
assert not X2t.data.shape == (n_queries * (n_neighbors + add_one),)
|
| 51 |
+
assert X2t.format == "csr"
|
| 52 |
+
assert _is_sorted_by_data(X2t)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _has_explicit_diagonal(X):
|
| 56 |
+
"""Return True if the diagonal is explicitly stored"""
|
| 57 |
+
X = X.tocoo()
|
| 58 |
+
explicit = X.row[X.row == X.col]
|
| 59 |
+
return len(explicit) == X.shape[0]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_explicit_diagonal():
|
| 63 |
+
# Test that the diagonal is explicitly stored in the sparse graph
|
| 64 |
+
n_neighbors = 5
|
| 65 |
+
n_samples_fit, n_samples_transform, n_features = 20, 18, 10
|
| 66 |
+
rng = np.random.RandomState(42)
|
| 67 |
+
X = rng.randn(n_samples_fit, n_features)
|
| 68 |
+
X2 = rng.randn(n_samples_transform, n_features)
|
| 69 |
+
|
| 70 |
+
nnt = KNeighborsTransformer(n_neighbors=n_neighbors)
|
| 71 |
+
Xt = nnt.fit_transform(X)
|
| 72 |
+
assert _has_explicit_diagonal(Xt)
|
| 73 |
+
assert np.all(Xt.data.reshape(n_samples_fit, n_neighbors + 1)[:, 0] == 0)
|
| 74 |
+
|
| 75 |
+
Xt = nnt.transform(X)
|
| 76 |
+
assert _has_explicit_diagonal(Xt)
|
| 77 |
+
assert np.all(Xt.data.reshape(n_samples_fit, n_neighbors + 1)[:, 0] == 0)
|
| 78 |
+
|
| 79 |
+
# Using transform on new data should not always have zero diagonal
|
| 80 |
+
X2t = nnt.transform(X2)
|
| 81 |
+
assert not _has_explicit_diagonal(X2t)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@pytest.mark.parametrize("Klass", [KNeighborsTransformer, RadiusNeighborsTransformer])
|
| 85 |
+
def test_graph_feature_names_out(Klass):
|
| 86 |
+
"""Check `get_feature_names_out` for transformers defined in `_graph.py`."""
|
| 87 |
+
|
| 88 |
+
n_samples_fit = 20
|
| 89 |
+
n_features = 10
|
| 90 |
+
rng = np.random.RandomState(42)
|
| 91 |
+
X = rng.randn(n_samples_fit, n_features)
|
| 92 |
+
|
| 93 |
+
est = Klass().fit(X)
|
| 94 |
+
names_out = est.get_feature_names_out()
|
| 95 |
+
|
| 96 |
+
class_name_lower = Klass.__name__.lower()
|
| 97 |
+
expected_names_out = np.array(
|
| 98 |
+
[f"{class_name_lower}{i}" for i in range(est.n_samples_fit_)],
|
| 99 |
+
dtype=object,
|
| 100 |
+
)
|
| 101 |
+
assert_array_equal(names_out, expected_names_out)
|
shared/package-files/41/41d4d08956f385ba5968965511255f4ba72050c2448ca6916896bddcde3dc346/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41d4d08956f385ba5968965511255f4ba72050c2448ca6916896bddcde3dc346
|
| 3 |
+
size 299736
|
shared/package-files/41/41d7179c2340c29b395554cda3a8ec766112e87e8aeb3aa9c9467121999f29ad/blob
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from importlib.util import find_spec
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
__all__ = ["amp_definitely_not_available"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def amp_definitely_not_available():
|
| 9 |
+
return not (torch.cuda.is_available() or find_spec("torch_xla"))
|
shared/package-files/41/41d7748bb1f870d8400017c53993eea65862ffd482aae1693be84d93245c303f/blob
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NIST/ITL StRD
|
| 2 |
+
Dataset Name: AtmWtAg (AtmWtAg.dat)
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
File Format: ASCII
|
| 6 |
+
Certified Values (lines 41 to 47)
|
| 7 |
+
Data (lines 61 to 108)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
Procedure: Analysis of Variance
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
Reference: Powell, L.J., Murphy, T.J. and Gramlich, J.W. (1982).
|
| 14 |
+
"The Absolute Isotopic Abundance & Atomic Weight
|
| 15 |
+
of a Reference Sample of Silver".
|
| 16 |
+
NBS Journal of Research, 87, pp. 9-19.
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
Data: 1 Factor
|
| 20 |
+
2 Treatments
|
| 21 |
+
24 Replicates/Cell
|
| 22 |
+
48 Observations
|
| 23 |
+
7 Constant Leading Digits
|
| 24 |
+
Average Level of Difficulty
|
| 25 |
+
Observed Data
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
Model: 3 Parameters (mu, tau_1, tau_2)
|
| 29 |
+
y_{ij} = mu + tau_i + epsilon_{ij}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
Certified Values:
|
| 37 |
+
|
| 38 |
+
Source of Sums of Mean
|
| 39 |
+
Variation df Squares Squares F Statistic
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
Between Instrument 1 3.63834187500000E-09 3.63834187500000E-09 1.59467335677930E+01
|
| 43 |
+
Within Instrument 46 1.04951729166667E-08 2.28155932971014E-10
|
| 44 |
+
|
| 45 |
+
Certified R-Squared 2.57426544538321E-01
|
| 46 |
+
|
| 47 |
+
Certified Residual
|
| 48 |
+
Standard Deviation 1.51048314446410E-05
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
Data: Instrument AgWt
|
| 61 |
+
1 107.8681568
|
| 62 |
+
1 107.8681465
|
| 63 |
+
1 107.8681572
|
| 64 |
+
1 107.8681785
|
| 65 |
+
1 107.8681446
|
| 66 |
+
1 107.8681903
|
| 67 |
+
1 107.8681526
|
| 68 |
+
1 107.8681494
|
| 69 |
+
1 107.8681616
|
| 70 |
+
1 107.8681587
|
| 71 |
+
1 107.8681519
|
| 72 |
+
1 107.8681486
|
| 73 |
+
1 107.8681419
|
| 74 |
+
1 107.8681569
|
| 75 |
+
1 107.8681508
|
| 76 |
+
1 107.8681672
|
| 77 |
+
1 107.8681385
|
| 78 |
+
1 107.8681518
|
| 79 |
+
1 107.8681662
|
| 80 |
+
1 107.8681424
|
| 81 |
+
1 107.8681360
|
| 82 |
+
1 107.8681333
|
| 83 |
+
1 107.8681610
|
| 84 |
+
1 107.8681477
|
| 85 |
+
2 107.8681079
|
| 86 |
+
2 107.8681344
|
| 87 |
+
2 107.8681513
|
| 88 |
+
2 107.8681197
|
| 89 |
+
2 107.8681604
|
| 90 |
+
2 107.8681385
|
| 91 |
+
2 107.8681642
|
| 92 |
+
2 107.8681365
|
| 93 |
+
2 107.8681151
|
| 94 |
+
2 107.8681082
|
| 95 |
+
2 107.8681517
|
| 96 |
+
2 107.8681448
|
| 97 |
+
2 107.8681198
|
| 98 |
+
2 107.8681482
|
| 99 |
+
2 107.8681334
|
| 100 |
+
2 107.8681609
|
| 101 |
+
2 107.8681101
|
| 102 |
+
2 107.8681512
|
| 103 |
+
2 107.8681469
|
| 104 |
+
2 107.8681360
|
| 105 |
+
2 107.8681254
|
| 106 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
# These two dicts are autogenerated with autogen/gen_dtypes.py,
|
| 6 |
+
# using numpy version 1.23.5.
|
| 7 |
+
|
| 8 |
+
_can_cast_dict = {
|
| 9 |
+
"no": {
|
| 10 |
+
torch.float16: {
|
| 11 |
+
torch.float16: True,
|
| 12 |
+
torch.float32: False,
|
| 13 |
+
torch.float64: False,
|
| 14 |
+
torch.complex64: False,
|
| 15 |
+
torch.complex128: False,
|
| 16 |
+
torch.uint8: False,
|
| 17 |
+
torch.int8: False,
|
| 18 |
+
torch.int16: False,
|
| 19 |
+
torch.int32: False,
|
| 20 |
+
torch.int64: False,
|
| 21 |
+
torch.bool: False,
|
| 22 |
+
},
|
| 23 |
+
torch.float32: {
|
| 24 |
+
torch.float16: False,
|
| 25 |
+
torch.float32: True,
|
| 26 |
+
torch.float64: False,
|
| 27 |
+
torch.complex64: False,
|
| 28 |
+
torch.complex128: False,
|
| 29 |
+
torch.uint8: False,
|
| 30 |
+
torch.int8: False,
|
| 31 |
+
torch.int16: False,
|
| 32 |
+
torch.int32: False,
|
| 33 |
+
torch.int64: False,
|
| 34 |
+
torch.bool: False,
|
| 35 |
+
},
|
| 36 |
+
torch.float64: {
|
| 37 |
+
torch.float16: False,
|
| 38 |
+
torch.float32: False,
|
| 39 |
+
torch.float64: True,
|
| 40 |
+
torch.complex64: False,
|
| 41 |
+
torch.complex128: False,
|
| 42 |
+
torch.uint8: False,
|
| 43 |
+
torch.int8: False,
|
| 44 |
+
torch.int16: False,
|
| 45 |
+
torch.int32: False,
|
| 46 |
+
torch.int64: False,
|
| 47 |
+
torch.bool: False,
|
| 48 |
+
},
|
| 49 |
+
torch.complex64: {
|
| 50 |
+
torch.float16: False,
|
| 51 |
+
torch.float32: False,
|
| 52 |
+
torch.float64: False,
|
| 53 |
+
torch.complex64: True,
|
| 54 |
+
torch.complex128: False,
|
| 55 |
+
torch.uint8: False,
|
| 56 |
+
torch.int8: False,
|
| 57 |
+
torch.int16: False,
|
| 58 |
+
torch.int32: False,
|
| 59 |
+
torch.int64: False,
|
| 60 |
+
torch.bool: False,
|
| 61 |
+
},
|
| 62 |
+
torch.complex128: {
|
| 63 |
+
torch.float16: False,
|
| 64 |
+
torch.float32: False,
|
| 65 |
+
torch.float64: False,
|
| 66 |
+
torch.complex64: False,
|
| 67 |
+
torch.complex128: True,
|
| 68 |
+
torch.uint8: False,
|
| 69 |
+
torch.int8: False,
|
| 70 |
+
torch.int16: False,
|
| 71 |
+
torch.int32: False,
|
| 72 |
+
torch.int64: False,
|
| 73 |
+
torch.bool: False,
|
| 74 |
+
},
|
| 75 |
+
torch.uint8: {
|
| 76 |
+
torch.float16: False,
|
| 77 |
+
torch.float32: False,
|
| 78 |
+
torch.float64: False,
|
| 79 |
+
torch.complex64: False,
|
| 80 |
+
torch.complex128: False,
|
| 81 |
+
torch.uint8: True,
|
| 82 |
+
torch.int8: False,
|
| 83 |
+
torch.int16: False,
|
| 84 |
+
torch.int32: False,
|
| 85 |
+
torch.int64: False,
|
| 86 |
+
torch.bool: False,
|
| 87 |
+
},
|
| 88 |
+
torch.int8: {
|
| 89 |
+
torch.float16: False,
|
| 90 |
+
torch.float32: False,
|
| 91 |
+
torch.float64: False,
|
| 92 |
+
torch.complex64: False,
|
| 93 |
+
torch.complex128: False,
|
| 94 |
+
torch.uint8: False,
|
| 95 |
+
torch.int8: True,
|
| 96 |
+
torch.int16: False,
|
| 97 |
+
torch.int32: False,
|
| 98 |
+
torch.int64: False,
|
| 99 |
+
torch.bool: False,
|
| 100 |
+
},
|
| 101 |
+
torch.int16: {
|
| 102 |
+
torch.float16: False,
|
| 103 |
+
torch.float32: False,
|
| 104 |
+
torch.float64: False,
|
| 105 |
+
torch.complex64: False,
|
| 106 |
+
torch.complex128: False,
|
| 107 |
+
torch.uint8: False,
|
| 108 |
+
torch.int8: False,
|
| 109 |
+
torch.int16: True,
|
| 110 |
+
torch.int32: False,
|
| 111 |
+
torch.int64: False,
|
| 112 |
+
torch.bool: False,
|
| 113 |
+
},
|
| 114 |
+
torch.int32: {
|
| 115 |
+
torch.float16: False,
|
| 116 |
+
torch.float32: False,
|
| 117 |
+
torch.float64: False,
|
| 118 |
+
torch.complex64: False,
|
| 119 |
+
torch.complex128: False,
|
| 120 |
+
torch.uint8: False,
|
| 121 |
+
torch.int8: False,
|
| 122 |
+
torch.int16: False,
|
| 123 |
+
torch.int32: True,
|
| 124 |
+
torch.int64: False,
|
| 125 |
+
torch.bool: False,
|
| 126 |
+
},
|
| 127 |
+
torch.int64: {
|
| 128 |
+
torch.float16: False,
|
| 129 |
+
torch.float32: False,
|
| 130 |
+
torch.float64: False,
|
| 131 |
+
torch.complex64: False,
|
| 132 |
+
torch.complex128: False,
|
| 133 |
+
torch.uint8: False,
|
| 134 |
+
torch.int8: False,
|
| 135 |
+
torch.int16: False,
|
| 136 |
+
torch.int32: False,
|
| 137 |
+
torch.int64: True,
|
| 138 |
+
torch.bool: False,
|
| 139 |
+
},
|
| 140 |
+
torch.bool: {
|
| 141 |
+
torch.float16: False,
|
| 142 |
+
torch.float32: False,
|
| 143 |
+
torch.float64: False,
|
| 144 |
+
torch.complex64: False,
|
| 145 |
+
torch.complex128: False,
|
| 146 |
+
torch.uint8: False,
|
| 147 |
+
torch.int8: False,
|
| 148 |
+
torch.int16: False,
|
| 149 |
+
torch.int32: False,
|
| 150 |
+
torch.int64: False,
|
| 151 |
+
torch.bool: True,
|
| 152 |
+
},
|
| 153 |
+
},
|
| 154 |
+
"equiv": {
|
| 155 |
+
torch.float16: {
|
| 156 |
+
torch.float16: True,
|
| 157 |
+
torch.float32: False,
|
| 158 |
+
torch.float64: False,
|
| 159 |
+
torch.complex64: False,
|
| 160 |
+
torch.complex128: False,
|
| 161 |
+
torch.uint8: False,
|
| 162 |
+
torch.int8: False,
|
| 163 |
+
torch.int16: False,
|
| 164 |
+
torch.int32: False,
|
| 165 |
+
torch.int64: False,
|
| 166 |
+
torch.bool: False,
|
| 167 |
+
},
|
| 168 |
+
torch.float32: {
|
| 169 |
+
torch.float16: False,
|
| 170 |
+
torch.float32: True,
|
| 171 |
+
torch.float64: False,
|
| 172 |
+
torch.complex64: False,
|
| 173 |
+
torch.complex128: False,
|
| 174 |
+
torch.uint8: False,
|
| 175 |
+
torch.int8: False,
|
| 176 |
+
torch.int16: False,
|
| 177 |
+
torch.int32: False,
|
| 178 |
+
torch.int64: False,
|
| 179 |
+
torch.bool: False,
|
| 180 |
+
},
|
| 181 |
+
torch.float64: {
|
| 182 |
+
torch.float16: False,
|
| 183 |
+
torch.float32: False,
|
| 184 |
+
torch.float64: True,
|
| 185 |
+
torch.complex64: False,
|
| 186 |
+
torch.complex128: False,
|
| 187 |
+
torch.uint8: False,
|
| 188 |
+
torch.int8: False,
|
| 189 |
+
torch.int16: False,
|
| 190 |
+
torch.int32: False,
|
| 191 |
+
torch.int64: False,
|
| 192 |
+
torch.bool: False,
|
| 193 |
+
},
|
| 194 |
+
torch.complex64: {
|
| 195 |
+
torch.float16: False,
|
| 196 |
+
torch.float32: False,
|
| 197 |
+
torch.float64: False,
|
| 198 |
+
torch.complex64: True,
|
| 199 |
+
torch.complex128: False,
|
| 200 |
+
torch.uint8: False,
|
| 201 |
+
torch.int8: False,
|
| 202 |
+
torch.int16: False,
|
| 203 |
+
torch.int32: False,
|
| 204 |
+
torch.int64: False,
|
| 205 |
+
torch.bool: False,
|
| 206 |
+
},
|
| 207 |
+
torch.complex128: {
|
| 208 |
+
torch.float16: False,
|
| 209 |
+
torch.float32: False,
|
| 210 |
+
torch.float64: False,
|
| 211 |
+
torch.complex64: False,
|
| 212 |
+
torch.complex128: True,
|
| 213 |
+
torch.uint8: False,
|
| 214 |
+
torch.int8: False,
|
| 215 |
+
torch.int16: False,
|
| 216 |
+
torch.int32: False,
|
| 217 |
+
torch.int64: False,
|
| 218 |
+
torch.bool: False,
|
| 219 |
+
},
|
| 220 |
+
torch.uint8: {
|
| 221 |
+
torch.float16: False,
|
| 222 |
+
torch.float32: False,
|
| 223 |
+
torch.float64: False,
|
| 224 |
+
torch.complex64: False,
|
| 225 |
+
torch.complex128: False,
|
| 226 |
+
torch.uint8: True,
|
| 227 |
+
torch.int8: False,
|
| 228 |
+
torch.int16: False,
|
| 229 |
+
torch.int32: False,
|
| 230 |
+
torch.int64: False,
|
| 231 |
+
torch.bool: False,
|
| 232 |
+
},
|
| 233 |
+
torch.int8: {
|
| 234 |
+
torch.float16: False,
|
| 235 |
+
torch.float32: False,
|
| 236 |
+
torch.float64: False,
|
| 237 |
+
torch.complex64: False,
|
| 238 |
+
torch.complex128: False,
|
| 239 |
+
torch.uint8: False,
|
| 240 |
+
torch.int8: True,
|
| 241 |
+
torch.int16: False,
|
| 242 |
+
torch.int32: False,
|
| 243 |
+
torch.int64: False,
|
| 244 |
+
torch.bool: False,
|
| 245 |
+
},
|
| 246 |
+
torch.int16: {
|
| 247 |
+
torch.float16: False,
|
| 248 |
+
torch.float32: False,
|
| 249 |
+
torch.float64: False,
|
| 250 |
+
torch.complex64: False,
|
| 251 |
+
torch.complex128: False,
|
| 252 |
+
torch.uint8: False,
|
| 253 |
+
torch.int8: False,
|
| 254 |
+
torch.int16: True,
|
| 255 |
+
torch.int32: False,
|
| 256 |
+
torch.int64: False,
|
| 257 |
+
torch.bool: False,
|
| 258 |
+
},
|
| 259 |
+
torch.int32: {
|
| 260 |
+
torch.float16: False,
|
| 261 |
+
torch.float32: False,
|
| 262 |
+
torch.float64: False,
|
| 263 |
+
torch.complex64: False,
|
| 264 |
+
torch.complex128: False,
|
| 265 |
+
torch.uint8: False,
|
| 266 |
+
torch.int8: False,
|
| 267 |
+
torch.int16: False,
|
| 268 |
+
torch.int32: True,
|
| 269 |
+
torch.int64: False,
|
| 270 |
+
torch.bool: False,
|
| 271 |
+
},
|
| 272 |
+
torch.int64: {
|
| 273 |
+
torch.float16: False,
|
| 274 |
+
torch.float32: False,
|
| 275 |
+
torch.float64: False,
|
| 276 |
+
torch.complex64: False,
|
| 277 |
+
torch.complex128: False,
|
| 278 |
+
torch.uint8: False,
|
| 279 |
+
torch.int8: False,
|
| 280 |
+
torch.int16: False,
|
| 281 |
+
torch.int32: False,
|
| 282 |
+
torch.int64: True,
|
| 283 |
+
torch.bool: False,
|
| 284 |
+
},
|
| 285 |
+
torch.bool: {
|
| 286 |
+
torch.float16: False,
|
| 287 |
+
torch.float32: False,
|
| 288 |
+
torch.float64: False,
|
| 289 |
+
torch.complex64: False,
|
| 290 |
+
torch.complex128: False,
|
| 291 |
+
torch.uint8: False,
|
| 292 |
+
torch.int8: False,
|
| 293 |
+
torch.int16: False,
|
| 294 |
+
torch.int32: False,
|
| 295 |
+
torch.int64: False,
|
| 296 |
+
torch.bool: True,
|
| 297 |
+
},
|
| 298 |
+
},
|
| 299 |
+
"safe": {
|
| 300 |
+
torch.float16: {
|
| 301 |
+
torch.float16: True,
|
| 302 |
+
torch.float32: True,
|
| 303 |
+
torch.float64: True,
|
| 304 |
+
torch.complex64: True,
|
| 305 |
+
torch.complex128: True,
|
| 306 |
+
torch.uint8: False,
|
| 307 |
+
torch.int8: False,
|
| 308 |
+
torch.int16: False,
|
| 309 |
+
torch.int32: False,
|
| 310 |
+
torch.int64: False,
|
| 311 |
+
torch.bool: False,
|
| 312 |
+
},
|
| 313 |
+
torch.float32: {
|
| 314 |
+
torch.float16: False,
|
| 315 |
+
torch.float32: True,
|
| 316 |
+
torch.float64: True,
|
| 317 |
+
torch.complex64: True,
|
| 318 |
+
torch.complex128: True,
|
| 319 |
+
torch.uint8: False,
|
| 320 |
+
torch.int8: False,
|
| 321 |
+
torch.int16: False,
|
| 322 |
+
torch.int32: False,
|
| 323 |
+
torch.int64: False,
|
| 324 |
+
torch.bool: False,
|
| 325 |
+
},
|
| 326 |
+
torch.float64: {
|
| 327 |
+
torch.float16: False,
|
| 328 |
+
torch.float32: False,
|
| 329 |
+
torch.float64: True,
|
| 330 |
+
torch.complex64: False,
|
| 331 |
+
torch.complex128: True,
|
| 332 |
+
torch.uint8: False,
|
| 333 |
+
torch.int8: False,
|
| 334 |
+
torch.int16: False,
|
| 335 |
+
torch.int32: False,
|
| 336 |
+
torch.int64: False,
|
| 337 |
+
torch.bool: False,
|
| 338 |
+
},
|
| 339 |
+
torch.complex64: {
|
| 340 |
+
torch.float16: False,
|
| 341 |
+
torch.float32: False,
|
| 342 |
+
torch.float64: False,
|
| 343 |
+
torch.complex64: True,
|
| 344 |
+
torch.complex128: True,
|
| 345 |
+
torch.uint8: False,
|
| 346 |
+
torch.int8: False,
|
| 347 |
+
torch.int16: False,
|
| 348 |
+
torch.int32: False,
|
| 349 |
+
torch.int64: False,
|
| 350 |
+
torch.bool: False,
|
| 351 |
+
},
|
| 352 |
+
torch.complex128: {
|
| 353 |
+
torch.float16: False,
|
| 354 |
+
torch.float32: False,
|
| 355 |
+
torch.float64: False,
|
| 356 |
+
torch.complex64: False,
|
| 357 |
+
torch.complex128: True,
|
| 358 |
+
torch.uint8: False,
|
| 359 |
+
torch.int8: False,
|
| 360 |
+
torch.int16: False,
|
| 361 |
+
torch.int32: False,
|
| 362 |
+
torch.int64: False,
|
| 363 |
+
torch.bool: False,
|
| 364 |
+
},
|
| 365 |
+
torch.uint8: {
|
| 366 |
+
torch.float16: True,
|
| 367 |
+
torch.float32: True,
|
| 368 |
+
torch.float64: True,
|
| 369 |
+
torch.complex64: True,
|
| 370 |
+
torch.complex128: True,
|
| 371 |
+
torch.uint8: True,
|
| 372 |
+
torch.int8: False,
|
| 373 |
+
torch.int16: True,
|
| 374 |
+
torch.int32: True,
|
| 375 |
+
torch.int64: True,
|
| 376 |
+
torch.bool: False,
|
| 377 |
+
},
|
| 378 |
+
torch.int8: {
|
| 379 |
+
torch.float16: True,
|
| 380 |
+
torch.float32: True,
|
| 381 |
+
torch.float64: True,
|
| 382 |
+
torch.complex64: True,
|
| 383 |
+
torch.complex128: True,
|
| 384 |
+
torch.uint8: False,
|
| 385 |
+
torch.int8: True,
|
| 386 |
+
torch.int16: True,
|
| 387 |
+
torch.int32: True,
|
| 388 |
+
torch.int64: True,
|
| 389 |
+
torch.bool: False,
|
| 390 |
+
},
|
| 391 |
+
torch.int16: {
|
| 392 |
+
torch.float16: False,
|
| 393 |
+
torch.float32: True,
|
| 394 |
+
torch.float64: True,
|
| 395 |
+
torch.complex64: True,
|
| 396 |
+
torch.complex128: True,
|
| 397 |
+
torch.uint8: False,
|
| 398 |
+
torch.int8: False,
|
| 399 |
+
torch.int16: True,
|
| 400 |
+
torch.int32: True,
|
| 401 |
+
torch.int64: True,
|
| 402 |
+
torch.bool: False,
|
| 403 |
+
},
|
| 404 |
+
torch.int32: {
|
| 405 |
+
torch.float16: False,
|
| 406 |
+
torch.float32: False,
|
| 407 |
+
torch.float64: True,
|
| 408 |
+
torch.complex64: False,
|
| 409 |
+
torch.complex128: True,
|
| 410 |
+
torch.uint8: False,
|
| 411 |
+
torch.int8: False,
|
| 412 |
+
torch.int16: False,
|
| 413 |
+
torch.int32: True,
|
| 414 |
+
torch.int64: True,
|
| 415 |
+
torch.bool: False,
|
| 416 |
+
},
|
| 417 |
+
torch.int64: {
|
| 418 |
+
torch.float16: False,
|
| 419 |
+
torch.float32: False,
|
| 420 |
+
torch.float64: True,
|
| 421 |
+
torch.complex64: False,
|
| 422 |
+
torch.complex128: True,
|
| 423 |
+
torch.uint8: False,
|
| 424 |
+
torch.int8: False,
|
| 425 |
+
torch.int16: False,
|
| 426 |
+
torch.int32: False,
|
| 427 |
+
torch.int64: True,
|
| 428 |
+
torch.bool: False,
|
| 429 |
+
},
|
| 430 |
+
torch.bool: {
|
| 431 |
+
torch.float16: True,
|
| 432 |
+
torch.float32: True,
|
| 433 |
+
torch.float64: True,
|
| 434 |
+
torch.complex64: True,
|
| 435 |
+
torch.complex128: True,
|
| 436 |
+
torch.uint8: True,
|
| 437 |
+
torch.int8: True,
|
| 438 |
+
torch.int16: True,
|
| 439 |
+
torch.int32: True,
|
| 440 |
+
torch.int64: True,
|
| 441 |
+
torch.bool: True,
|
| 442 |
+
},
|
| 443 |
+
},
|
| 444 |
+
"same_kind": {
|
| 445 |
+
torch.float16: {
|
| 446 |
+
torch.float16: True,
|
| 447 |
+
torch.float32: True,
|
| 448 |
+
torch.float64: True,
|
| 449 |
+
torch.complex64: True,
|
| 450 |
+
torch.complex128: True,
|
| 451 |
+
torch.uint8: False,
|
| 452 |
+
torch.int8: False,
|
| 453 |
+
torch.int16: False,
|
| 454 |
+
torch.int32: False,
|
| 455 |
+
torch.int64: False,
|
| 456 |
+
torch.bool: False,
|
| 457 |
+
},
|
| 458 |
+
torch.float32: {
|
| 459 |
+
torch.float16: True,
|
| 460 |
+
torch.float32: True,
|
| 461 |
+
torch.float64: True,
|
| 462 |
+
torch.complex64: True,
|
| 463 |
+
torch.complex128: True,
|
| 464 |
+
torch.uint8: False,
|
| 465 |
+
torch.int8: False,
|
| 466 |
+
torch.int16: False,
|
| 467 |
+
torch.int32: False,
|
| 468 |
+
torch.int64: False,
|
| 469 |
+
torch.bool: False,
|
| 470 |
+
},
|
| 471 |
+
torch.float64: {
|
| 472 |
+
torch.float16: True,
|
| 473 |
+
torch.float32: True,
|
| 474 |
+
torch.float64: True,
|
| 475 |
+
torch.complex64: True,
|
| 476 |
+
torch.complex128: True,
|
| 477 |
+
torch.uint8: False,
|
| 478 |
+
torch.int8: False,
|
| 479 |
+
torch.int16: False,
|
| 480 |
+
torch.int32: False,
|
| 481 |
+
torch.int64: False,
|
| 482 |
+
torch.bool: False,
|
| 483 |
+
},
|
| 484 |
+
torch.complex64: {
|
| 485 |
+
torch.float16: False,
|
| 486 |
+
torch.float32: False,
|
| 487 |
+
torch.float64: False,
|
| 488 |
+
torch.complex64: True,
|
| 489 |
+
torch.complex128: True,
|
| 490 |
+
torch.uint8: False,
|
| 491 |
+
torch.int8: False,
|
| 492 |
+
torch.int16: False,
|
| 493 |
+
torch.int32: False,
|
| 494 |
+
torch.int64: False,
|
| 495 |
+
torch.bool: False,
|
| 496 |
+
},
|
| 497 |
+
torch.complex128: {
|
| 498 |
+
torch.float16: False,
|
| 499 |
+
torch.float32: False,
|
| 500 |
+
torch.float64: False,
|
| 501 |
+
torch.complex64: True,
|
| 502 |
+
torch.complex128: True,
|
| 503 |
+
torch.uint8: False,
|
| 504 |
+
torch.int8: False,
|
| 505 |
+
torch.int16: False,
|
| 506 |
+
torch.int32: False,
|
| 507 |
+
torch.int64: False,
|
| 508 |
+
torch.bool: False,
|
| 509 |
+
},
|
| 510 |
+
torch.uint8: {
|
| 511 |
+
torch.float16: True,
|
| 512 |
+
torch.float32: True,
|
| 513 |
+
torch.float64: True,
|
| 514 |
+
torch.complex64: True,
|
| 515 |
+
torch.complex128: True,
|
| 516 |
+
torch.uint8: True,
|
| 517 |
+
torch.int8: True,
|
| 518 |
+
torch.int16: True,
|
| 519 |
+
torch.int32: True,
|
| 520 |
+
torch.int64: True,
|
| 521 |
+
torch.bool: False,
|
| 522 |
+
},
|
| 523 |
+
torch.int8: {
|
| 524 |
+
torch.float16: True,
|
| 525 |
+
torch.float32: True,
|
| 526 |
+
torch.float64: True,
|
| 527 |
+
torch.complex64: True,
|
| 528 |
+
torch.complex128: True,
|
| 529 |
+
torch.uint8: False,
|
| 530 |
+
torch.int8: True,
|
| 531 |
+
torch.int16: True,
|
| 532 |
+
torch.int32: True,
|
| 533 |
+
torch.int64: True,
|
| 534 |
+
torch.bool: False,
|
| 535 |
+
},
|
| 536 |
+
torch.int16: {
|
| 537 |
+
torch.float16: True,
|
| 538 |
+
torch.float32: True,
|
| 539 |
+
torch.float64: True,
|
| 540 |
+
torch.complex64: True,
|
| 541 |
+
torch.complex128: True,
|
| 542 |
+
torch.uint8: False,
|
| 543 |
+
torch.int8: True,
|
| 544 |
+
torch.int16: True,
|
| 545 |
+
torch.int32: True,
|
| 546 |
+
torch.int64: True,
|
| 547 |
+
torch.bool: False,
|
| 548 |
+
},
|
| 549 |
+
torch.int32: {
|
| 550 |
+
torch.float16: True,
|
| 551 |
+
torch.float32: True,
|
| 552 |
+
torch.float64: True,
|
| 553 |
+
torch.complex64: True,
|
| 554 |
+
torch.complex128: True,
|
| 555 |
+
torch.uint8: False,
|
| 556 |
+
torch.int8: True,
|
| 557 |
+
torch.int16: True,
|
| 558 |
+
torch.int32: True,
|
| 559 |
+
torch.int64: True,
|
| 560 |
+
torch.bool: False,
|
| 561 |
+
},
|
| 562 |
+
torch.int64: {
|
| 563 |
+
torch.float16: True,
|
| 564 |
+
torch.float32: True,
|
| 565 |
+
torch.float64: True,
|
| 566 |
+
torch.complex64: True,
|
| 567 |
+
torch.complex128: True,
|
| 568 |
+
torch.uint8: False,
|
| 569 |
+
torch.int8: True,
|
| 570 |
+
torch.int16: True,
|
| 571 |
+
torch.int32: True,
|
| 572 |
+
torch.int64: True,
|
| 573 |
+
torch.bool: False,
|
| 574 |
+
},
|
| 575 |
+
torch.bool: {
|
| 576 |
+
torch.float16: True,
|
| 577 |
+
torch.float32: True,
|
| 578 |
+
torch.float64: True,
|
| 579 |
+
torch.complex64: True,
|
| 580 |
+
torch.complex128: True,
|
| 581 |
+
torch.uint8: True,
|
| 582 |
+
torch.int8: True,
|
| 583 |
+
torch.int16: True,
|
| 584 |
+
torch.int32: True,
|
| 585 |
+
torch.int64: True,
|
| 586 |
+
torch.bool: True,
|
| 587 |
+
},
|
| 588 |
+
},
|
| 589 |
+
"unsafe": {
|
| 590 |
+
torch.float16: {
|
| 591 |
+
torch.float16: True,
|
| 592 |
+
torch.float32: True,
|
| 593 |
+
torch.float64: True,
|
| 594 |
+
torch.complex64: True,
|
| 595 |
+
torch.complex128: True,
|
| 596 |
+
torch.uint8: True,
|
| 597 |
+
torch.int8: True,
|
| 598 |
+
torch.int16: True,
|
| 599 |
+
torch.int32: True,
|
| 600 |
+
torch.int64: True,
|
| 601 |
+
torch.bool: True,
|
| 602 |
+
},
|
| 603 |
+
torch.float32: {
|
| 604 |
+
torch.float16: True,
|
| 605 |
+
torch.float32: True,
|
| 606 |
+
torch.float64: True,
|
| 607 |
+
torch.complex64: True,
|
| 608 |
+
torch.complex128: True,
|
| 609 |
+
torch.uint8: True,
|
| 610 |
+
torch.int8: True,
|
| 611 |
+
torch.int16: True,
|
| 612 |
+
torch.int32: True,
|
| 613 |
+
torch.int64: True,
|
| 614 |
+
torch.bool: True,
|
| 615 |
+
},
|
| 616 |
+
torch.float64: {
|
| 617 |
+
torch.float16: True,
|
| 618 |
+
torch.float32: True,
|
| 619 |
+
torch.float64: True,
|
| 620 |
+
torch.complex64: True,
|
| 621 |
+
torch.complex128: True,
|
| 622 |
+
torch.uint8: True,
|
| 623 |
+
torch.int8: True,
|
| 624 |
+
torch.int16: True,
|
| 625 |
+
torch.int32: True,
|
| 626 |
+
torch.int64: True,
|
| 627 |
+
torch.bool: True,
|
| 628 |
+
},
|
| 629 |
+
torch.complex64: {
|
| 630 |
+
torch.float16: True,
|
| 631 |
+
torch.float32: True,
|
| 632 |
+
torch.float64: True,
|
| 633 |
+
torch.complex64: True,
|
| 634 |
+
torch.complex128: True,
|
| 635 |
+
torch.uint8: True,
|
| 636 |
+
torch.int8: True,
|
| 637 |
+
torch.int16: True,
|
| 638 |
+
torch.int32: True,
|
| 639 |
+
torch.int64: True,
|
| 640 |
+
torch.bool: True,
|
| 641 |
+
},
|
| 642 |
+
torch.complex128: {
|
| 643 |
+
torch.float16: True,
|
| 644 |
+
torch.float32: True,
|
| 645 |
+
torch.float64: True,
|
| 646 |
+
torch.complex64: True,
|
| 647 |
+
torch.complex128: True,
|
| 648 |
+
torch.uint8: True,
|
| 649 |
+
torch.int8: True,
|
| 650 |
+
torch.int16: True,
|
| 651 |
+
torch.int32: True,
|
| 652 |
+
torch.int64: True,
|
| 653 |
+
torch.bool: True,
|
| 654 |
+
},
|
| 655 |
+
torch.uint8: {
|
| 656 |
+
torch.float16: True,
|
| 657 |
+
torch.float32: True,
|
| 658 |
+
torch.float64: True,
|
| 659 |
+
torch.complex64: True,
|
| 660 |
+
torch.complex128: True,
|
| 661 |
+
torch.uint8: True,
|
| 662 |
+
torch.int8: True,
|
| 663 |
+
torch.int16: True,
|
| 664 |
+
torch.int32: True,
|
| 665 |
+
torch.int64: True,
|
| 666 |
+
torch.bool: True,
|
| 667 |
+
},
|
| 668 |
+
torch.int8: {
|
| 669 |
+
torch.float16: True,
|
| 670 |
+
torch.float32: True,
|
| 671 |
+
torch.float64: True,
|
| 672 |
+
torch.complex64: True,
|
| 673 |
+
torch.complex128: True,
|
| 674 |
+
torch.uint8: True,
|
| 675 |
+
torch.int8: True,
|
| 676 |
+
torch.int16: True,
|
| 677 |
+
torch.int32: True,
|
| 678 |
+
torch.int64: True,
|
| 679 |
+
torch.bool: True,
|
| 680 |
+
},
|
| 681 |
+
torch.int16: {
|
| 682 |
+
torch.float16: True,
|
| 683 |
+
torch.float32: True,
|
| 684 |
+
torch.float64: True,
|
| 685 |
+
torch.complex64: True,
|
| 686 |
+
torch.complex128: True,
|
| 687 |
+
torch.uint8: True,
|
| 688 |
+
torch.int8: True,
|
| 689 |
+
torch.int16: True,
|
| 690 |
+
torch.int32: True,
|
| 691 |
+
torch.int64: True,
|
| 692 |
+
torch.bool: True,
|
| 693 |
+
},
|
| 694 |
+
torch.int32: {
|
| 695 |
+
torch.float16: True,
|
| 696 |
+
torch.float32: True,
|
| 697 |
+
torch.float64: True,
|
| 698 |
+
torch.complex64: True,
|
| 699 |
+
torch.complex128: True,
|
| 700 |
+
torch.uint8: True,
|
| 701 |
+
torch.int8: True,
|
| 702 |
+
torch.int16: True,
|
| 703 |
+
torch.int32: True,
|
| 704 |
+
torch.int64: True,
|
| 705 |
+
torch.bool: True,
|
| 706 |
+
},
|
| 707 |
+
torch.int64: {
|
| 708 |
+
torch.float16: True,
|
| 709 |
+
torch.float32: True,
|
| 710 |
+
torch.float64: True,
|
| 711 |
+
torch.complex64: True,
|
| 712 |
+
torch.complex128: True,
|
| 713 |
+
torch.uint8: True,
|
| 714 |
+
torch.int8: True,
|
| 715 |
+
torch.int16: True,
|
| 716 |
+
torch.int32: True,
|
| 717 |
+
torch.int64: True,
|
| 718 |
+
torch.bool: True,
|
| 719 |
+
},
|
| 720 |
+
torch.bool: {
|
| 721 |
+
torch.float16: True,
|
| 722 |
+
torch.float32: True,
|
| 723 |
+
torch.float64: True,
|
| 724 |
+
torch.complex64: True,
|
| 725 |
+
torch.complex128: True,
|
| 726 |
+
torch.uint8: True,
|
| 727 |
+
torch.int8: True,
|
| 728 |
+
torch.int16: True,
|
| 729 |
+
torch.int32: True,
|
| 730 |
+
torch.int64: True,
|
| 731 |
+
torch.bool: True,
|
| 732 |
+
},
|
| 733 |
+
},
|
| 734 |
+
}
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
_result_type_dict = {
|
| 738 |
+
torch.float16: {
|
| 739 |
+
torch.float16: torch.float16,
|
| 740 |
+
torch.float32: torch.float32,
|
| 741 |
+
torch.float64: torch.float64,
|
| 742 |
+
torch.complex64: torch.complex64,
|
| 743 |
+
torch.complex128: torch.complex128,
|
| 744 |
+
torch.uint8: torch.float16,
|
| 745 |
+
torch.int8: torch.float16,
|
| 746 |
+
torch.int16: torch.float32,
|
| 747 |
+
torch.int32: torch.float64,
|
| 748 |
+
torch.int64: torch.float64,
|
| 749 |
+
torch.bool: torch.float16,
|
| 750 |
+
},
|
| 751 |
+
torch.float32: {
|
| 752 |
+
torch.float16: torch.float32,
|
| 753 |
+
torch.float32: torch.float32,
|
| 754 |
+
torch.float64: torch.float64,
|
| 755 |
+
torch.complex64: torch.complex64,
|
| 756 |
+
torch.complex128: torch.complex128,
|
| 757 |
+
torch.uint8: torch.float32,
|
| 758 |
+
torch.int8: torch.float32,
|
| 759 |
+
torch.int16: torch.float32,
|
| 760 |
+
torch.int32: torch.float64,
|
| 761 |
+
torch.int64: torch.float64,
|
| 762 |
+
torch.bool: torch.float32,
|
| 763 |
+
},
|
| 764 |
+
torch.float64: {
|
| 765 |
+
torch.float16: torch.float64,
|
| 766 |
+
torch.float32: torch.float64,
|
| 767 |
+
torch.float64: torch.float64,
|
| 768 |
+
torch.complex64: torch.complex128,
|
| 769 |
+
torch.complex128: torch.complex128,
|
| 770 |
+
torch.uint8: torch.float64,
|
| 771 |
+
torch.int8: torch.float64,
|
| 772 |
+
torch.int16: torch.float64,
|
| 773 |
+
torch.int32: torch.float64,
|
| 774 |
+
torch.int64: torch.float64,
|
| 775 |
+
torch.bool: torch.float64,
|
| 776 |
+
},
|
| 777 |
+
torch.complex64: {
|
| 778 |
+
torch.float16: torch.complex64,
|
| 779 |
+
torch.float32: torch.complex64,
|
| 780 |
+
torch.float64: torch.complex128,
|
| 781 |
+
torch.complex64: torch.complex64,
|
| 782 |
+
torch.complex128: torch.complex128,
|
| 783 |
+
torch.uint8: torch.complex64,
|
| 784 |
+
torch.int8: torch.complex64,
|
| 785 |
+
torch.int16: torch.complex64,
|
| 786 |
+
torch.int32: torch.complex128,
|
| 787 |
+
torch.int64: torch.complex128,
|
| 788 |
+
torch.bool: torch.complex64,
|
| 789 |
+
},
|
| 790 |
+
torch.complex128: {
|
| 791 |
+
torch.float16: torch.complex128,
|
| 792 |
+
torch.float32: torch.complex128,
|
| 793 |
+
torch.float64: torch.complex128,
|
| 794 |
+
torch.complex64: torch.complex128,
|
| 795 |
+
torch.complex128: torch.complex128,
|
| 796 |
+
torch.uint8: torch.complex128,
|
| 797 |
+
torch.int8: torch.complex128,
|
| 798 |
+
torch.int16: torch.complex128,
|
| 799 |
+
torch.int32: torch.complex128,
|
| 800 |
+
torch.int64: torch.complex128,
|
| 801 |
+
torch.bool: torch.complex128,
|
| 802 |
+
},
|
| 803 |
+
torch.uint8: {
|
| 804 |
+
torch.float16: torch.float16,
|
| 805 |
+
torch.float32: torch.float32,
|
| 806 |
+
torch.float64: torch.float64,
|
| 807 |
+
torch.complex64: torch.complex64,
|
| 808 |
+
torch.complex128: torch.complex128,
|
| 809 |
+
torch.uint8: torch.uint8,
|
| 810 |
+
torch.int8: torch.int16,
|
| 811 |
+
torch.int16: torch.int16,
|
| 812 |
+
torch.int32: torch.int32,
|
| 813 |
+
torch.int64: torch.int64,
|
| 814 |
+
torch.bool: torch.uint8,
|
| 815 |
+
},
|
| 816 |
+
torch.int8: {
|
| 817 |
+
torch.float16: torch.float16,
|
| 818 |
+
torch.float32: torch.float32,
|
| 819 |
+
torch.float64: torch.float64,
|
| 820 |
+
torch.complex64: torch.complex64,
|
| 821 |
+
torch.complex128: torch.complex128,
|
| 822 |
+
torch.uint8: torch.int16,
|
| 823 |
+
torch.int8: torch.int8,
|
| 824 |
+
torch.int16: torch.int16,
|
| 825 |
+
torch.int32: torch.int32,
|
| 826 |
+
torch.int64: torch.int64,
|
| 827 |
+
torch.bool: torch.int8,
|
| 828 |
+
},
|
| 829 |
+
torch.int16: {
|
| 830 |
+
torch.float16: torch.float32,
|
| 831 |
+
torch.float32: torch.float32,
|
| 832 |
+
torch.float64: torch.float64,
|
| 833 |
+
torch.complex64: torch.complex64,
|
| 834 |
+
torch.complex128: torch.complex128,
|
| 835 |
+
torch.uint8: torch.int16,
|
| 836 |
+
torch.int8: torch.int16,
|
| 837 |
+
torch.int16: torch.int16,
|
| 838 |
+
torch.int32: torch.int32,
|
| 839 |
+
torch.int64: torch.int64,
|
| 840 |
+
torch.bool: torch.int16,
|
| 841 |
+
},
|
| 842 |
+
torch.int32: {
|
| 843 |
+
torch.float16: torch.float64,
|
| 844 |
+
torch.float32: torch.float64,
|
| 845 |
+
torch.float64: torch.float64,
|
| 846 |
+
torch.complex64: torch.complex128,
|
| 847 |
+
torch.complex128: torch.complex128,
|
| 848 |
+
torch.uint8: torch.int32,
|
| 849 |
+
torch.int8: torch.int32,
|
| 850 |
+
torch.int16: torch.int32,
|
| 851 |
+
torch.int32: torch.int32,
|
| 852 |
+
torch.int64: torch.int64,
|
| 853 |
+
torch.bool: torch.int32,
|
| 854 |
+
},
|
| 855 |
+
torch.int64: {
|
| 856 |
+
torch.float16: torch.float64,
|
| 857 |
+
torch.float32: torch.float64,
|
| 858 |
+
torch.float64: torch.float64,
|
| 859 |
+
torch.complex64: torch.complex128,
|
| 860 |
+
torch.complex128: torch.complex128,
|
| 861 |
+
torch.uint8: torch.int64,
|
| 862 |
+
torch.int8: torch.int64,
|
| 863 |
+
torch.int16: torch.int64,
|
| 864 |
+
torch.int32: torch.int64,
|
| 865 |
+
torch.int64: torch.int64,
|
| 866 |
+
torch.bool: torch.int64,
|
| 867 |
+
},
|
| 868 |
+
torch.bool: {
|
| 869 |
+
torch.float16: torch.float16,
|
| 870 |
+
torch.float32: torch.float32,
|
| 871 |
+
torch.float64: torch.float64,
|
| 872 |
+
torch.complex64: torch.complex64,
|
| 873 |
+
torch.complex128: torch.complex128,
|
| 874 |
+
torch.uint8: torch.uint8,
|
| 875 |
+
torch.int8: torch.int8,
|
| 876 |
+
torch.int16: torch.int16,
|
| 877 |
+
torch.int32: torch.int32,
|
| 878 |
+
torch.int64: torch.int64,
|
| 879 |
+
torch.bool: torch.bool,
|
| 880 |
+
},
|
| 881 |
+
}
|
shared/package-files/41/41d7bbdf2f62da80eefc257751f2636c3d3eba990c25b9489ff46f708ce2f83e/blob
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: bdist_wheel (0.38.4)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-linux_x86_64
|
| 5 |
+
|
shared/package-files/41/41da0e7eaac03dd6f0b6d2ebcdf01ee7968423665cc787d0850a7a853fe57c5b/blob
ADDED
|
Binary file (1.09 kB). View file
|
|
|
shared/package-files/41/41da76f5afb7ce062d248f762463a92f7ca47e4e0f905b224ba6afeef91ded0f/blob
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
| 3 |
+
"$id": "https://json-schema.org/draft/2020-12/schema",
|
| 4 |
+
"$vocabulary": {
|
| 5 |
+
"https://json-schema.org/draft/2020-12/vocab/core": true,
|
| 6 |
+
"https://json-schema.org/draft/2020-12/vocab/applicator": true,
|
| 7 |
+
"https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
|
| 8 |
+
"https://json-schema.org/draft/2020-12/vocab/validation": true,
|
| 9 |
+
"https://json-schema.org/draft/2020-12/vocab/meta-data": true,
|
| 10 |
+
"https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
|
| 11 |
+
"https://json-schema.org/draft/2020-12/vocab/content": true
|
| 12 |
+
},
|
| 13 |
+
"$dynamicAnchor": "meta",
|
| 14 |
+
|
| 15 |
+
"title": "Core and Validation specifications meta-schema",
|
| 16 |
+
"allOf": [
|
| 17 |
+
{"$ref": "meta/core"},
|
| 18 |
+
{"$ref": "meta/applicator"},
|
| 19 |
+
{"$ref": "meta/unevaluated"},
|
| 20 |
+
{"$ref": "meta/validation"},
|
| 21 |
+
{"$ref": "meta/meta-data"},
|
| 22 |
+
{"$ref": "meta/format-annotation"},
|
| 23 |
+
{"$ref": "meta/content"}
|
| 24 |
+
],
|
| 25 |
+
"type": ["object", "boolean"],
|
| 26 |
+
"$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.",
|
| 27 |
+
"properties": {
|
| 28 |
+
"definitions": {
|
| 29 |
+
"$comment": "\"definitions\" has been replaced by \"$defs\".",
|
| 30 |
+
"type": "object",
|
| 31 |
+
"additionalProperties": { "$dynamicRef": "#meta" },
|
| 32 |
+
"deprecated": true,
|
| 33 |
+
"default": {}
|
| 34 |
+
},
|
| 35 |
+
"dependencies": {
|
| 36 |
+
"$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
|
| 37 |
+
"type": "object",
|
| 38 |
+
"additionalProperties": {
|
| 39 |
+
"anyOf": [
|
| 40 |
+
{ "$dynamicRef": "#meta" },
|
| 41 |
+
{ "$ref": "meta/validation#/$defs/stringArray" }
|
| 42 |
+
]
|
| 43 |
+
},
|
| 44 |
+
"deprecated": true,
|
| 45 |
+
"default": {}
|
| 46 |
+
},
|
| 47 |
+
"$recursiveAnchor": {
|
| 48 |
+
"$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
|
| 49 |
+
"$ref": "meta/core#/$defs/anchorString",
|
| 50 |
+
"deprecated": true
|
| 51 |
+
},
|
| 52 |
+
"$recursiveRef": {
|
| 53 |
+
"$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
|
| 54 |
+
"$ref": "meta/core#/$defs/uriReferenceString",
|
| 55 |
+
"deprecated": true
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
}
|
shared/package-files/41/41dc9d81c4a6464bff41eb29c21b84fefad74914be7e77d578a78876c6d392e6/blob
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace cpu {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor quantize_per_tensor(const at::Tensor & self, double scale, int64_t zero_point, at::ScalarType dtype);
|
| 21 |
+
TORCH_API at::Tensor quantize_per_tensor(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, at::ScalarType dtype);
|
| 22 |
+
TORCH_API ::std::vector<at::Tensor> quantize_per_tensor(at::TensorList tensors, const at::Tensor & scales, const at::Tensor & zero_points, at::ScalarType dtype);
|
| 23 |
+
|
| 24 |
+
} // namespace cpu
|
| 25 |
+
} // namespace at
|
shared/package-files/41/41df4cdb9a30165dd83ae009fcbafe8408759bb6d1c7314412c3960ece8aebc6/blob
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Translated into C++ by SciPy developers in 2024.
|
| 2 |
+
* Original header with Copyright information appears below.
|
| 3 |
+
*/
|
| 4 |
+
|
| 5 |
+
/* j1.c
|
| 6 |
+
*
|
| 7 |
+
* Bessel function of order one
|
| 8 |
+
*
|
| 9 |
+
*
|
| 10 |
+
*
|
| 11 |
+
* SYNOPSIS:
|
| 12 |
+
*
|
| 13 |
+
* double x, y, j1();
|
| 14 |
+
*
|
| 15 |
+
* y = j1( x );
|
| 16 |
+
*
|
| 17 |
+
*
|
| 18 |
+
*
|
| 19 |
+
* DESCRIPTION:
|
| 20 |
+
*
|
| 21 |
+
* Returns Bessel function of order one of the argument.
|
| 22 |
+
*
|
| 23 |
+
* The domain is divided into the intervals [0, 8] and
|
| 24 |
+
* (8, infinity). In the first interval a 24 term Chebyshev
|
| 25 |
+
* expansion is used. In the second, the asymptotic
|
| 26 |
+
* trigonometric representation is employed using two
|
| 27 |
+
* rational functions of degree 5/5.
|
| 28 |
+
*
|
| 29 |
+
*
|
| 30 |
+
*
|
| 31 |
+
* ACCURACY:
|
| 32 |
+
*
|
| 33 |
+
* Absolute error:
|
| 34 |
+
* arithmetic domain # trials peak rms
|
| 35 |
+
* IEEE 0, 30 30000 2.6e-16 1.1e-16
|
| 36 |
+
*
|
| 37 |
+
*
|
| 38 |
+
*/
|
| 39 |
+
/* y1.c
|
| 40 |
+
*
|
| 41 |
+
* Bessel function of second kind of order one
|
| 42 |
+
*
|
| 43 |
+
*
|
| 44 |
+
*
|
| 45 |
+
* SYNOPSIS:
|
| 46 |
+
*
|
| 47 |
+
* double x, y, y1();
|
| 48 |
+
*
|
| 49 |
+
* y = y1( x );
|
| 50 |
+
*
|
| 51 |
+
*
|
| 52 |
+
*
|
| 53 |
+
* DESCRIPTION:
|
| 54 |
+
*
|
| 55 |
+
* Returns Bessel function of the second kind of order one
|
| 56 |
+
* of the argument.
|
| 57 |
+
*
|
| 58 |
+
* The domain is divided into the intervals [0, 8] and
|
| 59 |
+
* (8, infinity). In the first interval a 25 term Chebyshev
|
| 60 |
+
* expansion is used, and a call to j1() is required.
|
| 61 |
+
* In the second, the asymptotic trigonometric representation
|
| 62 |
+
* is employed using two rational functions of degree 5/5.
|
| 63 |
+
*
|
| 64 |
+
*
|
| 65 |
+
*
|
| 66 |
+
* ACCURACY:
|
| 67 |
+
*
|
| 68 |
+
* Absolute error:
|
| 69 |
+
* arithmetic domain # trials peak rms
|
| 70 |
+
* IEEE 0, 30 30000 1.0e-15 1.3e-16
|
| 71 |
+
*
|
| 72 |
+
* (error criterion relative when |y1| > 1).
|
| 73 |
+
*
|
| 74 |
+
*/
|
| 75 |
+
|
| 76 |
+
/*
|
| 77 |
+
* Cephes Math Library Release 2.8: June, 2000
|
| 78 |
+
* Copyright 1984, 1987, 1989, 2000 by Stephen L. Moshier
|
| 79 |
+
*/
|
| 80 |
+
|
| 81 |
+
/*
|
| 82 |
+
* #define PIO4 .78539816339744830962
|
| 83 |
+
* #define THPIO4 2.35619449019234492885
|
| 84 |
+
* #define SQ2OPI .79788456080286535588
|
| 85 |
+
*/
|
| 86 |
+
#pragma once
|
| 87 |
+
|
| 88 |
+
#include "../config.h"
|
| 89 |
+
#include "../error.h"
|
| 90 |
+
|
| 91 |
+
#include "const.h"
|
| 92 |
+
#include "polevl.h"
|
| 93 |
+
|
| 94 |
+
namespace xsf {
|
| 95 |
+
namespace cephes {
|
| 96 |
+
|
| 97 |
+
namespace detail {
|
| 98 |
+
constexpr double j1_RP[4] = {
|
| 99 |
+
-8.99971225705559398224E8,
|
| 100 |
+
4.52228297998194034323E11,
|
| 101 |
+
-7.27494245221818276015E13,
|
| 102 |
+
3.68295732863852883286E15,
|
| 103 |
+
};
|
| 104 |
+
|
| 105 |
+
constexpr double j1_RQ[8] = {
|
| 106 |
+
/* 1.00000000000000000000E0, */
|
| 107 |
+
6.20836478118054335476E2, 2.56987256757748830383E5, 8.35146791431949253037E7, 2.21511595479792499675E10,
|
| 108 |
+
4.74914122079991414898E12, 7.84369607876235854894E14, 8.95222336184627338078E16, 5.32278620332680085395E18,
|
| 109 |
+
};
|
| 110 |
+
|
| 111 |
+
constexpr double j1_PP[7] = {
|
| 112 |
+
7.62125616208173112003E-4, 7.31397056940917570436E-2, 1.12719608129684925192E0, 5.11207951146807644818E0,
|
| 113 |
+
8.42404590141772420927E0, 5.21451598682361504063E0, 1.00000000000000000254E0,
|
| 114 |
+
};
|
| 115 |
+
|
| 116 |
+
constexpr double j1_PQ[7] = {
|
| 117 |
+
5.71323128072548699714E-4, 6.88455908754495404082E-2, 1.10514232634061696926E0, 5.07386386128601488557E0,
|
| 118 |
+
8.39985554327604159757E0, 5.20982848682361821619E0, 9.99999999999999997461E-1,
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
constexpr double j1_QP[8] = {
|
| 122 |
+
5.10862594750176621635E-2, 4.98213872951233449420E0, 7.58238284132545283818E1, 3.66779609360150777800E2,
|
| 123 |
+
7.10856304998926107277E2, 5.97489612400613639965E2, 2.11688757100572135698E2, 2.52070205858023719784E1,
|
| 124 |
+
};
|
| 125 |
+
|
| 126 |
+
constexpr double j1_QQ[7] = {
|
| 127 |
+
/* 1.00000000000000000000E0, */
|
| 128 |
+
7.42373277035675149943E1, 1.05644886038262816351E3, 4.98641058337653607651E3, 9.56231892404756170795E3,
|
| 129 |
+
7.99704160447350683650E3, 2.82619278517639096600E3, 3.36093607810698293419E2,
|
| 130 |
+
};
|
| 131 |
+
|
| 132 |
+
constexpr double j1_YP[6] = {
|
| 133 |
+
1.26320474790178026440E9, -6.47355876379160291031E11, 1.14509511541823727583E14,
|
| 134 |
+
-8.12770255501325109621E15, 2.02439475713594898196E17, -7.78877196265950026825E17,
|
| 135 |
+
};
|
| 136 |
+
|
| 137 |
+
constexpr double j1_YQ[8] = {
|
| 138 |
+
/* 1.00000000000000000000E0, */
|
| 139 |
+
5.94301592346128195359E2, 2.35564092943068577943E5, 7.34811944459721705660E7, 1.87601316108706159478E10,
|
| 140 |
+
3.88231277496238566008E12, 6.20557727146953693363E14, 6.87141087355300489866E16, 3.97270608116560655612E18,
|
| 141 |
+
};
|
| 142 |
+
|
| 143 |
+
constexpr double j1_Z1 = 1.46819706421238932572E1;
|
| 144 |
+
constexpr double j1_Z2 = 4.92184563216946036703E1;
|
| 145 |
+
|
| 146 |
+
} // namespace detail
|
| 147 |
+
|
| 148 |
+
XSF_HOST_DEVICE inline double j1(double x) {
|
| 149 |
+
double w, z, p, q, xn;
|
| 150 |
+
|
| 151 |
+
w = x;
|
| 152 |
+
if (x < 0) {
|
| 153 |
+
return -j1(-x);
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
if (w <= 5.0) {
|
| 157 |
+
z = x * x;
|
| 158 |
+
w = polevl(z, detail::j1_RP, 3) / p1evl(z, detail::j1_RQ, 8);
|
| 159 |
+
w = w * x * (z - detail::j1_Z1) * (z - detail::j1_Z2);
|
| 160 |
+
return (w);
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
w = 5.0 / x;
|
| 164 |
+
z = w * w;
|
| 165 |
+
p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6);
|
| 166 |
+
q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7);
|
| 167 |
+
xn = x - detail::THPIO4;
|
| 168 |
+
p = p * std::cos(xn) - w * q * std::sin(xn);
|
| 169 |
+
return (p * detail::SQRT2OPI / std::sqrt(x));
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
XSF_HOST_DEVICE inline double y1(double x) {
|
| 173 |
+
double w, z, p, q, xn;
|
| 174 |
+
|
| 175 |
+
if (x <= 5.0) {
|
| 176 |
+
if (x == 0.0) {
|
| 177 |
+
set_error("y1", SF_ERROR_SINGULAR, NULL);
|
| 178 |
+
return -std::numeric_limits<double>::infinity();
|
| 179 |
+
} else if (x <= 0.0) {
|
| 180 |
+
set_error("y1", SF_ERROR_DOMAIN, NULL);
|
| 181 |
+
return std::numeric_limits<double>::quiet_NaN();
|
| 182 |
+
}
|
| 183 |
+
z = x * x;
|
| 184 |
+
w = x * (polevl(z, detail::j1_YP, 5) / p1evl(z, detail::j1_YQ, 8));
|
| 185 |
+
w += M_2_PI * (j1(x) * std::log(x) - 1.0 / x);
|
| 186 |
+
return (w);
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
w = 5.0 / x;
|
| 190 |
+
z = w * w;
|
| 191 |
+
p = polevl(z, detail::j1_PP, 6) / polevl(z, detail::j1_PQ, 6);
|
| 192 |
+
q = polevl(z, detail::j1_QP, 7) / p1evl(z, detail::j1_QQ, 7);
|
| 193 |
+
xn = x - detail::THPIO4;
|
| 194 |
+
p = p * std::sin(xn) + w * q * std::cos(xn);
|
| 195 |
+
return (p * detail::SQRT2OPI / std::sqrt(x));
|
| 196 |
+
}
|
| 197 |
+
} // namespace cephes
|
| 198 |
+
} // namespace xsf
|
shared/package-files/41/41df97defedabb250b1589cebc2e20b405d409a95d561e4c42b33117d90305aa/blob
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
316.23
|
| 25 |
+
316.92
|
| 26 |
+
317.76
|
| 27 |
+
318.54
|
| 28 |
+
319.49
|
| 29 |
+
320.64
|
| 30 |
+
319.85
|
| 31 |
+
318.7
|
| 32 |
+
316.96
|
| 33 |
+
315.17
|
| 34 |
+
315.47
|
| 35 |
+
316.19
|
| 36 |
+
317.17
|
| 37 |
+
318.12
|
| 38 |
+
318.72
|
| 39 |
+
319.79
|
| 40 |
+
320.68
|
| 41 |
+
321.28
|
| 42 |
+
320.89
|
| 43 |
+
319.79
|
| 44 |
+
317.56
|
| 45 |
+
316.46
|
| 46 |
+
315.59
|
| 47 |
+
316.85
|
| 48 |
+
317.87
|
| 49 |
+
318.87
|
| 50 |
+
319.25
|
| 51 |
+
320.13
|
| 52 |
+
321.49
|
| 53 |
+
322.34
|
| 54 |
+
321.62
|
| 55 |
+
319.85
|
| 56 |
+
317.87
|
| 57 |
+
316.36
|
| 58 |
+
316.24
|
| 59 |
+
317.13
|
| 60 |
+
318.46
|
| 61 |
+
319.57
|
| 62 |
+
320.23
|
| 63 |
+
320.89
|
| 64 |
+
321.54
|
| 65 |
+
322.2
|
| 66 |
+
321.9
|
| 67 |
+
320.42
|
| 68 |
+
318.6
|
| 69 |
+
316.73
|
| 70 |
+
317.15
|
| 71 |
+
317.94
|
| 72 |
+
318.91
|
| 73 |
+
319.73
|
| 74 |
+
320.78
|
| 75 |
+
321.23
|
| 76 |
+
322.49
|
| 77 |
+
322.59
|
| 78 |
+
322.35
|
| 79 |
+
321.61
|
| 80 |
+
319.24
|
| 81 |
+
318.23
|
| 82 |
+
317.76
|
| 83 |
+
319.36
|
| 84 |
+
319.5
|
| 85 |
+
320.35
|
| 86 |
+
321.4
|
| 87 |
+
322.22
|
| 88 |
+
323.45
|
| 89 |
+
323.8
|
| 90 |
+
323.5
|
| 91 |
+
322.16
|
| 92 |
+
320.09
|
| 93 |
+
318.26
|
| 94 |
+
317.66
|
| 95 |
+
319.47
|
| 96 |
+
320.7
|
| 97 |
+
322.06
|
| 98 |
+
322.23
|
| 99 |
+
322.78
|
| 100 |
+
324.1
|
| 101 |
+
324.63
|
| 102 |
+
323.79
|
| 103 |
+
322.34
|
| 104 |
+
320.73
|
| 105 |
+
319
|
| 106 |
+
318.99
|
| 107 |
+
320.41
|
| 108 |
+
321.68
|
| 109 |
+
322.3
|
| 110 |
+
322.89
|
| 111 |
+
323.59
|
| 112 |
+
324.65
|
| 113 |
+
325.3
|
| 114 |
+
325.15
|
| 115 |
+
323.88
|
| 116 |
+
321.8
|
| 117 |
+
319.99
|
| 118 |
+
319.86
|
| 119 |
+
320.88
|
| 120 |
+
322.36
|
| 121 |
+
323.59
|
| 122 |
+
324.23
|
| 123 |
+
325.34
|
| 124 |
+
326.33
|
| 125 |
+
327.03
|
| 126 |
+
326.24
|
| 127 |
+
325.39
|
| 128 |
+
323.16
|
| 129 |
+
321.87
|
| 130 |
+
321.31
|
| 131 |
+
322.34
|
| 132 |
+
323.74
|
| 133 |
+
324.61
|
| 134 |
+
325.58
|
| 135 |
+
326.55
|
| 136 |
+
327.81
|
| 137 |
+
327.82
|
| 138 |
+
327.53
|
| 139 |
+
326.29
|
| 140 |
+
324.66
|
| 141 |
+
323.12
|
| 142 |
+
323.09
|
| 143 |
+
324.01
|
| 144 |
+
325.1
|
| 145 |
+
326.12
|
| 146 |
+
326.62
|
| 147 |
+
327.16
|
| 148 |
+
327.94
|
| 149 |
+
329.15
|
| 150 |
+
328.79
|
| 151 |
+
327.53
|
| 152 |
+
325.65
|
| 153 |
+
323.6
|
| 154 |
+
323.78
|
| 155 |
+
325.13
|
| 156 |
+
326.26
|
| 157 |
+
326.93
|
| 158 |
+
327.84
|
| 159 |
+
327.96
|
| 160 |
+
329.93
|
| 161 |
+
330.25
|
| 162 |
+
329.24
|
| 163 |
+
328.13
|
| 164 |
+
326.42
|
| 165 |
+
324.97
|
| 166 |
+
325.29
|
| 167 |
+
326.56
|
| 168 |
+
327.73
|
| 169 |
+
328.73
|
| 170 |
+
329.7
|
| 171 |
+
330.46
|
| 172 |
+
331.7
|
| 173 |
+
332.66
|
| 174 |
+
332.22
|
| 175 |
+
331.02
|
| 176 |
+
329.39
|
| 177 |
+
327.58
|
| 178 |
+
327.27
|
| 179 |
+
328.3
|
| 180 |
+
328.81
|
| 181 |
+
329.44
|
| 182 |
+
330.89
|
| 183 |
+
331.62
|
| 184 |
+
332.85
|
| 185 |
+
333.29
|
| 186 |
+
332.44
|
| 187 |
+
331.35
|
| 188 |
+
329.58
|
| 189 |
+
327.58
|
| 190 |
+
327.55
|
| 191 |
+
328.56
|
| 192 |
+
329.73
|
| 193 |
+
330.45
|
| 194 |
+
330.98
|
| 195 |
+
331.63
|
| 196 |
+
332.88
|
| 197 |
+
333.63
|
| 198 |
+
333.53
|
| 199 |
+
331.9
|
| 200 |
+
330.08
|
| 201 |
+
328.59
|
| 202 |
+
328.31
|
| 203 |
+
329.44
|
| 204 |
+
330.64
|
| 205 |
+
331.62
|
| 206 |
+
332.45
|
| 207 |
+
333.36
|
| 208 |
+
334.46
|
| 209 |
+
334.84
|
| 210 |
+
334.29
|
| 211 |
+
333.04
|
| 212 |
+
330.88
|
| 213 |
+
329.23
|
| 214 |
+
328.83
|
| 215 |
+
330.18
|
| 216 |
+
331.5
|
| 217 |
+
332.8
|
| 218 |
+
333.22
|
| 219 |
+
334.54
|
| 220 |
+
335.82
|
| 221 |
+
336.45
|
| 222 |
+
335.97
|
| 223 |
+
334.65
|
| 224 |
+
332.4
|
| 225 |
+
331.28
|
| 226 |
+
330.73
|
| 227 |
+
332.05
|
| 228 |
+
333.54
|
| 229 |
+
334.65
|
| 230 |
+
335.06
|
| 231 |
+
336.32
|
| 232 |
+
337.39
|
| 233 |
+
337.66
|
| 234 |
+
337.56
|
| 235 |
+
336.24
|
| 236 |
+
334.39
|
| 237 |
+
332.43
|
| 238 |
+
332.22
|
| 239 |
+
333.61
|
| 240 |
+
334.78
|
| 241 |
+
335.88
|
| 242 |
+
336.43
|
| 243 |
+
337.61
|
| 244 |
+
338.53
|
| 245 |
+
339.06
|
| 246 |
+
338.92
|
| 247 |
+
337.39
|
| 248 |
+
335.72
|
| 249 |
+
333.64
|
| 250 |
+
333.65
|
| 251 |
+
335.07
|
| 252 |
+
336.53
|
| 253 |
+
337.82
|
| 254 |
+
338.19
|
| 255 |
+
339.89
|
| 256 |
+
340.56
|
| 257 |
+
341.22
|
| 258 |
+
340.92
|
| 259 |
+
339.26
|
| 260 |
+
337.27
|
| 261 |
+
335.66
|
| 262 |
+
335.54
|
| 263 |
+
336.71
|
| 264 |
+
337.79
|
| 265 |
+
338.79
|
| 266 |
+
340.06
|
| 267 |
+
340.93
|
| 268 |
+
342.02
|
| 269 |
+
342.65
|
| 270 |
+
341.8
|
| 271 |
+
340.01
|
| 272 |
+
337.94
|
| 273 |
+
336.17
|
| 274 |
+
336.28
|
| 275 |
+
337.76
|
| 276 |
+
339.05
|
| 277 |
+
340.18
|
| 278 |
+
341.04
|
| 279 |
+
342.16
|
| 280 |
+
343.01
|
| 281 |
+
343.64
|
| 282 |
+
342.91
|
| 283 |
+
341.72
|
| 284 |
+
339.52
|
| 285 |
+
337.75
|
| 286 |
+
337.68
|
| 287 |
+
339.14
|
| 288 |
+
340.37
|
| 289 |
+
341.32
|
| 290 |
+
342.45
|
| 291 |
+
343.05
|
| 292 |
+
344.91
|
| 293 |
+
345.77
|
| 294 |
+
345.3
|
| 295 |
+
343.98
|
| 296 |
+
342.41
|
| 297 |
+
339.89
|
| 298 |
+
340.03
|
| 299 |
+
341.19
|
| 300 |
+
342.87
|
| 301 |
+
343.74
|
| 302 |
+
344.55
|
| 303 |
+
345.28
|
| 304 |
+
347
|
| 305 |
+
347.37
|
| 306 |
+
346.74
|
| 307 |
+
345.36
|
| 308 |
+
343.19
|
| 309 |
+
340.97
|
| 310 |
+
341.2
|
| 311 |
+
342.76
|
| 312 |
+
343.96
|
| 313 |
+
344.82
|
| 314 |
+
345.82
|
| 315 |
+
347.24
|
| 316 |
+
348.09
|
| 317 |
+
348.66
|
| 318 |
+
347.9
|
| 319 |
+
346.27
|
| 320 |
+
344.21
|
| 321 |
+
342.88
|
| 322 |
+
342.58
|
| 323 |
+
343.99
|
| 324 |
+
345.31
|
| 325 |
+
345.98
|
| 326 |
+
346.72
|
| 327 |
+
347.63
|
| 328 |
+
349.24
|
| 329 |
+
349.83
|
| 330 |
+
349.1
|
| 331 |
+
347.52
|
| 332 |
+
345.43
|
| 333 |
+
344.48
|
| 334 |
+
343.89
|
| 335 |
+
345.29
|
| 336 |
+
346.54
|
| 337 |
+
347.66
|
| 338 |
+
348.07
|
| 339 |
+
349.12
|
| 340 |
+
350.55
|
| 341 |
+
351.34
|
| 342 |
+
350.8
|
| 343 |
+
349.1
|
| 344 |
+
347.54
|
| 345 |
+
346.2
|
| 346 |
+
346.2
|
| 347 |
+
347.44
|
| 348 |
+
348.67
|
shared/package-files/41/41e02cb261410cf082e5546839b029e1491e6f01133f7a92efe9dae1a72cb563/blob
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from .base import ProgressBar, ProgressBarCounter
|
| 4 |
+
from .formatters import (
|
| 5 |
+
Bar,
|
| 6 |
+
Formatter,
|
| 7 |
+
IterationsPerSecond,
|
| 8 |
+
Label,
|
| 9 |
+
Percentage,
|
| 10 |
+
Progress,
|
| 11 |
+
Rainbow,
|
| 12 |
+
SpinningWheel,
|
| 13 |
+
Text,
|
| 14 |
+
TimeElapsed,
|
| 15 |
+
TimeLeft,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"ProgressBar",
|
| 20 |
+
"ProgressBarCounter",
|
| 21 |
+
# Formatters.
|
| 22 |
+
"Formatter",
|
| 23 |
+
"Text",
|
| 24 |
+
"Label",
|
| 25 |
+
"Percentage",
|
| 26 |
+
"Bar",
|
| 27 |
+
"Progress",
|
| 28 |
+
"TimeElapsed",
|
| 29 |
+
"TimeLeft",
|
| 30 |
+
"IterationsPerSecond",
|
| 31 |
+
"SpinningWheel",
|
| 32 |
+
"Rainbow",
|
| 33 |
+
]
|
shared/package-files/41/41e0e8878e2d4bfff2f4b2bb2f050101cf920f9452fa984f03879858f979c888/blob
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
|
| 4 |
+
import pandas.util._test_decorators as td
|
| 5 |
+
|
| 6 |
+
from pandas import DataFrame
|
| 7 |
+
import pandas._testing as tm
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestCopy:
|
| 11 |
+
@pytest.mark.parametrize("attr", ["index", "columns"])
|
| 12 |
+
def test_copy_index_name_checking(self, float_frame, attr):
|
| 13 |
+
# don't want to be able to modify the index stored elsewhere after
|
| 14 |
+
# making a copy
|
| 15 |
+
ind = getattr(float_frame, attr)
|
| 16 |
+
ind.name = None
|
| 17 |
+
cp = float_frame.copy()
|
| 18 |
+
getattr(cp, attr).name = "foo"
|
| 19 |
+
assert getattr(float_frame, attr).name is None
|
| 20 |
+
|
| 21 |
+
@td.skip_copy_on_write_invalid_test
|
| 22 |
+
def test_copy_cache(self):
|
| 23 |
+
# GH#31784 _item_cache not cleared on copy causes incorrect reads after updates
|
| 24 |
+
df = DataFrame({"a": [1]})
|
| 25 |
+
|
| 26 |
+
df["x"] = [0]
|
| 27 |
+
df["a"]
|
| 28 |
+
|
| 29 |
+
df.copy()
|
| 30 |
+
|
| 31 |
+
df["a"].values[0] = -1
|
| 32 |
+
|
| 33 |
+
tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0]}))
|
| 34 |
+
|
| 35 |
+
df["y"] = [0]
|
| 36 |
+
|
| 37 |
+
assert df["a"].values[0] == -1
|
| 38 |
+
tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0], "y": [0]}))
|
| 39 |
+
|
| 40 |
+
def test_copy(self, float_frame, float_string_frame):
|
| 41 |
+
cop = float_frame.copy()
|
| 42 |
+
cop["E"] = cop["A"]
|
| 43 |
+
assert "E" not in float_frame
|
| 44 |
+
|
| 45 |
+
# copy objects
|
| 46 |
+
copy = float_string_frame.copy()
|
| 47 |
+
assert copy._mgr is not float_string_frame._mgr
|
| 48 |
+
|
| 49 |
+
@td.skip_array_manager_invalid_test
|
| 50 |
+
def test_copy_consolidates(self):
|
| 51 |
+
# GH#42477
|
| 52 |
+
df = DataFrame(
|
| 53 |
+
{
|
| 54 |
+
"a": np.random.default_rng(2).integers(0, 100, size=55),
|
| 55 |
+
"b": np.random.default_rng(2).integers(0, 100, size=55),
|
| 56 |
+
}
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
for i in range(10):
|
| 60 |
+
df.loc[:, f"n_{i}"] = np.random.default_rng(2).integers(0, 100, size=55)
|
| 61 |
+
|
| 62 |
+
assert len(df._mgr.blocks) == 11
|
| 63 |
+
result = df.copy()
|
| 64 |
+
assert len(result._mgr.blocks) == 1
|
shared/package-files/41/41e2ffde1a6743801c20aeb7422a454429dd72113c64a1aa8d0afc43d9d1c019/blob
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
#include <ATen/ATen.h>
|
| 4 |
+
#include <pybind11/pybind11.h>
|
| 5 |
+
#include <torch/csrc/Export.h>
|
| 6 |
+
#include <torch/csrc/autograd/python_variable.h>
|
| 7 |
+
#include <torch/csrc/autograd/saved_variable_hooks.h>
|
| 8 |
+
#include <torch/csrc/python_headers.h>
|
| 9 |
+
#include <torch/csrc/utils/pybind.h>
|
| 10 |
+
|
| 11 |
+
namespace py = pybind11;
|
| 12 |
+
|
| 13 |
+
namespace torch::autograd {
|
| 14 |
+
|
| 15 |
+
struct PySavedVariableHooks : public SavedVariableHooks {
|
| 16 |
+
PySavedVariableHooks(py::function& pack_hook, py::function& unpack_hook);
|
| 17 |
+
void call_pack_hook(const at::Tensor& tensor) override;
|
| 18 |
+
at::Tensor call_unpack_hook() override;
|
| 19 |
+
~PySavedVariableHooks() override;
|
| 20 |
+
|
| 21 |
+
private:
|
| 22 |
+
PyObject* pack_hook_;
|
| 23 |
+
PyObject* unpack_hook_;
|
| 24 |
+
PyObject* data_ = nullptr;
|
| 25 |
+
};
|
| 26 |
+
|
| 27 |
+
struct PyDefaultSavedVariableHooks {
|
| 28 |
+
static void push_hooks(py::function& pack_hook, py::function& unpack_hook);
|
| 29 |
+
static void pop_hooks();
|
| 30 |
+
static std::unique_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import io
|
| 3 |
+
import itertools
|
| 4 |
+
import platform
|
| 5 |
+
import time
|
| 6 |
+
from unittest import mock
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
from numpy.testing import assert_allclose
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
from matplotlib.testing.decorators import check_figures_equal, image_comparison
|
| 14 |
+
from matplotlib.testing._markers import needs_usetex
|
| 15 |
+
import matplotlib.pyplot as plt
|
| 16 |
+
import matplotlib as mpl
|
| 17 |
+
import matplotlib.patches as mpatches
|
| 18 |
+
import matplotlib.transforms as mtransforms
|
| 19 |
+
import matplotlib.collections as mcollections
|
| 20 |
+
import matplotlib.lines as mlines
|
| 21 |
+
from matplotlib.legend_handler import HandlerTuple
|
| 22 |
+
import matplotlib.legend as mlegend
|
| 23 |
+
from matplotlib import rc_context
|
| 24 |
+
from matplotlib.font_manager import FontProperties
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_legend_ordereddict():
|
| 28 |
+
# smoketest that ordereddict inputs work...
|
| 29 |
+
|
| 30 |
+
X = np.random.randn(10)
|
| 31 |
+
Y = np.random.randn(10)
|
| 32 |
+
labels = ['a'] * 5 + ['b'] * 5
|
| 33 |
+
colors = ['r'] * 5 + ['g'] * 5
|
| 34 |
+
|
| 35 |
+
fig, ax = plt.subplots()
|
| 36 |
+
for x, y, label, color in zip(X, Y, labels, colors):
|
| 37 |
+
ax.scatter(x, y, label=label, c=color)
|
| 38 |
+
|
| 39 |
+
handles, labels = ax.get_legend_handles_labels()
|
| 40 |
+
legend = collections.OrderedDict(zip(labels, handles))
|
| 41 |
+
ax.legend(legend.values(), legend.keys(),
|
| 42 |
+
loc='center left', bbox_to_anchor=(1, .5))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_legend_generator():
|
| 46 |
+
# smoketest that generator inputs work
|
| 47 |
+
fig, ax = plt.subplots()
|
| 48 |
+
ax.plot([0, 1])
|
| 49 |
+
ax.plot([0, 2])
|
| 50 |
+
|
| 51 |
+
handles = (line for line in ax.get_lines())
|
| 52 |
+
labels = (label for label in ['spam', 'eggs'])
|
| 53 |
+
|
| 54 |
+
ax.legend(handles, labels, loc='upper left')
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@image_comparison(['legend_auto1.png'], remove_text=True)
|
| 58 |
+
def test_legend_auto1():
|
| 59 |
+
"""Test automatic legend placement"""
|
| 60 |
+
fig, ax = plt.subplots()
|
| 61 |
+
x = np.arange(100)
|
| 62 |
+
ax.plot(x, 50 - x, 'o', label='y=1')
|
| 63 |
+
ax.plot(x, x - 50, 'o', label='y=-1')
|
| 64 |
+
ax.legend(loc='best')
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@image_comparison(['legend_auto2.png'], remove_text=True)
|
| 68 |
+
def test_legend_auto2():
|
| 69 |
+
"""Test automatic legend placement"""
|
| 70 |
+
fig, ax = plt.subplots()
|
| 71 |
+
x = np.arange(100)
|
| 72 |
+
b1 = ax.bar(x, x, align='edge', color='m')
|
| 73 |
+
b2 = ax.bar(x, x[::-1], align='edge', color='g')
|
| 74 |
+
ax.legend([b1[0], b2[0]], ['up', 'down'], loc='best')
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@image_comparison(['legend_auto3.png'])
|
| 78 |
+
def test_legend_auto3():
|
| 79 |
+
"""Test automatic legend placement"""
|
| 80 |
+
fig, ax = plt.subplots()
|
| 81 |
+
x = [0.9, 0.1, 0.1, 0.9, 0.9, 0.5]
|
| 82 |
+
y = [0.95, 0.95, 0.05, 0.05, 0.5, 0.5]
|
| 83 |
+
ax.plot(x, y, 'o-', label='line')
|
| 84 |
+
ax.set_xlim(0.0, 1.0)
|
| 85 |
+
ax.set_ylim(0.0, 1.0)
|
| 86 |
+
ax.legend(loc='best')
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def test_legend_auto4():
|
| 90 |
+
"""
|
| 91 |
+
Check that the legend location with automatic placement is the same,
|
| 92 |
+
whatever the histogram type is. Related to issue #9580.
|
| 93 |
+
"""
|
| 94 |
+
# NB: barstacked is pointless with a single dataset.
|
| 95 |
+
fig, axs = plt.subplots(ncols=3, figsize=(6.4, 2.4))
|
| 96 |
+
leg_bboxes = []
|
| 97 |
+
for ax, ht in zip(axs.flat, ('bar', 'step', 'stepfilled')):
|
| 98 |
+
ax.set_title(ht)
|
| 99 |
+
# A high bar on the left but an even higher one on the right.
|
| 100 |
+
ax.hist([0] + 5*[9], bins=range(10), label="Legend", histtype=ht)
|
| 101 |
+
leg = ax.legend(loc="best")
|
| 102 |
+
fig.canvas.draw()
|
| 103 |
+
leg_bboxes.append(
|
| 104 |
+
leg.get_window_extent().transformed(ax.transAxes.inverted()))
|
| 105 |
+
|
| 106 |
+
# The histogram type "bar" is assumed to be the correct reference.
|
| 107 |
+
assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)
|
| 108 |
+
assert_allclose(leg_bboxes[2].bounds, leg_bboxes[0].bounds)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_legend_auto5():
|
| 112 |
+
"""
|
| 113 |
+
Check that the automatic placement handle a rather complex
|
| 114 |
+
case with non rectangular patch. Related to issue #9580.
|
| 115 |
+
"""
|
| 116 |
+
fig, axs = plt.subplots(ncols=2, figsize=(9.6, 4.8))
|
| 117 |
+
|
| 118 |
+
leg_bboxes = []
|
| 119 |
+
for ax, loc in zip(axs.flat, ("center", "best")):
|
| 120 |
+
# An Ellipse patch at the top, a U-shaped Polygon patch at the
|
| 121 |
+
# bottom and a ring-like Wedge patch: the correct placement of
|
| 122 |
+
# the legend should be in the center.
|
| 123 |
+
for _patch in [
|
| 124 |
+
mpatches.Ellipse(
|
| 125 |
+
xy=(0.5, 0.9), width=0.8, height=0.2, fc="C1"),
|
| 126 |
+
mpatches.Polygon(np.array([
|
| 127 |
+
[0, 1], [0, 0], [1, 0], [1, 1], [0.9, 1.0], [0.9, 0.1],
|
| 128 |
+
[0.1, 0.1], [0.1, 1.0], [0.1, 1.0]]), fc="C1"),
|
| 129 |
+
mpatches.Wedge((0.5, 0.5), 0.5, 0, 360, width=0.05, fc="C0")
|
| 130 |
+
]:
|
| 131 |
+
ax.add_patch(_patch)
|
| 132 |
+
|
| 133 |
+
ax.plot([0.1, 0.9], [0.9, 0.9], label="A segment") # sthg to label
|
| 134 |
+
|
| 135 |
+
leg = ax.legend(loc=loc)
|
| 136 |
+
fig.canvas.draw()
|
| 137 |
+
leg_bboxes.append(
|
| 138 |
+
leg.get_window_extent().transformed(ax.transAxes.inverted()))
|
| 139 |
+
|
| 140 |
+
assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@image_comparison(['legend_various_labels.png'], remove_text=True)
|
| 144 |
+
def test_various_labels():
|
| 145 |
+
# tests all sorts of label types
|
| 146 |
+
fig = plt.figure()
|
| 147 |
+
ax = fig.add_subplot(121)
|
| 148 |
+
ax.plot(np.arange(4), 'o', label=1)
|
| 149 |
+
ax.plot(np.linspace(4, 4.1), 'o', label='Développés')
|
| 150 |
+
ax.plot(np.arange(4, 1, -1), 'o', label='__nolegend__')
|
| 151 |
+
ax.legend(numpoints=1, loc='best')
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@image_comparison(['legend_labels_first.png'], remove_text=True,
|
| 155 |
+
tol=0 if platform.machine() == 'x86_64' else 0.013)
|
| 156 |
+
def test_labels_first():
|
| 157 |
+
# test labels to left of markers
|
| 158 |
+
fig, ax = plt.subplots()
|
| 159 |
+
ax.plot(np.arange(10), '-o', label=1)
|
| 160 |
+
ax.plot(np.ones(10)*5, ':x', label="x")
|
| 161 |
+
ax.plot(np.arange(20, 10, -1), 'd', label="diamond")
|
| 162 |
+
ax.legend(loc='best', markerfirst=False)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
@image_comparison(['legend_multiple_keys.png'], remove_text=True,
|
| 166 |
+
tol=0 if platform.machine() == 'x86_64' else 0.013)
|
| 167 |
+
def test_multiple_keys():
|
| 168 |
+
# test legend entries with multiple keys
|
| 169 |
+
fig, ax = plt.subplots()
|
| 170 |
+
p1, = ax.plot([1, 2, 3], '-o')
|
| 171 |
+
p2, = ax.plot([2, 3, 4], '-x')
|
| 172 |
+
p3, = ax.plot([3, 4, 5], '-d')
|
| 173 |
+
ax.legend([(p1, p2), (p2, p1), p3], ['two keys', 'pad=0', 'one key'],
|
| 174 |
+
numpoints=1,
|
| 175 |
+
handler_map={(p1, p2): HandlerTuple(ndivide=None),
|
| 176 |
+
(p2, p1): HandlerTuple(ndivide=None, pad=0)})
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@image_comparison(['rgba_alpha.png'], remove_text=True,
|
| 180 |
+
tol=0 if platform.machine() == 'x86_64' else 0.03)
|
| 181 |
+
def test_alpha_rgba():
|
| 182 |
+
fig, ax = plt.subplots()
|
| 183 |
+
ax.plot(range(10), lw=5)
|
| 184 |
+
leg = plt.legend(['Longlabel that will go away'], loc='center')
|
| 185 |
+
leg.legendPatch.set_facecolor([1, 0, 0, 0.5])
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@image_comparison(['rcparam_alpha.png'], remove_text=True,
|
| 189 |
+
tol=0 if platform.machine() == 'x86_64' else 0.03)
|
| 190 |
+
def test_alpha_rcparam():
|
| 191 |
+
fig, ax = plt.subplots()
|
| 192 |
+
ax.plot(range(10), lw=5)
|
| 193 |
+
with mpl.rc_context(rc={'legend.framealpha': .75}):
|
| 194 |
+
leg = plt.legend(['Longlabel that will go away'], loc='center')
|
| 195 |
+
# this alpha is going to be over-ridden by the rcparam with
|
| 196 |
+
# sets the alpha of the patch to be non-None which causes the alpha
|
| 197 |
+
# value of the face color to be discarded. This behavior may not be
|
| 198 |
+
# ideal, but it is what it is and we should keep track of it changing
|
| 199 |
+
leg.legendPatch.set_facecolor([1, 0, 0, 0.5])
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
@image_comparison(['fancy.png'], remove_text=True, tol=0.05)
|
| 203 |
+
def test_fancy():
|
| 204 |
+
# Tolerance caused by changing default shadow "shade" from 0.3 to 1 - 0.7 =
|
| 205 |
+
# 0.30000000000000004
|
| 206 |
+
# using subplot triggers some offsetbox functionality untested elsewhere
|
| 207 |
+
plt.subplot(121)
|
| 208 |
+
plt.plot([5] * 10, 'o--', label='XX')
|
| 209 |
+
plt.scatter(np.arange(10), np.arange(10, 0, -1), label='XX\nXX')
|
| 210 |
+
plt.errorbar(np.arange(10), np.arange(10), xerr=0.5,
|
| 211 |
+
yerr=0.5, label='XX')
|
| 212 |
+
plt.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],
|
| 213 |
+
ncols=2, shadow=True, title="My legend", numpoints=1)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@image_comparison(['framealpha'], remove_text=True,
|
| 217 |
+
tol=0 if platform.machine() == 'x86_64' else 0.024)
|
| 218 |
+
def test_framealpha():
|
| 219 |
+
x = np.linspace(1, 100, 100)
|
| 220 |
+
y = x
|
| 221 |
+
plt.plot(x, y, label='mylabel', lw=10)
|
| 222 |
+
plt.legend(framealpha=0.5)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
@image_comparison(['scatter_rc3.png', 'scatter_rc1.png'], remove_text=True)
|
| 226 |
+
def test_rc():
|
| 227 |
+
# using subplot triggers some offsetbox functionality untested elsewhere
|
| 228 |
+
plt.figure()
|
| 229 |
+
ax = plt.subplot(121)
|
| 230 |
+
ax.scatter(np.arange(10), np.arange(10, 0, -1), label='three')
|
| 231 |
+
ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],
|
| 232 |
+
title="My legend")
|
| 233 |
+
|
| 234 |
+
mpl.rcParams['legend.scatterpoints'] = 1
|
| 235 |
+
plt.figure()
|
| 236 |
+
ax = plt.subplot(121)
|
| 237 |
+
ax.scatter(np.arange(10), np.arange(10, 0, -1), label='one')
|
| 238 |
+
ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],
|
| 239 |
+
title="My legend")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@image_comparison(['legend_expand.png'], remove_text=True)
|
| 243 |
+
def test_legend_expand():
|
| 244 |
+
"""Test expand mode"""
|
| 245 |
+
legend_modes = [None, "expand"]
|
| 246 |
+
fig, axs = plt.subplots(len(legend_modes), 1)
|
| 247 |
+
x = np.arange(100)
|
| 248 |
+
for ax, mode in zip(axs, legend_modes):
|
| 249 |
+
ax.plot(x, 50 - x, 'o', label='y=1')
|
| 250 |
+
l1 = ax.legend(loc='upper left', mode=mode)
|
| 251 |
+
ax.add_artist(l1)
|
| 252 |
+
ax.plot(x, x - 50, 'o', label='y=-1')
|
| 253 |
+
l2 = ax.legend(loc='right', mode=mode)
|
| 254 |
+
ax.add_artist(l2)
|
| 255 |
+
ax.legend(loc='lower left', mode=mode, ncols=2)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
@image_comparison(['hatching'], remove_text=True, style='default')
|
| 259 |
+
def test_hatching():
|
| 260 |
+
# Remove legend texts when this image is regenerated.
|
| 261 |
+
# Remove this line when this test image is regenerated.
|
| 262 |
+
plt.rcParams['text.kerning_factor'] = 6
|
| 263 |
+
|
| 264 |
+
fig, ax = plt.subplots()
|
| 265 |
+
|
| 266 |
+
# Patches
|
| 267 |
+
patch = plt.Rectangle((0, 0), 0.3, 0.3, hatch='xx',
|
| 268 |
+
label='Patch\ndefault color\nfilled')
|
| 269 |
+
ax.add_patch(patch)
|
| 270 |
+
patch = plt.Rectangle((0.33, 0), 0.3, 0.3, hatch='||', edgecolor='C1',
|
| 271 |
+
label='Patch\nexplicit color\nfilled')
|
| 272 |
+
ax.add_patch(patch)
|
| 273 |
+
patch = plt.Rectangle((0, 0.4), 0.3, 0.3, hatch='xx', fill=False,
|
| 274 |
+
label='Patch\ndefault color\nunfilled')
|
| 275 |
+
ax.add_patch(patch)
|
| 276 |
+
patch = plt.Rectangle((0.33, 0.4), 0.3, 0.3, hatch='||', fill=False,
|
| 277 |
+
edgecolor='C1',
|
| 278 |
+
label='Patch\nexplicit color\nunfilled')
|
| 279 |
+
ax.add_patch(patch)
|
| 280 |
+
|
| 281 |
+
# Paths
|
| 282 |
+
ax.fill_between([0, .15, .3], [.8, .8, .8], [.9, 1.0, .9],
|
| 283 |
+
hatch='+', label='Path\ndefault color')
|
| 284 |
+
ax.fill_between([.33, .48, .63], [.8, .8, .8], [.9, 1.0, .9],
|
| 285 |
+
hatch='+', edgecolor='C2', label='Path\nexplicit color')
|
| 286 |
+
|
| 287 |
+
ax.set_xlim(-0.01, 1.1)
|
| 288 |
+
ax.set_ylim(-0.01, 1.1)
|
| 289 |
+
ax.legend(handlelength=4, handleheight=4)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_legend_remove():
|
| 293 |
+
fig, ax = plt.subplots()
|
| 294 |
+
lines = ax.plot(range(10))
|
| 295 |
+
leg = fig.legend(lines, "test")
|
| 296 |
+
leg.remove()
|
| 297 |
+
assert fig.legends == []
|
| 298 |
+
leg = ax.legend("test")
|
| 299 |
+
leg.remove()
|
| 300 |
+
assert ax.get_legend() is None
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def test_reverse_legend_handles_and_labels():
|
| 304 |
+
"""Check that the legend handles and labels are reversed."""
|
| 305 |
+
fig, ax = plt.subplots()
|
| 306 |
+
x = 1
|
| 307 |
+
y = 1
|
| 308 |
+
labels = ["First label", "Second label", "Third label"]
|
| 309 |
+
markers = ['.', ',', 'o']
|
| 310 |
+
|
| 311 |
+
ax.plot(x, y, markers[0], label=labels[0])
|
| 312 |
+
ax.plot(x, y, markers[1], label=labels[1])
|
| 313 |
+
ax.plot(x, y, markers[2], label=labels[2])
|
| 314 |
+
leg = ax.legend(reverse=True)
|
| 315 |
+
actual_labels = [t.get_text() for t in leg.get_texts()]
|
| 316 |
+
actual_markers = [h.get_marker() for h in leg.legend_handles]
|
| 317 |
+
assert actual_labels == list(reversed(labels))
|
| 318 |
+
assert actual_markers == list(reversed(markers))
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
@check_figures_equal(extensions=["png"])
|
| 322 |
+
def test_reverse_legend_display(fig_test, fig_ref):
|
| 323 |
+
"""Check that the rendered legend entries are reversed"""
|
| 324 |
+
ax = fig_test.subplots()
|
| 325 |
+
ax.plot([1], 'ro', label="first")
|
| 326 |
+
ax.plot([2], 'bx', label="second")
|
| 327 |
+
ax.legend(reverse=True)
|
| 328 |
+
|
| 329 |
+
ax = fig_ref.subplots()
|
| 330 |
+
ax.plot([2], 'bx', label="second")
|
| 331 |
+
ax.plot([1], 'ro', label="first")
|
| 332 |
+
ax.legend()
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class TestLegendFunction:
|
| 336 |
+
# Tests the legend function on the Axes and pyplot.
|
| 337 |
+
def test_legend_no_args(self):
|
| 338 |
+
lines = plt.plot(range(10), label='hello world')
|
| 339 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 340 |
+
plt.legend()
|
| 341 |
+
Legend.assert_called_with(plt.gca(), lines, ['hello world'])
|
| 342 |
+
|
| 343 |
+
def test_legend_positional_handles_labels(self):
|
| 344 |
+
lines = plt.plot(range(10))
|
| 345 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 346 |
+
plt.legend(lines, ['hello world'])
|
| 347 |
+
Legend.assert_called_with(plt.gca(), lines, ['hello world'])
|
| 348 |
+
|
| 349 |
+
def test_legend_positional_handles_only(self):
|
| 350 |
+
lines = plt.plot(range(10))
|
| 351 |
+
with pytest.raises(TypeError, match='but found an Artist'):
|
| 352 |
+
# a single arg is interpreted as labels
|
| 353 |
+
# it's a common error to just pass handles
|
| 354 |
+
plt.legend(lines)
|
| 355 |
+
|
| 356 |
+
def test_legend_positional_labels_only(self):
|
| 357 |
+
lines = plt.plot(range(10), label='hello world')
|
| 358 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 359 |
+
plt.legend(['foobar'])
|
| 360 |
+
Legend.assert_called_with(plt.gca(), lines, ['foobar'])
|
| 361 |
+
|
| 362 |
+
def test_legend_three_args(self):
|
| 363 |
+
lines = plt.plot(range(10), label='hello world')
|
| 364 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 365 |
+
plt.legend(lines, ['foobar'], loc='right')
|
| 366 |
+
Legend.assert_called_with(plt.gca(), lines, ['foobar'], loc='right')
|
| 367 |
+
|
| 368 |
+
def test_legend_handler_map(self):
|
| 369 |
+
lines = plt.plot(range(10), label='hello world')
|
| 370 |
+
with mock.patch('matplotlib.legend.'
|
| 371 |
+
'_get_legend_handles_labels') as handles_labels:
|
| 372 |
+
handles_labels.return_value = lines, ['hello world']
|
| 373 |
+
plt.legend(handler_map={'1': 2})
|
| 374 |
+
handles_labels.assert_called_with([plt.gca()], {'1': 2})
|
| 375 |
+
|
| 376 |
+
def test_legend_kwargs_handles_only(self):
|
| 377 |
+
fig, ax = plt.subplots()
|
| 378 |
+
x = np.linspace(0, 1, 11)
|
| 379 |
+
ln1, = ax.plot(x, x, label='x')
|
| 380 |
+
ln2, = ax.plot(x, 2*x, label='2x')
|
| 381 |
+
ln3, = ax.plot(x, 3*x, label='3x')
|
| 382 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 383 |
+
ax.legend(handles=[ln3, ln2]) # reversed and not ln1
|
| 384 |
+
Legend.assert_called_with(ax, [ln3, ln2], ['3x', '2x'])
|
| 385 |
+
|
| 386 |
+
def test_legend_kwargs_labels_only(self):
|
| 387 |
+
fig, ax = plt.subplots()
|
| 388 |
+
x = np.linspace(0, 1, 11)
|
| 389 |
+
ln1, = ax.plot(x, x)
|
| 390 |
+
ln2, = ax.plot(x, 2*x)
|
| 391 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 392 |
+
ax.legend(labels=['x', '2x'])
|
| 393 |
+
Legend.assert_called_with(ax, [ln1, ln2], ['x', '2x'])
|
| 394 |
+
|
| 395 |
+
def test_legend_kwargs_handles_labels(self):
|
| 396 |
+
fig, ax = plt.subplots()
|
| 397 |
+
th = np.linspace(0, 2*np.pi, 1024)
|
| 398 |
+
lns, = ax.plot(th, np.sin(th), label='sin')
|
| 399 |
+
lnc, = ax.plot(th, np.cos(th), label='cos')
|
| 400 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 401 |
+
# labels of lns, lnc are overwritten with explicit ('a', 'b')
|
| 402 |
+
ax.legend(labels=('a', 'b'), handles=(lnc, lns))
|
| 403 |
+
Legend.assert_called_with(ax, (lnc, lns), ('a', 'b'))
|
| 404 |
+
|
| 405 |
+
def test_warn_mixed_args_and_kwargs(self):
|
| 406 |
+
fig, ax = plt.subplots()
|
| 407 |
+
th = np.linspace(0, 2*np.pi, 1024)
|
| 408 |
+
lns, = ax.plot(th, np.sin(th), label='sin')
|
| 409 |
+
lnc, = ax.plot(th, np.cos(th), label='cos')
|
| 410 |
+
with pytest.warns(DeprecationWarning) as record:
|
| 411 |
+
ax.legend((lnc, lns), labels=('a', 'b'))
|
| 412 |
+
assert len(record) == 1
|
| 413 |
+
assert str(record[0].message).startswith(
|
| 414 |
+
"You have mixed positional and keyword arguments, some input may "
|
| 415 |
+
"be discarded.")
|
| 416 |
+
|
| 417 |
+
def test_parasite(self):
|
| 418 |
+
from mpl_toolkits.axes_grid1 import host_subplot # type: ignore[import]
|
| 419 |
+
|
| 420 |
+
host = host_subplot(111)
|
| 421 |
+
par = host.twinx()
|
| 422 |
+
|
| 423 |
+
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
|
| 424 |
+
p2, = par.plot([0, 1, 2], [0, 3, 2], label="Temperature")
|
| 425 |
+
|
| 426 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 427 |
+
plt.legend()
|
| 428 |
+
Legend.assert_called_with(host, [p1, p2], ['Density', 'Temperature'])
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class TestLegendFigureFunction:
|
| 432 |
+
# Tests the legend function for figure
|
| 433 |
+
def test_legend_handle_label(self):
|
| 434 |
+
fig, ax = plt.subplots()
|
| 435 |
+
lines = ax.plot(range(10))
|
| 436 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 437 |
+
fig.legend(lines, ['hello world'])
|
| 438 |
+
Legend.assert_called_with(fig, lines, ['hello world'],
|
| 439 |
+
bbox_transform=fig.transFigure)
|
| 440 |
+
|
| 441 |
+
def test_legend_no_args(self):
|
| 442 |
+
fig, ax = plt.subplots()
|
| 443 |
+
lines = ax.plot(range(10), label='hello world')
|
| 444 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 445 |
+
fig.legend()
|
| 446 |
+
Legend.assert_called_with(fig, lines, ['hello world'],
|
| 447 |
+
bbox_transform=fig.transFigure)
|
| 448 |
+
|
| 449 |
+
def test_legend_label_arg(self):
|
| 450 |
+
fig, ax = plt.subplots()
|
| 451 |
+
lines = ax.plot(range(10))
|
| 452 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 453 |
+
fig.legend(['foobar'])
|
| 454 |
+
Legend.assert_called_with(fig, lines, ['foobar'],
|
| 455 |
+
bbox_transform=fig.transFigure)
|
| 456 |
+
|
| 457 |
+
def test_legend_label_three_args(self):
|
| 458 |
+
fig, ax = plt.subplots()
|
| 459 |
+
lines = ax.plot(range(10))
|
| 460 |
+
with pytest.raises(TypeError, match="0-2"):
|
| 461 |
+
fig.legend(lines, ['foobar'], 'right')
|
| 462 |
+
with pytest.raises(TypeError, match="0-2"):
|
| 463 |
+
fig.legend(lines, ['foobar'], 'right', loc='left')
|
| 464 |
+
|
| 465 |
+
def test_legend_kw_args(self):
|
| 466 |
+
fig, axs = plt.subplots(1, 2)
|
| 467 |
+
lines = axs[0].plot(range(10))
|
| 468 |
+
lines2 = axs[1].plot(np.arange(10) * 2.)
|
| 469 |
+
with mock.patch('matplotlib.legend.Legend') as Legend:
|
| 470 |
+
fig.legend(loc='right', labels=('a', 'b'), handles=(lines, lines2))
|
| 471 |
+
Legend.assert_called_with(
|
| 472 |
+
fig, (lines, lines2), ('a', 'b'), loc='right',
|
| 473 |
+
bbox_transform=fig.transFigure)
|
| 474 |
+
|
| 475 |
+
def test_warn_args_kwargs(self):
|
| 476 |
+
fig, axs = plt.subplots(1, 2)
|
| 477 |
+
lines = axs[0].plot(range(10))
|
| 478 |
+
lines2 = axs[1].plot(np.arange(10) * 2.)
|
| 479 |
+
with pytest.warns(DeprecationWarning) as record:
|
| 480 |
+
fig.legend((lines, lines2), labels=('a', 'b'))
|
| 481 |
+
assert len(record) == 1
|
| 482 |
+
assert str(record[0].message).startswith(
|
| 483 |
+
"You have mixed positional and keyword arguments, some input may "
|
| 484 |
+
"be discarded.")
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def test_figure_legend_outside():
|
| 488 |
+
todos = ['upper ' + pos for pos in ['left', 'center', 'right']]
|
| 489 |
+
todos += ['lower ' + pos for pos in ['left', 'center', 'right']]
|
| 490 |
+
todos += ['left ' + pos for pos in ['lower', 'center', 'upper']]
|
| 491 |
+
todos += ['right ' + pos for pos in ['lower', 'center', 'upper']]
|
| 492 |
+
|
| 493 |
+
upperext = [20.347556, 27.722556, 790.583, 545.499]
|
| 494 |
+
lowerext = [20.347556, 71.056556, 790.583, 588.833]
|
| 495 |
+
leftext = [151.681556, 27.722556, 790.583, 588.833]
|
| 496 |
+
rightext = [20.347556, 27.722556, 659.249, 588.833]
|
| 497 |
+
axbb = [upperext, upperext, upperext,
|
| 498 |
+
lowerext, lowerext, lowerext,
|
| 499 |
+
leftext, leftext, leftext,
|
| 500 |
+
rightext, rightext, rightext]
|
| 501 |
+
|
| 502 |
+
legbb = [[10., 555., 133., 590.], # upper left
|
| 503 |
+
[338.5, 555., 461.5, 590.], # upper center
|
| 504 |
+
[667, 555., 790., 590.], # upper right
|
| 505 |
+
[10., 10., 133., 45.], # lower left
|
| 506 |
+
[338.5, 10., 461.5, 45.], # lower center
|
| 507 |
+
[667., 10., 790., 45.], # lower right
|
| 508 |
+
[10., 10., 133., 45.], # left lower
|
| 509 |
+
[10., 282.5, 133., 317.5], # left center
|
| 510 |
+
[10., 555., 133., 590.], # left upper
|
| 511 |
+
[667, 10., 790., 45.], # right lower
|
| 512 |
+
[667., 282.5, 790., 317.5], # right center
|
| 513 |
+
[667., 555., 790., 590.]] # right upper
|
| 514 |
+
|
| 515 |
+
for nn, todo in enumerate(todos):
|
| 516 |
+
print(todo)
|
| 517 |
+
fig, axs = plt.subplots(constrained_layout=True, dpi=100)
|
| 518 |
+
axs.plot(range(10), label='Boo1')
|
| 519 |
+
leg = fig.legend(loc='outside ' + todo)
|
| 520 |
+
fig.draw_without_rendering()
|
| 521 |
+
|
| 522 |
+
assert_allclose(axs.get_window_extent().extents,
|
| 523 |
+
axbb[nn])
|
| 524 |
+
assert_allclose(leg.get_window_extent().extents,
|
| 525 |
+
legbb[nn])
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
@image_comparison(['legend_stackplot.png'],
|
| 529 |
+
tol=0 if platform.machine() == 'x86_64' else 0.031)
|
| 530 |
+
def test_legend_stackplot():
|
| 531 |
+
"""Test legend for PolyCollection using stackplot."""
|
| 532 |
+
# related to #1341, #1943, and PR #3303
|
| 533 |
+
fig, ax = plt.subplots()
|
| 534 |
+
x = np.linspace(0, 10, 10)
|
| 535 |
+
y1 = 1.0 * x
|
| 536 |
+
y2 = 2.0 * x + 1
|
| 537 |
+
y3 = 3.0 * x + 2
|
| 538 |
+
ax.stackplot(x, y1, y2, y3, labels=['y1', 'y2', 'y3'])
|
| 539 |
+
ax.set_xlim((0, 10))
|
| 540 |
+
ax.set_ylim((0, 70))
|
| 541 |
+
ax.legend(loc='best')
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def test_cross_figure_patch_legend():
|
| 545 |
+
fig, ax = plt.subplots()
|
| 546 |
+
fig2, ax2 = plt.subplots()
|
| 547 |
+
|
| 548 |
+
brs = ax.bar(range(3), range(3))
|
| 549 |
+
fig2.legend(brs, 'foo')
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def test_nanscatter():
|
| 553 |
+
fig, ax = plt.subplots()
|
| 554 |
+
|
| 555 |
+
h = ax.scatter([np.nan], [np.nan], marker="o",
|
| 556 |
+
facecolor="r", edgecolor="r", s=3)
|
| 557 |
+
|
| 558 |
+
ax.legend([h], ["scatter"])
|
| 559 |
+
|
| 560 |
+
fig, ax = plt.subplots()
|
| 561 |
+
for color in ['red', 'green', 'blue']:
|
| 562 |
+
n = 750
|
| 563 |
+
x, y = np.random.rand(2, n)
|
| 564 |
+
scale = 200.0 * np.random.rand(n)
|
| 565 |
+
ax.scatter(x, y, c=color, s=scale, label=color,
|
| 566 |
+
alpha=0.3, edgecolors='none')
|
| 567 |
+
|
| 568 |
+
ax.legend()
|
| 569 |
+
ax.grid(True)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def test_legend_repeatcheckok():
|
| 573 |
+
fig, ax = plt.subplots()
|
| 574 |
+
ax.scatter(0.0, 1.0, color='k', marker='o', label='test')
|
| 575 |
+
ax.scatter(0.5, 0.0, color='r', marker='v', label='test')
|
| 576 |
+
ax.legend()
|
| 577 |
+
hand, lab = mlegend._get_legend_handles_labels([ax])
|
| 578 |
+
assert len(lab) == 2
|
| 579 |
+
fig, ax = plt.subplots()
|
| 580 |
+
ax.scatter(0.0, 1.0, color='k', marker='o', label='test')
|
| 581 |
+
ax.scatter(0.5, 0.0, color='k', marker='v', label='test')
|
| 582 |
+
ax.legend()
|
| 583 |
+
hand, lab = mlegend._get_legend_handles_labels([ax])
|
| 584 |
+
assert len(lab) == 2
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
@image_comparison(['not_covering_scatter.png'])
|
| 588 |
+
def test_not_covering_scatter():
|
| 589 |
+
colors = ['b', 'g', 'r']
|
| 590 |
+
|
| 591 |
+
for n in range(3):
|
| 592 |
+
plt.scatter([n], [n], color=colors[n])
|
| 593 |
+
|
| 594 |
+
plt.legend(['foo', 'foo', 'foo'], loc='best')
|
| 595 |
+
plt.gca().set_xlim(-0.5, 2.2)
|
| 596 |
+
plt.gca().set_ylim(-0.5, 2.2)
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
@image_comparison(['not_covering_scatter_transform.png'])
|
| 600 |
+
def test_not_covering_scatter_transform():
|
| 601 |
+
# Offsets point to top left, the default auto position
|
| 602 |
+
offset = mtransforms.Affine2D().translate(-20, 20)
|
| 603 |
+
x = np.linspace(0, 30, 1000)
|
| 604 |
+
plt.plot(x, x)
|
| 605 |
+
|
| 606 |
+
plt.scatter([20], [10], transform=offset + plt.gca().transData)
|
| 607 |
+
|
| 608 |
+
plt.legend(['foo', 'bar'], loc='best')
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def test_linecollection_scaled_dashes():
|
| 612 |
+
lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]]
|
| 613 |
+
lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]]
|
| 614 |
+
lines3 = [[[0.6, .2], [.8, .4]], [[.5, .7], [.1, .1]]]
|
| 615 |
+
lc1 = mcollections.LineCollection(lines1, linestyles="--", lw=3)
|
| 616 |
+
lc2 = mcollections.LineCollection(lines2, linestyles="-.")
|
| 617 |
+
lc3 = mcollections.LineCollection(lines3, linestyles=":", lw=.5)
|
| 618 |
+
|
| 619 |
+
fig, ax = plt.subplots()
|
| 620 |
+
ax.add_collection(lc1)
|
| 621 |
+
ax.add_collection(lc2)
|
| 622 |
+
ax.add_collection(lc3)
|
| 623 |
+
|
| 624 |
+
leg = ax.legend([lc1, lc2, lc3], ["line1", "line2", 'line 3'])
|
| 625 |
+
h1, h2, h3 = leg.legend_handles
|
| 626 |
+
|
| 627 |
+
for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)):
|
| 628 |
+
assert oh.get_linestyles()[0] == lh._dash_pattern
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def test_handler_numpoints():
|
| 632 |
+
"""Test legend handler with numpoints <= 1."""
|
| 633 |
+
# related to #6921 and PR #8478
|
| 634 |
+
fig, ax = plt.subplots()
|
| 635 |
+
ax.plot(range(5), label='test')
|
| 636 |
+
ax.legend(numpoints=0.5)
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def test_text_nohandler_warning():
|
| 640 |
+
"""Test that Text artists with labels raise a warning"""
|
| 641 |
+
fig, ax = plt.subplots()
|
| 642 |
+
ax.plot([0], label="mock data")
|
| 643 |
+
ax.text(x=0, y=0, s="text", label="label")
|
| 644 |
+
with pytest.warns(UserWarning) as record:
|
| 645 |
+
ax.legend()
|
| 646 |
+
assert len(record) == 1
|
| 647 |
+
|
| 648 |
+
# this should _not_ warn:
|
| 649 |
+
f, ax = plt.subplots()
|
| 650 |
+
ax.pcolormesh(np.random.uniform(0, 1, (10, 10)))
|
| 651 |
+
with warnings.catch_warnings():
|
| 652 |
+
warnings.simplefilter("error")
|
| 653 |
+
ax.get_legend_handles_labels()
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
def test_empty_bar_chart_with_legend():
|
| 657 |
+
"""Test legend when bar chart is empty with a label."""
|
| 658 |
+
# related to issue #13003. Calling plt.legend() should not
|
| 659 |
+
# raise an IndexError.
|
| 660 |
+
plt.bar([], [], label='test')
|
| 661 |
+
plt.legend()
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
@image_comparison(['shadow_argument_types.png'], remove_text=True, style='mpl20',
|
| 665 |
+
tol=0 if platform.machine() == 'x86_64' else 0.028)
|
| 666 |
+
def test_shadow_argument_types():
|
| 667 |
+
# Test that different arguments for shadow work as expected
|
| 668 |
+
fig, ax = plt.subplots()
|
| 669 |
+
ax.plot([1, 2, 3], label='test')
|
| 670 |
+
|
| 671 |
+
# Test various shadow configurations
|
| 672 |
+
# as well as different ways of specifying colors
|
| 673 |
+
legs = (ax.legend(loc='upper left', shadow=True), # True
|
| 674 |
+
ax.legend(loc='upper right', shadow=False), # False
|
| 675 |
+
ax.legend(loc='center left', # string
|
| 676 |
+
shadow={'color': 'red', 'alpha': 0.1}),
|
| 677 |
+
ax.legend(loc='center right', # tuple
|
| 678 |
+
shadow={'color': (0.1, 0.2, 0.5), 'oy': -5}),
|
| 679 |
+
ax.legend(loc='lower left', # tab
|
| 680 |
+
shadow={'color': 'tab:cyan', 'ox': 10})
|
| 681 |
+
)
|
| 682 |
+
for l in legs:
|
| 683 |
+
ax.add_artist(l)
|
| 684 |
+
ax.legend(loc='lower right') # default
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
def test_shadow_invalid_argument():
|
| 688 |
+
# Test if invalid argument to legend shadow
|
| 689 |
+
# (i.e. not [color|bool]) raises ValueError
|
| 690 |
+
fig, ax = plt.subplots()
|
| 691 |
+
ax.plot([1, 2, 3], label='test')
|
| 692 |
+
with pytest.raises(ValueError, match="dict or bool"):
|
| 693 |
+
ax.legend(loc="upper left", shadow="aardvark") # Bad argument
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def test_shadow_framealpha():
|
| 697 |
+
# Test if framealpha is activated when shadow is True
|
| 698 |
+
# and framealpha is not explicitly passed'''
|
| 699 |
+
fig, ax = plt.subplots()
|
| 700 |
+
ax.plot(range(100), label="test")
|
| 701 |
+
leg = ax.legend(shadow=True, facecolor='w')
|
| 702 |
+
assert leg.get_frame().get_alpha() == 1
|
| 703 |
+
|
| 704 |
+
|
| 705 |
+
def test_legend_title_empty():
|
| 706 |
+
# test that if we don't set the legend title, that
|
| 707 |
+
# it comes back as an empty string, and that it is not
|
| 708 |
+
# visible:
|
| 709 |
+
fig, ax = plt.subplots()
|
| 710 |
+
ax.plot(range(10), label="mock data")
|
| 711 |
+
leg = ax.legend()
|
| 712 |
+
assert leg.get_title().get_text() == ""
|
| 713 |
+
assert not leg.get_title().get_visible()
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def test_legend_proper_window_extent():
|
| 717 |
+
# test that legend returns the expected extent under various dpi...
|
| 718 |
+
fig, ax = plt.subplots(dpi=100)
|
| 719 |
+
ax.plot(range(10), label='Aardvark')
|
| 720 |
+
leg = ax.legend()
|
| 721 |
+
x01 = leg.get_window_extent(fig.canvas.get_renderer()).x0
|
| 722 |
+
|
| 723 |
+
fig, ax = plt.subplots(dpi=200)
|
| 724 |
+
ax.plot(range(10), label='Aardvark')
|
| 725 |
+
leg = ax.legend()
|
| 726 |
+
x02 = leg.get_window_extent(fig.canvas.get_renderer()).x0
|
| 727 |
+
assert pytest.approx(x01*2, 0.1) == x02
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
def test_window_extent_cached_renderer():
|
| 731 |
+
fig, ax = plt.subplots(dpi=100)
|
| 732 |
+
ax.plot(range(10), label='Aardvark')
|
| 733 |
+
leg = ax.legend()
|
| 734 |
+
leg2 = fig.legend()
|
| 735 |
+
fig.canvas.draw()
|
| 736 |
+
# check that get_window_extent will use the cached renderer
|
| 737 |
+
leg.get_window_extent()
|
| 738 |
+
leg2.get_window_extent()
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def test_legend_title_fontprop_fontsize():
|
| 742 |
+
# test the title_fontsize kwarg
|
| 743 |
+
plt.plot(range(10), label="mock data")
|
| 744 |
+
with pytest.raises(ValueError):
|
| 745 |
+
plt.legend(title='Aardvark', title_fontsize=22,
|
| 746 |
+
title_fontproperties={'family': 'serif', 'size': 22})
|
| 747 |
+
|
| 748 |
+
leg = plt.legend(title='Aardvark', title_fontproperties=FontProperties(
|
| 749 |
+
family='serif', size=22))
|
| 750 |
+
assert leg.get_title().get_size() == 22
|
| 751 |
+
|
| 752 |
+
fig, axes = plt.subplots(2, 3, figsize=(10, 6))
|
| 753 |
+
axes = axes.flat
|
| 754 |
+
axes[0].plot(range(10), label="mock data")
|
| 755 |
+
leg0 = axes[0].legend(title='Aardvark', title_fontsize=22)
|
| 756 |
+
assert leg0.get_title().get_fontsize() == 22
|
| 757 |
+
axes[1].plot(range(10), label="mock data")
|
| 758 |
+
leg1 = axes[1].legend(title='Aardvark',
|
| 759 |
+
title_fontproperties={'family': 'serif', 'size': 22})
|
| 760 |
+
assert leg1.get_title().get_fontsize() == 22
|
| 761 |
+
axes[2].plot(range(10), label="mock data")
|
| 762 |
+
mpl.rcParams['legend.title_fontsize'] = None
|
| 763 |
+
leg2 = axes[2].legend(title='Aardvark',
|
| 764 |
+
title_fontproperties={'family': 'serif'})
|
| 765 |
+
assert leg2.get_title().get_fontsize() == mpl.rcParams['font.size']
|
| 766 |
+
axes[3].plot(range(10), label="mock data")
|
| 767 |
+
leg3 = axes[3].legend(title='Aardvark')
|
| 768 |
+
assert leg3.get_title().get_fontsize() == mpl.rcParams['font.size']
|
| 769 |
+
axes[4].plot(range(10), label="mock data")
|
| 770 |
+
mpl.rcParams['legend.title_fontsize'] = 20
|
| 771 |
+
leg4 = axes[4].legend(title='Aardvark',
|
| 772 |
+
title_fontproperties={'family': 'serif'})
|
| 773 |
+
assert leg4.get_title().get_fontsize() == 20
|
| 774 |
+
axes[5].plot(range(10), label="mock data")
|
| 775 |
+
leg5 = axes[5].legend(title='Aardvark')
|
| 776 |
+
assert leg5.get_title().get_fontsize() == 20
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
@pytest.mark.parametrize('alignment', ('center', 'left', 'right'))
|
| 780 |
+
def test_legend_alignment(alignment):
|
| 781 |
+
fig, ax = plt.subplots()
|
| 782 |
+
ax.plot(range(10), label='test')
|
| 783 |
+
leg = ax.legend(title="Aardvark", alignment=alignment)
|
| 784 |
+
assert leg.get_children()[0].align == alignment
|
| 785 |
+
assert leg.get_alignment() == alignment
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
@pytest.mark.parametrize('loc', ('center', 'best',))
|
| 789 |
+
def test_ax_legend_set_loc(loc):
|
| 790 |
+
fig, ax = plt.subplots()
|
| 791 |
+
ax.plot(range(10), label='test')
|
| 792 |
+
leg = ax.legend()
|
| 793 |
+
leg.set_loc(loc)
|
| 794 |
+
assert leg._get_loc() == mlegend.Legend.codes[loc]
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
@pytest.mark.parametrize('loc', ('outside right', 'right',))
|
| 798 |
+
def test_fig_legend_set_loc(loc):
|
| 799 |
+
fig, ax = plt.subplots()
|
| 800 |
+
ax.plot(range(10), label='test')
|
| 801 |
+
leg = fig.legend()
|
| 802 |
+
leg.set_loc(loc)
|
| 803 |
+
|
| 804 |
+
loc = loc.split()[1] if loc.startswith("outside") else loc
|
| 805 |
+
assert leg._get_loc() == mlegend.Legend.codes[loc]
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
@pytest.mark.parametrize('alignment', ('center', 'left', 'right'))
|
| 809 |
+
def test_legend_set_alignment(alignment):
|
| 810 |
+
fig, ax = plt.subplots()
|
| 811 |
+
ax.plot(range(10), label='test')
|
| 812 |
+
leg = ax.legend()
|
| 813 |
+
leg.set_alignment(alignment)
|
| 814 |
+
assert leg.get_children()[0].align == alignment
|
| 815 |
+
assert leg.get_alignment() == alignment
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
@pytest.mark.parametrize('color', ('red', 'none', (.5, .5, .5)))
|
| 819 |
+
def test_legend_labelcolor_single(color):
|
| 820 |
+
# test labelcolor for a single color
|
| 821 |
+
fig, ax = plt.subplots()
|
| 822 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1')
|
| 823 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2')
|
| 824 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3')
|
| 825 |
+
|
| 826 |
+
leg = ax.legend(labelcolor=color)
|
| 827 |
+
for text in leg.get_texts():
|
| 828 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
def test_legend_labelcolor_list():
|
| 832 |
+
# test labelcolor for a list of colors
|
| 833 |
+
fig, ax = plt.subplots()
|
| 834 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1')
|
| 835 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2')
|
| 836 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3')
|
| 837 |
+
|
| 838 |
+
leg = ax.legend(labelcolor=['r', 'g', 'b'])
|
| 839 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 840 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
def test_legend_labelcolor_linecolor():
|
| 844 |
+
# test the labelcolor for labelcolor='linecolor'
|
| 845 |
+
fig, ax = plt.subplots()
|
| 846 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', color='r')
|
| 847 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', color='g')
|
| 848 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', color='b')
|
| 849 |
+
|
| 850 |
+
leg = ax.legend(labelcolor='linecolor')
|
| 851 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 852 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
def test_legend_pathcollection_labelcolor_linecolor():
|
| 856 |
+
# test the labelcolor for labelcolor='linecolor' on PathCollection
|
| 857 |
+
fig, ax = plt.subplots()
|
| 858 |
+
ax.scatter(np.arange(10), np.arange(10)*1, label='#1', c='r')
|
| 859 |
+
ax.scatter(np.arange(10), np.arange(10)*2, label='#2', c='g')
|
| 860 |
+
ax.scatter(np.arange(10), np.arange(10)*3, label='#3', c='b')
|
| 861 |
+
|
| 862 |
+
leg = ax.legend(labelcolor='linecolor')
|
| 863 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 864 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
def test_legend_pathcollection_labelcolor_linecolor_iterable():
|
| 868 |
+
# test the labelcolor for labelcolor='linecolor' on PathCollection
|
| 869 |
+
# with iterable colors
|
| 870 |
+
fig, ax = plt.subplots()
|
| 871 |
+
colors = np.array(['r', 'g', 'b', 'c', 'm'] * 2)
|
| 872 |
+
ax.scatter(np.arange(10), np.arange(10), label='#1', c=colors)
|
| 873 |
+
|
| 874 |
+
leg = ax.legend(labelcolor='linecolor')
|
| 875 |
+
text, = leg.get_texts()
|
| 876 |
+
assert mpl.colors.same_color(text.get_color(), 'black')
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
def test_legend_pathcollection_labelcolor_linecolor_cmap():
|
| 880 |
+
# test the labelcolor for labelcolor='linecolor' on PathCollection
|
| 881 |
+
# with a colormap
|
| 882 |
+
fig, ax = plt.subplots()
|
| 883 |
+
ax.scatter(np.arange(10), np.arange(10), c=np.arange(10), label='#1')
|
| 884 |
+
|
| 885 |
+
leg = ax.legend(labelcolor='linecolor')
|
| 886 |
+
text, = leg.get_texts()
|
| 887 |
+
assert mpl.colors.same_color(text.get_color(), 'black')
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def test_legend_labelcolor_markeredgecolor():
|
| 891 |
+
# test the labelcolor for labelcolor='markeredgecolor'
|
| 892 |
+
fig, ax = plt.subplots()
|
| 893 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', markeredgecolor='r')
|
| 894 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', markeredgecolor='g')
|
| 895 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', markeredgecolor='b')
|
| 896 |
+
|
| 897 |
+
leg = ax.legend(labelcolor='markeredgecolor')
|
| 898 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 899 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def test_legend_pathcollection_labelcolor_markeredgecolor():
|
| 903 |
+
# test the labelcolor for labelcolor='markeredgecolor' on PathCollection
|
| 904 |
+
fig, ax = plt.subplots()
|
| 905 |
+
ax.scatter(np.arange(10), np.arange(10)*1, label='#1', edgecolor='r')
|
| 906 |
+
ax.scatter(np.arange(10), np.arange(10)*2, label='#2', edgecolor='g')
|
| 907 |
+
ax.scatter(np.arange(10), np.arange(10)*3, label='#3', edgecolor='b')
|
| 908 |
+
|
| 909 |
+
leg = ax.legend(labelcolor='markeredgecolor')
|
| 910 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 911 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
def test_legend_pathcollection_labelcolor_markeredgecolor_iterable():
|
| 915 |
+
# test the labelcolor for labelcolor='markeredgecolor' on PathCollection
|
| 916 |
+
# with iterable colors
|
| 917 |
+
fig, ax = plt.subplots()
|
| 918 |
+
colors = np.array(['r', 'g', 'b', 'c', 'm'] * 2)
|
| 919 |
+
ax.scatter(np.arange(10), np.arange(10), label='#1', edgecolor=colors)
|
| 920 |
+
|
| 921 |
+
leg = ax.legend(labelcolor='markeredgecolor')
|
| 922 |
+
for text, color in zip(leg.get_texts(), ['k']):
|
| 923 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
def test_legend_pathcollection_labelcolor_markeredgecolor_cmap():
|
| 927 |
+
# test the labelcolor for labelcolor='markeredgecolor' on PathCollection
|
| 928 |
+
# with a colormap
|
| 929 |
+
fig, ax = plt.subplots()
|
| 930 |
+
edgecolors = mpl.cm.viridis(np.random.rand(10))
|
| 931 |
+
ax.scatter(
|
| 932 |
+
np.arange(10),
|
| 933 |
+
np.arange(10),
|
| 934 |
+
label='#1',
|
| 935 |
+
c=np.arange(10),
|
| 936 |
+
edgecolor=edgecolors,
|
| 937 |
+
cmap="Reds"
|
| 938 |
+
)
|
| 939 |
+
|
| 940 |
+
leg = ax.legend(labelcolor='markeredgecolor')
|
| 941 |
+
for text, color in zip(leg.get_texts(), ['k']):
|
| 942 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
def test_legend_labelcolor_markerfacecolor():
|
| 946 |
+
# test the labelcolor for labelcolor='markerfacecolor'
|
| 947 |
+
fig, ax = plt.subplots()
|
| 948 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', markerfacecolor='r')
|
| 949 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', markerfacecolor='g')
|
| 950 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', markerfacecolor='b')
|
| 951 |
+
|
| 952 |
+
leg = ax.legend(labelcolor='markerfacecolor')
|
| 953 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 954 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
def test_legend_pathcollection_labelcolor_markerfacecolor():
|
| 958 |
+
# test the labelcolor for labelcolor='markerfacecolor' on PathCollection
|
| 959 |
+
fig, ax = plt.subplots()
|
| 960 |
+
ax.scatter(np.arange(10), np.arange(10)*1, label='#1', facecolor='r')
|
| 961 |
+
ax.scatter(np.arange(10), np.arange(10)*2, label='#2', facecolor='g')
|
| 962 |
+
ax.scatter(np.arange(10), np.arange(10)*3, label='#3', facecolor='b')
|
| 963 |
+
|
| 964 |
+
leg = ax.legend(labelcolor='markerfacecolor')
|
| 965 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 966 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def test_legend_pathcollection_labelcolor_markerfacecolor_iterable():
|
| 970 |
+
# test the labelcolor for labelcolor='markerfacecolor' on PathCollection
|
| 971 |
+
# with iterable colors
|
| 972 |
+
fig, ax = plt.subplots()
|
| 973 |
+
colors = np.array(['r', 'g', 'b', 'c', 'm'] * 2)
|
| 974 |
+
ax.scatter(np.arange(10), np.arange(10), label='#1', facecolor=colors)
|
| 975 |
+
|
| 976 |
+
leg = ax.legend(labelcolor='markerfacecolor')
|
| 977 |
+
for text, color in zip(leg.get_texts(), ['k']):
|
| 978 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def test_legend_pathcollection_labelcolor_markfacecolor_cmap():
|
| 982 |
+
# test the labelcolor for labelcolor='markerfacecolor' on PathCollection
|
| 983 |
+
# with colormaps
|
| 984 |
+
fig, ax = plt.subplots()
|
| 985 |
+
colors = mpl.cm.viridis(np.random.rand(10))
|
| 986 |
+
ax.scatter(
|
| 987 |
+
np.arange(10),
|
| 988 |
+
np.arange(10),
|
| 989 |
+
label='#1',
|
| 990 |
+
c=colors
|
| 991 |
+
)
|
| 992 |
+
|
| 993 |
+
leg = ax.legend(labelcolor='markerfacecolor')
|
| 994 |
+
for text, color in zip(leg.get_texts(), ['k']):
|
| 995 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 996 |
+
|
| 997 |
+
|
| 998 |
+
@pytest.mark.parametrize('color', ('red', 'none', (.5, .5, .5)))
|
| 999 |
+
def test_legend_labelcolor_rcparam_single(color):
|
| 1000 |
+
# test the rcParams legend.labelcolor for a single color
|
| 1001 |
+
fig, ax = plt.subplots()
|
| 1002 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1')
|
| 1003 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2')
|
| 1004 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3')
|
| 1005 |
+
|
| 1006 |
+
mpl.rcParams['legend.labelcolor'] = color
|
| 1007 |
+
leg = ax.legend()
|
| 1008 |
+
for text in leg.get_texts():
|
| 1009 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 1010 |
+
|
| 1011 |
+
|
| 1012 |
+
def test_legend_labelcolor_rcparam_linecolor():
|
| 1013 |
+
# test the rcParams legend.labelcolor for a linecolor
|
| 1014 |
+
fig, ax = plt.subplots()
|
| 1015 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', color='r')
|
| 1016 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', color='g')
|
| 1017 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', color='b')
|
| 1018 |
+
|
| 1019 |
+
mpl.rcParams['legend.labelcolor'] = 'linecolor'
|
| 1020 |
+
leg = ax.legend()
|
| 1021 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 1022 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
def test_legend_labelcolor_rcparam_markeredgecolor():
|
| 1026 |
+
# test the labelcolor for labelcolor='markeredgecolor'
|
| 1027 |
+
fig, ax = plt.subplots()
|
| 1028 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', markeredgecolor='r')
|
| 1029 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', markeredgecolor='g')
|
| 1030 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', markeredgecolor='b')
|
| 1031 |
+
|
| 1032 |
+
mpl.rcParams['legend.labelcolor'] = 'markeredgecolor'
|
| 1033 |
+
leg = ax.legend()
|
| 1034 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 1035 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 1036 |
+
|
| 1037 |
+
|
| 1038 |
+
def test_legend_labelcolor_rcparam_markeredgecolor_short():
|
| 1039 |
+
# test the labelcolor for labelcolor='markeredgecolor'
|
| 1040 |
+
fig, ax = plt.subplots()
|
| 1041 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', markeredgecolor='r')
|
| 1042 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', markeredgecolor='g')
|
| 1043 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', markeredgecolor='b')
|
| 1044 |
+
|
| 1045 |
+
mpl.rcParams['legend.labelcolor'] = 'mec'
|
| 1046 |
+
leg = ax.legend()
|
| 1047 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 1048 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 1049 |
+
|
| 1050 |
+
|
| 1051 |
+
def test_legend_labelcolor_rcparam_markerfacecolor():
|
| 1052 |
+
# test the labelcolor for labelcolor='markeredgecolor'
|
| 1053 |
+
fig, ax = plt.subplots()
|
| 1054 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', markerfacecolor='r')
|
| 1055 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', markerfacecolor='g')
|
| 1056 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', markerfacecolor='b')
|
| 1057 |
+
|
| 1058 |
+
mpl.rcParams['legend.labelcolor'] = 'markerfacecolor'
|
| 1059 |
+
leg = ax.legend()
|
| 1060 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 1061 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 1062 |
+
|
| 1063 |
+
|
| 1064 |
+
def test_legend_labelcolor_rcparam_markerfacecolor_short():
|
| 1065 |
+
# test the labelcolor for labelcolor='markeredgecolor'
|
| 1066 |
+
fig, ax = plt.subplots()
|
| 1067 |
+
ax.plot(np.arange(10), np.arange(10)*1, label='#1', markerfacecolor='r')
|
| 1068 |
+
ax.plot(np.arange(10), np.arange(10)*2, label='#2', markerfacecolor='g')
|
| 1069 |
+
ax.plot(np.arange(10), np.arange(10)*3, label='#3', markerfacecolor='b')
|
| 1070 |
+
|
| 1071 |
+
mpl.rcParams['legend.labelcolor'] = 'mfc'
|
| 1072 |
+
leg = ax.legend()
|
| 1073 |
+
for text, color in zip(leg.get_texts(), ['r', 'g', 'b']):
|
| 1074 |
+
assert mpl.colors.same_color(text.get_color(), color)
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
@pytest.mark.filterwarnings("ignore:No artists with labels found to put in legend")
|
| 1078 |
+
def test_get_set_draggable():
|
| 1079 |
+
legend = plt.legend()
|
| 1080 |
+
assert not legend.get_draggable()
|
| 1081 |
+
legend.set_draggable(True)
|
| 1082 |
+
assert legend.get_draggable()
|
| 1083 |
+
legend.set_draggable(False)
|
| 1084 |
+
assert not legend.get_draggable()
|
| 1085 |
+
|
| 1086 |
+
|
| 1087 |
+
@pytest.mark.parametrize('draggable', (True, False))
|
| 1088 |
+
def test_legend_draggable(draggable):
|
| 1089 |
+
fig, ax = plt.subplots()
|
| 1090 |
+
ax.plot(range(10), label='shabnams')
|
| 1091 |
+
leg = ax.legend(draggable=draggable)
|
| 1092 |
+
assert leg.get_draggable() is draggable
|
| 1093 |
+
|
| 1094 |
+
|
| 1095 |
+
def test_alpha_handles():
|
| 1096 |
+
x, n, hh = plt.hist([1, 2, 3], alpha=0.25, label='data', color='red')
|
| 1097 |
+
legend = plt.legend()
|
| 1098 |
+
for lh in legend.legend_handles:
|
| 1099 |
+
lh.set_alpha(1.0)
|
| 1100 |
+
assert lh.get_facecolor()[:-1] == hh[1].get_facecolor()[:-1]
|
| 1101 |
+
assert lh.get_edgecolor()[:-1] == hh[1].get_edgecolor()[:-1]
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
@needs_usetex
|
| 1105 |
+
def test_usetex_no_warn(caplog):
|
| 1106 |
+
mpl.rcParams['font.family'] = 'serif'
|
| 1107 |
+
mpl.rcParams['font.serif'] = 'Computer Modern'
|
| 1108 |
+
mpl.rcParams['text.usetex'] = True
|
| 1109 |
+
|
| 1110 |
+
fig, ax = plt.subplots()
|
| 1111 |
+
ax.plot(0, 0, label='input')
|
| 1112 |
+
ax.legend(title="My legend")
|
| 1113 |
+
|
| 1114 |
+
fig.canvas.draw()
|
| 1115 |
+
assert "Font family ['serif'] not found." not in caplog.text
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
def test_warn_big_data_best_loc(monkeypatch):
|
| 1119 |
+
# Force _find_best_position to think it took a long time.
|
| 1120 |
+
counter = itertools.count(0, step=1.5)
|
| 1121 |
+
monkeypatch.setattr(time, 'perf_counter', lambda: next(counter))
|
| 1122 |
+
|
| 1123 |
+
fig, ax = plt.subplots()
|
| 1124 |
+
fig.canvas.draw() # So that we can call draw_artist later.
|
| 1125 |
+
|
| 1126 |
+
# Place line across all possible legend locations.
|
| 1127 |
+
x = [0.9, 0.1, 0.1, 0.9, 0.9, 0.5]
|
| 1128 |
+
y = [0.95, 0.95, 0.05, 0.05, 0.5, 0.5]
|
| 1129 |
+
ax.plot(x, y, 'o-', label='line')
|
| 1130 |
+
|
| 1131 |
+
with rc_context({'legend.loc': 'best'}):
|
| 1132 |
+
legend = ax.legend()
|
| 1133 |
+
with pytest.warns(UserWarning,
|
| 1134 |
+
match='Creating legend with loc="best" can be slow with large '
|
| 1135 |
+
'amounts of data.') as records:
|
| 1136 |
+
fig.draw_artist(legend) # Don't bother drawing the lines -- it's slow.
|
| 1137 |
+
# The _find_best_position method of Legend is called twice, duplicating
|
| 1138 |
+
# the warning message.
|
| 1139 |
+
assert len(records) == 2
|
| 1140 |
+
|
| 1141 |
+
|
| 1142 |
+
def test_no_warn_big_data_when_loc_specified(monkeypatch):
|
| 1143 |
+
# Force _find_best_position to think it took a long time.
|
| 1144 |
+
counter = itertools.count(0, step=1.5)
|
| 1145 |
+
monkeypatch.setattr(time, 'perf_counter', lambda: next(counter))
|
| 1146 |
+
|
| 1147 |
+
fig, ax = plt.subplots()
|
| 1148 |
+
fig.canvas.draw()
|
| 1149 |
+
|
| 1150 |
+
# Place line across all possible legend locations.
|
| 1151 |
+
x = [0.9, 0.1, 0.1, 0.9, 0.9, 0.5]
|
| 1152 |
+
y = [0.95, 0.95, 0.05, 0.05, 0.5, 0.5]
|
| 1153 |
+
ax.plot(x, y, 'o-', label='line')
|
| 1154 |
+
|
| 1155 |
+
legend = ax.legend('best')
|
| 1156 |
+
fig.draw_artist(legend) # Check that no warning is emitted.
|
| 1157 |
+
|
| 1158 |
+
|
| 1159 |
+
@pytest.mark.parametrize('label_array', [['low', 'high'],
|
| 1160 |
+
('low', 'high'),
|
| 1161 |
+
np.array(['low', 'high'])])
|
| 1162 |
+
def test_plot_multiple_input_multiple_label(label_array):
|
| 1163 |
+
# test ax.plot() with multidimensional input
|
| 1164 |
+
# and multiple labels
|
| 1165 |
+
x = [1, 2, 3]
|
| 1166 |
+
y = [[1, 2],
|
| 1167 |
+
[2, 5],
|
| 1168 |
+
[4, 9]]
|
| 1169 |
+
|
| 1170 |
+
fig, ax = plt.subplots()
|
| 1171 |
+
ax.plot(x, y, label=label_array)
|
| 1172 |
+
leg = ax.legend()
|
| 1173 |
+
legend_texts = [entry.get_text() for entry in leg.get_texts()]
|
| 1174 |
+
assert legend_texts == ['low', 'high']
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
@pytest.mark.parametrize('label', ['one', 1, int])
|
| 1178 |
+
def test_plot_multiple_input_single_label(label):
|
| 1179 |
+
# test ax.plot() with multidimensional input
|
| 1180 |
+
# and single label
|
| 1181 |
+
x = [1, 2, 3]
|
| 1182 |
+
y = [[1, 2],
|
| 1183 |
+
[2, 5],
|
| 1184 |
+
[4, 9]]
|
| 1185 |
+
|
| 1186 |
+
fig, ax = plt.subplots()
|
| 1187 |
+
ax.plot(x, y, label=label)
|
| 1188 |
+
leg = ax.legend()
|
| 1189 |
+
legend_texts = [entry.get_text() for entry in leg.get_texts()]
|
| 1190 |
+
assert legend_texts == [str(label)] * 2
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
@pytest.mark.parametrize('label_array', [['low', 'high'],
|
| 1194 |
+
('low', 'high'),
|
| 1195 |
+
np.array(['low', 'high'])])
|
| 1196 |
+
def test_plot_single_input_multiple_label(label_array):
|
| 1197 |
+
# test ax.plot() with 1D array like input
|
| 1198 |
+
# and iterable label
|
| 1199 |
+
x = [1, 2, 3]
|
| 1200 |
+
y = [2, 5, 6]
|
| 1201 |
+
fig, ax = plt.subplots()
|
| 1202 |
+
with pytest.warns(mpl.MatplotlibDeprecationWarning,
|
| 1203 |
+
match='Passing label as a length 2 sequence'):
|
| 1204 |
+
ax.plot(x, y, label=label_array)
|
| 1205 |
+
leg = ax.legend()
|
| 1206 |
+
assert len(leg.get_texts()) == 1
|
| 1207 |
+
assert leg.get_texts()[0].get_text() == str(label_array)
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
def test_plot_single_input_list_label():
|
| 1211 |
+
fig, ax = plt.subplots()
|
| 1212 |
+
line, = ax.plot([[0], [1]], label=['A'])
|
| 1213 |
+
assert line.get_label() == 'A'
|
| 1214 |
+
|
| 1215 |
+
|
| 1216 |
+
def test_plot_multiple_label_incorrect_length_exception():
|
| 1217 |
+
# check that exception is raised if multiple labels
|
| 1218 |
+
# are given, but number of on labels != number of lines
|
| 1219 |
+
with pytest.raises(ValueError):
|
| 1220 |
+
x = [1, 2, 3]
|
| 1221 |
+
y = [[1, 2],
|
| 1222 |
+
[2, 5],
|
| 1223 |
+
[4, 9]]
|
| 1224 |
+
label = ['high', 'low', 'medium']
|
| 1225 |
+
fig, ax = plt.subplots()
|
| 1226 |
+
ax.plot(x, y, label=label)
|
| 1227 |
+
|
| 1228 |
+
|
| 1229 |
+
def test_legend_face_edgecolor():
|
| 1230 |
+
# Smoke test for PolyCollection legend handler with 'face' edgecolor.
|
| 1231 |
+
fig, ax = plt.subplots()
|
| 1232 |
+
ax.fill_between([0, 1, 2], [1, 2, 3], [2, 3, 4],
|
| 1233 |
+
facecolor='r', edgecolor='face', label='Fill')
|
| 1234 |
+
ax.legend()
|
| 1235 |
+
|
| 1236 |
+
|
| 1237 |
+
def test_legend_text_axes():
|
| 1238 |
+
fig, ax = plt.subplots()
|
| 1239 |
+
ax.plot([1, 2], [3, 4], label='line')
|
| 1240 |
+
leg = ax.legend()
|
| 1241 |
+
|
| 1242 |
+
assert leg.axes is ax
|
| 1243 |
+
assert leg.get_texts()[0].axes is ax
|
| 1244 |
+
|
| 1245 |
+
|
| 1246 |
+
def test_handlerline2d():
|
| 1247 |
+
# Test marker consistency for monolithic Line2D legend handler (#11357).
|
| 1248 |
+
fig, ax = plt.subplots()
|
| 1249 |
+
ax.scatter([0, 1], [0, 1], marker="v")
|
| 1250 |
+
handles = [mlines.Line2D([0], [0], marker="v")]
|
| 1251 |
+
leg = ax.legend(handles, ["Aardvark"], numpoints=1)
|
| 1252 |
+
assert handles[0].get_marker() == leg.legend_handles[0].get_marker()
|
| 1253 |
+
|
| 1254 |
+
|
| 1255 |
+
def test_subfigure_legend():
|
| 1256 |
+
# Test that legend can be added to subfigure (#20723)
|
| 1257 |
+
subfig = plt.figure().subfigures()
|
| 1258 |
+
ax = subfig.subplots()
|
| 1259 |
+
ax.plot([0, 1], [0, 1], label="line")
|
| 1260 |
+
leg = subfig.legend()
|
| 1261 |
+
assert leg.get_figure(root=False) is subfig
|
| 1262 |
+
|
| 1263 |
+
|
| 1264 |
+
def test_setting_alpha_keeps_polycollection_color():
|
| 1265 |
+
pc = plt.fill_between([0, 1], [2, 3], color='#123456', label='label')
|
| 1266 |
+
patch = plt.legend().get_patches()[0]
|
| 1267 |
+
patch.set_alpha(0.5)
|
| 1268 |
+
assert patch.get_facecolor()[:3] == tuple(pc.get_facecolor()[0][:3])
|
| 1269 |
+
assert patch.get_edgecolor()[:3] == tuple(pc.get_edgecolor()[0][:3])
|
| 1270 |
+
|
| 1271 |
+
|
| 1272 |
+
def test_legend_markers_from_line2d():
|
| 1273 |
+
# Test that markers can be copied for legend lines (#17960)
|
| 1274 |
+
_markers = ['.', '*', 'v']
|
| 1275 |
+
fig, ax = plt.subplots()
|
| 1276 |
+
lines = [mlines.Line2D([0], [0], ls='None', marker=mark)
|
| 1277 |
+
for mark in _markers]
|
| 1278 |
+
labels = ["foo", "bar", "xyzzy"]
|
| 1279 |
+
markers = [line.get_marker() for line in lines]
|
| 1280 |
+
legend = ax.legend(lines, labels)
|
| 1281 |
+
|
| 1282 |
+
new_markers = [line.get_marker() for line in legend.get_lines()]
|
| 1283 |
+
new_labels = [text.get_text() for text in legend.get_texts()]
|
| 1284 |
+
|
| 1285 |
+
assert markers == new_markers == _markers
|
| 1286 |
+
assert labels == new_labels
|
| 1287 |
+
|
| 1288 |
+
|
| 1289 |
+
@check_figures_equal(extensions=['png'])
|
| 1290 |
+
def test_ncol_ncols(fig_test, fig_ref):
|
| 1291 |
+
# Test that both ncol and ncols work
|
| 1292 |
+
strings = ["a", "b", "c", "d", "e", "f"]
|
| 1293 |
+
ncols = 3
|
| 1294 |
+
fig_test.legend(strings, ncol=ncols)
|
| 1295 |
+
fig_ref.legend(strings, ncols=ncols)
|
| 1296 |
+
|
| 1297 |
+
|
| 1298 |
+
def test_loc_invalid_tuple_exception():
|
| 1299 |
+
# check that exception is raised if the loc arg
|
| 1300 |
+
# of legend is not a 2-tuple of numbers
|
| 1301 |
+
fig, ax = plt.subplots()
|
| 1302 |
+
with pytest.raises(ValueError, match=('loc must be string, coordinate '
|
| 1303 |
+
'tuple, or an integer 0-10, not \\(1.1,\\)')):
|
| 1304 |
+
ax.legend(loc=(1.1, ), labels=["mock data"])
|
| 1305 |
+
|
| 1306 |
+
with pytest.raises(ValueError, match=('loc must be string, coordinate '
|
| 1307 |
+
'tuple, or an integer 0-10, not \\(0.481, 0.4227, 0.4523\\)')):
|
| 1308 |
+
ax.legend(loc=(0.481, 0.4227, 0.4523), labels=["mock data"])
|
| 1309 |
+
|
| 1310 |
+
with pytest.raises(ValueError, match=('loc must be string, coordinate '
|
| 1311 |
+
'tuple, or an integer 0-10, not \\(0.481, \'go blue\'\\)')):
|
| 1312 |
+
ax.legend(loc=(0.481, "go blue"), labels=["mock data"])
|
| 1313 |
+
|
| 1314 |
+
|
| 1315 |
+
def test_loc_valid_tuple():
|
| 1316 |
+
fig, ax = plt.subplots()
|
| 1317 |
+
ax.legend(loc=(0.481, 0.442), labels=["mock data"])
|
| 1318 |
+
ax.legend(loc=(1, 2), labels=["mock data"])
|
| 1319 |
+
|
| 1320 |
+
|
| 1321 |
+
def test_loc_valid_list():
|
| 1322 |
+
fig, ax = plt.subplots()
|
| 1323 |
+
ax.legend(loc=[0.481, 0.442], labels=["mock data"])
|
| 1324 |
+
ax.legend(loc=[1, 2], labels=["mock data"])
|
| 1325 |
+
|
| 1326 |
+
|
| 1327 |
+
def test_loc_invalid_list_exception():
|
| 1328 |
+
fig, ax = plt.subplots()
|
| 1329 |
+
with pytest.raises(ValueError, match=('loc must be string, coordinate '
|
| 1330 |
+
'tuple, or an integer 0-10, not \\[1.1, 2.2, 3.3\\]')):
|
| 1331 |
+
ax.legend(loc=[1.1, 2.2, 3.3], labels=["mock data"])
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
def test_loc_invalid_type():
|
| 1335 |
+
fig, ax = plt.subplots()
|
| 1336 |
+
with pytest.raises(ValueError, match=("loc must be string, coordinate "
|
| 1337 |
+
"tuple, or an integer 0-10, not {'not': True}")):
|
| 1338 |
+
ax.legend(loc={'not': True}, labels=["mock data"])
|
| 1339 |
+
|
| 1340 |
+
|
| 1341 |
+
def test_loc_validation_numeric_value():
|
| 1342 |
+
fig, ax = plt.subplots()
|
| 1343 |
+
ax.legend(loc=0, labels=["mock data"])
|
| 1344 |
+
ax.legend(loc=1, labels=["mock data"])
|
| 1345 |
+
ax.legend(loc=5, labels=["mock data"])
|
| 1346 |
+
ax.legend(loc=10, labels=["mock data"])
|
| 1347 |
+
with pytest.raises(ValueError, match=('loc must be string, coordinate '
|
| 1348 |
+
'tuple, or an integer 0-10, not 11')):
|
| 1349 |
+
ax.legend(loc=11, labels=["mock data"])
|
| 1350 |
+
|
| 1351 |
+
with pytest.raises(ValueError, match=('loc must be string, coordinate '
|
| 1352 |
+
'tuple, or an integer 0-10, not -1')):
|
| 1353 |
+
ax.legend(loc=-1, labels=["mock data"])
|
| 1354 |
+
|
| 1355 |
+
|
| 1356 |
+
def test_loc_validation_string_value():
|
| 1357 |
+
fig, ax = plt.subplots()
|
| 1358 |
+
labels = ["mock data"]
|
| 1359 |
+
ax.legend(loc='best', labels=labels)
|
| 1360 |
+
ax.legend(loc='upper right', labels=labels)
|
| 1361 |
+
ax.legend(loc='best', labels=labels)
|
| 1362 |
+
ax.legend(loc='upper right', labels=labels)
|
| 1363 |
+
ax.legend(loc='upper left', labels=labels)
|
| 1364 |
+
ax.legend(loc='lower left', labels=labels)
|
| 1365 |
+
ax.legend(loc='lower right', labels=labels)
|
| 1366 |
+
ax.legend(loc='right', labels=labels)
|
| 1367 |
+
ax.legend(loc='center left', labels=labels)
|
| 1368 |
+
ax.legend(loc='center right', labels=labels)
|
| 1369 |
+
ax.legend(loc='lower center', labels=labels)
|
| 1370 |
+
ax.legend(loc='upper center', labels=labels)
|
| 1371 |
+
with pytest.raises(ValueError, match="'wrong' is not a valid value for"):
|
| 1372 |
+
ax.legend(loc='wrong', labels=labels)
|
| 1373 |
+
|
| 1374 |
+
|
| 1375 |
+
def test_legend_handle_label_mismatch():
|
| 1376 |
+
pl1, = plt.plot(range(10))
|
| 1377 |
+
pl2, = plt.plot(range(10))
|
| 1378 |
+
with pytest.warns(UserWarning, match="number of handles and labels"):
|
| 1379 |
+
legend = plt.legend(handles=[pl1, pl2], labels=["pl1", "pl2", "pl3"])
|
| 1380 |
+
assert len(legend.legend_handles) == 2
|
| 1381 |
+
assert len(legend.get_texts()) == 2
|
| 1382 |
+
|
| 1383 |
+
|
| 1384 |
+
def test_legend_handle_label_mismatch_no_len():
|
| 1385 |
+
pl1, = plt.plot(range(10))
|
| 1386 |
+
pl2, = plt.plot(range(10))
|
| 1387 |
+
legend = plt.legend(handles=iter([pl1, pl2]),
|
| 1388 |
+
labels=iter(["pl1", "pl2", "pl3"]))
|
| 1389 |
+
assert len(legend.legend_handles) == 2
|
| 1390 |
+
assert len(legend.get_texts()) == 2
|
| 1391 |
+
|
| 1392 |
+
|
| 1393 |
+
def test_legend_nolabels_warning():
|
| 1394 |
+
plt.plot([1, 2, 3])
|
| 1395 |
+
with pytest.raises(UserWarning, match="No artists with labels found"):
|
| 1396 |
+
plt.legend()
|
| 1397 |
+
|
| 1398 |
+
|
| 1399 |
+
@pytest.mark.filterwarnings("ignore:No artists with labels found to put in legend")
|
| 1400 |
+
def test_legend_nolabels_draw():
|
| 1401 |
+
plt.plot([1, 2, 3])
|
| 1402 |
+
plt.legend()
|
| 1403 |
+
assert plt.gca().get_legend() is not None
|
| 1404 |
+
|
| 1405 |
+
|
| 1406 |
+
def test_legend_loc_polycollection():
|
| 1407 |
+
# Test that the legend is placed in the correct
|
| 1408 |
+
# position for 'best' for polycollection
|
| 1409 |
+
x = [3, 4, 5]
|
| 1410 |
+
y1 = [1, 1, 1]
|
| 1411 |
+
y2 = [5, 5, 5]
|
| 1412 |
+
leg_bboxes = []
|
| 1413 |
+
fig, axs = plt.subplots(ncols=2, figsize=(10, 5))
|
| 1414 |
+
for ax, loc in zip(axs.flat, ('best', 'lower left')):
|
| 1415 |
+
ax.fill_between(x, y1, y2, color='gray', alpha=0.5, label='Shaded Area')
|
| 1416 |
+
ax.set_xlim(0, 6)
|
| 1417 |
+
ax.set_ylim(-1, 5)
|
| 1418 |
+
leg = ax.legend(loc=loc)
|
| 1419 |
+
fig.canvas.draw()
|
| 1420 |
+
leg_bboxes.append(
|
| 1421 |
+
leg.get_window_extent().transformed(ax.transAxes.inverted()))
|
| 1422 |
+
assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)
|
| 1423 |
+
|
| 1424 |
+
|
| 1425 |
+
def test_legend_text():
|
| 1426 |
+
# Test that legend is place in the correct
|
| 1427 |
+
# position for 'best' when there is text in figure
|
| 1428 |
+
fig, axs = plt.subplots(ncols=2, figsize=(10, 5))
|
| 1429 |
+
leg_bboxes = []
|
| 1430 |
+
for ax, loc in zip(axs.flat, ('best', 'lower left')):
|
| 1431 |
+
x = [1, 2]
|
| 1432 |
+
y = [2, 1]
|
| 1433 |
+
ax.plot(x, y, label='plot name')
|
| 1434 |
+
ax.text(1.5, 2, 'some text blahblah', verticalalignment='top')
|
| 1435 |
+
leg = ax.legend(loc=loc)
|
| 1436 |
+
fig.canvas.draw()
|
| 1437 |
+
leg_bboxes.append(
|
| 1438 |
+
leg.get_window_extent().transformed(ax.transAxes.inverted()))
|
| 1439 |
+
assert_allclose(leg_bboxes[1].bounds, leg_bboxes[0].bounds)
|
| 1440 |
+
|
| 1441 |
+
|
| 1442 |
+
def test_legend_annotate():
|
| 1443 |
+
fig, ax = plt.subplots()
|
| 1444 |
+
|
| 1445 |
+
ax.plot([1, 2, 3], label="Line")
|
| 1446 |
+
ax.annotate("a", xy=(1, 1))
|
| 1447 |
+
ax.legend(loc=0)
|
| 1448 |
+
|
| 1449 |
+
with mock.patch.object(
|
| 1450 |
+
fig, '_get_renderer', wraps=fig._get_renderer) as mocked_get_renderer:
|
| 1451 |
+
fig.savefig(io.BytesIO())
|
| 1452 |
+
|
| 1453 |
+
# Finding the legend position should not require _get_renderer to be called
|
| 1454 |
+
mocked_get_renderer.assert_not_called()
|
| 1455 |
+
|
| 1456 |
+
|
| 1457 |
+
def test_boxplot_legend_labels():
|
| 1458 |
+
# Test that legend entries are generated when passing `label`.
|
| 1459 |
+
np.random.seed(19680801)
|
| 1460 |
+
data = np.random.random((10, 4))
|
| 1461 |
+
fig, axs = plt.subplots(nrows=1, ncols=4)
|
| 1462 |
+
legend_labels = ['box A', 'box B', 'box C', 'box D']
|
| 1463 |
+
|
| 1464 |
+
# Testing legend labels and patch passed to legend.
|
| 1465 |
+
bp1 = axs[0].boxplot(data, patch_artist=True, label=legend_labels)
|
| 1466 |
+
assert [v.get_label() for v in bp1['boxes']] == legend_labels
|
| 1467 |
+
handles, labels = axs[0].get_legend_handles_labels()
|
| 1468 |
+
assert labels == legend_labels
|
| 1469 |
+
assert all(isinstance(h, mpl.patches.PathPatch) for h in handles)
|
| 1470 |
+
|
| 1471 |
+
# Testing legend without `box`.
|
| 1472 |
+
bp2 = axs[1].boxplot(data, label=legend_labels, showbox=False)
|
| 1473 |
+
# Without a box, The legend entries should be passed from the medians.
|
| 1474 |
+
assert [v.get_label() for v in bp2['medians']] == legend_labels
|
| 1475 |
+
handles, labels = axs[1].get_legend_handles_labels()
|
| 1476 |
+
assert labels == legend_labels
|
| 1477 |
+
assert all(isinstance(h, mpl.lines.Line2D) for h in handles)
|
| 1478 |
+
|
| 1479 |
+
# Testing legend with number of labels different from number of boxes.
|
| 1480 |
+
with pytest.raises(ValueError, match='values must have same the length'):
|
| 1481 |
+
bp3 = axs[2].boxplot(data, label=legend_labels[:-1])
|
| 1482 |
+
|
| 1483 |
+
# Test that for a string label, only the first box gets a label.
|
| 1484 |
+
bp4 = axs[3].boxplot(data, label='box A')
|
| 1485 |
+
assert bp4['medians'][0].get_label() == 'box A'
|
| 1486 |
+
assert all(x.get_label().startswith("_") for x in bp4['medians'][1:])
|
shared/package-files/41/41e42466b686bd3739838b6fd503ec1d514c93bbcdef23b6b1b4e869fe86369e/blob
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from Function.h
|
| 4 |
+
|
| 5 |
+
#include <ATen/Context.h>
|
| 6 |
+
#include <ATen/DeviceGuard.h>
|
| 7 |
+
#include <ATen/TensorUtils.h>
|
| 8 |
+
#include <ATen/TracerMode.h>
|
| 9 |
+
#include <ATen/core/Generator.h>
|
| 10 |
+
#include <ATen/core/Reduction.h>
|
| 11 |
+
#include <ATen/core/Tensor.h>
|
| 12 |
+
#include <c10/core/Scalar.h>
|
| 13 |
+
#include <c10/core/Storage.h>
|
| 14 |
+
#include <c10/core/TensorOptions.h>
|
| 15 |
+
#include <c10/util/Deprecated.h>
|
| 16 |
+
#include <c10/util/Optional.h>
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
#include <ATen/ops/conv_transpose1d_ops.h>
|
| 21 |
+
|
| 22 |
+
namespace at {
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
// aten::conv_transpose1d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, SymInt[1] padding=0, SymInt[1] output_padding=0, SymInt groups=1, SymInt[1] dilation=1) -> Tensor
|
| 26 |
+
inline at::Tensor conv_transpose1d(const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1) {
|
| 27 |
+
return at::_ops::conv_transpose1d::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), groups, c10::fromIntArrayRefSlow(dilation));
|
| 28 |
+
}
|
| 29 |
+
namespace symint {
|
| 30 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
|
| 31 |
+
at::Tensor conv_transpose1d(const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, int64_t groups=1, at::IntArrayRef dilation=1) {
|
| 32 |
+
return at::_ops::conv_transpose1d::call(input, weight, bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), groups, c10::fromIntArrayRefSlow(dilation));
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// aten::conv_transpose1d(Tensor input, Tensor weight, Tensor? bias=None, SymInt[1] stride=1, SymInt[1] padding=0, SymInt[1] output_padding=0, SymInt groups=1, SymInt[1] dilation=1) -> Tensor
|
| 37 |
+
inline at::Tensor conv_transpose1d_symint(const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1)) {
|
| 38 |
+
return at::_ops::conv_transpose1d::call(input, weight, bias, stride, padding, output_padding, groups, dilation);
|
| 39 |
+
}
|
| 40 |
+
namespace symint {
|
| 41 |
+
template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
|
| 42 |
+
at::Tensor conv_transpose1d(const at::Tensor & input, const at::Tensor & weight, const c10::optional<at::Tensor> & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymInt groups=1, c10::SymIntArrayRef dilation=c10::SymInt(1)) {
|
| 43 |
+
return at::_ops::conv_transpose1d::call(input, weight, bias, stride, padding, output_padding, groups, dilation);
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
}
|
shared/package-files/41/41e51412e3668739e9b8a34f2fe0742153a431d302bbca095fad8e0b4569cee8/blob
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import socket
|
| 4 |
+
import typing
|
| 5 |
+
|
| 6 |
+
from ..exceptions import LocationParseError
|
| 7 |
+
from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT
|
| 8 |
+
|
| 9 |
+
_TYPE_SOCKET_OPTIONS = typing.Sequence[typing.Tuple[int, int, typing.Union[int, bytes]]]
|
| 10 |
+
|
| 11 |
+
if typing.TYPE_CHECKING:
|
| 12 |
+
from .._base_connection import BaseHTTPConnection
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific
|
| 16 |
+
"""
|
| 17 |
+
Returns True if the connection is dropped and should be closed.
|
| 18 |
+
:param conn: :class:`urllib3.connection.HTTPConnection` object.
|
| 19 |
+
"""
|
| 20 |
+
return not conn.is_connected
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# This function is copied from socket.py in the Python 2.7 standard
|
| 24 |
+
# library test suite. Added to its signature is only `socket_options`.
|
| 25 |
+
# One additional modification is that we avoid binding to IPv6 servers
|
| 26 |
+
# discovered in DNS if the system doesn't have IPv6 functionality.
|
| 27 |
+
def create_connection(
|
| 28 |
+
address: tuple[str, int],
|
| 29 |
+
timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
|
| 30 |
+
source_address: tuple[str, int] | None = None,
|
| 31 |
+
socket_options: _TYPE_SOCKET_OPTIONS | None = None,
|
| 32 |
+
) -> socket.socket:
|
| 33 |
+
"""Connect to *address* and return the socket object.
|
| 34 |
+
|
| 35 |
+
Convenience function. Connect to *address* (a 2-tuple ``(host,
|
| 36 |
+
port)``) and return the socket object. Passing the optional
|
| 37 |
+
*timeout* parameter will set the timeout on the socket instance
|
| 38 |
+
before attempting to connect. If no *timeout* is supplied, the
|
| 39 |
+
global default timeout setting returned by :func:`socket.getdefaulttimeout`
|
| 40 |
+
is used. If *source_address* is set it must be a tuple of (host, port)
|
| 41 |
+
for the socket to bind as a source address before making the connection.
|
| 42 |
+
An host of '' or port 0 tells the OS to use the default.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
host, port = address
|
| 46 |
+
if host.startswith("["):
|
| 47 |
+
host = host.strip("[]")
|
| 48 |
+
err = None
|
| 49 |
+
|
| 50 |
+
# Using the value from allowed_gai_family() in the context of getaddrinfo lets
|
| 51 |
+
# us select whether to work with IPv4 DNS records, IPv6 records, or both.
|
| 52 |
+
# The original create_connection function always returns all records.
|
| 53 |
+
family = allowed_gai_family()
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
host.encode("idna")
|
| 57 |
+
except UnicodeError:
|
| 58 |
+
raise LocationParseError(f"'{host}', label empty or too long") from None
|
| 59 |
+
|
| 60 |
+
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
|
| 61 |
+
af, socktype, proto, canonname, sa = res
|
| 62 |
+
sock = None
|
| 63 |
+
try:
|
| 64 |
+
sock = socket.socket(af, socktype, proto)
|
| 65 |
+
|
| 66 |
+
# If provided, set socket level options before connecting.
|
| 67 |
+
_set_socket_options(sock, socket_options)
|
| 68 |
+
|
| 69 |
+
if timeout is not _DEFAULT_TIMEOUT:
|
| 70 |
+
sock.settimeout(timeout)
|
| 71 |
+
if source_address:
|
| 72 |
+
sock.bind(source_address)
|
| 73 |
+
sock.connect(sa)
|
| 74 |
+
# Break explicitly a reference cycle
|
| 75 |
+
err = None
|
| 76 |
+
return sock
|
| 77 |
+
|
| 78 |
+
except OSError as _:
|
| 79 |
+
err = _
|
| 80 |
+
if sock is not None:
|
| 81 |
+
sock.close()
|
| 82 |
+
|
| 83 |
+
if err is not None:
|
| 84 |
+
try:
|
| 85 |
+
raise err
|
| 86 |
+
finally:
|
| 87 |
+
# Break explicitly a reference cycle
|
| 88 |
+
err = None
|
| 89 |
+
else:
|
| 90 |
+
raise OSError("getaddrinfo returns an empty list")
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _set_socket_options(
|
| 94 |
+
sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None
|
| 95 |
+
) -> None:
|
| 96 |
+
if options is None:
|
| 97 |
+
return
|
| 98 |
+
|
| 99 |
+
for opt in options:
|
| 100 |
+
sock.setsockopt(*opt)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def allowed_gai_family() -> socket.AddressFamily:
|
| 104 |
+
"""This function is designed to work in the context of
|
| 105 |
+
getaddrinfo, where family=socket.AF_UNSPEC is the default and
|
| 106 |
+
will perform a DNS search for both IPv6 and IPv4 records."""
|
| 107 |
+
|
| 108 |
+
family = socket.AF_INET
|
| 109 |
+
if HAS_IPV6:
|
| 110 |
+
family = socket.AF_UNSPEC
|
| 111 |
+
return family
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _has_ipv6(host: str) -> bool:
|
| 115 |
+
"""Returns True if the system can bind an IPv6 address."""
|
| 116 |
+
sock = None
|
| 117 |
+
has_ipv6 = False
|
| 118 |
+
|
| 119 |
+
if socket.has_ipv6:
|
| 120 |
+
# has_ipv6 returns true if cPython was compiled with IPv6 support.
|
| 121 |
+
# It does not tell us if the system has IPv6 support enabled. To
|
| 122 |
+
# determine that we must bind to an IPv6 address.
|
| 123 |
+
# https://github.com/urllib3/urllib3/pull/611
|
| 124 |
+
# https://bugs.python.org/issue658327
|
| 125 |
+
try:
|
| 126 |
+
sock = socket.socket(socket.AF_INET6)
|
| 127 |
+
sock.bind((host, 0))
|
| 128 |
+
has_ipv6 = True
|
| 129 |
+
except Exception:
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
if sock:
|
| 133 |
+
sock.close()
|
| 134 |
+
return has_ipv6
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
HAS_IPV6 = _has_ipv6("::1")
|
shared/package-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.tcl --
|
| 2 |
+
#
|
| 3 |
+
# This demonstration script creates a text widget that illustrates the
|
| 4 |
+
# various display styles that may be set for tags.
|
| 5 |
+
|
| 6 |
+
if {![info exists widgetDemo]} {
|
| 7 |
+
error "This script should be run from the \"widget\" demo."
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
package require Tk
|
| 11 |
+
|
| 12 |
+
set w .style
|
| 13 |
+
catch {destroy $w}
|
| 14 |
+
toplevel $w
|
| 15 |
+
wm title $w "Text Demonstration - Display Styles"
|
| 16 |
+
wm iconname $w "style"
|
| 17 |
+
positionWindow $w
|
| 18 |
+
|
| 19 |
+
## See Code / Dismiss buttons
|
| 20 |
+
set btns [addSeeDismiss $w.buttons $w]
|
| 21 |
+
pack $btns -side bottom -fill x
|
| 22 |
+
|
| 23 |
+
# Only set the font family in one place for simplicity and consistency
|
| 24 |
+
|
| 25 |
+
set family Courier
|
| 26 |
+
|
| 27 |
+
text $w.text -yscrollcommand "$w.scroll set" -setgrid true \
|
| 28 |
+
-width 70 -height 32 -wrap word -font "$family 12"
|
| 29 |
+
ttk::scrollbar $w.scroll -command "$w.text yview"
|
| 30 |
+
pack $w.scroll -side right -fill y
|
| 31 |
+
pack $w.text -expand yes -fill both
|
| 32 |
+
|
| 33 |
+
# Set up display styles
|
| 34 |
+
|
| 35 |
+
$w.text tag configure bold -font "$family 12 bold italic"
|
| 36 |
+
$w.text tag configure big -font "$family 14 bold"
|
| 37 |
+
$w.text tag configure verybig -font "Helvetica 24 bold"
|
| 38 |
+
$w.text tag configure tiny -font "Times 8 bold"
|
| 39 |
+
if {[winfo depth $w] > 1} {
|
| 40 |
+
$w.text tag configure color1 -background #a0b7ce
|
| 41 |
+
$w.text tag configure color2 -foreground red
|
| 42 |
+
$w.text tag configure raised -relief raised -borderwidth 1
|
| 43 |
+
$w.text tag configure sunken -relief sunken -borderwidth 1
|
| 44 |
+
} else {
|
| 45 |
+
$w.text tag configure color1 -background black -foreground white
|
| 46 |
+
$w.text tag configure color2 -background black -foreground white
|
| 47 |
+
$w.text tag configure raised -background white -relief raised \
|
| 48 |
+
-borderwidth 1
|
| 49 |
+
$w.text tag configure sunken -background white -relief sunken \
|
| 50 |
+
-borderwidth 1
|
| 51 |
+
}
|
| 52 |
+
$w.text tag configure bgstipple -background black -borderwidth 0 \
|
| 53 |
+
-bgstipple gray12
|
| 54 |
+
$w.text tag configure fgstipple -fgstipple gray50
|
| 55 |
+
$w.text tag configure underline -underline on
|
| 56 |
+
$w.text tag configure overstrike -overstrike on
|
| 57 |
+
$w.text tag configure right -justify right
|
| 58 |
+
$w.text tag configure center -justify center
|
| 59 |
+
$w.text tag configure super -offset 4p -font "$family 10"
|
| 60 |
+
$w.text tag configure sub -offset -2p -font "$family 10"
|
| 61 |
+
$w.text tag configure margins -lmargin1 12m -lmargin2 6m -rmargin 10m
|
| 62 |
+
$w.text tag configure spacing -spacing1 10p -spacing2 2p \
|
| 63 |
+
-lmargin1 12m -lmargin2 6m -rmargin 10m
|
| 64 |
+
|
| 65 |
+
$w.text insert end {Text widgets like this one allow you to display information in a
|
| 66 |
+
variety of styles. Display styles are controlled using a mechanism
|
| 67 |
+
called }
|
| 68 |
+
$w.text insert end tags bold
|
| 69 |
+
$w.text insert end {. Tags are just textual names that you can apply to one
|
| 70 |
+
or more ranges of characters within a text widget. You can configure
|
| 71 |
+
tags with various display styles. If you do this, then the tagged
|
| 72 |
+
characters will be displayed with the styles you chose. The
|
| 73 |
+
available display styles are:
|
| 74 |
+
}
|
| 75 |
+
$w.text insert end "\n1. Font." big
|
| 76 |
+
$w.text insert end " You can choose any system font, "
|
| 77 |
+
$w.text insert end large verybig
|
| 78 |
+
$w.text insert end " or "
|
| 79 |
+
$w.text insert end "small" tiny ".\n"
|
| 80 |
+
$w.text insert end "\n2. Color." big
|
| 81 |
+
$w.text insert end " You can change either the "
|
| 82 |
+
$w.text insert end background color1
|
| 83 |
+
$w.text insert end " or "
|
| 84 |
+
$w.text insert end foreground color2
|
| 85 |
+
$w.text insert end "\ncolor, or "
|
| 86 |
+
$w.text insert end both {color1 color2}
|
| 87 |
+
$w.text insert end ".\n"
|
| 88 |
+
$w.text insert end "\n3. Stippling." big
|
| 89 |
+
$w.text insert end " You can cause either the "
|
| 90 |
+
$w.text insert end background bgstipple
|
| 91 |
+
$w.text insert end " or "
|
| 92 |
+
$w.text insert end foreground fgstipple
|
| 93 |
+
$w.text insert end {
|
| 94 |
+
information to be drawn with a stipple fill instead of a solid fill.
|
| 95 |
+
}
|
| 96 |
+
$w.text insert end "\n4. Underlining." big
|
| 97 |
+
$w.text insert end " You can "
|
| 98 |
+
$w.text insert end underline underline
|
| 99 |
+
$w.text insert end " ranges of text.\n"
|
| 100 |
+
$w.text insert end "\n5. Overstrikes." big
|
| 101 |
+
$w.text insert end " You can "
|
| 102 |
+
$w.text insert end "draw lines through" overstrike
|
| 103 |
+
$w.text insert end " ranges of text.\n"
|
| 104 |
+
$w.text insert end "\n6. 3-D effects." big
|
| 105 |
+
$w.text insert end { You can arrange for the background to be drawn
|
| 106 |
+
with a border that makes characters appear either }
|
| 107 |
+
$w.text insert end raised raised
|
| 108 |
+
$w.text insert end " or "
|
| 109 |
+
$w.text insert end sunken sunken
|
| 110 |
+
$w.text insert end ".\n"
|
| 111 |
+
$w.text insert end "\n7. Justification." big
|
| 112 |
+
$w.text insert end " You can arrange for lines to be displayed\n"
|
| 113 |
+
$w.text insert end "left-justified,\n"
|
| 114 |
+
$w.text insert end "right-justified, or\n" right
|
| 115 |
+
$w.text insert end "centered.\n" center
|
| 116 |
+
$w.text insert end "\n8. Superscripts and subscripts." big
|
| 117 |
+
$w.text insert end " You can control the vertical\n"
|
| 118 |
+
$w.text insert end "position of text to generate superscript effects like 10"
|
| 119 |
+
$w.text insert end "n" super
|
| 120 |
+
$w.text insert end " or\nsubscript effects like X"
|
| 121 |
+
$w.text insert end "i" sub
|
| 122 |
+
$w.text insert end ".\n"
|
| 123 |
+
$w.text insert end "\n9. Margins." big
|
| 124 |
+
$w.text insert end " You can control the amount of extra space left"
|
| 125 |
+
$w.text insert end " on\neach side of the text:\n"
|
| 126 |
+
$w.text insert end "This paragraph is an example of the use of " margins
|
| 127 |
+
$w.text insert end "margins. It consists of a single line of text " margins
|
| 128 |
+
$w.text insert end "that wraps around on the screen. There are two " margins
|
| 129 |
+
$w.text insert end "separate left margin values, one for the first " margins
|
| 130 |
+
$w.text insert end "display line associated with the text line, " margins
|
| 131 |
+
$w.text insert end "and one for the subsequent display lines, which " margins
|
| 132 |
+
$w.text insert end "occur because of wrapping. There is also a " margins
|
| 133 |
+
$w.text insert end "separate specification for the right margin, " margins
|
| 134 |
+
$w.text insert end "which is used to choose wrap points for lines.\n" margins
|
| 135 |
+
$w.text insert end "\n10. Spacing." big
|
| 136 |
+
$w.text insert end " You can control the spacing of lines with three\n"
|
| 137 |
+
$w.text insert end "separate parameters. \"Spacing1\" tells how much "
|
| 138 |
+
$w.text insert end "extra space to leave\nabove a line, \"spacing3\" "
|
| 139 |
+
$w.text insert end "tells how much space to leave below a line,\nand "
|
| 140 |
+
$w.text insert end "if a text line wraps, \"spacing2\" tells how much "
|
| 141 |
+
$w.text insert end "space to leave\nbetween the display lines that "
|
| 142 |
+
$w.text insert end "make up the text line.\n"
|
| 143 |
+
$w.text insert end "These indented paragraphs illustrate how spacing " spacing
|
| 144 |
+
$w.text insert end "can be used. Each paragraph is actually a " spacing
|
| 145 |
+
$w.text insert end "single line in the text widget, which is " spacing
|
| 146 |
+
$w.text insert end "word-wrapped by the widget.\n" spacing
|
| 147 |
+
$w.text insert end "Spacing1 is set to 10 points for this text, " spacing
|
| 148 |
+
$w.text insert end "which results in relatively large gaps between " spacing
|
| 149 |
+
$w.text insert end "the paragraphs. Spacing2 is set to 2 points, " spacing
|
| 150 |
+
$w.text insert end "which results in just a bit of extra space " spacing
|
| 151 |
+
$w.text insert end "within a pararaph. Spacing3 isn't used " spacing
|
| 152 |
+
$w.text insert end "in this example.\n" spacing
|
| 153 |
+
$w.text insert end "To see where the space is, select ranges of " spacing
|
| 154 |
+
$w.text insert end "text within these paragraphs. The selection " spacing
|
| 155 |
+
$w.text insert end "highlight will cover the extra space." spacing
|
shared/package-files/41/41eb014e1136d816b5ede51d1b6d6558da8f46f061caea4b9cfb17b9e2dacc7c/blob
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pandas import timedelta_range
|
| 2 |
+
import pandas._testing as tm
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class TestPickle:
|
| 6 |
+
def test_pickle_after_set_freq(self):
|
| 7 |
+
tdi = timedelta_range("1 day", periods=4, freq="s")
|
| 8 |
+
tdi = tdi._with_freq(None)
|
| 9 |
+
|
| 10 |
+
res = tm.round_trip_pickle(tdi)
|
| 11 |
+
tm.assert_index_equal(res, tdi)
|
shared/package-files/41/41ec04f5a5a1b98ec51fbab9a72051194552aab6396188ab188a5740a791630b/blob
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
|
| 3 |
+
// @generated by torchgen/gen.py from NativeFunction.h
|
| 4 |
+
|
| 5 |
+
#include <c10/core/Scalar.h>
|
| 6 |
+
#include <c10/core/Storage.h>
|
| 7 |
+
#include <c10/core/TensorOptions.h>
|
| 8 |
+
#include <c10/util/Deprecated.h>
|
| 9 |
+
#include <c10/util/Optional.h>
|
| 10 |
+
#include <c10/core/QScheme.h>
|
| 11 |
+
#include <ATen/core/Reduction.h>
|
| 12 |
+
#include <ATen/core/Tensor.h>
|
| 13 |
+
#include <tuple>
|
| 14 |
+
#include <vector>
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
namespace at {
|
| 18 |
+
namespace native {
|
| 19 |
+
TORCH_API at::Tensor _embedding_bag_backward_symint(const at::Tensor & grad, const at::Tensor & indices, const at::Tensor & offsets, const at::Tensor & offset2bag, const at::Tensor & bag_size, const at::Tensor & maximum_indices, c10::SymInt num_weights, bool scale_grad_by_freq, int64_t mode, bool sparse, const c10::optional<at::Tensor> & per_sample_weights, int64_t padding_idx=-1);
|
| 20 |
+
} // namespace native
|
| 21 |
+
} // namespace at
|
shared/package-files/41/41ee0a110d3f5eca6ac054c050864febdd930ac6112750f7189cded34bf19256/blob
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pragma once
|
| 2 |
+
// @generated by torchgen/gen.py from DispatchKeyFunction.h
|
| 3 |
+
|
| 4 |
+
// NB: The implementing C++ file is RegisterDispatchKey.cpp
|
| 5 |
+
|
| 6 |
+
// The only #includes we need are for custom classes that have defaults in the C++ API
|
| 7 |
+
#include <c10/core/MemoryFormat.h>
|
| 8 |
+
#include <c10/core/Scalar.h>
|
| 9 |
+
#include <ATen/core/Reduction.h>
|
| 10 |
+
|
| 11 |
+
// Forward declarations of any types needed in the operator signatures.
|
| 12 |
+
// We can't directly include these classes because it will cause circular include dependencies.
|
| 13 |
+
// This file is included by TensorBody.h, which defines the Tensor class.
|
| 14 |
+
#include <ATen/core/ATen_fwd.h>
|
| 15 |
+
|
| 16 |
+
namespace at {
|
| 17 |
+
|
| 18 |
+
namespace compositeexplicitautograd {
|
| 19 |
+
|
| 20 |
+
TORCH_API at::Tensor empty(at::IntArrayRef size, c10::optional<at::DimnameList> names, at::TensorOptions options={}, c10::optional<at::MemoryFormat> memory_format=c10::nullopt);
|
| 21 |
+
TORCH_API at::Tensor empty(at::IntArrayRef size, c10::optional<at::DimnameList> names, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory, c10::optional<at::MemoryFormat> memory_format);
|
| 22 |
+
TORCH_API at::Tensor & empty_out(at::Tensor & out, at::IntArrayRef size, c10::optional<at::DimnameList> names, c10::optional<at::MemoryFormat> memory_format=c10::nullopt);
|
| 23 |
+
TORCH_API at::Tensor & empty_outf(at::IntArrayRef size, c10::optional<at::DimnameList> names, c10::optional<at::MemoryFormat> memory_format, at::Tensor & out);
|
| 24 |
+
|
| 25 |
+
} // namespace compositeexplicitautograd
|
| 26 |
+
} // namespace at
|
shared/package-files/41/41ee96f160ccca37ebf3ed10fa95b98e0803be54b448083ef92c6ac8cf6f6312/blob
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41ee96f160ccca37ebf3ed10fa95b98e0803be54b448083ef92c6ac8cf6f6312
|
| 3 |
+
size 1041704
|
shared/package-files/41/41f089ebe7eaba30a1d7ad9a45bf40fea356942d24fbae6b57834033470517da/blob
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
import math
|
| 4 |
+
from typing import Dict, List, Optional, Tuple, TYPE_CHECKING, Union
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from torch.distributed import is_available
|
| 9 |
+
|
| 10 |
+
from ..utils._typing_utils import not_none
|
| 11 |
+
|
| 12 |
+
__all__ = ["init_device_mesh", "DeviceMesh"]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if not is_available():
|
| 16 |
+
import sys
|
| 17 |
+
|
| 18 |
+
# We need to create the stubs when distributed is not available.
|
| 19 |
+
# Otherwise, we would fail the doc tests (```./.ci/pytorch/docs-test.sh```),
|
| 20 |
+
# since it would try to import ``torch.distributed.device_mesh`` or
|
| 21 |
+
# ``torch.distributed.init_device_mesh`` but cannot find them.
|
| 22 |
+
|
| 23 |
+
class _DeviceMeshStub:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
def _init_device_mesh_stub():
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
sys.modules["torch.distributed.device_mesh"].DeviceMesh = _DeviceMeshStub # type: ignore[attr-defined]
|
| 30 |
+
sys.modules[
|
| 31 |
+
"torch.distributed.device_mesh"
|
| 32 |
+
].init_device_mesh = _init_device_mesh_stub # type: ignore[attr-defined]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
else:
|
| 36 |
+
from torch.distributed.distributed_c10d import (
|
| 37 |
+
_find_pg_by_ranks_and_tag,
|
| 38 |
+
_get_default_group,
|
| 39 |
+
_get_group_tag,
|
| 40 |
+
get_rank,
|
| 41 |
+
get_world_size,
|
| 42 |
+
init_process_group,
|
| 43 |
+
is_initialized,
|
| 44 |
+
new_group,
|
| 45 |
+
ProcessGroup,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
logger = logging.getLogger(__name__)
|
| 49 |
+
|
| 50 |
+
# only import numpy typing when type checking
|
| 51 |
+
if TYPE_CHECKING:
|
| 52 |
+
try:
|
| 53 |
+
from numpy.typing import ArrayLike
|
| 54 |
+
except ImportError:
|
| 55 |
+
logger.warning(
|
| 56 |
+
"DeviceMesh requires numpy >= 1.21 to be installed for type checking"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
class _MeshEnv:
|
| 60 |
+
def __init__(self) -> None:
|
| 61 |
+
self.mesh_stack: List[DeviceMesh] = []
|
| 62 |
+
self.child_to_parent_mapping: Dict[DeviceMesh, DeviceMesh] = {}
|
| 63 |
+
self.parent_to_child_mapping: Dict[DeviceMesh, Dict[str, DeviceMesh]] = {}
|
| 64 |
+
|
| 65 |
+
def get_current_mesh(self) -> "DeviceMesh":
|
| 66 |
+
if len(self.mesh_stack) == 0:
|
| 67 |
+
raise RuntimeError("No device mesh is currently active!")
|
| 68 |
+
return self.mesh_stack[-1]
|
| 69 |
+
|
| 70 |
+
def create_child_mesh(
|
| 71 |
+
self, device_mesh: "DeviceMesh", mesh_dim: int, mesh_dim_name: str
|
| 72 |
+
) -> "DeviceMesh":
|
| 73 |
+
# Directly return the child mesh if it is already created.
|
| 74 |
+
child_mesh_mappings = self.parent_to_child_mapping.get(device_mesh)
|
| 75 |
+
if child_mesh_mappings:
|
| 76 |
+
sub_mesh = child_mesh_mappings.get(mesh_dim_name)
|
| 77 |
+
if sub_mesh:
|
| 78 |
+
return sub_mesh
|
| 79 |
+
|
| 80 |
+
# swap the current dim to the last dim then reshape to flatten out other
|
| 81 |
+
# dims, so we can just extract the list of ranks which contains cur_rank.
|
| 82 |
+
cur_rank = device_mesh.get_rank()
|
| 83 |
+
pg_ranks_by_dim = device_mesh.mesh.swapdims(-1, mesh_dim).reshape(
|
| 84 |
+
-1, device_mesh.mesh.size(mesh_dim)
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
for mesh_1d in pg_ranks_by_dim:
|
| 88 |
+
sub_mesh = DeviceMesh(
|
| 89 |
+
device_mesh.device_type,
|
| 90 |
+
mesh_1d,
|
| 91 |
+
mesh_dim_names=(mesh_dim_name,),
|
| 92 |
+
)
|
| 93 |
+
if cur_rank in mesh_1d:
|
| 94 |
+
res_sub_mesh = sub_mesh
|
| 95 |
+
|
| 96 |
+
res_sub_mesh._dim_group_infos = [device_mesh._dim_group_infos[mesh_dim]] # type: ignore[possibly-undefined]
|
| 97 |
+
# Assign the current DeviceMesh as the parent of the child DeviceMesh.
|
| 98 |
+
self.child_to_parent_mapping[res_sub_mesh] = device_mesh
|
| 99 |
+
self.parent_to_child_mapping.setdefault(device_mesh, {})[
|
| 100 |
+
mesh_dim_name
|
| 101 |
+
] = res_sub_mesh
|
| 102 |
+
return res_sub_mesh
|
| 103 |
+
|
| 104 |
+
def get_parent_mesh(self, device_mesh: "DeviceMesh") -> Optional["DeviceMesh"]:
|
| 105 |
+
return self.child_to_parent_mapping.get(device_mesh, None)
|
| 106 |
+
|
| 107 |
+
def get_parent_mesh_dim(self, device_mesh: "DeviceMesh") -> Optional[int]:
|
| 108 |
+
"""
|
| 109 |
+
Return the index of the mesh dim in the parent mesh.
|
| 110 |
+
The device_mesh passed in needs to be sliced out from a parent mesh.
|
| 111 |
+
"""
|
| 112 |
+
parent_mesh = self.get_parent_mesh(device_mesh)
|
| 113 |
+
child_mesh_dim_names = device_mesh.mesh_dim_names
|
| 114 |
+
if parent_mesh and child_mesh_dim_names:
|
| 115 |
+
assert (
|
| 116 |
+
len(child_mesh_dim_names) == 1
|
| 117 |
+
), "The child mesh can only be a 1D mesh."
|
| 118 |
+
child_mesh_dim_name = child_mesh_dim_names[0]
|
| 119 |
+
return self.get_mesh_dim_by_name(parent_mesh, child_mesh_dim_name)
|
| 120 |
+
return None
|
| 121 |
+
|
| 122 |
+
@staticmethod
|
| 123 |
+
def num_devices_per_host(device_type: str) -> int:
|
| 124 |
+
return _get_device_handle(device_type).device_count()
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def num_hosts(device_type: str) -> int:
|
| 128 |
+
# ProcessGroup can't tell us this info so we have to infer it, assume
|
| 129 |
+
# homogeneous hardware for now
|
| 130 |
+
return get_world_size() // _MeshEnv.num_devices_per_host(device_type)
|
| 131 |
+
|
| 132 |
+
def get_mesh_dim_by_name(
|
| 133 |
+
self, device_mesh: "DeviceMesh", mesh_dim_name: str
|
| 134 |
+
) -> int:
|
| 135 |
+
if (
|
| 136 |
+
device_mesh.mesh_dim_names is None
|
| 137 |
+
or len(device_mesh.mesh_dim_names) == 0
|
| 138 |
+
):
|
| 139 |
+
raise KeyError(
|
| 140 |
+
"No `mesh_dim_names` found.",
|
| 141 |
+
)
|
| 142 |
+
if mesh_dim_name not in device_mesh.mesh_dim_names:
|
| 143 |
+
raise KeyError(
|
| 144 |
+
f"Mesh dimension '{mesh_dim_name}' does not exist.",
|
| 145 |
+
f"Available mesh dimensions are: mesh_dim_names={device_mesh.mesh_dim_names}",
|
| 146 |
+
)
|
| 147 |
+
return not_none(device_mesh.mesh_dim_names.index(mesh_dim_name))
|
| 148 |
+
|
| 149 |
+
_mesh_resources: _MeshEnv = _MeshEnv()
|
| 150 |
+
|
| 151 |
+
def _get_device_handle(device_type: str = "cuda"):
|
| 152 |
+
"""
|
| 153 |
+
Get the module corresponding to the device_type which is cuda or cuda-like device.
|
| 154 |
+
For example, when the device_type is cuda, the module `torch.cuda` is returned.
|
| 155 |
+
Return None when there is no corresponding module for device_type, otherwise
|
| 156 |
+
return the corresponding module.
|
| 157 |
+
"""
|
| 158 |
+
return getattr(torch, device_type, None)
|
| 159 |
+
|
| 160 |
+
class DeviceMesh:
|
| 161 |
+
"""
|
| 162 |
+
DeviceMesh represents a mesh of devices, where layout of devices could be
|
| 163 |
+
represented as a n-d dimension array, and each value of the n-d dimensional
|
| 164 |
+
array is the global id of the default process group ranks.
|
| 165 |
+
|
| 166 |
+
DeviceMesh could be used to describe the layout of devices across the cluster,
|
| 167 |
+
and serves as a proxy for communication among the device lists within the cluster.
|
| 168 |
+
|
| 169 |
+
DeviceMesh can be used as a context manager.
|
| 170 |
+
|
| 171 |
+
.. note::
|
| 172 |
+
DeviceMesh follows SPMD programming model, which means the same PyTorch Python program
|
| 173 |
+
is running on all processes/ranks in the cluster. Therefore, users need to make sure the
|
| 174 |
+
`mesh` array (which describes the layout of devices) should be identical across all ranks.
|
| 175 |
+
Inconsistent `mesh` will lead to silent hang.
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
device_type (str): The device type of the mesh. Currently supports: "cpu", "cuda/cuda-like".
|
| 179 |
+
mesh (ndarray): A multi-dimensional array or an integer tensor describing the layout
|
| 180 |
+
of devices, where the IDs are global IDs of the default process group.
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
DeviceMesh: A :class:`DeviceMesh` object representing the device layout.
|
| 184 |
+
|
| 185 |
+
The following program runs on each process/rank in an SPMD manner. In this example, we have 2
|
| 186 |
+
hosts with 4 GPUs each.
|
| 187 |
+
A reduction over the first dimension of mesh will reduce across
|
| 188 |
+
columns (0, 4), .. and (3, 7), a reduction over the second dimension
|
| 189 |
+
of mesh reduces across rows (0, 1, 2, 3) and (4, 5, 6, 7).
|
| 190 |
+
|
| 191 |
+
Example::
|
| 192 |
+
>>> # xdoctest: +SKIP("no rank")
|
| 193 |
+
>>> from torch.distributed.device_mesh import DeviceMesh
|
| 194 |
+
>>>
|
| 195 |
+
>>> # Initialize device mesh as (2, 4) to represent the topology
|
| 196 |
+
>>> # of cross-host(dim 0), and within-host (dim 1).
|
| 197 |
+
>>> mesh = DeviceMesh(device_type="cuda", mesh=[[0, 1, 2, 3],[4, 5, 6, 7]])
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
device_type: str
|
| 201 |
+
mesh: torch.Tensor
|
| 202 |
+
mesh_dim_names: Optional[Tuple[str, ...]]
|
| 203 |
+
|
| 204 |
+
def __init__(
|
| 205 |
+
self,
|
| 206 |
+
device_type: str,
|
| 207 |
+
mesh: Union[torch.Tensor, "ArrayLike"],
|
| 208 |
+
*,
|
| 209 |
+
mesh_dim_names: Optional[Tuple[str, ...]] = None,
|
| 210 |
+
) -> None:
|
| 211 |
+
self.device_type = device_type
|
| 212 |
+
if isinstance(mesh, torch.Tensor) and mesh.device.type != "cpu":
|
| 213 |
+
raise ValueError(f"`mesh` must be a CPU tensor, got {mesh}")
|
| 214 |
+
self.mesh = (
|
| 215 |
+
mesh.detach().cpu()
|
| 216 |
+
if isinstance(mesh, torch.Tensor)
|
| 217 |
+
else torch.tensor(mesh, dtype=torch.int)
|
| 218 |
+
)
|
| 219 |
+
self.mesh_dim_names = mesh_dim_names
|
| 220 |
+
|
| 221 |
+
# private field to pre-generate DeviceMesh's hash
|
| 222 |
+
self._flatten_mesh_list = tuple(self.mesh.flatten().tolist())
|
| 223 |
+
self._hash = hash((self._flatten_mesh_list, self.mesh.shape, id(self)))
|
| 224 |
+
|
| 225 |
+
# Skip process group initialization if xla device.
|
| 226 |
+
# TODO(yeounoh) implement DeviceMesh backend and register XLA backend.
|
| 227 |
+
if device_type != "xla":
|
| 228 |
+
# always try to create default (world) pg, even if it is not initialized
|
| 229 |
+
# already. The world pg is used for device mesh identity (rank) on each
|
| 230 |
+
# process (we need to know if the current global rank is in the mesh or not).
|
| 231 |
+
self._get_or_create_default_group()
|
| 232 |
+
self._init_process_groups()
|
| 233 |
+
|
| 234 |
+
def _get_or_create_default_group(self):
|
| 235 |
+
default_initialized = is_initialized()
|
| 236 |
+
if not default_initialized:
|
| 237 |
+
init_process_group()
|
| 238 |
+
|
| 239 |
+
world_size = get_world_size()
|
| 240 |
+
if self.mesh.numel() > world_size:
|
| 241 |
+
raise RuntimeError(
|
| 242 |
+
f"Mesh should not be bigger than default world size, but found {self.mesh.numel()} ranks!"
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
device_handle = _get_device_handle(self.device_type)
|
| 246 |
+
# TODO: if user want to pass pg_options, offer a way to do it
|
| 247 |
+
if not default_initialized and device_handle:
|
| 248 |
+
# automatically set the current cuda/cuda-like device base on num of gpu devices available in each host
|
| 249 |
+
# NOTE: This device selection would only work for homogeneous hardware.
|
| 250 |
+
num_devices_per_host = device_handle.device_count()
|
| 251 |
+
if (
|
| 252 |
+
world_size > num_devices_per_host
|
| 253 |
+
and world_size % num_devices_per_host != 0
|
| 254 |
+
):
|
| 255 |
+
raise RuntimeError(
|
| 256 |
+
f"DeviceMesh only support homogeneous hardware, but found "
|
| 257 |
+
f"{world_size} ranks and {num_devices_per_host} {self.device_type} devices!"
|
| 258 |
+
)
|
| 259 |
+
device_handle.set_device(get_rank() % num_devices_per_host)
|
| 260 |
+
|
| 261 |
+
# calculate the coordinates of the current global rank on the mesh
|
| 262 |
+
rank_coords = (self.mesh == get_rank()).nonzero()
|
| 263 |
+
assert rank_coords.size(0) in (0, 1)
|
| 264 |
+
self._coordinate_on_dim: Optional[List[int]] = (
|
| 265 |
+
rank_coords[0].tolist() if rank_coords.size(0) > 0 else None
|
| 266 |
+
)
|
| 267 |
+
return _get_default_group()
|
| 268 |
+
|
| 269 |
+
def _init_process_groups(self):
|
| 270 |
+
# tag/ranks/group_name associated with each mesh dimension, each
|
| 271 |
+
# mesh dimension should have one sub-group per rank
|
| 272 |
+
#
|
| 273 |
+
# TODO(yifu): remove tag and ranks once we fully migrate to native
|
| 274 |
+
# functional collectives. See details in:
|
| 275 |
+
# https://github.com/pytorch/pytorch/issues/93173#issuecomment-1907095208
|
| 276 |
+
dim_group_infos: List[Tuple[str, List[int], str]] = []
|
| 277 |
+
|
| 278 |
+
if self.mesh.ndim == 1 and self.mesh.numel() == get_world_size():
|
| 279 |
+
# if the mesh is the same as world_pg, we just append the default
|
| 280 |
+
# pg to the first dim groups, as new_group cannot have the exact
|
| 281 |
+
# same ranks as world
|
| 282 |
+
dim_group_infos.append(
|
| 283 |
+
(
|
| 284 |
+
_get_group_tag(_get_default_group()),
|
| 285 |
+
list(range(get_world_size())),
|
| 286 |
+
_get_default_group().group_name,
|
| 287 |
+
)
|
| 288 |
+
)
|
| 289 |
+
else:
|
| 290 |
+
# create sub pgs base on the mesh argument specified
|
| 291 |
+
for dim in range(self.mesh.ndim):
|
| 292 |
+
# swap the current dim to the last dim
|
| 293 |
+
# then reshape to flatten out other dims
|
| 294 |
+
pg_ranks_by_dim = self.mesh.swapdims(-1, dim).reshape(
|
| 295 |
+
-1, self.mesh.size(dim)
|
| 296 |
+
)
|
| 297 |
+
# multi-dim mesh, create subgroups by looping over the pg_ranks
|
| 298 |
+
# for each dim and append the groups
|
| 299 |
+
for dim_mesh in pg_ranks_by_dim:
|
| 300 |
+
subgroup_ranks = dim_mesh.tolist()
|
| 301 |
+
|
| 302 |
+
# We temporarily revert the re-use subgroup, since it breaks two internal tests.
|
| 303 |
+
# Temporarily reverting to resolve test timeout while root-causing.
|
| 304 |
+
# TODO: Add two tests to cover internal tests scenarios and re-enable reuse subgroup if exists.
|
| 305 |
+
dim_group = new_group(ranks=subgroup_ranks)
|
| 306 |
+
|
| 307 |
+
# only add to dim_groups if the current rank in the subgroup
|
| 308 |
+
if self.get_rank() in subgroup_ranks:
|
| 309 |
+
if len(dim_group_infos) > dim:
|
| 310 |
+
raise RuntimeError(
|
| 311 |
+
f"Each device mesh dimension should get only one process group, but got {self.get_rank} "
|
| 312 |
+
f"in {subgroup_ranks}!"
|
| 313 |
+
)
|
| 314 |
+
dim_group_infos.append(
|
| 315 |
+
(
|
| 316 |
+
_get_group_tag(not_none(dim_group)),
|
| 317 |
+
subgroup_ranks,
|
| 318 |
+
dim_group.group_name,
|
| 319 |
+
)
|
| 320 |
+
)
|
| 321 |
+
self._dim_group_infos = dim_group_infos
|
| 322 |
+
|
| 323 |
+
def __enter__(self) -> "DeviceMesh":
|
| 324 |
+
# set this mesh as the current mesh in mesh env
|
| 325 |
+
_mesh_resources.mesh_stack.append(self)
|
| 326 |
+
return self
|
| 327 |
+
|
| 328 |
+
# pyre-fixme[2]: Parameter must be annotated.
|
| 329 |
+
def __exit__(self, exc_type, exc_value, exc_traceback) -> None:
|
| 330 |
+
# pop this mesh from mesh env
|
| 331 |
+
_mesh_resources.mesh_stack.pop()
|
| 332 |
+
|
| 333 |
+
def __repr__(self) -> str:
|
| 334 |
+
device_mesh_repr = (
|
| 335 |
+
f"DeviceMesh({self.mesh.tolist()})"
|
| 336 |
+
if not self.mesh_dim_names
|
| 337 |
+
else f"DeviceMesh({self.mesh.tolist()}, mesh_dim_names={self.mesh_dim_names})"
|
| 338 |
+
)
|
| 339 |
+
return device_mesh_repr
|
| 340 |
+
|
| 341 |
+
def __hash__(self):
|
| 342 |
+
return self._hash
|
| 343 |
+
|
| 344 |
+
def __eq__(self, other: object) -> bool:
|
| 345 |
+
if not isinstance(other, DeviceMesh):
|
| 346 |
+
return False
|
| 347 |
+
if id(self.mesh) == id(other.mesh):
|
| 348 |
+
return True
|
| 349 |
+
return (
|
| 350 |
+
self.mesh.shape == other.mesh.shape
|
| 351 |
+
and self._flatten_mesh_list == other._flatten_mesh_list
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
def __getitem__(self, mesh_dim_name: str) -> "DeviceMesh":
|
| 355 |
+
"""
|
| 356 |
+
Slice the current DeviceMesh based on the mesh_dim_name given to create a child
|
| 357 |
+
DeviceMesh.
|
| 358 |
+
|
| 359 |
+
Args:
|
| 360 |
+
mesh_dim_name (str): the name of the mesh dimension of the parent DeviceMesh
|
| 361 |
+
to create a child DeviceMesh for.
|
| 362 |
+
Returns:
|
| 363 |
+
A :class:`DeviceMesh` object
|
| 364 |
+
|
| 365 |
+
The following program runs on each process/rank in an SPMD manner. In this example, we have 2
|
| 366 |
+
hosts with 4 GPUs each.
|
| 367 |
+
Calling mesh["tp"] on rank 0, 1, 2, 3 would return a 1D child DeviceMesh:([0, 1, 2, 3]).
|
| 368 |
+
Calling mesh["tp"] on rank 4, 5, 6, 7 would return a 1D child DeviceMesh:([4, 5, 6, 7]).
|
| 369 |
+
Calling mesh["dp"] on rank 0, 4 would return a 1D child DeviceMesh:([0, 4]).
|
| 370 |
+
Calling mesh["dp"] on rank 1, 5 would return a 1D child DeviceMesh:([1, 5]).
|
| 371 |
+
Calling mesh["dp"] on rank 2, 6 would return a 1D child DeviceMesh:([2, 6]).
|
| 372 |
+
Calling mesh["dp"] on rank 3, 7 would return a 1D child DeviceMesh:([3, 7]).
|
| 373 |
+
|
| 374 |
+
Example::
|
| 375 |
+
>>> # xdoctest: +SKIP("no rank")
|
| 376 |
+
>>> from torch.distributed.device_mesh import DeviceMesh
|
| 377 |
+
>>>
|
| 378 |
+
>>> # Initialize device mesh as (2, 4) to represent the topology
|
| 379 |
+
>>> # of cross-host(dim 0), and within-host (dim 1).
|
| 380 |
+
>>> mesh = DeviceMesh(device_type="cuda", mesh=[[0, 1, 2, 3],[4, 5, 6, 7]])
|
| 381 |
+
"""
|
| 382 |
+
if self.mesh.ndim == 1:
|
| 383 |
+
if self.mesh_dim_names and mesh_dim_name == self.mesh_dim_names[0]:
|
| 384 |
+
return self
|
| 385 |
+
else:
|
| 386 |
+
raise RuntimeError(
|
| 387 |
+
f"Invalid mesh_dim_name {mesh_dim_name} specified."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
mesh_dim = _mesh_resources.get_mesh_dim_by_name(self, mesh_dim_name)
|
| 391 |
+
submesh = _mesh_resources.create_child_mesh(self, mesh_dim, mesh_dim_name)
|
| 392 |
+
return submesh
|
| 393 |
+
|
| 394 |
+
def get_group(
|
| 395 |
+
self, mesh_dim: Optional[Union[int, str]] = None
|
| 396 |
+
) -> Union[ProcessGroup, List[ProcessGroup]]:
|
| 397 |
+
"""
|
| 398 |
+
Returns a list of ProcessGroups corresponding to the mesh dimensions, or
|
| 399 |
+
returns a single ProcessGroup if mesh_dim is specified or the given mesh has
|
| 400 |
+
only one mesh dimension.
|
| 401 |
+
|
| 402 |
+
Args:
|
| 403 |
+
mesh_dim (str/int, optional): it can be the name of the mesh dimension or the index
|
| 404 |
+
of the mesh dimension. Default is None.
|
| 405 |
+
|
| 406 |
+
Returns:
|
| 407 |
+
A list of :class:`ProcessGroup` object when `mesh_dim` is not specified for
|
| 408 |
+
a DeviceMesh with more than 1 dimension; otherwise, returns a single
|
| 409 |
+
:class:`ProcessGroup` object.
|
| 410 |
+
"""
|
| 411 |
+
if not hasattr(self, "_dim_group_infos"):
|
| 412 |
+
raise RuntimeError("DeviceMesh process groups not initialized!")
|
| 413 |
+
|
| 414 |
+
if self.mesh.ndim == 1:
|
| 415 |
+
return not_none(
|
| 416 |
+
_find_pg_by_ranks_and_tag(*self._dim_group_infos[0][:2])
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
if mesh_dim is not None:
|
| 420 |
+
if isinstance(mesh_dim, str):
|
| 421 |
+
mesh_dim = _mesh_resources.get_mesh_dim_by_name(self, mesh_dim)
|
| 422 |
+
return not_none(
|
| 423 |
+
_find_pg_by_ranks_and_tag(*self._dim_group_infos[mesh_dim][:2])
|
| 424 |
+
)
|
| 425 |
+
else:
|
| 426 |
+
dim_groups = []
|
| 427 |
+
for ith_dim in range(self.mesh.ndim):
|
| 428 |
+
dim_groups.append(
|
| 429 |
+
not_none(
|
| 430 |
+
_find_pg_by_ranks_and_tag(
|
| 431 |
+
*self._dim_group_infos[ith_dim][:2]
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
)
|
| 435 |
+
return dim_groups
|
| 436 |
+
|
| 437 |
+
def size(self, mesh_dim: Optional[int] = None) -> int:
|
| 438 |
+
return self.mesh.numel() if mesh_dim is None else self.mesh.size(mesh_dim)
|
| 439 |
+
|
| 440 |
+
@property
|
| 441 |
+
def ndim(self) -> int:
|
| 442 |
+
return self.mesh.ndim
|
| 443 |
+
|
| 444 |
+
@property
|
| 445 |
+
def shape(self) -> Tuple[int, ...]:
|
| 446 |
+
return tuple(self.mesh.shape)
|
| 447 |
+
|
| 448 |
+
def get_rank(self) -> int:
|
| 449 |
+
"""
|
| 450 |
+
Returns the current global rank.
|
| 451 |
+
"""
|
| 452 |
+
return get_rank()
|
| 453 |
+
|
| 454 |
+
def get_local_rank(self, mesh_dim: Optional[Union[int, str]] = None) -> int:
|
| 455 |
+
"""
|
| 456 |
+
Returns the local rank of the given mesh_dim of the DeviceMesh.
|
| 457 |
+
|
| 458 |
+
Args:
|
| 459 |
+
mesh_dim (str/int, optional): it can be the name of the mesh dimension or the index
|
| 460 |
+
of the mesh dimension. Default is None.
|
| 461 |
+
|
| 462 |
+
Returns:
|
| 463 |
+
An integer denotes the local rank.
|
| 464 |
+
|
| 465 |
+
The following program runs on each process/rank in an SPMD manner. In this example, we have 2
|
| 466 |
+
hosts with 4 GPUs each.
|
| 467 |
+
Calling mesh_2d.get_local_rank(mesh_dim=0) on rank 0, 1, 2, 3 would return 0.
|
| 468 |
+
Calling mesh_2d.get_local_rank(mesh_dim=0) on rank 4, 5, 6, 7 would return 1.
|
| 469 |
+
Calling mesh_2d.get_local_rank(mesh_dim=1) on rank 0, 4 would return 0.
|
| 470 |
+
Calling mesh_2d.get_local_rank(mesh_dim=1) on rank 1, 5 would return 1.
|
| 471 |
+
Calling mesh_2d.get_local_rank(mesh_dim=1) on rank 2, 6 would return 2.
|
| 472 |
+
Calling mesh_2d.get_local_rank(mesh_dim=1) on rank 3, 7 would return 3.
|
| 473 |
+
|
| 474 |
+
Example::
|
| 475 |
+
>>> # xdoctest: +SKIP("no rank")
|
| 476 |
+
>>> from torch.distributed.device_mesh import DeviceMesh
|
| 477 |
+
>>>
|
| 478 |
+
>>> # Initialize device mesh as (2, 4) to represent the topology
|
| 479 |
+
>>> # of cross-host(dim 0), and within-host (dim 1).
|
| 480 |
+
>>> mesh = DeviceMesh(device_type="cuda", mesh=[[0, 1, 2, 3],[4, 5, 6, 7]])
|
| 481 |
+
"""
|
| 482 |
+
if self.ndim > 1 and mesh_dim is None:
|
| 483 |
+
raise RuntimeError(
|
| 484 |
+
f"Found the DeviceMesh have {self.mesh.ndim} dimensions",
|
| 485 |
+
"Optional kwarg `mesh_dim` needs to be specified when device_mesh.ndim > 1.",
|
| 486 |
+
)
|
| 487 |
+
elif mesh_dim is None:
|
| 488 |
+
mesh_dim = 0
|
| 489 |
+
|
| 490 |
+
mesh_dim_group = not_none(self.get_group(mesh_dim))
|
| 491 |
+
assert isinstance(
|
| 492 |
+
mesh_dim_group, ProcessGroup
|
| 493 |
+
), "We expect ProcessGroup before calling `get_rank`!"
|
| 494 |
+
return not_none(get_rank(mesh_dim_group))
|
| 495 |
+
|
| 496 |
+
def get_coordinate(self) -> Optional[List[int]]:
|
| 497 |
+
"""
|
| 498 |
+
Return the relative indices of this rank relative to all
|
| 499 |
+
dimensions of the mesh. If this rank is not part of the mesh, return None.
|
| 500 |
+
"""
|
| 501 |
+
return self._coordinate_on_dim if self._coordinate_on_dim else None
|
| 502 |
+
|
| 503 |
+
def init_device_mesh(
|
| 504 |
+
device_type: str,
|
| 505 |
+
mesh_shape: Tuple[int, ...],
|
| 506 |
+
*,
|
| 507 |
+
mesh_dim_names: Optional[Tuple[str, ...]] = None,
|
| 508 |
+
) -> DeviceMesh:
|
| 509 |
+
"""
|
| 510 |
+
Initializes a `DeviceMesh` based on `device_type`, `mesh_shape`, and `mesh_dim_names` parameters.
|
| 511 |
+
|
| 512 |
+
This creates a DeviceMesh with an n-dimensional array layout, where `n` is the length of `mesh_shape`.
|
| 513 |
+
If `mesh_dim_names` is provided, each dimension is labeled as `mesh_dim_names[i]`.
|
| 514 |
+
|
| 515 |
+
.. note::
|
| 516 |
+
`init_device_mesh` follows SPMD programming model, meaning the same PyTorch Python program
|
| 517 |
+
runs on all processes/ranks in the cluster. Ensure `mesh_shape` (the dimensions of the nD array
|
| 518 |
+
describing device layout) is identical across all ranks. Inconsistent `mesh_shape` may lead to hanging.
|
| 519 |
+
|
| 520 |
+
.. note::
|
| 521 |
+
If no process group is found, init_device_mesh will initialize distributed process group/groups
|
| 522 |
+
required for distributed communications behind the scene.
|
| 523 |
+
|
| 524 |
+
Args:
|
| 525 |
+
device_type (str): The device type of the mesh. Currently supports: "cpu", "cuda/cuda-like".
|
| 526 |
+
mesh_shape (Tuple[int]): A tuple defining the dimensions of the multi-dimensional array
|
| 527 |
+
describing the layout of devices.
|
| 528 |
+
mesh_dim_names (Tuple[str], optional): A tuple of mesh dimension names to assign to each dimension
|
| 529 |
+
of the multi-dimensional array describing the layout of devices. Its length must match the length
|
| 530 |
+
of `mesh_shape`. Each string in `mesh_dim_names` must be unique.
|
| 531 |
+
|
| 532 |
+
Returns:
|
| 533 |
+
DeviceMesh: A :class:`DeviceMesh` object representing the device layout.
|
| 534 |
+
|
| 535 |
+
Example::
|
| 536 |
+
>>> # xdoctest: +SKIP("no rank")
|
| 537 |
+
>>> from torch.distributed.device_mesh import init_device_mesh
|
| 538 |
+
>>>
|
| 539 |
+
>>> mesh_1d = init_device_mesh("cuda", mesh_shape=(8,))
|
| 540 |
+
>>> mesh_2d = init_device_mesh("cuda", mesh_shape=(2, 8), mesh_dim_names=("dp", "tp"))
|
| 541 |
+
|
| 542 |
+
"""
|
| 543 |
+
if mesh_dim_names is not None:
|
| 544 |
+
if len(set(mesh_dim_names)) != len(mesh_dim_names):
|
| 545 |
+
raise RuntimeError(
|
| 546 |
+
"Each mesh_dim_name must be unique.",
|
| 547 |
+
f"Found repeated mesh_dim_name in mesh_dim_names {mesh_dim_names}",
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
if len(mesh_shape) != len(mesh_dim_names):
|
| 551 |
+
raise RuntimeError(
|
| 552 |
+
"mesh_shape and mesh_dim_names should have same length!",
|
| 553 |
+
f"Found len(mesh_dim_names): {len(mesh_dim_names)} and len(mesh_shape):{len(mesh_shape)}.",
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
mesh = torch.arange(math.prod(mesh_shape)).view(mesh_shape)
|
| 557 |
+
device_mesh = DeviceMesh(
|
| 558 |
+
device_type=device_type,
|
| 559 |
+
mesh=mesh,
|
| 560 |
+
mesh_dim_names=mesh_dim_names,
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
return device_mesh
|
shared/package-files/41/41f0e2a823a0cd2c8273e38146fd1ddfcdccc8b5b5c4a4575ef365256681017a/blob
ADDED
|
Binary file (1.21 kB). View file
|
|
|
shared/package-files/41/41f62f4991e9fa89ec25bc78a82a65e4f6773e67ba8b900be61d360035c38188/blob
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 bartlett_window {
|
| 18 |
+
using schema = at::Tensor (int64_t, 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::bartlett_window")
|
| 22 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
|
| 23 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bartlett_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor")
|
| 24 |
+
static at::Tensor call(int64_t window_length, 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, int64_t window_length, 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 bartlett_window_periodic {
|
| 29 |
+
using schema = at::Tensor (int64_t, bool, 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::bartlett_window")
|
| 33 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "periodic")
|
| 34 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bartlett_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor")
|
| 35 |
+
static at::Tensor call(int64_t window_length, bool periodic, 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, int64_t window_length, bool periodic, c10::optional<at::ScalarType> dtype, c10::optional<at::Layout> layout, c10::optional<at::Device> device, c10::optional<bool> pin_memory);
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
struct TORCH_API bartlett_window_out {
|
| 40 |
+
using schema = at::Tensor & (int64_t, at::Tensor &);
|
| 41 |
+
using ptr_schema = schema*;
|
| 42 |
+
// See Note [static constexpr char* members for windows NVCC]
|
| 43 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bartlett_window")
|
| 44 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
|
| 45 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bartlett_window.out(int window_length, *, Tensor(a!) out) -> Tensor(a!)")
|
| 46 |
+
static at::Tensor & call(int64_t window_length, at::Tensor & out);
|
| 47 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, int64_t window_length, at::Tensor & out);
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
struct TORCH_API bartlett_window_periodic_out {
|
| 51 |
+
using schema = at::Tensor & (int64_t, bool, 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::bartlett_window")
|
| 55 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "periodic_out")
|
| 56 |
+
STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bartlett_window.periodic_out(int window_length, bool periodic, *, Tensor(a!) out) -> Tensor(a!)")
|
| 57 |
+
static at::Tensor & call(int64_t window_length, bool periodic, at::Tensor & out);
|
| 58 |
+
static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, int64_t window_length, bool periodic, at::Tensor & out);
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
}} // namespace at::_ops
|
shared/package-files/41/41f694531f93d0588a0490416f76c3965b7c3bc79313b3298a0abbc2f0dea517/blob
ADDED
|
@@ -0,0 +1,955 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Access and control log capturing."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
from contextlib import nullcontext
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from datetime import timedelta
|
| 10 |
+
from datetime import timezone
|
| 11 |
+
import io
|
| 12 |
+
from io import StringIO
|
| 13 |
+
import logging
|
| 14 |
+
from logging import LogRecord
|
| 15 |
+
import os
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
import re
|
| 18 |
+
from types import TracebackType
|
| 19 |
+
from typing import AbstractSet
|
| 20 |
+
from typing import Dict
|
| 21 |
+
from typing import final
|
| 22 |
+
from typing import Generator
|
| 23 |
+
from typing import Generic
|
| 24 |
+
from typing import List
|
| 25 |
+
from typing import Literal
|
| 26 |
+
from typing import Mapping
|
| 27 |
+
from typing import TYPE_CHECKING
|
| 28 |
+
from typing import TypeVar
|
| 29 |
+
|
| 30 |
+
from _pytest import nodes
|
| 31 |
+
from _pytest._io import TerminalWriter
|
| 32 |
+
from _pytest.capture import CaptureManager
|
| 33 |
+
from _pytest.config import _strtobool
|
| 34 |
+
from _pytest.config import Config
|
| 35 |
+
from _pytest.config import create_terminal_writer
|
| 36 |
+
from _pytest.config import hookimpl
|
| 37 |
+
from _pytest.config import UsageError
|
| 38 |
+
from _pytest.config.argparsing import Parser
|
| 39 |
+
from _pytest.deprecated import check_ispytest
|
| 40 |
+
from _pytest.fixtures import fixture
|
| 41 |
+
from _pytest.fixtures import FixtureRequest
|
| 42 |
+
from _pytest.main import Session
|
| 43 |
+
from _pytest.stash import StashKey
|
| 44 |
+
from _pytest.terminal import TerminalReporter
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if TYPE_CHECKING:
|
| 48 |
+
logging_StreamHandler = logging.StreamHandler[StringIO]
|
| 49 |
+
else:
|
| 50 |
+
logging_StreamHandler = logging.StreamHandler
|
| 51 |
+
|
| 52 |
+
DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
|
| 53 |
+
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
|
| 54 |
+
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
|
| 55 |
+
caplog_handler_key = StashKey["LogCaptureHandler"]()
|
| 56 |
+
caplog_records_key = StashKey[Dict[str, List[logging.LogRecord]]]()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _remove_ansi_escape_sequences(text: str) -> str:
|
| 60 |
+
return _ANSI_ESCAPE_SEQ.sub("", text)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class DatetimeFormatter(logging.Formatter):
|
| 64 |
+
"""A logging formatter which formats record with
|
| 65 |
+
:func:`datetime.datetime.strftime` formatter instead of
|
| 66 |
+
:func:`time.strftime` in case of microseconds in format string.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str:
|
| 70 |
+
if datefmt and "%f" in datefmt:
|
| 71 |
+
ct = self.converter(record.created)
|
| 72 |
+
tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone)
|
| 73 |
+
# Construct `datetime.datetime` object from `struct_time`
|
| 74 |
+
# and msecs information from `record`
|
| 75 |
+
# Using int() instead of round() to avoid it exceeding 1_000_000 and causing a ValueError (#11861).
|
| 76 |
+
dt = datetime(*ct[0:6], microsecond=int(record.msecs * 1000), tzinfo=tz)
|
| 77 |
+
return dt.strftime(datefmt)
|
| 78 |
+
# Use `logging.Formatter` for non-microsecond formats
|
| 79 |
+
return super().formatTime(record, datefmt)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class ColoredLevelFormatter(DatetimeFormatter):
|
| 83 |
+
"""A logging formatter which colorizes the %(levelname)..s part of the
|
| 84 |
+
log format passed to __init__."""
|
| 85 |
+
|
| 86 |
+
LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = {
|
| 87 |
+
logging.CRITICAL: {"red"},
|
| 88 |
+
logging.ERROR: {"red", "bold"},
|
| 89 |
+
logging.WARNING: {"yellow"},
|
| 90 |
+
logging.WARN: {"yellow"},
|
| 91 |
+
logging.INFO: {"green"},
|
| 92 |
+
logging.DEBUG: {"purple"},
|
| 93 |
+
logging.NOTSET: set(),
|
| 94 |
+
}
|
| 95 |
+
LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*(?:\.\d+)?s)")
|
| 96 |
+
|
| 97 |
+
def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None:
|
| 98 |
+
super().__init__(*args, **kwargs)
|
| 99 |
+
self._terminalwriter = terminalwriter
|
| 100 |
+
self._original_fmt = self._style._fmt
|
| 101 |
+
self._level_to_fmt_mapping: dict[int, str] = {}
|
| 102 |
+
|
| 103 |
+
for level, color_opts in self.LOGLEVEL_COLOROPTS.items():
|
| 104 |
+
self.add_color_level(level, *color_opts)
|
| 105 |
+
|
| 106 |
+
def add_color_level(self, level: int, *color_opts: str) -> None:
|
| 107 |
+
"""Add or update color opts for a log level.
|
| 108 |
+
|
| 109 |
+
:param level:
|
| 110 |
+
Log level to apply a style to, e.g. ``logging.INFO``.
|
| 111 |
+
:param color_opts:
|
| 112 |
+
ANSI escape sequence color options. Capitalized colors indicates
|
| 113 |
+
background color, i.e. ``'green', 'Yellow', 'bold'`` will give bold
|
| 114 |
+
green text on yellow background.
|
| 115 |
+
|
| 116 |
+
.. warning::
|
| 117 |
+
This is an experimental API.
|
| 118 |
+
"""
|
| 119 |
+
assert self._fmt is not None
|
| 120 |
+
levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)
|
| 121 |
+
if not levelname_fmt_match:
|
| 122 |
+
return
|
| 123 |
+
levelname_fmt = levelname_fmt_match.group()
|
| 124 |
+
|
| 125 |
+
formatted_levelname = levelname_fmt % {"levelname": logging.getLevelName(level)}
|
| 126 |
+
|
| 127 |
+
# add ANSI escape sequences around the formatted levelname
|
| 128 |
+
color_kwargs = {name: True for name in color_opts}
|
| 129 |
+
colorized_formatted_levelname = self._terminalwriter.markup(
|
| 130 |
+
formatted_levelname, **color_kwargs
|
| 131 |
+
)
|
| 132 |
+
self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(
|
| 133 |
+
colorized_formatted_levelname, self._fmt
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def format(self, record: logging.LogRecord) -> str:
|
| 137 |
+
fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)
|
| 138 |
+
self._style._fmt = fmt
|
| 139 |
+
return super().format(record)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class PercentStyleMultiline(logging.PercentStyle):
|
| 143 |
+
"""A logging style with special support for multiline messages.
|
| 144 |
+
|
| 145 |
+
If the message of a record consists of multiple lines, this style
|
| 146 |
+
formats the message as if each line were logged separately.
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
def __init__(self, fmt: str, auto_indent: int | str | bool | None) -> None:
|
| 150 |
+
super().__init__(fmt)
|
| 151 |
+
self._auto_indent = self._get_auto_indent(auto_indent)
|
| 152 |
+
|
| 153 |
+
@staticmethod
|
| 154 |
+
def _get_auto_indent(auto_indent_option: int | str | bool | None) -> int:
|
| 155 |
+
"""Determine the current auto indentation setting.
|
| 156 |
+
|
| 157 |
+
Specify auto indent behavior (on/off/fixed) by passing in
|
| 158 |
+
extra={"auto_indent": [value]} to the call to logging.log() or
|
| 159 |
+
using a --log-auto-indent [value] command line or the
|
| 160 |
+
log_auto_indent [value] config option.
|
| 161 |
+
|
| 162 |
+
Default behavior is auto-indent off.
|
| 163 |
+
|
| 164 |
+
Using the string "True" or "on" or the boolean True as the value
|
| 165 |
+
turns auto indent on, using the string "False" or "off" or the
|
| 166 |
+
boolean False or the int 0 turns it off, and specifying a
|
| 167 |
+
positive integer fixes the indentation position to the value
|
| 168 |
+
specified.
|
| 169 |
+
|
| 170 |
+
Any other values for the option are invalid, and will silently be
|
| 171 |
+
converted to the default.
|
| 172 |
+
|
| 173 |
+
:param None|bool|int|str auto_indent_option:
|
| 174 |
+
User specified option for indentation from command line, config
|
| 175 |
+
or extra kwarg. Accepts int, bool or str. str option accepts the
|
| 176 |
+
same range of values as boolean config options, as well as
|
| 177 |
+
positive integers represented in str form.
|
| 178 |
+
|
| 179 |
+
:returns:
|
| 180 |
+
Indentation value, which can be
|
| 181 |
+
-1 (automatically determine indentation) or
|
| 182 |
+
0 (auto-indent turned off) or
|
| 183 |
+
>0 (explicitly set indentation position).
|
| 184 |
+
"""
|
| 185 |
+
if auto_indent_option is None:
|
| 186 |
+
return 0
|
| 187 |
+
elif isinstance(auto_indent_option, bool):
|
| 188 |
+
if auto_indent_option:
|
| 189 |
+
return -1
|
| 190 |
+
else:
|
| 191 |
+
return 0
|
| 192 |
+
elif isinstance(auto_indent_option, int):
|
| 193 |
+
return int(auto_indent_option)
|
| 194 |
+
elif isinstance(auto_indent_option, str):
|
| 195 |
+
try:
|
| 196 |
+
return int(auto_indent_option)
|
| 197 |
+
except ValueError:
|
| 198 |
+
pass
|
| 199 |
+
try:
|
| 200 |
+
if _strtobool(auto_indent_option):
|
| 201 |
+
return -1
|
| 202 |
+
except ValueError:
|
| 203 |
+
return 0
|
| 204 |
+
|
| 205 |
+
return 0
|
| 206 |
+
|
| 207 |
+
def format(self, record: logging.LogRecord) -> str:
|
| 208 |
+
if "\n" in record.message:
|
| 209 |
+
if hasattr(record, "auto_indent"):
|
| 210 |
+
# Passed in from the "extra={}" kwarg on the call to logging.log().
|
| 211 |
+
auto_indent = self._get_auto_indent(record.auto_indent)
|
| 212 |
+
else:
|
| 213 |
+
auto_indent = self._auto_indent
|
| 214 |
+
|
| 215 |
+
if auto_indent:
|
| 216 |
+
lines = record.message.splitlines()
|
| 217 |
+
formatted = self._fmt % {**record.__dict__, "message": lines[0]}
|
| 218 |
+
|
| 219 |
+
if auto_indent < 0:
|
| 220 |
+
indentation = _remove_ansi_escape_sequences(formatted).find(
|
| 221 |
+
lines[0]
|
| 222 |
+
)
|
| 223 |
+
else:
|
| 224 |
+
# Optimizes logging by allowing a fixed indentation.
|
| 225 |
+
indentation = auto_indent
|
| 226 |
+
lines[0] = formatted
|
| 227 |
+
return ("\n" + " " * indentation).join(lines)
|
| 228 |
+
return self._fmt % record.__dict__
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def get_option_ini(config: Config, *names: str):
|
| 232 |
+
for name in names:
|
| 233 |
+
ret = config.getoption(name) # 'default' arg won't work as expected
|
| 234 |
+
if ret is None:
|
| 235 |
+
ret = config.getini(name)
|
| 236 |
+
if ret:
|
| 237 |
+
return ret
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 241 |
+
"""Add options to control log capturing."""
|
| 242 |
+
group = parser.getgroup("logging")
|
| 243 |
+
|
| 244 |
+
def add_option_ini(option, dest, default=None, type=None, **kwargs):
|
| 245 |
+
parser.addini(
|
| 246 |
+
dest, default=default, type=type, help="Default value for " + option
|
| 247 |
+
)
|
| 248 |
+
group.addoption(option, dest=dest, **kwargs)
|
| 249 |
+
|
| 250 |
+
add_option_ini(
|
| 251 |
+
"--log-level",
|
| 252 |
+
dest="log_level",
|
| 253 |
+
default=None,
|
| 254 |
+
metavar="LEVEL",
|
| 255 |
+
help=(
|
| 256 |
+
"Level of messages to catch/display."
|
| 257 |
+
" Not set by default, so it depends on the root/parent log handler's"
|
| 258 |
+
' effective level, where it is "WARNING" by default.'
|
| 259 |
+
),
|
| 260 |
+
)
|
| 261 |
+
add_option_ini(
|
| 262 |
+
"--log-format",
|
| 263 |
+
dest="log_format",
|
| 264 |
+
default=DEFAULT_LOG_FORMAT,
|
| 265 |
+
help="Log format used by the logging module",
|
| 266 |
+
)
|
| 267 |
+
add_option_ini(
|
| 268 |
+
"--log-date-format",
|
| 269 |
+
dest="log_date_format",
|
| 270 |
+
default=DEFAULT_LOG_DATE_FORMAT,
|
| 271 |
+
help="Log date format used by the logging module",
|
| 272 |
+
)
|
| 273 |
+
parser.addini(
|
| 274 |
+
"log_cli",
|
| 275 |
+
default=False,
|
| 276 |
+
type="bool",
|
| 277 |
+
help='Enable log display during test run (also known as "live logging")',
|
| 278 |
+
)
|
| 279 |
+
add_option_ini(
|
| 280 |
+
"--log-cli-level", dest="log_cli_level", default=None, help="CLI logging level"
|
| 281 |
+
)
|
| 282 |
+
add_option_ini(
|
| 283 |
+
"--log-cli-format",
|
| 284 |
+
dest="log_cli_format",
|
| 285 |
+
default=None,
|
| 286 |
+
help="Log format used by the logging module",
|
| 287 |
+
)
|
| 288 |
+
add_option_ini(
|
| 289 |
+
"--log-cli-date-format",
|
| 290 |
+
dest="log_cli_date_format",
|
| 291 |
+
default=None,
|
| 292 |
+
help="Log date format used by the logging module",
|
| 293 |
+
)
|
| 294 |
+
add_option_ini(
|
| 295 |
+
"--log-file",
|
| 296 |
+
dest="log_file",
|
| 297 |
+
default=None,
|
| 298 |
+
help="Path to a file when logging will be written to",
|
| 299 |
+
)
|
| 300 |
+
add_option_ini(
|
| 301 |
+
"--log-file-mode",
|
| 302 |
+
dest="log_file_mode",
|
| 303 |
+
default="w",
|
| 304 |
+
choices=["w", "a"],
|
| 305 |
+
help="Log file open mode",
|
| 306 |
+
)
|
| 307 |
+
add_option_ini(
|
| 308 |
+
"--log-file-level",
|
| 309 |
+
dest="log_file_level",
|
| 310 |
+
default=None,
|
| 311 |
+
help="Log file logging level",
|
| 312 |
+
)
|
| 313 |
+
add_option_ini(
|
| 314 |
+
"--log-file-format",
|
| 315 |
+
dest="log_file_format",
|
| 316 |
+
default=None,
|
| 317 |
+
help="Log format used by the logging module",
|
| 318 |
+
)
|
| 319 |
+
add_option_ini(
|
| 320 |
+
"--log-file-date-format",
|
| 321 |
+
dest="log_file_date_format",
|
| 322 |
+
default=None,
|
| 323 |
+
help="Log date format used by the logging module",
|
| 324 |
+
)
|
| 325 |
+
add_option_ini(
|
| 326 |
+
"--log-auto-indent",
|
| 327 |
+
dest="log_auto_indent",
|
| 328 |
+
default=None,
|
| 329 |
+
help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.",
|
| 330 |
+
)
|
| 331 |
+
group.addoption(
|
| 332 |
+
"--log-disable",
|
| 333 |
+
action="append",
|
| 334 |
+
default=[],
|
| 335 |
+
dest="logger_disable",
|
| 336 |
+
help="Disable a logger by name. Can be passed multiple times.",
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
_HandlerType = TypeVar("_HandlerType", bound=logging.Handler)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
# Not using @contextmanager for performance reasons.
|
| 344 |
+
class catching_logs(Generic[_HandlerType]):
|
| 345 |
+
"""Context manager that prepares the whole logging machinery properly."""
|
| 346 |
+
|
| 347 |
+
__slots__ = ("handler", "level", "orig_level")
|
| 348 |
+
|
| 349 |
+
def __init__(self, handler: _HandlerType, level: int | None = None) -> None:
|
| 350 |
+
self.handler = handler
|
| 351 |
+
self.level = level
|
| 352 |
+
|
| 353 |
+
def __enter__(self) -> _HandlerType:
|
| 354 |
+
root_logger = logging.getLogger()
|
| 355 |
+
if self.level is not None:
|
| 356 |
+
self.handler.setLevel(self.level)
|
| 357 |
+
root_logger.addHandler(self.handler)
|
| 358 |
+
if self.level is not None:
|
| 359 |
+
self.orig_level = root_logger.level
|
| 360 |
+
root_logger.setLevel(min(self.orig_level, self.level))
|
| 361 |
+
return self.handler
|
| 362 |
+
|
| 363 |
+
def __exit__(
|
| 364 |
+
self,
|
| 365 |
+
exc_type: type[BaseException] | None,
|
| 366 |
+
exc_val: BaseException | None,
|
| 367 |
+
exc_tb: TracebackType | None,
|
| 368 |
+
) -> None:
|
| 369 |
+
root_logger = logging.getLogger()
|
| 370 |
+
if self.level is not None:
|
| 371 |
+
root_logger.setLevel(self.orig_level)
|
| 372 |
+
root_logger.removeHandler(self.handler)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class LogCaptureHandler(logging_StreamHandler):
|
| 376 |
+
"""A logging handler that stores log records and the log text."""
|
| 377 |
+
|
| 378 |
+
def __init__(self) -> None:
|
| 379 |
+
"""Create a new log handler."""
|
| 380 |
+
super().__init__(StringIO())
|
| 381 |
+
self.records: list[logging.LogRecord] = []
|
| 382 |
+
|
| 383 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 384 |
+
"""Keep the log records in a list in addition to the log text."""
|
| 385 |
+
self.records.append(record)
|
| 386 |
+
super().emit(record)
|
| 387 |
+
|
| 388 |
+
def reset(self) -> None:
|
| 389 |
+
self.records = []
|
| 390 |
+
self.stream = StringIO()
|
| 391 |
+
|
| 392 |
+
def clear(self) -> None:
|
| 393 |
+
self.records.clear()
|
| 394 |
+
self.stream = StringIO()
|
| 395 |
+
|
| 396 |
+
def handleError(self, record: logging.LogRecord) -> None:
|
| 397 |
+
if logging.raiseExceptions:
|
| 398 |
+
# Fail the test if the log message is bad (emit failed).
|
| 399 |
+
# The default behavior of logging is to print "Logging error"
|
| 400 |
+
# to stderr with the call stack and some extra details.
|
| 401 |
+
# pytest wants to make such mistakes visible during testing.
|
| 402 |
+
raise # noqa: PLE0704
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
@final
|
| 406 |
+
class LogCaptureFixture:
|
| 407 |
+
"""Provides access and control of log capturing."""
|
| 408 |
+
|
| 409 |
+
def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None:
|
| 410 |
+
check_ispytest(_ispytest)
|
| 411 |
+
self._item = item
|
| 412 |
+
self._initial_handler_level: int | None = None
|
| 413 |
+
# Dict of log name -> log level.
|
| 414 |
+
self._initial_logger_levels: dict[str | None, int] = {}
|
| 415 |
+
self._initial_disabled_logging_level: int | None = None
|
| 416 |
+
|
| 417 |
+
def _finalize(self) -> None:
|
| 418 |
+
"""Finalize the fixture.
|
| 419 |
+
|
| 420 |
+
This restores the log levels and the disabled logging levels changed by :meth:`set_level`.
|
| 421 |
+
"""
|
| 422 |
+
# Restore log levels.
|
| 423 |
+
if self._initial_handler_level is not None:
|
| 424 |
+
self.handler.setLevel(self._initial_handler_level)
|
| 425 |
+
for logger_name, level in self._initial_logger_levels.items():
|
| 426 |
+
logger = logging.getLogger(logger_name)
|
| 427 |
+
logger.setLevel(level)
|
| 428 |
+
# Disable logging at the original disabled logging level.
|
| 429 |
+
if self._initial_disabled_logging_level is not None:
|
| 430 |
+
logging.disable(self._initial_disabled_logging_level)
|
| 431 |
+
self._initial_disabled_logging_level = None
|
| 432 |
+
|
| 433 |
+
@property
|
| 434 |
+
def handler(self) -> LogCaptureHandler:
|
| 435 |
+
"""Get the logging handler used by the fixture."""
|
| 436 |
+
return self._item.stash[caplog_handler_key]
|
| 437 |
+
|
| 438 |
+
def get_records(
|
| 439 |
+
self, when: Literal["setup", "call", "teardown"]
|
| 440 |
+
) -> list[logging.LogRecord]:
|
| 441 |
+
"""Get the logging records for one of the possible test phases.
|
| 442 |
+
|
| 443 |
+
:param when:
|
| 444 |
+
Which test phase to obtain the records from.
|
| 445 |
+
Valid values are: "setup", "call" and "teardown".
|
| 446 |
+
|
| 447 |
+
:returns: The list of captured records at the given stage.
|
| 448 |
+
|
| 449 |
+
.. versionadded:: 3.4
|
| 450 |
+
"""
|
| 451 |
+
return self._item.stash[caplog_records_key].get(when, [])
|
| 452 |
+
|
| 453 |
+
@property
|
| 454 |
+
def text(self) -> str:
|
| 455 |
+
"""The formatted log text."""
|
| 456 |
+
return _remove_ansi_escape_sequences(self.handler.stream.getvalue())
|
| 457 |
+
|
| 458 |
+
@property
|
| 459 |
+
def records(self) -> list[logging.LogRecord]:
|
| 460 |
+
"""The list of log records."""
|
| 461 |
+
return self.handler.records
|
| 462 |
+
|
| 463 |
+
@property
|
| 464 |
+
def record_tuples(self) -> list[tuple[str, int, str]]:
|
| 465 |
+
"""A list of a stripped down version of log records intended
|
| 466 |
+
for use in assertion comparison.
|
| 467 |
+
|
| 468 |
+
The format of the tuple is:
|
| 469 |
+
|
| 470 |
+
(logger_name, log_level, message)
|
| 471 |
+
"""
|
| 472 |
+
return [(r.name, r.levelno, r.getMessage()) for r in self.records]
|
| 473 |
+
|
| 474 |
+
@property
|
| 475 |
+
def messages(self) -> list[str]:
|
| 476 |
+
"""A list of format-interpolated log messages.
|
| 477 |
+
|
| 478 |
+
Unlike 'records', which contains the format string and parameters for
|
| 479 |
+
interpolation, log messages in this list are all interpolated.
|
| 480 |
+
|
| 481 |
+
Unlike 'text', which contains the output from the handler, log
|
| 482 |
+
messages in this list are unadorned with levels, timestamps, etc,
|
| 483 |
+
making exact comparisons more reliable.
|
| 484 |
+
|
| 485 |
+
Note that traceback or stack info (from :func:`logging.exception` or
|
| 486 |
+
the `exc_info` or `stack_info` arguments to the logging functions) is
|
| 487 |
+
not included, as this is added by the formatter in the handler.
|
| 488 |
+
|
| 489 |
+
.. versionadded:: 3.7
|
| 490 |
+
"""
|
| 491 |
+
return [r.getMessage() for r in self.records]
|
| 492 |
+
|
| 493 |
+
def clear(self) -> None:
|
| 494 |
+
"""Reset the list of log records and the captured log text."""
|
| 495 |
+
self.handler.clear()
|
| 496 |
+
|
| 497 |
+
def _force_enable_logging(
|
| 498 |
+
self, level: int | str, logger_obj: logging.Logger
|
| 499 |
+
) -> int:
|
| 500 |
+
"""Enable the desired logging level if the global level was disabled via ``logging.disabled``.
|
| 501 |
+
|
| 502 |
+
Only enables logging levels greater than or equal to the requested ``level``.
|
| 503 |
+
|
| 504 |
+
Does nothing if the desired ``level`` wasn't disabled.
|
| 505 |
+
|
| 506 |
+
:param level:
|
| 507 |
+
The logger level caplog should capture.
|
| 508 |
+
All logging is enabled if a non-standard logging level string is supplied.
|
| 509 |
+
Valid level strings are in :data:`logging._nameToLevel`.
|
| 510 |
+
:param logger_obj: The logger object to check.
|
| 511 |
+
|
| 512 |
+
:return: The original disabled logging level.
|
| 513 |
+
"""
|
| 514 |
+
original_disable_level: int = logger_obj.manager.disable
|
| 515 |
+
|
| 516 |
+
if isinstance(level, str):
|
| 517 |
+
# Try to translate the level string to an int for `logging.disable()`
|
| 518 |
+
level = logging.getLevelName(level)
|
| 519 |
+
|
| 520 |
+
if not isinstance(level, int):
|
| 521 |
+
# The level provided was not valid, so just un-disable all logging.
|
| 522 |
+
logging.disable(logging.NOTSET)
|
| 523 |
+
elif not logger_obj.isEnabledFor(level):
|
| 524 |
+
# Each level is `10` away from other levels.
|
| 525 |
+
# https://docs.python.org/3/library/logging.html#logging-levels
|
| 526 |
+
disable_level = max(level - 10, logging.NOTSET)
|
| 527 |
+
logging.disable(disable_level)
|
| 528 |
+
|
| 529 |
+
return original_disable_level
|
| 530 |
+
|
| 531 |
+
def set_level(self, level: int | str, logger: str | None = None) -> None:
|
| 532 |
+
"""Set the threshold level of a logger for the duration of a test.
|
| 533 |
+
|
| 534 |
+
Logging messages which are less severe than this level will not be captured.
|
| 535 |
+
|
| 536 |
+
.. versionchanged:: 3.4
|
| 537 |
+
The levels of the loggers changed by this function will be
|
| 538 |
+
restored to their initial values at the end of the test.
|
| 539 |
+
|
| 540 |
+
Will enable the requested logging level if it was disabled via :func:`logging.disable`.
|
| 541 |
+
|
| 542 |
+
:param level: The level.
|
| 543 |
+
:param logger: The logger to update. If not given, the root logger.
|
| 544 |
+
"""
|
| 545 |
+
logger_obj = logging.getLogger(logger)
|
| 546 |
+
# Save the original log-level to restore it during teardown.
|
| 547 |
+
self._initial_logger_levels.setdefault(logger, logger_obj.level)
|
| 548 |
+
logger_obj.setLevel(level)
|
| 549 |
+
if self._initial_handler_level is None:
|
| 550 |
+
self._initial_handler_level = self.handler.level
|
| 551 |
+
self.handler.setLevel(level)
|
| 552 |
+
initial_disabled_logging_level = self._force_enable_logging(level, logger_obj)
|
| 553 |
+
if self._initial_disabled_logging_level is None:
|
| 554 |
+
self._initial_disabled_logging_level = initial_disabled_logging_level
|
| 555 |
+
|
| 556 |
+
@contextmanager
|
| 557 |
+
def at_level(self, level: int | str, logger: str | None = None) -> Generator[None]:
|
| 558 |
+
"""Context manager that sets the level for capturing of logs. After
|
| 559 |
+
the end of the 'with' statement the level is restored to its original
|
| 560 |
+
value.
|
| 561 |
+
|
| 562 |
+
Will enable the requested logging level if it was disabled via :func:`logging.disable`.
|
| 563 |
+
|
| 564 |
+
:param level: The level.
|
| 565 |
+
:param logger: The logger to update. If not given, the root logger.
|
| 566 |
+
"""
|
| 567 |
+
logger_obj = logging.getLogger(logger)
|
| 568 |
+
orig_level = logger_obj.level
|
| 569 |
+
logger_obj.setLevel(level)
|
| 570 |
+
handler_orig_level = self.handler.level
|
| 571 |
+
self.handler.setLevel(level)
|
| 572 |
+
original_disable_level = self._force_enable_logging(level, logger_obj)
|
| 573 |
+
try:
|
| 574 |
+
yield
|
| 575 |
+
finally:
|
| 576 |
+
logger_obj.setLevel(orig_level)
|
| 577 |
+
self.handler.setLevel(handler_orig_level)
|
| 578 |
+
logging.disable(original_disable_level)
|
| 579 |
+
|
| 580 |
+
@contextmanager
|
| 581 |
+
def filtering(self, filter_: logging.Filter) -> Generator[None]:
|
| 582 |
+
"""Context manager that temporarily adds the given filter to the caplog's
|
| 583 |
+
:meth:`handler` for the 'with' statement block, and removes that filter at the
|
| 584 |
+
end of the block.
|
| 585 |
+
|
| 586 |
+
:param filter_: A custom :class:`logging.Filter` object.
|
| 587 |
+
|
| 588 |
+
.. versionadded:: 7.5
|
| 589 |
+
"""
|
| 590 |
+
self.handler.addFilter(filter_)
|
| 591 |
+
try:
|
| 592 |
+
yield
|
| 593 |
+
finally:
|
| 594 |
+
self.handler.removeFilter(filter_)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
@fixture
|
| 598 |
+
def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture]:
|
| 599 |
+
"""Access and control log capturing.
|
| 600 |
+
|
| 601 |
+
Captured logs are available through the following properties/methods::
|
| 602 |
+
|
| 603 |
+
* caplog.messages -> list of format-interpolated log messages
|
| 604 |
+
* caplog.text -> string containing formatted log output
|
| 605 |
+
* caplog.records -> list of logging.LogRecord instances
|
| 606 |
+
* caplog.record_tuples -> list of (logger_name, level, message) tuples
|
| 607 |
+
* caplog.clear() -> clear captured records and formatted log output string
|
| 608 |
+
"""
|
| 609 |
+
result = LogCaptureFixture(request.node, _ispytest=True)
|
| 610 |
+
yield result
|
| 611 |
+
result._finalize()
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
def get_log_level_for_setting(config: Config, *setting_names: str) -> int | None:
|
| 615 |
+
for setting_name in setting_names:
|
| 616 |
+
log_level = config.getoption(setting_name)
|
| 617 |
+
if log_level is None:
|
| 618 |
+
log_level = config.getini(setting_name)
|
| 619 |
+
if log_level:
|
| 620 |
+
break
|
| 621 |
+
else:
|
| 622 |
+
return None
|
| 623 |
+
|
| 624 |
+
if isinstance(log_level, str):
|
| 625 |
+
log_level = log_level.upper()
|
| 626 |
+
try:
|
| 627 |
+
return int(getattr(logging, log_level, log_level))
|
| 628 |
+
except ValueError as e:
|
| 629 |
+
# Python logging does not recognise this as a logging level
|
| 630 |
+
raise UsageError(
|
| 631 |
+
f"'{log_level}' is not recognized as a logging level name for "
|
| 632 |
+
f"'{setting_name}'. Please consider passing the "
|
| 633 |
+
"logging level num instead."
|
| 634 |
+
) from e
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
# run after terminalreporter/capturemanager are configured
|
| 638 |
+
@hookimpl(trylast=True)
|
| 639 |
+
def pytest_configure(config: Config) -> None:
|
| 640 |
+
config.pluginmanager.register(LoggingPlugin(config), "logging-plugin")
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
class LoggingPlugin:
|
| 644 |
+
"""Attaches to the logging module and captures log messages for each test."""
|
| 645 |
+
|
| 646 |
+
def __init__(self, config: Config) -> None:
|
| 647 |
+
"""Create a new plugin to capture log messages.
|
| 648 |
+
|
| 649 |
+
The formatter can be safely shared across all handlers so
|
| 650 |
+
create a single one for the entire test session here.
|
| 651 |
+
"""
|
| 652 |
+
self._config = config
|
| 653 |
+
|
| 654 |
+
# Report logging.
|
| 655 |
+
self.formatter = self._create_formatter(
|
| 656 |
+
get_option_ini(config, "log_format"),
|
| 657 |
+
get_option_ini(config, "log_date_format"),
|
| 658 |
+
get_option_ini(config, "log_auto_indent"),
|
| 659 |
+
)
|
| 660 |
+
self.log_level = get_log_level_for_setting(config, "log_level")
|
| 661 |
+
self.caplog_handler = LogCaptureHandler()
|
| 662 |
+
self.caplog_handler.setFormatter(self.formatter)
|
| 663 |
+
self.report_handler = LogCaptureHandler()
|
| 664 |
+
self.report_handler.setFormatter(self.formatter)
|
| 665 |
+
|
| 666 |
+
# File logging.
|
| 667 |
+
self.log_file_level = get_log_level_for_setting(
|
| 668 |
+
config, "log_file_level", "log_level"
|
| 669 |
+
)
|
| 670 |
+
log_file = get_option_ini(config, "log_file") or os.devnull
|
| 671 |
+
if log_file != os.devnull:
|
| 672 |
+
directory = os.path.dirname(os.path.abspath(log_file))
|
| 673 |
+
if not os.path.isdir(directory):
|
| 674 |
+
os.makedirs(directory)
|
| 675 |
+
|
| 676 |
+
self.log_file_mode = get_option_ini(config, "log_file_mode") or "w"
|
| 677 |
+
self.log_file_handler = _FileHandler(
|
| 678 |
+
log_file, mode=self.log_file_mode, encoding="UTF-8"
|
| 679 |
+
)
|
| 680 |
+
log_file_format = get_option_ini(config, "log_file_format", "log_format")
|
| 681 |
+
log_file_date_format = get_option_ini(
|
| 682 |
+
config, "log_file_date_format", "log_date_format"
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
log_file_formatter = DatetimeFormatter(
|
| 686 |
+
log_file_format, datefmt=log_file_date_format
|
| 687 |
+
)
|
| 688 |
+
self.log_file_handler.setFormatter(log_file_formatter)
|
| 689 |
+
|
| 690 |
+
# CLI/live logging.
|
| 691 |
+
self.log_cli_level = get_log_level_for_setting(
|
| 692 |
+
config, "log_cli_level", "log_level"
|
| 693 |
+
)
|
| 694 |
+
if self._log_cli_enabled():
|
| 695 |
+
terminal_reporter = config.pluginmanager.get_plugin("terminalreporter")
|
| 696 |
+
# Guaranteed by `_log_cli_enabled()`.
|
| 697 |
+
assert terminal_reporter is not None
|
| 698 |
+
capture_manager = config.pluginmanager.get_plugin("capturemanager")
|
| 699 |
+
# if capturemanager plugin is disabled, live logging still works.
|
| 700 |
+
self.log_cli_handler: (
|
| 701 |
+
_LiveLoggingStreamHandler | _LiveLoggingNullHandler
|
| 702 |
+
) = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)
|
| 703 |
+
else:
|
| 704 |
+
self.log_cli_handler = _LiveLoggingNullHandler()
|
| 705 |
+
log_cli_formatter = self._create_formatter(
|
| 706 |
+
get_option_ini(config, "log_cli_format", "log_format"),
|
| 707 |
+
get_option_ini(config, "log_cli_date_format", "log_date_format"),
|
| 708 |
+
get_option_ini(config, "log_auto_indent"),
|
| 709 |
+
)
|
| 710 |
+
self.log_cli_handler.setFormatter(log_cli_formatter)
|
| 711 |
+
self._disable_loggers(loggers_to_disable=config.option.logger_disable)
|
| 712 |
+
|
| 713 |
+
def _disable_loggers(self, loggers_to_disable: list[str]) -> None:
|
| 714 |
+
if not loggers_to_disable:
|
| 715 |
+
return
|
| 716 |
+
|
| 717 |
+
for name in loggers_to_disable:
|
| 718 |
+
logger = logging.getLogger(name)
|
| 719 |
+
logger.disabled = True
|
| 720 |
+
|
| 721 |
+
def _create_formatter(self, log_format, log_date_format, auto_indent):
|
| 722 |
+
# Color option doesn't exist if terminal plugin is disabled.
|
| 723 |
+
color = getattr(self._config.option, "color", "no")
|
| 724 |
+
if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(
|
| 725 |
+
log_format
|
| 726 |
+
):
|
| 727 |
+
formatter: logging.Formatter = ColoredLevelFormatter(
|
| 728 |
+
create_terminal_writer(self._config), log_format, log_date_format
|
| 729 |
+
)
|
| 730 |
+
else:
|
| 731 |
+
formatter = DatetimeFormatter(log_format, log_date_format)
|
| 732 |
+
|
| 733 |
+
formatter._style = PercentStyleMultiline(
|
| 734 |
+
formatter._style._fmt, auto_indent=auto_indent
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
return formatter
|
| 738 |
+
|
| 739 |
+
def set_log_path(self, fname: str) -> None:
|
| 740 |
+
"""Set the filename parameter for Logging.FileHandler().
|
| 741 |
+
|
| 742 |
+
Creates parent directory if it does not exist.
|
| 743 |
+
|
| 744 |
+
.. warning::
|
| 745 |
+
This is an experimental API.
|
| 746 |
+
"""
|
| 747 |
+
fpath = Path(fname)
|
| 748 |
+
|
| 749 |
+
if not fpath.is_absolute():
|
| 750 |
+
fpath = self._config.rootpath / fpath
|
| 751 |
+
|
| 752 |
+
if not fpath.parent.exists():
|
| 753 |
+
fpath.parent.mkdir(exist_ok=True, parents=True)
|
| 754 |
+
|
| 755 |
+
# https://github.com/python/mypy/issues/11193
|
| 756 |
+
stream: io.TextIOWrapper = fpath.open(mode=self.log_file_mode, encoding="UTF-8") # type: ignore[assignment]
|
| 757 |
+
old_stream = self.log_file_handler.setStream(stream)
|
| 758 |
+
if old_stream:
|
| 759 |
+
old_stream.close()
|
| 760 |
+
|
| 761 |
+
def _log_cli_enabled(self) -> bool:
|
| 762 |
+
"""Return whether live logging is enabled."""
|
| 763 |
+
enabled = self._config.getoption(
|
| 764 |
+
"--log-cli-level"
|
| 765 |
+
) is not None or self._config.getini("log_cli")
|
| 766 |
+
if not enabled:
|
| 767 |
+
return False
|
| 768 |
+
|
| 769 |
+
terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter")
|
| 770 |
+
if terminal_reporter is None:
|
| 771 |
+
# terminal reporter is disabled e.g. by pytest-xdist.
|
| 772 |
+
return False
|
| 773 |
+
|
| 774 |
+
return True
|
| 775 |
+
|
| 776 |
+
@hookimpl(wrapper=True, tryfirst=True)
|
| 777 |
+
def pytest_sessionstart(self) -> Generator[None]:
|
| 778 |
+
self.log_cli_handler.set_when("sessionstart")
|
| 779 |
+
|
| 780 |
+
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
|
| 781 |
+
with catching_logs(self.log_file_handler, level=self.log_file_level):
|
| 782 |
+
return (yield)
|
| 783 |
+
|
| 784 |
+
@hookimpl(wrapper=True, tryfirst=True)
|
| 785 |
+
def pytest_collection(self) -> Generator[None]:
|
| 786 |
+
self.log_cli_handler.set_when("collection")
|
| 787 |
+
|
| 788 |
+
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
|
| 789 |
+
with catching_logs(self.log_file_handler, level=self.log_file_level):
|
| 790 |
+
return (yield)
|
| 791 |
+
|
| 792 |
+
@hookimpl(wrapper=True)
|
| 793 |
+
def pytest_runtestloop(self, session: Session) -> Generator[None, object, object]:
|
| 794 |
+
if session.config.option.collectonly:
|
| 795 |
+
return (yield)
|
| 796 |
+
|
| 797 |
+
if self._log_cli_enabled() and self._config.get_verbosity() < 1:
|
| 798 |
+
# The verbose flag is needed to avoid messy test progress output.
|
| 799 |
+
self._config.option.verbose = 1
|
| 800 |
+
|
| 801 |
+
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
|
| 802 |
+
with catching_logs(self.log_file_handler, level=self.log_file_level):
|
| 803 |
+
return (yield) # Run all the tests.
|
| 804 |
+
|
| 805 |
+
@hookimpl
|
| 806 |
+
def pytest_runtest_logstart(self) -> None:
|
| 807 |
+
self.log_cli_handler.reset()
|
| 808 |
+
self.log_cli_handler.set_when("start")
|
| 809 |
+
|
| 810 |
+
@hookimpl
|
| 811 |
+
def pytest_runtest_logreport(self) -> None:
|
| 812 |
+
self.log_cli_handler.set_when("logreport")
|
| 813 |
+
|
| 814 |
+
def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None]:
|
| 815 |
+
"""Implement the internals of the pytest_runtest_xxx() hooks."""
|
| 816 |
+
with catching_logs(
|
| 817 |
+
self.caplog_handler,
|
| 818 |
+
level=self.log_level,
|
| 819 |
+
) as caplog_handler, catching_logs(
|
| 820 |
+
self.report_handler,
|
| 821 |
+
level=self.log_level,
|
| 822 |
+
) as report_handler:
|
| 823 |
+
caplog_handler.reset()
|
| 824 |
+
report_handler.reset()
|
| 825 |
+
item.stash[caplog_records_key][when] = caplog_handler.records
|
| 826 |
+
item.stash[caplog_handler_key] = caplog_handler
|
| 827 |
+
|
| 828 |
+
try:
|
| 829 |
+
yield
|
| 830 |
+
finally:
|
| 831 |
+
log = report_handler.stream.getvalue().strip()
|
| 832 |
+
item.add_report_section(when, "log", log)
|
| 833 |
+
|
| 834 |
+
@hookimpl(wrapper=True)
|
| 835 |
+
def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None]:
|
| 836 |
+
self.log_cli_handler.set_when("setup")
|
| 837 |
+
|
| 838 |
+
empty: dict[str, list[logging.LogRecord]] = {}
|
| 839 |
+
item.stash[caplog_records_key] = empty
|
| 840 |
+
yield from self._runtest_for(item, "setup")
|
| 841 |
+
|
| 842 |
+
@hookimpl(wrapper=True)
|
| 843 |
+
def pytest_runtest_call(self, item: nodes.Item) -> Generator[None]:
|
| 844 |
+
self.log_cli_handler.set_when("call")
|
| 845 |
+
|
| 846 |
+
yield from self._runtest_for(item, "call")
|
| 847 |
+
|
| 848 |
+
@hookimpl(wrapper=True)
|
| 849 |
+
def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None]:
|
| 850 |
+
self.log_cli_handler.set_when("teardown")
|
| 851 |
+
|
| 852 |
+
try:
|
| 853 |
+
yield from self._runtest_for(item, "teardown")
|
| 854 |
+
finally:
|
| 855 |
+
del item.stash[caplog_records_key]
|
| 856 |
+
del item.stash[caplog_handler_key]
|
| 857 |
+
|
| 858 |
+
@hookimpl
|
| 859 |
+
def pytest_runtest_logfinish(self) -> None:
|
| 860 |
+
self.log_cli_handler.set_when("finish")
|
| 861 |
+
|
| 862 |
+
@hookimpl(wrapper=True, tryfirst=True)
|
| 863 |
+
def pytest_sessionfinish(self) -> Generator[None]:
|
| 864 |
+
self.log_cli_handler.set_when("sessionfinish")
|
| 865 |
+
|
| 866 |
+
with catching_logs(self.log_cli_handler, level=self.log_cli_level):
|
| 867 |
+
with catching_logs(self.log_file_handler, level=self.log_file_level):
|
| 868 |
+
return (yield)
|
| 869 |
+
|
| 870 |
+
@hookimpl
|
| 871 |
+
def pytest_unconfigure(self) -> None:
|
| 872 |
+
# Close the FileHandler explicitly.
|
| 873 |
+
# (logging.shutdown might have lost the weakref?!)
|
| 874 |
+
self.log_file_handler.close()
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
class _FileHandler(logging.FileHandler):
|
| 878 |
+
"""A logging FileHandler with pytest tweaks."""
|
| 879 |
+
|
| 880 |
+
def handleError(self, record: logging.LogRecord) -> None:
|
| 881 |
+
# Handled by LogCaptureHandler.
|
| 882 |
+
pass
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
class _LiveLoggingStreamHandler(logging_StreamHandler):
|
| 886 |
+
"""A logging StreamHandler used by the live logging feature: it will
|
| 887 |
+
write a newline before the first log message in each test.
|
| 888 |
+
|
| 889 |
+
During live logging we must also explicitly disable stdout/stderr
|
| 890 |
+
capturing otherwise it will get captured and won't appear in the
|
| 891 |
+
terminal.
|
| 892 |
+
"""
|
| 893 |
+
|
| 894 |
+
# Officially stream needs to be a IO[str], but TerminalReporter
|
| 895 |
+
# isn't. So force it.
|
| 896 |
+
stream: TerminalReporter = None # type: ignore
|
| 897 |
+
|
| 898 |
+
def __init__(
|
| 899 |
+
self,
|
| 900 |
+
terminal_reporter: TerminalReporter,
|
| 901 |
+
capture_manager: CaptureManager | None,
|
| 902 |
+
) -> None:
|
| 903 |
+
super().__init__(stream=terminal_reporter) # type: ignore[arg-type]
|
| 904 |
+
self.capture_manager = capture_manager
|
| 905 |
+
self.reset()
|
| 906 |
+
self.set_when(None)
|
| 907 |
+
self._test_outcome_written = False
|
| 908 |
+
|
| 909 |
+
def reset(self) -> None:
|
| 910 |
+
"""Reset the handler; should be called before the start of each test."""
|
| 911 |
+
self._first_record_emitted = False
|
| 912 |
+
|
| 913 |
+
def set_when(self, when: str | None) -> None:
|
| 914 |
+
"""Prepare for the given test phase (setup/call/teardown)."""
|
| 915 |
+
self._when = when
|
| 916 |
+
self._section_name_shown = False
|
| 917 |
+
if when == "start":
|
| 918 |
+
self._test_outcome_written = False
|
| 919 |
+
|
| 920 |
+
def emit(self, record: logging.LogRecord) -> None:
|
| 921 |
+
ctx_manager = (
|
| 922 |
+
self.capture_manager.global_and_fixture_disabled()
|
| 923 |
+
if self.capture_manager
|
| 924 |
+
else nullcontext()
|
| 925 |
+
)
|
| 926 |
+
with ctx_manager:
|
| 927 |
+
if not self._first_record_emitted:
|
| 928 |
+
self.stream.write("\n")
|
| 929 |
+
self._first_record_emitted = True
|
| 930 |
+
elif self._when in ("teardown", "finish"):
|
| 931 |
+
if not self._test_outcome_written:
|
| 932 |
+
self._test_outcome_written = True
|
| 933 |
+
self.stream.write("\n")
|
| 934 |
+
if not self._section_name_shown and self._when:
|
| 935 |
+
self.stream.section("live log " + self._when, sep="-", bold=True)
|
| 936 |
+
self._section_name_shown = True
|
| 937 |
+
super().emit(record)
|
| 938 |
+
|
| 939 |
+
def handleError(self, record: logging.LogRecord) -> None:
|
| 940 |
+
# Handled by LogCaptureHandler.
|
| 941 |
+
pass
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
class _LiveLoggingNullHandler(logging.NullHandler):
|
| 945 |
+
"""A logging handler used when live logging is disabled."""
|
| 946 |
+
|
| 947 |
+
def reset(self) -> None:
|
| 948 |
+
pass
|
| 949 |
+
|
| 950 |
+
def set_when(self, when: str) -> None:
|
| 951 |
+
pass
|
| 952 |
+
|
| 953 |
+
def handleError(self, record: logging.LogRecord) -> None:
|
| 954 |
+
# Handled by LogCaptureHandler.
|
| 955 |
+
pass
|
shared/package-files/41/41f87914952ff5959dfcfe73c64bd860892faac3e9b60683b8a91e5ff17cbf20/blob
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#if defined(DETECT_FEATURES) && defined(__INTEL_COMPILER)
|
| 2 |
+
/*
|
| 3 |
+
* Unlike GCC and CLANG, Intel Compiler exposes all supported intrinsics,
|
| 4 |
+
* whether or not the build options for those features are specified.
|
| 5 |
+
* Therefore, we must test #definitions of CPU features when option native/host
|
| 6 |
+
* is enabled via `--cpu-baseline` or through env var `CFLAGS` otherwise
|
| 7 |
+
* the test will be broken and leads to enable all possible features.
|
| 8 |
+
*/
|
| 9 |
+
#ifndef __AVX512CD__
|
| 10 |
+
#error "HOST/ARCH doesn't support AVX512CD"
|
| 11 |
+
#endif
|
| 12 |
+
#endif
|
| 13 |
+
|
| 14 |
+
#include <immintrin.h>
|
| 15 |
+
|
| 16 |
+
int main(int argc, char **argv)
|
| 17 |
+
{
|
| 18 |
+
__m512i a = _mm512_lzcnt_epi32(_mm512_loadu_si512((const __m512i*)argv[argc-1]));
|
| 19 |
+
return _mm_cvtsi128_si32(_mm512_castsi512_si128(a));
|
| 20 |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ATen/core/ivalue_to.h>
|
| 4 |
+
#include <ATen/core/jit_type_base.h>
|
| 5 |
+
#include <c10/macros/Macros.h>
|
| 6 |
+
#include <c10/macros/Export.h>
|
| 7 |
+
#include <c10/util/TypeTraits.h>
|
| 8 |
+
#include <c10/util/TypeList.h>
|
| 9 |
+
#include <c10/util/intrusive_ptr.h>
|
| 10 |
+
#include <c10/util/ArrayRef.h>
|
| 11 |
+
#include <c10/util/Optional.h>
|
| 12 |
+
#include <vector>
|
| 13 |
+
|
| 14 |
+
namespace at {
|
| 15 |
+
class Tensor;
|
| 16 |
+
}
|
| 17 |
+
namespace c10 {
|
| 18 |
+
struct IValue;
|
| 19 |
+
template<class T> class List;
|
| 20 |
+
struct Type;
|
| 21 |
+
|
| 22 |
+
namespace detail {
|
| 23 |
+
|
| 24 |
+
struct ListImpl final : public c10::intrusive_ptr_target {
|
| 25 |
+
using list_type = std::vector<IValue>;
|
| 26 |
+
|
| 27 |
+
explicit TORCH_API ListImpl(list_type list_, TypePtr elementType_);
|
| 28 |
+
|
| 29 |
+
list_type list;
|
| 30 |
+
|
| 31 |
+
TypePtr elementType;
|
| 32 |
+
|
| 33 |
+
intrusive_ptr<ListImpl> copy() const {
|
| 34 |
+
return make_intrusive<ListImpl>(list, elementType);
|
| 35 |
+
}
|
| 36 |
+
friend TORCH_API bool operator==(const ListImpl& lhs, const ListImpl& rhs);
|
| 37 |
+
};
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
namespace impl {
|
| 41 |
+
|
| 42 |
+
template<class T, class Iterator> class ListIterator;
|
| 43 |
+
|
| 44 |
+
template<class T, class Iterator> class ListElementReference;
|
| 45 |
+
|
| 46 |
+
template<class T, class Iterator>
|
| 47 |
+
void swap(ListElementReference<T, Iterator>&& lhs, ListElementReference<T, Iterator>&& rhs);
|
| 48 |
+
|
| 49 |
+
template<class T, class Iterator>
|
| 50 |
+
bool operator==(const ListElementReference<T, Iterator>& lhs, const T& rhs);
|
| 51 |
+
|
| 52 |
+
template<class T, class Iterator>
|
| 53 |
+
bool operator==(const T& lhs, const ListElementReference<T, Iterator>& rhs);
|
| 54 |
+
|
| 55 |
+
template<class T>
|
| 56 |
+
struct ListElementConstReferenceTraits {
|
| 57 |
+
// In the general case, we use IValue::to().
|
| 58 |
+
using const_reference = typename c10::detail::ivalue_to_const_ref_overload_return<T>::type;
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
// There is no to() overload for c10::optional<std::string>.
|
| 62 |
+
template<>
|
| 63 |
+
struct ListElementConstReferenceTraits<c10::optional<std::string>> {
|
| 64 |
+
using const_reference = c10::optional<std::reference_wrapper<const std::string>>;
|
| 65 |
+
};
|
| 66 |
+
|
| 67 |
+
template<class T, class Iterator>
|
| 68 |
+
class ListElementReference final {
|
| 69 |
+
public:
|
| 70 |
+
operator std::conditional_t<
|
| 71 |
+
std::is_reference<typename c10::detail::
|
| 72 |
+
ivalue_to_const_ref_overload_return<T>::type>::value,
|
| 73 |
+
const T&,
|
| 74 |
+
T>() const;
|
| 75 |
+
|
| 76 |
+
ListElementReference& operator=(T&& new_value) &&;
|
| 77 |
+
|
| 78 |
+
ListElementReference& operator=(const T& new_value) &&;
|
| 79 |
+
|
| 80 |
+
// assigning another ref to this assigns the underlying value
|
| 81 |
+
ListElementReference& operator=(ListElementReference&& rhs) && noexcept;
|
| 82 |
+
|
| 83 |
+
const IValue& get() const& {
|
| 84 |
+
return *iterator_;
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
friend void swap<T, Iterator>(ListElementReference&& lhs, ListElementReference&& rhs);
|
| 88 |
+
|
| 89 |
+
ListElementReference(const ListElementReference&) = delete;
|
| 90 |
+
ListElementReference& operator=(const ListElementReference&) = delete;
|
| 91 |
+
|
| 92 |
+
private:
|
| 93 |
+
ListElementReference(Iterator iter)
|
| 94 |
+
: iterator_(iter) {}
|
| 95 |
+
|
| 96 |
+
// allow moving, but only our friends (i.e. the List class) can move us
|
| 97 |
+
ListElementReference(ListElementReference&&) noexcept = default;
|
| 98 |
+
ListElementReference& operator=(ListElementReference&& rhs) & noexcept {
|
| 99 |
+
iterator_ = std::move(rhs.iterator_);
|
| 100 |
+
return *this;
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
friend class List<T>;
|
| 104 |
+
friend class ListIterator<T, Iterator>;
|
| 105 |
+
|
| 106 |
+
Iterator iterator_;
|
| 107 |
+
};
|
| 108 |
+
|
| 109 |
+
// this wraps vector::iterator to make sure user code can't rely
|
| 110 |
+
// on it being the type of the underlying vector.
|
| 111 |
+
template <class T, class Iterator>
|
| 112 |
+
class ListIterator final {
|
| 113 |
+
public:
|
| 114 |
+
// C++17 friendly std::iterator implementation
|
| 115 |
+
using iterator_category = std::random_access_iterator_tag;
|
| 116 |
+
using value_type = T;
|
| 117 |
+
using difference_type = std::ptrdiff_t;
|
| 118 |
+
using pointer = T*;
|
| 119 |
+
using reference = ListElementReference<T, Iterator>;
|
| 120 |
+
|
| 121 |
+
explicit ListIterator() = default;
|
| 122 |
+
~ListIterator() = default;
|
| 123 |
+
|
| 124 |
+
ListIterator(const ListIterator&) = default;
|
| 125 |
+
ListIterator(ListIterator&&) noexcept = default;
|
| 126 |
+
ListIterator& operator=(const ListIterator&) = default;
|
| 127 |
+
ListIterator& operator=(ListIterator&&) noexcept = default;
|
| 128 |
+
|
| 129 |
+
ListIterator& operator++() {
|
| 130 |
+
++iterator_;
|
| 131 |
+
return *this;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
ListIterator operator++(int) {
|
| 135 |
+
ListIterator copy(*this);
|
| 136 |
+
++*this;
|
| 137 |
+
return copy;
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
ListIterator& operator--() {
|
| 141 |
+
--iterator_;
|
| 142 |
+
return *this;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
ListIterator operator--(int) {
|
| 146 |
+
ListIterator copy(*this);
|
| 147 |
+
--*this;
|
| 148 |
+
return copy;
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
ListIterator& operator+=(typename List<T>::size_type offset) {
|
| 152 |
+
iterator_ += offset;
|
| 153 |
+
return *this;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
ListIterator& operator-=(typename List<T>::size_type offset) {
|
| 157 |
+
iterator_ -= offset;
|
| 158 |
+
return *this;
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
ListIterator operator+(typename List<T>::size_type offset) const {
|
| 162 |
+
return ListIterator{iterator_ + offset};
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
ListIterator operator-(typename List<T>::size_type offset) const {
|
| 166 |
+
return ListIterator{iterator_ - offset};
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
friend difference_type operator-(const ListIterator& lhs, const ListIterator& rhs) {
|
| 170 |
+
return lhs.iterator_ - rhs.iterator_;
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
ListElementReference<T, Iterator> operator*() const {
|
| 174 |
+
return {iterator_};
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
ListElementReference<T, Iterator> operator[](typename List<T>::size_type offset) const {
|
| 178 |
+
return {iterator_ + offset};
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
private:
|
| 182 |
+
explicit ListIterator(Iterator iterator): iterator_(std::move(iterator)) {}
|
| 183 |
+
|
| 184 |
+
Iterator iterator_;
|
| 185 |
+
|
| 186 |
+
friend bool operator==(const ListIterator& lhs, const ListIterator& rhs) {
|
| 187 |
+
return lhs.iterator_ == rhs.iterator_;
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
friend bool operator!=(const ListIterator& lhs, const ListIterator& rhs) {
|
| 191 |
+
return !(lhs == rhs);
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
friend bool operator<(const ListIterator& lhs, const ListIterator& rhs) {
|
| 195 |
+
return lhs.iterator_ < rhs.iterator_;
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
friend bool operator<=(const ListIterator& lhs, const ListIterator& rhs) {
|
| 199 |
+
return lhs.iterator_ <= rhs.iterator_;
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
friend bool operator>(const ListIterator& lhs, const ListIterator& rhs) {
|
| 203 |
+
return lhs.iterator_ > rhs.iterator_;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
friend bool operator>=(const ListIterator& lhs, const ListIterator& rhs) {
|
| 207 |
+
return lhs.iterator_ >= rhs.iterator_;
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
friend class ListIterator<T, typename c10::detail::ListImpl::list_type::iterator>;
|
| 211 |
+
friend class List<T>;
|
| 212 |
+
};
|
| 213 |
+
|
| 214 |
+
template<class T> List<T> toTypedList(List<IValue> list);
|
| 215 |
+
template<class T> List<IValue> toList(List<T>&& list);
|
| 216 |
+
template<class T> List<IValue> toList(const List<T>& list);
|
| 217 |
+
const IValue* ptr_to_first_element(const List<IValue>& list);
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
/**
|
| 221 |
+
* An object of this class stores a list of values of type T.
|
| 222 |
+
*
|
| 223 |
+
* This is a pointer type. After a copy, both Lists
|
| 224 |
+
* will share the same storage:
|
| 225 |
+
*
|
| 226 |
+
* > List<int> a;
|
| 227 |
+
* > List<int> b = a;
|
| 228 |
+
* > b.push_back("three");
|
| 229 |
+
* > ASSERT("three" == a.get(0));
|
| 230 |
+
*
|
| 231 |
+
* We use this class in the PyTorch kernel API instead of
|
| 232 |
+
* std::vector<T>, because that allows us to do optimizations
|
| 233 |
+
* and switch out the underlying list implementation without
|
| 234 |
+
* breaking backwards compatibility for the kernel API.
|
| 235 |
+
*/
|
| 236 |
+
template<class T>
|
| 237 |
+
class List final {
|
| 238 |
+
private:
|
| 239 |
+
// This is an intrusive_ptr because List is a pointer type.
|
| 240 |
+
// Invariant: This will never be a nullptr, there will always be a valid
|
| 241 |
+
// ListImpl.
|
| 242 |
+
c10::intrusive_ptr<c10::detail::ListImpl> impl_;
|
| 243 |
+
|
| 244 |
+
using internal_reference_type = impl::ListElementReference<T, typename c10::detail::ListImpl::list_type::iterator>;
|
| 245 |
+
using internal_const_reference_type = typename impl::ListElementConstReferenceTraits<T>::const_reference;
|
| 246 |
+
|
| 247 |
+
public:
|
| 248 |
+
using value_type = T;
|
| 249 |
+
using size_type = typename c10::detail::ListImpl::list_type::size_type;
|
| 250 |
+
using iterator = impl::ListIterator<T, typename c10::detail::ListImpl::list_type::iterator>;
|
| 251 |
+
using const_iterator = impl::ListIterator<T, typename c10::detail::ListImpl::list_type::iterator>;
|
| 252 |
+
using reverse_iterator = impl::ListIterator<T, typename c10::detail::ListImpl::list_type::reverse_iterator>;
|
| 253 |
+
|
| 254 |
+
/**
|
| 255 |
+
* Constructs an empty list.
|
| 256 |
+
*/
|
| 257 |
+
explicit List();
|
| 258 |
+
|
| 259 |
+
/**
|
| 260 |
+
* Constructs a list with some initial values.
|
| 261 |
+
* Example:
|
| 262 |
+
* List<int> a({2, 3, 4});
|
| 263 |
+
*/
|
| 264 |
+
List(std::initializer_list<T> initial_values);
|
| 265 |
+
explicit List(ArrayRef<T> initial_values);
|
| 266 |
+
|
| 267 |
+
/**
|
| 268 |
+
* Create a generic list with runtime type information.
|
| 269 |
+
* This only works for c10::impl::GenericList and is not part of the public API
|
| 270 |
+
* but only supposed to be used internally by PyTorch.
|
| 271 |
+
*/
|
| 272 |
+
explicit List(TypePtr elementType);
|
| 273 |
+
|
| 274 |
+
List(const List&) = default;
|
| 275 |
+
List& operator=(const List&) = default;
|
| 276 |
+
|
| 277 |
+
/**
|
| 278 |
+
* Create a new List pointing to a deep copy of the same data.
|
| 279 |
+
* The List returned is a new list with separate storage.
|
| 280 |
+
* Changes in it are not reflected in the original list or vice versa.
|
| 281 |
+
*/
|
| 282 |
+
List copy() const;
|
| 283 |
+
|
| 284 |
+
/**
|
| 285 |
+
* Returns the element at specified location pos, with bounds checking.
|
| 286 |
+
* If pos is not within the range of the container, an exception of type std::out_of_range is thrown.
|
| 287 |
+
*/
|
| 288 |
+
internal_const_reference_type get(size_type pos) const;
|
| 289 |
+
|
| 290 |
+
/**
|
| 291 |
+
* Moves out the element at the specified location pos and returns it, with bounds checking.
|
| 292 |
+
* If pos is not within the range of the container, an exception of type std::out_of_range is thrown.
|
| 293 |
+
* The list contains an invalid element at position pos afterwards. Any operations
|
| 294 |
+
* on it before re-setting it are invalid.
|
| 295 |
+
*/
|
| 296 |
+
value_type extract(size_type pos) const;
|
| 297 |
+
|
| 298 |
+
/**
|
| 299 |
+
* Returns a reference to the element at specified location pos, with bounds checking.
|
| 300 |
+
* If pos is not within the range of the container, an exception of type std::out_of_range is thrown.
|
| 301 |
+
*
|
| 302 |
+
* You cannot store the reference, but you can read it and assign new values to it:
|
| 303 |
+
*
|
| 304 |
+
* List<int64_t> list = ...;
|
| 305 |
+
* list[2] = 5;
|
| 306 |
+
* int64_t v = list[1];
|
| 307 |
+
*/
|
| 308 |
+
internal_const_reference_type operator[](size_type pos) const;
|
| 309 |
+
|
| 310 |
+
internal_reference_type operator[](size_type pos);
|
| 311 |
+
|
| 312 |
+
/**
|
| 313 |
+
* Assigns a new value to the element at location pos.
|
| 314 |
+
*/
|
| 315 |
+
void set(size_type pos, const value_type& value) const;
|
| 316 |
+
|
| 317 |
+
/**
|
| 318 |
+
* Assigns a new value to the element at location pos.
|
| 319 |
+
*/
|
| 320 |
+
void set(size_type pos, value_type&& value) const;
|
| 321 |
+
|
| 322 |
+
/**
|
| 323 |
+
* Returns an iterator to the first element of the container.
|
| 324 |
+
* If the container is empty, the returned iterator will be equal to end().
|
| 325 |
+
*/
|
| 326 |
+
iterator begin() const;
|
| 327 |
+
|
| 328 |
+
/**
|
| 329 |
+
* Returns an iterator to the element following the last element of the container.
|
| 330 |
+
* This element acts as a placeholder; attempting to access it results in undefined behavior.
|
| 331 |
+
*/
|
| 332 |
+
iterator end() const;
|
| 333 |
+
|
| 334 |
+
/**
|
| 335 |
+
* Checks if the container has no elements.
|
| 336 |
+
*/
|
| 337 |
+
bool empty() const;
|
| 338 |
+
|
| 339 |
+
/**
|
| 340 |
+
* Returns the number of elements in the container
|
| 341 |
+
*/
|
| 342 |
+
size_type size() const;
|
| 343 |
+
|
| 344 |
+
/**
|
| 345 |
+
* Increase the capacity of the vector to a value that's greater or equal to new_cap.
|
| 346 |
+
*/
|
| 347 |
+
void reserve(size_type new_cap) const;
|
| 348 |
+
|
| 349 |
+
/**
|
| 350 |
+
* Erases all elements from the container. After this call, size() returns zero.
|
| 351 |
+
* Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterators are also invalidated.
|
| 352 |
+
*/
|
| 353 |
+
void clear() const;
|
| 354 |
+
|
| 355 |
+
/**
|
| 356 |
+
* Inserts value before pos.
|
| 357 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 358 |
+
*/
|
| 359 |
+
iterator insert(iterator pos, const T& value) const;
|
| 360 |
+
|
| 361 |
+
/**
|
| 362 |
+
* Inserts value before pos.
|
| 363 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 364 |
+
*/
|
| 365 |
+
iterator insert(iterator pos, T&& value) const;
|
| 366 |
+
|
| 367 |
+
/**
|
| 368 |
+
* Inserts a new element into the container directly before pos.
|
| 369 |
+
* The new element is constructed with the given arguments.
|
| 370 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 371 |
+
*/
|
| 372 |
+
template<class... Args>
|
| 373 |
+
iterator emplace(iterator pos, Args&&... value) const;
|
| 374 |
+
|
| 375 |
+
/**
|
| 376 |
+
* Appends the given element value to the end of the container.
|
| 377 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 378 |
+
*/
|
| 379 |
+
void push_back(const T& value) const;
|
| 380 |
+
|
| 381 |
+
/**
|
| 382 |
+
* Appends the given element value to the end of the container.
|
| 383 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 384 |
+
*/
|
| 385 |
+
void push_back(T&& value) const;
|
| 386 |
+
|
| 387 |
+
/**
|
| 388 |
+
* Appends the given list to the end of the container. Uses at most one memory allocation.
|
| 389 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 390 |
+
*/
|
| 391 |
+
void append(List<T> lst) const;
|
| 392 |
+
|
| 393 |
+
/**
|
| 394 |
+
* Appends the given element value to the end of the container.
|
| 395 |
+
* The new element is constructed with the given arguments.
|
| 396 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 397 |
+
*/
|
| 398 |
+
template<class... Args>
|
| 399 |
+
void emplace_back(Args&&... args) const;
|
| 400 |
+
|
| 401 |
+
/**
|
| 402 |
+
* Removes the element at pos.
|
| 403 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 404 |
+
*/
|
| 405 |
+
iterator erase(iterator pos) const;
|
| 406 |
+
|
| 407 |
+
/**
|
| 408 |
+
* Removes the elements in the range [first, last).
|
| 409 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 410 |
+
*/
|
| 411 |
+
iterator erase(iterator first, iterator last) const;
|
| 412 |
+
|
| 413 |
+
/**
|
| 414 |
+
* Removes the last element of the container.
|
| 415 |
+
* Calling pop_back on an empty container is undefined.
|
| 416 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 417 |
+
*/
|
| 418 |
+
void pop_back() const;
|
| 419 |
+
|
| 420 |
+
/**
|
| 421 |
+
* Resizes the container to contain count elements.
|
| 422 |
+
* If the current size is less than count, additional default-inserted elements are appended.
|
| 423 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 424 |
+
*/
|
| 425 |
+
void resize(size_type count) const;
|
| 426 |
+
|
| 427 |
+
/**
|
| 428 |
+
* Resizes the container to contain count elements.
|
| 429 |
+
* If the current size is less than count, additional copies of value are appended.
|
| 430 |
+
* May invalidate any references, pointers, or iterators referring to contained elements. Any past-the-end iterators may also be invalidated.
|
| 431 |
+
*/
|
| 432 |
+
void resize(size_type count, const T& value) const;
|
| 433 |
+
|
| 434 |
+
/**
|
| 435 |
+
* Value equality comparison. This function implements Python-like semantics for
|
| 436 |
+
* equality: two lists with the same identity (e.g. same pointer) trivially
|
| 437 |
+
* compare equal, otherwise each element is compared for equality.
|
| 438 |
+
*/
|
| 439 |
+
template <class T_>
|
| 440 |
+
friend bool operator==(const List<T_>& lhs, const List<T_>& rhs);
|
| 441 |
+
|
| 442 |
+
template <class T_>
|
| 443 |
+
friend bool operator!=(const List<T_>& lhs, const List<T_>& rhs);
|
| 444 |
+
|
| 445 |
+
/**
|
| 446 |
+
* Identity comparison. Returns true if and only if `rhs` represents the same
|
| 447 |
+
* List object as `this`.
|
| 448 |
+
*/
|
| 449 |
+
bool is(const List<T>& rhs) const;
|
| 450 |
+
|
| 451 |
+
std::vector<T> vec() const;
|
| 452 |
+
|
| 453 |
+
/**
|
| 454 |
+
* Returns the number of Lists currently pointing to this same list.
|
| 455 |
+
* If this is the only instance pointing to this list, returns 1.
|
| 456 |
+
*/
|
| 457 |
+
// TODO Test use_count
|
| 458 |
+
size_t use_count() const;
|
| 459 |
+
|
| 460 |
+
TypePtr elementType() const;
|
| 461 |
+
|
| 462 |
+
// See [unsafe set type] for why this exists.
|
| 463 |
+
void unsafeSetElementType(TypePtr t);
|
| 464 |
+
|
| 465 |
+
private:
|
| 466 |
+
explicit List(c10::intrusive_ptr<c10::detail::ListImpl>&& elements);
|
| 467 |
+
explicit List(const c10::intrusive_ptr<c10::detail::ListImpl>& elements);
|
| 468 |
+
friend struct IValue;
|
| 469 |
+
template<class T_> friend List<T_> impl::toTypedList(List<IValue>);
|
| 470 |
+
template<class T_> friend List<IValue> impl::toList(List<T_>&&);
|
| 471 |
+
template<class T_> friend List<IValue> impl::toList(const List<T_>&);
|
| 472 |
+
friend const IValue* impl::ptr_to_first_element(const List<IValue>& list);
|
| 473 |
+
};
|
| 474 |
+
|
| 475 |
+
namespace impl {
|
| 476 |
+
// GenericList is how IValue stores lists. It is, however, not part of the
|
| 477 |
+
// public API. Kernels should use Lists with concrete types instead
|
| 478 |
+
// (maybe except for some internal prim ops).
|
| 479 |
+
using GenericList = List<IValue>;
|
| 480 |
+
|
| 481 |
+
const IValue* ptr_to_first_element(const GenericList& list);
|
| 482 |
+
|
| 483 |
+
}
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
namespace torch {
|
| 487 |
+
template<class T> using List = c10::List<T>;
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
#include <ATen/core/List_inl.h> // IWYU pragma: keep
|
shared/package-files/41/41fb194beb1554d13af237fbe930c0a82455b9f315f08c1a049622f4533beb55/blob
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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misc import sstruct
|
| 2 |
+
from fontTools.misc.fixedTools import (
|
| 3 |
+
fixedToFloat as fi2fl,
|
| 4 |
+
floatToFixed as fl2fi,
|
| 5 |
+
floatToFixedToStr as fl2str,
|
| 6 |
+
strToFixedToFloat as str2fl,
|
| 7 |
+
)
|
| 8 |
+
from fontTools.misc.textTools import Tag, bytesjoin, safeEval
|
| 9 |
+
from fontTools.ttLib import TTLibError
|
| 10 |
+
from . import DefaultTable
|
| 11 |
+
import struct
|
| 12 |
+
|
| 13 |
+
# Apple's documentation of 'fvar':
|
| 14 |
+
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html
|
| 15 |
+
|
| 16 |
+
FVAR_HEADER_FORMAT = """
|
| 17 |
+
> # big endian
|
| 18 |
+
version: L
|
| 19 |
+
offsetToData: H
|
| 20 |
+
countSizePairs: H
|
| 21 |
+
axisCount: H
|
| 22 |
+
axisSize: H
|
| 23 |
+
instanceCount: H
|
| 24 |
+
instanceSize: H
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
FVAR_AXIS_FORMAT = """
|
| 28 |
+
> # big endian
|
| 29 |
+
axisTag: 4s
|
| 30 |
+
minValue: 16.16F
|
| 31 |
+
defaultValue: 16.16F
|
| 32 |
+
maxValue: 16.16F
|
| 33 |
+
flags: H
|
| 34 |
+
axisNameID: H
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
FVAR_INSTANCE_FORMAT = """
|
| 38 |
+
> # big endian
|
| 39 |
+
subfamilyNameID: H
|
| 40 |
+
flags: H
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class table__f_v_a_r(DefaultTable.DefaultTable):
|
| 45 |
+
"""FonT Variations table
|
| 46 |
+
|
| 47 |
+
The ``fvar`` table contains records of the variation axes and of the
|
| 48 |
+
named instances in a variable font.
|
| 49 |
+
|
| 50 |
+
See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(self, tag=None):
|
| 54 |
+
DefaultTable.DefaultTable.__init__(self, tag)
|
| 55 |
+
self.axes = []
|
| 56 |
+
self.instances = []
|
| 57 |
+
|
| 58 |
+
def compile(self, ttFont):
|
| 59 |
+
instanceSize = sstruct.calcsize(FVAR_INSTANCE_FORMAT) + (len(self.axes) * 4)
|
| 60 |
+
includePostScriptNames = any(
|
| 61 |
+
instance.postscriptNameID != 0xFFFF for instance in self.instances
|
| 62 |
+
)
|
| 63 |
+
if includePostScriptNames:
|
| 64 |
+
instanceSize += 2
|
| 65 |
+
header = {
|
| 66 |
+
"version": 0x00010000,
|
| 67 |
+
"offsetToData": sstruct.calcsize(FVAR_HEADER_FORMAT),
|
| 68 |
+
"countSizePairs": 2,
|
| 69 |
+
"axisCount": len(self.axes),
|
| 70 |
+
"axisSize": sstruct.calcsize(FVAR_AXIS_FORMAT),
|
| 71 |
+
"instanceCount": len(self.instances),
|
| 72 |
+
"instanceSize": instanceSize,
|
| 73 |
+
}
|
| 74 |
+
result = [sstruct.pack(FVAR_HEADER_FORMAT, header)]
|
| 75 |
+
result.extend([axis.compile() for axis in self.axes])
|
| 76 |
+
axisTags = [axis.axisTag for axis in self.axes]
|
| 77 |
+
for instance in self.instances:
|
| 78 |
+
result.append(instance.compile(axisTags, includePostScriptNames))
|
| 79 |
+
return bytesjoin(result)
|
| 80 |
+
|
| 81 |
+
def decompile(self, data, ttFont):
|
| 82 |
+
header = {}
|
| 83 |
+
headerSize = sstruct.calcsize(FVAR_HEADER_FORMAT)
|
| 84 |
+
header = sstruct.unpack(FVAR_HEADER_FORMAT, data[0:headerSize])
|
| 85 |
+
if header["version"] != 0x00010000:
|
| 86 |
+
raise TTLibError("unsupported 'fvar' version %04x" % header["version"])
|
| 87 |
+
pos = header["offsetToData"]
|
| 88 |
+
axisSize = header["axisSize"]
|
| 89 |
+
for _ in range(header["axisCount"]):
|
| 90 |
+
axis = Axis()
|
| 91 |
+
axis.decompile(data[pos : pos + axisSize])
|
| 92 |
+
self.axes.append(axis)
|
| 93 |
+
pos += axisSize
|
| 94 |
+
instanceSize = header["instanceSize"]
|
| 95 |
+
axisTags = [axis.axisTag for axis in self.axes]
|
| 96 |
+
for _ in range(header["instanceCount"]):
|
| 97 |
+
instance = NamedInstance()
|
| 98 |
+
instance.decompile(data[pos : pos + instanceSize], axisTags)
|
| 99 |
+
self.instances.append(instance)
|
| 100 |
+
pos += instanceSize
|
| 101 |
+
|
| 102 |
+
def toXML(self, writer, ttFont):
|
| 103 |
+
for axis in self.axes:
|
| 104 |
+
axis.toXML(writer, ttFont)
|
| 105 |
+
for instance in self.instances:
|
| 106 |
+
instance.toXML(writer, ttFont)
|
| 107 |
+
|
| 108 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 109 |
+
if name == "Axis":
|
| 110 |
+
axis = Axis()
|
| 111 |
+
axis.fromXML(name, attrs, content, ttFont)
|
| 112 |
+
self.axes.append(axis)
|
| 113 |
+
elif name == "NamedInstance":
|
| 114 |
+
instance = NamedInstance()
|
| 115 |
+
instance.fromXML(name, attrs, content, ttFont)
|
| 116 |
+
self.instances.append(instance)
|
| 117 |
+
|
| 118 |
+
def getAxes(self):
|
| 119 |
+
return {a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in self.axes}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class Axis(object):
|
| 123 |
+
def __init__(self):
|
| 124 |
+
self.axisTag = None
|
| 125 |
+
self.axisNameID = 0
|
| 126 |
+
self.flags = 0
|
| 127 |
+
self.minValue = -1.0
|
| 128 |
+
self.defaultValue = 0.0
|
| 129 |
+
self.maxValue = 1.0
|
| 130 |
+
|
| 131 |
+
def compile(self):
|
| 132 |
+
return sstruct.pack(FVAR_AXIS_FORMAT, self)
|
| 133 |
+
|
| 134 |
+
def decompile(self, data):
|
| 135 |
+
sstruct.unpack2(FVAR_AXIS_FORMAT, data, self)
|
| 136 |
+
|
| 137 |
+
def toXML(self, writer, ttFont):
|
| 138 |
+
name = (
|
| 139 |
+
ttFont["name"].getDebugName(self.axisNameID) if "name" in ttFont else None
|
| 140 |
+
)
|
| 141 |
+
if name is not None:
|
| 142 |
+
writer.newline()
|
| 143 |
+
writer.comment(name)
|
| 144 |
+
writer.newline()
|
| 145 |
+
writer.begintag("Axis")
|
| 146 |
+
writer.newline()
|
| 147 |
+
for tag, value in [
|
| 148 |
+
("AxisTag", self.axisTag),
|
| 149 |
+
("Flags", "0x%X" % self.flags),
|
| 150 |
+
("MinValue", fl2str(self.minValue, 16)),
|
| 151 |
+
("DefaultValue", fl2str(self.defaultValue, 16)),
|
| 152 |
+
("MaxValue", fl2str(self.maxValue, 16)),
|
| 153 |
+
("AxisNameID", str(self.axisNameID)),
|
| 154 |
+
]:
|
| 155 |
+
writer.begintag(tag)
|
| 156 |
+
writer.write(value)
|
| 157 |
+
writer.endtag(tag)
|
| 158 |
+
writer.newline()
|
| 159 |
+
writer.endtag("Axis")
|
| 160 |
+
writer.newline()
|
| 161 |
+
|
| 162 |
+
def fromXML(self, name, _attrs, content, ttFont):
|
| 163 |
+
assert name == "Axis"
|
| 164 |
+
for tag, _, value in filter(lambda t: type(t) is tuple, content):
|
| 165 |
+
value = "".join(value)
|
| 166 |
+
if tag == "AxisTag":
|
| 167 |
+
self.axisTag = Tag(value)
|
| 168 |
+
elif tag in {"Flags", "MinValue", "DefaultValue", "MaxValue", "AxisNameID"}:
|
| 169 |
+
setattr(
|
| 170 |
+
self,
|
| 171 |
+
tag[0].lower() + tag[1:],
|
| 172 |
+
str2fl(value, 16) if tag.endswith("Value") else safeEval(value),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class NamedInstance(object):
|
| 177 |
+
def __init__(self):
|
| 178 |
+
self.subfamilyNameID = 0
|
| 179 |
+
self.postscriptNameID = 0xFFFF
|
| 180 |
+
self.flags = 0
|
| 181 |
+
self.coordinates = {}
|
| 182 |
+
|
| 183 |
+
def compile(self, axisTags, includePostScriptName):
|
| 184 |
+
result = [sstruct.pack(FVAR_INSTANCE_FORMAT, self)]
|
| 185 |
+
for axis in axisTags:
|
| 186 |
+
fixedCoord = fl2fi(self.coordinates[axis], 16)
|
| 187 |
+
result.append(struct.pack(">l", fixedCoord))
|
| 188 |
+
if includePostScriptName:
|
| 189 |
+
result.append(struct.pack(">H", self.postscriptNameID))
|
| 190 |
+
return bytesjoin(result)
|
| 191 |
+
|
| 192 |
+
def decompile(self, data, axisTags):
|
| 193 |
+
sstruct.unpack2(FVAR_INSTANCE_FORMAT, data, self)
|
| 194 |
+
pos = sstruct.calcsize(FVAR_INSTANCE_FORMAT)
|
| 195 |
+
for axis in axisTags:
|
| 196 |
+
value = struct.unpack(">l", data[pos : pos + 4])[0]
|
| 197 |
+
self.coordinates[axis] = fi2fl(value, 16)
|
| 198 |
+
pos += 4
|
| 199 |
+
if pos + 2 <= len(data):
|
| 200 |
+
self.postscriptNameID = struct.unpack(">H", data[pos : pos + 2])[0]
|
| 201 |
+
else:
|
| 202 |
+
self.postscriptNameID = 0xFFFF
|
| 203 |
+
|
| 204 |
+
def toXML(self, writer, ttFont):
|
| 205 |
+
name = (
|
| 206 |
+
ttFont["name"].getDebugName(self.subfamilyNameID)
|
| 207 |
+
if "name" in ttFont
|
| 208 |
+
else None
|
| 209 |
+
)
|
| 210 |
+
if name is not None:
|
| 211 |
+
writer.newline()
|
| 212 |
+
writer.comment(name)
|
| 213 |
+
writer.newline()
|
| 214 |
+
psname = (
|
| 215 |
+
ttFont["name"].getDebugName(self.postscriptNameID)
|
| 216 |
+
if "name" in ttFont
|
| 217 |
+
else None
|
| 218 |
+
)
|
| 219 |
+
if psname is not None:
|
| 220 |
+
writer.comment("PostScript: " + psname)
|
| 221 |
+
writer.newline()
|
| 222 |
+
if self.postscriptNameID == 0xFFFF:
|
| 223 |
+
writer.begintag(
|
| 224 |
+
"NamedInstance",
|
| 225 |
+
flags=("0x%X" % self.flags),
|
| 226 |
+
subfamilyNameID=self.subfamilyNameID,
|
| 227 |
+
)
|
| 228 |
+
else:
|
| 229 |
+
writer.begintag(
|
| 230 |
+
"NamedInstance",
|
| 231 |
+
flags=("0x%X" % self.flags),
|
| 232 |
+
subfamilyNameID=self.subfamilyNameID,
|
| 233 |
+
postscriptNameID=self.postscriptNameID,
|
| 234 |
+
)
|
| 235 |
+
writer.newline()
|
| 236 |
+
for axis in ttFont["fvar"].axes:
|
| 237 |
+
writer.simpletag(
|
| 238 |
+
"coord",
|
| 239 |
+
axis=axis.axisTag,
|
| 240 |
+
value=fl2str(self.coordinates[axis.axisTag], 16),
|
| 241 |
+
)
|
| 242 |
+
writer.newline()
|
| 243 |
+
writer.endtag("NamedInstance")
|
| 244 |
+
writer.newline()
|
| 245 |
+
|
| 246 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 247 |
+
assert name == "NamedInstance"
|
| 248 |
+
self.subfamilyNameID = safeEval(attrs["subfamilyNameID"])
|
| 249 |
+
self.flags = safeEval(attrs.get("flags", "0"))
|
| 250 |
+
if "postscriptNameID" in attrs:
|
| 251 |
+
self.postscriptNameID = safeEval(attrs["postscriptNameID"])
|
| 252 |
+
else:
|
| 253 |
+
self.postscriptNameID = 0xFFFF
|
| 254 |
+
|
| 255 |
+
for tag, elementAttrs, _ in filter(lambda t: type(t) is tuple, content):
|
| 256 |
+
if tag == "coord":
|
| 257 |
+
value = str2fl(elementAttrs["value"], 16)
|
| 258 |
+
self.coordinates[elementAttrs["axis"]] = value
|
shared/package-files/41/41fcaa0ad1ff3099c890a5b99bef7c1990f6323b4f60bb4f4c38bbf697081a1b/blob
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import OrderedDict
|
| 2 |
+
from typing import Dict, Optional
|
| 3 |
+
|
| 4 |
+
from torch import nn, Tensor
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
|
| 7 |
+
from ...utils import _log_api_usage_once
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class _SimpleSegmentationModel(nn.Module):
|
| 11 |
+
__constants__ = ["aux_classifier"]
|
| 12 |
+
|
| 13 |
+
def __init__(self, backbone: nn.Module, classifier: nn.Module, aux_classifier: Optional[nn.Module] = None) -> None:
|
| 14 |
+
super().__init__()
|
| 15 |
+
_log_api_usage_once(self)
|
| 16 |
+
self.backbone = backbone
|
| 17 |
+
self.classifier = classifier
|
| 18 |
+
self.aux_classifier = aux_classifier
|
| 19 |
+
|
| 20 |
+
def forward(self, x: Tensor) -> Dict[str, Tensor]:
|
| 21 |
+
input_shape = x.shape[-2:]
|
| 22 |
+
# contract: features is a dict of tensors
|
| 23 |
+
features = self.backbone(x)
|
| 24 |
+
|
| 25 |
+
result = OrderedDict()
|
| 26 |
+
x = features["out"]
|
| 27 |
+
x = self.classifier(x)
|
| 28 |
+
x = F.interpolate(x, size=input_shape, mode="bilinear", align_corners=False)
|
| 29 |
+
result["out"] = x
|
| 30 |
+
|
| 31 |
+
if self.aux_classifier is not None:
|
| 32 |
+
x = features["aux"]
|
| 33 |
+
x = self.aux_classifier(x)
|
| 34 |
+
x = F.interpolate(x, size=input_shape, mode="bilinear", align_corners=False)
|
| 35 |
+
result["aux"] = x
|
| 36 |
+
|
| 37 |
+
return result
|